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, 2005 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;
71 // A list of resource files
73 static ArrayList resources;
74 static ArrayList embedded_resources;
75 static string win32ResourceFile;
76 static string win32IconFile;
79 // An array of the defines from the command line
81 static ArrayList defines;
86 static string output_file = null;
89 // Last time we took the time
91 static DateTime last_time, first_time;
96 static Encoding default_encoding;
97 static Encoding encoding;
100 static public void Reset ()
102 want_debugging_support = false;
106 show_counters = false;
107 load_default_config = true;
108 resources = embedded_resources = null;
109 win32ResourceFile = win32IconFile = null;
112 encoding = default_encoding = null;
116 public static void ShowTime (string msg)
121 DateTime now = DateTime.Now;
122 TimeSpan span = now - last_time;
126 "[{0:00}:{1:000}] {2}",
127 (int) span.TotalSeconds, span.Milliseconds, msg);
130 public static void ShowTotalTime (string msg)
135 DateTime now = DateTime.Now;
136 TimeSpan span = now - first_time;
140 "[{0:00}:{1:000}] {2}",
141 (int) span.TotalSeconds, span.Milliseconds, msg);
144 static void tokenize_file (SourceFile file)
149 input = File.OpenRead (file.Name);
151 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
156 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
157 Tokenizer lexer = new Tokenizer (reader, file, defines);
158 int token, tokens = 0, errors = 0;
160 while ((token = lexer.token ()) != Token.EOF){
162 if (token == Token.ERROR)
165 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
171 // MonoTODO("Change error code for aborted compilation to something reasonable")]
172 static void parse (SourceFile file)
178 input = File.OpenRead (file.Name);
180 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
184 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
187 if (reader.Read () == 77 && reader.Read () == 90) {
188 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
194 parser = new CSharpParser (reader, file, defines);
195 parser.ErrorOutput = Report.Stderr;
198 } catch (Exception ex) {
199 Report.Error(666, "Compilation aborted: " + ex);
205 static void OtherFlags ()
208 "Other flags in the compiler\n" +
209 " --fatal Makes errors fatal\n" +
210 " --parse Only parses the source file\n" +
211 " --stacktrace Shows stack trace at error location\n" +
212 " --timestamp Displays time stamps of various compiler events\n" +
213 " --expect-error X Expect that error X will be encountered\n" +
214 " -2 Enables experimental C# features\n" +
215 " -v Verbose parsing (for debugging the parser)\n" +
216 " --mcs-debug X Sets MCS debugging level to X\n");
222 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
223 "mcs [options] source-files\n" +
224 " --about About the Mono C# compiler\n" +
225 " -addmodule:MODULE Adds the module to the generated assembly\n" +
226 " -checked[+|-] Set default context to checked\n" +
227 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
228 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
229 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
230 " -debug[+|-], -g Generate debugging information\n" +
231 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
232 " -doc:FILE XML Documentation file to generate\n" +
233 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
234 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
235 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
236 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
237 " -main:class Specified the class that contains the entry point\n" +
238 " -noconfig[+|-] Disables implicit references to assemblies\n" +
239 " -nostdlib[+|-] Does not load core libraries\n" +
240 " -nowarn:W1[,W2] Disables one or more warnings\n" +
241 " -optimize[+|-] Enables code optimalizations\n" +
242 " -out:FNAME Specifies output file\n" +
243 " -pkg:P1[,Pn] References packages P1..Pn\n" +
244 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
245 " -reference:ASS References the specified assembly (-r:ASS)\n" +
246 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
247 " library, module), (short: /t:)\n" +
248 " -unsafe[+|-] Allows unsafe code\n" +
249 " -warnaserror[+|-] Treat warnings as errors\n" +
250 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
251 " -help2 Show other help flags\n" +
254 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
255 " -resource:FILE[,ID] Embed FILE as a resource\n" +
256 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
257 " -win32icon:FILE Use this icon for the output\n" +
258 " @file Read response file for more options\n\n" +
259 "Options can be of the form -option or /option");
262 static void TargetUsage ()
264 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
270 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
271 "The compiler source code is released under the terms of the GNU GPL\n\n" +
273 "For more information on Mono, visit the project Web site\n" +
274 " http://www.go-mono.com\n\n" +
276 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
277 Environment.Exit (0);
280 public static int counter1, counter2;
282 public static int Main (string[] args)
284 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
286 bool ok = MainDriver (args);
288 if (ok && Report.Errors == 0) {
289 if (Report.Warnings > 0) {
290 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
293 Console.WriteLine ("Counter1: " + counter1);
294 Console.WriteLine ("Counter2: " + counter2);
300 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
301 Report.Errors, Report.Warnings);
306 static public void LoadAssembly (string assembly, bool soft)
309 string total_log = "";
312 char[] path_chars = { '/', '\\' };
314 if (assembly.IndexOfAny (path_chars) != -1) {
315 a = Assembly.LoadFrom (assembly);
317 string ass = assembly;
318 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
319 ass = assembly.Substring (0, assembly.Length - 4);
320 a = Assembly.Load (ass);
322 TypeManager.AddAssembly (a);
324 } catch (FileNotFoundException){
325 foreach (string dir in link_paths){
326 string full_path = Path.Combine (dir, assembly);
327 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
331 a = Assembly.LoadFrom (full_path);
332 TypeManager.AddAssembly (a);
334 } catch (FileNotFoundException ff) {
335 total_log += ff.FusionLog;
340 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
341 Console.WriteLine ("Log: \n" + total_log);
343 } catch (BadImageFormatException f) {
344 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
345 } catch (FileLoadException f){
346 Report.Error(6, "Cannot load assembly " + f.FusionLog);
347 } catch (ArgumentNullException){
348 Report.Error(6, "Cannot load assembly (null argument)");
352 static public void LoadModule (MethodInfo adder_method, string module)
355 string total_log = "";
359 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
361 catch (TargetInvocationException ex) {
362 throw ex.InnerException;
364 TypeManager.AddModule (m);
367 catch (FileNotFoundException){
368 foreach (string dir in link_paths){
369 string full_path = Path.Combine (dir, module);
370 if (!module.EndsWith (".netmodule"))
371 full_path += ".netmodule";
375 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
377 catch (TargetInvocationException ex) {
378 throw ex.InnerException;
380 TypeManager.AddModule (m);
382 } catch (FileNotFoundException ff) {
383 total_log += ff.FusionLog;
387 Report.Error (6, "Cannot find module `" + module + "'" );
388 Console.WriteLine ("Log: \n" + total_log);
389 } catch (BadImageFormatException f) {
390 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
391 } catch (FileLoadException f){
392 Report.Error(6, "Cannot load module " + f.FusionLog);
393 } catch (ArgumentNullException){
394 Report.Error(6, "Cannot load module (null argument)");
399 /// Loads all assemblies referenced on the command line
401 static public void LoadReferences ()
403 foreach (string r in references)
404 LoadAssembly (r, false);
406 foreach (string r in soft_references)
407 LoadAssembly (r, true);
412 static void SetupDefaultDefines ()
414 defines = new ArrayList ();
415 defines.Add ("__MonoCS__");
418 static string [] LoadArgs (string file)
421 ArrayList args = new ArrayList ();
424 f = new StreamReader (file);
429 StringBuilder sb = new StringBuilder ();
431 while ((line = f.ReadLine ()) != null){
434 for (int i = 0; i < t; i++){
437 if (c == '"' || c == '\''){
440 for (i++; i < t; i++){
447 } else if (c == ' '){
449 args.Add (sb.ToString ());
456 args.Add (sb.ToString ());
461 string [] ret_value = new string [args.Count];
462 args.CopyTo (ret_value, 0);
468 // Returns the directory where the system assemblies are installed
470 static string GetSystemDir ()
472 return Path.GetDirectoryName (typeof (object).Assembly.Location);
476 // Given a path specification, splits the path from the file/pattern
478 static void SplitPathAndPattern (string spec, out string path, out string pattern)
480 int p = spec.LastIndexOf ('/');
483 // Windows does not like /file.cs, switch that to:
488 pattern = spec.Substring (1);
490 path = spec.Substring (0, p);
491 pattern = spec.Substring (p + 1);
496 p = spec.LastIndexOf ('\\');
498 path = spec.Substring (0, p);
499 pattern = spec.Substring (p + 1);
507 static void ProcessFile (string f)
509 if (first_source == null)
512 Location.AddFile (f);
515 static void ProcessFiles ()
517 Location.Initialize ();
519 foreach (SourceFile file in Location.SourceFiles) {
521 tokenize_file (file);
528 static void CompileFiles (string spec, bool recurse)
530 string path, pattern;
532 SplitPathAndPattern (spec, out path, out pattern);
533 if (pattern.IndexOf ('*') == -1){
538 string [] files = null;
540 files = Directory.GetFiles (path, pattern);
541 } catch (System.IO.DirectoryNotFoundException) {
542 Report.Error (2001, "Source file `" + spec + "' could not be found");
544 } catch (System.IO.IOException){
545 Report.Error (2001, "Source file `" + spec + "' could not be found");
548 foreach (string f in files) {
555 string [] dirs = null;
558 dirs = Directory.GetDirectories (path);
562 foreach (string d in dirs) {
564 // Don't include path in this string, as each
565 // directory entry already does
566 CompileFiles (d + "/" + pattern, true);
570 static void DefineDefaultConfig ()
573 // For now the "default config" is harcoded into the compiler
574 // we can move this outside later
576 string [] default_config = {
581 // Is it worth pre-loading all this stuff?
584 "System.Configuration.Install",
587 "System.DirectoryServices",
588 "System.Drawing.Design",
590 "System.EnterpriseServices",
593 "System.Runtime.Remoting",
594 "System.Runtime.Serialization.Formatters.Soap",
596 "System.ServiceProcess",
598 "System.Web.RegularExpressions",
599 "System.Web.Services",
600 "System.Windows.Forms"
605 foreach (string def in default_config)
606 soft_references.Insert (p++, def);
609 public static string OutputFile
615 return Path.GetFileName (output_file);
619 static void SetWarningLevel (string s)
624 level = Int32.Parse (s);
627 if (level < 0 || level > 4){
628 Report.Error (1900, "Warning level must be in the range 0-4");
631 RootContext.WarningLevel = level;
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 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
669 if ((i + 1) >= args.Length){
671 Environment.Exit (1);
673 RootContext.MainClass = args [++i];
677 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
678 RootContext.Unsafe = true;
681 case "/?": case "/h": case "/help":
684 Environment.Exit (0);
688 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
689 if ((i + 1) >= args.Length){
691 Environment.Exit (1);
693 defines.Add (args [++i]);
696 case "--show-counters":
697 show_counters = true;
700 case "--expect-error": {
705 args [++i], NumberStyles.AllowLeadingSign);
706 Report.ExpectedError = code;
708 Report.Error (-14, "Invalid number specified");
719 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
720 if ((i + 1) >= args.Length){
722 Environment.Exit (1);
724 OutputFile = args [++i];
728 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
729 RootContext.Checked = true;
733 Report.Stacktrace = true;
736 case "--linkresource":
738 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
739 if ((i + 1) >= args.Length){
741 Report.Error (5, "Missing argument to --linkres");
742 Environment.Exit (1);
744 if (resources == null)
745 resources = new ArrayList ();
747 resources.Add (args [++i]);
752 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
753 if ((i + 1) >= args.Length){
755 Report.Error (5, "Missing argument to --resource");
756 Environment.Exit (1);
758 if (embedded_resources == null)
759 embedded_resources = new ArrayList ();
761 embedded_resources.Add (args [++i]);
765 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
766 if ((i + 1) >= args.Length){
767 Environment.Exit (1);
771 string type = args [++i];
774 RootContext.Target = Target.Library;
775 RootContext.TargetExt = ".dll";
779 RootContext.Target = Target.Exe;
783 RootContext.Target = Target.WinExe;
787 RootContext.Target = Target.Module;
788 RootContext.TargetExt = ".dll";
797 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
798 if ((i + 1) >= args.Length){
800 Environment.Exit (1);
803 references.Add (args [++i]);
807 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
808 if ((i + 1) >= args.Length){
810 Environment.Exit (1);
812 link_paths.Add (args [++i]);
816 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
817 RootContext.StdLib = false;
825 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
826 Report.WarningsAreErrors = true;
830 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
831 if ((i + 1) >= args.Length){
833 Environment.Exit (1);
838 warn = Int32.Parse (args [++i]);
841 Environment.Exit (1);
843 Report.SetIgnoreWarning (warn);
847 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
848 if ((i + 1) >= args.Length){
851 "--wlevel requires a value from 0 to 4");
852 Environment.Exit (1);
855 SetWarningLevel (args [++i]);
859 if ((i + 1) >= args.Length){
860 Report.Error (5, "--mcs-debug requires an argument");
861 Environment.Exit (1);
865 Report.DebugFlags = Int32.Parse (args [++i]);
867 Report.Error (5, "Invalid argument to --mcs-debug");
868 Environment.Exit (1);
877 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
878 if ((i + 1) >= args.Length){
879 Report.Error (5, "--recurse requires an argument");
880 Environment.Exit (1);
882 CompileFiles (args [++i], true);
887 last_time = first_time = DateTime.Now;
894 case "--debug": case "-g":
895 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
896 want_debugging_support = true;
900 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
901 load_default_config = false;
909 // This parses the -arg and /arg options to the compiler, even if the strings
910 // in the following text use "/arg" on the strings.
912 static bool CSCParseOption (string option, ref string [] args, ref int i)
914 int idx = option.IndexOf (':');
921 arg = option.Substring (0, idx);
923 value = option.Substring (idx + 1);
934 RootContext.Target = Target.Exe;
938 RootContext.Target = Target.WinExe;
942 RootContext.Target = Target.Library;
943 RootContext.TargetExt = ".dll";
947 RootContext.Target = Target.Module;
948 RootContext.TargetExt = ".netmodule";
960 Environment.Exit (1);
967 RootContext.Optimize = true;
971 RootContext.Optimize = false;
975 case "/incremental+":
976 case "/incremental-":
986 Environment.Exit (1);
989 defs = value.Split (new Char [] {';', ','});
990 foreach (string d in defs){
998 // We should collect data, runtime, etc and store in the file specified
1000 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1004 case "/linkresource":
1006 Report.Error (5, arg + " requires an argument");
1007 Environment.Exit (1);
1009 if (resources == null)
1010 resources = new ArrayList ();
1012 resources.Add (value);
1020 Environment.Exit (1);
1022 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1024 ProcessStartInfo pi = new ProcessStartInfo ();
1025 pi.FileName = "pkg-config";
1026 pi.RedirectStandardOutput = true;
1027 pi.UseShellExecute = false;
1028 pi.Arguments = "--libs " + packages;
1031 p = Process.Start (pi);
1032 } catch (Exception e) {
1033 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1034 Environment.Exit (1);
1037 if (p.StandardOutput == null){
1038 Report.Warning (-27, "Specified package did not return any information");
1041 string pkgout = p.StandardOutput.ReadToEnd ();
1043 if (p.ExitCode != 0) {
1044 Report.Error (-27, "Error running pkg-config. Check the above output.");
1045 Environment.Exit (1);
1048 if (pkgout != null){
1049 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1050 Split (new Char [] { ' ', '\t'});
1051 args = AddArgs (args, xargs);
1061 Report.Error (5, "-resource requires an argument");
1062 Environment.Exit (1);
1064 if (embedded_resources == null)
1065 embedded_resources = new ArrayList ();
1067 if (embedded_resources.Contains (value)) {
1068 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1070 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1071 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1074 embedded_resources.Add (value);
1080 Report.Error (5, "-recurse requires an argument");
1081 Environment.Exit (1);
1083 CompileFiles (value, true);
1087 case "/reference": {
1089 Report.Error (5, "-reference requires an argument");
1090 Environment.Exit (1);
1093 string [] refs = value.Split (new char [] { ';', ',' });
1094 foreach (string r in refs){
1099 case "/addmodule": {
1101 Report.Error (5, arg + " requires an argument");
1102 Environment.Exit (1);
1105 string [] refs = value.Split (new char [] { ';', ',' });
1106 foreach (string r in refs){
1113 Report.Error (5, arg + " requires an argument");
1114 Environment.Exit (1);
1117 win32ResourceFile = value;
1120 case "/win32icon": {
1122 Report.Error (5, arg + " requires an argument");
1123 Environment.Exit (1);
1126 win32IconFile = value;
1131 Report.Error (2006, arg + " requires an argument");
1132 Environment.Exit (1);
1134 RootContext.Documentation = new Documentation (value);
1141 Report.Error (5, "/lib requires an argument");
1142 Environment.Exit (1);
1145 libdirs = value.Split (new Char [] { ',' });
1146 foreach (string dir in libdirs)
1147 link_paths.Add (dir);
1152 want_debugging_support = false;
1157 want_debugging_support = true;
1162 RootContext.Checked = true;
1166 RootContext.Checked = false;
1174 RootContext.VerifyClsCompliance = false;
1179 RootContext.Unsafe = true;
1183 RootContext.Unsafe = false;
1186 case "/warnaserror":
1187 case "/warnaserror+":
1188 Report.WarningsAreErrors = true;
1191 case "/warnaserror-":
1192 Report.WarningsAreErrors = false;
1196 SetWarningLevel (value);
1203 Report.Error (5, "/nowarn requires an argument");
1204 Environment.Exit (1);
1207 warns = value.Split (new Char [] {','});
1208 foreach (string wc in warns){
1210 int warn = Int32.Parse (wc);
1212 throw new ArgumentOutOfRangeException("warn");
1214 Report.SetIgnoreWarning (warn);
1216 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1223 load_default_config = true;
1228 load_default_config = false;
1233 Environment.Exit(0);
1239 Environment.Exit (0);
1245 Report.Error (5, arg + " requires an argument");
1246 Environment.Exit (1);
1248 RootContext.MainClass = value;
1253 RootContext.StdLib = false;
1257 RootContext.StdLib = true;
1264 if (value == String.Empty) {
1265 Report.Error (5, arg + " requires an argument");
1266 Environment.Exit (1);
1268 RootContext.StrongNameKeyFile = value;
1270 case "/keycontainer":
1271 if (value == String.Empty) {
1272 Report.Error (5, arg + " requires an argument");
1273 Environment.Exit (1);
1275 RootContext.StrongNameKeyContainer = value;
1278 RootContext.StrongNameDelaySign = true;
1281 RootContext.StrongNameDelaySign = false;
1286 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1290 case "/langversion":
1291 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1293 RootContext.Version = LanguageVersion.ISO_1;
1300 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1306 encoding = new UTF8Encoding();
1309 encoding = default_encoding;
1313 encoding = Encoding.GetEncoding (
1314 Int32.Parse (value));
1316 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1326 static void Error_WrongOption (string option)
1328 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1331 static string [] AddArgs (string [] args, string [] extra_args)
1334 new_args = new string [extra_args.Length + args.Length];
1336 // if args contains '--' we have to take that into account
1337 // split args into first half and second half based on '--'
1338 // and add the extra_args before --
1339 int split_position = Array.IndexOf (args, "--");
1340 if (split_position != -1)
1342 Array.Copy (args, new_args, split_position);
1343 extra_args.CopyTo (new_args, split_position);
1344 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1348 args.CopyTo (new_args, 0);
1349 extra_args.CopyTo (new_args, args.Length);
1356 /// Parses the arguments, and drives the compilation
1361 /// TODO: Mostly structured to debug the compiler
1362 /// now, needs to be turned into a real driver soon.
1364 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1365 internal static bool MainDriver (string [] args)
1368 bool parsing_options = true;
1372 default_encoding = Encoding.GetEncoding (28591);
1373 } catch (Exception) {
1375 default_encoding = Encoding.GetEncoding (1252);
1377 encoding = default_encoding;
1379 references = new ArrayList ();
1380 soft_references = new ArrayList ();
1381 modules = new ArrayList ();
1382 link_paths = new ArrayList ();
1384 SetupDefaultDefines ();
1389 // This is not required because Assembly.Load knows about this
1393 Hashtable response_file_list = null;
1395 for (i = 0; i < args.Length; i++){
1396 string arg = args [i];
1400 if (arg.StartsWith ("@")){
1401 string [] extra_args;
1402 string response_file = arg.Substring (1);
1404 if (response_file_list == null)
1405 response_file_list = new Hashtable ();
1407 if (response_file_list.Contains (response_file)){
1409 1515, "Response file `" + response_file +
1410 "' specified multiple times");
1411 Environment.Exit (1);
1414 response_file_list.Add (response_file, response_file);
1416 extra_args = LoadArgs (response_file);
1417 if (extra_args == null){
1418 Report.Error (2011, "Unable to open response file: " +
1423 args = AddArgs (args, extra_args);
1427 if (parsing_options){
1429 parsing_options = false;
1433 if (arg.StartsWith ("-")){
1434 if (UnixParseOption (arg, ref args, ref i))
1438 string csc_opt = "/" + arg.Substring (1);
1439 if (CSCParseOption (csc_opt, ref args, ref i))
1442 Error_WrongOption (arg);
1445 if (arg [0] == '/'){
1446 if (CSCParseOption (arg, ref args, ref i))
1449 // Need to skip `/home/test.cs' however /test.cs is considered as error
1450 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1451 Error_WrongOption (arg);
1458 CompileFiles (arg, false);
1467 // This will point to the NamespaceEntry of the last file that was parsed, and may
1468 // not be meaningful when resolving classes from other files. So, reset it to prevent
1471 RootContext.Tree.Types.NamespaceEntry = null;
1474 // If we are an exe, require a source file for the entry point
1476 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1477 if (first_source == null){
1478 Report.Error (2008, "No files to compile were specified");
1485 // If there is nothing to put in the assembly, and we are not a library
1487 if (first_source == null && embedded_resources == null && resources == null){
1488 Report.Error (2008, "No files to compile were specified");
1492 if (Report.Errors > 0)
1499 // Load Core Library for default compilation
1501 if (RootContext.StdLib)
1502 references.Insert (0, "mscorlib");
1504 if (load_default_config)
1505 DefineDefaultConfig ();
1507 if (Report.Errors > 0){
1512 // Load assemblies required
1515 ShowTime ("Loading references");
1516 link_paths.Add (GetSystemDir ());
1517 link_paths.Add (Directory.GetCurrentDirectory ());
1521 ShowTime (" References loaded");
1523 if (Report.Errors > 0){
1530 if (output_file == null){
1531 int pos = first_source.LastIndexOf ('.');
1534 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1536 output_file = first_source + RootContext.TargetExt;
1539 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1542 if (RootContext.Target == Target.Module) {
1543 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1544 if (module_only == null) {
1545 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1546 Environment.Exit (1);
1549 MethodInfo set_method = module_only.GetSetMethod (true);
1550 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1553 TypeManager.AddModule (CodeGen.Module.Builder);
1555 if (modules.Count > 0) {
1556 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1557 if (adder_method == null) {
1558 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1559 Environment.Exit (1);
1562 foreach (string module in modules)
1563 LoadModule (adder_method, module);
1566 TypeManager.ComputeNamespaces ();
1569 // Before emitting, we need to get the core
1570 // types emitted from the user defined types
1571 // or from the system ones.
1574 ShowTime ("Initializing Core Types");
1575 if (!RootContext.StdLib){
1576 RootContext.ResolveCore ();
1577 if (Report.Errors > 0)
1581 TypeManager.InitCoreTypes ();
1583 ShowTime (" Core Types done");
1585 CodeGen.Module.ResolveAttributes ();
1588 // The second pass of the compiler
1591 ShowTime ("Resolving tree");
1592 RootContext.ResolveTree ();
1594 if (Report.Errors > 0)
1597 ShowTime ("Populate tree");
1598 if (!RootContext.StdLib)
1599 RootContext.BootCorlib_PopulateCoreTypes ();
1601 RootContext.PopulateTypes ();
1603 TypeManager.InitCodeHelpers ();
1605 RootContext.DefineTypes ();
1607 if (RootContext.Documentation != null &&
1608 !RootContext.Documentation.OutputDocComment (
1613 // Verify using aliases now
1615 Namespace.VerifyUsing ();
1617 if (Report.Errors > 0){
1621 if (RootContext.VerifyClsCompliance) {
1622 CodeGen.Assembly.ResolveClsCompliance ();
1623 if (CodeGen.Assembly.IsClsCompliant) {
1624 AttributeTester.VerifyModulesClsCompliance ();
1625 TypeManager.LoadAllImportedTypes ();
1628 if (Report.Errors > 0)
1632 // The code generator
1635 ShowTime ("Emitting code");
1636 ShowTotalTime ("Total so far");
1637 RootContext.EmitCode ();
1641 if (Report.Errors > 0){
1646 ShowTime ("Closing types");
1648 RootContext.CloseTypes ();
1650 PEFileKinds k = PEFileKinds.ConsoleApplication;
1652 switch (RootContext.Target) {
1653 case Target.Library:
1655 k = PEFileKinds.Dll; break;
1657 k = PEFileKinds.ConsoleApplication; break;
1659 k = PEFileKinds.WindowApplication; break;
1662 if (RootContext.NeedsEntryPoint) {
1663 MethodInfo ep = RootContext.EntryPoint;
1666 if (RootContext.MainClass != null) {
1667 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1668 if (main_cont == null) {
1669 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1673 if (!(main_cont is ClassOrStruct)) {
1674 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1678 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1682 if (Report.Errors == 0)
1683 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1688 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1689 } else if (RootContext.MainClass != null) {
1690 Report.Error (2017, "Cannot specify -main if building a module or library");
1694 // Add the resources
1696 if (resources != null){
1697 foreach (string spec in resources){
1701 cp = spec.IndexOf (',');
1703 file = spec.Substring (0, cp);
1704 res = spec.Substring (cp + 1);
1708 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1712 if (embedded_resources != null){
1713 object[] margs = new object [2];
1714 Type[] argst = new Type [2];
1715 argst [0] = argst [1] = typeof (string);
1717 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1718 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1719 null, CallingConventions.Any, argst, null);
1721 if (embed_res == null) {
1722 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1724 foreach (string spec in embedded_resources) {
1727 cp = spec.IndexOf (',');
1729 margs [0] = spec.Substring (cp + 1);
1730 margs [1] = spec.Substring (0, cp);
1733 margs [0] = Path.GetFileName (spec);
1736 if (File.Exists ((string) margs [1]))
1737 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1739 Report.Error (1566, "Can not find the resource " + margs [1]);
1746 // Add Win32 resources
1749 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1751 if (win32ResourceFile != null) {
1753 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1755 catch (ArgumentException) {
1756 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1760 if (win32IconFile != null) {
1761 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1762 if (define_icon == null) {
1763 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1765 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1768 if (Report.Errors > 0)
1771 CodeGen.Save (output_file);
1773 ShowTime ("Saved output");
1774 ShowTotalTime ("Total");
1777 Timer.ShowTimers ();
1779 if (Report.ExpectedError != 0) {
1780 if (Report.Errors == 0) {
1781 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1782 "No other errors reported.");
1784 Environment.Exit (2);
1786 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1787 "However, other errors were reported.");
1789 Environment.Exit (1);
1797 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1798 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1800 return (Report.Errors == 0);
1805 // This is the only public entry point
1807 public class CompilerCallableEntryPoint : MarshalByRefObject {
1808 public static bool InvokeCompiler (string [] args, TextWriter error)
1810 Report.Stderr = error;
1812 return Driver.MainDriver (args) && Report.Errors == 0;
1815 Report.Stderr = Console.Error;
1820 static void Reset ()
1824 RootContext.Reset ();
1826 TypeManager.Reset ();
1827 TypeHandle.Reset ();