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;
17 using System.Diagnostics;
20 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_flag = yacc_verbose;
188 } catch (Exception ex) {
189 Report.Error(666, "Compilation aborted: " + ex);
195 static void OtherFlags ()
198 "Other flags in the compiler\n" +
199 " --fatal Makes errors fatal\n" +
200 " --parse Only parses the source file\n" +
201 " --stacktrace Shows stack trace at error location\n" +
202 " --timestamp Displays time stamps of various compiler events\n" +
203 " -2 Enables experimental C# features\n" +
204 " -v Verbose parsing (for debugging the parser)\n" +
205 " --mcs-debug X Sets MCS debugging level to X\n");
211 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
212 "mcs [options] source-files\n" +
213 " --about About the Mono C# compiler\n" +
214 " -checked[+|-] Set default context to checked\n" +
215 " -codepage:ID Sets code page to the one in ID\n" +
216 " (number, `utf8' or `reset')\n" +
217 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
218 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
219 " -debug[+|-] Generate debugging information\n" +
220 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
221 " -doc:FILE XML Documentation file to generate\n" +
222 " -g Generate debugging information\n" +
223 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
224 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
225 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
226 " -main:class Specified the class that contains the entry point\n" +
227 " -noconfig[+|-] Disables implicit references to assemblies\n" +
228 " -nostdlib[+|-] Does not load core libraries\n" +
229 " -nowarn:W1[,W2] Disables one or more warnings\n" +
230 " -out:FNAME Specifies output file\n" +
231 " -pkg:P1[,Pn] References packages P1..Pn\n" +
232 " --expect-error X Expect that error X will be encountered\n" +
233 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
234 " -reference:ASS References the specified assembly (-r:ASS)\n" +
235 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
236 " library, module), (short: /t:)\n" +
237 " -unsafe[+|-] Allows unsafe code\n" +
238 " -warnaserror[+|-] Treat warnings as errors\n" +
239 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
240 " -help2 Show other help flags\n" +
243 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
244 " -resource:FILE[,ID] Embed FILE as a resource\n" +
245 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
246 " -win32icon:FILE Use this icon for the output\n" +
247 " @file Read response file for more options\n\n" +
248 "Options can be of the form -option or /option");
251 static void TargetUsage ()
253 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
259 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
260 "The compiler source code is released under the terms of the GNU GPL\n\n" +
262 "For more information on Mono, visit the project Web site\n" +
263 " http://www.go-mono.com\n\n" +
265 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
266 Environment.Exit (0);
269 public static int counter1, counter2;
271 public static int Main (string[] args)
273 RootContext.V2 = true;
274 bool ok = MainDriver (args);
276 if (ok && Report.Errors == 0) {
277 Console.Write("Compilation succeeded");
278 if (Report.Warnings > 0) {
279 Console.Write(" - {0} warning(s)", Report.Warnings);
283 Console.WriteLine ("Counter1: " + counter1);
284 Console.WriteLine ("Counter2: " + counter2);
290 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
291 Report.Errors, Report.Warnings);
296 static public void LoadAssembly (string assembly, bool soft)
299 string total_log = "";
302 char[] path_chars = { '/', '\\' };
304 if (assembly.IndexOfAny (path_chars) != -1) {
305 a = Assembly.LoadFrom (assembly);
307 string ass = assembly;
308 if (ass.EndsWith (".dll"))
309 ass = assembly.Substring (0, assembly.Length - 4);
310 a = Assembly.Load (ass);
312 TypeManager.AddAssembly (a);
314 } catch (FileNotFoundException){
315 foreach (string dir in link_paths){
316 string full_path = Path.Combine (dir, assembly);
317 if (!assembly.EndsWith (".dll"))
321 a = Assembly.LoadFrom (full_path);
322 TypeManager.AddAssembly (a);
324 } catch (FileNotFoundException ff) {
325 total_log += ff.FusionLog;
330 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
331 Console.WriteLine ("Log: \n" + total_log);
333 } catch (BadImageFormatException f) {
334 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
335 } catch (FileLoadException f){
336 Report.Error(6, "Cannot load assembly " + f.FusionLog);
337 } catch (ArgumentNullException){
338 Report.Error(6, "Cannot load assembly (null argument)");
342 static public void LoadModule (MethodInfo adder_method, string module)
345 string total_log = "";
349 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
351 catch (TargetInvocationException ex) {
352 throw ex.InnerException;
354 TypeManager.AddModule (m);
357 catch (FileNotFoundException){
358 foreach (string dir in link_paths){
359 string full_path = Path.Combine (dir, module);
360 if (!module.EndsWith (".netmodule"))
361 full_path += ".netmodule";
365 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
367 catch (TargetInvocationException ex) {
368 throw ex.InnerException;
370 TypeManager.AddModule (m);
372 } catch (FileNotFoundException ff) {
373 total_log += ff.FusionLog;
377 Report.Error (6, "Cannot find module `" + module + "'" );
378 Console.WriteLine ("Log: \n" + total_log);
379 } catch (BadImageFormatException f) {
380 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
381 } catch (FileLoadException f){
382 Report.Error(6, "Cannot load module " + f.FusionLog);
383 } catch (ArgumentNullException){
384 Report.Error(6, "Cannot load module (null argument)");
389 /// Loads all assemblies referenced on the command line
391 static public void LoadReferences ()
393 foreach (string r in references)
394 LoadAssembly (r, false);
396 foreach (string r in soft_references)
397 LoadAssembly (r, true);
402 static void SetupDefaultDefines ()
404 defines = new ArrayList ();
405 defines.Add ("__MonoCS__");
408 static string [] LoadArgs (string file)
411 ArrayList args = new ArrayList ();
414 f = new StreamReader (file);
419 StringBuilder sb = new StringBuilder ();
421 while ((line = f.ReadLine ()) != null){
424 for (int i = 0; i < t; i++){
427 if (c == '"' || c == '\''){
430 for (i++; i < t; i++){
437 } else if (c == ' '){
439 args.Add (sb.ToString ());
446 args.Add (sb.ToString ());
451 string [] ret_value = new string [args.Count];
452 args.CopyTo (ret_value, 0);
458 // Returns the directory where the system assemblies are installed
460 static string GetSystemDir ()
462 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
464 foreach (Assembly a in assemblies){
465 string codebase = a.Location;
466 string fn = System.IO.Path.GetFileName (codebase);
467 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
468 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
472 Report.Error (-15, "Can not compute my system path");
477 // Given a path specification, splits the path from the file/pattern
479 static void SplitPathAndPattern (string spec, out string path, out string pattern)
481 int p = spec.LastIndexOf ('/');
484 // Windows does not like /file.cs, switch that to:
489 pattern = spec.Substring (1);
491 path = spec.Substring (0, p);
492 pattern = spec.Substring (p + 1);
497 p = spec.LastIndexOf ('\\');
499 path = spec.Substring (0, p);
500 pattern = spec.Substring (p + 1);
508 static void ProcessFile (string f)
510 if (first_source == null)
513 Location.AddFile (f);
516 static void ProcessFiles ()
518 Location.Initialize ();
520 foreach (SourceFile file in Location.SourceFiles) {
522 tokenize_file (file);
529 static void CompileFiles (string spec, bool recurse)
531 string path, pattern;
533 SplitPathAndPattern (spec, out path, out pattern);
534 if (pattern.IndexOf ('*') == -1){
539 string [] files = null;
541 files = Directory.GetFiles (path, pattern);
542 } catch (System.IO.DirectoryNotFoundException) {
543 Report.Error (2001, "Source file `" + spec + "' could not be found");
545 } catch (System.IO.IOException){
546 Report.Error (2001, "Source file `" + spec + "' could not be found");
549 foreach (string f in files) {
556 string [] dirs = null;
559 dirs = Directory.GetDirectories (path);
563 foreach (string d in dirs) {
565 // Don't include path in this string, as each
566 // directory entry already does
567 CompileFiles (d + "/" + pattern, true);
571 static void DefineDefaultConfig ()
574 // For now the "default config" is harcoded into the compiler
575 // we can move this outside later
577 string [] default_config = {
582 // Is it worth pre-loading all this stuff?
585 "System.Configuration.Install",
588 "System.DirectoryServices",
589 "System.Drawing.Design",
591 "System.EnterpriseServices",
594 "System.Runtime.Remoting",
595 "System.Runtime.Serialization.Formatters.Soap",
597 "System.ServiceProcess",
599 "System.Web.RegularExpressions",
600 "System.Web.Services",
601 "System.Windows.Forms"
606 foreach (string def in default_config)
607 soft_references.Insert (p++, def);
610 static void SetOutputFile (string name)
615 static void SetWarningLevel (string s)
620 level = Int32.Parse (s);
624 "--wlevel requires a value from 0 to 4");
625 Environment.Exit (1);
627 if (level < 0 || level > 4){
628 Report.Error (1900, "Warning level must be 0 to 4");
629 Environment.Exit (1);
631 RootContext.WarningLevel = level;
632 TestWarningConflict ();
635 static void TestWarningConflict ()
637 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
638 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
639 Environment.Exit (1);
643 static void SetupV2 ()
645 RootContext.V2 = true;
646 defines.Add ("__V2__");
649 static void Version ()
651 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
652 Console.WriteLine ("Mono C# compiler version {0}", version);
653 Environment.Exit (0);
657 // Currently handles the Unix-like command line options, but will be
658 // deprecated in favor of the CSCParseOption, which will also handle the
659 // options that start with a dash in the future.
661 static bool UnixParseOption (string arg, ref string [] args, ref int i)
665 parser_verbose = true;
680 case "--main": case "-m":
681 if ((i + 1) >= args.Length){
683 Environment.Exit (1);
685 RootContext.MainClass = args [++i];
689 RootContext.Unsafe = true;
692 case "/?": case "/h": case "/help":
695 Environment.Exit (0);
699 if ((i + 1) >= args.Length){
701 Environment.Exit (1);
703 defines.Add (args [++i]);
706 case "--show-counters":
707 show_counters = true;
710 case "--expect-error": {
715 args [++i], NumberStyles.AllowLeadingSign);
716 Report.ExpectedError = code;
718 Report.Error (-14, "Invalid number specified");
729 if ((i + 1) >= args.Length){
731 Environment.Exit (1);
733 SetOutputFile (args [++i]);
737 RootContext.Checked = true;
741 Report.Stacktrace = true;
744 case "--linkresource":
746 if ((i + 1) >= args.Length){
748 Report.Error (5, "Missing argument to --linkres");
749 Environment.Exit (1);
751 if (resources == null)
752 resources = new ArrayList ();
754 resources.Add (args [++i]);
759 if ((i + 1) >= args.Length){
761 Report.Error (5, "Missing argument to --resource");
762 Environment.Exit (1);
764 if (embedded_resources == null)
765 embedded_resources = new ArrayList ();
767 embedded_resources.Add (args [++i]);
771 if ((i + 1) >= args.Length){
772 Environment.Exit (1);
776 string type = args [++i];
779 RootContext.Target = Target.Library;
780 RootContext.TargetExt = ".dll";
784 RootContext.Target = Target.Exe;
788 RootContext.Target = Target.WinExe;
792 RootContext.Target = Target.Module;
793 RootContext.TargetExt = ".dll";
797 Environment.Exit (1);
803 if ((i + 1) >= args.Length){
805 Environment.Exit (1);
808 references.Add (args [++i]);
812 if ((i + 1) >= args.Length){
814 Environment.Exit (1);
816 link_paths.Add (args [++i]);
820 RootContext.StdLib = false;
828 Report.WarningsAreErrors = true;
829 TestWarningConflict();
833 if ((i + 1) >= args.Length){
835 Environment.Exit (1);
840 warn = Int32.Parse (args [++i]);
843 Environment.Exit (1);
845 Report.SetIgnoreWarning (warn);
849 if ((i + 1) >= args.Length){
852 "--wlevel requires a value from 0 to 4");
853 Environment.Exit (1);
856 SetWarningLevel (args [++i]);
860 if ((i + 1) >= args.Length){
861 Report.Error (5, "--mcs-debug requires an argument");
862 Environment.Exit (1);
866 Report.DebugFlags = Int32.Parse (args [++i]);
868 Report.Error (5, "Invalid argument to --mcs-debug");
869 Environment.Exit (1);
878 if ((i + 1) >= args.Length){
879 Report.Error (5, "--recurse requires an argument");
880 Environment.Exit (1);
882 CompileFiles (args [++i], true);
887 last_time = first_time = DateTime.Now;
894 case "--debug": case "-g":
895 want_debugging_support = true;
899 load_default_config = false;
907 // Currently it is very basic option parsing, but eventually, this will
908 // be the complete option parser
910 static bool CSCParseOption (string option, ref string [] args, ref int i)
912 int idx = option.IndexOf (':');
919 arg = option.Substring (0, idx);
921 value = option.Substring (idx + 1);
932 RootContext.Target = Target.Exe;
936 RootContext.Target = Target.WinExe;
940 RootContext.Target = Target.Library;
941 RootContext.TargetExt = ".dll";
945 RootContext.Target = Target.Module;
946 RootContext.TargetExt = ".netmodule";
951 Environment.Exit (1);
959 Environment.Exit (1);
961 SetOutputFile (value);
968 case "/incremental+":
969 case "/incremental-":
979 Environment.Exit (1);
982 defs = value.Split (new Char [] {';', ','});
983 foreach (string d in defs){
990 case "/linkresource":
992 Report.Error (5, arg + " requires an argument");
993 Environment.Exit (1);
995 if (resources == null)
996 resources = new ArrayList ();
998 resources.Add (value);
1006 Environment.Exit (1);
1008 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1010 ProcessStartInfo pi = new ProcessStartInfo ();
1011 pi.FileName = "pkg-config";
1012 pi.RedirectStandardOutput = true;
1013 pi.UseShellExecute = false;
1014 pi.Arguments = "--libs " + packages;
1017 p = Process.Start (pi);
1018 } catch (Exception e) {
1019 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1020 Environment.Exit (1);
1023 if (p.StandardOutput == null){
1024 Report.Warning (-27, "Specified package did not return any information");
1027 string pkgout = p.StandardOutput.ReadToEnd ();
1029 if (p.ExitCode != 0) {
1030 Report.Error (-27, "Error running pkg-config. Check the above output.");
1031 Environment.Exit (1);
1034 if (pkgout != null){
1035 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1036 Split (new Char [] { ' ', '\t'});
1037 args = AddArgs (args, xargs);
1047 Report.Error (5, arg + " requires an argument");
1048 Environment.Exit (1);
1050 if (embedded_resources == null)
1051 embedded_resources = new ArrayList ();
1053 embedded_resources.Add (value);
1058 Report.Error (5, "/recurse requires an argument");
1059 Environment.Exit (1);
1061 CompileFiles (value, true);
1065 case "/reference": {
1067 Report.Error (5, arg + " requires an argument");
1068 Environment.Exit (1);
1071 string [] refs = value.Split (new char [] { ';', ',' });
1072 foreach (string r in refs){
1077 case "/addmodule": {
1079 Report.Error (5, arg + " requires an argument");
1080 Environment.Exit (1);
1083 string [] refs = value.Split (new char [] { ';', ',' });
1084 foreach (string r in refs){
1091 Report.Error (5, arg + " requires an argument");
1092 Environment.Exit (1);
1095 win32ResourceFile = value;
1098 case "/win32icon": {
1100 Report.Error (5, arg + " requires an argument");
1101 Environment.Exit (1);
1104 win32IconFile = value;
1109 Report.Error (5, arg + " requires an argument");
1110 Environment.Exit (1);
1112 // TODO handle the /doc argument to generate xml doc
1119 Report.Error (5, "/lib requires an argument");
1120 Environment.Exit (1);
1123 libdirs = value.Split (new Char [] { ',' });
1124 foreach (string dir in libdirs)
1125 link_paths.Add (dir);
1130 want_debugging_support = false;
1135 want_debugging_support = true;
1140 RootContext.Checked = true;
1144 RootContext.Checked = false;
1152 RootContext.VerifyClsCompliance = false;
1157 RootContext.Unsafe = true;
1161 RootContext.Unsafe = false;
1164 case "/warnaserror":
1165 case "/warnaserror+":
1166 Report.WarningsAreErrors = true;
1167 TestWarningConflict();
1170 case "/warnaserror-":
1171 Report.WarningsAreErrors = false;
1175 SetWarningLevel (value);
1182 Report.Error (5, "/nowarn requires an argument");
1183 Environment.Exit (1);
1186 warns = value.Split (new Char [] {','});
1187 foreach (string wc in warns){
1189 int warn = Int32.Parse (wc);
1191 throw new ArgumentOutOfRangeException("warn");
1193 Report.SetIgnoreWarning (warn);
1195 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1196 Environment.Exit (1);
1203 load_default_config = true;
1208 load_default_config = false;
1213 Environment.Exit(0);
1219 Environment.Exit (0);
1225 Report.Error (5, arg + " requires an argument");
1226 Environment.Exit (1);
1228 RootContext.MainClass = value;
1233 RootContext.StdLib = false;
1237 RootContext.StdLib = true;
1244 if (value == String.Empty) {
1245 Report.Error (5, arg + " requires an argument");
1246 Environment.Exit (1);
1248 RootContext.StrongNameKeyFile = value;
1250 case "/keycontainer":
1251 if (value == String.Empty) {
1252 Report.Error (5, arg + " requires an argument");
1253 Environment.Exit (1);
1255 RootContext.StrongNameKeyContainer = value;
1258 RootContext.StrongNameDelaySign = true;
1261 RootContext.StrongNameDelaySign = false;
1272 if (value == "utf8"){
1273 encoding = new UTF8Encoding();
1274 using_default_encoder = false;
1277 if (value == "reset"){
1279 // 28591 is the code page for ISO-8859-1 encoding.
1282 using_default_encoder = true;
1286 cp = Int32.Parse (value);
1287 encoding = Encoding.GetEncoding (cp);
1288 using_default_encoder = false;
1290 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1291 Environment.Exit (1);
1295 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1296 //Environment.Exit (1);
1300 static string [] AddArgs (string [] args, string [] extra_args)
1304 new_args = new string [extra_args.Length + args.Length];
1305 args.CopyTo (new_args, 0);
1306 extra_args.CopyTo (new_args, args.Length);
1312 /// Parses the arguments, and drives the compilation
1317 /// TODO: Mostly structured to debug the compiler
1318 /// now, needs to be turned into a real driver soon.
1320 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1321 internal static bool MainDriver (string [] args)
1324 bool parsing_options = true;
1326 Console.WriteLine ("ALPHA SOFTWARE: Mono C# Compiler {0} for Generics",
1327 Assembly.GetExecutingAssembly ().GetName ().Version.ToString ());
1329 encoding = Encoding.GetEncoding (28591);
1331 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1332 encoding = Encoding.GetEncoding (1252);
1335 references = new ArrayList ();
1336 soft_references = new ArrayList ();
1337 modules = new ArrayList ();
1338 link_paths = new ArrayList ();
1340 SetupDefaultDefines ();
1345 // This is not required because Assembly.Load knows about this
1349 for (i = 0; i < args.Length; i++){
1350 string arg = args [i];
1354 if (arg.StartsWith ("@")){
1355 string [] extra_args;
1356 string response_file = arg.Substring (1);
1358 if (response_file_list == null)
1359 response_file_list = new Hashtable ();
1361 if (response_file_list.Contains (response_file)){
1363 1515, "Response file `" + response_file +
1364 "' specified multiple times");
1365 Environment.Exit (1);
1368 response_file_list.Add (response_file, response_file);
1370 extra_args = LoadArgs (response_file);
1371 if (extra_args == null){
1372 Report.Error (2011, "Unable to open response file: " +
1377 args = AddArgs (args, extra_args);
1381 if (parsing_options){
1383 parsing_options = false;
1387 if (arg.StartsWith ("-")){
1388 if (UnixParseOption (arg, ref args, ref i))
1392 string csc_opt = "/" + arg.Substring (1);
1393 if (CSCParseOption (csc_opt, ref args, ref i))
1396 if (arg.StartsWith ("/")){
1397 if (CSCParseOption (arg, ref args, ref i))
1403 CompileFiles (arg, false);
1412 // If we are an exe, require a source file for the entry point
1414 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1415 if (first_source == null){
1416 Report.Error (2008, "No files to compile were specified");
1423 // If there is nothing to put in the assembly, and we are not a library
1425 if (first_source == null && embedded_resources == null && resources == null){
1426 Report.Error (2008, "No files to compile were specified");
1430 if (Report.Errors > 0)
1436 Tokenizer.Cleanup ();
1439 // Load Core Library for default compilation
1441 if (RootContext.StdLib)
1442 references.Insert (0, "mscorlib");
1444 if (load_default_config)
1445 DefineDefaultConfig ();
1447 if (Report.Errors > 0){
1452 // Load assemblies required
1455 ShowTime ("Loading references");
1456 link_paths.Add (GetSystemDir ());
1457 link_paths.Add (Directory.GetCurrentDirectory ());
1461 ShowTime (" References loaded");
1463 if (Report.Errors > 0){
1470 if (output_file == null){
1471 int pos = first_source.LastIndexOf ('.');
1474 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1476 output_file = first_source + RootContext.TargetExt;
1479 CodeGen.Init (output_file, output_file, want_debugging_support);
1481 if (RootContext.Target == Target.Module) {
1482 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1483 if (module_only == null) {
1484 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1485 Environment.Exit (1);
1488 MethodInfo set_method = module_only.GetSetMethod (true);
1489 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1492 TypeManager.AddModule (CodeGen.Module.Builder);
1494 if (modules.Count > 0) {
1495 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1496 if (adder_method == null) {
1497 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1498 Environment.Exit (1);
1501 foreach (string module in modules)
1502 LoadModule (adder_method, module);
1505 TypeManager.ComputeNamespaces ();
1508 // Before emitting, we need to get the core
1509 // types emitted from the user defined types
1510 // or from the system ones.
1513 ShowTime ("Initializing Core Types");
1514 if (!RootContext.StdLib){
1515 RootContext.ResolveCore ();
1516 if (Report.Errors > 0)
1520 TypeManager.InitCoreTypes ();
1522 ShowTime (" Core Types done");
1525 // The second pass of the compiler
1528 ShowTime ("Resolving tree");
1529 RootContext.ResolveTree ();
1530 if (Report.Errors > 0)
1533 ShowTime ("Populate tree");
1534 if (!RootContext.StdLib)
1535 RootContext.BootCorlib_PopulateCoreTypes ();
1536 RootContext.PopulateTypes ();
1537 RootContext.DefineTypes ();
1539 TypeManager.InitCodeHelpers ();
1542 // Verify using aliases now
1544 Namespace.VerifyUsing ();
1546 if (Report.Errors > 0){
1550 if (RootContext.VerifyClsCompliance) {
1551 CodeGen.Assembly.ResolveClsCompliance ();
1552 AttributeTester.VerifyModulesClsCompliance ();
1553 TypeManager.LoadAllImportedTypes ();
1557 // The code generator
1560 ShowTime ("Emitting code");
1561 ShowTotalTime ("Total so far");
1562 RootContext.EmitCode ();
1566 if (Report.Errors > 0){
1571 ShowTime ("Closing types");
1573 RootContext.CloseTypes ();
1575 PEFileKinds k = PEFileKinds.ConsoleApplication;
1577 switch (RootContext.Target) {
1578 case Target.Library:
1580 k = PEFileKinds.Dll; break;
1582 k = PEFileKinds.ConsoleApplication; break;
1584 k = PEFileKinds.WindowApplication; break;
1587 if (RootContext.NeedsEntryPoint) {
1588 MethodInfo ep = RootContext.EntryPoint;
1591 if (Report.Errors == 0)
1592 Report.Error (5001, "Program " + output_file +
1593 " does not have an entry point defined");
1597 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1598 } else if (RootContext.MainClass != null) {
1599 Report.Error (2017, "Can not specify -main: when building module or library");
1603 // Add the resources
1605 if (resources != null){
1606 foreach (string spec in resources){
1610 cp = spec.IndexOf (',');
1612 file = spec.Substring (0, cp);
1613 res = spec.Substring (cp + 1);
1617 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1621 if (embedded_resources != null){
1622 object[] margs = new object [2];
1623 Type[] argst = new Type [2];
1624 argst [0] = argst [1] = typeof (string);
1626 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1627 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1628 null, CallingConventions.Any, argst, null);
1630 if (embed_res == null) {
1631 Report.Warning (0, new Location (-1),
1632 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1634 foreach (string spec in embedded_resources) {
1637 cp = spec.IndexOf (',');
1639 margs [0] = spec.Substring (cp + 1);
1640 margs [1] = spec.Substring (0, cp);
1643 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1646 if (File.Exists ((string) margs [1]))
1647 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1649 Report.Error (1566, "Can not find the resource " + margs [1]);
1656 // Add Win32 resources
1659 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1661 if (win32ResourceFile != null) {
1663 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1665 catch (ArgumentException) {
1666 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1670 if (win32IconFile != null) {
1671 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1672 if (define_icon == null) {
1673 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1675 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1678 if (Report.Errors > 0)
1681 CodeGen.Save (output_file);
1683 ShowTime ("Saved output");
1684 ShowTotalTime ("Total");
1687 Timer.ShowTimers ();
1689 if (Report.ExpectedError != 0){
1690 if (Report.Errors == 0) {
1691 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1692 "No other errors reported.");
1694 Environment.Exit (2);
1696 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1697 "However, other errors were reported.");
1699 Environment.Exit (1);
1707 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1708 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1710 return (Report.Errors == 0);
1716 // This is the only public entry point
1718 public class CompilerCallableEntryPoint : MarshalByRefObject {
1719 static bool used = false;
1721 public bool InvokeCompiler (string [] args)
1725 bool ok = Driver.MainDriver (args);
1726 return ok && Report.Errors == 0;
1729 public void Reset ()