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;
109 // The system version we are using, if not specified on the commandline we
110 // will use the same version as corlib for looking for libraries in the GAC.
112 static string sys_version;
114 public static void ShowTime (string msg)
119 DateTime now = DateTime.Now;
120 TimeSpan span = now - last_time;
124 "[{0:00}:{1:000}] {2}",
125 (int) span.TotalSeconds, span.Milliseconds, msg);
128 public static void ShowTotalTime (string msg)
133 DateTime now = DateTime.Now;
134 TimeSpan span = now - first_time;
138 "[{0:00}:{1:000}] {2}",
139 (int) span.TotalSeconds, span.Milliseconds, msg);
142 static void tokenize_file (SourceFile file)
147 input = File.OpenRead (file.Name);
149 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
154 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
155 Tokenizer lexer = new Tokenizer (reader, file, defines);
156 int token, tokens = 0, errors = 0;
158 while ((token = lexer.token ()) != Token.EOF){
160 if (token == Token.ERROR)
163 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
169 // MonoTODO("Change error code for aborted compilation to something reasonable")]
170 static void parse (SourceFile file)
176 input = File.OpenRead (file.Name);
178 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
182 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
184 parser = new CSharpParser (reader, file, defines);
185 parser.yacc_verbose = yacc_verbose;
188 } catch (Exception ex) {
189 Report.Error(666, "Compilation aborted: " + ex);
198 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
199 "mcs [options] source-files\n" +
200 " --about About the Mono C# compiler\n" +
201 " -checked[+|-] Set default context to checked\n" +
202 " -codepage:ID Sets code page to the one in ID\n" +
203 " (number, `utf8' or `reset')\n" +
204 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
205 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
206 " -debug[+|-] Generate debugging information\n" +
207 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
208 " -doc:FILE XML Documentation file to generate\n" +
209 " -g Generate debugging information\n" +
210 " --fatal Makes errors fatal\n" +
211 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
212 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
213 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
214 " -main:class Specified the class that contains the entry point\n" +
215 " -noconfig[+|-] Disables implicit references to assemblies\n" +
216 " -nostdlib[+|-] Does not load core libraries\n" +
217 " -nowarn:W1[,W2] Disables one or more warnings\n" +
218 " -out:FNAME Specifies output file\n" +
219 " --parse Only parses the source file\n" +
220 " --expect-error X Expect that error X will be encountered\n" +
221 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
222 " -reference:ASS References the specified assembly (-r:ASS)\n" +
223 " --stacktrace Shows stack trace at error location\n" +
224 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
225 " library, module), (short: /t:)\n" +
226 " --timestamp Displays time stamps of various compiler events\n" +
227 " -unsafe[+|-] Allows unsafe code\n" +
228 " -warnaserror[+|-] Treat warnings as errors\n" +
229 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
230 " -v Verbose parsing (for debugging the parser)\n" +
231 " -2 Enables experimental C# features\n" +
234 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
235 " -resource:FILE[,ID] Embed FILE as a resource\n" +
236 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
237 " -win32icon:FILE Use this icon for the output\n" +
238 " --mcs-debug X Sets MCS debugging level to X\n" +
239 " @file Read response file for more options\n\n" +
240 "Options can be of the form -option or /option");
243 static void TargetUsage ()
245 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
251 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
252 "The compiler source code is released under the terms of the GNU GPL\n\n" +
254 "For more information on Mono, visit the project Web site\n" +
255 " http://www.go-mono.com\n\n" +
257 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
258 Environment.Exit (0);
261 public static int counter1, counter2;
263 public static int Main (string[] args)
265 bool ok = MainDriver (args);
267 if (ok && Report.Errors == 0) {
268 Console.Write("Compilation succeeded");
269 if (Report.Warnings > 0) {
270 Console.Write(" - {0} warning(s)", Report.Warnings);
274 Console.WriteLine ("Counter1: " + counter1);
275 Console.WriteLine ("Counter2: " + counter2);
281 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
282 Report.Errors, Report.Warnings);
287 static public void LoadAssembly (string assembly, bool soft)
290 string total_log = "";
293 char[] path_chars = { '/', '\\' };
295 if (assembly.IndexOfAny (path_chars) != -1) {
296 a = Assembly.LoadFrom (assembly);
298 string ass = assembly;
299 if (ass.EndsWith (".dll"))
300 ass = assembly.Substring (0, assembly.Length - 4);
301 a = Assembly.Load (ass);
303 TypeManager.AddAssembly (a);
305 } catch (FileNotFoundException){
306 foreach (string dir in link_paths){
307 string full_path = Path.Combine (dir, assembly);
308 if (!assembly.EndsWith (".dll"))
312 a = Assembly.LoadFrom (full_path);
313 TypeManager.AddAssembly (a);
315 } catch (FileNotFoundException ff) {
316 total_log += ff.FusionLog;
321 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
322 Console.WriteLine ("Log: \n" + total_log);
324 } catch (BadImageFormatException f) {
325 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
326 } catch (FileLoadException f){
327 Report.Error(6, "Cannot load assembly " + f.FusionLog);
328 } catch (ArgumentNullException){
329 Report.Error(6, "Cannot load assembly (null argument)");
333 static public void LoadModule (MethodInfo adder_method, string module)
336 string total_log = "";
340 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
342 catch (TargetInvocationException ex) {
343 throw ex.InnerException;
345 TypeManager.AddModule (m);
348 catch (FileNotFoundException){
349 foreach (string dir in link_paths){
350 string full_path = Path.Combine (dir, module);
351 if (!module.EndsWith (".netmodule"))
352 full_path += ".netmodule";
356 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
358 catch (TargetInvocationException ex) {
359 throw ex.InnerException;
361 TypeManager.AddModule (m);
363 } catch (FileNotFoundException ff) {
364 total_log += ff.FusionLog;
368 Report.Error (6, "Cannot find module `" + module + "'" );
369 Console.WriteLine ("Log: \n" + total_log);
370 } catch (BadImageFormatException f) {
371 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
372 } catch (FileLoadException f){
373 Report.Error(6, "Cannot load module " + f.FusionLog);
374 } catch (ArgumentNullException){
375 Report.Error(6, "Cannot load module (null argument)");
380 /// Loads all assemblies referenced on the command line
382 static public void LoadReferences ()
384 foreach (string r in references)
385 LoadAssembly (r, false);
387 foreach (string r in soft_references)
388 LoadAssembly (r, true);
393 static void SetupDefaultDefines ()
395 defines = new ArrayList ();
396 defines.Add ("__MonoCS__");
399 static string [] LoadArgs (string file)
402 ArrayList args = new ArrayList ();
405 f = new StreamReader (file);
410 StringBuilder sb = new StringBuilder ();
412 while ((line = f.ReadLine ()) != null){
415 for (int i = 0; i < t; i++){
418 if (c == '"' || c == '\''){
421 for (i++; i < t; i++){
428 } else if (c == ' '){
430 args.Add (sb.ToString ());
437 args.Add (sb.ToString ());
442 string [] ret_value = new string [args.Count];
443 args.CopyTo (ret_value, 0);
449 // Returns the directory where the system assemblies are installed
451 static string GetSystemDir ()
453 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
455 foreach (Assembly a in assemblies){
456 string codebase = a.Location;
457 string fn = System.IO.Path.GetFileName (codebase);
458 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
459 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
463 Report.Error (-15, "Can not compute my system path");
468 // Given a path specification, splits the path from the file/pattern
470 static void SplitPathAndPattern (string spec, out string path, out string pattern)
472 int p = spec.LastIndexOf ('/');
475 // Windows does not like /file.cs, switch that to:
480 pattern = spec.Substring (1);
482 path = spec.Substring (0, p);
483 pattern = spec.Substring (p + 1);
488 p = spec.LastIndexOf ('\\');
490 path = spec.Substring (0, p);
491 pattern = spec.Substring (p + 1);
499 static void ProcessFile (string f)
501 if (first_source == null)
504 Location.AddFile (f);
507 static void ProcessFiles ()
509 Location.Initialize ();
511 foreach (SourceFile file in Location.SourceFiles) {
513 tokenize_file (file);
520 static void CompileFiles (string spec, bool recurse)
522 string path, pattern;
524 SplitPathAndPattern (spec, out path, out pattern);
525 if (pattern.IndexOf ('*') == -1){
530 string [] files = null;
532 files = Directory.GetFiles (path, pattern);
533 } catch (System.IO.DirectoryNotFoundException) {
534 Report.Error (2001, "Source file `" + spec + "' could not be found");
536 } catch (System.IO.IOException){
537 Report.Error (2001, "Source file `" + spec + "' could not be found");
540 foreach (string f in files) {
547 string [] dirs = null;
550 dirs = Directory.GetDirectories (path);
554 foreach (string d in dirs) {
556 // Don't include path in this string, as each
557 // directory entry already does
558 CompileFiles (d + "/" + pattern, true);
562 static void DefineDefaultConfig ()
565 // For now the "default config" is harcoded into the compiler
566 // we can move this outside later
568 string [] default_config = {
573 // Is it worth pre-loading all this stuff?
576 "System.Configuration.Install",
579 "System.DirectoryServices",
580 "System.Drawing.Design",
582 "System.EnterpriseServices",
585 "System.Runtime.Remoting",
586 "System.Runtime.Serialization.Formatters.Soap",
588 "System.ServiceProcess",
590 "System.Web.RegularExpressions",
591 "System.Web.Services",
592 "System.Windows.Forms"
597 foreach (string def in default_config)
598 soft_references.Insert (p++, def);
601 static void SetOutputFile (string name)
606 static void SetWarningLevel (string s)
611 level = Int32.Parse (s);
615 "--wlevel requires a value from 0 to 4");
616 Environment.Exit (1);
618 if (level < 0 || level > 4){
619 Report.Error (1900, "Warning level must be 0 to 4");
620 Environment.Exit (1);
622 RootContext.WarningLevel = level;
623 TestWarningConflict ();
626 static void TestWarningConflict ()
628 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
629 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
630 Environment.Exit (1);
634 static void SetupV2 ()
636 RootContext.V2 = true;
637 defines.Add ("__V2__");
640 static void Version ()
642 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
643 Console.WriteLine ("Mono C# compiler version {0}", version);
644 Environment.Exit (0);
648 // Currently handles the Unix-like command line options, but will be
649 // deprecated in favor of the CSCParseOption, which will also handle the
650 // options that start with a dash in the future.
652 static bool UnixParseOption (string arg, ref string [] args, ref int i)
656 parser_verbose = true;
671 case "--main": case "-m":
672 if ((i + 1) >= args.Length){
674 Environment.Exit (1);
676 RootContext.MainClass = args [++i];
680 RootContext.Unsafe = true;
683 case "/?": case "/h": case "/help":
686 Environment.Exit (0);
690 if ((i + 1) >= args.Length){
692 Environment.Exit (1);
694 defines.Add (args [++i]);
697 case "--show-counters":
698 show_counters = true;
701 case "--expect-error": {
706 args [++i], NumberStyles.AllowLeadingSign);
707 Report.ExpectedError = code;
709 Report.Error (-14, "Invalid number specified");
720 if ((i + 1) >= args.Length){
722 Environment.Exit (1);
724 SetOutputFile (args [++i]);
728 RootContext.Checked = true;
732 Report.Stacktrace = true;
735 case "--linkresource":
737 if ((i + 1) >= args.Length){
739 Report.Error (5, "Missing argument to --linkres");
740 Environment.Exit (1);
742 if (resources == null)
743 resources = new ArrayList ();
745 resources.Add (args [++i]);
750 if ((i + 1) >= args.Length){
752 Report.Error (5, "Missing argument to --resource");
753 Environment.Exit (1);
755 if (embedded_resources == null)
756 embedded_resources = new ArrayList ();
758 embedded_resources.Add (args [++i]);
762 if ((i + 1) >= args.Length){
763 Environment.Exit (1);
767 string type = args [++i];
770 RootContext.Target = Target.Library;
771 RootContext.TargetExt = ".dll";
775 RootContext.Target = Target.Exe;
779 RootContext.Target = Target.WinExe;
783 RootContext.Target = Target.Module;
784 RootContext.TargetExt = ".dll";
788 Environment.Exit (1);
794 if ((i + 1) >= args.Length){
796 Environment.Exit (1);
799 references.Add (args [++i]);
803 if ((i + 1) >= args.Length){
805 Environment.Exit (1);
807 link_paths.Add (args [++i]);
811 RootContext.StdLib = false;
819 Report.WarningsAreErrors = true;
820 TestWarningConflict();
824 if ((i + 1) >= args.Length){
826 Environment.Exit (1);
831 warn = Int32.Parse (args [++i]);
834 Environment.Exit (1);
836 Report.SetIgnoreWarning (warn);
840 if ((i + 1) >= args.Length){
843 "--wlevel requires a value from 0 to 4");
844 Environment.Exit (1);
847 SetWarningLevel (args [++i]);
851 if ((i + 1) >= args.Length){
852 Report.Error (5, "--mcs-debug requires an argument");
853 Environment.Exit (1);
857 Report.DebugFlags = Int32.Parse (args [++i]);
859 Report.Error (5, "Invalid argument to --mcs-debug");
860 Environment.Exit (1);
869 if ((i + 1) >= args.Length){
870 Report.Error (5, "--recurse requires an argument");
871 Environment.Exit (1);
873 CompileFiles (args [++i], true);
878 last_time = first_time = DateTime.Now;
885 case "--debug": case "-g":
886 want_debugging_support = true;
890 load_default_config = false;
898 // Currently it is very basic option parsing, but eventually, this will
899 // be the complete option parser
901 static bool CSCParseOption (string option, ref string [] args, ref int i)
903 int idx = option.IndexOf (':');
910 arg = option.Substring (0, idx);
912 value = option.Substring (idx + 1);
923 RootContext.Target = Target.Exe;
927 RootContext.Target = Target.WinExe;
931 RootContext.Target = Target.Library;
932 RootContext.TargetExt = ".dll";
936 RootContext.Target = Target.Module;
937 RootContext.TargetExt = ".netmodule";
942 Environment.Exit (1);
950 Environment.Exit (1);
952 SetOutputFile (value);
959 case "/incremental+":
960 case "/incremental-":
970 Environment.Exit (1);
973 defs = value.Split (new Char [] {';', ','});
974 foreach (string d in defs){
981 case "/linkresource":
983 Report.Error (5, arg + " requires an argument");
984 Environment.Exit (1);
986 if (resources == null)
987 resources = new ArrayList ();
989 resources.Add (value);
995 Report.Error (5, arg + " requires an argument");
996 Environment.Exit (1);
998 if (embedded_resources == null)
999 embedded_resources = new ArrayList ();
1001 embedded_resources.Add (value);
1006 Report.Error (5, "/recurse requires an argument");
1007 Environment.Exit (1);
1009 CompileFiles (value, true);
1013 case "/reference": {
1015 Report.Error (5, arg + " requires an argument");
1016 Environment.Exit (1);
1019 string [] refs = value.Split (new char [] { ';', ',' });
1020 foreach (string r in refs){
1025 case "/addmodule": {
1027 Report.Error (5, arg + " requires an argument");
1028 Environment.Exit (1);
1031 string [] refs = value.Split (new char [] { ';', ',' });
1032 foreach (string r in refs){
1039 Report.Error (5, arg + " requires an argument");
1040 Environment.Exit (1);
1043 win32ResourceFile = value;
1046 case "/win32icon": {
1048 Report.Error (5, arg + " requires an argument");
1049 Environment.Exit (1);
1052 win32IconFile = value;
1057 Report.Error (5, arg + " requires an argument");
1058 Environment.Exit (1);
1060 // TODO handle the /doc argument to generate xml doc
1067 Report.Error (5, "/lib requires an argument");
1068 Environment.Exit (1);
1071 libdirs = value.Split (new Char [] { ',' });
1072 foreach (string dir in libdirs)
1073 link_paths.Add (dir);
1079 want_debugging_support = true;
1084 RootContext.Checked = true;
1088 RootContext.Checked = false;
1096 RootContext.VerifyClsCompliance = false;
1101 RootContext.Unsafe = true;
1105 RootContext.Unsafe = false;
1108 case "/warnaserror":
1109 case "/warnaserror+":
1110 Report.WarningsAreErrors = true;
1111 TestWarningConflict();
1114 case "/warnaserror-":
1115 Report.WarningsAreErrors = false;
1119 SetWarningLevel (value);
1126 Report.Error (5, "/nowarn requires an argument");
1127 Environment.Exit (1);
1130 warns = value.Split (new Char [] {','});
1131 foreach (string wc in warns){
1133 int warn = Int32.Parse (wc);
1135 throw new ArgumentOutOfRangeException("warn");
1137 Report.SetIgnoreWarning (warn);
1139 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1140 Environment.Exit (1);
1147 load_default_config = true;
1152 load_default_config = false;
1158 Environment.Exit (0);
1164 Report.Error (5, arg + " requires an argument");
1165 Environment.Exit (1);
1167 RootContext.MainClass = value;
1172 RootContext.StdLib = false;
1176 RootContext.StdLib = true;
1183 if (value == String.Empty) {
1184 Report.Error (5, arg + " requires an argument");
1185 Environment.Exit (1);
1187 RootContext.StrongNameKeyFile = value;
1189 case "/keycontainer":
1190 if (value == String.Empty) {
1191 Report.Error (5, arg + " requires an argument");
1192 Environment.Exit (1);
1194 RootContext.StrongNameKeyContainer = value;
1197 RootContext.StrongNameDelaySign = true;
1200 RootContext.StrongNameDelaySign = false;
1211 if (value == "utf8"){
1212 encoding = new UTF8Encoding();
1213 using_default_encoder = false;
1216 if (value == "reset"){
1218 // 28591 is the code page for ISO-8859-1 encoding.
1221 using_default_encoder = true;
1225 cp = Int32.Parse (value);
1226 encoding = Encoding.GetEncoding (cp);
1227 using_default_encoder = false;
1229 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1230 Environment.Exit (1);
1234 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1235 //Environment.Exit (1);
1240 /// Parses the arguments, and drives the compilation
1245 /// TODO: Mostly structured to debug the compiler
1246 /// now, needs to be turned into a real driver soon.
1248 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1249 internal static bool MainDriver (string [] args)
1252 bool parsing_options = true;
1255 encoding = Encoding.GetEncoding (28591);
1257 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1258 encoding = Encoding.GetEncoding (1252);
1261 references = new ArrayList ();
1262 soft_references = new ArrayList ();
1263 modules = new ArrayList ();
1264 link_paths = new ArrayList ();
1266 SetupDefaultDefines ();
1271 // This is not required because Assembly.Load knows about this
1275 int argc = args.Length;
1276 for (i = 0; i < argc; i++){
1277 string arg = args [i];
1279 if (arg.StartsWith ("@")){
1280 string [] new_args, extra_args;
1281 string response_file = arg.Substring (1);
1283 if (response_file_list == null)
1284 response_file_list = new Hashtable ();
1286 if (response_file_list.Contains (response_file)){
1288 1515, "Response file `" + response_file +
1289 "' specified multiple times");
1290 Environment.Exit (1);
1293 response_file_list.Add (response_file, response_file);
1295 extra_args = LoadArgs (response_file);
1296 if (extra_args == null){
1297 Report.Error (2011, "Unable to open response file: " +
1302 new_args = new string [extra_args.Length + argc];
1303 args.CopyTo (new_args, 0);
1304 extra_args.CopyTo (new_args, argc);
1306 argc = new_args.Length;
1310 if (parsing_options){
1312 parsing_options = false;
1316 if (arg.StartsWith ("-")){
1317 if (UnixParseOption (arg, ref args, ref i))
1321 string csc_opt = "/" + arg.Substring (1);
1322 if (CSCParseOption (csc_opt, ref args, ref i))
1325 if (arg.StartsWith ("/")){
1326 if (CSCParseOption (arg, ref args, ref i))
1332 CompileFiles (arg, false);
1341 // If we are an exe, require a source file for the entry point
1343 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1344 if (first_source == null){
1345 Report.Error (2008, "No files to compile were specified");
1352 // If there is nothing to put in the assembly, and we are not a library
1354 if (first_source == null && embedded_resources == null && resources == null){
1355 Report.Error (2008, "No files to compile were specified");
1359 if (Report.Errors > 0)
1365 Tokenizer.Cleanup ();
1368 // Load Core Library for default compilation
1370 if (RootContext.StdLib)
1371 references.Insert (0, "mscorlib");
1373 if (load_default_config)
1374 DefineDefaultConfig ();
1376 if (Report.Errors > 0){
1381 // Load assemblies required
1384 ShowTime ("Loading references");
1385 link_paths.Add (GetSystemDir ());
1386 link_paths.Add (Directory.GetCurrentDirectory ());
1390 ShowTime (" References loaded");
1392 if (Report.Errors > 0){
1399 if (output_file == null){
1400 int pos = first_source.LastIndexOf ('.');
1403 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1405 output_file = first_source + RootContext.TargetExt;
1408 CodeGen.Init (output_file, output_file, want_debugging_support);
1410 if (RootContext.Target == Target.Module) {
1411 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1412 if (module_only == null) {
1413 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1414 Environment.Exit (1);
1417 MethodInfo set_method = module_only.GetSetMethod (true);
1418 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1421 TypeManager.AddModule (CodeGen.Module.Builder);
1423 if (modules.Count > 0) {
1424 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1425 if (adder_method == null) {
1426 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1427 Environment.Exit (1);
1430 foreach (string module in modules)
1431 LoadModule (adder_method, module);
1434 TypeManager.ComputeNamespaces ();
1437 // Before emitting, we need to get the core
1438 // types emitted from the user defined types
1439 // or from the system ones.
1442 ShowTime ("Initializing Core Types");
1443 if (!RootContext.StdLib){
1444 RootContext.ResolveCore ();
1445 if (Report.Errors > 0)
1449 TypeManager.InitCoreTypes ();
1451 ShowTime (" Core Types done");
1454 // The second pass of the compiler
1457 ShowTime ("Resolving tree");
1458 RootContext.ResolveTree ();
1459 if (Report.Errors > 0)
1462 ShowTime ("Populate tree");
1463 if (!RootContext.StdLib)
1464 RootContext.BootCorlib_PopulateCoreTypes ();
1466 RootContext.PopulateTypes ();
1467 RootContext.DefineTypes ();
1469 TypeManager.InitCodeHelpers ();
1472 // Verify using aliases now
1474 Namespace.VerifyUsing ();
1476 if (Report.Errors > 0){
1480 if (RootContext.VerifyClsCompliance) {
1481 CodeGen.Assembly.ResolveClsCompliance ();
1482 AttributeTester.VerifyModulesClsCompliance ();
1483 TypeManager.LoadAllImportedTypes ();
1487 // The code generator
1490 ShowTime ("Emitting code");
1491 ShowTotalTime ("Total so far");
1492 RootContext.EmitCode ();
1496 if (Report.Errors > 0){
1501 ShowTime ("Closing types");
1503 RootContext.CloseTypes ();
1505 PEFileKinds k = PEFileKinds.ConsoleApplication;
1507 switch (RootContext.Target) {
1508 case Target.Library:
1510 k = PEFileKinds.Dll; break;
1512 k = PEFileKinds.ConsoleApplication; break;
1514 k = PEFileKinds.WindowApplication; break;
1517 if (RootContext.NeedsEntryPoint) {
1518 MethodInfo ep = RootContext.EntryPoint;
1521 if (Report.Errors == 0)
1522 Report.Error (5001, "Program " + output_file +
1523 " does not have an entry point defined");
1527 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1528 } else if (RootContext.MainClass != null) {
1529 Report.Error (2017, "Can not specify -main: when building module or library");
1533 // Add the resources
1535 if (resources != null){
1536 foreach (string spec in resources){
1540 cp = spec.IndexOf (',');
1542 file = spec.Substring (0, cp);
1543 res = spec.Substring (cp + 1);
1547 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1551 if (embedded_resources != null){
1552 object[] margs = new object [2];
1553 Type[] argst = new Type [2];
1554 argst [0] = argst [1] = typeof (string);
1556 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1557 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1558 null, CallingConventions.Any, argst, null);
1560 if (embed_res == null) {
1561 Report.Warning (0, new Location (-1),
1562 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1564 foreach (string spec in embedded_resources) {
1567 cp = spec.IndexOf (',');
1569 margs [0] = spec.Substring (cp + 1);
1570 margs [1] = spec.Substring (0, cp);
1573 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1576 if (File.Exists ((string) margs [1]))
1577 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1579 Report.Error (1566, "Can not find the resource " + margs [1]);
1586 // Add Win32 resources
1589 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1591 if (win32ResourceFile != null) {
1593 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1595 catch (ArgumentException) {
1596 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1600 if (win32IconFile != null) {
1601 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1602 if (define_icon == null) {
1603 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1605 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1608 if (Report.Errors > 0)
1611 CodeGen.Save (output_file);
1613 ShowTime ("Saved output");
1614 ShowTotalTime ("Total");
1617 Timer.ShowTimers ();
1619 if (Report.ExpectedError != 0) {
1620 if (Report.Errors == 0) {
1621 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1622 "No other errors reported.");
1624 Environment.Exit (2);
1626 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1627 "However, other errors were reported.");
1629 Environment.Exit (1);
1637 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1638 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1640 return (Report.Errors == 0);
1646 // This is the only public entry point
1648 public class CompilerCallableEntryPoint : MarshalByRefObject {
1649 static bool used = false;
1651 public bool InvokeCompiler (string [] args)
1655 bool ok = Driver.MainDriver (args);
1656 return ok && Report.Errors == 0;
1659 public void Reset ()