2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004, 2005 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.Diagnostics;
21 using System.Globalization;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references;
47 // Modules to be linked
49 static ArrayList modules;
52 static ArrayList link_paths;
54 // Whether we want to only run the tokenizer
55 static bool tokenize = false;
57 static string first_source;
59 static bool want_debugging_support = false;
61 static bool parse_only = false;
62 static bool timestamps = false;
63 static bool pause = false;
64 static bool show_counters = false;
67 // Whether to load the initial config file (what CSC.RSP has by default)
69 static bool load_default_config = true;
72 // A list of resource files
74 static ArrayList resources;
75 static ArrayList embedded_resources;
76 static string win32ResourceFile;
77 static string win32IconFile;
80 // An array of the defines from the command line
82 static ArrayList defines;
87 static string output_file = null;
90 // Last time we took the time
92 static DateTime last_time, first_time;
97 static Encoding defaultEncoding;
98 static Encoding encoding;
100 static public void Reset ()
102 want_debugging_support = false;
106 show_counters = false;
107 load_default_config = true;
108 resources = embedded_resources = null;
109 win32ResourceFile = win32IconFile = null;
112 encoding = defaultEncoding = null;
116 public static void ShowTime (string msg)
121 DateTime now = DateTime.Now;
122 TimeSpan span = now - last_time;
126 "[{0:00}:{1:000}] {2}",
127 (int) span.TotalSeconds, span.Milliseconds, msg);
130 public static void ShowTotalTime (string msg)
135 DateTime now = DateTime.Now;
136 TimeSpan span = now - first_time;
140 "[{0:00}:{1:000}] {2}",
141 (int) span.TotalSeconds, span.Milliseconds, msg);
144 static void tokenize_file (SourceFile file)
149 input = File.OpenRead (file.Name);
151 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
156 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
157 Tokenizer lexer = new Tokenizer (reader, file, defines);
158 int token, tokens = 0, errors = 0;
160 while ((token = lexer.token ()) != Token.EOF){
162 if (token == Token.ERROR)
165 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
171 // MonoTODO("Change error code for aborted compilation to something reasonable")]
172 static void parse (SourceFile file)
178 input = File.OpenRead (file.Name);
180 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
184 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
187 if (reader.Read () == 77 && reader.Read () == 90) {
188 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
194 parser = new CSharpParser (reader, file, defines);
195 parser.ErrorOutput = Report.Stderr;
199 } catch (Exception ex) {
200 Report.Error(666, "Compilation aborted: " + ex);
209 static void OtherFlags ()
212 "Other flags in the compiler\n" +
213 " --fatal Makes errors fatal\n" +
214 " --parse Only parses the source file\n" +
215 " --stacktrace Shows stack trace at error location\n" +
216 " --timestamp Displays time stamps of various compiler events\n" +
217 " --expect-error X Expect that error X will be encountered\n" +
218 " -2 Enables experimental C# features\n" +
219 " -v Verbose parsing (for debugging the parser)\n" +
220 " --mcs-debug X Sets MCS debugging level to X\n");
226 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
227 "mcs [options] source-files\n" +
228 " --about About the Mono C# compiler\n" +
229 " -addmodule:MODULE Adds the module to the generated assembly\n" +
230 " -checked[+|-] Set default context to checked\n" +
231 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
232 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
233 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
234 " -debug[+|-], -g Generate debugging information\n" +
235 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
236 " -doc:FILE XML Documentation file to generate\n" +
237 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
238 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
239 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
240 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
241 " -main:class Specified the class that contains the entry point\n" +
242 " -noconfig[+|-] Disables implicit references to assemblies\n" +
243 " -nostdlib[+|-] Does not load core libraries\n" +
244 " -nowarn:W1[,W2] Disables one or more warnings\n" +
245 " -optimize[+|-] Enables code optimalizations\n" +
246 " -out:FNAME Specifies output file\n" +
247 " -pkg:P1[,Pn] References packages P1..Pn\n" +
248 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
249 " -reference:ASS References the specified assembly (-r:ASS)\n" +
250 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
251 " library, module), (short: /t:)\n" +
252 " -unsafe[+|-] Allows unsafe code\n" +
253 " -warnaserror[+|-] Treat warnings as errors\n" +
254 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
255 " -help2 Show other help flags\n" +
258 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
259 " -resource:FILE[,ID] Embed FILE as a resource\n" +
260 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
261 " -win32icon:FILE Use this icon for the output\n" +
262 " @file Read response file for more options\n\n" +
263 "Options can be of the form -option or /option");
266 static void TargetUsage ()
268 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
274 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
275 "The compiler source code is released under the terms of the GNU GPL\n\n" +
277 "For more information on Mono, visit the project Web site\n" +
278 " http://www.go-mono.com\n\n" +
280 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
281 Environment.Exit (0);
284 public static int counter1, counter2;
286 public static int Main (string[] args)
288 RootContext.Version = LanguageVersion.Default;
289 bool ok = MainDriver (args);
291 if (ok && Report.Errors == 0) {
292 if (Report.Warnings > 0) {
293 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
296 Console.WriteLine ("Counter1: " + counter1);
297 Console.WriteLine ("Counter2: " + counter2);
303 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
304 Report.Errors, Report.Warnings);
309 static public void LoadAssembly (string assembly, bool soft)
312 string total_log = "";
315 char[] path_chars = { '/', '\\' };
317 if (assembly.IndexOfAny (path_chars) != -1) {
318 a = Assembly.LoadFrom (assembly);
320 string ass = assembly;
321 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
322 ass = assembly.Substring (0, assembly.Length - 4);
323 a = Assembly.Load (ass);
325 TypeManager.AddAssembly (a);
327 } catch (FileNotFoundException){
328 foreach (string dir in link_paths){
329 string full_path = Path.Combine (dir, assembly);
330 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
334 a = Assembly.LoadFrom (full_path);
335 TypeManager.AddAssembly (a);
337 } catch (FileNotFoundException ff) {
338 total_log += ff.FusionLog;
343 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
344 Console.WriteLine ("Log: \n" + total_log);
346 } catch (BadImageFormatException f) {
347 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
348 } catch (FileLoadException f){
349 Report.Error(6, "Cannot load assembly " + f.FusionLog);
350 } catch (ArgumentNullException){
351 Report.Error(6, "Cannot load assembly (null argument)");
355 static public void LoadModule (MethodInfo adder_method, string module)
358 string total_log = "";
362 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
364 catch (TargetInvocationException ex) {
365 throw ex.InnerException;
367 TypeManager.AddModule (m);
370 catch (FileNotFoundException){
371 foreach (string dir in link_paths){
372 string full_path = Path.Combine (dir, module);
373 if (!module.EndsWith (".netmodule"))
374 full_path += ".netmodule";
378 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
380 catch (TargetInvocationException ex) {
381 throw ex.InnerException;
383 TypeManager.AddModule (m);
385 } catch (FileNotFoundException ff) {
386 total_log += ff.FusionLog;
390 Report.Error (6, "Cannot find module `" + module + "'" );
391 Console.WriteLine ("Log: \n" + total_log);
392 } catch (BadImageFormatException f) {
393 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
394 } catch (FileLoadException f){
395 Report.Error(6, "Cannot load module " + f.FusionLog);
396 } catch (ArgumentNullException){
397 Report.Error(6, "Cannot load module (null argument)");
402 /// Loads all assemblies referenced on the command line
404 static public void LoadReferences ()
406 foreach (string r in references)
407 LoadAssembly (r, false);
409 foreach (string r in soft_references)
410 LoadAssembly (r, true);
415 static void SetupDefaultDefines ()
417 defines = new ArrayList ();
418 defines.Add ("__MonoCS__");
421 static string [] LoadArgs (string file)
424 ArrayList args = new ArrayList ();
427 f = new StreamReader (file);
432 StringBuilder sb = new StringBuilder ();
434 while ((line = f.ReadLine ()) != null){
437 for (int i = 0; i < t; i++){
440 if (c == '"' || c == '\''){
443 for (i++; i < t; i++){
450 } else if (c == ' '){
452 args.Add (sb.ToString ());
459 args.Add (sb.ToString ());
464 string [] ret_value = new string [args.Count];
465 args.CopyTo (ret_value, 0);
471 // Returns the directory where the system assemblies are installed
473 static string GetSystemDir ()
475 return Path.GetDirectoryName (typeof (object).Assembly.Location);
479 // Given a path specification, splits the path from the file/pattern
481 static void SplitPathAndPattern (string spec, out string path, out string pattern)
483 int p = spec.LastIndexOf ('/');
486 // Windows does not like /file.cs, switch that to:
491 pattern = spec.Substring (1);
493 path = spec.Substring (0, p);
494 pattern = spec.Substring (p + 1);
499 p = spec.LastIndexOf ('\\');
501 path = spec.Substring (0, p);
502 pattern = spec.Substring (p + 1);
510 static void ProcessFile (string f)
512 if (first_source == null)
515 Location.AddFile (f);
518 static void ProcessFiles ()
520 Location.Initialize ();
522 foreach (SourceFile file in Location.SourceFiles) {
524 tokenize_file (file);
531 static void CompileFiles (string spec, bool recurse)
533 string path, pattern;
535 SplitPathAndPattern (spec, out path, out pattern);
536 if (pattern.IndexOf ('*') == -1){
541 string [] files = null;
543 files = Directory.GetFiles (path, pattern);
544 } catch (System.IO.DirectoryNotFoundException) {
545 Report.Error (2001, "Source file `" + spec + "' could not be found");
547 } catch (System.IO.IOException){
548 Report.Error (2001, "Source file `" + spec + "' could not be found");
551 foreach (string f in files) {
558 string [] dirs = null;
561 dirs = Directory.GetDirectories (path);
565 foreach (string d in dirs) {
567 // Don't include path in this string, as each
568 // directory entry already does
569 CompileFiles (d + "/" + pattern, true);
573 static void DefineDefaultConfig ()
576 // For now the "default config" is harcoded into the compiler
577 // we can move this outside later
579 string [] default_config = {
584 // Is it worth pre-loading all this stuff?
587 "System.Configuration.Install",
590 "System.DirectoryServices",
591 "System.Drawing.Design",
593 "System.EnterpriseServices",
596 "System.Runtime.Remoting",
597 "System.Runtime.Serialization.Formatters.Soap",
599 "System.ServiceProcess",
601 "System.Web.RegularExpressions",
602 "System.Web.Services",
603 "System.Windows.Forms"
608 foreach (string def in default_config)
609 soft_references.Insert (p++, def);
612 public static string OutputFile
618 return Path.GetFileName (output_file);
622 static void SetWarningLevel (string s)
627 level = Int32.Parse (s);
630 if (level < 0 || level > 4){
631 Report.Error (1900, "Warning level must be in the range 0-4");
634 RootContext.WarningLevel = level;
637 static void SetupV2 ()
639 RootContext.Version = LanguageVersion.Default;
640 defines.Add ("__V2__");
643 static void Version ()
645 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
646 Console.WriteLine ("Mono C# compiler version {0}", version);
647 Environment.Exit (0);
651 // Currently handles the Unix-like command line options, but will be
652 // deprecated in favor of the CSCParseOption, which will also handle the
653 // options that start with a dash in the future.
655 static bool UnixParseOption (string arg, ref string [] args, ref int i)
659 CSharpParser.yacc_verbose_flag++;
670 case "--main": case "-m":
671 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
672 if ((i + 1) >= args.Length){
674 Environment.Exit (1);
676 RootContext.MainClass = args [++i];
680 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
681 RootContext.Unsafe = true;
684 case "/?": case "/h": case "/help":
687 Environment.Exit (0);
691 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
692 if ((i + 1) >= args.Length){
694 Environment.Exit (1);
696 defines.Add (args [++i]);
699 case "--show-counters":
700 show_counters = true;
703 case "--expect-error": {
708 args [++i], NumberStyles.AllowLeadingSign);
709 Report.ExpectedError = code;
711 Report.Error (-14, "Invalid number specified");
722 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
723 if ((i + 1) >= args.Length){
725 Environment.Exit (1);
727 OutputFile = args [++i];
731 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
732 RootContext.Checked = true;
736 Report.Stacktrace = true;
739 case "--linkresource":
741 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
742 if ((i + 1) >= args.Length){
744 Report.Error (5, "Missing argument to --linkres");
745 Environment.Exit (1);
747 if (resources == null)
748 resources = new ArrayList ();
750 resources.Add (args [++i]);
755 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
756 if ((i + 1) >= args.Length){
758 Report.Error (5, "Missing argument to --resource");
759 Environment.Exit (1);
761 if (embedded_resources == null)
762 embedded_resources = new ArrayList ();
764 embedded_resources.Add (args [++i]);
768 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
769 if ((i + 1) >= args.Length){
770 Environment.Exit (1);
774 string type = args [++i];
777 RootContext.Target = Target.Library;
778 RootContext.TargetExt = ".dll";
782 RootContext.Target = Target.Exe;
786 RootContext.Target = Target.WinExe;
790 RootContext.Target = Target.Module;
791 RootContext.TargetExt = ".dll";
800 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
801 if ((i + 1) >= args.Length){
803 Environment.Exit (1);
806 references.Add (args [++i]);
810 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
811 if ((i + 1) >= args.Length){
813 Environment.Exit (1);
815 link_paths.Add (args [++i]);
819 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
820 RootContext.StdLib = false;
828 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
829 Report.WarningsAreErrors = true;
833 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
834 if ((i + 1) >= args.Length){
836 Environment.Exit (1);
841 warn = Int32.Parse (args [++i]);
844 Environment.Exit (1);
846 Report.SetIgnoreWarning (warn);
850 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
851 if ((i + 1) >= args.Length){
854 "--wlevel requires a value from 0 to 4");
855 Environment.Exit (1);
858 SetWarningLevel (args [++i]);
862 if ((i + 1) >= args.Length){
863 Report.Error (5, "--mcs-debug requires an argument");
864 Environment.Exit (1);
868 Report.DebugFlags = Int32.Parse (args [++i]);
870 Report.Error (5, "Invalid argument to --mcs-debug");
871 Environment.Exit (1);
880 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
881 if ((i + 1) >= args.Length){
882 Report.Error (5, "--recurse requires an argument");
883 Environment.Exit (1);
885 CompileFiles (args [++i], true);
890 last_time = first_time = DateTime.Now;
897 case "--debug": case "-g":
898 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
899 want_debugging_support = true;
903 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
904 load_default_config = false;
912 // This parses the -arg and /arg options to the compiler, even if the strings
913 // in the following text use "/arg" on the strings.
915 static bool CSCParseOption (string option, ref string [] args, ref int i)
917 int idx = option.IndexOf (':');
924 arg = option.Substring (0, idx);
926 value = option.Substring (idx + 1);
937 RootContext.Target = Target.Exe;
941 RootContext.Target = Target.WinExe;
945 RootContext.Target = Target.Library;
946 RootContext.TargetExt = ".dll";
950 RootContext.Target = Target.Module;
951 RootContext.TargetExt = ".netmodule";
963 Environment.Exit (1);
970 RootContext.Optimize = true;
974 RootContext.Optimize = false;
978 case "/incremental+":
979 case "/incremental-":
989 Environment.Exit (1);
992 defs = value.Split (new Char [] {';', ','});
993 foreach (string d in defs){
1001 // We should collect data, runtime, etc and store in the file specified
1003 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1007 case "/linkresource":
1009 Report.Error (5, arg + " requires an argument");
1010 Environment.Exit (1);
1012 if (resources == null)
1013 resources = new ArrayList ();
1015 resources.Add (value);
1023 Environment.Exit (1);
1025 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1027 ProcessStartInfo pi = new ProcessStartInfo ();
1028 pi.FileName = "pkg-config";
1029 pi.RedirectStandardOutput = true;
1030 pi.UseShellExecute = false;
1031 pi.Arguments = "--libs " + packages;
1034 p = Process.Start (pi);
1035 } catch (Exception e) {
1036 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1037 Environment.Exit (1);
1040 if (p.StandardOutput == null){
1041 Report.Warning (-27, "Specified package did not return any information");
1044 string pkgout = p.StandardOutput.ReadToEnd ();
1046 if (p.ExitCode != 0) {
1047 Report.Error (-27, "Error running pkg-config. Check the above output.");
1048 Environment.Exit (1);
1051 if (pkgout != null){
1052 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1053 Split (new Char [] { ' ', '\t'});
1054 args = AddArgs (args, xargs);
1064 Report.Error (5, "-resource requires an argument");
1065 Environment.Exit (1);
1067 if (embedded_resources == null)
1068 embedded_resources = new ArrayList ();
1070 if (embedded_resources.Contains (value)) {
1071 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1073 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1074 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1077 embedded_resources.Add (value);
1083 Report.Error (5, "-recurse requires an argument");
1084 Environment.Exit (1);
1086 CompileFiles (value, true);
1090 case "/reference": {
1092 Report.Error (5, "-reference requires an argument");
1093 Environment.Exit (1);
1096 string [] refs = value.Split (new char [] { ';', ',' });
1097 foreach (string r in refs){
1102 case "/addmodule": {
1104 Report.Error (5, arg + " requires an argument");
1105 Environment.Exit (1);
1108 string [] refs = value.Split (new char [] { ';', ',' });
1109 foreach (string r in refs){
1116 Report.Error (5, arg + " requires an argument");
1117 Environment.Exit (1);
1120 win32ResourceFile = value;
1123 case "/win32icon": {
1125 Report.Error (5, arg + " requires an argument");
1126 Environment.Exit (1);
1129 win32IconFile = value;
1134 Report.Error (2006, arg + " requires an argument");
1135 Environment.Exit (1);
1137 RootContext.Documentation = new Documentation (value);
1144 Report.Error (5, "/lib requires an argument");
1145 Environment.Exit (1);
1148 libdirs = value.Split (new Char [] { ',' });
1149 foreach (string dir in libdirs)
1150 link_paths.Add (dir);
1155 want_debugging_support = false;
1160 want_debugging_support = true;
1165 RootContext.Checked = true;
1169 RootContext.Checked = false;
1177 RootContext.VerifyClsCompliance = false;
1182 RootContext.Unsafe = true;
1186 RootContext.Unsafe = false;
1189 case "/warnaserror":
1190 case "/warnaserror+":
1191 Report.WarningsAreErrors = true;
1194 case "/warnaserror-":
1195 Report.WarningsAreErrors = false;
1199 SetWarningLevel (value);
1206 Report.Error (5, "/nowarn requires an argument");
1207 Environment.Exit (1);
1210 warns = value.Split (new Char [] {','});
1211 foreach (string wc in warns){
1213 int warn = Int32.Parse (wc);
1215 throw new ArgumentOutOfRangeException("warn");
1217 Report.SetIgnoreWarning (warn);
1219 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1226 load_default_config = true;
1231 load_default_config = false;
1236 Environment.Exit(0);
1242 Environment.Exit (0);
1248 Report.Error (5, arg + " requires an argument");
1249 Environment.Exit (1);
1251 RootContext.MainClass = value;
1256 RootContext.StdLib = false;
1260 RootContext.StdLib = true;
1267 if (value == String.Empty) {
1268 Report.Error (5, arg + " requires an argument");
1269 Environment.Exit (1);
1271 RootContext.StrongNameKeyFile = value;
1273 case "/keycontainer":
1274 if (value == String.Empty) {
1275 Report.Error (5, arg + " requires an argument");
1276 Environment.Exit (1);
1278 RootContext.StrongNameKeyContainer = value;
1281 RootContext.StrongNameDelaySign = true;
1284 RootContext.StrongNameDelaySign = false;
1289 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1293 case "/langversion":
1294 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1296 RootContext.Version = LanguageVersion.ISO_1;
1303 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1309 encoding = new UTF8Encoding();
1312 encoding = defaultEncoding;
1316 encoding = Encoding.GetEncoding (
1317 Int32.Parse (value));
1319 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1325 //Report.Error (2007, String.Format ("Unrecognized command-line option: `{0}'", option));
1326 //Environment.Exit (1);
1330 static string [] AddArgs (string [] args, string [] extra_args)
1333 new_args = new string [extra_args.Length + args.Length];
1335 // if args contains '--' we have to take that into account
1336 // split args into first half and second half based on '--'
1337 // and add the extra_args before --
1338 int split_position = Array.IndexOf (args, "--");
1339 if (split_position != -1)
1341 Array.Copy (args, new_args, split_position);
1342 extra_args.CopyTo (new_args, split_position);
1343 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1347 args.CopyTo (new_args, 0);
1348 extra_args.CopyTo (new_args, args.Length);
1355 /// Parses the arguments, and drives the compilation
1360 /// TODO: Mostly structured to debug the compiler
1361 /// now, needs to be turned into a real driver soon.
1363 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1364 internal static bool MainDriver (string [] args)
1367 bool parsing_options = true;
1371 defaultEncoding = Encoding.GetEncoding (28591);
1372 } catch (Exception) {
1374 defaultEncoding = Encoding.GetEncoding (1252);
1376 encoding = defaultEncoding;
1378 references = new ArrayList ();
1379 soft_references = new ArrayList ();
1380 modules = new ArrayList ();
1381 link_paths = new ArrayList ();
1383 SetupDefaultDefines ();
1388 // This is not required because Assembly.Load knows about this
1392 Hashtable response_file_list = null;
1394 for (i = 0; i < args.Length; i++){
1395 string arg = args [i];
1399 if (arg.StartsWith ("@")){
1400 string [] extra_args;
1401 string response_file = arg.Substring (1);
1403 if (response_file_list == null)
1404 response_file_list = new Hashtable ();
1406 if (response_file_list.Contains (response_file)){
1408 1515, "Response file `" + response_file +
1409 "' specified multiple times");
1410 Environment.Exit (1);
1413 response_file_list.Add (response_file, response_file);
1415 extra_args = LoadArgs (response_file);
1416 if (extra_args == null){
1417 Report.Error (2011, "Unable to open response file: " +
1422 args = AddArgs (args, extra_args);
1426 if (parsing_options){
1428 parsing_options = false;
1432 if (arg.StartsWith ("-")){
1433 if (UnixParseOption (arg, ref args, ref i))
1437 string csc_opt = "/" + arg.Substring (1);
1438 if (CSCParseOption (csc_opt, ref args, ref i))
1441 if (arg.StartsWith ("/")){
1442 if (CSCParseOption (arg, ref args, ref i))
1448 CompileFiles (arg, false);
1457 // This will point to the NamespaceEntry of the last file that was parsed, and may
1458 // not be meaningful when resolving classes from other files. So, reset it to prevent
1461 RootContext.Tree.Types.NamespaceEntry = null;
1464 // If we are an exe, require a source file for the entry point
1466 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1467 if (first_source == null){
1468 Report.Error (2008, "No files to compile were specified");
1475 // If there is nothing to put in the assembly, and we are not a library
1477 if (first_source == null && embedded_resources == null && resources == null){
1478 Report.Error (2008, "No files to compile were specified");
1482 if (Report.Errors > 0)
1489 // Load Core Library for default compilation
1491 if (RootContext.StdLib)
1492 references.Insert (0, "mscorlib");
1494 if (load_default_config)
1495 DefineDefaultConfig ();
1497 if (Report.Errors > 0){
1502 // Load assemblies required
1505 ShowTime ("Loading references");
1506 link_paths.Add (GetSystemDir ());
1507 link_paths.Add (Directory.GetCurrentDirectory ());
1511 ShowTime (" References loaded");
1513 if (Report.Errors > 0){
1520 if (output_file == null){
1521 int pos = first_source.LastIndexOf ('.');
1524 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1526 output_file = first_source + RootContext.TargetExt;
1529 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1532 if (RootContext.Target == Target.Module) {
1533 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1534 if (module_only == null) {
1535 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1536 Environment.Exit (1);
1539 MethodInfo set_method = module_only.GetSetMethod (true);
1540 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1543 TypeManager.AddModule (CodeGen.Module.Builder);
1545 if (modules.Count > 0) {
1546 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1547 if (adder_method == null) {
1548 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1549 Environment.Exit (1);
1552 foreach (string module in modules)
1553 LoadModule (adder_method, module);
1556 TypeManager.ComputeNamespaces ();
1559 // Before emitting, we need to get the core
1560 // types emitted from the user defined types
1561 // or from the system ones.
1564 ShowTime ("Initializing Core Types");
1565 if (!RootContext.StdLib){
1566 RootContext.ResolveCore ();
1567 if (Report.Errors > 0)
1571 TypeManager.InitCoreTypes ();
1573 ShowTime (" Core Types done");
1575 CodeGen.Module.ResolveAttributes ();
1578 // The second pass of the compiler
1581 ShowTime ("Resolving tree");
1582 RootContext.ResolveTree ();
1584 if (Report.Errors > 0)
1587 ShowTime ("Populate tree");
1588 if (!RootContext.StdLib)
1589 RootContext.BootCorlib_PopulateCoreTypes ();
1590 RootContext.PopulateTypes ();
1592 TypeManager.InitCodeHelpers ();
1594 RootContext.DefineTypes ();
1596 if (RootContext.Documentation != null &&
1597 !RootContext.Documentation.OutputDocComment (
1602 // Verify using aliases now
1604 Namespace.VerifyUsing ();
1606 if (Report.Errors > 0){
1610 if (RootContext.VerifyClsCompliance) {
1611 CodeGen.Assembly.ResolveClsCompliance ();
1612 if (CodeGen.Assembly.IsClsCompliant) {
1613 AttributeTester.VerifyModulesClsCompliance ();
1614 TypeManager.LoadAllImportedTypes ();
1617 if (Report.Errors > 0)
1621 // The code generator
1624 ShowTime ("Emitting code");
1625 ShowTotalTime ("Total so far");
1626 RootContext.EmitCode ();
1630 if (Report.Errors > 0){
1635 ShowTime ("Closing types");
1637 RootContext.CloseTypes ();
1639 PEFileKinds k = PEFileKinds.ConsoleApplication;
1641 switch (RootContext.Target) {
1642 case Target.Library:
1644 k = PEFileKinds.Dll; break;
1646 k = PEFileKinds.ConsoleApplication; break;
1648 k = PEFileKinds.WindowApplication; break;
1651 if (RootContext.NeedsEntryPoint) {
1652 MethodInfo ep = RootContext.EntryPoint;
1655 if (RootContext.MainClass != null) {
1656 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass, Location.Null));
1657 if (main_cont == null) {
1658 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1662 if (!(main_cont is ClassOrStruct)) {
1663 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1667 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1671 if (Report.Errors == 0)
1672 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1677 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1678 } else if (RootContext.MainClass != null) {
1679 Report.Error (2017, "Cannot specify -main if building a module or library");
1683 // Add the resources
1685 if (resources != null){
1686 foreach (string spec in resources){
1690 cp = spec.IndexOf (',');
1692 file = spec.Substring (0, cp);
1693 res = spec.Substring (cp + 1);
1697 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1701 if (embedded_resources != null){
1702 object[] margs = new object [2];
1703 Type[] argst = new Type [2];
1704 argst [0] = argst [1] = typeof (string);
1706 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1707 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1708 null, CallingConventions.Any, argst, null);
1710 if (embed_res == null) {
1711 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1713 foreach (string spec in embedded_resources) {
1716 cp = spec.IndexOf (',');
1718 margs [0] = spec.Substring (cp + 1);
1719 margs [1] = spec.Substring (0, cp);
1722 margs [0] = Path.GetFileName (spec);
1725 if (File.Exists ((string) margs [1]))
1726 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1728 Report.Error (1566, "Can not find the resource " + margs [1]);
1735 // Add Win32 resources
1738 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1740 if (win32ResourceFile != null) {
1742 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1744 catch (ArgumentException) {
1745 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1749 if (win32IconFile != null) {
1750 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1751 if (define_icon == null) {
1752 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1754 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1757 if (Report.Errors > 0)
1760 CodeGen.Save (output_file);
1762 ShowTime ("Saved output");
1763 ShowTotalTime ("Total");
1766 Timer.ShowTimers ();
1768 if (Report.ExpectedError != 0){
1769 if (Report.Errors == 0) {
1770 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1771 "No other errors reported.");
1773 Environment.Exit (2);
1775 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1776 "However, other errors were reported.");
1778 Environment.Exit (1);
1786 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1787 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1789 return (Report.Errors == 0);
1794 // This is the only public entry point
1796 public class CompilerCallableEntryPoint : MarshalByRefObject {
1797 public static bool InvokeCompiler (string [] args, TextWriter error)
1799 Report.Stderr = error;
1801 return Driver.MainDriver (args) && Report.Errors == 0;
1804 Report.Stderr = Console.Error;
1809 static void Reset ()
1813 RootContext.Reset ();
1815 TypeManager.Reset ();
1816 TypeHandle.Reset ();