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;
23 Library, Exe, Module, WinExe
27 /// The compiler driver.
33 // Assemblies references to be linked. Initialized with
35 static ArrayList references;
38 // If any of these fail, we ignore the problem. This is so
39 // that we can list all the assemblies in Windows and not fail
40 // if they are missing on Linux.
42 static ArrayList soft_references;
45 // Modules to be linked
47 static ArrayList modules;
50 static ArrayList link_paths;
52 // Whether we want Yacc to output its progress
53 static bool yacc_verbose = false;
55 // Whether we want to only run the tokenizer
56 static bool tokenize = false;
58 static string first_source;
60 static bool want_debugging_support = false;
62 static bool parse_only = false;
63 static bool timestamps = false;
64 static bool pause = false;
65 static bool show_counters = false;
66 public static bool parser_verbose = false;
69 // Whether to load the initial config file (what CSC.RSP has by default)
71 static bool load_default_config = true;
73 static Hashtable response_file_list;
76 // A list of resource files
78 static ArrayList resources;
79 static ArrayList embedded_resources;
80 static string win32ResourceFile;
81 static string win32IconFile;
84 // An array of the defines from the command line
86 static ArrayList defines;
91 static string output_file = null;
94 // Last time we took the time
96 static DateTime last_time, first_time;
99 // Encoding: ISO-Latin1 is 28591
101 static Encoding encoding;
104 // Whether the user has specified a different encoder manually
106 static bool using_default_encoder = true;
108 public static void ShowTime (string msg)
113 DateTime now = DateTime.Now;
114 TimeSpan span = now - last_time;
118 "[{0:00}:{1:000}] {2}",
119 (int) span.TotalSeconds, span.Milliseconds, msg);
122 public static void ShowTotalTime (string msg)
127 DateTime now = DateTime.Now;
128 TimeSpan span = now - first_time;
132 "[{0:00}:{1:000}] {2}",
133 (int) span.TotalSeconds, span.Milliseconds, msg);
136 static void tokenize_file (SourceFile file)
141 input = File.OpenRead (file.Name);
143 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
148 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
149 Tokenizer lexer = new Tokenizer (reader, file, defines);
150 int token, tokens = 0, errors = 0;
152 while ((token = lexer.token ()) != Token.EOF){
154 if (token == Token.ERROR)
157 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
163 // MonoTODO("Change error code for aborted compilation to something reasonable")]
164 static void parse (SourceFile file)
170 input = File.OpenRead (file.Name);
172 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
176 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
178 parser = new CSharpParser (reader, file, defines);
179 parser.yacc_verbose = yacc_verbose;
182 } catch (Exception ex) {
183 Report.Error(666, "Compilation aborted: " + ex);
192 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
193 "mcs [options] source-files\n" +
194 " --about About the Mono C# compiler\n" +
195 " -checked[+|-] Set default context to checked\n" +
196 " -codepage:ID Sets code page to the one in ID\n" +
197 " (number, `utf8' or `reset')\n" +
198 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
199 " -debug[+-] Generate debugging information\n" +
200 " -doc:FILE XML Documentation file to generate\n" +
201 " -g Generate debugging information\n" +
202 " --fatal Makes errors fatal\n" +
203 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
204 " -main:class Specified the class that contains the entry point\n" +
205 " -noconfig[+|-] Disables implicit references to assemblies\n" +
206 " -nostdlib[+|-] Does not load core libraries\n" +
207 " -nowarn:W1[,W2] Disables one or more warnings\n" +
208 " -out:FNAME Specifies output file\n" +
209 " --parse Only parses the source file\n" +
210 " --expect-error X Expect that error X will be encountered\n" +
211 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
212 " -reference:ASS References the specified assembly (-r:ASS)\n" +
213 " --stacktrace Shows stack trace at error location\n" +
214 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
215 " library, module), (short: /t:)\n" +
216 " --timestamp Displays time stamps of various compiler events\n" +
217 " -unsafe[+|-] Allows unsafe code\n" +
218 " -warnaserror[+|-] Treat warnings as errors\n" +
219 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
220 " -v Verbose parsing (for debugging the parser)\n" +
221 " -2 Enables experimental C# features\n" +
224 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
225 " -resource:FILE[,ID] Embed FILE as a resource\n" +
226 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
227 " -win32icon:FILE Use this icon for the output\n" +
228 " --mcs-debug X Sets MCS debugging level to X\n" +
229 " @file Read response file for more options\n\n" +
230 "Options can be of the form -option or /option");
233 static void TargetUsage ()
235 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
241 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
242 "The compiler source code is released under the terms of the GNU GPL\n\n" +
244 "For more information on Mono, visit the project Web site\n" +
245 " http://www.go-mono.com\n\n" +
247 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
248 Environment.Exit (0);
251 public static int counter1, counter2;
253 public static int Main (string[] args)
255 bool ok = MainDriver (args);
257 if (ok && Report.Errors == 0) {
258 Console.Write("Compilation succeeded");
259 if (Report.Warnings > 0) {
260 Console.Write(" - {0} warning(s)", Report.Warnings);
264 Console.WriteLine ("Counter1: " + counter1);
265 Console.WriteLine ("Counter2: " + counter2);
271 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
272 Report.Errors, Report.Warnings);
277 static public void LoadAssembly (string assembly, bool soft)
280 string total_log = "";
283 char[] path_chars = { '/', '\\', '.' };
285 if (assembly.IndexOfAny (path_chars) != -1) {
286 a = Assembly.LoadFrom (assembly);
288 a = Assembly.Load (assembly);
290 TypeManager.AddAssembly (a);
292 } catch (FileNotFoundException){
293 foreach (string dir in link_paths){
294 string full_path = Path.Combine (dir, assembly);
295 if (!assembly.EndsWith (".dll"))
299 a = Assembly.LoadFrom (full_path);
300 TypeManager.AddAssembly (a);
302 } catch (FileNotFoundException ff) {
303 total_log += ff.FusionLog;
308 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
309 Console.WriteLine ("Log: \n" + total_log);
311 } catch (BadImageFormatException f) {
312 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
313 } catch (FileLoadException f){
314 Report.Error(6, "Cannot load assembly " + f.FusionLog);
315 } catch (ArgumentNullException){
316 Report.Error(6, "Cannot load assembly (null argument)");
320 static public void LoadModule (MethodInfo adder_method, string module)
323 string total_log = "";
327 m = (Module)adder_method.Invoke (CodeGen.AssemblyBuilder, new object [] { module });
329 catch (TargetInvocationException ex) {
330 throw ex.InnerException;
332 TypeManager.AddModule (m);
335 catch (FileNotFoundException){
336 foreach (string dir in link_paths){
337 string full_path = Path.Combine (dir, module);
338 if (!module.EndsWith (".netmodule"))
339 full_path += ".netmodule";
343 m = (Module)adder_method.Invoke (CodeGen.AssemblyBuilder, new object [] { full_path });
345 catch (TargetInvocationException ex) {
346 throw ex.InnerException;
348 TypeManager.AddModule (m);
350 } catch (FileNotFoundException ff) {
351 total_log += ff.FusionLog;
355 Report.Error (6, "Cannot find module `" + module + "'" );
356 Console.WriteLine ("Log: \n" + total_log);
357 } catch (BadImageFormatException f) {
358 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
359 } catch (FileLoadException f){
360 Report.Error(6, "Cannot load module " + f.FusionLog);
361 } catch (ArgumentNullException){
362 Report.Error(6, "Cannot load module (null argument)");
367 /// Loads all assemblies referenced on the command line
369 static public void LoadReferences ()
371 foreach (string r in references)
372 LoadAssembly (r, false);
374 foreach (string r in soft_references)
375 LoadAssembly (r, true);
380 static void SetupDefaultDefines ()
382 defines = new ArrayList ();
383 defines.Add ("__MonoCS__");
386 static string [] LoadArgs (string file)
389 ArrayList args = new ArrayList ();
392 f = new StreamReader (file);
397 StringBuilder sb = new StringBuilder ();
399 while ((line = f.ReadLine ()) != null){
402 for (int i = 0; i < t; i++){
405 if (c == '"' || c == '\''){
408 for (i++; i < t; i++){
415 } else if (c == ' '){
417 args.Add (sb.ToString ());
424 args.Add (sb.ToString ());
429 string [] ret_value = new string [args.Count];
430 args.CopyTo (ret_value, 0);
436 // Returns the directory where the system assemblies are installed
438 static string GetSystemDir ()
440 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
442 foreach (Assembly a in assemblies){
443 string codebase = a.Location;
444 string fn = System.IO.Path.GetFileName (codebase);
445 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
446 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
450 Report.Error (-15, "Can not compute my system path");
455 // Given a path specification, splits the path from the file/pattern
457 static void SplitPathAndPattern (string spec, out string path, out string pattern)
459 int p = spec.LastIndexOf ('/');
462 // Windows does not like /file.cs, switch that to:
467 pattern = spec.Substring (1);
469 path = spec.Substring (0, p);
470 pattern = spec.Substring (p + 1);
475 p = spec.LastIndexOf ('\\');
477 path = spec.Substring (0, p);
478 pattern = spec.Substring (p + 1);
486 static void ProcessFile (string f)
488 if (first_source == null)
491 Location.AddFile (f);
494 static void ProcessFiles ()
496 Location.Initialize ();
498 foreach (SourceFile file in Location.SourceFiles) {
500 tokenize_file (file);
507 static void CompileFiles (string spec, bool recurse)
509 string path, pattern;
511 SplitPathAndPattern (spec, out path, out pattern);
512 if (pattern.IndexOf ('*') == -1){
517 string [] files = null;
519 files = Directory.GetFiles (path, pattern);
520 } catch (System.IO.DirectoryNotFoundException) {
521 Report.Error (2001, "Source file `" + spec + "' could not be found");
523 } catch (System.IO.IOException){
524 Report.Error (2001, "Source file `" + spec + "' could not be found");
527 foreach (string f in files) {
534 string [] dirs = null;
537 dirs = Directory.GetDirectories (path);
541 foreach (string d in dirs) {
543 // Don't include path in this string, as each
544 // directory entry already does
545 CompileFiles (d + "/" + pattern, true);
549 static void DefineDefaultConfig ()
552 // For now the "default config" is harcoded into the compiler
553 // we can move this outside later
555 string [] default_config = {
560 // Is it worth pre-loading all this stuff?
563 "System.Configuration.Install",
566 "System.DirectoryServices",
567 "System.Drawing.Design",
569 "System.EnterpriseServices",
572 "System.Runtime.Remoting",
573 "System.Runtime.Serialization.Formatters.Soap",
575 "System.ServiceProcess",
577 "System.Web.RegularExpressions",
578 "System.Web.Services",
579 "System.Windows.Forms"
584 foreach (string def in default_config)
585 soft_references.Insert (p++, def);
588 static void SetOutputFile (string name)
593 static void SetWarningLevel (string s)
598 level = Int32.Parse (s);
602 "--wlevel requires a value from 0 to 4");
603 Environment.Exit (1);
605 if (level < 0 || level > 4){
606 Report.Error (1900, "Warning level must be 0 to 4");
607 Environment.Exit (1);
609 RootContext.WarningLevel = level;
610 TestWarningConflict ();
613 static void TestWarningConflict ()
615 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
616 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
617 Environment.Exit (1);
621 static void SetupV2 ()
623 RootContext.V2 = true;
624 defines.Add ("__V2__");
627 static void Version ()
629 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
630 Console.WriteLine ("Mono C# compiler version {0}", version);
631 Environment.Exit (0);
635 // Currently handles the Unix-like command line options, but will be
636 // deprecated in favor of the CSCParseOption, which will also handle the
637 // options that start with a dash in the future.
639 static bool UnixParseOption (string arg, ref string [] args, ref int i)
643 parser_verbose = true;
658 case "--main": case "-m":
659 if ((i + 1) >= args.Length){
661 Environment.Exit (1);
663 RootContext.MainClass = args [++i];
667 RootContext.Unsafe = true;
670 case "/?": case "/h": case "/help":
673 Environment.Exit (0);
677 if ((i + 1) >= args.Length){
679 Environment.Exit (1);
681 defines.Add (args [++i]);
684 case "--show-counters":
685 show_counters = true;
688 case "--expect-error": {
693 args [++i], NumberStyles.AllowLeadingSign);
694 Report.ExpectedError = code;
696 Report.Error (-14, "Invalid number specified");
707 if ((i + 1) >= args.Length){
709 Environment.Exit (1);
711 SetOutputFile (args [++i]);
715 RootContext.Checked = true;
719 Report.Stacktrace = true;
722 case "--linkresource":
724 if ((i + 1) >= args.Length){
726 Report.Error (5, "Missing argument to --linkres");
727 Environment.Exit (1);
729 if (resources == null)
730 resources = new ArrayList ();
732 resources.Add (args [++i]);
737 if ((i + 1) >= args.Length){
739 Report.Error (5, "Missing argument to --resource");
740 Environment.Exit (1);
742 if (embedded_resources == null)
743 embedded_resources = new ArrayList ();
745 embedded_resources.Add (args [++i]);
749 if ((i + 1) >= args.Length){
750 Environment.Exit (1);
754 string type = args [++i];
757 RootContext.Target = Target.Library;
758 RootContext.TargetExt = ".dll";
762 RootContext.Target = Target.Exe;
766 RootContext.Target = Target.WinExe;
770 RootContext.Target = Target.Module;
771 RootContext.TargetExt = ".dll";
775 Environment.Exit (1);
781 if ((i + 1) >= args.Length){
783 Environment.Exit (1);
786 references.Add (args [++i]);
790 if ((i + 1) >= args.Length){
792 Environment.Exit (1);
794 link_paths.Add (args [++i]);
798 RootContext.StdLib = false;
806 Report.WarningsAreErrors = true;
807 TestWarningConflict();
811 if ((i + 1) >= args.Length){
813 Environment.Exit (1);
818 warn = Int32.Parse (args [++i]);
821 Environment.Exit (1);
823 Report.SetIgnoreWarning (warn);
827 if ((i + 1) >= args.Length){
830 "--wlevel requires a value from 0 to 4");
831 Environment.Exit (1);
834 SetWarningLevel (args [++i]);
838 if ((i + 1) >= args.Length){
839 Report.Error (5, "--mcs-debug requires an argument");
840 Environment.Exit (1);
844 Report.DebugFlags = Int32.Parse (args [++i]);
846 Report.Error (5, "Invalid argument to --mcs-debug");
847 Environment.Exit (1);
856 if ((i + 1) >= args.Length){
857 Report.Error (5, "--recurse requires an argument");
858 Environment.Exit (1);
860 CompileFiles (args [++i], true);
865 last_time = first_time = DateTime.Now;
872 case "--debug": case "-g":
873 want_debugging_support = true;
877 load_default_config = false;
885 // Currently it is very basic option parsing, but eventually, this will
886 // be the complete option parser
888 static bool CSCParseOption (string option, ref string [] args, ref int i)
890 int idx = option.IndexOf (':');
897 arg = option.Substring (0, idx);
899 value = option.Substring (idx + 1);
910 RootContext.Target = Target.Exe;
914 RootContext.Target = Target.WinExe;
918 RootContext.Target = Target.Library;
919 RootContext.TargetExt = ".dll";
923 RootContext.Target = Target.Module;
924 RootContext.TargetExt = ".netmodule";
929 Environment.Exit (1);
937 Environment.Exit (1);
939 SetOutputFile (value);
946 case "/incremental+":
947 case "/incremental-":
957 Environment.Exit (1);
960 defs = value.Split (new Char [] {';', ','});
961 foreach (string d in defs){
968 case "/linkresource":
970 Report.Error (5, arg + " requires an argument");
971 Environment.Exit (1);
973 if (resources == null)
974 resources = new ArrayList ();
976 resources.Add (value);
982 Report.Error (5, arg + " requires an argument");
983 Environment.Exit (1);
985 if (embedded_resources == null)
986 embedded_resources = new ArrayList ();
988 embedded_resources.Add (value);
993 Report.Error (5, "/recurse requires an argument");
994 Environment.Exit (1);
996 CompileFiles (value, true);
1000 case "/reference": {
1002 Report.Error (5, arg + " requires an argument");
1003 Environment.Exit (1);
1006 string [] refs = value.Split (new char [] { ';', ',' });
1007 foreach (string r in refs){
1012 case "/addmodule": {
1014 Report.Error (5, arg + " requires an argument");
1015 Environment.Exit (1);
1018 string [] refs = value.Split (new char [] { ';', ',' });
1019 foreach (string r in refs){
1026 Report.Error (5, arg + " requires an argument");
1027 Environment.Exit (1);
1030 win32ResourceFile = value;
1033 case "/win32icon": {
1035 Report.Error (5, arg + " requires an argument");
1036 Environment.Exit (1);
1039 win32IconFile = value;
1044 Report.Error (5, arg + " requires an argument");
1045 Environment.Exit (1);
1047 // TODO handle the /doc argument to generate xml doc
1054 Report.Error (5, "/lib requires an argument");
1055 Environment.Exit (1);
1058 libdirs = value.Split (new Char [] { ',' });
1059 foreach (string dir in libdirs)
1060 link_paths.Add (dir);
1066 want_debugging_support = true;
1071 RootContext.Checked = true;
1075 RootContext.Checked = false;
1080 RootContext.Unsafe = true;
1084 RootContext.Unsafe = false;
1087 case "/warnaserror":
1088 case "/warnaserror+":
1089 Report.WarningsAreErrors = true;
1090 TestWarningConflict();
1093 case "/warnaserror-":
1094 Report.WarningsAreErrors = false;
1098 SetWarningLevel (value);
1105 Report.Error (5, "/nowarn requires an argument");
1106 Environment.Exit (1);
1109 warns = value.Split (new Char [] {','});
1110 foreach (string wc in warns){
1112 int warn = Int32.Parse (wc);
1114 throw new ArgumentOutOfRangeException("warn");
1116 Report.SetIgnoreWarning (warn);
1118 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1119 Environment.Exit (1);
1126 load_default_config = true;
1131 load_default_config = false;
1137 Environment.Exit (0);
1143 Report.Error (5, arg + " requires an argument");
1144 Environment.Exit (1);
1146 RootContext.MainClass = value;
1151 RootContext.StdLib = false;
1155 RootContext.StdLib = true;
1169 if (value == "utf8"){
1170 encoding = new UTF8Encoding();
1171 using_default_encoder = false;
1174 if (value == "reset"){
1176 // 28591 is the code page for ISO-8859-1 encoding.
1179 using_default_encoder = true;
1183 cp = Int32.Parse (value);
1184 encoding = Encoding.GetEncoding (cp);
1185 using_default_encoder = false;
1187 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1188 Environment.Exit (1);
1192 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1193 //Environment.Exit (1);
1198 /// Parses the arguments, and drives the compilation
1203 /// TODO: Mostly structured to debug the compiler
1204 /// now, needs to be turned into a real driver soon.
1206 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1207 internal static bool MainDriver (string [] args)
1210 bool parsing_options = true;
1213 encoding = Encoding.GetEncoding (28591);
1215 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1216 encoding = Encoding.GetEncoding (1252);
1219 references = new ArrayList ();
1220 soft_references = new ArrayList ();
1221 modules = new ArrayList ();
1222 link_paths = new ArrayList ();
1224 SetupDefaultDefines ();
1229 // This is not required because Assembly.Load knows about this
1233 int argc = args.Length;
1234 for (i = 0; i < argc; i++){
1235 string arg = args [i];
1237 if (arg.StartsWith ("@")){
1238 string [] new_args, extra_args;
1239 string response_file = arg.Substring (1);
1241 if (response_file_list == null)
1242 response_file_list = new Hashtable ();
1244 if (response_file_list.Contains (response_file)){
1246 1515, "Response file `" + response_file +
1247 "' specified multiple times");
1248 Environment.Exit (1);
1251 response_file_list.Add (response_file, response_file);
1253 extra_args = LoadArgs (response_file);
1254 if (extra_args == null){
1255 Report.Error (2011, "Unable to open response file: " +
1260 new_args = new string [extra_args.Length + argc];
1261 args.CopyTo (new_args, 0);
1262 extra_args.CopyTo (new_args, argc);
1264 argc = new_args.Length;
1268 if (parsing_options){
1270 parsing_options = false;
1274 if (arg.StartsWith ("-")){
1275 if (UnixParseOption (arg, ref args, ref i))
1279 string csc_opt = "/" + arg.Substring (1);
1280 if (CSCParseOption (csc_opt, ref args, ref i))
1283 if (arg.StartsWith ("/")){
1284 if (CSCParseOption (arg, ref args, ref i))
1290 CompileFiles (arg, false);
1299 // If we are an exe, require a source file for the entry point
1301 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1302 if (first_source == null){
1303 Report.Error (2008, "No files to compile were specified");
1310 // If there is nothing to put in the assembly, and we are not a library
1312 if (first_source == null && embedded_resources == null && resources == null){
1313 Report.Error (2008, "No files to compile were specified");
1317 if (Report.Errors > 0)
1323 Tokenizer.Cleanup ();
1326 // Load Core Library for default compilation
1328 if (RootContext.StdLib)
1329 references.Insert (0, "mscorlib");
1331 if (load_default_config)
1332 DefineDefaultConfig ();
1334 if (Report.Errors > 0){
1339 // Load assemblies required
1342 ShowTime ("Loading references");
1343 link_paths.Add (GetSystemDir ());
1347 ShowTime (" References loaded");
1349 if (Report.Errors > 0){
1356 if (output_file == null){
1357 int pos = first_source.LastIndexOf ('.');
1360 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1362 output_file = first_source + RootContext.TargetExt;
1365 CodeGen.Init (output_file, output_file, want_debugging_support);
1367 if (RootContext.Target == Target.Module) {
1368 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1369 if (module_only == null) {
1370 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1371 Environment.Exit (1);
1374 module_only.SetValue (CodeGen.AssemblyBuilder, true, null);
1377 TypeManager.AddModule (CodeGen.ModuleBuilder);
1379 if (modules.Count > 0) {
1380 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1381 if (adder_method == null) {
1382 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1383 Environment.Exit (1);
1386 foreach (string module in modules)
1387 LoadModule (adder_method, module);
1390 TypeManager.ComputeNamespaces ();
1393 // Before emitting, we need to get the core
1394 // types emitted from the user defined types
1395 // or from the system ones.
1398 ShowTime ("Initializing Core Types");
1399 if (!RootContext.StdLib){
1400 RootContext.ResolveCore ();
1401 if (Report.Errors > 0)
1405 TypeManager.InitCoreTypes ();
1407 ShowTime (" Core Types done");
1410 // The second pass of the compiler
1413 ShowTime ("Resolving tree");
1414 RootContext.ResolveTree ();
1415 if (Report.Errors > 0)
1418 ShowTime ("Populate tree");
1419 if (!RootContext.StdLib)
1420 RootContext.BootCorlib_PopulateCoreTypes ();
1421 RootContext.PopulateTypes ();
1422 RootContext.DefineTypes ();
1424 TypeManager.InitCodeHelpers ();
1427 // Verify using aliases now
1429 Namespace.VerifyUsing ();
1431 if (Report.Errors > 0){
1436 // The code generator
1439 ShowTime ("Emitting code");
1440 ShowTotalTime ("Total so far");
1441 RootContext.EmitCode ();
1445 if (Report.Errors > 0){
1450 ShowTime ("Closing types");
1452 RootContext.CloseTypes ();
1454 PEFileKinds k = PEFileKinds.ConsoleApplication;
1456 switch (RootContext.Target) {
1457 case Target.Library:
1459 k = PEFileKinds.Dll; break;
1461 k = PEFileKinds.ConsoleApplication; break;
1463 k = PEFileKinds.WindowApplication; break;
1466 if (RootContext.NeedsEntryPoint) {
1467 MethodInfo ep = RootContext.EntryPoint;
1470 if (Report.Errors == 0)
1471 Report.Error (5001, "Program " + output_file +
1472 " does not have an entry point defined");
1476 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1477 } else if (RootContext.MainClass != null) {
1478 Report.Error (2017, "Can not specify -main: when building module or library");
1482 // Add the resources
1484 if (resources != null){
1485 foreach (string spec in resources){
1489 cp = spec.IndexOf (',');
1491 file = spec.Substring (0, cp);
1492 res = spec.Substring (cp + 1);
1496 CodeGen.AssemblyBuilder.AddResourceFile (res, file);
1500 if (embedded_resources != null){
1501 object[] margs = new object [2];
1502 Type[] argst = new Type [2];
1503 argst [0] = argst [1] = typeof (string);
1505 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod ("EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic, null, CallingConventions.Any, argst, null);
1506 if (embed_res == null) {
1507 Report.Warning (0, new Location (-1), "Cannot embed resources on this runtime: try the Mono runtime instead.");
1509 foreach (string spec in embedded_resources) {
1512 cp = spec.IndexOf (',');
1514 margs [0] = spec.Substring (cp + 1);
1515 margs [1] = spec.Substring (0, cp);
1517 margs [0] = margs [1] = spec;
1519 if (File.Exists ((string) margs [1]))
1520 embed_res.Invoke (CodeGen.AssemblyBuilder, margs);
1522 Report.Error (1566, "Can not find the resource " + margs [1]);
1529 // Add Win32 resources
1532 CodeGen.AssemblyBuilder.DefineVersionInfoResource ();
1534 if (win32ResourceFile != null) {
1536 CodeGen.AssemblyBuilder.DefineUnmanagedResource (win32ResourceFile);
1538 catch (ArgumentException) {
1539 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1543 if (win32IconFile != null) {
1544 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1545 if (define_icon == null) {
1546 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1548 define_icon.Invoke (CodeGen.AssemblyBuilder, new object [] { win32IconFile });
1551 if (Report.Errors > 0)
1554 CodeGen.Save (output_file);
1556 ShowTime ("Saved output");
1557 ShowTotalTime ("Total");
1560 Timer.ShowTimers ();
1562 if (Report.ExpectedError != 0){
1563 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1564 Environment.Exit (1);
1569 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1570 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1572 return (Report.Errors == 0);
1578 // This is the only public entry point
1580 public class CompilerCallableEntryPoint : MarshalByRefObject {
1581 static bool used = false;
1583 public bool InvokeCompiler (string [] args)
1587 bool ok = Driver.MainDriver (args);
1588 return ok && Report.Errors == 0;
1591 public void Reset ()