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 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
201 " -doc:FILE XML Documentation file to generate\n" +
202 " -g Generate debugging information\n" +
203 " --fatal Makes errors fatal\n" +
204 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
205 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
206 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
207 " -main:class Specified the class that contains the entry point\n" +
208 " -noconfig[+|-] Disables implicit references to assemblies\n" +
209 " -nostdlib[+|-] Does not load core libraries\n" +
210 " -nowarn:W1[,W2] Disables one or more warnings\n" +
211 " -out:FNAME Specifies output file\n" +
212 " --parse Only parses the source file\n" +
213 " --expect-error X Expect that error X will be encountered\n" +
214 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
215 " -reference:ASS References the specified assembly (-r:ASS)\n" +
216 " --stacktrace Shows stack trace at error location\n" +
217 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
218 " library, module), (short: /t:)\n" +
219 " --timestamp Displays time stamps of various compiler events\n" +
220 " -unsafe[+|-] Allows unsafe code\n" +
221 " -warnaserror[+|-] Treat warnings as errors\n" +
222 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
223 " -v Verbose parsing (for debugging the parser)\n" +
224 " -2 Enables experimental C# features\n" +
227 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
228 " -resource:FILE[,ID] Embed FILE as a resource\n" +
229 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
230 " -win32icon:FILE Use this icon for the output\n" +
231 " --mcs-debug X Sets MCS debugging level to X\n" +
232 " @file Read response file for more options\n\n" +
233 "Options can be of the form -option or /option");
236 static void TargetUsage ()
238 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
244 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
245 "The compiler source code is released under the terms of the GNU GPL\n\n" +
247 "For more information on Mono, visit the project Web site\n" +
248 " http://www.go-mono.com\n\n" +
250 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
251 Environment.Exit (0);
254 public static int counter1, counter2;
256 public static int Main (string[] args)
258 bool ok = MainDriver (args);
260 if (ok && Report.Errors == 0) {
261 Console.Write("Compilation succeeded");
262 if (Report.Warnings > 0) {
263 Console.Write(" - {0} warning(s)", Report.Warnings);
267 Console.WriteLine ("Counter1: " + counter1);
268 Console.WriteLine ("Counter2: " + counter2);
274 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
275 Report.Errors, Report.Warnings);
280 static public void LoadAssembly (string assembly, bool soft)
283 string total_log = "";
286 char[] path_chars = { '/', '\\', '.' };
288 if (assembly.IndexOfAny (path_chars) != -1) {
289 a = Assembly.LoadFrom (assembly);
291 a = Assembly.Load (assembly);
293 TypeManager.AddAssembly (a);
295 } catch (FileNotFoundException){
296 foreach (string dir in link_paths){
297 string full_path = Path.Combine (dir, assembly);
298 if (!assembly.EndsWith (".dll"))
302 a = Assembly.LoadFrom (full_path);
303 TypeManager.AddAssembly (a);
305 } catch (FileNotFoundException ff) {
306 total_log += ff.FusionLog;
311 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
312 Console.WriteLine ("Log: \n" + total_log);
314 } catch (BadImageFormatException f) {
315 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
316 } catch (FileLoadException f){
317 Report.Error(6, "Cannot load assembly " + f.FusionLog);
318 } catch (ArgumentNullException){
319 Report.Error(6, "Cannot load assembly (null argument)");
323 static public void LoadModule (MethodInfo adder_method, string module)
326 string total_log = "";
330 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
332 catch (TargetInvocationException ex) {
333 throw ex.InnerException;
335 TypeManager.AddModule (m);
338 catch (FileNotFoundException){
339 foreach (string dir in link_paths){
340 string full_path = Path.Combine (dir, module);
341 if (!module.EndsWith (".netmodule"))
342 full_path += ".netmodule";
346 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
348 catch (TargetInvocationException ex) {
349 throw ex.InnerException;
351 TypeManager.AddModule (m);
353 } catch (FileNotFoundException ff) {
354 total_log += ff.FusionLog;
358 Report.Error (6, "Cannot find module `" + module + "'" );
359 Console.WriteLine ("Log: \n" + total_log);
360 } catch (BadImageFormatException f) {
361 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
362 } catch (FileLoadException f){
363 Report.Error(6, "Cannot load module " + f.FusionLog);
364 } catch (ArgumentNullException){
365 Report.Error(6, "Cannot load module (null argument)");
370 /// Loads all assemblies referenced on the command line
372 static public void LoadReferences ()
374 foreach (string r in references)
375 LoadAssembly (r, false);
377 foreach (string r in soft_references)
378 LoadAssembly (r, true);
383 static void SetupDefaultDefines ()
385 defines = new ArrayList ();
386 defines.Add ("__MonoCS__");
389 static string [] LoadArgs (string file)
392 ArrayList args = new ArrayList ();
395 f = new StreamReader (file);
400 StringBuilder sb = new StringBuilder ();
402 while ((line = f.ReadLine ()) != null){
405 for (int i = 0; i < t; i++){
408 if (c == '"' || c == '\''){
411 for (i++; i < t; i++){
418 } else if (c == ' '){
420 args.Add (sb.ToString ());
427 args.Add (sb.ToString ());
432 string [] ret_value = new string [args.Count];
433 args.CopyTo (ret_value, 0);
439 // Returns the directory where the system assemblies are installed
441 static string GetSystemDir ()
443 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
445 foreach (Assembly a in assemblies){
446 string codebase = a.Location;
447 string fn = System.IO.Path.GetFileName (codebase);
448 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
449 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
453 Report.Error (-15, "Can not compute my system path");
458 // Given a path specification, splits the path from the file/pattern
460 static void SplitPathAndPattern (string spec, out string path, out string pattern)
462 int p = spec.LastIndexOf ('/');
465 // Windows does not like /file.cs, switch that to:
470 pattern = spec.Substring (1);
472 path = spec.Substring (0, p);
473 pattern = spec.Substring (p + 1);
478 p = spec.LastIndexOf ('\\');
480 path = spec.Substring (0, p);
481 pattern = spec.Substring (p + 1);
489 static void ProcessFile (string f)
491 if (first_source == null)
494 Location.AddFile (f);
497 static void ProcessFiles ()
499 Location.Initialize ();
501 foreach (SourceFile file in Location.SourceFiles) {
503 tokenize_file (file);
510 static void CompileFiles (string spec, bool recurse)
512 string path, pattern;
514 SplitPathAndPattern (spec, out path, out pattern);
515 if (pattern.IndexOf ('*') == -1){
520 string [] files = null;
522 files = Directory.GetFiles (path, pattern);
523 } catch (System.IO.DirectoryNotFoundException) {
524 Report.Error (2001, "Source file `" + spec + "' could not be found");
526 } catch (System.IO.IOException){
527 Report.Error (2001, "Source file `" + spec + "' could not be found");
530 foreach (string f in files) {
537 string [] dirs = null;
540 dirs = Directory.GetDirectories (path);
544 foreach (string d in dirs) {
546 // Don't include path in this string, as each
547 // directory entry already does
548 CompileFiles (d + "/" + pattern, true);
552 static void DefineDefaultConfig ()
555 // For now the "default config" is harcoded into the compiler
556 // we can move this outside later
558 string [] default_config = {
563 // Is it worth pre-loading all this stuff?
566 "System.Configuration.Install",
569 "System.DirectoryServices",
570 "System.Drawing.Design",
572 "System.EnterpriseServices",
575 "System.Runtime.Remoting",
576 "System.Runtime.Serialization.Formatters.Soap",
578 "System.ServiceProcess",
580 "System.Web.RegularExpressions",
581 "System.Web.Services",
582 "System.Windows.Forms"
587 foreach (string def in default_config)
588 soft_references.Insert (p++, def);
591 static void SetOutputFile (string name)
596 static void SetWarningLevel (string s)
601 level = Int32.Parse (s);
605 "--wlevel requires a value from 0 to 4");
606 Environment.Exit (1);
608 if (level < 0 || level > 4){
609 Report.Error (1900, "Warning level must be 0 to 4");
610 Environment.Exit (1);
612 RootContext.WarningLevel = level;
613 TestWarningConflict ();
616 static void TestWarningConflict ()
618 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
619 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
620 Environment.Exit (1);
624 static void SetupV2 ()
626 RootContext.V2 = true;
627 defines.Add ("__V2__");
630 static void Version ()
632 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
633 Console.WriteLine ("Mono C# compiler version {0}", version);
634 Environment.Exit (0);
638 // Currently handles the Unix-like command line options, but will be
639 // deprecated in favor of the CSCParseOption, which will also handle the
640 // options that start with a dash in the future.
642 static bool UnixParseOption (string arg, ref string [] args, ref int i)
646 parser_verbose = true;
661 case "--main": case "-m":
662 if ((i + 1) >= args.Length){
664 Environment.Exit (1);
666 RootContext.MainClass = args [++i];
670 RootContext.Unsafe = true;
673 case "/?": case "/h": case "/help":
676 Environment.Exit (0);
680 if ((i + 1) >= args.Length){
682 Environment.Exit (1);
684 defines.Add (args [++i]);
687 case "--show-counters":
688 show_counters = true;
691 case "--expect-error": {
696 args [++i], NumberStyles.AllowLeadingSign);
697 Report.ExpectedError = code;
699 Report.Error (-14, "Invalid number specified");
710 if ((i + 1) >= args.Length){
712 Environment.Exit (1);
714 SetOutputFile (args [++i]);
718 RootContext.Checked = true;
722 Report.Stacktrace = true;
725 case "--linkresource":
727 if ((i + 1) >= args.Length){
729 Report.Error (5, "Missing argument to --linkres");
730 Environment.Exit (1);
732 if (resources == null)
733 resources = new ArrayList ();
735 resources.Add (args [++i]);
740 if ((i + 1) >= args.Length){
742 Report.Error (5, "Missing argument to --resource");
743 Environment.Exit (1);
745 if (embedded_resources == null)
746 embedded_resources = new ArrayList ();
748 embedded_resources.Add (args [++i]);
752 if ((i + 1) >= args.Length){
753 Environment.Exit (1);
757 string type = args [++i];
760 RootContext.Target = Target.Library;
761 RootContext.TargetExt = ".dll";
765 RootContext.Target = Target.Exe;
769 RootContext.Target = Target.WinExe;
773 RootContext.Target = Target.Module;
774 RootContext.TargetExt = ".dll";
778 Environment.Exit (1);
784 if ((i + 1) >= args.Length){
786 Environment.Exit (1);
789 references.Add (args [++i]);
793 if ((i + 1) >= args.Length){
795 Environment.Exit (1);
797 link_paths.Add (args [++i]);
801 RootContext.StdLib = false;
809 Report.WarningsAreErrors = true;
810 TestWarningConflict();
814 if ((i + 1) >= args.Length){
816 Environment.Exit (1);
821 warn = Int32.Parse (args [++i]);
824 Environment.Exit (1);
826 Report.SetIgnoreWarning (warn);
830 if ((i + 1) >= args.Length){
833 "--wlevel requires a value from 0 to 4");
834 Environment.Exit (1);
837 SetWarningLevel (args [++i]);
841 if ((i + 1) >= args.Length){
842 Report.Error (5, "--mcs-debug requires an argument");
843 Environment.Exit (1);
847 Report.DebugFlags = Int32.Parse (args [++i]);
849 Report.Error (5, "Invalid argument to --mcs-debug");
850 Environment.Exit (1);
859 if ((i + 1) >= args.Length){
860 Report.Error (5, "--recurse requires an argument");
861 Environment.Exit (1);
863 CompileFiles (args [++i], true);
868 last_time = first_time = DateTime.Now;
875 case "--debug": case "-g":
876 want_debugging_support = true;
880 load_default_config = false;
888 // Currently it is very basic option parsing, but eventually, this will
889 // be the complete option parser
891 static bool CSCParseOption (string option, ref string [] args, ref int i)
893 int idx = option.IndexOf (':');
900 arg = option.Substring (0, idx);
902 value = option.Substring (idx + 1);
913 RootContext.Target = Target.Exe;
917 RootContext.Target = Target.WinExe;
921 RootContext.Target = Target.Library;
922 RootContext.TargetExt = ".dll";
926 RootContext.Target = Target.Module;
927 RootContext.TargetExt = ".netmodule";
932 Environment.Exit (1);
940 Environment.Exit (1);
942 SetOutputFile (value);
949 case "/incremental+":
950 case "/incremental-":
960 Environment.Exit (1);
963 defs = value.Split (new Char [] {';', ','});
964 foreach (string d in defs){
971 case "/linkresource":
973 Report.Error (5, arg + " requires an argument");
974 Environment.Exit (1);
976 if (resources == null)
977 resources = new ArrayList ();
979 resources.Add (value);
985 Report.Error (5, arg + " requires an argument");
986 Environment.Exit (1);
988 if (embedded_resources == null)
989 embedded_resources = new ArrayList ();
991 embedded_resources.Add (value);
996 Report.Error (5, "/recurse requires an argument");
997 Environment.Exit (1);
999 CompileFiles (value, true);
1003 case "/reference": {
1005 Report.Error (5, arg + " requires an argument");
1006 Environment.Exit (1);
1009 string [] refs = value.Split (new char [] { ';', ',' });
1010 foreach (string r in refs){
1015 case "/addmodule": {
1017 Report.Error (5, arg + " requires an argument");
1018 Environment.Exit (1);
1021 string [] refs = value.Split (new char [] { ';', ',' });
1022 foreach (string r in refs){
1029 Report.Error (5, arg + " requires an argument");
1030 Environment.Exit (1);
1033 win32ResourceFile = value;
1036 case "/win32icon": {
1038 Report.Error (5, arg + " requires an argument");
1039 Environment.Exit (1);
1042 win32IconFile = value;
1047 Report.Error (5, arg + " requires an argument");
1048 Environment.Exit (1);
1050 // TODO handle the /doc argument to generate xml doc
1057 Report.Error (5, "/lib requires an argument");
1058 Environment.Exit (1);
1061 libdirs = value.Split (new Char [] { ',' });
1062 foreach (string dir in libdirs)
1063 link_paths.Add (dir);
1069 want_debugging_support = true;
1074 RootContext.Checked = true;
1078 RootContext.Checked = false;
1083 RootContext.Unsafe = true;
1087 RootContext.Unsafe = false;
1090 case "/warnaserror":
1091 case "/warnaserror+":
1092 Report.WarningsAreErrors = true;
1093 TestWarningConflict();
1096 case "/warnaserror-":
1097 Report.WarningsAreErrors = false;
1101 SetWarningLevel (value);
1108 Report.Error (5, "/nowarn requires an argument");
1109 Environment.Exit (1);
1112 warns = value.Split (new Char [] {','});
1113 foreach (string wc in warns){
1115 int warn = Int32.Parse (wc);
1117 throw new ArgumentOutOfRangeException("warn");
1119 Report.SetIgnoreWarning (warn);
1121 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1122 Environment.Exit (1);
1129 load_default_config = true;
1134 load_default_config = false;
1140 Environment.Exit (0);
1146 Report.Error (5, arg + " requires an argument");
1147 Environment.Exit (1);
1149 RootContext.MainClass = value;
1154 RootContext.StdLib = false;
1158 RootContext.StdLib = true;
1165 if (value == String.Empty) {
1166 Report.Error (5, arg + " requires an argument");
1167 Environment.Exit (1);
1169 RootContext.StrongNameKeyFile = value;
1171 case "/keycontainer":
1172 if (value == String.Empty) {
1173 Report.Error (5, arg + " requires an argument");
1174 Environment.Exit (1);
1176 RootContext.StrongNameKeyContainer = value;
1179 RootContext.StrongNameDelaySign = true;
1182 RootContext.StrongNameDelaySign = false;
1193 if (value == "utf8"){
1194 encoding = new UTF8Encoding();
1195 using_default_encoder = false;
1198 if (value == "reset"){
1200 // 28591 is the code page for ISO-8859-1 encoding.
1203 using_default_encoder = true;
1207 cp = Int32.Parse (value);
1208 encoding = Encoding.GetEncoding (cp);
1209 using_default_encoder = false;
1211 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1212 Environment.Exit (1);
1216 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1217 //Environment.Exit (1);
1222 /// Parses the arguments, and drives the compilation
1227 /// TODO: Mostly structured to debug the compiler
1228 /// now, needs to be turned into a real driver soon.
1230 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1231 internal static bool MainDriver (string [] args)
1234 bool parsing_options = true;
1237 encoding = Encoding.GetEncoding (28591);
1239 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1240 encoding = Encoding.GetEncoding (1252);
1243 references = new ArrayList ();
1244 soft_references = new ArrayList ();
1245 modules = new ArrayList ();
1246 link_paths = new ArrayList ();
1248 SetupDefaultDefines ();
1253 // This is not required because Assembly.Load knows about this
1257 int argc = args.Length;
1258 for (i = 0; i < argc; i++){
1259 string arg = args [i];
1261 if (arg.StartsWith ("@")){
1262 string [] new_args, extra_args;
1263 string response_file = arg.Substring (1);
1265 if (response_file_list == null)
1266 response_file_list = new Hashtable ();
1268 if (response_file_list.Contains (response_file)){
1270 1515, "Response file `" + response_file +
1271 "' specified multiple times");
1272 Environment.Exit (1);
1275 response_file_list.Add (response_file, response_file);
1277 extra_args = LoadArgs (response_file);
1278 if (extra_args == null){
1279 Report.Error (2011, "Unable to open response file: " +
1284 new_args = new string [extra_args.Length + argc];
1285 args.CopyTo (new_args, 0);
1286 extra_args.CopyTo (new_args, argc);
1288 argc = new_args.Length;
1292 if (parsing_options){
1294 parsing_options = false;
1298 if (arg.StartsWith ("-")){
1299 if (UnixParseOption (arg, ref args, ref i))
1303 string csc_opt = "/" + arg.Substring (1);
1304 if (CSCParseOption (csc_opt, ref args, ref i))
1307 if (arg.StartsWith ("/")){
1308 if (CSCParseOption (arg, ref args, ref i))
1314 CompileFiles (arg, false);
1323 // If we are an exe, require a source file for the entry point
1325 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1326 if (first_source == null){
1327 Report.Error (2008, "No files to compile were specified");
1334 // If there is nothing to put in the assembly, and we are not a library
1336 if (first_source == null && embedded_resources == null && resources == null){
1337 Report.Error (2008, "No files to compile were specified");
1341 if (Report.Errors > 0)
1347 Tokenizer.Cleanup ();
1350 // Load Core Library for default compilation
1352 if (RootContext.StdLib)
1353 references.Insert (0, "mscorlib");
1355 if (load_default_config)
1356 DefineDefaultConfig ();
1358 if (Report.Errors > 0){
1363 // Load assemblies required
1366 ShowTime ("Loading references");
1367 link_paths.Add (GetSystemDir ());
1371 ShowTime (" References loaded");
1373 if (Report.Errors > 0){
1380 if (output_file == null){
1381 int pos = first_source.LastIndexOf ('.');
1384 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1386 output_file = first_source + RootContext.TargetExt;
1389 CodeGen.Init (output_file, output_file, want_debugging_support);
1391 if (RootContext.Target == Target.Module) {
1392 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1393 if (module_only == null) {
1394 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1395 Environment.Exit (1);
1398 module_only.SetValue (CodeGen.Assembly.Builder, true, null);
1401 TypeManager.AddModule (CodeGen.Module.Builder);
1403 if (modules.Count > 0) {
1404 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1405 if (adder_method == null) {
1406 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1407 Environment.Exit (1);
1410 foreach (string module in modules)
1411 LoadModule (adder_method, module);
1414 TypeManager.ComputeNamespaces ();
1417 // Before emitting, we need to get the core
1418 // types emitted from the user defined types
1419 // or from the system ones.
1422 ShowTime ("Initializing Core Types");
1423 if (!RootContext.StdLib){
1424 RootContext.ResolveCore ();
1425 if (Report.Errors > 0)
1429 TypeManager.InitCoreTypes ();
1431 ShowTime (" Core Types done");
1434 // The second pass of the compiler
1437 ShowTime ("Resolving tree");
1438 RootContext.ResolveTree ();
1439 if (Report.Errors > 0)
1442 ShowTime ("Populate tree");
1443 if (!RootContext.StdLib)
1444 RootContext.BootCorlib_PopulateCoreTypes ();
1445 RootContext.PopulateTypes ();
1446 RootContext.DefineTypes ();
1448 TypeManager.InitCodeHelpers ();
1451 // Verify using aliases now
1453 Namespace.VerifyUsing ();
1455 if (Report.Errors > 0){
1460 // The code generator
1463 ShowTime ("Emitting code");
1464 ShowTotalTime ("Total so far");
1465 RootContext.EmitCode ();
1469 if (Report.Errors > 0){
1474 ShowTime ("Closing types");
1476 RootContext.CloseTypes ();
1478 PEFileKinds k = PEFileKinds.ConsoleApplication;
1480 switch (RootContext.Target) {
1481 case Target.Library:
1483 k = PEFileKinds.Dll; break;
1485 k = PEFileKinds.ConsoleApplication; break;
1487 k = PEFileKinds.WindowApplication; break;
1490 if (RootContext.NeedsEntryPoint) {
1491 MethodInfo ep = RootContext.EntryPoint;
1494 if (Report.Errors == 0)
1495 Report.Error (5001, "Program " + output_file +
1496 " does not have an entry point defined");
1500 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1501 } else if (RootContext.MainClass != null) {
1502 Report.Error (2017, "Can not specify -main: when building module or library");
1506 // Add the resources
1508 if (resources != null){
1509 foreach (string spec in resources){
1513 cp = spec.IndexOf (',');
1515 file = spec.Substring (0, cp);
1516 res = spec.Substring (cp + 1);
1520 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1524 if (embedded_resources != null){
1525 object[] margs = new object [2];
1526 Type[] argst = new Type [2];
1527 argst [0] = argst [1] = typeof (string);
1529 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1530 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1531 null, CallingConventions.Any, argst, null);
1533 if (embed_res == null) {
1534 Report.Warning (0, new Location (-1),
1535 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1537 foreach (string spec in embedded_resources) {
1540 cp = spec.IndexOf (',');
1542 margs [0] = spec.Substring (cp + 1);
1543 margs [1] = spec.Substring (0, cp);
1546 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1549 if (File.Exists ((string) margs [1]))
1550 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1552 Report.Error (1566, "Can not find the resource " + margs [1]);
1559 // Add Win32 resources
1562 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1564 if (win32ResourceFile != null) {
1566 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1568 catch (ArgumentException) {
1569 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1573 if (win32IconFile != null) {
1574 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1575 if (define_icon == null) {
1576 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1578 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1581 if (Report.Errors > 0)
1584 CodeGen.Save (output_file);
1586 ShowTime ("Saved output");
1587 ShowTotalTime ("Total");
1590 Timer.ShowTimers ();
1592 if (Report.ExpectedError != 0) {
1593 if (Report.Errors == 0) {
1594 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1595 "No other errors reported.");
1597 Environment.Exit (2);
1599 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1600 "However, other errors were reported.");
1602 Environment.Exit (1);
1610 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1611 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1613 return (Report.Errors == 0);
1619 // This is the only public entry point
1621 public class CompilerCallableEntryPoint : MarshalByRefObject {
1622 static bool used = false;
1624 public bool InvokeCompiler (string [] args)
1628 bool ok = Driver.MainDriver (args);
1629 return ok && Report.Errors == 0;
1632 public void Reset ()