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 " -optimize[+|-] Enables code optimalizations" + Environment.NewLine +
224 " -out:FNAME Specifies output 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 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
238 " -resource:FILE[,ID] Embed FILE as a resource\n" +
239 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
240 " -win32icon:FILE Use this icon for the output\n" +
241 " @file Read response file for more options\n\n" +
242 "Options can be of the form -option or /option");
245 static void TargetUsage ()
247 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
253 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
254 "The compiler source code is released under the terms of the GNU GPL\n\n" +
256 "For more information on Mono, visit the project Web site\n" +
257 " http://www.go-mono.com\n\n" +
259 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
260 Environment.Exit (0);
263 public static int counter1, counter2;
265 public static int Main (string[] args)
267 RootContext.Version = LanguageVersion.Default;
268 bool ok = MainDriver (args);
270 if (ok && Report.Errors == 0) {
271 if (Report.Warnings > 0) {
272 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
275 Console.WriteLine ("Counter1: " + counter1);
276 Console.WriteLine ("Counter2: " + counter2);
282 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
283 Report.Errors, Report.Warnings);
288 static public void LoadAssembly (string assembly, bool soft)
291 string total_log = "";
294 char[] path_chars = { '/', '\\' };
296 if (assembly.IndexOfAny (path_chars) != -1) {
297 a = Assembly.LoadFrom (assembly);
299 string ass = assembly;
300 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
301 ass = assembly.Substring (0, assembly.Length - 4);
302 a = Assembly.Load (ass);
304 TypeManager.AddAssembly (a);
306 } catch (FileNotFoundException){
307 foreach (string dir in link_paths){
308 string full_path = Path.Combine (dir, assembly);
309 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
313 a = Assembly.LoadFrom (full_path);
314 TypeManager.AddAssembly (a);
316 } catch (FileNotFoundException ff) {
317 total_log += ff.FusionLog;
322 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
323 Console.WriteLine ("Log: \n" + total_log);
325 } catch (BadImageFormatException f) {
326 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
327 } catch (FileLoadException f){
328 Report.Error(6, "Cannot load assembly " + f.FusionLog);
329 } catch (ArgumentNullException){
330 Report.Error(6, "Cannot load assembly (null argument)");
334 static public void LoadModule (MethodInfo adder_method, string module)
337 string total_log = "";
341 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
343 catch (TargetInvocationException ex) {
344 throw ex.InnerException;
346 TypeManager.AddModule (m);
349 catch (FileNotFoundException){
350 foreach (string dir in link_paths){
351 string full_path = Path.Combine (dir, module);
352 if (!module.EndsWith (".netmodule"))
353 full_path += ".netmodule";
357 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
359 catch (TargetInvocationException ex) {
360 throw ex.InnerException;
362 TypeManager.AddModule (m);
364 } catch (FileNotFoundException ff) {
365 total_log += ff.FusionLog;
369 Report.Error (6, "Cannot find module `" + module + "'" );
370 Console.WriteLine ("Log: \n" + total_log);
371 } catch (BadImageFormatException f) {
372 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
373 } catch (FileLoadException f){
374 Report.Error(6, "Cannot load module " + f.FusionLog);
375 } catch (ArgumentNullException){
376 Report.Error(6, "Cannot load module (null argument)");
381 /// Loads all assemblies referenced on the command line
383 static public void LoadReferences ()
385 foreach (string r in references)
386 LoadAssembly (r, false);
388 foreach (string r in soft_references)
389 LoadAssembly (r, true);
394 static void SetupDefaultDefines ()
396 defines = new ArrayList ();
397 defines.Add ("__MonoCS__");
400 static string [] LoadArgs (string file)
403 ArrayList args = new ArrayList ();
406 f = new StreamReader (file);
411 StringBuilder sb = new StringBuilder ();
413 while ((line = f.ReadLine ()) != null){
416 for (int i = 0; i < t; i++){
419 if (c == '"' || c == '\''){
422 for (i++; i < t; i++){
429 } else if (c == ' '){
431 args.Add (sb.ToString ());
438 args.Add (sb.ToString ());
443 string [] ret_value = new string [args.Count];
444 args.CopyTo (ret_value, 0);
450 // Returns the directory where the system assemblies are installed
452 static string GetSystemDir ()
454 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
456 foreach (Assembly a in assemblies){
457 string codebase = a.Location;
458 string fn = System.IO.Path.GetFileName (codebase);
459 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
460 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
464 Report.Error (-15, "Can not compute my system path");
469 // Given a path specification, splits the path from the file/pattern
471 static void SplitPathAndPattern (string spec, out string path, out string pattern)
473 int p = spec.LastIndexOf ('/');
476 // Windows does not like /file.cs, switch that to:
481 pattern = spec.Substring (1);
483 path = spec.Substring (0, p);
484 pattern = spec.Substring (p + 1);
489 p = spec.LastIndexOf ('\\');
491 path = spec.Substring (0, p);
492 pattern = spec.Substring (p + 1);
500 static void ProcessFile (string f)
502 if (first_source == null)
505 Location.AddFile (f);
508 static void ProcessFiles ()
510 Location.Initialize ();
512 foreach (SourceFile file in Location.SourceFiles) {
514 tokenize_file (file);
521 static void CompileFiles (string spec, bool recurse)
523 string path, pattern;
525 SplitPathAndPattern (spec, out path, out pattern);
526 if (pattern.IndexOf ('*') == -1){
531 string [] files = null;
533 files = Directory.GetFiles (path, pattern);
534 } catch (System.IO.DirectoryNotFoundException) {
535 Report.Error (2001, "Source file `" + spec + "' could not be found");
537 } catch (System.IO.IOException){
538 Report.Error (2001, "Source file `" + spec + "' could not be found");
541 foreach (string f in files) {
548 string [] dirs = null;
551 dirs = Directory.GetDirectories (path);
555 foreach (string d in dirs) {
557 // Don't include path in this string, as each
558 // directory entry already does
559 CompileFiles (d + "/" + pattern, true);
563 static void DefineDefaultConfig ()
566 // For now the "default config" is harcoded into the compiler
567 // we can move this outside later
569 string [] default_config = {
574 // Is it worth pre-loading all this stuff?
577 "System.Configuration.Install",
580 "System.DirectoryServices",
581 "System.Drawing.Design",
583 "System.EnterpriseServices",
586 "System.Runtime.Remoting",
587 "System.Runtime.Serialization.Formatters.Soap",
589 "System.ServiceProcess",
591 "System.Web.RegularExpressions",
592 "System.Web.Services",
593 "System.Windows.Forms"
598 foreach (string def in default_config)
599 soft_references.Insert (p++, def);
602 static void SetOutputFile (string name)
607 static void SetWarningLevel (string s)
612 level = Int32.Parse (s);
616 "--wlevel requires a value from 0 to 4");
617 Environment.Exit (1);
619 if (level < 0 || level > 4){
620 Report.Error (1900, "Warning level must be 0 to 4");
621 Environment.Exit (1);
623 RootContext.WarningLevel = level;
624 TestWarningConflict ();
627 static void TestWarningConflict ()
629 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
630 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
631 Environment.Exit (1);
635 static void SetupV2 ()
637 RootContext.Version = LanguageVersion.Default;
638 defines.Add ("__V2__");
641 static void Version ()
643 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
644 Console.WriteLine ("Mono C# compiler version {0}", version);
645 Environment.Exit (0);
649 // Currently handles the Unix-like command line options, but will be
650 // deprecated in favor of the CSCParseOption, which will also handle the
651 // options that start with a dash in the future.
653 static bool UnixParseOption (string arg, ref string [] args, ref int i)
657 CSharpParser.yacc_verbose_flag++;
668 case "--main": case "-m":
669 if ((i + 1) >= args.Length){
671 Environment.Exit (1);
673 RootContext.MainClass = args [++i];
677 RootContext.Unsafe = true;
680 case "/?": case "/h": case "/help":
683 Environment.Exit (0);
687 if ((i + 1) >= args.Length){
689 Environment.Exit (1);
691 defines.Add (args [++i]);
694 case "--show-counters":
695 show_counters = true;
698 case "--expect-error": {
703 args [++i], NumberStyles.AllowLeadingSign);
704 Report.ExpectedError = code;
706 Report.Error (-14, "Invalid number specified");
717 if ((i + 1) >= args.Length){
719 Environment.Exit (1);
721 SetOutputFile (args [++i]);
725 RootContext.Checked = true;
729 Report.Stacktrace = true;
732 case "--linkresource":
734 if ((i + 1) >= args.Length){
736 Report.Error (5, "Missing argument to --linkres");
737 Environment.Exit (1);
739 if (resources == null)
740 resources = new ArrayList ();
742 resources.Add (args [++i]);
747 if ((i + 1) >= args.Length){
749 Report.Error (5, "Missing argument to --resource");
750 Environment.Exit (1);
752 if (embedded_resources == null)
753 embedded_resources = new ArrayList ();
755 embedded_resources.Add (args [++i]);
759 if ((i + 1) >= args.Length){
760 Environment.Exit (1);
764 string type = args [++i];
767 RootContext.Target = Target.Library;
768 RootContext.TargetExt = ".dll";
772 RootContext.Target = Target.Exe;
776 RootContext.Target = Target.WinExe;
780 RootContext.Target = Target.Module;
781 RootContext.TargetExt = ".dll";
785 Environment.Exit (1);
791 if ((i + 1) >= args.Length){
793 Environment.Exit (1);
796 references.Add (args [++i]);
800 if ((i + 1) >= args.Length){
802 Environment.Exit (1);
804 link_paths.Add (args [++i]);
808 RootContext.StdLib = false;
816 Report.WarningsAreErrors = true;
817 TestWarningConflict();
821 if ((i + 1) >= args.Length){
823 Environment.Exit (1);
828 warn = Int32.Parse (args [++i]);
831 Environment.Exit (1);
833 Report.SetIgnoreWarning (warn);
837 if ((i + 1) >= args.Length){
840 "--wlevel requires a value from 0 to 4");
841 Environment.Exit (1);
844 SetWarningLevel (args [++i]);
848 if ((i + 1) >= args.Length){
849 Report.Error (5, "--mcs-debug requires an argument");
850 Environment.Exit (1);
854 Report.DebugFlags = Int32.Parse (args [++i]);
856 Report.Error (5, "Invalid argument to --mcs-debug");
857 Environment.Exit (1);
866 if ((i + 1) >= args.Length){
867 Report.Error (5, "--recurse requires an argument");
868 Environment.Exit (1);
870 CompileFiles (args [++i], true);
875 last_time = first_time = DateTime.Now;
882 case "--debug": case "-g":
883 want_debugging_support = true;
887 load_default_config = false;
895 // Currently it is very basic option parsing, but eventually, this will
896 // be the complete option parser
898 static bool CSCParseOption (string option, ref string [] args, ref int i)
900 int idx = option.IndexOf (':');
907 arg = option.Substring (0, idx);
909 value = option.Substring (idx + 1);
920 RootContext.Target = Target.Exe;
924 RootContext.Target = Target.WinExe;
928 RootContext.Target = Target.Library;
929 RootContext.TargetExt = ".dll";
933 RootContext.Target = Target.Module;
934 RootContext.TargetExt = ".netmodule";
939 Environment.Exit (1);
947 Environment.Exit (1);
949 SetOutputFile (value);
954 RootContext.Optimize = true;
958 RootContext.Optimize = false;
962 case "/incremental+":
963 case "/incremental-":
973 Environment.Exit (1);
976 defs = value.Split (new Char [] {';', ','});
977 foreach (string d in defs){
984 case "/linkresource":
986 Report.Error (5, arg + " requires an argument");
987 Environment.Exit (1);
989 if (resources == null)
990 resources = new ArrayList ();
992 resources.Add (value);
1000 Environment.Exit (1);
1002 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1004 ProcessStartInfo pi = new ProcessStartInfo ();
1005 pi.FileName = "pkg-config";
1006 pi.RedirectStandardOutput = true;
1007 pi.UseShellExecute = false;
1008 pi.Arguments = "--libs " + packages;
1011 p = Process.Start (pi);
1012 } catch (Exception e) {
1013 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1014 Environment.Exit (1);
1017 if (p.StandardOutput == null){
1018 Report.Warning (-27, "Specified package did not return any information");
1021 string pkgout = p.StandardOutput.ReadToEnd ();
1023 if (p.ExitCode != 0) {
1024 Report.Error (-27, "Error running pkg-config. Check the above output.");
1025 Environment.Exit (1);
1028 if (pkgout != null){
1029 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1030 Split (new Char [] { ' ', '\t'});
1031 args = AddArgs (args, xargs);
1041 Report.Error (5, "-resource requires an argument");
1042 Environment.Exit (1);
1044 if (embedded_resources == null)
1045 embedded_resources = new ArrayList ();
1047 if (embedded_resources.Contains (value)) {
1048 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1050 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1051 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1054 embedded_resources.Add (value);
1060 Report.Error (5, "-recurse requires an argument");
1061 Environment.Exit (1);
1063 CompileFiles (value, true);
1067 case "/reference": {
1069 Report.Error (5, "-reference requires an argument");
1070 Environment.Exit (1);
1073 string [] refs = value.Split (new char [] { ';', ',' });
1074 foreach (string r in refs){
1079 case "/addmodule": {
1081 Report.Error (5, arg + " requires an argument");
1082 Environment.Exit (1);
1085 string [] refs = value.Split (new char [] { ';', ',' });
1086 foreach (string r in refs){
1093 Report.Error (5, arg + " requires an argument");
1094 Environment.Exit (1);
1097 win32ResourceFile = value;
1100 case "/win32icon": {
1102 Report.Error (5, arg + " requires an argument");
1103 Environment.Exit (1);
1106 win32IconFile = value;
1111 Report.Error (2006, arg + " requires an argument");
1112 Environment.Exit (1);
1114 RootContext.Documentation = new Documentation (value);
1121 Report.Error (5, "/lib requires an argument");
1122 Environment.Exit (1);
1125 libdirs = value.Split (new Char [] { ',' });
1126 foreach (string dir in libdirs)
1127 link_paths.Add (dir);
1132 want_debugging_support = false;
1137 want_debugging_support = true;
1142 RootContext.Checked = true;
1146 RootContext.Checked = false;
1154 RootContext.VerifyClsCompliance = false;
1159 RootContext.Unsafe = true;
1163 RootContext.Unsafe = false;
1166 case "/warnaserror":
1167 case "/warnaserror+":
1168 Report.WarningsAreErrors = true;
1169 TestWarningConflict();
1172 case "/warnaserror-":
1173 Report.WarningsAreErrors = false;
1177 SetWarningLevel (value);
1184 Report.Error (5, "/nowarn requires an argument");
1185 Environment.Exit (1);
1188 warns = value.Split (new Char [] {','});
1189 foreach (string wc in warns){
1191 int warn = Int32.Parse (wc);
1193 throw new ArgumentOutOfRangeException("warn");
1195 Report.SetIgnoreWarning (warn);
1197 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1198 Environment.Exit (1);
1205 load_default_config = true;
1210 load_default_config = false;
1215 Environment.Exit(0);
1221 Environment.Exit (0);
1227 Report.Error (5, arg + " requires an argument");
1228 Environment.Exit (1);
1230 RootContext.MainClass = value;
1235 RootContext.StdLib = false;
1239 RootContext.StdLib = true;
1246 if (value == String.Empty) {
1247 Report.Error (5, arg + " requires an argument");
1248 Environment.Exit (1);
1250 RootContext.StrongNameKeyFile = value;
1252 case "/keycontainer":
1253 if (value == String.Empty) {
1254 Report.Error (5, arg + " requires an argument");
1255 Environment.Exit (1);
1257 RootContext.StrongNameKeyContainer = value;
1260 RootContext.StrongNameDelaySign = true;
1263 RootContext.StrongNameDelaySign = false;
1268 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1272 case "/langversion":
1273 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1275 RootContext.Version = LanguageVersion.ISO_1;
1282 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1283 Environment.Exit (1);
1289 if (value == "utf8"){
1290 encoding = new UTF8Encoding();
1291 using_default_encoder = false;
1294 if (value == "reset"){
1296 // 28591 is the code page for ISO-8859-1 encoding.
1299 using_default_encoder = true;
1303 cp = Int32.Parse (value);
1304 encoding = Encoding.GetEncoding (cp);
1305 using_default_encoder = false;
1307 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1308 Environment.Exit (1);
1312 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1313 //Environment.Exit (1);
1317 static string [] AddArgs (string [] args, string [] extra_args)
1320 new_args = new string [extra_args.Length + args.Length];
1322 // if args contains '--' we have to take that into account
1323 // split args into first half and second half based on '--'
1324 // and add the extra_args before --
1325 int split_position = Array.IndexOf (args, "--");
1326 if (split_position != -1)
1328 Array.Copy (args, new_args, split_position);
1329 extra_args.CopyTo (new_args, split_position);
1330 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1334 args.CopyTo (new_args, 0);
1335 extra_args.CopyTo (new_args, args.Length);
1342 /// Parses the arguments, and drives the compilation
1347 /// TODO: Mostly structured to debug the compiler
1348 /// now, needs to be turned into a real driver soon.
1350 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1351 internal static bool MainDriver (string [] args)
1354 bool parsing_options = true;
1357 encoding = Encoding.GetEncoding (28591);
1359 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1360 encoding = Encoding.GetEncoding (1252);
1363 references = new ArrayList ();
1364 soft_references = new ArrayList ();
1365 modules = new ArrayList ();
1366 link_paths = new ArrayList ();
1368 SetupDefaultDefines ();
1373 // This is not required because Assembly.Load knows about this
1377 for (i = 0; i < args.Length; i++){
1378 string arg = args [i];
1382 if (arg.StartsWith ("@")){
1383 string [] extra_args;
1384 string response_file = arg.Substring (1);
1386 if (response_file_list == null)
1387 response_file_list = new Hashtable ();
1389 if (response_file_list.Contains (response_file)){
1391 1515, "Response file `" + response_file +
1392 "' specified multiple times");
1393 Environment.Exit (1);
1396 response_file_list.Add (response_file, response_file);
1398 extra_args = LoadArgs (response_file);
1399 if (extra_args == null){
1400 Report.Error (2011, "Unable to open response file: " +
1405 args = AddArgs (args, extra_args);
1409 if (parsing_options){
1411 parsing_options = false;
1415 if (arg.StartsWith ("-")){
1416 if (UnixParseOption (arg, ref args, ref i))
1420 string csc_opt = "/" + arg.Substring (1);
1421 if (CSCParseOption (csc_opt, ref args, ref i))
1424 if (arg.StartsWith ("/")){
1425 if (CSCParseOption (arg, ref args, ref i))
1431 CompileFiles (arg, false);
1440 // This will point to the NamespaceEntry of the last file that was parsed, and may
1441 // not be meaningful when resolving classes from other files. So, reset it to prevent
1444 RootContext.Tree.Types.NamespaceEntry = null;
1447 // If we are an exe, require a source file for the entry point
1449 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1450 if (first_source == null){
1451 Report.Error (2008, "No files to compile were specified");
1458 // If there is nothing to put in the assembly, and we are not a library
1460 if (first_source == null && embedded_resources == null && resources == null){
1461 Report.Error (2008, "No files to compile were specified");
1465 if (Report.Errors > 0)
1471 Tokenizer.Cleanup ();
1474 // Load Core Library for default compilation
1476 if (RootContext.StdLib)
1477 references.Insert (0, "mscorlib");
1479 if (load_default_config)
1480 DefineDefaultConfig ();
1482 if (Report.Errors > 0){
1487 // Load assemblies required
1490 ShowTime ("Loading references");
1491 link_paths.Add (GetSystemDir ());
1492 link_paths.Add (Directory.GetCurrentDirectory ());
1496 ShowTime (" References loaded");
1498 if (Report.Errors > 0){
1505 if (output_file == null){
1506 int pos = first_source.LastIndexOf ('.');
1509 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1511 output_file = first_source + RootContext.TargetExt;
1514 CodeGen.Init (output_file, output_file, want_debugging_support);
1516 if (RootContext.Target == Target.Module) {
1517 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1518 if (module_only == null) {
1519 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1520 Environment.Exit (1);
1523 MethodInfo set_method = module_only.GetSetMethod (true);
1524 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1527 TypeManager.AddModule (CodeGen.Module.Builder);
1529 if (modules.Count > 0) {
1530 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1531 if (adder_method == null) {
1532 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1533 Environment.Exit (1);
1536 foreach (string module in modules)
1537 LoadModule (adder_method, module);
1540 TypeManager.ComputeNamespaces ();
1543 // Before emitting, we need to get the core
1544 // types emitted from the user defined types
1545 // or from the system ones.
1548 ShowTime ("Initializing Core Types");
1549 if (!RootContext.StdLib){
1550 RootContext.ResolveCore ();
1551 if (Report.Errors > 0)
1555 TypeManager.InitCoreTypes ();
1557 ShowTime (" Core Types done");
1560 // The second pass of the compiler
1563 ShowTime ("Resolving tree");
1564 RootContext.ResolveTree ();
1566 if (Report.Errors > 0)
1569 ShowTime ("Populate tree");
1570 if (!RootContext.StdLib)
1571 RootContext.BootCorlib_PopulateCoreTypes ();
1572 RootContext.PopulateTypes ();
1573 RootContext.DefineTypes ();
1575 if (RootContext.Documentation != null &&
1576 !RootContext.Documentation.OutputDocComment (
1580 TypeManager.InitCodeHelpers ();
1583 // Verify using aliases now
1585 Namespace.VerifyUsing ();
1587 if (Report.Errors > 0){
1591 if (RootContext.VerifyClsCompliance) {
1592 CodeGen.Assembly.ResolveClsCompliance ();
1593 if (CodeGen.Assembly.IsClsCompliant) {
1594 AttributeTester.VerifyModulesClsCompliance ();
1595 TypeManager.LoadAllImportedTypes ();
1596 AttributeTester.VerifyTopLevelNameClsCompliance ();
1601 // The code generator
1604 ShowTime ("Emitting code");
1605 ShowTotalTime ("Total so far");
1606 RootContext.EmitCode ();
1610 if (Report.Errors > 0){
1615 ShowTime ("Closing types");
1617 RootContext.CloseTypes ();
1619 PEFileKinds k = PEFileKinds.ConsoleApplication;
1621 switch (RootContext.Target) {
1622 case Target.Library:
1624 k = PEFileKinds.Dll; break;
1626 k = PEFileKinds.ConsoleApplication; break;
1628 k = PEFileKinds.WindowApplication; break;
1631 if (RootContext.NeedsEntryPoint) {
1632 MethodInfo ep = RootContext.EntryPoint;
1635 if (RootContext.MainClass != null) {
1636 DeclSpace main_cont = RootContext.Tree.Decls [RootContext.MainClass] as DeclSpace;
1637 if (main_cont == null) {
1638 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1642 if (!(main_cont is ClassOrStruct)) {
1643 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1647 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1651 if (Report.Errors == 0)
1652 Report.Error (5001, "Program " + output_file +
1653 " does not have an entry point defined");
1657 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1658 } else if (RootContext.MainClass != null) {
1659 Report.Error (2017, "Can not specify -main: when building module or library");
1663 // Add the resources
1665 if (resources != null){
1666 foreach (string spec in resources){
1670 cp = spec.IndexOf (',');
1672 file = spec.Substring (0, cp);
1673 res = spec.Substring (cp + 1);
1677 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1681 if (embedded_resources != null){
1682 object[] margs = new object [2];
1683 Type[] argst = new Type [2];
1684 argst [0] = argst [1] = typeof (string);
1686 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1687 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1688 null, CallingConventions.Any, argst, null);
1690 if (embed_res == null) {
1691 Report.Warning (0, new Location (-1),
1692 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1694 foreach (string spec in embedded_resources) {
1697 cp = spec.IndexOf (',');
1699 margs [0] = spec.Substring (cp + 1);
1700 margs [1] = spec.Substring (0, cp);
1703 margs [0] = Path.GetFileName (spec);
1706 if (File.Exists ((string) margs [1]))
1707 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1709 Report.Error (1566, "Can not find the resource " + margs [1]);
1716 // Add Win32 resources
1719 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1721 if (win32ResourceFile != null) {
1723 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1725 catch (ArgumentException) {
1726 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1730 if (win32IconFile != null) {
1731 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1732 if (define_icon == null) {
1733 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1735 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1738 if (Report.Errors > 0)
1741 CodeGen.Save (output_file);
1743 ShowTime ("Saved output");
1744 ShowTotalTime ("Total");
1747 Timer.ShowTimers ();
1749 if (Report.ExpectedError != 0){
1750 if (Report.Errors == 0) {
1751 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1752 "No other errors reported.");
1754 Environment.Exit (2);
1756 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1757 "However, other errors were reported.");
1759 Environment.Exit (1);
1767 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1768 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1770 return (Report.Errors == 0);
1775 // This is the only public entry point
1777 public class CompilerCallableEntryPoint : MarshalByRefObject {
1778 static bool used = false;
1780 public bool InvokeCompiler (string [] args)
1784 bool ok = Driver.MainDriver (args);
1785 return ok && Report.Errors == 0;
1788 public void Reset ()