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 = {
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 CSharpParser.yacc_verbose_flag++;
672 case "--main": case "-m":
673 if ((i + 1) >= args.Length){
675 Environment.Exit (1);
677 RootContext.MainClass = args [++i];
681 RootContext.Unsafe = true;
684 case "/?": case "/h": case "/help":
687 Environment.Exit (0);
691 if ((i + 1) >= args.Length){
693 Environment.Exit (1);
695 defines.Add (args [++i]);
698 case "--show-counters":
699 show_counters = true;
702 case "--expect-error": {
707 args [++i], NumberStyles.AllowLeadingSign);
708 Report.ExpectedError = code;
710 Report.Error (-14, "Invalid number specified");
721 if ((i + 1) >= args.Length){
723 Environment.Exit (1);
725 SetOutputFile (args [++i]);
729 RootContext.Checked = true;
733 Report.Stacktrace = true;
736 case "--linkresource":
738 if ((i + 1) >= args.Length){
740 Report.Error (5, "Missing argument to --linkres");
741 Environment.Exit (1);
743 if (resources == null)
744 resources = new ArrayList ();
746 resources.Add (args [++i]);
751 if ((i + 1) >= args.Length){
753 Report.Error (5, "Missing argument to --resource");
754 Environment.Exit (1);
756 if (embedded_resources == null)
757 embedded_resources = new ArrayList ();
759 embedded_resources.Add (args [++i]);
763 if ((i + 1) >= args.Length){
764 Environment.Exit (1);
768 string type = args [++i];
771 RootContext.Target = Target.Library;
772 RootContext.TargetExt = ".dll";
776 RootContext.Target = Target.Exe;
780 RootContext.Target = Target.WinExe;
784 RootContext.Target = Target.Module;
785 RootContext.TargetExt = ".dll";
789 Environment.Exit (1);
795 if ((i + 1) >= args.Length){
797 Environment.Exit (1);
800 references.Add (args [++i]);
804 if ((i + 1) >= args.Length){
806 Environment.Exit (1);
808 link_paths.Add (args [++i]);
812 RootContext.StdLib = false;
820 Report.WarningsAreErrors = true;
821 TestWarningConflict();
825 if ((i + 1) >= args.Length){
827 Environment.Exit (1);
832 warn = Int32.Parse (args [++i]);
835 Environment.Exit (1);
837 Report.SetIgnoreWarning (warn);
841 if ((i + 1) >= args.Length){
844 "--wlevel requires a value from 0 to 4");
845 Environment.Exit (1);
848 SetWarningLevel (args [++i]);
852 if ((i + 1) >= args.Length){
853 Report.Error (5, "--mcs-debug requires an argument");
854 Environment.Exit (1);
858 Report.DebugFlags = Int32.Parse (args [++i]);
860 Report.Error (5, "Invalid argument to --mcs-debug");
861 Environment.Exit (1);
870 if ((i + 1) >= args.Length){
871 Report.Error (5, "--recurse requires an argument");
872 Environment.Exit (1);
874 CompileFiles (args [++i], true);
879 last_time = first_time = DateTime.Now;
886 case "--debug": case "-g":
887 want_debugging_support = true;
891 load_default_config = false;
899 // Currently it is very basic option parsing, but eventually, this will
900 // be the complete option parser
902 static bool CSCParseOption (string option, ref string [] args, ref int i)
904 int idx = option.IndexOf (':');
911 arg = option.Substring (0, idx);
913 value = option.Substring (idx + 1);
924 RootContext.Target = Target.Exe;
928 RootContext.Target = Target.WinExe;
932 RootContext.Target = Target.Library;
933 RootContext.TargetExt = ".dll";
937 RootContext.Target = Target.Module;
938 RootContext.TargetExt = ".netmodule";
943 Environment.Exit (1);
951 Environment.Exit (1);
953 SetOutputFile (value);
960 case "/incremental+":
961 case "/incremental-":
971 Environment.Exit (1);
974 defs = value.Split (new Char [] {';', ','});
975 foreach (string d in defs){
982 case "/linkresource":
984 Report.Error (5, arg + " requires an argument");
985 Environment.Exit (1);
987 if (resources == null)
988 resources = new ArrayList ();
990 resources.Add (value);
998 Environment.Exit (1);
1000 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1002 ProcessStartInfo pi = new ProcessStartInfo ();
1003 pi.FileName = "pkg-config";
1004 pi.RedirectStandardOutput = true;
1005 pi.UseShellExecute = false;
1006 pi.Arguments = "--libs " + packages;
1009 p = Process.Start (pi);
1010 } catch (Exception e) {
1011 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1012 Environment.Exit (1);
1015 if (p.StandardOutput == null){
1016 Report.Warning (-27, "Specified package did not return any information");
1019 string pkgout = p.StandardOutput.ReadToEnd ();
1021 if (p.ExitCode != 0) {
1022 Report.Error (-27, "Error running pkg-config. Check the above output.");
1023 Environment.Exit (1);
1026 if (pkgout != null){
1027 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1028 Split (new Char [] { ' ', '\t'});
1029 args = AddArgs (args, xargs);
1039 Report.Error (5, "-resource requires an argument");
1040 Environment.Exit (1);
1042 if (embedded_resources == null)
1043 embedded_resources = new ArrayList ();
1045 if (embedded_resources.Contains (value)) {
1046 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1048 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1049 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1052 embedded_resources.Add (value);
1058 Report.Error (5, "-recurse requires an argument");
1059 Environment.Exit (1);
1061 CompileFiles (value, true);
1065 case "/reference": {
1067 Report.Error (5, "-reference requires an argument");
1068 Environment.Exit (1);
1071 string [] refs = value.Split (new char [] { ';', ',' });
1072 foreach (string r in refs){
1077 case "/addmodule": {
1079 Report.Error (5, arg + " requires an argument");
1080 Environment.Exit (1);
1083 string [] refs = value.Split (new char [] { ';', ',' });
1084 foreach (string r in refs){
1091 Report.Error (5, arg + " requires an argument");
1092 Environment.Exit (1);
1095 win32ResourceFile = value;
1098 case "/win32icon": {
1100 Report.Error (5, arg + " requires an argument");
1101 Environment.Exit (1);
1104 win32IconFile = value;
1109 Report.Error (2006, arg + " requires an argument");
1110 Environment.Exit (1);
1112 RootContext.Documentation = new Documentation (value);
1119 Report.Error (5, "/lib requires an argument");
1120 Environment.Exit (1);
1123 libdirs = value.Split (new Char [] { ',' });
1124 foreach (string dir in libdirs)
1125 link_paths.Add (dir);
1130 want_debugging_support = false;
1135 want_debugging_support = true;
1140 RootContext.Checked = true;
1144 RootContext.Checked = false;
1152 RootContext.VerifyClsCompliance = false;
1157 RootContext.Unsafe = true;
1161 RootContext.Unsafe = false;
1164 case "/warnaserror":
1165 case "/warnaserror+":
1166 Report.WarningsAreErrors = true;
1167 TestWarningConflict();
1170 case "/warnaserror-":
1171 Report.WarningsAreErrors = false;
1175 SetWarningLevel (value);
1182 Report.Error (5, "/nowarn requires an argument");
1183 Environment.Exit (1);
1186 warns = value.Split (new Char [] {','});
1187 foreach (string wc in warns){
1189 int warn = Int32.Parse (wc);
1191 throw new ArgumentOutOfRangeException("warn");
1193 Report.SetIgnoreWarning (warn);
1195 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1196 Environment.Exit (1);
1203 load_default_config = true;
1208 load_default_config = false;
1213 Environment.Exit(0);
1219 Environment.Exit (0);
1225 Report.Error (5, arg + " requires an argument");
1226 Environment.Exit (1);
1228 RootContext.MainClass = value;
1233 RootContext.StdLib = false;
1237 RootContext.StdLib = true;
1244 if (value == String.Empty) {
1245 Report.Error (5, arg + " requires an argument");
1246 Environment.Exit (1);
1248 RootContext.StrongNameKeyFile = value;
1250 case "/keycontainer":
1251 if (value == String.Empty) {
1252 Report.Error (5, arg + " requires an argument");
1253 Environment.Exit (1);
1255 RootContext.StrongNameKeyContainer = value;
1258 RootContext.StrongNameDelaySign = true;
1261 RootContext.StrongNameDelaySign = false;
1266 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1270 case "/langversion":
1271 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1273 RootContext.Version = LanguageVersion.ISO_1;
1280 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1281 Environment.Exit (1);
1287 if (value == "utf8"){
1288 encoding = new UTF8Encoding();
1289 using_default_encoder = false;
1292 if (value == "reset"){
1294 // 28591 is the code page for ISO-8859-1 encoding.
1297 using_default_encoder = true;
1301 cp = Int32.Parse (value);
1302 encoding = Encoding.GetEncoding (cp);
1303 using_default_encoder = false;
1305 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1306 Environment.Exit (1);
1310 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1311 //Environment.Exit (1);
1315 static string [] AddArgs (string [] args, string [] extra_args)
1319 new_args = new string [extra_args.Length + args.Length];
1320 args.CopyTo (new_args, 0);
1321 extra_args.CopyTo (new_args, args.Length);
1327 /// Parses the arguments, and drives the compilation
1332 /// TODO: Mostly structured to debug the compiler
1333 /// now, needs to be turned into a real driver soon.
1335 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1336 internal static bool MainDriver (string [] args)
1339 bool parsing_options = true;
1341 Console.WriteLine ("ALPHA SOFTWARE: Mono C# Compiler {0} for Generics",
1342 Assembly.GetExecutingAssembly ().GetName ().Version.ToString ());
1344 encoding = Encoding.GetEncoding (28591);
1346 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1347 encoding = Encoding.GetEncoding (1252);
1350 references = new ArrayList ();
1351 soft_references = new ArrayList ();
1352 modules = new ArrayList ();
1353 link_paths = new ArrayList ();
1355 SetupDefaultDefines ();
1360 // This is not required because Assembly.Load knows about this
1364 for (i = 0; i < args.Length; i++){
1365 string arg = args [i];
1369 if (arg.StartsWith ("@")){
1370 string [] extra_args;
1371 string response_file = arg.Substring (1);
1373 if (response_file_list == null)
1374 response_file_list = new Hashtable ();
1376 if (response_file_list.Contains (response_file)){
1378 1515, "Response file `" + response_file +
1379 "' specified multiple times");
1380 Environment.Exit (1);
1383 response_file_list.Add (response_file, response_file);
1385 extra_args = LoadArgs (response_file);
1386 if (extra_args == null){
1387 Report.Error (2011, "Unable to open response file: " +
1392 args = AddArgs (args, extra_args);
1396 if (parsing_options){
1398 parsing_options = false;
1402 if (arg.StartsWith ("-")){
1403 if (UnixParseOption (arg, ref args, ref i))
1407 string csc_opt = "/" + arg.Substring (1);
1408 if (CSCParseOption (csc_opt, ref args, ref i))
1411 if (arg.StartsWith ("/")){
1412 if (CSCParseOption (arg, ref args, ref i))
1418 CompileFiles (arg, false);
1427 // If we are an exe, require a source file for the entry point
1429 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1430 if (first_source == null){
1431 Report.Error (2008, "No files to compile were specified");
1438 // If there is nothing to put in the assembly, and we are not a library
1440 if (first_source == null && embedded_resources == null && resources == null){
1441 Report.Error (2008, "No files to compile were specified");
1445 if (Report.Errors > 0)
1451 Tokenizer.Cleanup ();
1454 // Load Core Library for default compilation
1456 if (RootContext.StdLib)
1457 references.Insert (0, "mscorlib");
1459 if (load_default_config)
1460 DefineDefaultConfig ();
1462 if (Report.Errors > 0){
1467 // Load assemblies required
1470 ShowTime ("Loading references");
1471 link_paths.Add (GetSystemDir ());
1472 link_paths.Add (Directory.GetCurrentDirectory ());
1476 ShowTime (" References loaded");
1478 if (Report.Errors > 0){
1485 if (output_file == null){
1486 int pos = first_source.LastIndexOf ('.');
1489 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1491 output_file = first_source + RootContext.TargetExt;
1494 CodeGen.Init (output_file, output_file, want_debugging_support);
1496 if (RootContext.Target == Target.Module) {
1497 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1498 if (module_only == null) {
1499 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1500 Environment.Exit (1);
1503 MethodInfo set_method = module_only.GetSetMethod (true);
1504 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1507 TypeManager.AddModule (CodeGen.Module.Builder);
1509 if (modules.Count > 0) {
1510 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1511 if (adder_method == null) {
1512 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1513 Environment.Exit (1);
1516 foreach (string module in modules)
1517 LoadModule (adder_method, module);
1520 TypeManager.ComputeNamespaces ();
1523 // Before emitting, we need to get the core
1524 // types emitted from the user defined types
1525 // or from the system ones.
1528 ShowTime ("Initializing Core Types");
1529 if (!RootContext.StdLib){
1530 RootContext.ResolveCore ();
1531 if (Report.Errors > 0)
1535 TypeManager.InitCoreTypes ();
1537 ShowTime (" Core Types done");
1540 // The second pass of the compiler
1543 ShowTime ("Resolving tree");
1544 RootContext.ResolveTree ();
1546 if (Report.Errors > 0)
1549 ShowTime ("Populate tree");
1550 if (!RootContext.StdLib)
1551 RootContext.BootCorlib_PopulateCoreTypes ();
1552 RootContext.PopulateTypes ();
1553 RootContext.DefineTypes ();
1555 if (RootContext.Documentation != null &&
1556 !RootContext.Documentation.OutputDocComment (
1560 TypeManager.InitCodeHelpers ();
1563 // Verify using aliases now
1565 Namespace.VerifyUsing ();
1567 if (Report.Errors > 0){
1571 if (RootContext.VerifyClsCompliance) {
1572 CodeGen.Assembly.ResolveClsCompliance ();
1573 if (CodeGen.Assembly.IsClsCompliant) {
1574 AttributeTester.VerifyModulesClsCompliance ();
1575 TypeManager.LoadAllImportedTypes ();
1576 AttributeTester.VerifyTopLevelNameClsCompliance ();
1581 // The code generator
1584 ShowTime ("Emitting code");
1585 ShowTotalTime ("Total so far");
1586 RootContext.EmitCode ();
1590 if (Report.Errors > 0){
1595 ShowTime ("Closing types");
1597 RootContext.CloseTypes ();
1599 PEFileKinds k = PEFileKinds.ConsoleApplication;
1601 switch (RootContext.Target) {
1602 case Target.Library:
1604 k = PEFileKinds.Dll; break;
1606 k = PEFileKinds.ConsoleApplication; break;
1608 k = PEFileKinds.WindowApplication; break;
1611 if (RootContext.NeedsEntryPoint) {
1612 MethodInfo ep = RootContext.EntryPoint;
1615 if (RootContext.MainClass != null) {
1616 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1617 if (main_cont == null) {
1618 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1622 if (!(main_cont is ClassOrStruct)) {
1623 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1628 if (Report.Errors == 0)
1629 Report.Error (5001, "Program " + output_file +
1630 " does not have an entry point defined");
1634 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1635 } else if (RootContext.MainClass != null) {
1636 Report.Error (2017, "Can not specify -main: when building module or library");
1640 // Add the resources
1642 if (resources != null){
1643 foreach (string spec in resources){
1647 cp = spec.IndexOf (',');
1649 file = spec.Substring (0, cp);
1650 res = spec.Substring (cp + 1);
1654 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1658 if (embedded_resources != null){
1659 object[] margs = new object [2];
1660 Type[] argst = new Type [2];
1661 argst [0] = argst [1] = typeof (string);
1663 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1664 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1665 null, CallingConventions.Any, argst, null);
1667 if (embed_res == null) {
1668 Report.Warning (0, new Location (-1),
1669 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1671 foreach (string spec in embedded_resources) {
1674 cp = spec.IndexOf (',');
1676 margs [0] = spec.Substring (cp + 1);
1677 margs [1] = spec.Substring (0, cp);
1680 margs [0] = Path.GetFileName (spec);
1683 if (File.Exists ((string) margs [1]))
1684 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1686 Report.Error (1566, "Can not find the resource " + margs [1]);
1693 // Add Win32 resources
1696 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1698 if (win32ResourceFile != null) {
1700 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1702 catch (ArgumentException) {
1703 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1707 if (win32IconFile != null) {
1708 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1709 if (define_icon == null) {
1710 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1712 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1715 if (Report.Errors > 0)
1718 CodeGen.Save (output_file);
1720 ShowTime ("Saved output");
1721 ShowTotalTime ("Total");
1724 Timer.ShowTimers ();
1726 if (Report.ExpectedError != 0){
1727 if (Report.Errors == 0) {
1728 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1729 "No other errors reported.");
1731 Environment.Exit (2);
1733 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1734 "However, other errors were reported.");
1736 Environment.Exit (1);
1744 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1745 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1747 return (Report.Errors == 0);
1752 // This is the only public entry point
1754 public class CompilerCallableEntryPoint : MarshalByRefObject {
1755 static bool used = false;
1757 public bool InvokeCompiler (string [] args)
1761 bool ok = Driver.MainDriver (args);
1762 return ok && Report.Errors == 0;
1765 public void Reset ()