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;
20 using System.Globalization;
21 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 to only run the tokenizer
54 static bool tokenize = false;
56 static string first_source;
58 static bool want_debugging_support = false;
60 static bool parse_only = false;
61 static bool timestamps = false;
62 static bool pause = false;
63 static bool show_counters = false;
66 // Whether to load the initial config file (what CSC.RSP has by default)
68 static bool load_default_config = true;
70 static Hashtable response_file_list;
73 // A list of resource files
75 static ArrayList resources;
76 static ArrayList embedded_resources;
77 static string win32ResourceFile;
78 static string win32IconFile;
81 // An array of the defines from the command line
83 static ArrayList defines;
88 static string output_file = null;
91 // Last time we took the time
93 static DateTime last_time, first_time;
96 // Encoding: ISO-Latin1 is 28591
98 static Encoding encoding;
101 // Whether the user has specified a different encoder manually
103 static bool using_default_encoder = true;
105 public static void ShowTime (string msg)
110 DateTime now = DateTime.Now;
111 TimeSpan span = now - last_time;
115 "[{0:00}:{1:000}] {2}",
116 (int) span.TotalSeconds, span.Milliseconds, msg);
119 public static void ShowTotalTime (string msg)
124 DateTime now = DateTime.Now;
125 TimeSpan span = now - first_time;
129 "[{0:00}:{1:000}] {2}",
130 (int) span.TotalSeconds, span.Milliseconds, msg);
133 static void tokenize_file (SourceFile file)
138 input = File.OpenRead (file.Name);
140 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
145 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
146 Tokenizer lexer = new Tokenizer (reader, file, defines);
147 int token, tokens = 0, errors = 0;
149 while ((token = lexer.token ()) != Token.EOF){
151 if (token == Token.ERROR)
154 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
160 // MonoTODO("Change error code for aborted compilation to something reasonable")]
161 static void parse (SourceFile file)
167 input = File.OpenRead (file.Name);
169 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
173 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
175 parser = new CSharpParser (reader, file, defines);
178 } catch (Exception ex) {
179 Report.Error(666, "Compilation aborted: " + ex);
185 static void OtherFlags ()
188 "Other flags in the compiler\n" +
189 " --fatal Makes errors fatal\n" +
190 " --parse Only parses the source file\n" +
191 " --stacktrace Shows stack trace at error location\n" +
192 " --timestamp Displays time stamps of various compiler events\n" +
193 " -2 Enables experimental C# features\n" +
194 " -v Verbose parsing (for debugging the parser)\n" +
195 " --mcs-debug X Sets MCS debugging level to X\n");
201 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
202 "mcs [options] source-files\n" +
203 " --about About the Mono C# compiler\n" +
204 " -addmodule:MODULE Adds the module to the generated assembly\n" +
205 " -checked[+|-] Set default context to checked\n" +
206 " -codepage:ID Sets code page to the one in ID\n" +
207 " (number, `utf8' or `reset')\n" +
208 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
209 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
210 " -debug[+|-] Generate debugging information\n" +
211 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
212 " -doc:FILE XML Documentation file to generate\n" +
213 " -g Generate debugging information\n" +
214 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
215 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
216 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
217 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
218 " -main:class Specified the class that contains the entry point\n" +
219 " -noconfig[+|-] Disables implicit references to assemblies\n" +
220 " -nostdlib[+|-] Does not load core libraries\n" +
221 " -nowarn:W1[,W2] Disables one or more warnings\n" +
222 " -out:FNAME Specifies output file\n" +
223 " -pkg:P1[,Pn] References packages P1..Pn\n" +
224 " --expect-error X Expect that error X will be encountered\n" +
225 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
226 " -reference:ASS References the specified assembly (-r:ASS)\n" +
227 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
228 " library, module), (short: /t:)\n" +
229 " -unsafe[+|-] Allows unsafe code\n" +
230 " -warnaserror[+|-] Treat warnings as errors\n" +
231 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
232 " -help2 Show other help flags\n" +
235 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
236 " -resource:FILE[,ID] Embed FILE as a resource\n" +
237 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
238 " -win32icon:FILE Use this icon for the output\n" +
239 " @file Read response file for more options\n\n" +
240 "Options can be of the form -option or /option");
243 static void TargetUsage ()
245 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
251 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
252 "The compiler source code is released under the terms of the GNU GPL\n\n" +
254 "For more information on Mono, visit the project Web site\n" +
255 " http://www.go-mono.com\n\n" +
257 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
258 Environment.Exit (0);
261 public static int counter1, counter2;
263 public static int Main (string[] args)
265 bool ok = MainDriver (args);
267 if (ok && Report.Errors == 0) {
268 if (Report.Warnings > 0) {
269 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
272 Console.WriteLine ("Counter1: " + counter1);
273 Console.WriteLine ("Counter2: " + counter2);
279 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
280 Report.Errors, Report.Warnings);
285 static public void LoadAssembly (string assembly, bool soft)
288 string total_log = "";
291 char[] path_chars = { '/', '\\' };
293 if (assembly.IndexOfAny (path_chars) != -1) {
294 a = Assembly.LoadFrom (assembly);
296 string ass = assembly;
297 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
298 ass = assembly.Substring (0, assembly.Length - 4);
299 a = Assembly.Load (ass);
301 TypeManager.AddAssembly (a);
303 } catch (FileNotFoundException){
304 foreach (string dir in link_paths){
305 string full_path = Path.Combine (dir, assembly);
306 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
310 a = Assembly.LoadFrom (full_path);
311 TypeManager.AddAssembly (a);
313 } catch (FileNotFoundException ff) {
314 total_log += ff.FusionLog;
319 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
320 Console.WriteLine ("Log: \n" + total_log);
322 } catch (BadImageFormatException f) {
323 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
324 } catch (FileLoadException f){
325 Report.Error(6, "Cannot load assembly " + f.FusionLog);
326 } catch (ArgumentNullException){
327 Report.Error(6, "Cannot load assembly (null argument)");
331 static public void LoadModule (MethodInfo adder_method, string module)
334 string total_log = "";
338 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
340 catch (TargetInvocationException ex) {
341 throw ex.InnerException;
343 TypeManager.AddModule (m);
346 catch (FileNotFoundException){
347 foreach (string dir in link_paths){
348 string full_path = Path.Combine (dir, module);
349 if (!module.EndsWith (".netmodule"))
350 full_path += ".netmodule";
354 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
356 catch (TargetInvocationException ex) {
357 throw ex.InnerException;
359 TypeManager.AddModule (m);
361 } catch (FileNotFoundException ff) {
362 total_log += ff.FusionLog;
366 Report.Error (6, "Cannot find module `" + module + "'" );
367 Console.WriteLine ("Log: \n" + total_log);
368 } catch (BadImageFormatException f) {
369 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
370 } catch (FileLoadException f){
371 Report.Error(6, "Cannot load module " + f.FusionLog);
372 } catch (ArgumentNullException){
373 Report.Error(6, "Cannot load module (null argument)");
378 /// Loads all assemblies referenced on the command line
380 static public void LoadReferences ()
382 foreach (string r in references)
383 LoadAssembly (r, false);
385 foreach (string r in soft_references)
386 LoadAssembly (r, true);
391 static void SetupDefaultDefines ()
393 defines = new ArrayList ();
394 defines.Add ("__MonoCS__");
397 static string [] LoadArgs (string file)
400 ArrayList args = new ArrayList ();
403 f = new StreamReader (file);
408 StringBuilder sb = new StringBuilder ();
410 while ((line = f.ReadLine ()) != null){
413 for (int i = 0; i < t; i++){
416 if (c == '"' || c == '\''){
419 for (i++; i < t; i++){
426 } else if (c == ' '){
428 args.Add (sb.ToString ());
435 args.Add (sb.ToString ());
440 string [] ret_value = new string [args.Count];
441 args.CopyTo (ret_value, 0);
447 // Returns the directory where the system assemblies are installed
449 static string GetSystemDir ()
451 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
453 foreach (Assembly a in assemblies){
454 string codebase = a.Location;
455 string fn = System.IO.Path.GetFileName (codebase);
456 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
457 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
461 Report.Error (-15, "Can not compute my system path");
466 // Given a path specification, splits the path from the file/pattern
468 static void SplitPathAndPattern (string spec, out string path, out string pattern)
470 int p = spec.LastIndexOf ('/');
473 // Windows does not like /file.cs, switch that to:
478 pattern = spec.Substring (1);
480 path = spec.Substring (0, p);
481 pattern = spec.Substring (p + 1);
486 p = spec.LastIndexOf ('\\');
488 path = spec.Substring (0, p);
489 pattern = spec.Substring (p + 1);
497 static void ProcessFile (string f)
499 if (first_source == null)
502 Location.AddFile (f);
505 static void ProcessFiles ()
507 Location.Initialize ();
509 foreach (SourceFile file in Location.SourceFiles) {
511 tokenize_file (file);
518 static void CompileFiles (string spec, bool recurse)
520 string path, pattern;
522 SplitPathAndPattern (spec, out path, out pattern);
523 if (pattern.IndexOf ('*') == -1){
528 string [] files = null;
530 files = Directory.GetFiles (path, pattern);
531 } catch (System.IO.DirectoryNotFoundException) {
532 Report.Error (2001, "Source file `" + spec + "' could not be found");
534 } catch (System.IO.IOException){
535 Report.Error (2001, "Source file `" + spec + "' could not be found");
538 foreach (string f in files) {
545 string [] dirs = null;
548 dirs = Directory.GetDirectories (path);
552 foreach (string d in dirs) {
554 // Don't include path in this string, as each
555 // directory entry already does
556 CompileFiles (d + "/" + pattern, true);
560 static void DefineDefaultConfig ()
563 // For now the "default config" is harcoded into the compiler
564 // we can move this outside later
566 string [] default_config = {
571 // Is it worth pre-loading all this stuff?
574 "System.Configuration.Install",
577 "System.DirectoryServices",
578 "System.Drawing.Design",
580 "System.EnterpriseServices",
583 "System.Runtime.Remoting",
584 "System.Runtime.Serialization.Formatters.Soap",
586 "System.ServiceProcess",
588 "System.Web.RegularExpressions",
589 "System.Web.Services",
590 "System.Windows.Forms"
595 foreach (string def in default_config)
596 soft_references.Insert (p++, def);
599 static void SetOutputFile (string name)
604 static void SetWarningLevel (string s)
609 level = Int32.Parse (s);
613 "--wlevel requires a value from 0 to 4");
614 Environment.Exit (1);
616 if (level < 0 || level > 4){
617 Report.Error (1900, "Warning level must be 0 to 4");
618 Environment.Exit (1);
620 RootContext.WarningLevel = level;
621 TestWarningConflict ();
624 static void TestWarningConflict ()
626 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
627 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
628 Environment.Exit (1);
632 static void SetupV2 ()
634 RootContext.Version = LanguageVersion.Default;
635 defines.Add ("__V2__");
638 static void Version ()
640 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
641 Console.WriteLine ("Mono C# compiler version {0}", version);
642 Environment.Exit (0);
646 // Currently handles the Unix-like command line options, but will be
647 // deprecated in favor of the CSCParseOption, which will also handle the
648 // options that start with a dash in the future.
650 static bool UnixParseOption (string arg, ref string [] args, ref int i)
654 CSharpParser.yacc_verbose_flag++;
665 case "--main": case "-m":
666 if ((i + 1) >= args.Length){
668 Environment.Exit (1);
670 RootContext.MainClass = args [++i];
674 RootContext.Unsafe = true;
677 case "/?": case "/h": case "/help":
680 Environment.Exit (0);
684 if ((i + 1) >= args.Length){
686 Environment.Exit (1);
688 defines.Add (args [++i]);
691 case "--show-counters":
692 show_counters = true;
695 case "--expect-error": {
700 args [++i], NumberStyles.AllowLeadingSign);
701 Report.ExpectedError = code;
703 Report.Error (-14, "Invalid number specified");
714 if ((i + 1) >= args.Length){
716 Environment.Exit (1);
718 SetOutputFile (args [++i]);
722 RootContext.Checked = true;
726 Report.Stacktrace = true;
729 case "--linkresource":
731 if ((i + 1) >= args.Length){
733 Report.Error (5, "Missing argument to --linkres");
734 Environment.Exit (1);
736 if (resources == null)
737 resources = new ArrayList ();
739 resources.Add (args [++i]);
744 if ((i + 1) >= args.Length){
746 Report.Error (5, "Missing argument to --resource");
747 Environment.Exit (1);
749 if (embedded_resources == null)
750 embedded_resources = new ArrayList ();
752 embedded_resources.Add (args [++i]);
756 if ((i + 1) >= args.Length){
757 Environment.Exit (1);
761 string type = args [++i];
764 RootContext.Target = Target.Library;
765 RootContext.TargetExt = ".dll";
769 RootContext.Target = Target.Exe;
773 RootContext.Target = Target.WinExe;
777 RootContext.Target = Target.Module;
778 RootContext.TargetExt = ".dll";
782 Environment.Exit (1);
788 if ((i + 1) >= args.Length){
790 Environment.Exit (1);
793 references.Add (args [++i]);
797 if ((i + 1) >= args.Length){
799 Environment.Exit (1);
801 link_paths.Add (args [++i]);
805 RootContext.StdLib = false;
813 Report.WarningsAreErrors = true;
814 TestWarningConflict();
818 if ((i + 1) >= args.Length){
820 Environment.Exit (1);
825 warn = Int32.Parse (args [++i]);
828 Environment.Exit (1);
830 Report.SetIgnoreWarning (warn);
834 if ((i + 1) >= args.Length){
837 "--wlevel requires a value from 0 to 4");
838 Environment.Exit (1);
841 SetWarningLevel (args [++i]);
845 if ((i + 1) >= args.Length){
846 Report.Error (5, "--mcs-debug requires an argument");
847 Environment.Exit (1);
851 Report.DebugFlags = Int32.Parse (args [++i]);
853 Report.Error (5, "Invalid argument to --mcs-debug");
854 Environment.Exit (1);
863 if ((i + 1) >= args.Length){
864 Report.Error (5, "--recurse requires an argument");
865 Environment.Exit (1);
867 CompileFiles (args [++i], true);
872 last_time = first_time = DateTime.Now;
879 case "--debug": case "-g":
880 want_debugging_support = true;
884 load_default_config = false;
892 // Currently it is very basic option parsing, but eventually, this will
893 // be the complete option parser
895 static bool CSCParseOption (string option, ref string [] args, ref int i)
897 int idx = option.IndexOf (':');
904 arg = option.Substring (0, idx);
906 value = option.Substring (idx + 1);
917 RootContext.Target = Target.Exe;
921 RootContext.Target = Target.WinExe;
925 RootContext.Target = Target.Library;
926 RootContext.TargetExt = ".dll";
930 RootContext.Target = Target.Module;
931 RootContext.TargetExt = ".netmodule";
936 Environment.Exit (1);
944 Environment.Exit (1);
946 SetOutputFile (value);
953 case "/incremental+":
954 case "/incremental-":
964 Environment.Exit (1);
967 defs = value.Split (new Char [] {';', ','});
968 foreach (string d in defs){
975 case "/linkresource":
977 Report.Error (5, arg + " requires an argument");
978 Environment.Exit (1);
980 if (resources == null)
981 resources = new ArrayList ();
983 resources.Add (value);
991 Environment.Exit (1);
993 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
995 ProcessStartInfo pi = new ProcessStartInfo ();
996 pi.FileName = "pkg-config";
997 pi.RedirectStandardOutput = true;
998 pi.UseShellExecute = false;
999 pi.Arguments = "--libs " + packages;
1002 p = Process.Start (pi);
1003 } catch (Exception e) {
1004 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1005 Environment.Exit (1);
1008 if (p.StandardOutput == null){
1009 Report.Warning (-27, "Specified package did not return any information");
1012 string pkgout = p.StandardOutput.ReadToEnd ();
1014 if (p.ExitCode != 0) {
1015 Report.Error (-27, "Error running pkg-config. Check the above output.");
1016 Environment.Exit (1);
1019 if (pkgout != null){
1020 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1021 Split (new Char [] { ' ', '\t'});
1022 args = AddArgs (args, xargs);
1032 Report.Error (5, "-resource requires an argument");
1033 Environment.Exit (1);
1035 if (embedded_resources == null)
1036 embedded_resources = new ArrayList ();
1038 if (embedded_resources.Contains (value)) {
1039 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1041 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1042 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1045 embedded_resources.Add (value);
1051 Report.Error (5, "-recurse requires an argument");
1052 Environment.Exit (1);
1054 CompileFiles (value, true);
1058 case "/reference": {
1060 Report.Error (5, "-reference requires an argument");
1061 Environment.Exit (1);
1064 string [] refs = value.Split (new char [] { ';', ',' });
1065 foreach (string r in refs){
1070 case "/addmodule": {
1072 Report.Error (5, arg + " requires an argument");
1073 Environment.Exit (1);
1076 string [] refs = value.Split (new char [] { ';', ',' });
1077 foreach (string r in refs){
1084 Report.Error (5, arg + " requires an argument");
1085 Environment.Exit (1);
1088 win32ResourceFile = value;
1091 case "/win32icon": {
1093 Report.Error (5, arg + " requires an argument");
1094 Environment.Exit (1);
1097 win32IconFile = value;
1102 Report.Error (2006, arg + " requires an argument");
1103 Environment.Exit (1);
1105 RootContext.Documentation = new Documentation (value);
1112 Report.Error (5, "/lib requires an argument");
1113 Environment.Exit (1);
1116 libdirs = value.Split (new Char [] { ',' });
1117 foreach (string dir in libdirs)
1118 link_paths.Add (dir);
1123 want_debugging_support = false;
1128 want_debugging_support = true;
1133 RootContext.Checked = true;
1137 RootContext.Checked = false;
1145 RootContext.VerifyClsCompliance = false;
1150 RootContext.Unsafe = true;
1154 RootContext.Unsafe = false;
1157 case "/warnaserror":
1158 case "/warnaserror+":
1159 Report.WarningsAreErrors = true;
1160 TestWarningConflict();
1163 case "/warnaserror-":
1164 Report.WarningsAreErrors = false;
1168 SetWarningLevel (value);
1175 Report.Error (5, "/nowarn requires an argument");
1176 Environment.Exit (1);
1179 warns = value.Split (new Char [] {','});
1180 foreach (string wc in warns){
1182 int warn = Int32.Parse (wc);
1184 throw new ArgumentOutOfRangeException("warn");
1186 Report.SetIgnoreWarning (warn);
1188 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1189 Environment.Exit (1);
1196 load_default_config = true;
1201 load_default_config = false;
1206 Environment.Exit(0);
1212 Environment.Exit (0);
1218 Report.Error (5, arg + " requires an argument");
1219 Environment.Exit (1);
1221 RootContext.MainClass = value;
1226 RootContext.StdLib = false;
1230 RootContext.StdLib = true;
1237 if (value == String.Empty) {
1238 Report.Error (5, arg + " requires an argument");
1239 Environment.Exit (1);
1241 RootContext.StrongNameKeyFile = value;
1243 case "/keycontainer":
1244 if (value == String.Empty) {
1245 Report.Error (5, arg + " requires an argument");
1246 Environment.Exit (1);
1248 RootContext.StrongNameKeyContainer = value;
1251 RootContext.StrongNameDelaySign = true;
1254 RootContext.StrongNameDelaySign = false;
1259 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1263 case "/langversion":
1264 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1266 RootContext.Version = LanguageVersion.ISO_1;
1273 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1274 Environment.Exit (1);
1280 if (value == "utf8"){
1281 encoding = new UTF8Encoding();
1282 using_default_encoder = false;
1285 if (value == "reset"){
1287 // 28591 is the code page for ISO-8859-1 encoding.
1290 using_default_encoder = true;
1294 cp = Int32.Parse (value);
1295 encoding = Encoding.GetEncoding (cp);
1296 using_default_encoder = false;
1298 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1299 Environment.Exit (1);
1304 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1305 //Environment.Exit (1);
1309 static string [] AddArgs (string [] args, string [] extra_args)
1312 new_args = new string [extra_args.Length + args.Length];
1314 // if args contains '--' we have to take that into account
1315 // split args into first half and second half based on '--'
1316 // and add the extra_args before --
1317 int split_position = Array.IndexOf (args, "--");
1318 if (split_position != -1)
1320 Array.Copy (args, new_args, split_position);
1321 extra_args.CopyTo (new_args, split_position);
1322 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1326 args.CopyTo (new_args, 0);
1327 extra_args.CopyTo (new_args, args.Length);
1334 /// Parses the arguments, and drives the compilation
1339 /// TODO: Mostly structured to debug the compiler
1340 /// now, needs to be turned into a real driver soon.
1342 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1343 internal static bool MainDriver (string [] args)
1346 bool parsing_options = true;
1349 encoding = Encoding.GetEncoding (28591);
1351 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1352 encoding = Encoding.GetEncoding (1252);
1355 references = new ArrayList ();
1356 soft_references = new ArrayList ();
1357 modules = new ArrayList ();
1358 link_paths = new ArrayList ();
1360 SetupDefaultDefines ();
1365 // This is not required because Assembly.Load knows about this
1369 for (i = 0; i < args.Length; i++){
1370 string arg = args [i];
1374 if (arg.StartsWith ("@")){
1375 string [] extra_args;
1376 string response_file = arg.Substring (1);
1378 if (response_file_list == null)
1379 response_file_list = new Hashtable ();
1381 if (response_file_list.Contains (response_file)){
1383 1515, "Response file `" + response_file +
1384 "' specified multiple times");
1385 Environment.Exit (1);
1388 response_file_list.Add (response_file, response_file);
1390 extra_args = LoadArgs (response_file);
1391 if (extra_args == null){
1392 Report.Error (2011, "Unable to open response file: " +
1397 args = AddArgs (args, extra_args);
1401 if (parsing_options){
1403 parsing_options = false;
1407 if (arg.StartsWith ("-")){
1408 if (UnixParseOption (arg, ref args, ref i))
1412 string csc_opt = "/" + arg.Substring (1);
1413 if (CSCParseOption (csc_opt, ref args, ref i))
1416 if (arg.StartsWith ("/")){
1417 if (CSCParseOption (arg, ref args, ref i))
1423 CompileFiles (arg, false);
1432 // This will point to the NamespaceEntry of the last file that was parsed, and may
1433 // not be meaningful when resolving classes from other files. So, reset it to prevent
1436 RootContext.Tree.Types.NamespaceEntry = null;
1439 // If we are an exe, require a source file for the entry point
1441 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1442 if (first_source == null){
1443 Report.Error (2008, "No files to compile were specified");
1450 // If there is nothing to put in the assembly, and we are not a library
1452 if (first_source == null && embedded_resources == null && resources == null){
1453 Report.Error (2008, "No files to compile were specified");
1457 if (Report.Errors > 0)
1463 Tokenizer.Cleanup ();
1466 // Load Core Library for default compilation
1468 if (RootContext.StdLib)
1469 references.Insert (0, "mscorlib");
1471 if (load_default_config)
1472 DefineDefaultConfig ();
1474 if (Report.Errors > 0){
1479 // Load assemblies required
1482 ShowTime ("Loading references");
1483 link_paths.Add (GetSystemDir ());
1484 link_paths.Add (Directory.GetCurrentDirectory ());
1488 ShowTime (" References loaded");
1490 if (Report.Errors > 0){
1497 if (output_file == null){
1498 int pos = first_source.LastIndexOf ('.');
1501 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1503 output_file = first_source + RootContext.TargetExt;
1506 CodeGen.Init (output_file, output_file, want_debugging_support);
1508 if (RootContext.Target == Target.Module) {
1509 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1510 if (module_only == null) {
1511 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1512 Environment.Exit (1);
1515 MethodInfo set_method = module_only.GetSetMethod (true);
1516 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1519 TypeManager.AddModule (CodeGen.Module.Builder);
1521 if (modules.Count > 0) {
1522 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1523 if (adder_method == null) {
1524 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1525 Environment.Exit (1);
1528 foreach (string module in modules)
1529 LoadModule (adder_method, module);
1532 TypeManager.ComputeNamespaces ();
1535 // Before emitting, we need to get the core
1536 // types emitted from the user defined types
1537 // or from the system ones.
1540 ShowTime ("Initializing Core Types");
1541 if (!RootContext.StdLib){
1542 RootContext.ResolveCore ();
1543 if (Report.Errors > 0)
1547 TypeManager.InitCoreTypes ();
1549 ShowTime (" Core Types done");
1552 // The second pass of the compiler
1555 ShowTime ("Resolving tree");
1556 RootContext.ResolveTree ();
1558 if (Report.Errors > 0)
1561 ShowTime ("Populate tree");
1562 if (!RootContext.StdLib)
1563 RootContext.BootCorlib_PopulateCoreTypes ();
1565 RootContext.PopulateTypes ();
1566 RootContext.DefineTypes ();
1568 if (RootContext.Documentation != null &&
1569 !RootContext.Documentation.OutputDocComment (
1573 TypeManager.InitCodeHelpers ();
1576 // Verify using aliases now
1578 Namespace.VerifyUsing ();
1580 if (Report.Errors > 0){
1584 if (RootContext.VerifyClsCompliance) {
1585 CodeGen.Assembly.ResolveClsCompliance ();
1586 if (CodeGen.Assembly.IsClsCompliant) {
1587 AttributeTester.VerifyModulesClsCompliance ();
1588 TypeManager.LoadAllImportedTypes ();
1589 AttributeTester.VerifyTopLevelNameClsCompliance ();
1594 // The code generator
1597 ShowTime ("Emitting code");
1598 ShowTotalTime ("Total so far");
1599 RootContext.EmitCode ();
1603 if (Report.Errors > 0){
1608 ShowTime ("Closing types");
1610 RootContext.CloseTypes ();
1612 PEFileKinds k = PEFileKinds.ConsoleApplication;
1614 switch (RootContext.Target) {
1615 case Target.Library:
1617 k = PEFileKinds.Dll; break;
1619 k = PEFileKinds.ConsoleApplication; break;
1621 k = PEFileKinds.WindowApplication; break;
1624 if (RootContext.NeedsEntryPoint) {
1625 MethodInfo ep = RootContext.EntryPoint;
1628 if (RootContext.MainClass != null) {
1629 DeclSpace main_cont = RootContext.Tree.Decls [RootContext.MainClass] as DeclSpace;
1630 if (main_cont == null) {
1631 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1635 if (!(main_cont is ClassOrStruct)) {
1636 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1640 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1644 if (Report.Errors == 0)
1645 Report.Error (5001, "Program " + output_file +
1646 " does not have an entry point defined");
1650 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1651 } else if (RootContext.MainClass != null) {
1652 Report.Error (2017, "Can not specify -main: when building module or library");
1656 // Add the resources
1658 if (resources != null){
1659 foreach (string spec in resources){
1663 cp = spec.IndexOf (',');
1665 file = spec.Substring (0, cp);
1666 res = spec.Substring (cp + 1);
1670 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1674 if (embedded_resources != null){
1675 object[] margs = new object [2];
1676 Type[] argst = new Type [2];
1677 argst [0] = argst [1] = typeof (string);
1679 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1680 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1681 null, CallingConventions.Any, argst, null);
1683 if (embed_res == null) {
1684 Report.Warning (0, new Location (-1),
1685 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1687 foreach (string spec in embedded_resources) {
1690 cp = spec.IndexOf (',');
1692 margs [0] = spec.Substring (cp + 1);
1693 margs [1] = spec.Substring (0, cp);
1696 margs [0] = Path.GetFileName (spec);
1699 if (File.Exists ((string) margs [1]))
1700 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1702 Report.Error (1566, "Can not find the resource " + margs [1]);
1709 // Add Win32 resources
1712 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1714 if (win32ResourceFile != null) {
1716 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1718 catch (ArgumentException) {
1719 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1723 if (win32IconFile != null) {
1724 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1725 if (define_icon == null) {
1726 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1728 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1731 if (Report.Errors > 0)
1734 CodeGen.Save (output_file);
1736 ShowTime ("Saved output");
1737 ShowTotalTime ("Total");
1740 Timer.ShowTimers ();
1742 if (Report.ExpectedError != 0) {
1743 if (Report.Errors == 0) {
1744 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1745 "No other errors reported.");
1747 Environment.Exit (2);
1749 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1750 "However, other errors were reported.");
1752 Environment.Exit (1);
1760 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1761 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1763 return (Report.Errors == 0);
1768 // This is the only public entry point
1770 public class CompilerCallableEntryPoint : MarshalByRefObject {
1771 static bool used = false;
1773 public bool InvokeCompiler (string [] args)
1777 bool ok = Driver.MainDriver (args);
1778 return ok && Report.Errors == 0;
1781 public void Reset ()