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)
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 using System.Globalization;
20 using System.Diagnostics;
23 Library, Exe, Module, WinExe
27 /// The compiler driver.
33 // Assemblies references to be linked. Initialized with
35 static ArrayList references;
38 // If any of these fail, we ignore the problem. This is so
39 // that we can list all the assemblies in Windows and not fail
40 // if they are missing on Linux.
42 static ArrayList soft_references;
45 // Modules to be linked
47 static ArrayList modules;
50 static ArrayList link_paths;
52 // Whether we want Yacc to output its progress
53 static bool yacc_verbose = false;
55 // Whether we want to only run the tokenizer
56 static bool tokenize = false;
58 static string first_source;
60 static bool want_debugging_support = false;
62 static bool parse_only = false;
63 static bool timestamps = false;
64 static bool pause = false;
65 static bool show_counters = false;
66 public static bool parser_verbose = false;
69 // Whether to load the initial config file (what CSC.RSP has by default)
71 static bool load_default_config = true;
73 static Hashtable response_file_list;
76 // A list of resource files
78 static ArrayList resources;
79 static ArrayList embedded_resources;
80 static string win32ResourceFile;
81 static string win32IconFile;
84 // An array of the defines from the command line
86 static ArrayList defines;
91 static string output_file = null;
94 // Last time we took the time
96 static DateTime last_time, first_time;
99 // Encoding: ISO-Latin1 is 28591
101 static Encoding encoding;
104 // Whether the user has specified a different encoder manually
106 static bool using_default_encoder = true;
108 public static void ShowTime (string msg)
113 DateTime now = DateTime.Now;
114 TimeSpan span = now - last_time;
118 "[{0:00}:{1:000}] {2}",
119 (int) span.TotalSeconds, span.Milliseconds, msg);
122 public static void ShowTotalTime (string msg)
127 DateTime now = DateTime.Now;
128 TimeSpan span = now - first_time;
132 "[{0:00}:{1:000}] {2}",
133 (int) span.TotalSeconds, span.Milliseconds, msg);
136 static void tokenize_file (SourceFile file)
141 input = File.OpenRead (file.Name);
143 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
148 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
149 Tokenizer lexer = new Tokenizer (reader, file, defines);
150 int token, tokens = 0, errors = 0;
152 while ((token = lexer.token ()) != Token.EOF){
154 if (token == Token.ERROR)
157 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
163 // MonoTODO("Change error code for aborted compilation to something reasonable")]
164 static void parse (SourceFile file)
170 input = File.OpenRead (file.Name);
172 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
176 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
178 parser = new CSharpParser (reader, file, defines);
181 } catch (Exception ex) {
182 Report.Error(666, "Compilation aborted: " + ex);
188 static void OtherFlags ()
191 "Other flags in the compiler\n" +
192 " --fatal Makes errors fatal\n" +
193 " --parse Only parses the source file\n" +
194 " --stacktrace Shows stack trace at error location\n" +
195 " --timestamp Displays time stamps of various compiler events\n" +
196 " -2 Enables experimental C# features\n" +
197 " -v Verbose parsing (for debugging the parser)\n" +
198 " --mcs-debug X Sets MCS debugging level to X\n");
204 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
205 "mcs [options] source-files\n" +
206 " --about About the Mono C# compiler\n" +
207 " -addmodule:MODULE Adds the module to the generated assembly\n" +
208 " -checked[+|-] Set default context to checked\n" +
209 " -codepage:ID Sets code page to the one in ID\n" +
210 " (number, `utf8' or `reset')\n" +
211 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
212 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
213 " -debug[+|-] Generate debugging information\n" +
214 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
215 " -doc:FILE XML Documentation file to generate\n" +
216 " -g Generate debugging information\n" +
217 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
218 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
219 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
220 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
221 " -main:class Specified the class that contains the entry point\n" +
222 " -noconfig[+|-] Disables implicit references to assemblies\n" +
223 " -nostdlib[+|-] Does not load core libraries\n" +
224 " -nowarn:W1[,W2] Disables one or more warnings\n" +
225 " -out:FNAME Specifies output file\n" +
226 " -pkg:P1[,Pn] References packages P1..Pn\n" +
227 " --expect-error X Expect that error X will be encountered\n" +
228 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
229 " -reference:ASS References the specified assembly (-r:ASS)\n" +
230 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
231 " library, module), (short: /t:)\n" +
232 " -unsafe[+|-] Allows unsafe code\n" +
233 " -warnaserror[+|-] Treat warnings as errors\n" +
234 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
235 " -help2 Show other help flags\n" +
238 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
239 " -resource:FILE[,ID] Embed FILE as a resource\n" +
240 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
241 " -win32icon:FILE Use this icon for the output\n" +
242 " @file Read response file for more options\n\n" +
243 "Options can be of the form -option or /option");
246 static void TargetUsage ()
248 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
254 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
255 "The compiler source code is released under the terms of the GNU GPL\n\n" +
257 "For more information on Mono, visit the project Web site\n" +
258 " http://www.go-mono.com\n\n" +
260 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
261 Environment.Exit (0);
264 public static int counter1, counter2;
266 public static int Main (string[] args)
268 bool ok = MainDriver (args);
270 if (ok && Report.Errors == 0) {
271 Console.Write("Compilation succeeded");
272 if (Report.Warnings > 0) {
273 Console.Write(" - {0} warning(s)", Report.Warnings);
277 Console.WriteLine ("Counter1: " + counter1);
278 Console.WriteLine ("Counter2: " + counter2);
284 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
285 Report.Errors, Report.Warnings);
290 static public void LoadAssembly (string assembly, bool soft)
293 string total_log = "";
296 char[] path_chars = { '/', '\\' };
298 if (assembly.IndexOfAny (path_chars) != -1) {
299 a = Assembly.LoadFrom (assembly);
301 string ass = assembly;
302 if (ass.EndsWith (".dll"))
303 ass = assembly.Substring (0, assembly.Length - 4);
304 a = Assembly.Load (ass);
306 TypeManager.AddAssembly (a);
308 } catch (FileNotFoundException){
309 foreach (string dir in link_paths){
310 string full_path = Path.Combine (dir, assembly);
311 if (!assembly.EndsWith (".dll"))
315 a = Assembly.LoadFrom (full_path);
316 TypeManager.AddAssembly (a);
318 } catch (FileNotFoundException ff) {
319 total_log += ff.FusionLog;
324 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
325 Console.WriteLine ("Log: \n" + total_log);
327 } catch (BadImageFormatException f) {
328 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
329 } catch (FileLoadException f){
330 Report.Error(6, "Cannot load assembly " + f.FusionLog);
331 } catch (ArgumentNullException){
332 Report.Error(6, "Cannot load assembly (null argument)");
336 static public void LoadModule (MethodInfo adder_method, string module)
339 string total_log = "";
343 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
345 catch (TargetInvocationException ex) {
346 throw ex.InnerException;
348 TypeManager.AddModule (m);
351 catch (FileNotFoundException){
352 foreach (string dir in link_paths){
353 string full_path = Path.Combine (dir, module);
354 if (!module.EndsWith (".netmodule"))
355 full_path += ".netmodule";
359 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
361 catch (TargetInvocationException ex) {
362 throw ex.InnerException;
364 TypeManager.AddModule (m);
366 } catch (FileNotFoundException ff) {
367 total_log += ff.FusionLog;
371 Report.Error (6, "Cannot find module `" + module + "'" );
372 Console.WriteLine ("Log: \n" + total_log);
373 } catch (BadImageFormatException f) {
374 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
375 } catch (FileLoadException f){
376 Report.Error(6, "Cannot load module " + f.FusionLog);
377 } catch (ArgumentNullException){
378 Report.Error(6, "Cannot load module (null argument)");
383 /// Loads all assemblies referenced on the command line
385 static public void LoadReferences ()
387 foreach (string r in references)
388 LoadAssembly (r, false);
390 foreach (string r in soft_references)
391 LoadAssembly (r, true);
396 static void SetupDefaultDefines ()
398 defines = new ArrayList ();
399 defines.Add ("__MonoCS__");
402 static string [] LoadArgs (string file)
405 ArrayList args = new ArrayList ();
408 f = new StreamReader (file);
413 StringBuilder sb = new StringBuilder ();
415 while ((line = f.ReadLine ()) != null){
418 for (int i = 0; i < t; i++){
421 if (c == '"' || c == '\''){
424 for (i++; i < t; i++){
431 } else if (c == ' '){
433 args.Add (sb.ToString ());
440 args.Add (sb.ToString ());
445 string [] ret_value = new string [args.Count];
446 args.CopyTo (ret_value, 0);
452 // Returns the directory where the system assemblies are installed
454 static string GetSystemDir ()
456 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
458 foreach (Assembly a in assemblies){
459 string codebase = a.Location;
460 string fn = System.IO.Path.GetFileName (codebase);
461 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
462 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
466 Report.Error (-15, "Can not compute my system path");
471 // Given a path specification, splits the path from the file/pattern
473 static void SplitPathAndPattern (string spec, out string path, out string pattern)
475 int p = spec.LastIndexOf ('/');
478 // Windows does not like /file.cs, switch that to:
483 pattern = spec.Substring (1);
485 path = spec.Substring (0, p);
486 pattern = spec.Substring (p + 1);
491 p = spec.LastIndexOf ('\\');
493 path = spec.Substring (0, p);
494 pattern = spec.Substring (p + 1);
502 static void ProcessFile (string f)
504 if (first_source == null)
507 Location.AddFile (f);
510 static void ProcessFiles ()
512 Location.Initialize ();
514 foreach (SourceFile file in Location.SourceFiles) {
516 tokenize_file (file);
523 static void CompileFiles (string spec, bool recurse)
525 string path, pattern;
527 SplitPathAndPattern (spec, out path, out pattern);
528 if (pattern.IndexOf ('*') == -1){
533 string [] files = null;
535 files = Directory.GetFiles (path, pattern);
536 } catch (System.IO.DirectoryNotFoundException) {
537 Report.Error (2001, "Source file `" + spec + "' could not be found");
539 } catch (System.IO.IOException){
540 Report.Error (2001, "Source file `" + spec + "' could not be found");
543 foreach (string f in files) {
550 string [] dirs = null;
553 dirs = Directory.GetDirectories (path);
557 foreach (string d in dirs) {
559 // Don't include path in this string, as each
560 // directory entry already does
561 CompileFiles (d + "/" + pattern, true);
565 static void DefineDefaultConfig ()
568 // For now the "default config" is harcoded into the compiler
569 // we can move this outside later
571 string [] default_config = {
576 // Is it worth pre-loading all this stuff?
579 "System.Configuration.Install",
582 "System.DirectoryServices",
583 "System.Drawing.Design",
585 "System.EnterpriseServices",
588 "System.Runtime.Remoting",
589 "System.Runtime.Serialization.Formatters.Soap",
591 "System.ServiceProcess",
593 "System.Web.RegularExpressions",
594 "System.Web.Services",
595 "System.Windows.Forms"
600 foreach (string def in default_config)
601 soft_references.Insert (p++, def);
604 static void SetOutputFile (string name)
609 static void SetWarningLevel (string s)
614 level = Int32.Parse (s);
618 "--wlevel requires a value from 0 to 4");
619 Environment.Exit (1);
621 if (level < 0 || level > 4){
622 Report.Error (1900, "Warning level must be 0 to 4");
623 Environment.Exit (1);
625 RootContext.WarningLevel = level;
626 TestWarningConflict ();
629 static void TestWarningConflict ()
631 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
632 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
633 Environment.Exit (1);
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 if ((i + 1) >= args.Length){
673 Environment.Exit (1);
675 RootContext.MainClass = args [++i];
679 RootContext.Unsafe = true;
682 case "/?": case "/h": case "/help":
685 Environment.Exit (0);
689 if ((i + 1) >= args.Length){
691 Environment.Exit (1);
693 defines.Add (args [++i]);
696 case "--show-counters":
697 show_counters = true;
700 case "--expect-error": {
705 args [++i], NumberStyles.AllowLeadingSign);
706 Report.ExpectedError = code;
708 Report.Error (-14, "Invalid number specified");
719 if ((i + 1) >= args.Length){
721 Environment.Exit (1);
723 SetOutputFile (args [++i]);
727 RootContext.Checked = true;
731 Report.Stacktrace = true;
734 case "--linkresource":
736 if ((i + 1) >= args.Length){
738 Report.Error (5, "Missing argument to --linkres");
739 Environment.Exit (1);
741 if (resources == null)
742 resources = new ArrayList ();
744 resources.Add (args [++i]);
749 if ((i + 1) >= args.Length){
751 Report.Error (5, "Missing argument to --resource");
752 Environment.Exit (1);
754 if (embedded_resources == null)
755 embedded_resources = new ArrayList ();
757 embedded_resources.Add (args [++i]);
761 if ((i + 1) >= args.Length){
762 Environment.Exit (1);
766 string type = args [++i];
769 RootContext.Target = Target.Library;
770 RootContext.TargetExt = ".dll";
774 RootContext.Target = Target.Exe;
778 RootContext.Target = Target.WinExe;
782 RootContext.Target = Target.Module;
783 RootContext.TargetExt = ".dll";
787 Environment.Exit (1);
793 if ((i + 1) >= args.Length){
795 Environment.Exit (1);
798 references.Add (args [++i]);
802 if ((i + 1) >= args.Length){
804 Environment.Exit (1);
806 link_paths.Add (args [++i]);
810 RootContext.StdLib = false;
818 Report.WarningsAreErrors = true;
819 TestWarningConflict();
823 if ((i + 1) >= args.Length){
825 Environment.Exit (1);
830 warn = Int32.Parse (args [++i]);
833 Environment.Exit (1);
835 Report.SetIgnoreWarning (warn);
839 if ((i + 1) >= args.Length){
842 "--wlevel requires a value from 0 to 4");
843 Environment.Exit (1);
846 SetWarningLevel (args [++i]);
850 if ((i + 1) >= args.Length){
851 Report.Error (5, "--mcs-debug requires an argument");
852 Environment.Exit (1);
856 Report.DebugFlags = Int32.Parse (args [++i]);
858 Report.Error (5, "Invalid argument to --mcs-debug");
859 Environment.Exit (1);
868 if ((i + 1) >= args.Length){
869 Report.Error (5, "--recurse requires an argument");
870 Environment.Exit (1);
872 CompileFiles (args [++i], true);
877 last_time = first_time = DateTime.Now;
884 case "--debug": case "-g":
885 want_debugging_support = true;
889 load_default_config = false;
897 // Currently it is very basic option parsing, but eventually, this will
898 // be the complete option parser
900 static bool CSCParseOption (string option, ref string [] args, ref int i)
902 int idx = option.IndexOf (':');
909 arg = option.Substring (0, idx);
911 value = option.Substring (idx + 1);
922 RootContext.Target = Target.Exe;
926 RootContext.Target = Target.WinExe;
930 RootContext.Target = Target.Library;
931 RootContext.TargetExt = ".dll";
935 RootContext.Target = Target.Module;
936 RootContext.TargetExt = ".netmodule";
941 Environment.Exit (1);
949 Environment.Exit (1);
951 SetOutputFile (value);
958 case "/incremental+":
959 case "/incremental-":
969 Environment.Exit (1);
972 defs = value.Split (new Char [] {';', ','});
973 foreach (string d in defs){
980 case "/linkresource":
982 Report.Error (5, arg + " requires an argument");
983 Environment.Exit (1);
985 if (resources == null)
986 resources = new ArrayList ();
988 resources.Add (value);
996 Environment.Exit (1);
998 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1000 ProcessStartInfo pi = new ProcessStartInfo ();
1001 pi.FileName = "pkg-config";
1002 pi.RedirectStandardOutput = true;
1003 pi.UseShellExecute = false;
1004 pi.Arguments = "--libs " + packages;
1007 p = Process.Start (pi);
1008 } catch (Exception e) {
1009 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1010 Environment.Exit (1);
1013 if (p.StandardOutput == null){
1014 Report.Warning (-27, "Specified package did not return any information");
1017 string pkgout = p.StandardOutput.ReadToEnd ();
1019 if (p.ExitCode != 0) {
1020 Report.Error (-27, "Error running pkg-config. Check the above output.");
1021 Environment.Exit (1);
1024 if (pkgout != null){
1025 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1026 Split (new Char [] { ' ', '\t'});
1027 args = AddArgs (args, xargs);
1037 Report.Error (5, "-resource requires an argument");
1038 Environment.Exit (1);
1040 if (embedded_resources == null)
1041 embedded_resources = new ArrayList ();
1043 if (embedded_resources.Contains (value)) {
1044 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1046 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1047 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1050 embedded_resources.Add (value);
1056 Report.Error (5, "-recurse requires an argument");
1057 Environment.Exit (1);
1059 CompileFiles (value, true);
1063 case "/reference": {
1065 Report.Error (5, "-reference requires an argument");
1066 Environment.Exit (1);
1069 string [] refs = value.Split (new char [] { ';', ',' });
1070 foreach (string r in refs){
1075 case "/addmodule": {
1077 Report.Error (5, arg + " requires an argument");
1078 Environment.Exit (1);
1081 string [] refs = value.Split (new char [] { ';', ',' });
1082 foreach (string r in refs){
1089 Report.Error (5, arg + " requires an argument");
1090 Environment.Exit (1);
1093 win32ResourceFile = value;
1096 case "/win32icon": {
1098 Report.Error (5, arg + " requires an argument");
1099 Environment.Exit (1);
1102 win32IconFile = value;
1107 Report.Error (5, arg + " requires an argument");
1108 Environment.Exit (1);
1110 // TODO handle the /doc argument to generate xml doc
1117 Report.Error (5, "/lib requires an argument");
1118 Environment.Exit (1);
1121 libdirs = value.Split (new Char [] { ',' });
1122 foreach (string dir in libdirs)
1123 link_paths.Add (dir);
1128 want_debugging_support = false;
1133 want_debugging_support = true;
1138 RootContext.Checked = true;
1142 RootContext.Checked = false;
1150 RootContext.VerifyClsCompliance = false;
1155 RootContext.Unsafe = true;
1159 RootContext.Unsafe = false;
1162 case "/warnaserror":
1163 case "/warnaserror+":
1164 Report.WarningsAreErrors = true;
1165 TestWarningConflict();
1168 case "/warnaserror-":
1169 Report.WarningsAreErrors = false;
1173 SetWarningLevel (value);
1180 Report.Error (5, "/nowarn requires an argument");
1181 Environment.Exit (1);
1184 warns = value.Split (new Char [] {','});
1185 foreach (string wc in warns){
1187 int warn = Int32.Parse (wc);
1189 throw new ArgumentOutOfRangeException("warn");
1191 Report.SetIgnoreWarning (warn);
1193 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1194 Environment.Exit (1);
1201 load_default_config = true;
1206 load_default_config = false;
1211 Environment.Exit(0);
1217 Environment.Exit (0);
1223 Report.Error (5, arg + " requires an argument");
1224 Environment.Exit (1);
1226 RootContext.MainClass = value;
1231 RootContext.StdLib = false;
1235 RootContext.StdLib = true;
1242 if (value == String.Empty) {
1243 Report.Error (5, arg + " requires an argument");
1244 Environment.Exit (1);
1246 RootContext.StrongNameKeyFile = value;
1248 case "/keycontainer":
1249 if (value == String.Empty) {
1250 Report.Error (5, arg + " requires an argument");
1251 Environment.Exit (1);
1253 RootContext.StrongNameKeyContainer = value;
1256 RootContext.StrongNameDelaySign = true;
1259 RootContext.StrongNameDelaySign = false;
1264 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1268 case "/langversion":
1269 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1271 RootContext.Version = LanguageVersion.ISO_1;
1278 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1279 Environment.Exit (1);
1285 if (value == "utf8"){
1286 encoding = new UTF8Encoding();
1287 using_default_encoder = false;
1290 if (value == "reset"){
1292 // 28591 is the code page for ISO-8859-1 encoding.
1295 using_default_encoder = true;
1299 cp = Int32.Parse (value);
1300 encoding = Encoding.GetEncoding (cp);
1301 using_default_encoder = false;
1303 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1304 Environment.Exit (1);
1309 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1310 //Environment.Exit (1);
1314 static string [] AddArgs (string [] args, string [] extra_args)
1318 new_args = new string [extra_args.Length + args.Length];
1319 args.CopyTo (new_args, 0);
1320 extra_args.CopyTo (new_args, args.Length);
1326 /// Parses the arguments, and drives the compilation
1331 /// TODO: Mostly structured to debug the compiler
1332 /// now, needs to be turned into a real driver soon.
1334 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1335 internal static bool MainDriver (string [] args)
1338 bool parsing_options = true;
1341 encoding = Encoding.GetEncoding (28591);
1343 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1344 encoding = Encoding.GetEncoding (1252);
1347 references = new ArrayList ();
1348 soft_references = new ArrayList ();
1349 modules = new ArrayList ();
1350 link_paths = new ArrayList ();
1352 SetupDefaultDefines ();
1357 // This is not required because Assembly.Load knows about this
1361 for (i = 0; i < args.Length; i++){
1362 string arg = args [i];
1366 if (arg.StartsWith ("@")){
1367 string [] extra_args;
1368 string response_file = arg.Substring (1);
1370 if (response_file_list == null)
1371 response_file_list = new Hashtable ();
1373 if (response_file_list.Contains (response_file)){
1375 1515, "Response file `" + response_file +
1376 "' specified multiple times");
1377 Environment.Exit (1);
1380 response_file_list.Add (response_file, response_file);
1382 extra_args = LoadArgs (response_file);
1383 if (extra_args == null){
1384 Report.Error (2011, "Unable to open response file: " +
1389 args = AddArgs (args, extra_args);
1393 if (parsing_options){
1395 parsing_options = false;
1399 if (arg.StartsWith ("-")){
1400 if (UnixParseOption (arg, ref args, ref i))
1404 string csc_opt = "/" + arg.Substring (1);
1405 if (CSCParseOption (csc_opt, ref args, ref i))
1408 if (arg.StartsWith ("/")){
1409 if (CSCParseOption (arg, ref args, ref i))
1415 CompileFiles (arg, false);
1424 // If we are an exe, require a source file for the entry point
1426 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1427 if (first_source == null){
1428 Report.Error (2008, "No files to compile were specified");
1435 // If there is nothing to put in the assembly, and we are not a library
1437 if (first_source == null && embedded_resources == null && resources == null){
1438 Report.Error (2008, "No files to compile were specified");
1442 if (Report.Errors > 0)
1448 Tokenizer.Cleanup ();
1451 // Load Core Library for default compilation
1453 if (RootContext.StdLib)
1454 references.Insert (0, "mscorlib");
1456 if (load_default_config)
1457 DefineDefaultConfig ();
1459 if (Report.Errors > 0){
1464 // Load assemblies required
1467 ShowTime ("Loading references");
1468 link_paths.Add (GetSystemDir ());
1469 link_paths.Add (Directory.GetCurrentDirectory ());
1473 ShowTime (" References loaded");
1475 if (Report.Errors > 0){
1482 if (output_file == null){
1483 int pos = first_source.LastIndexOf ('.');
1486 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1488 output_file = first_source + RootContext.TargetExt;
1491 CodeGen.Init (output_file, output_file, want_debugging_support);
1493 if (RootContext.Target == Target.Module) {
1494 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1495 if (module_only == null) {
1496 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1497 Environment.Exit (1);
1500 MethodInfo set_method = module_only.GetSetMethod (true);
1501 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1504 TypeManager.AddModule (CodeGen.Module.Builder);
1506 if (modules.Count > 0) {
1507 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1508 if (adder_method == null) {
1509 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1510 Environment.Exit (1);
1513 foreach (string module in modules)
1514 LoadModule (adder_method, module);
1517 TypeManager.ComputeNamespaces ();
1520 // Before emitting, we need to get the core
1521 // types emitted from the user defined types
1522 // or from the system ones.
1525 ShowTime ("Initializing Core Types");
1526 if (!RootContext.StdLib){
1527 RootContext.ResolveCore ();
1528 if (Report.Errors > 0)
1532 TypeManager.InitCoreTypes ();
1534 ShowTime (" Core Types done");
1537 // The second pass of the compiler
1540 ShowTime ("Resolving tree");
1541 RootContext.ResolveTree ();
1542 if (Report.Errors > 0)
1545 ShowTime ("Populate tree");
1546 if (!RootContext.StdLib)
1547 RootContext.BootCorlib_PopulateCoreTypes ();
1549 RootContext.PopulateTypes ();
1550 RootContext.DefineTypes ();
1552 TypeManager.InitCodeHelpers ();
1555 // Verify using aliases now
1557 Namespace.VerifyUsing ();
1559 if (Report.Errors > 0){
1563 if (RootContext.VerifyClsCompliance) {
1564 CodeGen.Assembly.ResolveClsCompliance ();
1565 if (CodeGen.Assembly.IsClsCompliant) {
1566 AttributeTester.VerifyModulesClsCompliance ();
1567 TypeManager.LoadAllImportedTypes ();
1568 AttributeTester.VerifyTopLevelNameClsCompliance ();
1573 // The code generator
1576 ShowTime ("Emitting code");
1577 ShowTotalTime ("Total so far");
1578 RootContext.EmitCode ();
1582 if (Report.Errors > 0){
1587 ShowTime ("Closing types");
1589 RootContext.CloseTypes ();
1591 PEFileKinds k = PEFileKinds.ConsoleApplication;
1593 switch (RootContext.Target) {
1594 case Target.Library:
1596 k = PEFileKinds.Dll; break;
1598 k = PEFileKinds.ConsoleApplication; break;
1600 k = PEFileKinds.WindowApplication; break;
1603 if (RootContext.NeedsEntryPoint) {
1604 MethodInfo ep = RootContext.EntryPoint;
1607 if (RootContext.MainClass != null) {
1608 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1609 if (main_cont == null) {
1610 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1614 if (!(main_cont is ClassOrStruct)) {
1615 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1620 if (Report.Errors == 0)
1621 Report.Error (5001, "Program " + output_file +
1622 " does not have an entry point defined");
1626 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1627 } else if (RootContext.MainClass != null) {
1628 Report.Error (2017, "Can not specify -main: when building module or library");
1632 // Add the resources
1634 if (resources != null){
1635 foreach (string spec in resources){
1639 cp = spec.IndexOf (',');
1641 file = spec.Substring (0, cp);
1642 res = spec.Substring (cp + 1);
1646 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1650 if (embedded_resources != null){
1651 object[] margs = new object [2];
1652 Type[] argst = new Type [2];
1653 argst [0] = argst [1] = typeof (string);
1655 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1656 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1657 null, CallingConventions.Any, argst, null);
1659 if (embed_res == null) {
1660 Report.Warning (0, new Location (-1),
1661 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1663 foreach (string spec in embedded_resources) {
1666 cp = spec.IndexOf (',');
1668 margs [0] = spec.Substring (cp + 1);
1669 margs [1] = spec.Substring (0, cp);
1672 margs [0] = Path.GetFileName (spec);
1675 if (File.Exists ((string) margs [1]))
1676 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1678 Report.Error (1566, "Can not find the resource " + margs [1]);
1685 // Add Win32 resources
1688 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1690 if (win32ResourceFile != null) {
1692 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1694 catch (ArgumentException) {
1695 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1699 if (win32IconFile != null) {
1700 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1701 if (define_icon == null) {
1702 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1704 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1707 if (Report.Errors > 0)
1710 CodeGen.Save (output_file);
1712 ShowTime ("Saved output");
1713 ShowTotalTime ("Total");
1716 Timer.ShowTimers ();
1718 if (Report.ExpectedError != 0) {
1719 if (Report.Errors == 0) {
1720 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1721 "No other errors reported.");
1723 Environment.Exit (2);
1725 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1726 "However, other errors were reported.");
1728 Environment.Exit (1);
1736 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1737 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1739 return (Report.Errors == 0);
1745 // This is the only public entry point
1747 public class CompilerCallableEntryPoint : MarshalByRefObject {
1748 static bool used = false;
1750 public bool InvokeCompiler (string [] args)
1754 bool ok = Driver.MainDriver (args);
1755 return ok && Report.Errors == 0;
1758 public void Reset ()