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 " -pkg:P1[,Pn] References packages P1..Pn\n" +
225 " --expect-error X Expect that error X will be encountered\n" +
226 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
227 " -reference:ASS References the specified assembly (-r:ASS)\n" +
228 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
229 " library, module), (short: /t:)\n" +
230 " -unsafe[+|-] Allows unsafe code\n" +
231 " -warnaserror[+|-] Treat warnings as errors\n" +
232 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
233 " -help2 Show other help flags\n" +
236 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
237 " -resource:FILE[,ID] Embed FILE as a resource\n" +
238 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
239 " -win32icon:FILE Use this icon for the output\n" +
240 " @file Read response file for more options\n\n" +
241 "Options can be of the form -option or /option");
244 static void TargetUsage ()
246 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
252 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
253 "The compiler source code is released under the terms of the GNU GPL\n\n" +
255 "For more information on Mono, visit the project Web site\n" +
256 " http://www.go-mono.com\n\n" +
258 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
259 Environment.Exit (0);
262 public static int counter1, counter2;
264 public static int Main (string[] args)
266 RootContext.Version = LanguageVersion.Default;
267 bool ok = MainDriver (args);
269 if (ok && Report.Errors == 0) {
270 if (Report.Warnings > 0) {
271 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
274 Console.WriteLine ("Counter1: " + counter1);
275 Console.WriteLine ("Counter2: " + counter2);
281 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
282 Report.Errors, Report.Warnings);
287 static public void LoadAssembly (string assembly, bool soft)
290 string total_log = "";
293 char[] path_chars = { '/', '\\' };
295 if (assembly.IndexOfAny (path_chars) != -1) {
296 a = Assembly.LoadFrom (assembly);
298 string ass = assembly;
299 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
300 ass = assembly.Substring (0, assembly.Length - 4);
301 a = Assembly.Load (ass);
303 TypeManager.AddAssembly (a);
305 } catch (FileNotFoundException){
306 foreach (string dir in link_paths){
307 string full_path = Path.Combine (dir, assembly);
308 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
312 a = Assembly.LoadFrom (full_path);
313 TypeManager.AddAssembly (a);
315 } catch (FileNotFoundException ff) {
316 total_log += ff.FusionLog;
321 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
322 Console.WriteLine ("Log: \n" + total_log);
324 } catch (BadImageFormatException f) {
325 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
326 } catch (FileLoadException f){
327 Report.Error(6, "Cannot load assembly " + f.FusionLog);
328 } catch (ArgumentNullException){
329 Report.Error(6, "Cannot load assembly (null argument)");
333 static public void LoadModule (MethodInfo adder_method, string module)
336 string total_log = "";
340 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
342 catch (TargetInvocationException ex) {
343 throw ex.InnerException;
345 TypeManager.AddModule (m);
348 catch (FileNotFoundException){
349 foreach (string dir in link_paths){
350 string full_path = Path.Combine (dir, module);
351 if (!module.EndsWith (".netmodule"))
352 full_path += ".netmodule";
356 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
358 catch (TargetInvocationException ex) {
359 throw ex.InnerException;
361 TypeManager.AddModule (m);
363 } catch (FileNotFoundException ff) {
364 total_log += ff.FusionLog;
368 Report.Error (6, "Cannot find module `" + module + "'" );
369 Console.WriteLine ("Log: \n" + total_log);
370 } catch (BadImageFormatException f) {
371 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
372 } catch (FileLoadException f){
373 Report.Error(6, "Cannot load module " + f.FusionLog);
374 } catch (ArgumentNullException){
375 Report.Error(6, "Cannot load module (null argument)");
380 /// Loads all assemblies referenced on the command line
382 static public void LoadReferences ()
384 foreach (string r in references)
385 LoadAssembly (r, false);
387 foreach (string r in soft_references)
388 LoadAssembly (r, true);
393 static void SetupDefaultDefines ()
395 defines = new ArrayList ();
396 defines.Add ("__MonoCS__");
399 static string [] LoadArgs (string file)
402 ArrayList args = new ArrayList ();
405 f = new StreamReader (file);
410 StringBuilder sb = new StringBuilder ();
412 while ((line = f.ReadLine ()) != null){
415 for (int i = 0; i < t; i++){
418 if (c == '"' || c == '\''){
421 for (i++; i < t; i++){
428 } else if (c == ' '){
430 args.Add (sb.ToString ());
437 args.Add (sb.ToString ());
442 string [] ret_value = new string [args.Count];
443 args.CopyTo (ret_value, 0);
449 // Returns the directory where the system assemblies are installed
451 static string GetSystemDir ()
453 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
455 foreach (Assembly a in assemblies){
456 string codebase = a.Location;
457 string fn = System.IO.Path.GetFileName (codebase);
458 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
459 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
463 Report.Error (-15, "Can not compute my system path");
468 // Given a path specification, splits the path from the file/pattern
470 static void SplitPathAndPattern (string spec, out string path, out string pattern)
472 int p = spec.LastIndexOf ('/');
475 // Windows does not like /file.cs, switch that to:
480 pattern = spec.Substring (1);
482 path = spec.Substring (0, p);
483 pattern = spec.Substring (p + 1);
488 p = spec.LastIndexOf ('\\');
490 path = spec.Substring (0, p);
491 pattern = spec.Substring (p + 1);
499 static void ProcessFile (string f)
501 if (first_source == null)
504 Location.AddFile (f);
507 static void ProcessFiles ()
509 Location.Initialize ();
511 foreach (SourceFile file in Location.SourceFiles) {
513 tokenize_file (file);
520 static void CompileFiles (string spec, bool recurse)
522 string path, pattern;
524 SplitPathAndPattern (spec, out path, out pattern);
525 if (pattern.IndexOf ('*') == -1){
530 string [] files = null;
532 files = Directory.GetFiles (path, pattern);
533 } catch (System.IO.DirectoryNotFoundException) {
534 Report.Error (2001, "Source file `" + spec + "' could not be found");
536 } catch (System.IO.IOException){
537 Report.Error (2001, "Source file `" + spec + "' could not be found");
540 foreach (string f in files) {
547 string [] dirs = null;
550 dirs = Directory.GetDirectories (path);
554 foreach (string d in dirs) {
556 // Don't include path in this string, as each
557 // directory entry already does
558 CompileFiles (d + "/" + pattern, true);
562 static void DefineDefaultConfig ()
565 // For now the "default config" is harcoded into the compiler
566 // we can move this outside later
568 string [] default_config = {
573 // Is it worth pre-loading all this stuff?
576 "System.Configuration.Install",
579 "System.DirectoryServices",
580 "System.Drawing.Design",
582 "System.EnterpriseServices",
585 "System.Runtime.Remoting",
586 "System.Runtime.Serialization.Formatters.Soap",
588 "System.ServiceProcess",
590 "System.Web.RegularExpressions",
591 "System.Web.Services",
592 "System.Windows.Forms"
597 foreach (string def in default_config)
598 soft_references.Insert (p++, def);
601 static void SetOutputFile (string name)
606 static void SetWarningLevel (string s)
611 level = Int32.Parse (s);
615 "--wlevel requires a value from 0 to 4");
616 Environment.Exit (1);
618 if (level < 0 || level > 4){
619 Report.Error (1900, "Warning level must be 0 to 4");
620 Environment.Exit (1);
622 RootContext.WarningLevel = level;
623 TestWarningConflict ();
626 static void TestWarningConflict ()
628 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
629 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
630 Environment.Exit (1);
634 static void SetupV2 ()
636 RootContext.Version = LanguageVersion.Default;
637 defines.Add ("__V2__");
640 static void Version ()
642 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
643 Console.WriteLine ("Mono C# compiler version {0}", version);
644 Environment.Exit (0);
648 // Currently handles the Unix-like command line options, but will be
649 // deprecated in favor of the CSCParseOption, which will also handle the
650 // options that start with a dash in the future.
652 static bool UnixParseOption (string arg, ref string [] args, ref int i)
656 CSharpParser.yacc_verbose_flag++;
667 case "--main": case "-m":
668 if ((i + 1) >= args.Length){
670 Environment.Exit (1);
672 RootContext.MainClass = args [++i];
676 RootContext.Unsafe = true;
679 case "/?": case "/h": case "/help":
682 Environment.Exit (0);
686 if ((i + 1) >= args.Length){
688 Environment.Exit (1);
690 defines.Add (args [++i]);
693 case "--show-counters":
694 show_counters = true;
697 case "--expect-error": {
702 args [++i], NumberStyles.AllowLeadingSign);
703 Report.ExpectedError = code;
705 Report.Error (-14, "Invalid number specified");
716 if ((i + 1) >= args.Length){
718 Environment.Exit (1);
720 SetOutputFile (args [++i]);
724 RootContext.Checked = true;
728 Report.Stacktrace = true;
731 case "--linkresource":
733 if ((i + 1) >= args.Length){
735 Report.Error (5, "Missing argument to --linkres");
736 Environment.Exit (1);
738 if (resources == null)
739 resources = new ArrayList ();
741 resources.Add (args [++i]);
746 if ((i + 1) >= args.Length){
748 Report.Error (5, "Missing argument to --resource");
749 Environment.Exit (1);
751 if (embedded_resources == null)
752 embedded_resources = new ArrayList ();
754 embedded_resources.Add (args [++i]);
758 if ((i + 1) >= args.Length){
759 Environment.Exit (1);
763 string type = args [++i];
766 RootContext.Target = Target.Library;
767 RootContext.TargetExt = ".dll";
771 RootContext.Target = Target.Exe;
775 RootContext.Target = Target.WinExe;
779 RootContext.Target = Target.Module;
780 RootContext.TargetExt = ".dll";
784 Environment.Exit (1);
790 if ((i + 1) >= args.Length){
792 Environment.Exit (1);
795 references.Add (args [++i]);
799 if ((i + 1) >= args.Length){
801 Environment.Exit (1);
803 link_paths.Add (args [++i]);
807 RootContext.StdLib = false;
815 Report.WarningsAreErrors = true;
816 TestWarningConflict();
820 if ((i + 1) >= args.Length){
822 Environment.Exit (1);
827 warn = Int32.Parse (args [++i]);
830 Environment.Exit (1);
832 Report.SetIgnoreWarning (warn);
836 if ((i + 1) >= args.Length){
839 "--wlevel requires a value from 0 to 4");
840 Environment.Exit (1);
843 SetWarningLevel (args [++i]);
847 if ((i + 1) >= args.Length){
848 Report.Error (5, "--mcs-debug requires an argument");
849 Environment.Exit (1);
853 Report.DebugFlags = Int32.Parse (args [++i]);
855 Report.Error (5, "Invalid argument to --mcs-debug");
856 Environment.Exit (1);
865 if ((i + 1) >= args.Length){
866 Report.Error (5, "--recurse requires an argument");
867 Environment.Exit (1);
869 CompileFiles (args [++i], true);
874 last_time = first_time = DateTime.Now;
881 case "--debug": case "-g":
882 want_debugging_support = true;
886 load_default_config = false;
894 // Currently it is very basic option parsing, but eventually, this will
895 // be the complete option parser
897 static bool CSCParseOption (string option, ref string [] args, ref int i)
899 int idx = option.IndexOf (':');
906 arg = option.Substring (0, idx);
908 value = option.Substring (idx + 1);
919 RootContext.Target = Target.Exe;
923 RootContext.Target = Target.WinExe;
927 RootContext.Target = Target.Library;
928 RootContext.TargetExt = ".dll";
932 RootContext.Target = Target.Module;
933 RootContext.TargetExt = ".netmodule";
938 Environment.Exit (1);
946 Environment.Exit (1);
948 SetOutputFile (value);
955 case "/incremental+":
956 case "/incremental-":
966 Environment.Exit (1);
969 defs = value.Split (new Char [] {';', ','});
970 foreach (string d in defs){
977 case "/linkresource":
979 Report.Error (5, arg + " requires an argument");
980 Environment.Exit (1);
982 if (resources == null)
983 resources = new ArrayList ();
985 resources.Add (value);
993 Environment.Exit (1);
995 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
997 ProcessStartInfo pi = new ProcessStartInfo ();
998 pi.FileName = "pkg-config";
999 pi.RedirectStandardOutput = true;
1000 pi.UseShellExecute = false;
1001 pi.Arguments = "--libs " + packages;
1004 p = Process.Start (pi);
1005 } catch (Exception e) {
1006 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1007 Environment.Exit (1);
1010 if (p.StandardOutput == null){
1011 Report.Warning (-27, "Specified package did not return any information");
1014 string pkgout = p.StandardOutput.ReadToEnd ();
1016 if (p.ExitCode != 0) {
1017 Report.Error (-27, "Error running pkg-config. Check the above output.");
1018 Environment.Exit (1);
1021 if (pkgout != null){
1022 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1023 Split (new Char [] { ' ', '\t'});
1024 args = AddArgs (args, xargs);
1034 Report.Error (5, "-resource requires an argument");
1035 Environment.Exit (1);
1037 if (embedded_resources == null)
1038 embedded_resources = new ArrayList ();
1040 if (embedded_resources.Contains (value)) {
1041 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1043 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1044 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1047 embedded_resources.Add (value);
1053 Report.Error (5, "-recurse requires an argument");
1054 Environment.Exit (1);
1056 CompileFiles (value, true);
1060 case "/reference": {
1062 Report.Error (5, "-reference requires an argument");
1063 Environment.Exit (1);
1066 string [] refs = value.Split (new char [] { ';', ',' });
1067 foreach (string r in refs){
1072 case "/addmodule": {
1074 Report.Error (5, arg + " requires an argument");
1075 Environment.Exit (1);
1078 string [] refs = value.Split (new char [] { ';', ',' });
1079 foreach (string r in refs){
1086 Report.Error (5, arg + " requires an argument");
1087 Environment.Exit (1);
1090 win32ResourceFile = value;
1093 case "/win32icon": {
1095 Report.Error (5, arg + " requires an argument");
1096 Environment.Exit (1);
1099 win32IconFile = value;
1104 Report.Error (2006, arg + " requires an argument");
1105 Environment.Exit (1);
1107 RootContext.Documentation = new Documentation (value);
1114 Report.Error (5, "/lib requires an argument");
1115 Environment.Exit (1);
1118 libdirs = value.Split (new Char [] { ',' });
1119 foreach (string dir in libdirs)
1120 link_paths.Add (dir);
1125 want_debugging_support = false;
1130 want_debugging_support = true;
1135 RootContext.Checked = true;
1139 RootContext.Checked = false;
1147 RootContext.VerifyClsCompliance = false;
1152 RootContext.Unsafe = true;
1156 RootContext.Unsafe = false;
1159 case "/warnaserror":
1160 case "/warnaserror+":
1161 Report.WarningsAreErrors = true;
1162 TestWarningConflict();
1165 case "/warnaserror-":
1166 Report.WarningsAreErrors = false;
1170 SetWarningLevel (value);
1177 Report.Error (5, "/nowarn requires an argument");
1178 Environment.Exit (1);
1181 warns = value.Split (new Char [] {','});
1182 foreach (string wc in warns){
1184 int warn = Int32.Parse (wc);
1186 throw new ArgumentOutOfRangeException("warn");
1188 Report.SetIgnoreWarning (warn);
1190 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1191 Environment.Exit (1);
1198 load_default_config = true;
1203 load_default_config = false;
1208 Environment.Exit(0);
1214 Environment.Exit (0);
1220 Report.Error (5, arg + " requires an argument");
1221 Environment.Exit (1);
1223 RootContext.MainClass = value;
1228 RootContext.StdLib = false;
1232 RootContext.StdLib = true;
1239 if (value == String.Empty) {
1240 Report.Error (5, arg + " requires an argument");
1241 Environment.Exit (1);
1243 RootContext.StrongNameKeyFile = value;
1245 case "/keycontainer":
1246 if (value == String.Empty) {
1247 Report.Error (5, arg + " requires an argument");
1248 Environment.Exit (1);
1250 RootContext.StrongNameKeyContainer = value;
1253 RootContext.StrongNameDelaySign = true;
1256 RootContext.StrongNameDelaySign = false;
1261 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1265 case "/langversion":
1266 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1268 RootContext.Version = LanguageVersion.ISO_1;
1275 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1276 Environment.Exit (1);
1282 if (value == "utf8"){
1283 encoding = new UTF8Encoding();
1284 using_default_encoder = false;
1287 if (value == "reset"){
1289 // 28591 is the code page for ISO-8859-1 encoding.
1292 using_default_encoder = true;
1296 cp = Int32.Parse (value);
1297 encoding = Encoding.GetEncoding (cp);
1298 using_default_encoder = false;
1300 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1301 Environment.Exit (1);
1305 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1306 //Environment.Exit (1);
1310 static string [] AddArgs (string [] args, string [] extra_args)
1313 new_args = new string [extra_args.Length + args.Length];
1315 // if args contains '--' we have to take that into account
1316 // split args into first half and second half based on '--'
1317 // and add the extra_args before --
1318 int split_position = Array.IndexOf (args, "--");
1319 if (split_position != -1)
1321 Array.Copy (args, new_args, split_position);
1322 extra_args.CopyTo (new_args, split_position);
1323 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1327 args.CopyTo (new_args, 0);
1328 extra_args.CopyTo (new_args, args.Length);
1335 /// Parses the arguments, and drives the compilation
1340 /// TODO: Mostly structured to debug the compiler
1341 /// now, needs to be turned into a real driver soon.
1343 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1344 internal static bool MainDriver (string [] args)
1347 bool parsing_options = true;
1350 encoding = Encoding.GetEncoding (28591);
1352 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1353 encoding = Encoding.GetEncoding (1252);
1356 references = new ArrayList ();
1357 soft_references = new ArrayList ();
1358 modules = new ArrayList ();
1359 link_paths = new ArrayList ();
1361 SetupDefaultDefines ();
1366 // This is not required because Assembly.Load knows about this
1370 for (i = 0; i < args.Length; i++){
1371 string arg = args [i];
1375 if (arg.StartsWith ("@")){
1376 string [] extra_args;
1377 string response_file = arg.Substring (1);
1379 if (response_file_list == null)
1380 response_file_list = new Hashtable ();
1382 if (response_file_list.Contains (response_file)){
1384 1515, "Response file `" + response_file +
1385 "' specified multiple times");
1386 Environment.Exit (1);
1389 response_file_list.Add (response_file, response_file);
1391 extra_args = LoadArgs (response_file);
1392 if (extra_args == null){
1393 Report.Error (2011, "Unable to open response file: " +
1398 args = AddArgs (args, extra_args);
1402 if (parsing_options){
1404 parsing_options = false;
1408 if (arg.StartsWith ("-")){
1409 if (UnixParseOption (arg, ref args, ref i))
1413 string csc_opt = "/" + arg.Substring (1);
1414 if (CSCParseOption (csc_opt, ref args, ref i))
1417 if (arg.StartsWith ("/")){
1418 if (CSCParseOption (arg, ref args, ref i))
1424 CompileFiles (arg, false);
1433 // This will point to the NamespaceEntry of the last file that was parsed, and may
1434 // not be meaningful when resolving classes from other files. So, reset it to prevent
1437 RootContext.Tree.Types.NamespaceEntry = null;
1440 // If we are an exe, require a source file for the entry point
1442 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1443 if (first_source == null){
1444 Report.Error (2008, "No files to compile were specified");
1451 // If there is nothing to put in the assembly, and we are not a library
1453 if (first_source == null && embedded_resources == null && resources == null){
1454 Report.Error (2008, "No files to compile were specified");
1458 if (Report.Errors > 0)
1464 Tokenizer.Cleanup ();
1467 // Load Core Library for default compilation
1469 if (RootContext.StdLib)
1470 references.Insert (0, "mscorlib");
1472 if (load_default_config)
1473 DefineDefaultConfig ();
1475 if (Report.Errors > 0){
1480 // Load assemblies required
1483 ShowTime ("Loading references");
1484 link_paths.Add (GetSystemDir ());
1485 link_paths.Add (Directory.GetCurrentDirectory ());
1489 ShowTime (" References loaded");
1491 if (Report.Errors > 0){
1498 if (output_file == null){
1499 int pos = first_source.LastIndexOf ('.');
1502 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1504 output_file = first_source + RootContext.TargetExt;
1507 CodeGen.Init (output_file, output_file, want_debugging_support);
1509 if (RootContext.Target == Target.Module) {
1510 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1511 if (module_only == null) {
1512 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1513 Environment.Exit (1);
1516 MethodInfo set_method = module_only.GetSetMethod (true);
1517 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1520 TypeManager.AddModule (CodeGen.Module.Builder);
1522 if (modules.Count > 0) {
1523 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1524 if (adder_method == null) {
1525 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1526 Environment.Exit (1);
1529 foreach (string module in modules)
1530 LoadModule (adder_method, module);
1533 TypeManager.ComputeNamespaces ();
1536 // Before emitting, we need to get the core
1537 // types emitted from the user defined types
1538 // or from the system ones.
1541 ShowTime ("Initializing Core Types");
1542 if (!RootContext.StdLib){
1543 RootContext.ResolveCore ();
1544 if (Report.Errors > 0)
1548 TypeManager.InitCoreTypes ();
1550 ShowTime (" Core Types done");
1553 // The second pass of the compiler
1556 ShowTime ("Resolving tree");
1557 RootContext.ResolveTree ();
1559 if (Report.Errors > 0)
1562 ShowTime ("Populate tree");
1563 if (!RootContext.StdLib)
1564 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 ()