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)
9 // (C) 2004 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.Diagnostics;
21 using System.Globalization;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references;
47 // Modules to be linked
49 static ArrayList modules;
52 static ArrayList link_paths;
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;
67 // Whether to load the initial config file (what CSC.RSP has by default)
69 static bool load_default_config = true;
71 static Hashtable response_file_list;
74 // A list of resource files
76 static ArrayList resources;
77 static ArrayList embedded_resources;
78 static string win32ResourceFile;
79 static string win32IconFile;
82 // An array of the defines from the command line
84 static ArrayList defines;
89 static string output_file = null;
92 // Last time we took the time
94 static DateTime last_time, first_time;
97 // Encoding: ISO-Latin1 is 28591
99 static Encoding encoding;
102 // Whether the user has specified a different encoder manually
104 static bool using_default_encoder = true;
106 public static void ShowTime (string msg)
111 DateTime now = DateTime.Now;
112 TimeSpan span = now - last_time;
116 "[{0:00}:{1:000}] {2}",
117 (int) span.TotalSeconds, span.Milliseconds, msg);
120 public static void ShowTotalTime (string msg)
125 DateTime now = DateTime.Now;
126 TimeSpan span = now - first_time;
130 "[{0:00}:{1:000}] {2}",
131 (int) span.TotalSeconds, span.Milliseconds, msg);
134 static void tokenize_file (SourceFile file)
139 input = File.OpenRead (file.Name);
141 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
146 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
147 Tokenizer lexer = new Tokenizer (reader, file, defines);
148 int token, tokens = 0, errors = 0;
150 while ((token = lexer.token ()) != Token.EOF){
152 if (token == Token.ERROR)
155 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
161 // MonoTODO("Change error code for aborted compilation to something reasonable")]
162 static void parse (SourceFile file)
168 input = File.OpenRead (file.Name);
170 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
174 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
176 parser = new CSharpParser (reader, file, defines);
179 } catch (Exception ex) {
180 Report.Error(666, "Compilation aborted: " + ex);
186 static void OtherFlags ()
189 "Other flags in the compiler\n" +
190 " --fatal Makes errors fatal\n" +
191 " --parse Only parses the source file\n" +
192 " --stacktrace Shows stack trace at error location\n" +
193 " --timestamp Displays time stamps of various compiler events\n" +
194 " -2 Enables experimental C# features\n" +
195 " -v Verbose parsing (for debugging the parser)\n" +
196 " --mcs-debug X Sets MCS debugging level to X\n");
202 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
203 "mcs [options] source-files\n" +
204 " --about About the Mono C# compiler\n" +
205 " -addmodule:MODULE Adds the module to the generated assembly\n" +
206 " -checked[+|-] Set default context to checked\n" +
207 " -codepage:ID Sets code page to the one in ID\n" +
208 " (number, `utf8' or `reset')\n" +
209 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
210 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
211 " -debug[+|-] Generate debugging information\n" +
212 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
213 " -doc:FILE XML Documentation file to generate\n" +
214 " -g Generate debugging information\n" +
215 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
216 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
217 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
218 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
219 " -main:class Specified the class that contains the entry point\n" +
220 " -noconfig[+|-] Disables implicit references to assemblies\n" +
221 " -nostdlib[+|-] Does not load core libraries\n" +
222 " -nowarn:W1[,W2] Disables one or more warnings\n" +
223 " -out:FNAME Specifies output file\n" +
224 " -doc:XMLFILE Generates xml documentation into specified file\n" +
225 " -pkg:P1[,Pn] References packages P1..Pn\n" +
226 " --expect-error X Expect that error X will be encountered\n" +
227 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
228 " -reference:ASS References the specified assembly (-r:ASS)\n" +
229 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
230 " library, module), (short: /t:)\n" +
231 " -unsafe[+|-] Allows unsafe code\n" +
232 " -warnaserror[+|-] Treat warnings as errors\n" +
233 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
234 " -help2 Show other help flags\n" +
237 // VB.NET specific compiler options
239 " -removeintchecks[+|-] Set default context to unchecked\n" +
240 " -optionstrict[+|-] Enables stricter type checking\n" +
244 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
245 " -resource:FILE[,ID] Embed FILE as a resource\n" +
246 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
247 " -win32icon:FILE Use this icon for the output\n" +
248 " @file Read response file for more options\n\n" +
249 "Options can be of the form -option or /option");
252 static void TargetUsage ()
254 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
260 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
261 "The compiler source code is released under the terms of the GNU GPL\n\n" +
263 "For more information on Mono, visit the project Web site\n" +
264 " http://www.go-mono.com\n\n" +
266 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
267 Environment.Exit (0);
270 public static int counter1, counter2;
272 public static int Main (string[] args)
274 RootContext.Version = LanguageVersion.Default;
275 bool ok = MainDriver (args);
277 if (ok && Report.Errors == 0) {
278 if (Report.Warnings > 0) {
279 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
282 Console.WriteLine ("Counter1: " + counter1);
283 Console.WriteLine ("Counter2: " + counter2);
289 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
290 Report.Errors, Report.Warnings);
295 static public void LoadAssembly (string assembly, bool soft)
298 string total_log = "";
301 char[] path_chars = { '/', '\\' };
303 if (assembly.IndexOfAny (path_chars) != -1) {
304 a = Assembly.LoadFrom (assembly);
306 string ass = assembly;
307 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
308 ass = assembly.Substring (0, assembly.Length - 4);
309 a = Assembly.Load (ass);
311 TypeManager.AddAssembly (a);
313 } catch (FileNotFoundException){
314 foreach (string dir in link_paths){
315 string full_path = Path.Combine (dir, assembly);
316 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
320 a = Assembly.LoadFrom (full_path);
321 TypeManager.AddAssembly (a);
323 } catch (FileNotFoundException ff) {
324 total_log += ff.FusionLog;
329 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
330 Console.WriteLine ("Log: \n" + total_log);
332 } catch (BadImageFormatException f) {
333 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
334 } catch (FileLoadException f){
335 Report.Error(6, "Cannot load assembly " + f.FusionLog);
336 } catch (ArgumentNullException){
337 Report.Error(6, "Cannot load assembly (null argument)");
341 static public void LoadModule (MethodInfo adder_method, string module)
344 string total_log = "";
348 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
350 catch (TargetInvocationException ex) {
351 throw ex.InnerException;
353 TypeManager.AddModule (m);
356 catch (FileNotFoundException){
357 foreach (string dir in link_paths){
358 string full_path = Path.Combine (dir, module);
359 if (!module.EndsWith (".netmodule"))
360 full_path += ".netmodule";
364 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
366 catch (TargetInvocationException ex) {
367 throw ex.InnerException;
369 TypeManager.AddModule (m);
371 } catch (FileNotFoundException ff) {
372 total_log += ff.FusionLog;
376 Report.Error (6, "Cannot find module `" + module + "'" );
377 Console.WriteLine ("Log: \n" + total_log);
378 } catch (BadImageFormatException f) {
379 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
380 } catch (FileLoadException f){
381 Report.Error(6, "Cannot load module " + f.FusionLog);
382 } catch (ArgumentNullException){
383 Report.Error(6, "Cannot load module (null argument)");
388 /// Loads all assemblies referenced on the command line
390 static public void LoadReferences ()
392 foreach (string r in references)
393 LoadAssembly (r, false);
395 foreach (string r in soft_references)
396 LoadAssembly (r, true);
401 static void SetupDefaultDefines ()
403 defines = new ArrayList ();
404 defines.Add ("__MonoCS__");
407 static string [] LoadArgs (string file)
410 ArrayList args = new ArrayList ();
413 f = new StreamReader (file);
418 StringBuilder sb = new StringBuilder ();
420 while ((line = f.ReadLine ()) != null){
423 for (int i = 0; i < t; i++){
426 if (c == '"' || c == '\''){
429 for (i++; i < t; i++){
436 } else if (c == ' '){
438 args.Add (sb.ToString ());
445 args.Add (sb.ToString ());
450 string [] ret_value = new string [args.Count];
451 args.CopyTo (ret_value, 0);
457 // Returns the directory where the system assemblies are installed
459 static string GetSystemDir ()
461 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
463 foreach (Assembly a in assemblies){
464 string codebase = a.Location;
465 string fn = System.IO.Path.GetFileName (codebase);
466 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
467 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
471 Report.Error (-15, "Can not compute my system path");
476 // Given a path specification, splits the path from the file/pattern
478 static void SplitPathAndPattern (string spec, out string path, out string pattern)
480 int p = spec.LastIndexOf ('/');
483 // Windows does not like /file.cs, switch that to:
488 pattern = spec.Substring (1);
490 path = spec.Substring (0, p);
491 pattern = spec.Substring (p + 1);
496 p = spec.LastIndexOf ('\\');
498 path = spec.Substring (0, p);
499 pattern = spec.Substring (p + 1);
507 static void ProcessFile (string f)
509 if (first_source == null)
512 Location.AddFile (f);
515 static void ProcessFiles ()
517 Location.Initialize ();
519 foreach (SourceFile file in Location.SourceFiles) {
521 tokenize_file (file);
528 static void CompileFiles (string spec, bool recurse)
530 string path, pattern;
532 SplitPathAndPattern (spec, out path, out pattern);
533 if (pattern.IndexOf ('*') == -1){
538 string [] files = null;
540 files = Directory.GetFiles (path, pattern);
541 } catch (System.IO.DirectoryNotFoundException) {
542 Report.Error (2001, "Source file `" + spec + "' could not be found");
544 } catch (System.IO.IOException){
545 Report.Error (2001, "Source file `" + spec + "' could not be found");
548 foreach (string f in files) {
555 string [] dirs = null;
558 dirs = Directory.GetDirectories (path);
562 foreach (string d in dirs) {
564 // Don't include path in this string, as each
565 // directory entry already does
566 CompileFiles (d + "/" + pattern, true);
570 static void DefineDefaultConfig ()
573 // For now the "default config" is harcoded into the compiler
574 // we can move this outside later
576 string [] default_config = {
579 "Microsoft.VisualBasic",
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.Version = LanguageVersion.Default;
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 CSharpParser.yacc_verbose_flag++;
676 case "--main": case "-m":
677 if ((i + 1) >= args.Length){
679 Environment.Exit (1);
681 RootContext.MainClass = args [++i];
685 RootContext.Unsafe = true;
688 case "/?": case "/h": case "/help":
691 Environment.Exit (0);
695 if ((i + 1) >= args.Length){
697 Environment.Exit (1);
699 defines.Add (args [++i]);
702 case "--show-counters":
703 show_counters = true;
706 case "--expect-error": {
711 args [++i], NumberStyles.AllowLeadingSign);
712 Report.ExpectedError = code;
714 Report.Error (-14, "Invalid number specified");
725 if ((i + 1) >= args.Length){
727 Environment.Exit (1);
729 SetOutputFile (args [++i]);
733 RootContext.Checked = true;
738 Report.Stacktrace = true;
741 case "--linkresource":
743 if ((i + 1) >= args.Length){
745 Report.Error (5, "Missing argument to --linkres");
746 Environment.Exit (1);
748 if (resources == null)
749 resources = new ArrayList ();
751 resources.Add (args [++i]);
756 if ((i + 1) >= args.Length){
758 Report.Error (5, "Missing argument to --resource");
759 Environment.Exit (1);
761 if (embedded_resources == null)
762 embedded_resources = new ArrayList ();
764 embedded_resources.Add (args [++i]);
768 if ((i + 1) >= args.Length){
769 Environment.Exit (1);
773 string type = args [++i];
776 RootContext.Target = Target.Library;
777 RootContext.TargetExt = ".dll";
781 RootContext.Target = Target.Exe;
785 RootContext.Target = Target.WinExe;
789 RootContext.Target = Target.Module;
790 RootContext.TargetExt = ".dll";
794 Environment.Exit (1);
800 if ((i + 1) >= args.Length){
802 Environment.Exit (1);
805 references.Add (args [++i]);
809 if ((i + 1) >= args.Length){
811 Environment.Exit (1);
813 link_paths.Add (args [++i]);
817 RootContext.StdLib = false;
825 Report.WarningsAreErrors = true;
826 TestWarningConflict();
830 if ((i + 1) >= args.Length){
832 Environment.Exit (1);
837 warn = Int32.Parse (args [++i]);
840 Environment.Exit (1);
842 Report.SetIgnoreWarning (warn);
846 if ((i + 1) >= args.Length){
849 "--wlevel requires a value from 0 to 4");
850 Environment.Exit (1);
853 SetWarningLevel (args [++i]);
857 if ((i + 1) >= args.Length){
858 Report.Error (5, "--mcs-debug requires an argument");
859 Environment.Exit (1);
863 Report.DebugFlags = Int32.Parse (args [++i]);
865 Report.Error (5, "Invalid argument to --mcs-debug");
866 Environment.Exit (1);
875 if ((i + 1) >= args.Length){
876 Report.Error (5, "--recurse requires an argument");
877 Environment.Exit (1);
879 CompileFiles (args [++i], true);
884 last_time = first_time = DateTime.Now;
891 case "--debug": case "-g":
892 want_debugging_support = true;
896 load_default_config = false;
900 // VB.NET specific compiler options
903 case "--removeintchecks":
904 RootContext.Checked = false;
907 case "--optionstrict":
908 RootContext.StricterTypeChecking= true;
917 // Currently it is very basic option parsing, but eventually, this will
918 // be the complete option parser
920 static bool CSCParseOption (string option, ref string [] args, ref int i)
922 int idx = option.IndexOf (':');
929 arg = option.Substring (0, idx);
931 value = option.Substring (idx + 1);
942 RootContext.Target = Target.Exe;
946 RootContext.Target = Target.WinExe;
950 RootContext.Target = Target.Library;
951 RootContext.TargetExt = ".dll";
955 RootContext.Target = Target.Module;
956 RootContext.TargetExt = ".netmodule";
961 Environment.Exit (1);
969 Environment.Exit (1);
971 SetOutputFile (value);
978 case "/incremental+":
979 case "/incremental-":
989 Environment.Exit (1);
992 defs = value.Split (new Char [] {';', ','});
993 foreach (string d in defs){
1000 case "/linkresource":
1002 Report.Error (5, arg + " requires an argument");
1003 Environment.Exit (1);
1005 if (resources == null)
1006 resources = new ArrayList ();
1008 resources.Add (value);
1016 Environment.Exit (1);
1018 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1020 ProcessStartInfo pi = new ProcessStartInfo ();
1021 pi.FileName = "pkg-config";
1022 pi.RedirectStandardOutput = true;
1023 pi.UseShellExecute = false;
1024 pi.Arguments = "--libs " + packages;
1027 p = Process.Start (pi);
1028 } catch (Exception e) {
1029 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1030 Environment.Exit (1);
1033 if (p.StandardOutput == null){
1034 Report.Warning (-27, "Specified package did not return any information");
1037 string pkgout = p.StandardOutput.ReadToEnd ();
1039 if (p.ExitCode != 0) {
1040 Report.Error (-27, "Error running pkg-config. Check the above output.");
1041 Environment.Exit (1);
1044 if (pkgout != null){
1045 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1046 Split (new Char [] { ' ', '\t'});
1047 args = AddArgs (args, xargs);
1057 Report.Error (5, "-resource requires an argument");
1058 Environment.Exit (1);
1060 if (embedded_resources == null)
1061 embedded_resources = new ArrayList ();
1063 if (embedded_resources.Contains (value)) {
1064 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1066 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1067 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1070 embedded_resources.Add (value);
1076 Report.Error (5, "-recurse requires an argument");
1077 Environment.Exit (1);
1079 CompileFiles (value, true);
1083 case "/reference": {
1085 Report.Error (5, "-reference requires an argument");
1086 Environment.Exit (1);
1089 string [] refs = value.Split (new char [] { ';', ',' });
1090 foreach (string r in refs){
1095 case "/addmodule": {
1097 Report.Error (5, arg + " requires an argument");
1098 Environment.Exit (1);
1101 string [] refs = value.Split (new char [] { ';', ',' });
1102 foreach (string r in refs){
1109 Report.Error (5, arg + " requires an argument");
1110 Environment.Exit (1);
1113 win32ResourceFile = value;
1116 case "/win32icon": {
1118 Report.Error (5, arg + " requires an argument");
1119 Environment.Exit (1);
1122 win32IconFile = value;
1127 Report.Error (2006, arg + " requires an argument");
1128 Environment.Exit (1);
1130 RootContext.Documentation = new Documentation (value);
1137 Report.Error (5, "/lib requires an argument");
1138 Environment.Exit (1);
1141 libdirs = value.Split (new Char [] { ',' });
1142 foreach (string dir in libdirs)
1143 link_paths.Add (dir);
1148 want_debugging_support = false;
1153 want_debugging_support = true;
1158 RootContext.Checked = true;
1162 RootContext.Checked = false;
1171 RootContext.VerifyClsCompliance = false;
1176 RootContext.Unsafe = true;
1180 RootContext.Unsafe = false;
1183 case "/warnaserror":
1184 case "/warnaserror+":
1185 Report.WarningsAreErrors = true;
1186 TestWarningConflict();
1189 case "/warnaserror-":
1190 Report.WarningsAreErrors = false;
1194 SetWarningLevel (value);
1201 Report.Error (5, "/nowarn requires an argument");
1202 Environment.Exit (1);
1205 warns = value.Split (new Char [] {','});
1206 foreach (string wc in warns){
1208 int warn = Int32.Parse (wc);
1210 throw new ArgumentOutOfRangeException("warn");
1212 Report.SetIgnoreWarning (warn);
1214 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1215 Environment.Exit (1);
1222 load_default_config = true;
1227 load_default_config = false;
1232 Environment.Exit(0);
1238 Environment.Exit (0);
1244 Report.Error (5, arg + " requires an argument");
1245 Environment.Exit (1);
1247 RootContext.MainClass = value;
1252 RootContext.StdLib = false;
1256 RootContext.StdLib = true;
1263 if (value == String.Empty) {
1264 Report.Error (5, arg + " requires an argument");
1265 Environment.Exit (1);
1267 RootContext.StrongNameKeyFile = value;
1269 case "/keycontainer":
1270 if (value == String.Empty) {
1271 Report.Error (5, arg + " requires an argument");
1272 Environment.Exit (1);
1274 RootContext.StrongNameKeyContainer = value;
1277 RootContext.StrongNameDelaySign = true;
1280 RootContext.StrongNameDelaySign = false;
1285 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1289 case "/langversion":
1290 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1292 RootContext.Version = LanguageVersion.ISO_1;
1299 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1300 Environment.Exit (1);
1306 if (value == "utf8"){
1307 encoding = new UTF8Encoding();
1308 using_default_encoder = false;
1311 if (value == "reset"){
1313 // 28591 is the code page for ISO-8859-1 encoding.
1316 using_default_encoder = true;
1320 cp = Int32.Parse (value);
1321 encoding = Encoding.GetEncoding (cp);
1322 using_default_encoder = false;
1324 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1325 Environment.Exit (1);
1330 // VB.NET specific compiler options
1333 case "/removeintchecks":
1334 case "/removeintchecks+":
1335 RootContext.Checked = false;
1338 case "/removeintchecks-":
1339 RootContext.Checked = true;
1342 case "/optionstrict":
1343 case "/optionstrict+":
1344 RootContext.StricterTypeChecking = true;
1347 case "/optionstrict-":
1348 RootContext.StricterTypeChecking = false;
1352 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1353 //Environment.Exit (1);
1357 static string [] AddArgs (string [] args, string [] extra_args)
1360 new_args = new string [extra_args.Length + args.Length];
1362 // if args contains '--' we have to take that into account
1363 // split args into first half and second half based on '--'
1364 // and add the extra_args before --
1365 int split_position = Array.IndexOf (args, "--");
1366 if (split_position != -1)
1368 Array.Copy (args, new_args, split_position);
1369 extra_args.CopyTo (new_args, split_position);
1370 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1374 args.CopyTo (new_args, 0);
1375 extra_args.CopyTo (new_args, args.Length);
1382 /// Parses the arguments, and drives the compilation
1387 /// TODO: Mostly structured to debug the compiler
1388 /// now, needs to be turned into a real driver soon.
1390 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1391 internal static bool MainDriver (string [] args)
1394 bool parsing_options = true;
1397 encoding = Encoding.GetEncoding (28591);
1399 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1400 encoding = Encoding.GetEncoding (1252);
1403 references = new ArrayList ();
1404 soft_references = new ArrayList ();
1405 modules = new ArrayList ();
1406 link_paths = new ArrayList ();
1408 SetupDefaultDefines ();
1413 // This is not required because Assembly.Load knows about this
1417 for (i = 0; i < args.Length; i++){
1418 string arg = args [i];
1422 if (arg.StartsWith ("@")){
1423 string [] extra_args;
1424 string response_file = arg.Substring (1);
1426 if (response_file_list == null)
1427 response_file_list = new Hashtable ();
1429 if (response_file_list.Contains (response_file)){
1431 1515, "Response file `" + response_file +
1432 "' specified multiple times");
1433 Environment.Exit (1);
1436 response_file_list.Add (response_file, response_file);
1438 extra_args = LoadArgs (response_file);
1439 if (extra_args == null){
1440 Report.Error (2011, "Unable to open response file: " +
1445 args = AddArgs (args, extra_args);
1449 if (parsing_options){
1451 parsing_options = false;
1455 if (arg.StartsWith ("-")){
1456 if (UnixParseOption (arg, ref args, ref i))
1460 string csc_opt = "/" + arg.Substring (1);
1461 if (CSCParseOption (csc_opt, ref args, ref i))
1464 if (arg.StartsWith ("/")){
1465 if (CSCParseOption (arg, ref args, ref i))
1471 CompileFiles (arg, false);
1480 // This will point to the NamespaceEntry of the last file that was parsed, and may
1481 // not be meaningful when resolving classes from other files. So, reset it to prevent
1484 RootContext.Tree.Types.NamespaceEntry = null;
1487 // If we are an exe, require a source file for the entry point
1489 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1490 if (first_source == null){
1491 Report.Error (2008, "No files to compile were specified");
1498 // If there is nothing to put in the assembly, and we are not a library
1500 if (first_source == null && embedded_resources == null && resources == null){
1501 Report.Error (2008, "No files to compile were specified");
1505 if (Report.Errors > 0)
1511 Tokenizer.Cleanup ();
1514 // Load Core Library for default compilation
1516 if (RootContext.StdLib)
1517 references.Insert (0, "mscorlib");
1519 if (load_default_config)
1520 DefineDefaultConfig ();
1522 if (Report.Errors > 0){
1527 // Load assemblies required
1530 ShowTime ("Loading references");
1531 link_paths.Add (GetSystemDir ());
1532 link_paths.Add (Directory.GetCurrentDirectory ());
1536 ShowTime (" References loaded");
1538 if (Report.Errors > 0){
1545 if (output_file == null){
1546 int pos = first_source.LastIndexOf ('.');
1549 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1551 output_file = first_source + RootContext.TargetExt;
1554 CodeGen.Init (output_file, output_file, want_debugging_support);
1556 if (RootContext.Target == Target.Module) {
1557 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1558 if (module_only == null) {
1559 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1560 Environment.Exit (1);
1563 MethodInfo set_method = module_only.GetSetMethod (true);
1564 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1567 TypeManager.AddModule (CodeGen.Module.Builder);
1569 if (modules.Count > 0) {
1570 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1571 if (adder_method == null) {
1572 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1573 Environment.Exit (1);
1576 foreach (string module in modules)
1577 LoadModule (adder_method, module);
1580 TypeManager.ComputeNamespaces ();
1583 // Before emitting, we need to get the core
1584 // types emitted from the user defined types
1585 // or from the system ones.
1588 ShowTime ("Initializing Core Types");
1589 if (!RootContext.StdLib){
1590 RootContext.ResolveCore ();
1591 if (Report.Errors > 0)
1595 TypeManager.InitCoreTypes ();
1597 ShowTime (" Core Types done");
1600 // The second pass of the compiler
1603 ShowTime ("Resolving tree");
1604 RootContext.ResolveTree ();
1606 if (Report.Errors > 0)
1609 ShowTime ("Populate tree");
1610 if (!RootContext.StdLib)
1611 RootContext.BootCorlib_PopulateCoreTypes ();
1612 RootContext.PopulateTypes ();
1613 RootContext.DefineTypes ();
1615 if (RootContext.Documentation != null &&
1616 !RootContext.Documentation.OutputDocComment (
1620 TypeManager.InitCodeHelpers ();
1623 // Verify using aliases now
1625 Namespace.VerifyUsing ();
1627 if (Report.Errors > 0){
1631 if (RootContext.VerifyClsCompliance) {
1632 CodeGen.Assembly.ResolveClsCompliance ();
1633 if (CodeGen.Assembly.IsClsCompliant) {
1634 AttributeTester.VerifyModulesClsCompliance ();
1635 TypeManager.LoadAllImportedTypes ();
1636 AttributeTester.VerifyTopLevelNameClsCompliance ();
1641 // The code generator
1644 ShowTime ("Emitting code");
1645 ShowTotalTime ("Total so far");
1646 RootContext.EmitCode ();
1650 if (Report.Errors > 0){
1655 ShowTime ("Closing types");
1657 RootContext.CloseTypes ();
1659 PEFileKinds k = PEFileKinds.ConsoleApplication;
1661 switch (RootContext.Target) {
1662 case Target.Library:
1664 k = PEFileKinds.Dll; break;
1666 k = PEFileKinds.ConsoleApplication; break;
1668 k = PEFileKinds.WindowApplication; break;
1671 if (RootContext.NeedsEntryPoint) {
1672 MethodInfo ep = RootContext.EntryPoint;
1675 if (RootContext.MainClass != null) {
1676 DeclSpace main_cont = RootContext.Tree.Decls [RootContext.MainClass] as DeclSpace;
1677 if (main_cont == null) {
1678 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1682 if (!(main_cont is ClassOrStruct)) {
1683 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1687 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1691 if (Report.Errors == 0)
1692 Report.Error (5001, "Program " + output_file +
1693 " does not have an entry point defined");
1697 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1698 } else if (RootContext.MainClass != null) {
1699 Report.Error (2017, "Can not specify -main: when building module or library");
1703 // Add the resources
1705 if (resources != null){
1706 foreach (string spec in resources){
1710 cp = spec.IndexOf (',');
1712 file = spec.Substring (0, cp);
1713 res = spec.Substring (cp + 1);
1717 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1721 if (embedded_resources != null){
1722 object[] margs = new object [2];
1723 Type[] argst = new Type [2];
1724 argst [0] = argst [1] = typeof (string);
1726 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1727 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1728 null, CallingConventions.Any, argst, null);
1730 if (embed_res == null) {
1731 Report.Warning (0, new Location (-1),
1732 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1734 foreach (string spec in embedded_resources) {
1737 cp = spec.IndexOf (',');
1739 margs [0] = spec.Substring (cp + 1);
1740 margs [1] = spec.Substring (0, cp);
1743 margs [0] = Path.GetFileName (spec);
1746 if (File.Exists ((string) margs [1]))
1747 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1749 Report.Error (1566, "Can not find the resource " + margs [1]);
1756 // Add Win32 resources
1759 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1761 if (win32ResourceFile != null) {
1763 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1765 catch (ArgumentException) {
1766 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1770 if (win32IconFile != null) {
1771 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1772 if (define_icon == null) {
1773 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1775 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1778 if (Report.Errors > 0)
1781 CodeGen.Save (output_file);
1783 ShowTime ("Saved output");
1784 ShowTotalTime ("Total");
1787 Timer.ShowTimers ();
1789 if (Report.ExpectedError != 0){
1790 if (Report.Errors == 0) {
1791 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1792 "No other errors reported.");
1794 Environment.Exit (2);
1796 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1797 "However, other errors were reported.");
1799 Environment.Exit (1);
1807 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1808 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1810 return (Report.Errors == 0);
1815 // This is the only public entry point
1817 public class CompilerCallableEntryPoint : MarshalByRefObject {
1818 static bool used = false;
1820 public bool InvokeCompiler (string [] args)
1824 bool ok = Driver.MainDriver (args);
1825 return ok && Report.Errors == 0;
1828 public void Reset ()