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;
22 Library, Exe, Module, WinExe
26 /// The compiler driver.
32 // Assemblies references to be linked. Initialized with
34 static ArrayList references;
37 // If any of these fail, we ignore the problem. This is so
38 // that we can list all the assemblies in Windows and not fail
39 // if they are missing on Linux.
41 static ArrayList soft_references;
44 // Modules to be linked
46 static ArrayList modules;
49 static ArrayList link_paths;
51 // Whether we want Yacc to output its progress
52 static bool yacc_verbose = false;
54 // Whether we want to only run the tokenizer
55 static bool tokenize = false;
57 static string first_source;
59 static bool want_debugging_support = false;
61 static bool parse_only = false;
62 static bool timestamps = false;
63 static bool pause = false;
64 static bool show_counters = false;
65 public static bool parser_verbose = false;
68 // Whether to load the initial config file (what CSC.RSP has by default)
70 static bool load_default_config = true;
72 static Hashtable response_file_list;
75 // A list of resource files
77 static ArrayList resources;
78 static ArrayList embedded_resources;
79 static string win32ResourceFile;
80 static string win32IconFile;
83 // An array of the defines from the command line
85 static ArrayList defines;
90 static string output_file = null;
93 // Last time we took the time
95 static DateTime last_time, first_time;
98 // Encoding: ISO-Latin1 is 28591
100 static Encoding encoding;
103 // Whether the user has specified a different encoder manually
105 static bool using_default_encoder = true;
108 // The system version we are using, if not specified on the commandline we
109 // will use the same version as corlib for looking for libraries in the GAC.
111 static string sys_version;
113 public static void ShowTime (string msg)
118 DateTime now = DateTime.Now;
119 TimeSpan span = now - last_time;
123 "[{0:00}:{1:000}] {2}",
124 (int) span.TotalSeconds, span.Milliseconds, msg);
127 public static void ShowTotalTime (string msg)
132 DateTime now = DateTime.Now;
133 TimeSpan span = now - first_time;
137 "[{0:00}:{1:000}] {2}",
138 (int) span.TotalSeconds, span.Milliseconds, msg);
141 static void tokenize_file (SourceFile file)
146 input = File.OpenRead (file.Name);
148 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
153 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
154 Tokenizer lexer = new Tokenizer (reader, file, defines);
155 int token, tokens = 0, errors = 0;
157 while ((token = lexer.token ()) != Token.EOF){
159 if (token == Token.ERROR)
162 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
168 // MonoTODO("Change error code for aborted compilation to something reasonable")]
169 static void parse (SourceFile file)
175 input = File.OpenRead (file.Name);
177 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
181 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
183 parser = new CSharpParser (reader, file, defines);
184 parser.yacc_verbose_flag = yacc_verbose;
187 } catch (Exception ex) {
188 Report.Error(666, "Compilation aborted: " + ex);
197 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
198 "mcs [options] source-files\n" +
199 " --about About the Mono C# compiler\n" +
200 " -checked[+|-] Set default context to checked\n" +
201 " -codepage:ID Sets code page to the one in ID\n" +
202 " (number, `utf8' or `reset')\n" +
203 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
204 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
205 " -debug[+|-] Generate debugging information\n" +
206 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
207 " -doc:FILE XML Documentation file to generate\n" +
208 " -g Generate debugging information\n" +
209 " --fatal Makes errors fatal\n" +
210 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
211 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
212 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
213 " -main:class Specified the class that contains the entry point\n" +
214 " -noconfig[+|-] Disables implicit references to assemblies\n" +
215 " -nostdlib[+|-] Does not load core libraries\n" +
216 " -nowarn:W1[,W2] Disables one or more warnings\n" +
217 " -out:FNAME Specifies output file\n" +
218 " --parse Only parses the source file\n" +
219 " --expect-error X Expect that error X will be encountered\n" +
220 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
221 " -reference:ASS References the specified assembly (-r:ASS)\n" +
222 " --stacktrace Shows stack trace at error location\n" +
223 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
224 " library, module), (short: /t:)\n" +
225 " --timestamp Displays time stamps of various compiler events\n" +
226 " -unsafe[+|-] Allows unsafe code\n" +
227 " -warnaserror[+|-] Treat warnings as errors\n" +
228 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
229 " -v Verbose parsing (for debugging the parser)\n" +
230 " -2 Enables experimental C# features\n" +
233 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
234 " -resource:FILE[,ID] Embed FILE as a resource\n" +
235 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
236 " -win32icon:FILE Use this icon for the output\n" +
237 " --mcs-debug X Sets MCS debugging level to X\n" +
238 " @file Read response file for more options\n\n" +
239 "Options can be of the form -option or /option");
242 static void TargetUsage ()
244 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
250 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
251 "The compiler source code is released under the terms of the GNU GPL\n\n" +
253 "For more information on Mono, visit the project Web site\n" +
254 " http://www.go-mono.com\n\n" +
256 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
257 Environment.Exit (0);
260 public static int counter1, counter2;
262 public static int Main (string[] args)
264 RootContext.V2 = true;
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 a = LoadAssemblyFromGac (assembly);
300 a = Assembly.Load (assembly);
302 TypeManager.AddAssembly (a);
304 } catch (FileNotFoundException){
305 foreach (string dir in link_paths){
306 string full_path = Path.Combine (dir, assembly);
307 if (!assembly.EndsWith (".dll"))
311 a = Assembly.LoadFrom (full_path);
312 TypeManager.AddAssembly (a);
314 } catch (FileNotFoundException ff) {
315 total_log += ff.FusionLog;
320 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
321 Console.WriteLine ("Log: \n" + total_log);
323 } catch (BadImageFormatException f) {
324 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
325 } catch (FileLoadException f){
326 Report.Error(6, "Cannot load assembly " + f.FusionLog);
327 } catch (ArgumentNullException){
328 Report.Error(6, "Cannot load assembly (null argument)");
332 static Assembly LoadAssemblyFromGac (string name)
334 PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath",
335 BindingFlags.Static|BindingFlags.NonPublic);
340 MethodInfo gac_get = gac.GetGetMethod (true);
341 string use_name = name;
345 if (name.EndsWith (".dll"))
346 use_name = name.Substring (0, name.Length - 4);
348 asmb_path = Path.Combine ((string) gac_get.Invoke (null, null), use_name);
350 if (!Directory.Exists (asmb_path))
353 canidates = Directory.GetDirectories (asmb_path, GetSysVersion () + "*");
354 if (canidates.Length == 0)
355 canidates = Directory.GetDirectories (asmb_path);
356 if (canidates.Length == 0)
359 Assembly a = Assembly.LoadFrom (Path.Combine (canidates [0], use_name + ".dll"));
361 } catch (Exception e) {
366 static string GetSysVersion ()
368 if (sys_version != null)
370 sys_version = typeof (object).Assembly.GetName ().Version.ToString ();
374 static public void LoadModule (MethodInfo adder_method, string module)
377 string total_log = "";
381 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
383 catch (TargetInvocationException ex) {
384 throw ex.InnerException;
386 TypeManager.AddModule (m);
389 catch (FileNotFoundException){
390 foreach (string dir in link_paths){
391 string full_path = Path.Combine (dir, module);
392 if (!module.EndsWith (".netmodule"))
393 full_path += ".netmodule";
397 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
399 catch (TargetInvocationException ex) {
400 throw ex.InnerException;
402 TypeManager.AddModule (m);
404 } catch (FileNotFoundException ff) {
405 total_log += ff.FusionLog;
409 Report.Error (6, "Cannot find module `" + module + "'" );
410 Console.WriteLine ("Log: \n" + total_log);
411 } catch (BadImageFormatException f) {
412 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
413 } catch (FileLoadException f){
414 Report.Error(6, "Cannot load module " + f.FusionLog);
415 } catch (ArgumentNullException){
416 Report.Error(6, "Cannot load module (null argument)");
421 /// Loads all assemblies referenced on the command line
423 static public void LoadReferences ()
425 foreach (string r in references)
426 LoadAssembly (r, false);
428 foreach (string r in soft_references)
429 LoadAssembly (r, true);
434 static void SetupDefaultDefines ()
436 defines = new ArrayList ();
437 defines.Add ("__MonoCS__");
440 static string [] LoadArgs (string file)
443 ArrayList args = new ArrayList ();
446 f = new StreamReader (file);
451 StringBuilder sb = new StringBuilder ();
453 while ((line = f.ReadLine ()) != null){
456 for (int i = 0; i < t; i++){
459 if (c == '"' || c == '\''){
462 for (i++; i < t; i++){
469 } else if (c == ' '){
471 args.Add (sb.ToString ());
478 args.Add (sb.ToString ());
483 string [] ret_value = new string [args.Count];
484 args.CopyTo (ret_value, 0);
490 // Returns the directory where the system assemblies are installed
492 static string GetSystemDir ()
494 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
496 foreach (Assembly a in assemblies){
497 string codebase = a.Location;
498 string fn = System.IO.Path.GetFileName (codebase);
499 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
500 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
504 Report.Error (-15, "Can not compute my system path");
509 // Given a path specification, splits the path from the file/pattern
511 static void SplitPathAndPattern (string spec, out string path, out string pattern)
513 int p = spec.LastIndexOf ('/');
516 // Windows does not like /file.cs, switch that to:
521 pattern = spec.Substring (1);
523 path = spec.Substring (0, p);
524 pattern = spec.Substring (p + 1);
529 p = spec.LastIndexOf ('\\');
531 path = spec.Substring (0, p);
532 pattern = spec.Substring (p + 1);
540 static void ProcessFile (string f)
542 if (first_source == null)
545 Location.AddFile (f);
548 static void ProcessFiles ()
550 Location.Initialize ();
552 foreach (SourceFile file in Location.SourceFiles) {
554 tokenize_file (file);
561 static void CompileFiles (string spec, bool recurse)
563 string path, pattern;
565 SplitPathAndPattern (spec, out path, out pattern);
566 if (pattern.IndexOf ('*') == -1){
571 string [] files = null;
573 files = Directory.GetFiles (path, pattern);
574 } catch (System.IO.DirectoryNotFoundException) {
575 Report.Error (2001, "Source file `" + spec + "' could not be found");
577 } catch (System.IO.IOException){
578 Report.Error (2001, "Source file `" + spec + "' could not be found");
581 foreach (string f in files) {
588 string [] dirs = null;
591 dirs = Directory.GetDirectories (path);
595 foreach (string d in dirs) {
597 // Don't include path in this string, as each
598 // directory entry already does
599 CompileFiles (d + "/" + pattern, true);
603 static void DefineDefaultConfig ()
606 // For now the "default config" is harcoded into the compiler
607 // we can move this outside later
609 string [] default_config = {
614 // Is it worth pre-loading all this stuff?
617 "System.Configuration.Install",
620 "System.DirectoryServices",
621 "System.Drawing.Design",
623 "System.EnterpriseServices",
626 "System.Runtime.Remoting",
627 "System.Runtime.Serialization.Formatters.Soap",
629 "System.ServiceProcess",
631 "System.Web.RegularExpressions",
632 "System.Web.Services",
633 "System.Windows.Forms"
638 foreach (string def in default_config)
639 soft_references.Insert (p++, def);
642 static void SetOutputFile (string name)
647 static void SetWarningLevel (string s)
652 level = Int32.Parse (s);
656 "--wlevel requires a value from 0 to 4");
657 Environment.Exit (1);
659 if (level < 0 || level > 4){
660 Report.Error (1900, "Warning level must be 0 to 4");
661 Environment.Exit (1);
663 RootContext.WarningLevel = level;
664 TestWarningConflict ();
667 static void TestWarningConflict ()
669 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
670 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
671 Environment.Exit (1);
675 static void SetupV2 ()
677 RootContext.V2 = true;
678 defines.Add ("__V2__");
681 static void Version ()
683 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
684 Console.WriteLine ("Mono C# compiler version {0}", version);
685 Environment.Exit (0);
689 // Currently handles the Unix-like command line options, but will be
690 // deprecated in favor of the CSCParseOption, which will also handle the
691 // options that start with a dash in the future.
693 static bool UnixParseOption (string arg, ref string [] args, ref int i)
697 parser_verbose = true;
712 case "--main": case "-m":
713 if ((i + 1) >= args.Length){
715 Environment.Exit (1);
717 RootContext.MainClass = args [++i];
721 RootContext.Unsafe = true;
724 case "/?": case "/h": case "/help":
727 Environment.Exit (0);
731 if ((i + 1) >= args.Length){
733 Environment.Exit (1);
735 defines.Add (args [++i]);
738 case "--show-counters":
739 show_counters = true;
742 case "--expect-error": {
747 args [++i], NumberStyles.AllowLeadingSign);
748 Report.ExpectedError = code;
750 Report.Error (-14, "Invalid number specified");
761 if ((i + 1) >= args.Length){
763 Environment.Exit (1);
765 SetOutputFile (args [++i]);
769 RootContext.Checked = true;
773 Report.Stacktrace = true;
776 case "--linkresource":
778 if ((i + 1) >= args.Length){
780 Report.Error (5, "Missing argument to --linkres");
781 Environment.Exit (1);
783 if (resources == null)
784 resources = new ArrayList ();
786 resources.Add (args [++i]);
791 if ((i + 1) >= args.Length){
793 Report.Error (5, "Missing argument to --resource");
794 Environment.Exit (1);
796 if (embedded_resources == null)
797 embedded_resources = new ArrayList ();
799 embedded_resources.Add (args [++i]);
803 if ((i + 1) >= args.Length){
804 Environment.Exit (1);
808 string type = args [++i];
811 RootContext.Target = Target.Library;
812 RootContext.TargetExt = ".dll";
816 RootContext.Target = Target.Exe;
820 RootContext.Target = Target.WinExe;
824 RootContext.Target = Target.Module;
825 RootContext.TargetExt = ".dll";
829 Environment.Exit (1);
835 if ((i + 1) >= args.Length){
837 Environment.Exit (1);
840 references.Add (args [++i]);
844 if ((i + 1) >= args.Length){
846 Environment.Exit (1);
848 link_paths.Add (args [++i]);
852 RootContext.StdLib = false;
860 Report.WarningsAreErrors = true;
861 TestWarningConflict();
865 if ((i + 1) >= args.Length){
867 Environment.Exit (1);
872 warn = Int32.Parse (args [++i]);
875 Environment.Exit (1);
877 Report.SetIgnoreWarning (warn);
881 if ((i + 1) >= args.Length){
884 "--wlevel requires a value from 0 to 4");
885 Environment.Exit (1);
888 SetWarningLevel (args [++i]);
892 if ((i + 1) >= args.Length){
893 Report.Error (5, "--mcs-debug requires an argument");
894 Environment.Exit (1);
898 Report.DebugFlags = Int32.Parse (args [++i]);
900 Report.Error (5, "Invalid argument to --mcs-debug");
901 Environment.Exit (1);
910 if ((i + 1) >= args.Length){
911 Report.Error (5, "--recurse requires an argument");
912 Environment.Exit (1);
914 CompileFiles (args [++i], true);
919 last_time = first_time = DateTime.Now;
926 case "--debug": case "-g":
927 want_debugging_support = true;
931 load_default_config = false;
939 // Currently it is very basic option parsing, but eventually, this will
940 // be the complete option parser
942 static bool CSCParseOption (string option, ref string [] args, ref int i)
944 int idx = option.IndexOf (':');
951 arg = option.Substring (0, idx);
953 value = option.Substring (idx + 1);
964 RootContext.Target = Target.Exe;
968 RootContext.Target = Target.WinExe;
972 RootContext.Target = Target.Library;
973 RootContext.TargetExt = ".dll";
977 RootContext.Target = Target.Module;
978 RootContext.TargetExt = ".netmodule";
983 Environment.Exit (1);
991 Environment.Exit (1);
993 SetOutputFile (value);
1000 case "/incremental+":
1001 case "/incremental-":
1011 Environment.Exit (1);
1014 defs = value.Split (new Char [] {';', ','});
1015 foreach (string d in defs){
1022 case "/linkresource":
1024 Report.Error (5, arg + " requires an argument");
1025 Environment.Exit (1);
1027 if (resources == null)
1028 resources = new ArrayList ();
1030 resources.Add (value);
1036 Report.Error (5, arg + " requires an argument");
1037 Environment.Exit (1);
1039 if (embedded_resources == null)
1040 embedded_resources = new ArrayList ();
1042 embedded_resources.Add (value);
1047 Report.Error (5, "/recurse requires an argument");
1048 Environment.Exit (1);
1050 CompileFiles (value, true);
1054 case "/reference": {
1056 Report.Error (5, arg + " requires an argument");
1057 Environment.Exit (1);
1060 string [] refs = value.Split (new char [] { ';', ',' });
1061 foreach (string r in refs){
1066 case "/addmodule": {
1068 Report.Error (5, arg + " requires an argument");
1069 Environment.Exit (1);
1072 string [] refs = value.Split (new char [] { ';', ',' });
1073 foreach (string r in refs){
1080 Report.Error (5, arg + " requires an argument");
1081 Environment.Exit (1);
1084 win32ResourceFile = value;
1087 case "/win32icon": {
1089 Report.Error (5, arg + " requires an argument");
1090 Environment.Exit (1);
1093 win32IconFile = value;
1098 Report.Error (5, arg + " requires an argument");
1099 Environment.Exit (1);
1101 // TODO handle the /doc argument to generate xml doc
1108 Report.Error (5, "/lib requires an argument");
1109 Environment.Exit (1);
1112 libdirs = value.Split (new Char [] { ',' });
1113 foreach (string dir in libdirs)
1114 link_paths.Add (dir);
1120 want_debugging_support = true;
1125 RootContext.Checked = true;
1129 RootContext.Checked = false;
1137 RootContext.VerifyClsCompliance = false;
1142 RootContext.Unsafe = true;
1146 RootContext.Unsafe = false;
1149 case "/warnaserror":
1150 case "/warnaserror+":
1151 Report.WarningsAreErrors = true;
1152 TestWarningConflict();
1155 case "/warnaserror-":
1156 Report.WarningsAreErrors = false;
1160 SetWarningLevel (value);
1167 Report.Error (5, "/nowarn requires an argument");
1168 Environment.Exit (1);
1171 warns = value.Split (new Char [] {','});
1172 foreach (string wc in warns){
1174 int warn = Int32.Parse (wc);
1176 throw new ArgumentOutOfRangeException("warn");
1178 Report.SetIgnoreWarning (warn);
1180 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1181 Environment.Exit (1);
1188 load_default_config = true;
1193 load_default_config = false;
1199 Environment.Exit (0);
1205 Report.Error (5, arg + " requires an argument");
1206 Environment.Exit (1);
1208 RootContext.MainClass = value;
1213 RootContext.StdLib = false;
1217 RootContext.StdLib = true;
1224 if (value == String.Empty) {
1225 Report.Error (5, arg + " requires an argument");
1226 Environment.Exit (1);
1228 RootContext.StrongNameKeyFile = value;
1230 case "/keycontainer":
1231 if (value == String.Empty) {
1232 Report.Error (5, arg + " requires an argument");
1233 Environment.Exit (1);
1235 RootContext.StrongNameKeyContainer = value;
1238 RootContext.StrongNameDelaySign = true;
1241 RootContext.StrongNameDelaySign = false;
1252 if (value == "utf8"){
1253 encoding = new UTF8Encoding();
1254 using_default_encoder = false;
1257 if (value == "reset"){
1259 // 28591 is the code page for ISO-8859-1 encoding.
1262 using_default_encoder = true;
1266 cp = Int32.Parse (value);
1267 encoding = Encoding.GetEncoding (cp);
1268 using_default_encoder = false;
1270 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1271 Environment.Exit (1);
1275 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1276 //Environment.Exit (1);
1281 /// Parses the arguments, and drives the compilation
1286 /// TODO: Mostly structured to debug the compiler
1287 /// now, needs to be turned into a real driver soon.
1289 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1290 internal static bool MainDriver (string [] args)
1293 bool parsing_options = true;
1295 Console.WriteLine ("ALPHA SOFTWARE: Mono C# Compiler {0} for Generics",
1296 Assembly.GetExecutingAssembly ().GetName ().Version.ToString ());
1298 encoding = Encoding.GetEncoding (28591);
1300 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1301 encoding = Encoding.GetEncoding (1252);
1304 references = new ArrayList ();
1305 soft_references = new ArrayList ();
1306 modules = new ArrayList ();
1307 link_paths = new ArrayList ();
1309 SetupDefaultDefines ();
1314 // This is not required because Assembly.Load knows about this
1318 int argc = args.Length;
1319 for (i = 0; i < argc; i++){
1320 string arg = args [i];
1322 if (arg.StartsWith ("@")){
1323 string [] new_args, extra_args;
1324 string response_file = arg.Substring (1);
1326 if (response_file_list == null)
1327 response_file_list = new Hashtable ();
1329 if (response_file_list.Contains (response_file)){
1331 1515, "Response file `" + response_file +
1332 "' specified multiple times");
1333 Environment.Exit (1);
1336 response_file_list.Add (response_file, response_file);
1338 extra_args = LoadArgs (response_file);
1339 if (extra_args == null){
1340 Report.Error (2011, "Unable to open response file: " +
1345 new_args = new string [extra_args.Length + argc];
1346 args.CopyTo (new_args, 0);
1347 extra_args.CopyTo (new_args, argc);
1349 argc = new_args.Length;
1353 if (parsing_options){
1355 parsing_options = false;
1359 if (arg.StartsWith ("-")){
1360 if (UnixParseOption (arg, ref args, ref i))
1364 string csc_opt = "/" + arg.Substring (1);
1365 if (CSCParseOption (csc_opt, ref args, ref i))
1368 if (arg.StartsWith ("/")){
1369 if (CSCParseOption (arg, ref args, ref i))
1375 CompileFiles (arg, false);
1384 // If we are an exe, require a source file for the entry point
1386 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1387 if (first_source == null){
1388 Report.Error (2008, "No files to compile were specified");
1395 // If there is nothing to put in the assembly, and we are not a library
1397 if (first_source == null && embedded_resources == null && resources == null){
1398 Report.Error (2008, "No files to compile were specified");
1402 if (Report.Errors > 0)
1408 Tokenizer.Cleanup ();
1411 // Load Core Library for default compilation
1413 if (RootContext.StdLib)
1414 references.Insert (0, "mscorlib");
1416 if (load_default_config)
1417 DefineDefaultConfig ();
1419 if (Report.Errors > 0){
1424 // Load assemblies required
1427 ShowTime ("Loading references");
1428 link_paths.Add (GetSystemDir ());
1432 ShowTime (" References loaded");
1434 if (Report.Errors > 0){
1441 if (output_file == null){
1442 int pos = first_source.LastIndexOf ('.');
1445 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1447 output_file = first_source + RootContext.TargetExt;
1450 CodeGen.Init (output_file, output_file, want_debugging_support);
1452 if (RootContext.Target == Target.Module) {
1453 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1454 if (module_only == null) {
1455 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1456 Environment.Exit (1);
1459 module_only.SetValue (CodeGen.Assembly.Builder, true, null);
1462 TypeManager.AddModule (CodeGen.Module.Builder);
1464 if (modules.Count > 0) {
1465 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1466 if (adder_method == null) {
1467 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1468 Environment.Exit (1);
1471 foreach (string module in modules)
1472 LoadModule (adder_method, module);
1475 TypeManager.ComputeNamespaces ();
1478 // Before emitting, we need to get the core
1479 // types emitted from the user defined types
1480 // or from the system ones.
1483 ShowTime ("Initializing Core Types");
1484 if (!RootContext.StdLib){
1485 RootContext.ResolveCore ();
1486 if (Report.Errors > 0)
1490 TypeManager.InitCoreTypes ();
1492 ShowTime (" Core Types done");
1495 // The second pass of the compiler
1498 ShowTime ("Resolving tree");
1499 RootContext.ResolveTree ();
1500 if (Report.Errors > 0)
1503 ShowTime ("Populate tree");
1504 if (!RootContext.StdLib)
1505 RootContext.BootCorlib_PopulateCoreTypes ();
1506 RootContext.PopulateTypes ();
1507 RootContext.DefineTypes ();
1509 TypeManager.InitCodeHelpers ();
1512 // Verify using aliases now
1514 Namespace.VerifyUsing ();
1516 if (Report.Errors > 0){
1520 if (RootContext.VerifyClsCompliance) {
1521 CodeGen.Assembly.ResolveClsCompliance ();
1522 AttributeTester.VerifyModulesClsCompliance ();
1523 TypeManager.LoadAllImportedTypes ();
1527 // The code generator
1530 ShowTime ("Emitting code");
1531 ShowTotalTime ("Total so far");
1532 RootContext.EmitCode ();
1536 if (Report.Errors > 0){
1541 ShowTime ("Closing types");
1543 RootContext.CloseTypes ();
1545 PEFileKinds k = PEFileKinds.ConsoleApplication;
1547 switch (RootContext.Target) {
1548 case Target.Library:
1550 k = PEFileKinds.Dll; break;
1552 k = PEFileKinds.ConsoleApplication; break;
1554 k = PEFileKinds.WindowApplication; break;
1557 if (RootContext.NeedsEntryPoint) {
1558 MethodInfo ep = RootContext.EntryPoint;
1561 if (Report.Errors == 0)
1562 Report.Error (5001, "Program " + output_file +
1563 " does not have an entry point defined");
1567 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1568 } else if (RootContext.MainClass != null) {
1569 Report.Error (2017, "Can not specify -main: when building module or library");
1573 // Add the resources
1575 if (resources != null){
1576 foreach (string spec in resources){
1580 cp = spec.IndexOf (',');
1582 file = spec.Substring (0, cp);
1583 res = spec.Substring (cp + 1);
1587 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1591 if (embedded_resources != null){
1592 object[] margs = new object [2];
1593 Type[] argst = new Type [2];
1594 argst [0] = argst [1] = typeof (string);
1596 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1597 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1598 null, CallingConventions.Any, argst, null);
1600 if (embed_res == null) {
1601 Report.Warning (0, new Location (-1),
1602 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1604 foreach (string spec in embedded_resources) {
1607 cp = spec.IndexOf (',');
1609 margs [0] = spec.Substring (cp + 1);
1610 margs [1] = spec.Substring (0, cp);
1613 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1616 if (File.Exists ((string) margs [1]))
1617 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1619 Report.Error (1566, "Can not find the resource " + margs [1]);
1626 // Add Win32 resources
1629 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1631 if (win32ResourceFile != null) {
1633 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1635 catch (ArgumentException) {
1636 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1640 if (win32IconFile != null) {
1641 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1642 if (define_icon == null) {
1643 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1645 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1648 if (Report.Errors > 0)
1651 CodeGen.Save (output_file);
1653 ShowTime ("Saved output");
1654 ShowTotalTime ("Total");
1657 Timer.ShowTimers ();
1659 if (Report.ExpectedError != 0){
1660 if (Report.Errors == 0) {
1661 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1662 "No other errors reported.");
1664 Environment.Exit (2);
1666 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1667 "However, other errors were reported.");
1669 Environment.Exit (1);
1677 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1678 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1680 return (Report.Errors == 0);
1686 // This is the only public entry point
1688 public class CompilerCallableEntryPoint : MarshalByRefObject {
1689 static bool used = false;
1691 public bool InvokeCompiler (string [] args)
1695 bool ok = Driver.MainDriver (args);
1696 return ok && Report.Errors == 0;
1699 public void Reset ()