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;
20 using System.Diagnostics;
24 Library, Exe, Module, WinExe
28 /// The compiler driver.
34 // Assemblies references to be linked. Initialized with
36 static ArrayList references;
39 // If any of these fail, we ignore the problem. This is so
40 // that we can list all the assemblies in Windows and not fail
41 // if they are missing on Linux.
43 static ArrayList soft_references;
46 // Modules to be linked
48 static ArrayList modules;
51 static ArrayList link_paths;
53 // Whether we want Yacc to output its progress
54 static bool yacc_verbose = false;
56 // Whether we want to only run the tokenizer
57 static bool tokenize = false;
59 static string first_source;
61 static bool want_debugging_support = false;
63 static bool parse_only = false;
64 static bool timestamps = false;
65 static bool pause = false;
66 static bool show_counters = false;
67 public static bool parser_verbose = false;
70 // Whether to load the initial config file (what CSC.RSP has by default)
72 static bool load_default_config = true;
74 static Hashtable response_file_list;
77 // A list of resource files
79 static ArrayList resources;
80 static ArrayList embedded_resources;
81 static string win32ResourceFile;
82 static string win32IconFile;
85 // An array of the defines from the command line
87 static ArrayList defines;
92 static string output_file = null;
95 // Last time we took the time
97 static DateTime last_time, first_time;
100 // Encoding: ISO-Latin1 is 28591
102 static Encoding encoding;
105 // Whether the user has specified a different encoder manually
107 static bool using_default_encoder = true;
110 // The system version we are using, if not specified on the commandline we
111 // will use the same version as corlib for looking for libraries in the GAC.
113 static string sys_version;
115 public static void ShowTime (string msg)
120 DateTime now = DateTime.Now;
121 TimeSpan span = now - last_time;
125 "[{0:00}:{1:000}] {2}",
126 (int) span.TotalSeconds, span.Milliseconds, msg);
129 public static void ShowTotalTime (string msg)
134 DateTime now = DateTime.Now;
135 TimeSpan span = now - first_time;
139 "[{0:00}:{1:000}] {2}",
140 (int) span.TotalSeconds, span.Milliseconds, msg);
143 static void tokenize_file (SourceFile file)
148 input = File.OpenRead (file.Name);
150 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
155 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
156 Tokenizer lexer = new Tokenizer (reader, file, defines);
157 int token, tokens = 0, errors = 0;
159 while ((token = lexer.token ()) != Token.EOF){
161 if (token == Token.ERROR)
164 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
170 // MonoTODO("Change error code for aborted compilation to something reasonable")]
171 static void parse (SourceFile file)
177 input = File.OpenRead (file.Name);
179 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
183 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
185 parser = new CSharpParser (reader, file, defines);
186 parser.yacc_verbose = yacc_verbose;
189 } catch (Exception ex) {
190 Report.Error(666, "Compilation aborted: " + ex);
196 static void OtherFlags ()
199 "Other flags in the compiler\n" +
200 " --fatal Makes errors fatal\n" +
201 " --parse Only parses the source file\n" +
202 " --stacktrace Shows stack trace at error location\n" +
203 " --timestamp Displays time stamps of various compiler events\n" +
204 " -2 Enables experimental C# features\n" +
205 " -v Verbose parsing (for debugging the parser)\n" +
206 " --mcs-debug X Sets MCS debugging level to X\n");
212 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
213 "mcs [options] source-files\n" +
214 " --about About the Mono C# compiler\n" +
215 " -addmodule:MODULE Adds the module to the generated assembly\n" +
216 " -checked[+|-] Set default context to checked\n" +
217 " -codepage:ID Sets code page to the one in ID\n" +
218 " (number, `utf8' or `reset')\n" +
219 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
220 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
221 " -debug[+|-] Generate debugging information\n" +
222 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
223 " -doc:FILE XML Documentation file to generate\n" +
224 " -g Generate debugging information\n" +
225 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
226 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
227 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
228 " -main:class Specified the class that contains the entry point\n" +
229 " -noconfig[+|-] Disables implicit references to assemblies\n" +
230 " -nostdlib[+|-] Does not load core libraries\n" +
231 " -nowarn:W1[,W2] Disables one or more warnings\n" +
232 " -out:FNAME Specifies output file\n" +
233 " -pkg:P1[,Pn] References packages P1..Pn\n" +
234 " --expect-error X Expect that error X will be encountered\n" +
235 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
236 " -reference:ASS References the specified assembly (-r:ASS)\n" +
237 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
238 " library, module), (short: /t:)\n" +
239 " -unsafe[+|-] Allows unsafe code\n" +
240 " -warnaserror[+|-] Treat warnings as errors\n" +
241 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
242 " -help2 Show other help flags\n" +
245 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
246 " -resource:FILE[,ID] Embed FILE as a resource\n" +
247 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
248 " -win32icon:FILE Use this icon for the output\n" +
249 " @file Read response file for more options\n\n" +
250 "Options can be of the form -option or /option");
253 static void TargetUsage ()
255 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
261 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
262 "The compiler source code is released under the terms of the GNU GPL\n\n" +
264 "For more information on Mono, visit the project Web site\n" +
265 " http://www.go-mono.com\n\n" +
267 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
268 Environment.Exit (0);
271 public static int counter1, counter2;
273 public static int Main (string[] args)
275 bool ok = MainDriver (args);
277 if (ok && Report.Errors == 0) {
278 Console.Write("Compilation succeeded");
279 if (Report.Warnings > 0) {
280 Console.Write(" - {0} warning(s)", Report.Warnings);
284 Console.WriteLine ("Counter1: " + counter1);
285 Console.WriteLine ("Counter2: " + counter2);
291 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
292 Report.Errors, Report.Warnings);
297 static public void LoadAssembly (string assembly, bool soft)
300 string total_log = "";
303 char[] path_chars = { '/', '\\' };
305 if (assembly.IndexOfAny (path_chars) != -1) {
306 a = Assembly.LoadFrom (assembly);
308 string ass = assembly;
309 if (ass.EndsWith (".dll"))
310 ass = assembly.Substring (0, assembly.Length - 4);
311 a = Assembly.Load (ass);
313 TypeManager.AddAssembly (a);
315 } catch (FileNotFoundException){
316 foreach (string dir in link_paths){
317 string full_path = Path.Combine (dir, assembly);
318 if (!assembly.EndsWith (".dll"))
322 a = Assembly.LoadFrom (full_path);
323 TypeManager.AddAssembly (a);
325 } catch (FileNotFoundException ff) {
326 total_log += ff.FusionLog;
331 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
332 Console.WriteLine ("Log: \n" + total_log);
334 } catch (BadImageFormatException f) {
335 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
336 } catch (FileLoadException f){
337 Report.Error(6, "Cannot load assembly " + f.FusionLog);
338 } catch (ArgumentNullException){
339 Report.Error(6, "Cannot load assembly (null argument)");
343 static public void LoadModule (MethodInfo adder_method, string module)
346 string total_log = "";
350 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
352 catch (TargetInvocationException ex) {
353 throw ex.InnerException;
355 TypeManager.AddModule (m);
358 catch (FileNotFoundException){
359 foreach (string dir in link_paths){
360 string full_path = Path.Combine (dir, module);
361 if (!module.EndsWith (".netmodule"))
362 full_path += ".netmodule";
366 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
368 catch (TargetInvocationException ex) {
369 throw ex.InnerException;
371 TypeManager.AddModule (m);
373 } catch (FileNotFoundException ff) {
374 total_log += ff.FusionLog;
378 Report.Error (6, "Cannot find module `" + module + "'" );
379 Console.WriteLine ("Log: \n" + total_log);
380 } catch (BadImageFormatException f) {
381 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
382 } catch (FileLoadException f){
383 Report.Error(6, "Cannot load module " + f.FusionLog);
384 } catch (ArgumentNullException){
385 Report.Error(6, "Cannot load module (null argument)");
390 /// Loads all assemblies referenced on the command line
392 static public void LoadReferences ()
394 foreach (string r in references)
395 LoadAssembly (r, false);
397 foreach (string r in soft_references)
398 LoadAssembly (r, true);
403 static void SetupDefaultDefines ()
405 defines = new ArrayList ();
406 defines.Add ("__MonoCS__");
409 static string [] LoadArgs (string file)
412 ArrayList args = new ArrayList ();
415 f = new StreamReader (file);
420 StringBuilder sb = new StringBuilder ();
422 while ((line = f.ReadLine ()) != null){
425 for (int i = 0; i < t; i++){
428 if (c == '"' || c == '\''){
431 for (i++; i < t; i++){
438 } else if (c == ' '){
440 args.Add (sb.ToString ());
447 args.Add (sb.ToString ());
452 string [] ret_value = new string [args.Count];
453 args.CopyTo (ret_value, 0);
459 // Returns the directory where the system assemblies are installed
461 static string GetSystemDir ()
463 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
465 foreach (Assembly a in assemblies){
466 string codebase = a.Location;
467 string fn = System.IO.Path.GetFileName (codebase);
468 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
469 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
473 Report.Error (-15, "Can not compute my system path");
478 // Given a path specification, splits the path from the file/pattern
480 static void SplitPathAndPattern (string spec, out string path, out string pattern)
482 int p = spec.LastIndexOf ('/');
485 // Windows does not like /file.cs, switch that to:
490 pattern = spec.Substring (1);
492 path = spec.Substring (0, p);
493 pattern = spec.Substring (p + 1);
498 p = spec.LastIndexOf ('\\');
500 path = spec.Substring (0, p);
501 pattern = spec.Substring (p + 1);
509 static void ProcessFile (string f)
511 if (first_source == null)
514 Location.AddFile (f);
517 static void ProcessFiles ()
519 Location.Initialize ();
521 foreach (SourceFile file in Location.SourceFiles) {
523 tokenize_file (file);
530 static void CompileFiles (string spec, bool recurse)
532 string path, pattern;
534 SplitPathAndPattern (spec, out path, out pattern);
535 if (pattern.IndexOf ('*') == -1){
540 string [] files = null;
542 files = Directory.GetFiles (path, pattern);
543 } catch (System.IO.DirectoryNotFoundException) {
544 Report.Error (2001, "Source file `" + spec + "' could not be found");
546 } catch (System.IO.IOException){
547 Report.Error (2001, "Source file `" + spec + "' could not be found");
550 foreach (string f in files) {
557 string [] dirs = null;
560 dirs = Directory.GetDirectories (path);
564 foreach (string d in dirs) {
566 // Don't include path in this string, as each
567 // directory entry already does
568 CompileFiles (d + "/" + pattern, true);
572 static void DefineDefaultConfig ()
575 // For now the "default config" is harcoded into the compiler
576 // we can move this outside later
578 string [] default_config = {
583 // Is it worth pre-loading all this stuff?
586 "System.Configuration.Install",
589 "System.DirectoryServices",
590 "System.Drawing.Design",
592 "System.EnterpriseServices",
595 "System.Runtime.Remoting",
596 "System.Runtime.Serialization.Formatters.Soap",
598 "System.ServiceProcess",
600 "System.Web.RegularExpressions",
601 "System.Web.Services",
602 "System.Windows.Forms"
607 foreach (string def in default_config)
608 soft_references.Insert (p++, def);
611 static void SetOutputFile (string name)
616 static void SetWarningLevel (string s)
621 level = Int32.Parse (s);
625 "--wlevel requires a value from 0 to 4");
626 Environment.Exit (1);
628 if (level < 0 || level > 4){
629 Report.Error (1900, "Warning level must be 0 to 4");
630 Environment.Exit (1);
632 RootContext.WarningLevel = level;
633 TestWarningConflict ();
636 static void TestWarningConflict ()
638 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
639 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
640 Environment.Exit (1);
644 static void SetupV2 ()
646 RootContext.V2 = true;
647 defines.Add ("__V2__");
650 static void Version ()
652 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
653 Console.WriteLine ("Mono C# compiler version {0}", version);
654 Environment.Exit (0);
658 // Currently handles the Unix-like command line options, but will be
659 // deprecated in favor of the CSCParseOption, which will also handle the
660 // options that start with a dash in the future.
662 static bool UnixParseOption (string arg, ref string [] args, ref int i)
666 parser_verbose = true;
681 case "--main": case "-m":
682 if ((i + 1) >= args.Length){
684 Environment.Exit (1);
686 RootContext.MainClass = args [++i];
690 RootContext.Unsafe = true;
693 case "/?": case "/h": case "/help":
696 Environment.Exit (0);
700 if ((i + 1) >= args.Length){
702 Environment.Exit (1);
704 defines.Add (args [++i]);
707 case "--show-counters":
708 show_counters = true;
711 case "--expect-error": {
716 args [++i], NumberStyles.AllowLeadingSign);
717 Report.ExpectedError = code;
719 Report.Error (-14, "Invalid number specified");
730 if ((i + 1) >= args.Length){
732 Environment.Exit (1);
734 SetOutputFile (args [++i]);
738 RootContext.Checked = true;
742 Report.Stacktrace = true;
745 case "--linkresource":
747 if ((i + 1) >= args.Length){
749 Report.Error (5, "Missing argument to --linkres");
750 Environment.Exit (1);
752 if (resources == null)
753 resources = new ArrayList ();
755 resources.Add (args [++i]);
760 if ((i + 1) >= args.Length){
762 Report.Error (5, "Missing argument to --resource");
763 Environment.Exit (1);
765 if (embedded_resources == null)
766 embedded_resources = new ArrayList ();
768 embedded_resources.Add (args [++i]);
772 if ((i + 1) >= args.Length){
773 Environment.Exit (1);
777 string type = args [++i];
780 RootContext.Target = Target.Library;
781 RootContext.TargetExt = ".dll";
785 RootContext.Target = Target.Exe;
789 RootContext.Target = Target.WinExe;
793 RootContext.Target = Target.Module;
794 RootContext.TargetExt = ".dll";
798 Environment.Exit (1);
804 if ((i + 1) >= args.Length){
806 Environment.Exit (1);
809 references.Add (args [++i]);
813 if ((i + 1) >= args.Length){
815 Environment.Exit (1);
817 link_paths.Add (args [++i]);
821 RootContext.StdLib = false;
829 Report.WarningsAreErrors = true;
830 TestWarningConflict();
834 if ((i + 1) >= args.Length){
836 Environment.Exit (1);
841 warn = Int32.Parse (args [++i]);
844 Environment.Exit (1);
846 Report.SetIgnoreWarning (warn);
850 if ((i + 1) >= args.Length){
853 "--wlevel requires a value from 0 to 4");
854 Environment.Exit (1);
857 SetWarningLevel (args [++i]);
861 if ((i + 1) >= args.Length){
862 Report.Error (5, "--mcs-debug requires an argument");
863 Environment.Exit (1);
867 Report.DebugFlags = Int32.Parse (args [++i]);
869 Report.Error (5, "Invalid argument to --mcs-debug");
870 Environment.Exit (1);
879 if ((i + 1) >= args.Length){
880 Report.Error (5, "--recurse requires an argument");
881 Environment.Exit (1);
883 CompileFiles (args [++i], true);
888 last_time = first_time = DateTime.Now;
895 case "--debug": case "-g":
896 want_debugging_support = true;
900 load_default_config = false;
908 // Currently it is very basic option parsing, but eventually, this will
909 // be the complete option parser
911 static bool CSCParseOption (string option, ref string [] args, ref int i)
913 int idx = option.IndexOf (':');
920 arg = option.Substring (0, idx);
922 value = option.Substring (idx + 1);
933 RootContext.Target = Target.Exe;
937 RootContext.Target = Target.WinExe;
941 RootContext.Target = Target.Library;
942 RootContext.TargetExt = ".dll";
946 RootContext.Target = Target.Module;
947 RootContext.TargetExt = ".netmodule";
952 Environment.Exit (1);
960 Environment.Exit (1);
962 SetOutputFile (value);
969 case "/incremental+":
970 case "/incremental-":
980 Environment.Exit (1);
983 defs = value.Split (new Char [] {';', ','});
984 foreach (string d in defs){
991 case "/linkresource":
993 Report.Error (5, arg + " requires an argument");
994 Environment.Exit (1);
996 if (resources == null)
997 resources = new ArrayList ();
999 resources.Add (value);
1007 Environment.Exit (1);
1009 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1011 ProcessStartInfo pi = new ProcessStartInfo ();
1012 pi.FileName = "pkg-config";
1013 pi.RedirectStandardOutput = true;
1014 pi.UseShellExecute = false;
1015 pi.Arguments = "--libs " + packages;
1018 p = Process.Start (pi);
1019 } catch (Exception e) {
1020 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1021 Environment.Exit (1);
1024 if (p.StandardOutput == null){
1025 Report.Warning (-27, "Specified package did not return any information");
1028 string pkgout = p.StandardOutput.ReadToEnd ();
1030 if (p.ExitCode != 0) {
1031 Report.Error (-27, "Error running pkg-config. Check the above output.");
1032 Environment.Exit (1);
1035 if (pkgout != null){
1036 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1037 Split (new Char [] { ' ', '\t'});
1038 args = AddArgs (args, xargs);
1048 Report.Error (5, "-resource requires an argument");
1049 Environment.Exit (1);
1051 if (embedded_resources == null)
1052 embedded_resources = new ArrayList ();
1054 embedded_resources.Add (value);
1059 Report.Error (5, "-recurse requires an argument");
1060 Environment.Exit (1);
1062 CompileFiles (value, true);
1066 case "/reference": {
1068 Report.Error (5, "-reference requires an argument");
1069 Environment.Exit (1);
1072 string [] refs = value.Split (new char [] { ';', ',' });
1073 foreach (string r in refs){
1078 case "/addmodule": {
1080 Report.Error (5, arg + " requires an argument");
1081 Environment.Exit (1);
1084 string [] refs = value.Split (new char [] { ';', ',' });
1085 foreach (string r in refs){
1092 Report.Error (5, arg + " requires an argument");
1093 Environment.Exit (1);
1096 win32ResourceFile = value;
1099 case "/win32icon": {
1101 Report.Error (5, arg + " requires an argument");
1102 Environment.Exit (1);
1105 win32IconFile = value;
1110 Report.Error (5, arg + " requires an argument");
1111 Environment.Exit (1);
1113 // TODO handle the /doc argument to generate xml doc
1120 Report.Error (5, "/lib requires an argument");
1121 Environment.Exit (1);
1124 libdirs = value.Split (new Char [] { ',' });
1125 foreach (string dir in libdirs)
1126 link_paths.Add (dir);
1131 want_debugging_support = false;
1136 want_debugging_support = true;
1141 RootContext.Checked = true;
1145 RootContext.Checked = false;
1153 RootContext.VerifyClsCompliance = false;
1158 RootContext.Unsafe = true;
1162 RootContext.Unsafe = false;
1165 case "/warnaserror":
1166 case "/warnaserror+":
1167 Report.WarningsAreErrors = true;
1168 TestWarningConflict();
1171 case "/warnaserror-":
1172 Report.WarningsAreErrors = false;
1176 SetWarningLevel (value);
1183 Report.Error (5, "/nowarn requires an argument");
1184 Environment.Exit (1);
1187 warns = value.Split (new Char [] {','});
1188 foreach (string wc in warns){
1190 int warn = Int32.Parse (wc);
1192 throw new ArgumentOutOfRangeException("warn");
1194 Report.SetIgnoreWarning (warn);
1196 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1197 Environment.Exit (1);
1204 load_default_config = true;
1209 load_default_config = false;
1214 Environment.Exit(0);
1220 Environment.Exit (0);
1226 Report.Error (5, arg + " requires an argument");
1227 Environment.Exit (1);
1229 RootContext.MainClass = value;
1234 RootContext.StdLib = false;
1238 RootContext.StdLib = true;
1245 if (value == String.Empty) {
1246 Report.Error (5, arg + " requires an argument");
1247 Environment.Exit (1);
1249 RootContext.StrongNameKeyFile = value;
1251 case "/keycontainer":
1252 if (value == String.Empty) {
1253 Report.Error (5, arg + " requires an argument");
1254 Environment.Exit (1);
1256 RootContext.StrongNameKeyContainer = value;
1259 RootContext.StrongNameDelaySign = true;
1262 RootContext.StrongNameDelaySign = false;
1273 if (value == "utf8"){
1274 encoding = new UTF8Encoding();
1275 using_default_encoder = false;
1278 if (value == "reset"){
1280 // 28591 is the code page for ISO-8859-1 encoding.
1283 using_default_encoder = true;
1287 cp = Int32.Parse (value);
1288 encoding = Encoding.GetEncoding (cp);
1289 using_default_encoder = false;
1291 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1292 Environment.Exit (1);
1296 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1297 //Environment.Exit (1);
1301 static string [] AddArgs (string [] args, string [] extra_args)
1305 new_args = new string [extra_args.Length + args.Length];
1306 args.CopyTo (new_args, 0);
1307 extra_args.CopyTo (new_args, args.Length);
1313 /// Parses the arguments, and drives the compilation
1318 /// TODO: Mostly structured to debug the compiler
1319 /// now, needs to be turned into a real driver soon.
1321 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1322 internal static bool MainDriver (string [] args)
1325 bool parsing_options = true;
1328 encoding = Encoding.GetEncoding (28591);
1330 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1331 encoding = Encoding.GetEncoding (1252);
1334 references = new ArrayList ();
1335 soft_references = new ArrayList ();
1336 modules = new ArrayList ();
1337 link_paths = new ArrayList ();
1339 SetupDefaultDefines ();
1344 // This is not required because Assembly.Load knows about this
1348 for (i = 0; i < args.Length; i++){
1349 string arg = args [i];
1353 if (arg.StartsWith ("@")){
1354 string [] extra_args;
1355 string response_file = arg.Substring (1);
1357 if (response_file_list == null)
1358 response_file_list = new Hashtable ();
1360 if (response_file_list.Contains (response_file)){
1362 1515, "Response file `" + response_file +
1363 "' specified multiple times");
1364 Environment.Exit (1);
1367 response_file_list.Add (response_file, response_file);
1369 extra_args = LoadArgs (response_file);
1370 if (extra_args == null){
1371 Report.Error (2011, "Unable to open response file: " +
1376 args = AddArgs (args, extra_args);
1380 if (parsing_options){
1382 parsing_options = false;
1386 if (arg.StartsWith ("-")){
1387 if (UnixParseOption (arg, ref args, ref i))
1391 string csc_opt = "/" + arg.Substring (1);
1392 if (CSCParseOption (csc_opt, ref args, ref i))
1395 if (arg.StartsWith ("/")){
1396 if (CSCParseOption (arg, ref args, ref i))
1402 CompileFiles (arg, false);
1411 // If we are an exe, require a source file for the entry point
1413 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1414 if (first_source == null){
1415 Report.Error (2008, "No files to compile were specified");
1422 // If there is nothing to put in the assembly, and we are not a library
1424 if (first_source == null && embedded_resources == null && resources == null){
1425 Report.Error (2008, "No files to compile were specified");
1429 if (Report.Errors > 0)
1435 Tokenizer.Cleanup ();
1438 // Load Core Library for default compilation
1440 if (RootContext.StdLib)
1441 references.Insert (0, "mscorlib");
1443 if (load_default_config)
1444 DefineDefaultConfig ();
1446 if (Report.Errors > 0){
1451 // Load assemblies required
1454 ShowTime ("Loading references");
1455 link_paths.Add (GetSystemDir ());
1456 link_paths.Add (Directory.GetCurrentDirectory ());
1460 ShowTime (" References loaded");
1462 if (Report.Errors > 0){
1469 if (output_file == null){
1470 int pos = first_source.LastIndexOf ('.');
1473 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1475 output_file = first_source + RootContext.TargetExt;
1478 CodeGen.Init (output_file, output_file, want_debugging_support);
1480 if (RootContext.Target == Target.Module) {
1481 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1482 if (module_only == null) {
1483 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1484 Environment.Exit (1);
1487 MethodInfo set_method = module_only.GetSetMethod (true);
1488 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1491 TypeManager.AddModule (CodeGen.Module.Builder);
1493 if (modules.Count > 0) {
1494 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1495 if (adder_method == null) {
1496 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1497 Environment.Exit (1);
1500 foreach (string module in modules)
1501 LoadModule (adder_method, module);
1504 TypeManager.ComputeNamespaces ();
1507 // Before emitting, we need to get the core
1508 // types emitted from the user defined types
1509 // or from the system ones.
1512 ShowTime ("Initializing Core Types");
1513 if (!RootContext.StdLib){
1514 RootContext.ResolveCore ();
1515 if (Report.Errors > 0)
1519 TypeManager.InitCoreTypes ();
1521 ShowTime (" Core Types done");
1524 // The second pass of the compiler
1527 ShowTime ("Resolving tree");
1528 RootContext.ResolveTree ();
1529 if (Report.Errors > 0)
1532 ShowTime ("Populate tree");
1533 if (!RootContext.StdLib)
1534 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 if (CodeGen.Assembly.IsClsCompliant) {
1553 AttributeTester.VerifyModulesClsCompliance ();
1554 TypeManager.LoadAllImportedTypes ();
1555 AttributeTester.VerifyTopLevelNameClsCompliance ();
1560 // The code generator
1563 ShowTime ("Emitting code");
1564 ShowTotalTime ("Total so far");
1565 RootContext.EmitCode ();
1569 if (Report.Errors > 0){
1574 ShowTime ("Closing types");
1576 RootContext.CloseTypes ();
1578 PEFileKinds k = PEFileKinds.ConsoleApplication;
1580 switch (RootContext.Target) {
1581 case Target.Library:
1583 k = PEFileKinds.Dll; break;
1585 k = PEFileKinds.ConsoleApplication; break;
1587 k = PEFileKinds.WindowApplication; break;
1590 if (RootContext.NeedsEntryPoint) {
1591 MethodInfo ep = RootContext.EntryPoint;
1594 if (RootContext.MainClass != null) {
1595 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1596 if (main_cont == null) {
1597 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1601 if (!(main_cont is ClassOrStruct)) {
1602 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1607 if (Report.Errors == 0)
1608 Report.Error (5001, "Program " + output_file +
1609 " does not have an entry point defined");
1613 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1614 } else if (RootContext.MainClass != null) {
1615 Report.Error (2017, "Can not specify -main: when building module or library");
1619 // Add the resources
1621 if (resources != null){
1622 foreach (string spec in resources){
1626 cp = spec.IndexOf (',');
1628 file = spec.Substring (0, cp);
1629 res = spec.Substring (cp + 1);
1633 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1637 if (embedded_resources != null){
1638 object[] margs = new object [2];
1639 Type[] argst = new Type [2];
1640 argst [0] = argst [1] = typeof (string);
1642 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1643 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1644 null, CallingConventions.Any, argst, null);
1646 if (embed_res == null) {
1647 Report.Warning (0, new Location (-1),
1648 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1650 foreach (string spec in embedded_resources) {
1653 cp = spec.IndexOf (',');
1655 margs [0] = spec.Substring (cp + 1);
1656 margs [1] = spec.Substring (0, cp);
1659 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1662 if (File.Exists ((string) margs [1]))
1663 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1665 Report.Error (1566, "Can not find the resource " + margs [1]);
1672 // Add Win32 resources
1675 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1677 if (win32ResourceFile != null) {
1679 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1681 catch (ArgumentException) {
1682 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1686 if (win32IconFile != null) {
1687 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1688 if (define_icon == null) {
1689 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1691 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1694 if (Report.Errors > 0)
1697 CodeGen.Save (output_file);
1699 ShowTime ("Saved output");
1700 ShowTotalTime ("Total");
1703 Timer.ShowTimers ();
1705 if (Report.ExpectedError != 0) {
1706 if (Report.Errors == 0) {
1707 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1708 "No other errors reported.");
1710 Environment.Exit (2);
1712 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1713 "However, other errors were reported.");
1715 Environment.Exit (1);
1723 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1724 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1726 return (Report.Errors == 0);
1732 // This is the only public entry point
1734 public class CompilerCallableEntryPoint : MarshalByRefObject {
1735 static bool used = false;
1737 public bool InvokeCompiler (string [] args)
1741 bool ok = Driver.MainDriver (args);
1742 return ok && Report.Errors == 0;
1745 public void Reset ()