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;
17 using System.Diagnostics;
20 using System.Globalization;
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);
179 parser.yacc_verbose_flag = yacc_verbose;
182 } catch (Exception ex) {
183 Report.Error(666, "Compilation aborted: " + ex);
189 static void OtherFlags ()
192 "Other flags in the compiler\n" +
193 " --fatal Makes errors fatal\n" +
194 " --parse Only parses the source file\n" +
195 " --stacktrace Shows stack trace at error location\n" +
196 " --timestamp Displays time stamps of various compiler events\n" +
197 " -2 Enables experimental C# features\n" +
198 " -v Verbose parsing (for debugging the parser)\n" +
199 " --mcs-debug X Sets MCS debugging level to X\n");
205 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
206 "mcs [options] source-files\n" +
207 " --about About the Mono C# compiler\n" +
208 " -addmodule:MODULE Adds the module to the generated assembly\n" +
209 " -checked[+|-] Set default context to checked\n" +
210 " -codepage:ID Sets code page to the one in ID\n" +
211 " (number, `utf8' or `reset')\n" +
212 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
213 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
214 " -debug[+|-] Generate debugging information\n" +
215 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
216 " -doc:FILE XML Documentation file to generate\n" +
217 " -g Generate debugging information\n" +
218 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
219 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
220 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
221 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
222 " -main:class Specified the class that contains the entry point\n" +
223 " -noconfig[+|-] Disables implicit references to assemblies\n" +
224 " -nostdlib[+|-] Does not load core libraries\n" +
225 " -nowarn:W1[,W2] Disables one or more warnings\n" +
226 " -out:FNAME Specifies output file\n" +
227 " -pkg:P1[,Pn] References packages P1..Pn\n" +
228 " --expect-error X Expect that error X will be encountered\n" +
229 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
230 " -reference:ASS References the specified assembly (-r:ASS)\n" +
231 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
232 " library, module), (short: /t:)\n" +
233 " -unsafe[+|-] Allows unsafe code\n" +
234 " -warnaserror[+|-] Treat warnings as errors\n" +
235 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
236 " -help2 Show other help flags\n" +
239 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
240 " -resource:FILE[,ID] Embed FILE as a resource\n" +
241 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
242 " -win32icon:FILE Use this icon for the output\n" +
243 " @file Read response file for more options\n\n" +
244 "Options can be of the form -option or /option");
247 static void TargetUsage ()
249 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
255 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
256 "The compiler source code is released under the terms of the GNU GPL\n\n" +
258 "For more information on Mono, visit the project Web site\n" +
259 " http://www.go-mono.com\n\n" +
261 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
262 Environment.Exit (0);
265 public static int counter1, counter2;
267 public static int Main (string[] args)
269 RootContext.Version = LanguageVersion.Default;
270 bool ok = MainDriver (args);
272 if (ok && Report.Errors == 0) {
273 Console.Write("Compilation succeeded");
274 if (Report.Warnings > 0) {
275 Console.Write(" - {0} warning(s)", Report.Warnings);
279 Console.WriteLine ("Counter1: " + counter1);
280 Console.WriteLine ("Counter2: " + counter2);
286 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
287 Report.Errors, Report.Warnings);
292 static public void LoadAssembly (string assembly, bool soft)
295 string total_log = "";
298 char[] path_chars = { '/', '\\' };
300 if (assembly.IndexOfAny (path_chars) != -1) {
301 a = Assembly.LoadFrom (assembly);
303 string ass = assembly;
304 if (ass.EndsWith (".dll"))
305 ass = assembly.Substring (0, assembly.Length - 4);
306 a = Assembly.Load (ass);
308 TypeManager.AddAssembly (a);
310 } catch (FileNotFoundException){
311 foreach (string dir in link_paths){
312 string full_path = Path.Combine (dir, assembly);
313 if (!assembly.EndsWith (".dll"))
317 a = Assembly.LoadFrom (full_path);
318 TypeManager.AddAssembly (a);
320 } catch (FileNotFoundException ff) {
321 total_log += ff.FusionLog;
326 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
327 Console.WriteLine ("Log: \n" + total_log);
329 } catch (BadImageFormatException f) {
330 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
331 } catch (FileLoadException f){
332 Report.Error(6, "Cannot load assembly " + f.FusionLog);
333 } catch (ArgumentNullException){
334 Report.Error(6, "Cannot load assembly (null argument)");
338 static public void LoadModule (MethodInfo adder_method, string module)
341 string total_log = "";
345 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
347 catch (TargetInvocationException ex) {
348 throw ex.InnerException;
350 TypeManager.AddModule (m);
353 catch (FileNotFoundException){
354 foreach (string dir in link_paths){
355 string full_path = Path.Combine (dir, module);
356 if (!module.EndsWith (".netmodule"))
357 full_path += ".netmodule";
361 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
363 catch (TargetInvocationException ex) {
364 throw ex.InnerException;
366 TypeManager.AddModule (m);
368 } catch (FileNotFoundException ff) {
369 total_log += ff.FusionLog;
373 Report.Error (6, "Cannot find module `" + module + "'" );
374 Console.WriteLine ("Log: \n" + total_log);
375 } catch (BadImageFormatException f) {
376 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
377 } catch (FileLoadException f){
378 Report.Error(6, "Cannot load module " + f.FusionLog);
379 } catch (ArgumentNullException){
380 Report.Error(6, "Cannot load module (null argument)");
385 /// Loads all assemblies referenced on the command line
387 static public void LoadReferences ()
389 foreach (string r in references)
390 LoadAssembly (r, false);
392 foreach (string r in soft_references)
393 LoadAssembly (r, true);
398 static void SetupDefaultDefines ()
400 defines = new ArrayList ();
401 defines.Add ("__MonoCS__");
404 static string [] LoadArgs (string file)
407 ArrayList args = new ArrayList ();
410 f = new StreamReader (file);
415 StringBuilder sb = new StringBuilder ();
417 while ((line = f.ReadLine ()) != null){
420 for (int i = 0; i < t; i++){
423 if (c == '"' || c == '\''){
426 for (i++; i < t; i++){
433 } else if (c == ' '){
435 args.Add (sb.ToString ());
442 args.Add (sb.ToString ());
447 string [] ret_value = new string [args.Count];
448 args.CopyTo (ret_value, 0);
454 // Returns the directory where the system assemblies are installed
456 static string GetSystemDir ()
458 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
460 foreach (Assembly a in assemblies){
461 string codebase = a.Location;
462 string fn = System.IO.Path.GetFileName (codebase);
463 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
464 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
468 Report.Error (-15, "Can not compute my system path");
473 // Given a path specification, splits the path from the file/pattern
475 static void SplitPathAndPattern (string spec, out string path, out string pattern)
477 int p = spec.LastIndexOf ('/');
480 // Windows does not like /file.cs, switch that to:
485 pattern = spec.Substring (1);
487 path = spec.Substring (0, p);
488 pattern = spec.Substring (p + 1);
493 p = spec.LastIndexOf ('\\');
495 path = spec.Substring (0, p);
496 pattern = spec.Substring (p + 1);
504 static void ProcessFile (string f)
506 if (first_source == null)
509 Location.AddFile (f);
512 static void ProcessFiles ()
514 Location.Initialize ();
516 foreach (SourceFile file in Location.SourceFiles) {
518 tokenize_file (file);
525 static void CompileFiles (string spec, bool recurse)
527 string path, pattern;
529 SplitPathAndPattern (spec, out path, out pattern);
530 if (pattern.IndexOf ('*') == -1){
535 string [] files = null;
537 files = Directory.GetFiles (path, pattern);
538 } catch (System.IO.DirectoryNotFoundException) {
539 Report.Error (2001, "Source file `" + spec + "' could not be found");
541 } catch (System.IO.IOException){
542 Report.Error (2001, "Source file `" + spec + "' could not be found");
545 foreach (string f in files) {
552 string [] dirs = null;
555 dirs = Directory.GetDirectories (path);
559 foreach (string d in dirs) {
561 // Don't include path in this string, as each
562 // directory entry already does
563 CompileFiles (d + "/" + pattern, true);
567 static void DefineDefaultConfig ()
570 // For now the "default config" is harcoded into the compiler
571 // we can move this outside later
573 string [] default_config = {
578 // Is it worth pre-loading all this stuff?
581 "System.Configuration.Install",
584 "System.DirectoryServices",
585 "System.Drawing.Design",
587 "System.EnterpriseServices",
590 "System.Runtime.Remoting",
591 "System.Runtime.Serialization.Formatters.Soap",
593 "System.ServiceProcess",
595 "System.Web.RegularExpressions",
596 "System.Web.Services",
597 "System.Windows.Forms"
602 foreach (string def in default_config)
603 soft_references.Insert (p++, def);
606 static void SetOutputFile (string name)
611 static void SetWarningLevel (string s)
616 level = Int32.Parse (s);
620 "--wlevel requires a value from 0 to 4");
621 Environment.Exit (1);
623 if (level < 0 || level > 4){
624 Report.Error (1900, "Warning level must be 0 to 4");
625 Environment.Exit (1);
627 RootContext.WarningLevel = level;
628 TestWarningConflict ();
631 static void TestWarningConflict ()
633 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
634 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
635 Environment.Exit (1);
639 static void SetupV2 ()
641 RootContext.Version = LanguageVersion.Default;
642 defines.Add ("__V2__");
645 static void Version ()
647 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
648 Console.WriteLine ("Mono C# compiler version {0}", version);
649 Environment.Exit (0);
653 // Currently handles the Unix-like command line options, but will be
654 // deprecated in favor of the CSCParseOption, which will also handle the
655 // options that start with a dash in the future.
657 static bool UnixParseOption (string arg, ref string [] args, ref int i)
661 parser_verbose = true;
676 case "--main": case "-m":
677 if ((i + 1) >= args.Length){
679 Environment.Exit (1);
681 RootContext.MainClass = args [++i];
685 RootContext.Unsafe = true;
688 case "/?": case "/h": case "/help":
691 Environment.Exit (0);
695 if ((i + 1) >= args.Length){
697 Environment.Exit (1);
699 defines.Add (args [++i]);
702 case "--show-counters":
703 show_counters = true;
706 case "--expect-error": {
711 args [++i], NumberStyles.AllowLeadingSign);
712 Report.ExpectedError = code;
714 Report.Error (-14, "Invalid number specified");
725 if ((i + 1) >= args.Length){
727 Environment.Exit (1);
729 SetOutputFile (args [++i]);
733 RootContext.Checked = true;
737 Report.Stacktrace = true;
740 case "--linkresource":
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 if ((i + 1) >= args.Length){
757 Report.Error (5, "Missing argument to --resource");
758 Environment.Exit (1);
760 if (embedded_resources == null)
761 embedded_resources = new ArrayList ();
763 embedded_resources.Add (args [++i]);
767 if ((i + 1) >= args.Length){
768 Environment.Exit (1);
772 string type = args [++i];
775 RootContext.Target = Target.Library;
776 RootContext.TargetExt = ".dll";
780 RootContext.Target = Target.Exe;
784 RootContext.Target = Target.WinExe;
788 RootContext.Target = Target.Module;
789 RootContext.TargetExt = ".dll";
793 Environment.Exit (1);
799 if ((i + 1) >= args.Length){
801 Environment.Exit (1);
804 references.Add (args [++i]);
808 if ((i + 1) >= args.Length){
810 Environment.Exit (1);
812 link_paths.Add (args [++i]);
816 RootContext.StdLib = false;
824 Report.WarningsAreErrors = true;
825 TestWarningConflict();
829 if ((i + 1) >= args.Length){
831 Environment.Exit (1);
836 warn = Int32.Parse (args [++i]);
839 Environment.Exit (1);
841 Report.SetIgnoreWarning (warn);
845 if ((i + 1) >= args.Length){
848 "--wlevel requires a value from 0 to 4");
849 Environment.Exit (1);
852 SetWarningLevel (args [++i]);
856 if ((i + 1) >= args.Length){
857 Report.Error (5, "--mcs-debug requires an argument");
858 Environment.Exit (1);
862 Report.DebugFlags = Int32.Parse (args [++i]);
864 Report.Error (5, "Invalid argument to --mcs-debug");
865 Environment.Exit (1);
874 if ((i + 1) >= args.Length){
875 Report.Error (5, "--recurse requires an argument");
876 Environment.Exit (1);
878 CompileFiles (args [++i], true);
883 last_time = first_time = DateTime.Now;
890 case "--debug": case "-g":
891 want_debugging_support = true;
895 load_default_config = false;
903 // Currently it is very basic option parsing, but eventually, this will
904 // be the complete option parser
906 static bool CSCParseOption (string option, ref string [] args, ref int i)
908 int idx = option.IndexOf (':');
915 arg = option.Substring (0, idx);
917 value = option.Substring (idx + 1);
928 RootContext.Target = Target.Exe;
932 RootContext.Target = Target.WinExe;
936 RootContext.Target = Target.Library;
937 RootContext.TargetExt = ".dll";
941 RootContext.Target = Target.Module;
942 RootContext.TargetExt = ".netmodule";
947 Environment.Exit (1);
955 Environment.Exit (1);
957 SetOutputFile (value);
964 case "/incremental+":
965 case "/incremental-":
975 Environment.Exit (1);
978 defs = value.Split (new Char [] {';', ','});
979 foreach (string d in defs){
986 case "/linkresource":
988 Report.Error (5, arg + " requires an argument");
989 Environment.Exit (1);
991 if (resources == null)
992 resources = new ArrayList ();
994 resources.Add (value);
1002 Environment.Exit (1);
1004 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1006 ProcessStartInfo pi = new ProcessStartInfo ();
1007 pi.FileName = "pkg-config";
1008 pi.RedirectStandardOutput = true;
1009 pi.UseShellExecute = false;
1010 pi.Arguments = "--libs " + packages;
1013 p = Process.Start (pi);
1014 } catch (Exception e) {
1015 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1016 Environment.Exit (1);
1019 if (p.StandardOutput == null){
1020 Report.Warning (-27, "Specified package did not return any information");
1023 string pkgout = p.StandardOutput.ReadToEnd ();
1025 if (p.ExitCode != 0) {
1026 Report.Error (-27, "Error running pkg-config. Check the above output.");
1027 Environment.Exit (1);
1030 if (pkgout != null){
1031 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1032 Split (new Char [] { ' ', '\t'});
1033 args = AddArgs (args, xargs);
1043 Report.Error (5, "-resource requires an argument");
1044 Environment.Exit (1);
1046 if (embedded_resources == null)
1047 embedded_resources = new ArrayList ();
1049 if (embedded_resources.Contains (value)) {
1050 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1052 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1053 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1056 embedded_resources.Add (value);
1062 Report.Error (5, "-recurse requires an argument");
1063 Environment.Exit (1);
1065 CompileFiles (value, true);
1069 case "/reference": {
1071 Report.Error (5, "-reference requires an argument");
1072 Environment.Exit (1);
1075 string [] refs = value.Split (new char [] { ';', ',' });
1076 foreach (string r in refs){
1081 case "/addmodule": {
1083 Report.Error (5, arg + " requires an argument");
1084 Environment.Exit (1);
1087 string [] refs = value.Split (new char [] { ';', ',' });
1088 foreach (string r in refs){
1095 Report.Error (5, arg + " requires an argument");
1096 Environment.Exit (1);
1099 win32ResourceFile = value;
1102 case "/win32icon": {
1104 Report.Error (5, arg + " requires an argument");
1105 Environment.Exit (1);
1108 win32IconFile = value;
1113 Report.Error (5, arg + " requires an argument");
1114 Environment.Exit (1);
1116 // TODO handle the /doc argument to generate xml doc
1123 Report.Error (5, "/lib requires an argument");
1124 Environment.Exit (1);
1127 libdirs = value.Split (new Char [] { ',' });
1128 foreach (string dir in libdirs)
1129 link_paths.Add (dir);
1134 want_debugging_support = false;
1139 want_debugging_support = true;
1144 RootContext.Checked = true;
1148 RootContext.Checked = false;
1156 RootContext.VerifyClsCompliance = false;
1161 RootContext.Unsafe = true;
1165 RootContext.Unsafe = false;
1168 case "/warnaserror":
1169 case "/warnaserror+":
1170 Report.WarningsAreErrors = true;
1171 TestWarningConflict();
1174 case "/warnaserror-":
1175 Report.WarningsAreErrors = false;
1179 SetWarningLevel (value);
1186 Report.Error (5, "/nowarn requires an argument");
1187 Environment.Exit (1);
1190 warns = value.Split (new Char [] {','});
1191 foreach (string wc in warns){
1193 int warn = Int32.Parse (wc);
1195 throw new ArgumentOutOfRangeException("warn");
1197 Report.SetIgnoreWarning (warn);
1199 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1200 Environment.Exit (1);
1207 load_default_config = true;
1212 load_default_config = false;
1217 Environment.Exit(0);
1223 Environment.Exit (0);
1229 Report.Error (5, arg + " requires an argument");
1230 Environment.Exit (1);
1232 RootContext.MainClass = value;
1237 RootContext.StdLib = false;
1241 RootContext.StdLib = true;
1248 if (value == String.Empty) {
1249 Report.Error (5, arg + " requires an argument");
1250 Environment.Exit (1);
1252 RootContext.StrongNameKeyFile = value;
1254 case "/keycontainer":
1255 if (value == String.Empty) {
1256 Report.Error (5, arg + " requires an argument");
1257 Environment.Exit (1);
1259 RootContext.StrongNameKeyContainer = value;
1262 RootContext.StrongNameDelaySign = true;
1265 RootContext.StrongNameDelaySign = false;
1270 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1274 case "/langversion":
1275 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1277 RootContext.Version = LanguageVersion.ISO_1;
1284 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1285 Environment.Exit (1);
1291 if (value == "utf8"){
1292 encoding = new UTF8Encoding();
1293 using_default_encoder = false;
1296 if (value == "reset"){
1298 // 28591 is the code page for ISO-8859-1 encoding.
1301 using_default_encoder = true;
1305 cp = Int32.Parse (value);
1306 encoding = Encoding.GetEncoding (cp);
1307 using_default_encoder = false;
1309 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1310 Environment.Exit (1);
1314 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1315 //Environment.Exit (1);
1319 static string [] AddArgs (string [] args, string [] extra_args)
1323 new_args = new string [extra_args.Length + args.Length];
1324 args.CopyTo (new_args, 0);
1325 extra_args.CopyTo (new_args, args.Length);
1331 /// Parses the arguments, and drives the compilation
1336 /// TODO: Mostly structured to debug the compiler
1337 /// now, needs to be turned into a real driver soon.
1339 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1340 internal static bool MainDriver (string [] args)
1343 bool parsing_options = true;
1345 Console.WriteLine ("ALPHA SOFTWARE: Mono C# Compiler {0} for Generics",
1346 Assembly.GetExecutingAssembly ().GetName ().Version.ToString ());
1348 encoding = Encoding.GetEncoding (28591);
1350 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1351 encoding = Encoding.GetEncoding (1252);
1354 references = new ArrayList ();
1355 soft_references = new ArrayList ();
1356 modules = new ArrayList ();
1357 link_paths = new ArrayList ();
1359 SetupDefaultDefines ();
1364 // This is not required because Assembly.Load knows about this
1368 for (i = 0; i < args.Length; i++){
1369 string arg = args [i];
1373 if (arg.StartsWith ("@")){
1374 string [] extra_args;
1375 string response_file = arg.Substring (1);
1377 if (response_file_list == null)
1378 response_file_list = new Hashtable ();
1380 if (response_file_list.Contains (response_file)){
1382 1515, "Response file `" + response_file +
1383 "' specified multiple times");
1384 Environment.Exit (1);
1387 response_file_list.Add (response_file, response_file);
1389 extra_args = LoadArgs (response_file);
1390 if (extra_args == null){
1391 Report.Error (2011, "Unable to open response file: " +
1396 args = AddArgs (args, extra_args);
1400 if (parsing_options){
1402 parsing_options = false;
1406 if (arg.StartsWith ("-")){
1407 if (UnixParseOption (arg, ref args, ref i))
1411 string csc_opt = "/" + arg.Substring (1);
1412 if (CSCParseOption (csc_opt, ref args, ref i))
1415 if (arg.StartsWith ("/")){
1416 if (CSCParseOption (arg, ref args, ref i))
1422 CompileFiles (arg, false);
1431 // If we are an exe, require a source file for the entry point
1433 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1434 if (first_source == null){
1435 Report.Error (2008, "No files to compile were specified");
1442 // If there is nothing to put in the assembly, and we are not a library
1444 if (first_source == null && embedded_resources == null && resources == null){
1445 Report.Error (2008, "No files to compile were specified");
1449 if (Report.Errors > 0)
1455 Tokenizer.Cleanup ();
1458 // Load Core Library for default compilation
1460 if (RootContext.StdLib)
1461 references.Insert (0, "mscorlib");
1463 if (load_default_config)
1464 DefineDefaultConfig ();
1466 if (Report.Errors > 0){
1471 // Load assemblies required
1474 ShowTime ("Loading references");
1475 link_paths.Add (GetSystemDir ());
1476 link_paths.Add (Directory.GetCurrentDirectory ());
1480 ShowTime (" References loaded");
1482 if (Report.Errors > 0){
1489 if (output_file == null){
1490 int pos = first_source.LastIndexOf ('.');
1493 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1495 output_file = first_source + RootContext.TargetExt;
1498 CodeGen.Init (output_file, output_file, want_debugging_support);
1500 if (RootContext.Target == Target.Module) {
1501 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1502 if (module_only == null) {
1503 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1504 Environment.Exit (1);
1507 MethodInfo set_method = module_only.GetSetMethod (true);
1508 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1511 TypeManager.AddModule (CodeGen.Module.Builder);
1513 if (modules.Count > 0) {
1514 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1515 if (adder_method == null) {
1516 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1517 Environment.Exit (1);
1520 foreach (string module in modules)
1521 LoadModule (adder_method, module);
1524 TypeManager.ComputeNamespaces ();
1527 // Before emitting, we need to get the core
1528 // types emitted from the user defined types
1529 // or from the system ones.
1532 ShowTime ("Initializing Core Types");
1533 if (!RootContext.StdLib){
1534 RootContext.ResolveCore ();
1535 if (Report.Errors > 0)
1539 TypeManager.InitCoreTypes ();
1541 ShowTime (" Core Types done");
1544 // The second pass of the compiler
1547 ShowTime ("Resolving tree");
1548 RootContext.ResolveTree ();
1549 if (Report.Errors > 0)
1552 ShowTime ("Populate tree");
1553 if (!RootContext.StdLib)
1554 RootContext.BootCorlib_PopulateCoreTypes ();
1555 RootContext.PopulateTypes ();
1556 RootContext.DefineTypes ();
1558 TypeManager.InitCodeHelpers ();
1561 // Verify using aliases now
1563 Namespace.VerifyUsing ();
1565 if (Report.Errors > 0){
1569 if (RootContext.VerifyClsCompliance) {
1570 CodeGen.Assembly.ResolveClsCompliance ();
1571 if (CodeGen.Assembly.IsClsCompliant) {
1572 AttributeTester.VerifyModulesClsCompliance ();
1573 TypeManager.LoadAllImportedTypes ();
1574 AttributeTester.VerifyTopLevelNameClsCompliance ();
1579 // The code generator
1582 ShowTime ("Emitting code");
1583 ShowTotalTime ("Total so far");
1584 RootContext.EmitCode ();
1588 if (Report.Errors > 0){
1593 ShowTime ("Closing types");
1595 RootContext.CloseTypes ();
1597 PEFileKinds k = PEFileKinds.ConsoleApplication;
1599 switch (RootContext.Target) {
1600 case Target.Library:
1602 k = PEFileKinds.Dll; break;
1604 k = PEFileKinds.ConsoleApplication; break;
1606 k = PEFileKinds.WindowApplication; break;
1609 if (RootContext.NeedsEntryPoint) {
1610 MethodInfo ep = RootContext.EntryPoint;
1613 if (RootContext.MainClass != null) {
1614 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1615 if (main_cont == null) {
1616 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1620 if (!(main_cont is ClassOrStruct)) {
1621 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1626 if (Report.Errors == 0)
1627 Report.Error (5001, "Program " + output_file +
1628 " does not have an entry point defined");
1632 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1633 } else if (RootContext.MainClass != null) {
1634 Report.Error (2017, "Can not specify -main: when building module or library");
1638 // Add the resources
1640 if (resources != null){
1641 foreach (string spec in resources){
1645 cp = spec.IndexOf (',');
1647 file = spec.Substring (0, cp);
1648 res = spec.Substring (cp + 1);
1652 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1656 if (embedded_resources != null){
1657 object[] margs = new object [2];
1658 Type[] argst = new Type [2];
1659 argst [0] = argst [1] = typeof (string);
1661 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1662 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1663 null, CallingConventions.Any, argst, null);
1665 if (embed_res == null) {
1666 Report.Warning (0, new Location (-1),
1667 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1669 foreach (string spec in embedded_resources) {
1672 cp = spec.IndexOf (',');
1674 margs [0] = spec.Substring (cp + 1);
1675 margs [1] = spec.Substring (0, cp);
1678 margs [0] = Path.GetFileName (spec);
1681 if (File.Exists ((string) margs [1]))
1682 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1684 Report.Error (1566, "Can not find the resource " + margs [1]);
1691 // Add Win32 resources
1694 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1696 if (win32ResourceFile != null) {
1698 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1700 catch (ArgumentException) {
1701 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1705 if (win32IconFile != null) {
1706 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1707 if (define_icon == null) {
1708 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1710 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1713 if (Report.Errors > 0)
1716 CodeGen.Save (output_file);
1718 ShowTime ("Saved output");
1719 ShowTotalTime ("Total");
1722 Timer.ShowTimers ();
1724 if (Report.ExpectedError != 0){
1725 if (Report.Errors == 0) {
1726 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1727 "No other errors reported.");
1729 Environment.Exit (2);
1731 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1732 "However, other errors were reported.");
1734 Environment.Exit (1);
1742 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1743 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1745 return (Report.Errors == 0);
1751 // This is the only public entry point
1753 public class CompilerCallableEntryPoint : MarshalByRefObject {
1754 static bool used = false;
1756 public bool InvokeCompiler (string [] args)
1760 bool ok = Driver.MainDriver (args);
1761 return ok && Report.Errors == 0;
1764 public void Reset ()