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 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.Diagnostics;
21 using System.Globalization;
23 using System.Diagnostics;
26 Library, Exe, Module, WinExe
30 /// The compiler driver.
36 // Assemblies references to be linked. Initialized with
38 static ArrayList references;
41 // If any of these fail, we ignore the problem. This is so
42 // that we can list all the assemblies in Windows and not fail
43 // if they are missing on Linux.
45 static ArrayList soft_references;
48 // Modules to be linked
50 static ArrayList modules;
53 static ArrayList link_paths;
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 " -doc:XMLFILE Generates xml documentation into specified 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 = {
576 "Microsoft.VisualBasic",
579 // Is it worth pre-loading all this stuff?
582 "System.Configuration.Install",
585 "System.DirectoryServices",
586 "System.Drawing.Design",
588 "System.EnterpriseServices",
591 "System.Runtime.Remoting",
592 "System.Runtime.Serialization.Formatters.Soap",
594 "System.ServiceProcess",
596 "System.Web.RegularExpressions",
597 "System.Web.Services",
598 "System.Windows.Forms"
603 foreach (string def in default_config)
604 soft_references.Insert (p++, def);
607 static void SetOutputFile (string name)
612 static void SetWarningLevel (string s)
617 level = Int32.Parse (s);
621 "--wlevel requires a value from 0 to 4");
622 Environment.Exit (1);
624 if (level < 0 || level > 4){
625 Report.Error (1900, "Warning level must be 0 to 4");
626 Environment.Exit (1);
628 RootContext.WarningLevel = level;
629 TestWarningConflict ();
632 static void TestWarningConflict ()
634 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
635 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
636 Environment.Exit (1);
640 static void SetupV2 ()
642 RootContext.Version = LanguageVersion.Default;
643 defines.Add ("__V2__");
646 static void Version ()
648 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
649 Console.WriteLine ("Mono C# compiler version {0}", version);
650 Environment.Exit (0);
654 // Currently handles the Unix-like command line options, but will be
655 // deprecated in favor of the CSCParseOption, which will also handle the
656 // options that start with a dash in the future.
658 static bool UnixParseOption (string arg, ref string [] args, ref int i)
662 CSharpParser.yacc_verbose_flag++;
673 case "--main": case "-m":
674 if ((i + 1) >= args.Length){
676 Environment.Exit (1);
678 RootContext.MainClass = args [++i];
682 RootContext.Unsafe = true;
685 case "/?": case "/h": case "/help":
688 Environment.Exit (0);
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 if ((i + 1) >= args.Length){
724 Environment.Exit (1);
726 SetOutputFile (args [++i]);
730 RootContext.Checked = true;
734 Report.Stacktrace = true;
737 case "--linkresource":
739 if ((i + 1) >= args.Length){
741 Report.Error (5, "Missing argument to --linkres");
742 Environment.Exit (1);
744 if (resources == null)
745 resources = new ArrayList ();
747 resources.Add (args [++i]);
752 if ((i + 1) >= args.Length){
754 Report.Error (5, "Missing argument to --resource");
755 Environment.Exit (1);
757 if (embedded_resources == null)
758 embedded_resources = new ArrayList ();
760 embedded_resources.Add (args [++i]);
764 if ((i + 1) >= args.Length){
765 Environment.Exit (1);
769 string type = args [++i];
772 RootContext.Target = Target.Library;
773 RootContext.TargetExt = ".dll";
777 RootContext.Target = Target.Exe;
781 RootContext.Target = Target.WinExe;
785 RootContext.Target = Target.Module;
786 RootContext.TargetExt = ".dll";
790 Environment.Exit (1);
796 if ((i + 1) >= args.Length){
798 Environment.Exit (1);
801 references.Add (args [++i]);
805 if ((i + 1) >= args.Length){
807 Environment.Exit (1);
809 link_paths.Add (args [++i]);
813 RootContext.StdLib = false;
821 Report.WarningsAreErrors = true;
822 TestWarningConflict();
826 if ((i + 1) >= args.Length){
828 Environment.Exit (1);
833 warn = Int32.Parse (args [++i]);
836 Environment.Exit (1);
838 Report.SetIgnoreWarning (warn);
842 if ((i + 1) >= args.Length){
845 "--wlevel requires a value from 0 to 4");
846 Environment.Exit (1);
849 SetWarningLevel (args [++i]);
853 if ((i + 1) >= args.Length){
854 Report.Error (5, "--mcs-debug requires an argument");
855 Environment.Exit (1);
859 Report.DebugFlags = Int32.Parse (args [++i]);
861 Report.Error (5, "Invalid argument to --mcs-debug");
862 Environment.Exit (1);
871 if ((i + 1) >= args.Length){
872 Report.Error (5, "--recurse requires an argument");
873 Environment.Exit (1);
875 CompileFiles (args [++i], true);
880 last_time = first_time = DateTime.Now;
887 case "--debug": case "-g":
888 want_debugging_support = true;
892 load_default_config = false;
900 // Currently it is very basic option parsing, but eventually, this will
901 // be the complete option parser
903 static bool CSCParseOption (string option, ref string [] args, ref int i)
905 int idx = option.IndexOf (':');
912 arg = option.Substring (0, idx);
914 value = option.Substring (idx + 1);
925 RootContext.Target = Target.Exe;
929 RootContext.Target = Target.WinExe;
933 RootContext.Target = Target.Library;
934 RootContext.TargetExt = ".dll";
938 RootContext.Target = Target.Module;
939 RootContext.TargetExt = ".netmodule";
944 Environment.Exit (1);
952 Environment.Exit (1);
954 SetOutputFile (value);
961 case "/incremental+":
962 case "/incremental-":
972 Environment.Exit (1);
975 defs = value.Split (new Char [] {';', ','});
976 foreach (string d in defs){
983 case "/linkresource":
985 Report.Error (5, arg + " requires an argument");
986 Environment.Exit (1);
988 if (resources == null)
989 resources = new ArrayList ();
991 resources.Add (value);
999 Environment.Exit (1);
1001 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1003 ProcessStartInfo pi = new ProcessStartInfo ();
1004 pi.FileName = "pkg-config";
1005 pi.RedirectStandardOutput = true;
1006 pi.UseShellExecute = false;
1007 pi.Arguments = "--libs " + packages;
1010 p = Process.Start (pi);
1011 } catch (Exception e) {
1012 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1013 Environment.Exit (1);
1016 if (p.StandardOutput == null){
1017 Report.Warning (-27, "Specified package did not return any information");
1020 string pkgout = p.StandardOutput.ReadToEnd ();
1022 if (p.ExitCode != 0) {
1023 Report.Error (-27, "Error running pkg-config. Check the above output.");
1024 Environment.Exit (1);
1027 if (pkgout != null){
1028 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1029 Split (new Char [] { ' ', '\t'});
1030 args = AddArgs (args, xargs);
1040 Report.Error (5, "-resource requires an argument");
1041 Environment.Exit (1);
1043 if (embedded_resources == null)
1044 embedded_resources = new ArrayList ();
1046 if (embedded_resources.Contains (value)) {
1047 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1049 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1050 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1053 embedded_resources.Add (value);
1059 Report.Error (5, "-recurse requires an argument");
1060 Environment.Exit (1);
1062 CompileFiles (value, true);
1066 case "/reference": {
1068 Report.Error (5, "-reference requires an argument");
1069 Environment.Exit (1);
1072 string [] refs = value.Split (new char [] { ';', ',' });
1073 foreach (string r in refs){
1078 case "/addmodule": {
1080 Report.Error (5, arg + " requires an argument");
1081 Environment.Exit (1);
1084 string [] refs = value.Split (new char [] { ';', ',' });
1085 foreach (string r in refs){
1092 Report.Error (5, arg + " requires an argument");
1093 Environment.Exit (1);
1096 win32ResourceFile = value;
1099 case "/win32icon": {
1101 Report.Error (5, arg + " requires an argument");
1102 Environment.Exit (1);
1105 win32IconFile = value;
1110 Report.Error (2006, arg + " requires an argument");
1111 Environment.Exit (1);
1113 RootContext.Documentation = new Documentation (value);
1120 Report.Error (5, "/lib requires an argument");
1121 Environment.Exit (1);
1124 libdirs = value.Split (new Char [] { ',' });
1125 foreach (string dir in libdirs)
1126 link_paths.Add (dir);
1131 want_debugging_support = false;
1136 want_debugging_support = true;
1141 RootContext.Checked = true;
1145 RootContext.Checked = false;
1153 RootContext.VerifyClsCompliance = false;
1158 RootContext.Unsafe = true;
1162 RootContext.Unsafe = false;
1165 case "/warnaserror":
1166 case "/warnaserror+":
1167 Report.WarningsAreErrors = true;
1168 TestWarningConflict();
1171 case "/warnaserror-":
1172 Report.WarningsAreErrors = false;
1176 SetWarningLevel (value);
1183 Report.Error (5, "/nowarn requires an argument");
1184 Environment.Exit (1);
1187 warns = value.Split (new Char [] {','});
1188 foreach (string wc in warns){
1190 int warn = Int32.Parse (wc);
1192 throw new ArgumentOutOfRangeException("warn");
1194 Report.SetIgnoreWarning (warn);
1196 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1197 Environment.Exit (1);
1204 load_default_config = true;
1209 load_default_config = false;
1214 Environment.Exit(0);
1220 Environment.Exit (0);
1226 Report.Error (5, arg + " requires an argument");
1227 Environment.Exit (1);
1229 RootContext.MainClass = value;
1234 RootContext.StdLib = false;
1238 RootContext.StdLib = true;
1245 if (value == String.Empty) {
1246 Report.Error (5, arg + " requires an argument");
1247 Environment.Exit (1);
1249 RootContext.StrongNameKeyFile = value;
1251 case "/keycontainer":
1252 if (value == String.Empty) {
1253 Report.Error (5, arg + " requires an argument");
1254 Environment.Exit (1);
1256 RootContext.StrongNameKeyContainer = value;
1259 RootContext.StrongNameDelaySign = true;
1262 RootContext.StrongNameDelaySign = false;
1267 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1271 case "/langversion":
1272 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1274 RootContext.Version = LanguageVersion.ISO_1;
1281 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1282 Environment.Exit (1);
1288 if (value == "utf8"){
1289 encoding = new UTF8Encoding();
1290 using_default_encoder = false;
1293 if (value == "reset"){
1295 // 28591 is the code page for ISO-8859-1 encoding.
1298 using_default_encoder = true;
1302 cp = Int32.Parse (value);
1303 encoding = Encoding.GetEncoding (cp);
1304 using_default_encoder = false;
1306 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1307 Environment.Exit (1);
1311 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1312 //Environment.Exit (1);
1316 static string [] AddArgs (string [] args, string [] extra_args)
1320 new_args = new string [extra_args.Length + args.Length];
1321 args.CopyTo (new_args, 0);
1322 extra_args.CopyTo (new_args, args.Length);
1328 /// Parses the arguments, and drives the compilation
1333 /// TODO: Mostly structured to debug the compiler
1334 /// now, needs to be turned into a real driver soon.
1336 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1337 internal static bool MainDriver (string [] args)
1340 bool parsing_options = true;
1343 encoding = Encoding.GetEncoding (28591);
1345 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1346 encoding = Encoding.GetEncoding (1252);
1349 references = new ArrayList ();
1350 soft_references = new ArrayList ();
1351 modules = new ArrayList ();
1352 link_paths = new ArrayList ();
1354 SetupDefaultDefines ();
1359 // This is not required because Assembly.Load knows about this
1363 for (i = 0; i < args.Length; i++){
1364 string arg = args [i];
1368 if (arg.StartsWith ("@")){
1369 string [] extra_args;
1370 string response_file = arg.Substring (1);
1372 if (response_file_list == null)
1373 response_file_list = new Hashtable ();
1375 if (response_file_list.Contains (response_file)){
1377 1515, "Response file `" + response_file +
1378 "' specified multiple times");
1379 Environment.Exit (1);
1382 response_file_list.Add (response_file, response_file);
1384 extra_args = LoadArgs (response_file);
1385 if (extra_args == null){
1386 Report.Error (2011, "Unable to open response file: " +
1391 args = AddArgs (args, extra_args);
1395 if (parsing_options){
1397 parsing_options = false;
1401 if (arg.StartsWith ("-")){
1402 if (UnixParseOption (arg, ref args, ref i))
1406 string csc_opt = "/" + arg.Substring (1);
1407 if (CSCParseOption (csc_opt, ref args, ref i))
1410 if (arg.StartsWith ("/")){
1411 if (CSCParseOption (arg, ref args, ref i))
1417 CompileFiles (arg, false);
1426 // If we are an exe, require a source file for the entry point
1428 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1429 if (first_source == null){
1430 Report.Error (2008, "No files to compile were specified");
1437 // If there is nothing to put in the assembly, and we are not a library
1439 if (first_source == null && embedded_resources == null && resources == null){
1440 Report.Error (2008, "No files to compile were specified");
1444 if (Report.Errors > 0)
1450 Tokenizer.Cleanup ();
1453 // Load Core Library for default compilation
1455 if (RootContext.StdLib)
1456 references.Insert (0, "mscorlib");
1458 if (load_default_config)
1459 DefineDefaultConfig ();
1461 if (Report.Errors > 0){
1466 // Load assemblies required
1469 ShowTime ("Loading references");
1470 link_paths.Add (GetSystemDir ());
1471 link_paths.Add (Directory.GetCurrentDirectory ());
1475 ShowTime (" References loaded");
1477 if (Report.Errors > 0){
1484 if (output_file == null){
1485 int pos = first_source.LastIndexOf ('.');
1488 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1490 output_file = first_source + RootContext.TargetExt;
1493 CodeGen.Init (output_file, output_file, want_debugging_support);
1495 if (RootContext.Target == Target.Module) {
1496 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1497 if (module_only == null) {
1498 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1499 Environment.Exit (1);
1502 MethodInfo set_method = module_only.GetSetMethod (true);
1503 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1506 TypeManager.AddModule (CodeGen.Module.Builder);
1508 if (modules.Count > 0) {
1509 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1510 if (adder_method == null) {
1511 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1512 Environment.Exit (1);
1515 foreach (string module in modules)
1516 LoadModule (adder_method, module);
1519 TypeManager.ComputeNamespaces ();
1522 // Before emitting, we need to get the core
1523 // types emitted from the user defined types
1524 // or from the system ones.
1527 ShowTime ("Initializing Core Types");
1528 if (!RootContext.StdLib){
1529 RootContext.ResolveCore ();
1530 if (Report.Errors > 0)
1534 TypeManager.InitCoreTypes ();
1536 ShowTime (" Core Types done");
1539 // The second pass of the compiler
1542 ShowTime ("Resolving tree");
1543 RootContext.ResolveTree ();
1545 if (Report.Errors > 0)
1548 ShowTime ("Populate tree");
1549 if (!RootContext.StdLib)
1550 RootContext.BootCorlib_PopulateCoreTypes ();
1551 RootContext.PopulateTypes ();
1552 RootContext.DefineTypes ();
1554 if (RootContext.Documentation != null &&
1555 !RootContext.Documentation.OutputDocComment (
1559 TypeManager.InitCodeHelpers ();
1562 // Verify using aliases now
1564 Namespace.VerifyUsing ();
1566 if (Report.Errors > 0){
1570 if (RootContext.VerifyClsCompliance) {
1571 CodeGen.Assembly.ResolveClsCompliance ();
1572 if (CodeGen.Assembly.IsClsCompliant) {
1573 AttributeTester.VerifyModulesClsCompliance ();
1574 TypeManager.LoadAllImportedTypes ();
1575 AttributeTester.VerifyTopLevelNameClsCompliance ();
1580 // The code generator
1583 ShowTime ("Emitting code");
1584 ShowTotalTime ("Total so far");
1585 RootContext.EmitCode ();
1589 if (Report.Errors > 0){
1594 ShowTime ("Closing types");
1596 RootContext.CloseTypes ();
1598 PEFileKinds k = PEFileKinds.ConsoleApplication;
1600 switch (RootContext.Target) {
1601 case Target.Library:
1603 k = PEFileKinds.Dll; break;
1605 k = PEFileKinds.ConsoleApplication; break;
1607 k = PEFileKinds.WindowApplication; break;
1610 if (RootContext.NeedsEntryPoint) {
1611 MethodInfo ep = RootContext.EntryPoint;
1614 if (RootContext.MainClass != null) {
1615 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1616 if (main_cont == null) {
1617 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1621 if (!(main_cont is ClassOrStruct)) {
1622 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1627 if (Report.Errors == 0)
1628 Report.Error (5001, "Program " + output_file +
1629 " does not have an entry point defined");
1633 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1634 } else if (RootContext.MainClass != null) {
1635 Report.Error (2017, "Can not specify -main: when building module or library");
1639 // Add the resources
1641 if (resources != null){
1642 foreach (string spec in resources){
1646 cp = spec.IndexOf (',');
1648 file = spec.Substring (0, cp);
1649 res = spec.Substring (cp + 1);
1653 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1657 if (embedded_resources != null){
1658 object[] margs = new object [2];
1659 Type[] argst = new Type [2];
1660 argst [0] = argst [1] = typeof (string);
1662 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1663 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1664 null, CallingConventions.Any, argst, null);
1666 if (embed_res == null) {
1667 Report.Warning (0, new Location (-1),
1668 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1670 foreach (string spec in embedded_resources) {
1673 cp = spec.IndexOf (',');
1675 margs [0] = spec.Substring (cp + 1);
1676 margs [1] = spec.Substring (0, cp);
1679 margs [0] = Path.GetFileName (spec);
1682 if (File.Exists ((string) margs [1]))
1683 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1685 Report.Error (1566, "Can not find the resource " + margs [1]);
1692 // Add Win32 resources
1695 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1697 if (win32ResourceFile != null) {
1699 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1701 catch (ArgumentException) {
1702 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1706 if (win32IconFile != null) {
1707 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1708 if (define_icon == null) {
1709 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1711 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1714 if (Report.Errors > 0)
1717 CodeGen.Save (output_file);
1719 ShowTime ("Saved output");
1720 ShowTotalTime ("Total");
1723 Timer.ShowTimers ();
1725 if (Report.ExpectedError != 0){
1726 if (Report.Errors == 0) {
1727 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1728 "No other errors reported.");
1730 Environment.Exit (2);
1732 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1733 "However, other errors were reported.");
1735 Environment.Exit (1);
1743 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1744 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1746 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 ()