2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 using System.Globalization;
20 using System.Diagnostics;
24 Library, Exe, Module, WinExe
28 /// The compiler driver.
34 // Assemblies references to be linked. Initialized with
36 static ArrayList references;
39 // If any of these fail, we ignore the problem. This is so
40 // that we can list all the assemblies in Windows and not fail
41 // if they are missing on Linux.
43 static ArrayList soft_references;
46 // Modules to be linked
48 static ArrayList modules;
51 static ArrayList link_paths;
53 // Whether we want Yacc to output its progress
54 static bool yacc_verbose = false;
56 // Whether we want to only run the tokenizer
57 static bool tokenize = false;
59 static string first_source;
61 static bool want_debugging_support = false;
63 static bool parse_only = false;
64 static bool timestamps = false;
65 static bool pause = false;
66 static bool show_counters = false;
67 public static bool parser_verbose = false;
70 // Whether to load the initial config file (what CSC.RSP has by default)
72 static bool load_default_config = true;
74 static Hashtable response_file_list;
77 // A list of resource files
79 static ArrayList resources;
80 static ArrayList embedded_resources;
81 static string win32ResourceFile;
82 static string win32IconFile;
85 // An array of the defines from the command line
87 static ArrayList defines;
92 static string output_file = null;
95 // Last time we took the time
97 static DateTime last_time, first_time;
100 // Encoding: ISO-Latin1 is 28591
102 static Encoding encoding;
105 // Whether the user has specified a different encoder manually
107 static bool using_default_encoder = true;
110 // The system version we are using, if not specified on the commandline we
111 // will use the same version as corlib for looking for libraries in the GAC.
113 static string sys_version;
115 public static void ShowTime (string msg)
120 DateTime now = DateTime.Now;
121 TimeSpan span = now - last_time;
125 "[{0:00}:{1:000}] {2}",
126 (int) span.TotalSeconds, span.Milliseconds, msg);
129 public static void ShowTotalTime (string msg)
134 DateTime now = DateTime.Now;
135 TimeSpan span = now - first_time;
139 "[{0:00}:{1:000}] {2}",
140 (int) span.TotalSeconds, span.Milliseconds, msg);
143 static void tokenize_file (SourceFile file)
148 input = File.OpenRead (file.Name);
150 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
155 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
156 Tokenizer lexer = new Tokenizer (reader, file, defines);
157 int token, tokens = 0, errors = 0;
159 while ((token = lexer.token ()) != Token.EOF){
161 if (token == Token.ERROR)
164 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
170 // MonoTODO("Change error code for aborted compilation to something reasonable")]
171 static void parse (SourceFile file)
177 input = File.OpenRead (file.Name);
179 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
183 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
185 parser = new CSharpParser (reader, file, defines);
186 parser.yacc_verbose = yacc_verbose;
189 } catch (Exception ex) {
190 Report.Error(666, "Compilation aborted: " + ex);
196 static void OtherFlags ()
199 "Other flags in the compiler\n" +
200 " --fatal Makes errors fatal\n" +
201 " --parse Only parses the source file\n" +
202 " --stacktrace Shows stack trace at error location\n" +
203 " --timestamp Displays time stamps of various compiler events\n" +
204 " -2 Enables experimental C# features\n" +
205 " -v Verbose parsing (for debugging the parser)\n" +
206 " --mcs-debug X Sets MCS debugging level to X\n");
212 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
213 "mcs [options] source-files\n" +
214 " --about About the Mono C# compiler\n" +
215 " -addmodule:MODULE Adds the module to the generated assembly\n" +
216 " -checked[+|-] Set default context to checked\n" +
217 " -codepage:ID Sets code page to the one in ID\n" +
218 " (number, `utf8' or `reset')\n" +
219 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
220 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
221 " -debug[+|-] Generate debugging information\n" +
222 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
223 " -doc:FILE XML Documentation file to generate\n" +
224 " -g Generate debugging information\n" +
225 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
226 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
227 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
228 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
229 " -main:class Specified the class that contains the entry point\n" +
230 " -noconfig[+|-] Disables implicit references to assemblies\n" +
231 " -nostdlib[+|-] Does not load core libraries\n" +
232 " -nowarn:W1[,W2] Disables one or more warnings\n" +
233 " -out:FNAME Specifies output file\n" +
234 " -pkg:P1[,Pn] References packages P1..Pn\n" +
235 " --expect-error X Expect that error X will be encountered\n" +
236 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
237 " -reference:ASS References the specified assembly (-r:ASS)\n" +
238 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
239 " library, module), (short: /t:)\n" +
240 " -unsafe[+|-] Allows unsafe code\n" +
241 " -warnaserror[+|-] Treat warnings as errors\n" +
242 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
243 " -help2 Show other help flags\n" +
246 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
247 " -resource:FILE[,ID] Embed FILE as a resource\n" +
248 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
249 " -win32icon:FILE Use this icon for the output\n" +
250 " @file Read response file for more options\n\n" +
251 "Options can be of the form -option or /option");
254 static void TargetUsage ()
256 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
262 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
263 "The compiler source code is released under the terms of the GNU GPL\n\n" +
265 "For more information on Mono, visit the project Web site\n" +
266 " http://www.go-mono.com\n\n" +
268 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
269 Environment.Exit (0);
272 public static int counter1, counter2;
274 public static int Main (string[] args)
276 bool ok = MainDriver (args);
278 if (ok && Report.Errors == 0) {
279 Console.Write("Compilation succeeded");
280 if (Report.Warnings > 0) {
281 Console.Write(" - {0} warning(s)", Report.Warnings);
285 Console.WriteLine ("Counter1: " + counter1);
286 Console.WriteLine ("Counter2: " + counter2);
292 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
293 Report.Errors, Report.Warnings);
298 static public void LoadAssembly (string assembly, bool soft)
301 string total_log = "";
304 char[] path_chars = { '/', '\\' };
306 if (assembly.IndexOfAny (path_chars) != -1) {
307 a = Assembly.LoadFrom (assembly);
309 string ass = assembly;
310 if (ass.EndsWith (".dll"))
311 ass = assembly.Substring (0, assembly.Length - 4);
312 a = Assembly.Load (ass);
314 TypeManager.AddAssembly (a);
316 } catch (FileNotFoundException){
317 foreach (string dir in link_paths){
318 string full_path = Path.Combine (dir, assembly);
319 if (!assembly.EndsWith (".dll"))
323 a = Assembly.LoadFrom (full_path);
324 TypeManager.AddAssembly (a);
326 } catch (FileNotFoundException ff) {
327 total_log += ff.FusionLog;
332 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
333 Console.WriteLine ("Log: \n" + total_log);
335 } catch (BadImageFormatException f) {
336 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
337 } catch (FileLoadException f){
338 Report.Error(6, "Cannot load assembly " + f.FusionLog);
339 } catch (ArgumentNullException){
340 Report.Error(6, "Cannot load assembly (null argument)");
344 static public void LoadModule (MethodInfo adder_method, string module)
347 string total_log = "";
351 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
353 catch (TargetInvocationException ex) {
354 throw ex.InnerException;
356 TypeManager.AddModule (m);
359 catch (FileNotFoundException){
360 foreach (string dir in link_paths){
361 string full_path = Path.Combine (dir, module);
362 if (!module.EndsWith (".netmodule"))
363 full_path += ".netmodule";
367 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
369 catch (TargetInvocationException ex) {
370 throw ex.InnerException;
372 TypeManager.AddModule (m);
374 } catch (FileNotFoundException ff) {
375 total_log += ff.FusionLog;
379 Report.Error (6, "Cannot find module `" + module + "'" );
380 Console.WriteLine ("Log: \n" + total_log);
381 } catch (BadImageFormatException f) {
382 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
383 } catch (FileLoadException f){
384 Report.Error(6, "Cannot load module " + f.FusionLog);
385 } catch (ArgumentNullException){
386 Report.Error(6, "Cannot load module (null argument)");
391 /// Loads all assemblies referenced on the command line
393 static public void LoadReferences ()
395 foreach (string r in references)
396 LoadAssembly (r, false);
398 foreach (string r in soft_references)
399 LoadAssembly (r, true);
404 static void SetupDefaultDefines ()
406 defines = new ArrayList ();
407 defines.Add ("__MonoCS__");
410 static string [] LoadArgs (string file)
413 ArrayList args = new ArrayList ();
416 f = new StreamReader (file);
421 StringBuilder sb = new StringBuilder ();
423 while ((line = f.ReadLine ()) != null){
426 for (int i = 0; i < t; i++){
429 if (c == '"' || c == '\''){
432 for (i++; i < t; i++){
439 } else if (c == ' '){
441 args.Add (sb.ToString ());
448 args.Add (sb.ToString ());
453 string [] ret_value = new string [args.Count];
454 args.CopyTo (ret_value, 0);
460 // Returns the directory where the system assemblies are installed
462 static string GetSystemDir ()
464 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
466 foreach (Assembly a in assemblies){
467 string codebase = a.Location;
468 string fn = System.IO.Path.GetFileName (codebase);
469 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
470 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
474 Report.Error (-15, "Can not compute my system path");
479 // Given a path specification, splits the path from the file/pattern
481 static void SplitPathAndPattern (string spec, out string path, out string pattern)
483 int p = spec.LastIndexOf ('/');
486 // Windows does not like /file.cs, switch that to:
491 pattern = spec.Substring (1);
493 path = spec.Substring (0, p);
494 pattern = spec.Substring (p + 1);
499 p = spec.LastIndexOf ('\\');
501 path = spec.Substring (0, p);
502 pattern = spec.Substring (p + 1);
510 static void ProcessFile (string f)
512 if (first_source == null)
515 Location.AddFile (f);
518 static void ProcessFiles ()
520 Location.Initialize ();
522 foreach (SourceFile file in Location.SourceFiles) {
524 tokenize_file (file);
531 static void CompileFiles (string spec, bool recurse)
533 string path, pattern;
535 SplitPathAndPattern (spec, out path, out pattern);
536 if (pattern.IndexOf ('*') == -1){
541 string [] files = null;
543 files = Directory.GetFiles (path, pattern);
544 } catch (System.IO.DirectoryNotFoundException) {
545 Report.Error (2001, "Source file `" + spec + "' could not be found");
547 } catch (System.IO.IOException){
548 Report.Error (2001, "Source file `" + spec + "' could not be found");
551 foreach (string f in files) {
558 string [] dirs = null;
561 dirs = Directory.GetDirectories (path);
565 foreach (string d in dirs) {
567 // Don't include path in this string, as each
568 // directory entry already does
569 CompileFiles (d + "/" + pattern, true);
573 static void DefineDefaultConfig ()
576 // For now the "default config" is harcoded into the compiler
577 // we can move this outside later
579 string [] default_config = {
584 // Is it worth pre-loading all this stuff?
587 "System.Configuration.Install",
590 "System.DirectoryServices",
591 "System.Drawing.Design",
593 "System.EnterpriseServices",
596 "System.Runtime.Remoting",
597 "System.Runtime.Serialization.Formatters.Soap",
599 "System.ServiceProcess",
601 "System.Web.RegularExpressions",
602 "System.Web.Services",
603 "System.Windows.Forms"
608 foreach (string def in default_config)
609 soft_references.Insert (p++, def);
612 static void SetOutputFile (string name)
617 static void SetWarningLevel (string s)
622 level = Int32.Parse (s);
626 "--wlevel requires a value from 0 to 4");
627 Environment.Exit (1);
629 if (level < 0 || level > 4){
630 Report.Error (1900, "Warning level must be 0 to 4");
631 Environment.Exit (1);
633 RootContext.WarningLevel = level;
634 TestWarningConflict ();
637 static void TestWarningConflict ()
639 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
640 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
641 Environment.Exit (1);
645 static void SetupV2 ()
647 RootContext.Version = LanguageVersion.Default;
648 defines.Add ("__V2__");
651 static void Version ()
653 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
654 Console.WriteLine ("Mono C# compiler version {0}", version);
655 Environment.Exit (0);
659 // Currently handles the Unix-like command line options, but will be
660 // deprecated in favor of the CSCParseOption, which will also handle the
661 // options that start with a dash in the future.
663 static bool UnixParseOption (string arg, ref string [] args, ref int i)
667 parser_verbose = true;
682 case "--main": case "-m":
683 if ((i + 1) >= args.Length){
685 Environment.Exit (1);
687 RootContext.MainClass = args [++i];
691 RootContext.Unsafe = true;
694 case "/?": case "/h": case "/help":
697 Environment.Exit (0);
701 if ((i + 1) >= args.Length){
703 Environment.Exit (1);
705 defines.Add (args [++i]);
708 case "--show-counters":
709 show_counters = true;
712 case "--expect-error": {
717 args [++i], NumberStyles.AllowLeadingSign);
718 Report.ExpectedError = code;
720 Report.Error (-14, "Invalid number specified");
731 if ((i + 1) >= args.Length){
733 Environment.Exit (1);
735 SetOutputFile (args [++i]);
739 RootContext.Checked = true;
743 Report.Stacktrace = true;
746 case "--linkresource":
748 if ((i + 1) >= args.Length){
750 Report.Error (5, "Missing argument to --linkres");
751 Environment.Exit (1);
753 if (resources == null)
754 resources = new ArrayList ();
756 resources.Add (args [++i]);
761 if ((i + 1) >= args.Length){
763 Report.Error (5, "Missing argument to --resource");
764 Environment.Exit (1);
766 if (embedded_resources == null)
767 embedded_resources = new ArrayList ();
769 embedded_resources.Add (args [++i]);
773 if ((i + 1) >= args.Length){
774 Environment.Exit (1);
778 string type = args [++i];
781 RootContext.Target = Target.Library;
782 RootContext.TargetExt = ".dll";
786 RootContext.Target = Target.Exe;
790 RootContext.Target = Target.WinExe;
794 RootContext.Target = Target.Module;
795 RootContext.TargetExt = ".dll";
799 Environment.Exit (1);
805 if ((i + 1) >= args.Length){
807 Environment.Exit (1);
810 references.Add (args [++i]);
814 if ((i + 1) >= args.Length){
816 Environment.Exit (1);
818 link_paths.Add (args [++i]);
822 RootContext.StdLib = false;
830 Report.WarningsAreErrors = true;
831 TestWarningConflict();
835 if ((i + 1) >= args.Length){
837 Environment.Exit (1);
842 warn = Int32.Parse (args [++i]);
845 Environment.Exit (1);
847 Report.SetIgnoreWarning (warn);
851 if ((i + 1) >= args.Length){
854 "--wlevel requires a value from 0 to 4");
855 Environment.Exit (1);
858 SetWarningLevel (args [++i]);
862 if ((i + 1) >= args.Length){
863 Report.Error (5, "--mcs-debug requires an argument");
864 Environment.Exit (1);
868 Report.DebugFlags = Int32.Parse (args [++i]);
870 Report.Error (5, "Invalid argument to --mcs-debug");
871 Environment.Exit (1);
880 if ((i + 1) >= args.Length){
881 Report.Error (5, "--recurse requires an argument");
882 Environment.Exit (1);
884 CompileFiles (args [++i], true);
889 last_time = first_time = DateTime.Now;
896 case "--debug": case "-g":
897 want_debugging_support = true;
901 load_default_config = false;
909 // Currently it is very basic option parsing, but eventually, this will
910 // be the complete option parser
912 static bool CSCParseOption (string option, ref string [] args, ref int i)
914 int idx = option.IndexOf (':');
921 arg = option.Substring (0, idx);
923 value = option.Substring (idx + 1);
934 RootContext.Target = Target.Exe;
938 RootContext.Target = Target.WinExe;
942 RootContext.Target = Target.Library;
943 RootContext.TargetExt = ".dll";
947 RootContext.Target = Target.Module;
948 RootContext.TargetExt = ".netmodule";
953 Environment.Exit (1);
961 Environment.Exit (1);
963 SetOutputFile (value);
970 case "/incremental+":
971 case "/incremental-":
981 Environment.Exit (1);
984 defs = value.Split (new Char [] {';', ','});
985 foreach (string d in defs){
992 case "/linkresource":
994 Report.Error (5, arg + " requires an argument");
995 Environment.Exit (1);
997 if (resources == null)
998 resources = new ArrayList ();
1000 resources.Add (value);
1008 Environment.Exit (1);
1010 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1012 ProcessStartInfo pi = new ProcessStartInfo ();
1013 pi.FileName = "pkg-config";
1014 pi.RedirectStandardOutput = true;
1015 pi.UseShellExecute = false;
1016 pi.Arguments = "--libs " + packages;
1019 p = Process.Start (pi);
1020 } catch (Exception e) {
1021 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1022 Environment.Exit (1);
1025 if (p.StandardOutput == null){
1026 Report.Warning (-27, "Specified package did not return any information");
1029 string pkgout = p.StandardOutput.ReadToEnd ();
1031 if (p.ExitCode != 0) {
1032 Report.Error (-27, "Error running pkg-config. Check the above output.");
1033 Environment.Exit (1);
1036 if (pkgout != null){
1037 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1038 Split (new Char [] { ' ', '\t'});
1039 args = AddArgs (args, xargs);
1049 Report.Error (5, "-resource requires an argument");
1050 Environment.Exit (1);
1052 if (embedded_resources == null)
1053 embedded_resources = new ArrayList ();
1055 embedded_resources.Add (value);
1060 Report.Error (5, "-recurse requires an argument");
1061 Environment.Exit (1);
1063 CompileFiles (value, true);
1067 case "/reference": {
1069 Report.Error (5, "-reference requires an argument");
1070 Environment.Exit (1);
1073 string [] refs = value.Split (new char [] { ';', ',' });
1074 foreach (string r in refs){
1079 case "/addmodule": {
1081 Report.Error (5, arg + " requires an argument");
1082 Environment.Exit (1);
1085 string [] refs = value.Split (new char [] { ';', ',' });
1086 foreach (string r in refs){
1093 Report.Error (5, arg + " requires an argument");
1094 Environment.Exit (1);
1097 win32ResourceFile = value;
1100 case "/win32icon": {
1102 Report.Error (5, arg + " requires an argument");
1103 Environment.Exit (1);
1106 win32IconFile = value;
1111 Report.Error (5, arg + " requires an argument");
1112 Environment.Exit (1);
1114 // TODO handle the /doc argument to generate xml doc
1121 Report.Error (5, "/lib requires an argument");
1122 Environment.Exit (1);
1125 libdirs = value.Split (new Char [] { ',' });
1126 foreach (string dir in libdirs)
1127 link_paths.Add (dir);
1132 want_debugging_support = false;
1137 want_debugging_support = true;
1142 RootContext.Checked = true;
1146 RootContext.Checked = false;
1154 RootContext.VerifyClsCompliance = false;
1159 RootContext.Unsafe = true;
1163 RootContext.Unsafe = false;
1166 case "/warnaserror":
1167 case "/warnaserror+":
1168 Report.WarningsAreErrors = true;
1169 TestWarningConflict();
1172 case "/warnaserror-":
1173 Report.WarningsAreErrors = false;
1177 SetWarningLevel (value);
1184 Report.Error (5, "/nowarn requires an argument");
1185 Environment.Exit (1);
1188 warns = value.Split (new Char [] {','});
1189 foreach (string wc in warns){
1191 int warn = Int32.Parse (wc);
1193 throw new ArgumentOutOfRangeException("warn");
1195 Report.SetIgnoreWarning (warn);
1197 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1198 Environment.Exit (1);
1205 load_default_config = true;
1210 load_default_config = false;
1215 Environment.Exit(0);
1221 Environment.Exit (0);
1227 Report.Error (5, arg + " requires an argument");
1228 Environment.Exit (1);
1230 RootContext.MainClass = value;
1235 RootContext.StdLib = false;
1239 RootContext.StdLib = true;
1246 if (value == String.Empty) {
1247 Report.Error (5, arg + " requires an argument");
1248 Environment.Exit (1);
1250 RootContext.StrongNameKeyFile = value;
1252 case "/keycontainer":
1253 if (value == String.Empty) {
1254 Report.Error (5, arg + " requires an argument");
1255 Environment.Exit (1);
1257 RootContext.StrongNameKeyContainer = value;
1260 RootContext.StrongNameDelaySign = true;
1263 RootContext.StrongNameDelaySign = false;
1268 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1272 case "/langversion":
1273 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1275 RootContext.Version = LanguageVersion.ISO_1;
1282 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1283 Environment.Exit (1);
1289 if (value == "utf8"){
1290 encoding = new UTF8Encoding();
1291 using_default_encoder = false;
1294 if (value == "reset"){
1296 // 28591 is the code page for ISO-8859-1 encoding.
1299 using_default_encoder = true;
1303 cp = Int32.Parse (value);
1304 encoding = Encoding.GetEncoding (cp);
1305 using_default_encoder = false;
1307 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1308 Environment.Exit (1);
1313 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1314 //Environment.Exit (1);
1318 static string [] AddArgs (string [] args, string [] extra_args)
1322 new_args = new string [extra_args.Length + args.Length];
1323 args.CopyTo (new_args, 0);
1324 extra_args.CopyTo (new_args, args.Length);
1330 /// Parses the arguments, and drives the compilation
1335 /// TODO: Mostly structured to debug the compiler
1336 /// now, needs to be turned into a real driver soon.
1338 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1339 internal static bool MainDriver (string [] args)
1342 bool parsing_options = true;
1345 encoding = Encoding.GetEncoding (28591);
1347 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1348 encoding = Encoding.GetEncoding (1252);
1351 references = new ArrayList ();
1352 soft_references = new ArrayList ();
1353 modules = new ArrayList ();
1354 link_paths = new ArrayList ();
1356 SetupDefaultDefines ();
1361 // This is not required because Assembly.Load knows about this
1365 for (i = 0; i < args.Length; i++){
1366 string arg = args [i];
1370 if (arg.StartsWith ("@")){
1371 string [] extra_args;
1372 string response_file = arg.Substring (1);
1374 if (response_file_list == null)
1375 response_file_list = new Hashtable ();
1377 if (response_file_list.Contains (response_file)){
1379 1515, "Response file `" + response_file +
1380 "' specified multiple times");
1381 Environment.Exit (1);
1384 response_file_list.Add (response_file, response_file);
1386 extra_args = LoadArgs (response_file);
1387 if (extra_args == null){
1388 Report.Error (2011, "Unable to open response file: " +
1393 args = AddArgs (args, extra_args);
1397 if (parsing_options){
1399 parsing_options = false;
1403 if (arg.StartsWith ("-")){
1404 if (UnixParseOption (arg, ref args, ref i))
1408 string csc_opt = "/" + arg.Substring (1);
1409 if (CSCParseOption (csc_opt, ref args, ref i))
1412 if (arg.StartsWith ("/")){
1413 if (CSCParseOption (arg, ref args, ref i))
1419 CompileFiles (arg, false);
1428 // If we are an exe, require a source file for the entry point
1430 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1431 if (first_source == null){
1432 Report.Error (2008, "No files to compile were specified");
1439 // If there is nothing to put in the assembly, and we are not a library
1441 if (first_source == null && embedded_resources == null && resources == null){
1442 Report.Error (2008, "No files to compile were specified");
1446 if (Report.Errors > 0)
1452 Tokenizer.Cleanup ();
1455 // Load Core Library for default compilation
1457 if (RootContext.StdLib)
1458 references.Insert (0, "mscorlib");
1460 if (load_default_config)
1461 DefineDefaultConfig ();
1463 if (Report.Errors > 0){
1468 // Load assemblies required
1471 ShowTime ("Loading references");
1472 link_paths.Add (GetSystemDir ());
1473 link_paths.Add (Directory.GetCurrentDirectory ());
1477 ShowTime (" References loaded");
1479 if (Report.Errors > 0){
1486 if (output_file == null){
1487 int pos = first_source.LastIndexOf ('.');
1490 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1492 output_file = first_source + RootContext.TargetExt;
1495 CodeGen.Init (output_file, output_file, want_debugging_support);
1497 if (RootContext.Target == Target.Module) {
1498 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1499 if (module_only == null) {
1500 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1501 Environment.Exit (1);
1504 MethodInfo set_method = module_only.GetSetMethod (true);
1505 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1508 TypeManager.AddModule (CodeGen.Module.Builder);
1510 if (modules.Count > 0) {
1511 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1512 if (adder_method == null) {
1513 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1514 Environment.Exit (1);
1517 foreach (string module in modules)
1518 LoadModule (adder_method, module);
1521 TypeManager.ComputeNamespaces ();
1524 // Before emitting, we need to get the core
1525 // types emitted from the user defined types
1526 // or from the system ones.
1529 ShowTime ("Initializing Core Types");
1530 if (!RootContext.StdLib){
1531 RootContext.ResolveCore ();
1532 if (Report.Errors > 0)
1536 TypeManager.InitCoreTypes ();
1538 ShowTime (" Core Types done");
1541 // The second pass of the compiler
1544 ShowTime ("Resolving tree");
1545 RootContext.ResolveTree ();
1546 if (Report.Errors > 0)
1549 ShowTime ("Populate tree");
1550 if (!RootContext.StdLib)
1551 RootContext.BootCorlib_PopulateCoreTypes ();
1553 RootContext.PopulateTypes ();
1554 RootContext.DefineTypes ();
1556 TypeManager.InitCodeHelpers ();
1559 // Verify using aliases now
1561 Namespace.VerifyUsing ();
1563 if (Report.Errors > 0){
1567 if (RootContext.VerifyClsCompliance) {
1568 CodeGen.Assembly.ResolveClsCompliance ();
1569 if (CodeGen.Assembly.IsClsCompliant) {
1570 AttributeTester.VerifyModulesClsCompliance ();
1571 TypeManager.LoadAllImportedTypes ();
1572 AttributeTester.VerifyTopLevelNameClsCompliance ();
1577 // The code generator
1580 ShowTime ("Emitting code");
1581 ShowTotalTime ("Total so far");
1582 RootContext.EmitCode ();
1586 if (Report.Errors > 0){
1591 ShowTime ("Closing types");
1593 RootContext.CloseTypes ();
1595 PEFileKinds k = PEFileKinds.ConsoleApplication;
1597 switch (RootContext.Target) {
1598 case Target.Library:
1600 k = PEFileKinds.Dll; break;
1602 k = PEFileKinds.ConsoleApplication; break;
1604 k = PEFileKinds.WindowApplication; break;
1607 if (RootContext.NeedsEntryPoint) {
1608 MethodInfo ep = RootContext.EntryPoint;
1611 if (RootContext.MainClass != null) {
1612 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1613 if (main_cont == null) {
1614 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1618 if (!(main_cont is ClassOrStruct)) {
1619 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1624 if (Report.Errors == 0)
1625 Report.Error (5001, "Program " + output_file +
1626 " does not have an entry point defined");
1630 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1631 } else if (RootContext.MainClass != null) {
1632 Report.Error (2017, "Can not specify -main: when building module or library");
1636 // Add the resources
1638 if (resources != null){
1639 foreach (string spec in resources){
1643 cp = spec.IndexOf (',');
1645 file = spec.Substring (0, cp);
1646 res = spec.Substring (cp + 1);
1650 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1654 if (embedded_resources != null){
1655 object[] margs = new object [2];
1656 Type[] argst = new Type [2];
1657 argst [0] = argst [1] = typeof (string);
1659 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1660 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1661 null, CallingConventions.Any, argst, null);
1663 if (embed_res == null) {
1664 Report.Warning (0, new Location (-1),
1665 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1667 foreach (string spec in embedded_resources) {
1670 cp = spec.IndexOf (',');
1672 margs [0] = spec.Substring (cp + 1);
1673 margs [1] = spec.Substring (0, cp);
1676 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1679 if (File.Exists ((string) margs [1]))
1680 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1682 Report.Error (1566, "Can not find the resource " + margs [1]);
1689 // Add Win32 resources
1692 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1694 if (win32ResourceFile != null) {
1696 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1698 catch (ArgumentException) {
1699 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1703 if (win32IconFile != null) {
1704 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1705 if (define_icon == null) {
1706 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1708 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1711 if (Report.Errors > 0)
1714 CodeGen.Save (output_file);
1716 ShowTime ("Saved output");
1717 ShowTotalTime ("Total");
1720 Timer.ShowTimers ();
1722 if (Report.ExpectedError != 0) {
1723 if (Report.Errors == 0) {
1724 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1725 "No other errors reported.");
1727 Environment.Exit (2);
1729 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1730 "However, other errors were reported.");
1732 Environment.Exit (1);
1740 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1741 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1743 return (Report.Errors == 0);
1749 // This is the only public entry point
1751 public class CompilerCallableEntryPoint : MarshalByRefObject {
1752 static bool used = false;
1754 public bool InvokeCompiler (string [] args)
1758 bool ok = Driver.MainDriver (args);
1759 return ok && Report.Errors == 0;
1762 public void Reset ()