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;
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;
72 // A list of resource files
74 static ArrayList resources;
75 static ArrayList embedded_resources;
76 static string win32ResourceFile;
77 static string win32IconFile;
80 // An array of the defines from the command line
82 static ArrayList defines;
87 static string output_file = null;
90 // Last time we took the time
92 static DateTime last_time, first_time;
97 static Encoding default_encoding;
98 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 RootContext.Version = LanguageVersion.Default;
285 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
287 bool ok = MainDriver (args);
289 if (ok && Report.Errors == 0) {
290 if (Report.Warnings > 0) {
291 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
294 Console.WriteLine ("Counter1: " + counter1);
295 Console.WriteLine ("Counter2: " + counter2);
301 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
302 Report.Errors, Report.Warnings);
307 static public void LoadAssembly (string assembly, bool soft)
310 string total_log = "";
313 char[] path_chars = { '/', '\\' };
315 if (assembly.IndexOfAny (path_chars) != -1) {
316 a = Assembly.LoadFrom (assembly);
318 string ass = assembly;
319 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
320 ass = assembly.Substring (0, assembly.Length - 4);
321 a = Assembly.Load (ass);
323 TypeManager.AddAssembly (a);
325 } catch (FileNotFoundException){
326 foreach (string dir in link_paths){
327 string full_path = Path.Combine (dir, assembly);
328 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
332 a = Assembly.LoadFrom (full_path);
333 TypeManager.AddAssembly (a);
335 } catch (FileNotFoundException ff) {
336 total_log += ff.FusionLog;
341 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
342 Console.WriteLine ("Log: \n" + total_log);
344 } catch (BadImageFormatException f) {
345 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
346 } catch (FileLoadException f){
347 Report.Error(6, "Cannot load assembly " + f.FusionLog);
348 } catch (ArgumentNullException){
349 Report.Error(6, "Cannot load assembly (null argument)");
353 static public void LoadModule (MethodInfo adder_method, string module)
356 string total_log = "";
360 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
362 catch (TargetInvocationException ex) {
363 throw ex.InnerException;
365 TypeManager.AddModule (m);
368 catch (FileNotFoundException){
369 foreach (string dir in link_paths){
370 string full_path = Path.Combine (dir, module);
371 if (!module.EndsWith (".netmodule"))
372 full_path += ".netmodule";
376 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
378 catch (TargetInvocationException ex) {
379 throw ex.InnerException;
381 TypeManager.AddModule (m);
383 } catch (FileNotFoundException ff) {
384 total_log += ff.FusionLog;
388 Report.Error (6, "Cannot find module `" + module + "'" );
389 Console.WriteLine ("Log: \n" + total_log);
390 } catch (BadImageFormatException f) {
391 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
392 } catch (FileLoadException f){
393 Report.Error(6, "Cannot load module " + f.FusionLog);
394 } catch (ArgumentNullException){
395 Report.Error(6, "Cannot load module (null argument)");
400 /// Loads all assemblies referenced on the command line
402 static public void LoadReferences ()
404 foreach (string r in references)
405 LoadAssembly (r, false);
407 foreach (string r in soft_references)
408 LoadAssembly (r, true);
413 static void SetupDefaultDefines ()
415 defines = new ArrayList ();
416 defines.Add ("__MonoCS__");
419 static string [] LoadArgs (string file)
422 ArrayList args = new ArrayList ();
425 f = new StreamReader (file);
430 StringBuilder sb = new StringBuilder ();
432 while ((line = f.ReadLine ()) != null){
435 for (int i = 0; i < t; i++){
438 if (c == '"' || c == '\''){
441 for (i++; i < t; i++){
448 } else if (c == ' '){
450 args.Add (sb.ToString ());
457 args.Add (sb.ToString ());
462 string [] ret_value = new string [args.Count];
463 args.CopyTo (ret_value, 0);
469 // Returns the directory where the system assemblies are installed
471 static string GetSystemDir ()
473 return Path.GetDirectoryName (typeof (object).Assembly.Location);
477 // Given a path specification, splits the path from the file/pattern
479 static void SplitPathAndPattern (string spec, out string path, out string pattern)
481 int p = spec.LastIndexOf ('/');
484 // Windows does not like /file.cs, switch that to:
489 pattern = spec.Substring (1);
491 path = spec.Substring (0, p);
492 pattern = spec.Substring (p + 1);
497 p = spec.LastIndexOf ('\\');
499 path = spec.Substring (0, p);
500 pattern = spec.Substring (p + 1);
508 static void ProcessFile (string f)
510 if (first_source == null)
513 Location.AddFile (f);
516 static void ProcessFiles ()
518 Location.Initialize ();
520 foreach (SourceFile file in Location.SourceFiles) {
522 tokenize_file (file);
529 static void CompileFiles (string spec, bool recurse)
531 string path, pattern;
533 SplitPathAndPattern (spec, out path, out pattern);
534 if (pattern.IndexOf ('*') == -1){
539 string [] files = null;
541 files = Directory.GetFiles (path, pattern);
542 } catch (System.IO.DirectoryNotFoundException) {
543 Report.Error (2001, "Source file `" + spec + "' could not be found");
545 } catch (System.IO.IOException){
546 Report.Error (2001, "Source file `" + spec + "' could not be found");
549 foreach (string f in files) {
556 string [] dirs = null;
559 dirs = Directory.GetDirectories (path);
563 foreach (string d in dirs) {
565 // Don't include path in this string, as each
566 // directory entry already does
567 CompileFiles (d + "/" + pattern, true);
571 static void DefineDefaultConfig ()
574 // For now the "default config" is harcoded into the compiler
575 // we can move this outside later
577 string [] default_config = {
582 // Is it worth pre-loading all this stuff?
585 "System.Configuration.Install",
588 "System.DirectoryServices",
589 "System.Drawing.Design",
591 "System.EnterpriseServices",
594 "System.Runtime.Remoting",
595 "System.Runtime.Serialization.Formatters.Soap",
597 "System.ServiceProcess",
599 "System.Web.RegularExpressions",
600 "System.Web.Services",
601 "System.Windows.Forms"
606 foreach (string def in default_config)
607 soft_references.Insert (p++, def);
610 public static string OutputFile
616 return Path.GetFileName (output_file);
620 static void SetWarningLevel (string s)
625 level = Int32.Parse (s);
628 if (level < 0 || level > 4){
629 Report.Error (1900, "Warning level must be in the range 0-4");
632 RootContext.WarningLevel = level;
635 static void SetupV2 ()
637 RootContext.Version = LanguageVersion.Default;
638 defines.Add ("__V2__");
641 static void Version ()
643 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
644 Console.WriteLine ("Mono C# compiler version {0}", version);
645 Environment.Exit (0);
649 // Currently handles the Unix-like command line options, but will be
650 // deprecated in favor of the CSCParseOption, which will also handle the
651 // options that start with a dash in the future.
653 static bool UnixParseOption (string arg, ref string [] args, ref int i)
657 CSharpParser.yacc_verbose_flag++;
668 case "--main": case "-m":
669 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
670 if ((i + 1) >= args.Length){
672 Environment.Exit (1);
674 RootContext.MainClass = args [++i];
678 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
679 RootContext.Unsafe = true;
682 case "/?": case "/h": case "/help":
685 Environment.Exit (0);
689 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
690 if ((i + 1) >= args.Length){
692 Environment.Exit (1);
694 defines.Add (args [++i]);
697 case "--show-counters":
698 show_counters = true;
701 case "--expect-error": {
706 args [++i], NumberStyles.AllowLeadingSign);
707 Report.ExpectedError = code;
709 Report.Error (-14, "Invalid number specified");
720 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
721 if ((i + 1) >= args.Length){
723 Environment.Exit (1);
725 OutputFile = args [++i];
729 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
730 RootContext.Checked = true;
734 Report.Stacktrace = true;
737 case "--linkresource":
739 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
740 if ((i + 1) >= args.Length){
742 Report.Error (5, "Missing argument to --linkres");
743 Environment.Exit (1);
745 if (resources == null)
746 resources = new ArrayList ();
748 resources.Add (args [++i]);
753 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
754 if ((i + 1) >= args.Length){
756 Report.Error (5, "Missing argument to --resource");
757 Environment.Exit (1);
759 if (embedded_resources == null)
760 embedded_resources = new ArrayList ();
762 embedded_resources.Add (args [++i]);
766 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
767 if ((i + 1) >= args.Length){
768 Environment.Exit (1);
772 string type = args [++i];
775 RootContext.Target = Target.Library;
776 RootContext.TargetExt = ".dll";
780 RootContext.Target = Target.Exe;
784 RootContext.Target = Target.WinExe;
788 RootContext.Target = Target.Module;
789 RootContext.TargetExt = ".dll";
798 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
799 if ((i + 1) >= args.Length){
801 Environment.Exit (1);
804 references.Add (args [++i]);
808 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
809 if ((i + 1) >= args.Length){
811 Environment.Exit (1);
813 link_paths.Add (args [++i]);
817 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
818 RootContext.StdLib = false;
826 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
827 Report.WarningsAreErrors = true;
831 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
832 if ((i + 1) >= args.Length){
834 Environment.Exit (1);
839 warn = Int32.Parse (args [++i]);
842 Environment.Exit (1);
844 Report.SetIgnoreWarning (warn);
848 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
849 if ((i + 1) >= args.Length){
852 "--wlevel requires a value from 0 to 4");
853 Environment.Exit (1);
856 SetWarningLevel (args [++i]);
860 if ((i + 1) >= args.Length){
861 Report.Error (5, "--mcs-debug requires an argument");
862 Environment.Exit (1);
866 Report.DebugFlags = Int32.Parse (args [++i]);
868 Report.Error (5, "Invalid argument to --mcs-debug");
869 Environment.Exit (1);
878 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
879 if ((i + 1) >= args.Length){
880 Report.Error (5, "--recurse requires an argument");
881 Environment.Exit (1);
883 CompileFiles (args [++i], true);
888 last_time = first_time = DateTime.Now;
895 case "--debug": case "-g":
896 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
897 want_debugging_support = true;
901 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
902 load_default_config = false;
910 // This parses the -arg and /arg options to the compiler, even if the strings
911 // in the following text use "/arg" on the strings.
913 static bool CSCParseOption (string option, ref string [] args, ref int i)
915 int idx = option.IndexOf (':');
922 arg = option.Substring (0, idx);
924 value = option.Substring (idx + 1);
935 RootContext.Target = Target.Exe;
939 RootContext.Target = Target.WinExe;
943 RootContext.Target = Target.Library;
944 RootContext.TargetExt = ".dll";
948 RootContext.Target = Target.Module;
949 RootContext.TargetExt = ".netmodule";
961 Environment.Exit (1);
968 RootContext.Optimize = true;
972 RootContext.Optimize = false;
976 case "/incremental+":
977 case "/incremental-":
987 Environment.Exit (1);
990 defs = value.Split (new Char [] {';', ','});
991 foreach (string d in defs){
999 // We should collect data, runtime, etc and store in the file specified
1001 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1005 case "/linkresource":
1007 Report.Error (5, arg + " requires an argument");
1008 Environment.Exit (1);
1010 if (resources == null)
1011 resources = new ArrayList ();
1013 resources.Add (value);
1021 Environment.Exit (1);
1023 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1025 ProcessStartInfo pi = new ProcessStartInfo ();
1026 pi.FileName = "pkg-config";
1027 pi.RedirectStandardOutput = true;
1028 pi.UseShellExecute = false;
1029 pi.Arguments = "--libs " + packages;
1032 p = Process.Start (pi);
1033 } catch (Exception e) {
1034 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1035 Environment.Exit (1);
1038 if (p.StandardOutput == null){
1039 Report.Warning (-27, "Specified package did not return any information");
1042 string pkgout = p.StandardOutput.ReadToEnd ();
1044 if (p.ExitCode != 0) {
1045 Report.Error (-27, "Error running pkg-config. Check the above output.");
1046 Environment.Exit (1);
1049 if (pkgout != null){
1050 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1051 Split (new Char [] { ' ', '\t'});
1052 args = AddArgs (args, xargs);
1062 Report.Error (5, "-resource requires an argument");
1063 Environment.Exit (1);
1065 if (embedded_resources == null)
1066 embedded_resources = new ArrayList ();
1068 if (embedded_resources.Contains (value)) {
1069 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1071 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1072 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1075 embedded_resources.Add (value);
1081 Report.Error (5, "-recurse requires an argument");
1082 Environment.Exit (1);
1084 CompileFiles (value, true);
1088 case "/reference": {
1090 Report.Error (5, "-reference requires an argument");
1091 Environment.Exit (1);
1094 string [] refs = value.Split (new char [] { ';', ',' });
1095 foreach (string r in refs){
1100 case "/addmodule": {
1102 Report.Error (5, arg + " requires an argument");
1103 Environment.Exit (1);
1106 string [] refs = value.Split (new char [] { ';', ',' });
1107 foreach (string r in refs){
1114 Report.Error (5, arg + " requires an argument");
1115 Environment.Exit (1);
1118 win32ResourceFile = value;
1121 case "/win32icon": {
1123 Report.Error (5, arg + " requires an argument");
1124 Environment.Exit (1);
1127 win32IconFile = value;
1132 Report.Error (2006, arg + " requires an argument");
1133 Environment.Exit (1);
1135 RootContext.Documentation = new Documentation (value);
1142 Report.Error (5, "/lib requires an argument");
1143 Environment.Exit (1);
1146 libdirs = value.Split (new Char [] { ',' });
1147 foreach (string dir in libdirs)
1148 link_paths.Add (dir);
1153 want_debugging_support = false;
1158 want_debugging_support = true;
1163 RootContext.Checked = true;
1167 RootContext.Checked = false;
1175 RootContext.VerifyClsCompliance = false;
1180 RootContext.Unsafe = true;
1184 RootContext.Unsafe = false;
1187 case "/warnaserror":
1188 case "/warnaserror+":
1189 Report.WarningsAreErrors = true;
1192 case "/warnaserror-":
1193 Report.WarningsAreErrors = false;
1197 SetWarningLevel (value);
1204 Report.Error (5, "/nowarn requires an argument");
1205 Environment.Exit (1);
1208 warns = value.Split (new Char [] {','});
1209 foreach (string wc in warns){
1211 int warn = Int32.Parse (wc);
1213 throw new ArgumentOutOfRangeException("warn");
1215 Report.SetIgnoreWarning (warn);
1217 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1224 load_default_config = true;
1229 load_default_config = false;
1234 Environment.Exit(0);
1240 Environment.Exit (0);
1246 Report.Error (5, arg + " requires an argument");
1247 Environment.Exit (1);
1249 RootContext.MainClass = value;
1254 RootContext.StdLib = false;
1258 RootContext.StdLib = true;
1265 if (value == String.Empty) {
1266 Report.Error (5, arg + " requires an argument");
1267 Environment.Exit (1);
1269 RootContext.StrongNameKeyFile = value;
1271 case "/keycontainer":
1272 if (value == String.Empty) {
1273 Report.Error (5, arg + " requires an argument");
1274 Environment.Exit (1);
1276 RootContext.StrongNameKeyContainer = value;
1279 RootContext.StrongNameDelaySign = true;
1282 RootContext.StrongNameDelaySign = false;
1287 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1291 case "/langversion":
1292 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1294 RootContext.Version = LanguageVersion.ISO_1;
1301 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1307 encoding = new UTF8Encoding();
1310 encoding = default_encoding;
1314 encoding = Encoding.GetEncoding (
1315 Int32.Parse (value));
1317 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1327 static void Error_WrongOption (string option)
1329 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1332 static string [] AddArgs (string [] args, string [] extra_args)
1335 new_args = new string [extra_args.Length + args.Length];
1337 // if args contains '--' we have to take that into account
1338 // split args into first half and second half based on '--'
1339 // and add the extra_args before --
1340 int split_position = Array.IndexOf (args, "--");
1341 if (split_position != -1)
1343 Array.Copy (args, new_args, split_position);
1344 extra_args.CopyTo (new_args, split_position);
1345 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1349 args.CopyTo (new_args, 0);
1350 extra_args.CopyTo (new_args, args.Length);
1357 /// Parses the arguments, and drives the compilation
1362 /// TODO: Mostly structured to debug the compiler
1363 /// now, needs to be turned into a real driver soon.
1365 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1366 internal static bool MainDriver (string [] args)
1369 bool parsing_options = true;
1373 default_encoding = Encoding.GetEncoding (28591);
1374 } catch (Exception) {
1376 default_encoding = Encoding.GetEncoding (1252);
1378 encoding = default_encoding;
1380 references = new ArrayList ();
1381 soft_references = new ArrayList ();
1382 modules = new ArrayList ();
1383 link_paths = new ArrayList ();
1385 SetupDefaultDefines ();
1390 // This is not required because Assembly.Load knows about this
1394 Hashtable response_file_list = null;
1396 for (i = 0; i < args.Length; i++){
1397 string arg = args [i];
1401 if (arg.StartsWith ("@")){
1402 string [] extra_args;
1403 string response_file = arg.Substring (1);
1405 if (response_file_list == null)
1406 response_file_list = new Hashtable ();
1408 if (response_file_list.Contains (response_file)){
1410 1515, "Response file `" + response_file +
1411 "' specified multiple times");
1412 Environment.Exit (1);
1415 response_file_list.Add (response_file, response_file);
1417 extra_args = LoadArgs (response_file);
1418 if (extra_args == null){
1419 Report.Error (2011, "Unable to open response file: " +
1424 args = AddArgs (args, extra_args);
1428 if (parsing_options){
1430 parsing_options = false;
1434 if (arg.StartsWith ("-")){
1435 if (UnixParseOption (arg, ref args, ref i))
1439 string csc_opt = "/" + arg.Substring (1);
1440 if (CSCParseOption (csc_opt, ref args, ref i))
1443 Error_WrongOption (arg);
1446 if (arg [0] == '/'){
1447 if (CSCParseOption (arg, ref args, ref i))
1450 // Need to skip `/home/test.cs' however /test.cs is considered as error
1451 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1452 Error_WrongOption (arg);
1459 CompileFiles (arg, false);
1468 // This will point to the NamespaceEntry of the last file that was parsed, and may
1469 // not be meaningful when resolving classes from other files. So, reset it to prevent
1472 RootContext.Tree.Types.NamespaceEntry = null;
1475 // If we are an exe, require a source file for the entry point
1477 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1478 if (first_source == null){
1479 Report.Error (2008, "No files to compile were specified");
1486 // If there is nothing to put in the assembly, and we are not a library
1488 if (first_source == null && embedded_resources == null && resources == null){
1489 Report.Error (2008, "No files to compile were specified");
1493 if (Report.Errors > 0)
1500 // Load Core Library for default compilation
1502 if (RootContext.StdLib)
1503 references.Insert (0, "mscorlib");
1505 if (load_default_config)
1506 DefineDefaultConfig ();
1508 if (Report.Errors > 0){
1513 // Load assemblies required
1516 ShowTime ("Loading references");
1517 link_paths.Add (GetSystemDir ());
1518 link_paths.Add (Directory.GetCurrentDirectory ());
1522 ShowTime (" References loaded");
1524 if (Report.Errors > 0){
1531 if (output_file == null){
1532 int pos = first_source.LastIndexOf ('.');
1535 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1537 output_file = first_source + RootContext.TargetExt;
1540 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1543 if (RootContext.Target == Target.Module) {
1544 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1545 if (module_only == null) {
1546 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1547 Environment.Exit (1);
1550 MethodInfo set_method = module_only.GetSetMethod (true);
1551 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1554 TypeManager.AddModule (CodeGen.Module.Builder);
1556 if (modules.Count > 0) {
1557 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1558 if (adder_method == null) {
1559 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1560 Environment.Exit (1);
1563 foreach (string module in modules)
1564 LoadModule (adder_method, module);
1567 TypeManager.ComputeNamespaces ();
1570 // Before emitting, we need to get the core
1571 // types emitted from the user defined types
1572 // or from the system ones.
1575 ShowTime ("Initializing Core Types");
1576 if (!RootContext.StdLib){
1577 RootContext.ResolveCore ();
1578 if (Report.Errors > 0)
1582 TypeManager.InitCoreTypes ();
1584 ShowTime (" Core Types done");
1586 CodeGen.Module.ResolveAttributes ();
1589 // The second pass of the compiler
1592 ShowTime ("Resolving tree");
1593 RootContext.ResolveTree ();
1595 if (Report.Errors > 0)
1598 ShowTime ("Populate tree");
1599 if (!RootContext.StdLib)
1600 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, Location.Null));
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 ();