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.Collections.Specialized;
21 using System.Globalization;
22 using System.Diagnostics;
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 // External aliases for assemblies.
49 static Hashtable external_aliases;
52 // Modules to be linked
54 static ArrayList modules;
57 static ArrayList link_paths;
59 // Whether we want to only run the tokenizer
60 static bool tokenize = false;
62 static string first_source;
64 static bool want_debugging_support = false;
66 static bool parse_only = false;
67 static bool timestamps = false;
68 static bool pause = false;
69 static bool show_counters = false;
72 // Whether to load the initial config file (what CSC.RSP has by default)
74 static bool load_default_config = true;
77 // A list of resource files
79 static Resources embedded_resources;
80 static string win32ResourceFile;
81 static string win32IconFile;
84 // An array of the defines from the command line
86 static ArrayList defines;
91 static string output_file = null;
94 // Last time we took the time
96 static DateTime last_time, first_time;
101 static Encoding encoding;
103 static public void Reset ()
105 want_debugging_support = false;
109 show_counters = false;
110 load_default_config = true;
111 embedded_resources = null;
112 win32ResourceFile = win32IconFile = null;
119 public static void ShowTime (string msg)
124 DateTime now = DateTime.Now;
125 TimeSpan span = now - last_time;
129 "[{0:00}:{1:000}] {2}",
130 (int) span.TotalSeconds, span.Milliseconds, msg);
133 public static void ShowTotalTime (string msg)
138 DateTime now = DateTime.Now;
139 TimeSpan span = now - first_time;
143 "[{0:00}:{1:000}] {2}",
144 (int) span.TotalSeconds, span.Milliseconds, msg);
147 static void tokenize_file (SourceFile file)
152 input = File.OpenRead (file.Name);
154 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
159 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
160 Tokenizer lexer = new Tokenizer (reader, file, defines);
161 int token, tokens = 0, errors = 0;
163 while ((token = lexer.token ()) != Token.EOF){
165 if (token == Token.ERROR)
168 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
174 // MonoTODO("Change error code for aborted compilation to something reasonable")]
175 static void parse (SourceFile file)
181 input = File.OpenRead (file.Name);
183 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
187 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
190 if (reader.Read () == 77 && reader.Read () == 90) {
191 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
197 parser = new CSharpParser (reader, file, defines);
198 parser.ErrorOutput = Report.Stderr;
201 } catch (Exception ex) {
202 Report.Error(666, "Compilation aborted: " + ex);
208 static void OtherFlags ()
211 "Other flags in the compiler\n" +
212 " --fatal Makes errors fatal\n" +
213 " --parse Only parses the source file\n" +
214 " --stacktrace Shows stack trace at error location\n" +
215 " --timestamp Displays time stamps of various compiler events\n" +
216 " --expect-error X Expect that error X will be encountered\n" +
217 " -2 Enables experimental C# features\n" +
218 " -v Verbose parsing (for debugging the parser)\n" +
219 " --mcs-debug X Sets MCS debugging level to X\n");
225 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
226 "mcs [options] source-files\n" +
227 " --about About the Mono C# compiler\n" +
228 " -addmodule:MODULE Adds the module to the generated assembly\n" +
229 " -checked[+|-] Set default context to checked\n" +
230 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
231 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
232 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
233 " -debug[+|-], -g Generate debugging information\n" +
234 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
235 " -doc:FILE XML Documentation file to generate\n" +
236 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
237 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
238 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
239 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
240 " -main:class Specified the class that contains the entry point\n" +
241 " -noconfig[+|-] Disables implicit references to assemblies\n" +
242 " -nostdlib[+|-] Does not load core libraries\n" +
243 " -nowarn:W1[,W2] Disables one or more warnings\n" +
244 " -optimize[+|-] Enables code optimalizations\n" +
245 " -out:FNAME Specifies output file\n" +
246 " -pkg:P1[,Pn] References packages P1..Pn\n" +
247 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
248 " -reference:ASS References the specified assembly (-r:ASS)\n" +
249 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
250 " library, module), (short: /t:)\n" +
251 " -unsafe[+|-] Allows unsafe code\n" +
252 " -warnaserror[+|-] Treat warnings as errors\n" +
253 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
254 " -help2 Show other help flags\n" +
257 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
258 " -resource:FILE[,ID] Embed FILE as a resource\n" +
259 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
260 " -win32icon:FILE Use this icon for the output\n" +
261 " @file Read response file for more options\n\n" +
262 "Options can be of the form -option or /option");
265 static void TargetUsage ()
267 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
273 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
274 "The compiler source code is released under the terms of the GNU GPL\n\n" +
276 "For more information on Mono, visit the project Web site\n" +
277 " http://www.go-mono.com\n\n" +
279 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
280 Environment.Exit (0);
283 public static int counter1, counter2;
285 public static int Main (string[] args)
287 RootContext.Version = LanguageVersion.Default;
288 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
290 bool ok = MainDriver (args);
292 if (ok && Report.Errors == 0) {
293 if (Report.Warnings > 0) {
294 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
297 Console.WriteLine ("Counter1: " + counter1);
298 Console.WriteLine ("Counter2: " + counter2);
304 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
305 Report.Errors, Report.Warnings);
310 static public void LoadAssembly (string assembly, bool soft)
312 LoadAssembly (assembly, null, soft);
315 static public void LoadAssembly (string assembly, string alias, bool soft)
318 string total_log = "";
321 char[] path_chars = { '/', '\\' };
323 if (assembly.IndexOfAny (path_chars) != -1) {
324 a = Assembly.LoadFrom (assembly);
326 string ass = assembly;
327 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
328 ass = assembly.Substring (0, assembly.Length - 4);
329 a = Assembly.Load (ass);
331 // Extern aliased refs require special handling
333 RootNamespace.Global.AddAssemblyReference (a);
335 RootNamespace.DefineRootNamespace (alias, a);
337 } catch (FileNotFoundException){
338 foreach (string dir in link_paths){
339 string full_path = Path.Combine (dir, assembly);
340 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
344 a = Assembly.LoadFrom (full_path);
346 RootNamespace.Global.AddAssemblyReference (a);
348 RootNamespace.DefineRootNamespace (alias, a);
350 } catch (FileNotFoundException ff) {
351 total_log += ff.FusionLog;
356 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
357 Console.WriteLine ("Log: \n" + total_log);
359 } catch (BadImageFormatException f) {
360 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
361 } catch (FileLoadException f){
362 Report.Error(6, "Cannot load assembly " + f.FusionLog);
363 } catch (ArgumentNullException){
364 Report.Error(6, "Cannot load assembly (null argument)");
368 static public void LoadModule (MethodInfo adder_method, string module)
371 string total_log = "";
375 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
377 catch (TargetInvocationException ex) {
378 throw ex.InnerException;
380 RootNamespace.Global.AddModuleReference (m);
383 catch (FileNotFoundException){
384 foreach (string dir in link_paths){
385 string full_path = Path.Combine (dir, module);
386 if (!module.EndsWith (".netmodule"))
387 full_path += ".netmodule";
391 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
393 catch (TargetInvocationException ex) {
394 throw ex.InnerException;
396 RootNamespace.Global.AddModuleReference (m);
398 } catch (FileNotFoundException ff) {
399 total_log += ff.FusionLog;
403 Report.Error (6, "Cannot find module `" + module + "'" );
404 Console.WriteLine ("Log: \n" + total_log);
405 } catch (BadImageFormatException f) {
406 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
407 } catch (FileLoadException f){
408 Report.Error(6, "Cannot load module " + f.FusionLog);
409 } catch (ArgumentNullException){
410 Report.Error(6, "Cannot load module (null argument)");
415 /// Loads all assemblies referenced on the command line
417 static public void LoadReferences ()
419 foreach (string r in references)
420 LoadAssembly (r, false);
422 foreach (string r in soft_references)
423 LoadAssembly (r, true);
425 foreach (DictionaryEntry entry in external_aliases)
426 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
431 static void SetupDefaultDefines ()
433 defines = new ArrayList ();
434 defines.Add ("__MonoCS__");
437 static string [] LoadArgs (string file)
440 ArrayList args = new ArrayList ();
443 f = new StreamReader (file);
448 StringBuilder sb = new StringBuilder ();
450 while ((line = f.ReadLine ()) != null){
453 for (int i = 0; i < t; i++){
456 if (c == '"' || c == '\''){
459 for (i++; i < t; i++){
466 } else if (c == ' '){
468 args.Add (sb.ToString ());
475 args.Add (sb.ToString ());
480 string [] ret_value = new string [args.Count];
481 args.CopyTo (ret_value, 0);
487 // Returns the directory where the system assemblies are installed
489 static string GetSystemDir ()
491 return Path.GetDirectoryName (typeof (object).Assembly.Location);
495 // Given a path specification, splits the path from the file/pattern
497 static void SplitPathAndPattern (string spec, out string path, out string pattern)
499 int p = spec.LastIndexOf ('/');
502 // Windows does not like /file.cs, switch that to:
507 pattern = spec.Substring (1);
509 path = spec.Substring (0, p);
510 pattern = spec.Substring (p + 1);
515 p = spec.LastIndexOf ('\\');
517 path = spec.Substring (0, p);
518 pattern = spec.Substring (p + 1);
526 static void ProcessFile (string f)
528 if (first_source == null)
531 Location.AddFile (f);
534 static void ProcessFiles ()
536 Location.Initialize ();
538 foreach (SourceFile file in Location.SourceFiles) {
540 tokenize_file (file);
547 static void CompileFiles (string spec, bool recurse)
549 string path, pattern;
551 SplitPathAndPattern (spec, out path, out pattern);
552 if (pattern.IndexOf ('*') == -1){
557 string [] files = null;
559 files = Directory.GetFiles (path, pattern);
560 } catch (System.IO.DirectoryNotFoundException) {
561 Report.Error (2001, "Source file `" + spec + "' could not be found");
563 } catch (System.IO.IOException){
564 Report.Error (2001, "Source file `" + spec + "' could not be found");
567 foreach (string f in files) {
574 string [] dirs = null;
577 dirs = Directory.GetDirectories (path);
581 foreach (string d in dirs) {
583 // Don't include path in this string, as each
584 // directory entry already does
585 CompileFiles (d + "/" + pattern, true);
589 static void DefineDefaultConfig ()
592 // For now the "default config" is harcoded into the compiler
593 // we can move this outside later
595 string [] default_config = {
600 // Is it worth pre-loading all this stuff?
603 "System.Configuration.Install",
606 "System.DirectoryServices",
607 "System.Drawing.Design",
609 "System.EnterpriseServices",
612 "System.Runtime.Remoting",
613 "System.Runtime.Serialization.Formatters.Soap",
615 "System.ServiceProcess",
617 "System.Web.RegularExpressions",
618 "System.Web.Services",
619 "System.Windows.Forms"
624 foreach (string def in default_config)
625 soft_references.Insert (p++, def);
628 public static string OutputFile
634 return Path.GetFileName (output_file);
638 static void SetWarningLevel (string s)
643 level = Int32.Parse (s);
646 if (level < 0 || level > 4){
647 Report.Error (1900, "Warning level must be in the range 0-4");
650 RootContext.WarningLevel = level;
653 static void SetupV2 ()
655 RootContext.Version = LanguageVersion.Default;
656 defines.Add ("__V2__");
659 static void Version ()
661 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
662 Console.WriteLine ("Mono C# compiler version {0}", version);
663 Environment.Exit (0);
667 // Currently handles the Unix-like command line options, but will be
668 // deprecated in favor of the CSCParseOption, which will also handle the
669 // options that start with a dash in the future.
671 static bool UnixParseOption (string arg, ref string [] args, ref int i)
675 CSharpParser.yacc_verbose_flag++;
686 case "--main": case "-m":
687 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
688 if ((i + 1) >= args.Length){
690 Environment.Exit (1);
692 RootContext.MainClass = args [++i];
696 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
697 RootContext.Unsafe = true;
700 case "/?": case "/h": case "/help":
703 Environment.Exit (0);
707 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
708 if ((i + 1) >= args.Length){
710 Environment.Exit (1);
712 defines.Add (args [++i]);
715 case "--show-counters":
716 show_counters = true;
719 case "--expect-error": {
724 args [++i], NumberStyles.AllowLeadingSign);
725 Report.ExpectedError = code;
727 Report.Error (-14, "Invalid number specified");
738 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
739 if ((i + 1) >= args.Length){
741 Environment.Exit (1);
743 OutputFile = args [++i];
747 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
748 RootContext.Checked = true;
752 Report.Stacktrace = true;
755 case "--linkresource":
757 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
758 if ((i + 1) >= args.Length){
760 Report.Error (5, "Missing argument to --linkres");
761 Environment.Exit (1);
763 if (embedded_resources == null)
764 embedded_resources = new Resources ();
766 embedded_resources.Add (false, args [++i], args [i]);
771 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
772 if ((i + 1) >= args.Length){
774 Report.Error (5, "Missing argument to --resource");
775 Environment.Exit (1);
777 if (embedded_resources == null)
778 embedded_resources = new Resources ();
780 embedded_resources.Add (true, args [++i], args [i]);
784 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
785 if ((i + 1) >= args.Length){
786 Environment.Exit (1);
790 string type = args [++i];
793 RootContext.Target = Target.Library;
794 RootContext.TargetExt = ".dll";
798 RootContext.Target = Target.Exe;
802 RootContext.Target = Target.WinExe;
806 RootContext.Target = Target.Module;
807 RootContext.TargetExt = ".dll";
816 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
817 if ((i + 1) >= args.Length){
819 Environment.Exit (1);
822 string val = args [++i];
823 int idx = val.IndexOf ('=');
825 string alias = val.Substring (0, idx);
826 string assembly = val.Substring (idx + 1);
827 AddExternAlias (alias, assembly);
831 references.Add (val);
835 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
836 if ((i + 1) >= args.Length){
838 Environment.Exit (1);
840 link_paths.Add (args [++i]);
844 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
845 RootContext.StdLib = false;
853 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
854 Report.WarningsAreErrors = true;
857 case "--broken-cycles":
858 RootContext.BrokenCircularDeps = true;
862 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
863 if ((i + 1) >= args.Length){
865 Environment.Exit (1);
870 warn = Int32.Parse (args [++i]);
873 Environment.Exit (1);
875 Report.SetIgnoreWarning (warn);
879 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
880 if ((i + 1) >= args.Length){
883 "--wlevel requires a value from 0 to 4");
884 Environment.Exit (1);
887 SetWarningLevel (args [++i]);
891 if ((i + 1) >= args.Length){
892 Report.Error (5, "--mcs-debug requires an argument");
893 Environment.Exit (1);
897 Report.DebugFlags = Int32.Parse (args [++i]);
899 Report.Error (5, "Invalid argument to --mcs-debug");
900 Environment.Exit (1);
909 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
910 if ((i + 1) >= args.Length){
911 Report.Error (5, "--recurse requires an argument");
912 Environment.Exit (1);
914 CompileFiles (args [++i], true);
919 last_time = first_time = DateTime.Now;
926 case "--debug": case "-g":
927 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
928 want_debugging_support = true;
932 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
933 load_default_config = false;
941 // This parses the -arg and /arg options to the compiler, even if the strings
942 // in the following text use "/arg" on the strings.
944 static bool CSCParseOption (string option, ref string [] args, ref int i)
946 int idx = option.IndexOf (':');
953 arg = option.Substring (0, idx);
955 value = option.Substring (idx + 1);
966 RootContext.Target = Target.Exe;
970 RootContext.Target = Target.WinExe;
974 RootContext.Target = Target.Library;
975 RootContext.TargetExt = ".dll";
979 RootContext.Target = Target.Module;
980 RootContext.TargetExt = ".netmodule";
990 if (value.Length == 0){
992 Environment.Exit (1);
999 RootContext.Optimize = true;
1003 RootContext.Optimize = false;
1006 case "/incremental":
1007 case "/incremental+":
1008 case "/incremental-":
1016 if (value.Length == 0){
1018 Environment.Exit (1);
1021 defs = value.Split (new Char [] {';', ','});
1022 foreach (string d in defs){
1030 // We should collect data, runtime, etc and store in the file specified
1032 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1038 if (value.Length == 0){
1040 Environment.Exit (1);
1042 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1044 ProcessStartInfo pi = new ProcessStartInfo ();
1045 pi.FileName = "pkg-config";
1046 pi.RedirectStandardOutput = true;
1047 pi.UseShellExecute = false;
1048 pi.Arguments = "--libs " + packages;
1051 p = Process.Start (pi);
1052 } catch (Exception e) {
1053 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1054 Environment.Exit (1);
1057 if (p.StandardOutput == null){
1058 Report.Warning (-27, 1, "Specified package did not return any information");
1061 string pkgout = p.StandardOutput.ReadToEnd ();
1063 if (p.ExitCode != 0) {
1064 Report.Error (-27, "Error running pkg-config. Check the above output.");
1065 Environment.Exit (1);
1068 if (pkgout != null){
1069 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1070 Split (new Char [] { ' ', '\t'});
1071 args = AddArgs (args, xargs);
1079 case "/linkresource":
1082 if (embedded_resources == null)
1083 embedded_resources = new Resources ();
1085 bool embeded = arg.StartsWith ("/r");
1086 string[] s = value.Split (',');
1089 if (s[0].Length == 0)
1091 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1094 embedded_resources.Add (embeded, s [0], s [1]);
1097 if (s [2] != "public" && s [2] != "private") {
1098 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1101 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1104 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1111 if (value.Length == 0){
1112 Report.Error (5, "-recurse requires an argument");
1113 Environment.Exit (1);
1115 CompileFiles (value, true);
1119 case "/reference": {
1120 if (value.Length == 0){
1121 Report.Error (5, "-reference requires an argument");
1122 Environment.Exit (1);
1125 string [] refs = value.Split (new char [] { ';', ',' });
1126 foreach (string r in refs){
1128 int index = val.IndexOf ("=");
1130 string alias = r.Substring (0, index);
1131 string assembly = r.Substring (index + 1);
1132 AddExternAlias (alias, assembly);
1136 references.Add (val);
1140 case "/addmodule": {
1141 if (value.Length == 0){
1142 Report.Error (5, arg + " requires an argument");
1143 Environment.Exit (1);
1146 string [] refs = value.Split (new char [] { ';', ',' });
1147 foreach (string r in refs){
1153 if (value.Length == 0) {
1154 Report.Error (5, arg + " requires an argument");
1155 Environment.Exit (1);
1158 win32ResourceFile = value;
1161 case "/win32icon": {
1162 if (value.Length == 0) {
1163 Report.Error (5, arg + " requires an argument");
1164 Environment.Exit (1);
1167 win32IconFile = value;
1171 if (value.Length == 0){
1172 Report.Error (2006, arg + " requires an argument");
1173 Environment.Exit (1);
1175 RootContext.Documentation = new Documentation (value);
1181 if (value.Length == 0){
1182 Report.Error (5, "/lib requires an argument");
1183 Environment.Exit (1);
1186 libdirs = value.Split (new Char [] { ',' });
1187 foreach (string dir in libdirs)
1188 link_paths.Add (dir);
1193 want_debugging_support = false;
1198 want_debugging_support = true;
1203 RootContext.Checked = true;
1207 RootContext.Checked = false;
1215 RootContext.VerifyClsCompliance = false;
1220 RootContext.Unsafe = true;
1224 RootContext.Unsafe = false;
1227 case "/warnaserror":
1228 case "/warnaserror+":
1229 Report.WarningsAreErrors = true;
1232 case "/warnaserror-":
1233 Report.WarningsAreErrors = false;
1237 SetWarningLevel (value);
1243 if (value.Length == 0){
1244 Report.Error (5, "/nowarn requires an argument");
1245 Environment.Exit (1);
1248 warns = value.Split (new Char [] {','});
1249 foreach (string wc in warns){
1251 int warn = Int32.Parse (wc);
1253 throw new ArgumentOutOfRangeException("warn");
1255 Report.SetIgnoreWarning (warn);
1257 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1264 load_default_config = true;
1269 load_default_config = false;
1274 Environment.Exit(0);
1280 Environment.Exit (0);
1285 if (value.Length == 0){
1286 Report.Error (5, arg + " requires an argument");
1287 Environment.Exit (1);
1289 RootContext.MainClass = value;
1294 RootContext.StdLib = false;
1298 RootContext.StdLib = true;
1305 if (value == String.Empty) {
1306 Report.Error (5, arg + " requires an argument");
1307 Environment.Exit (1);
1309 RootContext.StrongNameKeyFile = value;
1311 case "/keycontainer":
1312 if (value == String.Empty) {
1313 Report.Error (5, arg + " requires an argument");
1314 Environment.Exit (1);
1316 RootContext.StrongNameKeyContainer = value;
1319 RootContext.StrongNameDelaySign = true;
1322 RootContext.StrongNameDelaySign = false;
1327 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1331 case "/langversion":
1332 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1334 RootContext.Version = LanguageVersion.ISO_1;
1341 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1347 encoding = new UTF8Encoding();
1350 encoding = Encoding.Default;
1354 encoding = Encoding.GetEncoding (
1355 Int32.Parse (value));
1357 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1367 static void Error_WrongOption (string option)
1369 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1372 static string [] AddArgs (string [] args, string [] extra_args)
1375 new_args = new string [extra_args.Length + args.Length];
1377 // if args contains '--' we have to take that into account
1378 // split args into first half and second half based on '--'
1379 // and add the extra_args before --
1380 int split_position = Array.IndexOf (args, "--");
1381 if (split_position != -1)
1383 Array.Copy (args, new_args, split_position);
1384 extra_args.CopyTo (new_args, split_position);
1385 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1389 args.CopyTo (new_args, 0);
1390 extra_args.CopyTo (new_args, args.Length);
1396 static void AddExternAlias (string identifier, string assembly)
1398 if (assembly.Length == 0) {
1399 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1403 if (!IsExternAliasValid (identifier)) {
1404 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1408 // Could here hashtable throw an exception?
1409 external_aliases [identifier] = assembly;
1412 static bool IsExternAliasValid (string identifier)
1414 if (identifier.Length == 0)
1416 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1419 for (int i = 1; i < identifier.Length; i++) {
1420 char c = identifier [i];
1421 if (Char.IsLetter (c) || Char.IsDigit (c))
1424 UnicodeCategory category = Char.GetUnicodeCategory (c);
1425 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1426 category != UnicodeCategory.SpacingCombiningMark ||
1427 category != UnicodeCategory.ConnectorPunctuation)
1435 /// Parses the arguments, and drives the compilation
1440 /// TODO: Mostly structured to debug the compiler
1441 /// now, needs to be turned into a real driver soon.
1443 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1444 internal static bool MainDriver (string [] args)
1447 bool parsing_options = true;
1449 encoding = Encoding.Default;
1451 references = new ArrayList ();
1452 external_aliases = new Hashtable ();
1453 soft_references = new ArrayList ();
1454 modules = new ArrayList ();
1455 link_paths = new ArrayList ();
1457 SetupDefaultDefines ();
1462 // This is not required because Assembly.Load knows about this
1466 Hashtable response_file_list = null;
1468 for (i = 0; i < args.Length; i++){
1469 string arg = args [i];
1470 if (arg.Length == 0)
1473 if (arg.StartsWith ("@")){
1474 string [] extra_args;
1475 string response_file = arg.Substring (1);
1477 if (response_file_list == null)
1478 response_file_list = new Hashtable ();
1480 if (response_file_list.Contains (response_file)){
1482 1515, "Response file `" + response_file +
1483 "' specified multiple times");
1484 Environment.Exit (1);
1487 response_file_list.Add (response_file, response_file);
1489 extra_args = LoadArgs (response_file);
1490 if (extra_args == null){
1491 Report.Error (2011, "Unable to open response file: " +
1496 args = AddArgs (args, extra_args);
1500 if (parsing_options){
1502 parsing_options = false;
1506 if (arg.StartsWith ("-")){
1507 if (UnixParseOption (arg, ref args, ref i))
1511 string csc_opt = "/" + arg.Substring (1);
1512 if (CSCParseOption (csc_opt, ref args, ref i))
1515 Error_WrongOption (arg);
1518 if (arg [0] == '/'){
1519 if (CSCParseOption (arg, ref args, ref i))
1522 // Need to skip `/home/test.cs' however /test.cs is considered as error
1523 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1524 Error_WrongOption (arg);
1531 CompileFiles (arg, false);
1540 // This will point to the NamespaceEntry of the last file that was parsed, and may
1541 // not be meaningful when resolving classes from other files. So, reset it to prevent
1544 RootContext.Tree.Types.NamespaceEntry = null;
1547 // If we are an exe, require a source file for the entry point
1549 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1550 if (first_source == null){
1551 Report.Error (2008, "No files to compile were specified");
1558 // If there is nothing to put in the assembly, and we are not a library
1560 if (first_source == null && embedded_resources == null){
1561 Report.Error (2008, "No files to compile were specified");
1565 if (Report.Errors > 0)
1572 // Load Core Library for default compilation
1574 if (RootContext.StdLib)
1575 references.Insert (0, "mscorlib");
1577 if (load_default_config)
1578 DefineDefaultConfig ();
1580 if (Report.Errors > 0){
1585 // Load assemblies required
1588 ShowTime ("Loading references");
1589 link_paths.Add (GetSystemDir ());
1590 link_paths.Add (Directory.GetCurrentDirectory ());
1594 ShowTime (" References loaded");
1596 if (Report.Errors > 0){
1603 if (output_file == null){
1604 if (first_source == null){
1605 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1609 int pos = first_source.LastIndexOf ('.');
1612 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1614 output_file = first_source + RootContext.TargetExt;
1617 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1620 if (RootContext.Target == Target.Module) {
1621 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1622 if (module_only == null) {
1623 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1624 Environment.Exit (1);
1627 MethodInfo set_method = module_only.GetSetMethod (true);
1628 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1631 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1633 if (modules.Count > 0) {
1634 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1635 if (adder_method == null) {
1636 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1637 Environment.Exit (1);
1640 foreach (string module in modules)
1641 LoadModule (adder_method, module);
1645 // Before emitting, we need to get the core
1646 // types emitted from the user defined types
1647 // or from the system ones.
1650 ShowTime ("Initializing Core Types");
1651 if (!RootContext.StdLib){
1652 RootContext.ResolveCore ();
1653 if (Report.Errors > 0)
1657 TypeManager.InitCoreTypes ();
1659 ShowTime (" Core Types done");
1661 CodeGen.Module.ResolveAttributes ();
1664 // The second pass of the compiler
1667 ShowTime ("Resolving tree");
1668 RootContext.ResolveTree ();
1670 if (Report.Errors > 0)
1673 ShowTime ("Populate tree");
1674 if (!RootContext.StdLib)
1675 RootContext.BootCorlib_PopulateCoreTypes ();
1676 RootContext.PopulateTypes ();
1678 TypeManager.InitCodeHelpers ();
1680 RootContext.DefineTypes ();
1682 if (Report.Errors == 0 &&
1683 RootContext.Documentation != null &&
1684 !RootContext.Documentation.OutputDocComment (
1689 // Verify using aliases now
1691 NamespaceEntry.VerifyAllUsing ();
1693 if (Report.Errors > 0){
1697 CodeGen.Assembly.Resolve ();
1699 if (RootContext.VerifyClsCompliance) {
1700 if (CodeGen.Assembly.IsClsCompliant) {
1701 AttributeTester.VerifyModulesClsCompliance ();
1702 TypeManager.LoadAllImportedTypes ();
1705 if (Report.Errors > 0)
1709 // The code generator
1712 ShowTime ("Emitting code");
1713 ShowTotalTime ("Total so far");
1714 RootContext.EmitCode ();
1718 if (Report.Errors > 0){
1723 ShowTime ("Closing types");
1725 RootContext.CloseTypes ();
1727 PEFileKinds k = PEFileKinds.ConsoleApplication;
1729 switch (RootContext.Target) {
1730 case Target.Library:
1732 k = PEFileKinds.Dll; break;
1734 k = PEFileKinds.ConsoleApplication; break;
1736 k = PEFileKinds.WindowApplication; break;
1739 if (RootContext.NeedsEntryPoint) {
1740 MethodInfo ep = RootContext.EntryPoint;
1743 if (RootContext.MainClass != null) {
1744 DeclSpace main_cont = RootContext.Tree.Types.GetDefinition (RootContext.MainClass) as DeclSpace;
1745 if (main_cont == null) {
1746 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1750 if (!(main_cont is ClassOrStruct)) {
1751 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1755 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1759 if (Report.Errors == 0)
1760 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1765 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1766 } else if (RootContext.MainClass != null) {
1767 Report.Error (2017, "Cannot specify -main if building a module or library");
1770 if (embedded_resources != null){
1771 if (RootContext.Target == Target.Module) {
1772 Report.Error (1507, "Cannot link resource file when building a module");
1776 embedded_resources.Emit ();
1780 // Add Win32 resources
1783 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1785 if (win32ResourceFile != null) {
1787 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1789 catch (ArgumentException) {
1790 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1794 if (win32IconFile != null) {
1795 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1796 if (define_icon == null) {
1797 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1799 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1802 if (Report.Errors > 0)
1805 CodeGen.Save (output_file);
1807 ShowTime ("Saved output");
1808 ShowTotalTime ("Total");
1811 Timer.ShowTimers ();
1813 if (Report.ExpectedError != 0){
1814 if (Report.Errors == 0) {
1815 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1816 "No other errors reported.");
1818 Environment.Exit (2);
1820 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1821 "However, other errors were reported.");
1823 Environment.Exit (1);
1831 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1832 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1834 return (Report.Errors == 0);
1843 string FileName { get; }
1846 class EmbededResource : IResource
1848 static MethodInfo embed_res;
1850 static EmbededResource () {
1851 Type[] argst = new Type [] {
1852 typeof (string), typeof (string), typeof (ResourceAttributes)
1855 embed_res = typeof (AssemblyBuilder).GetMethod (
1856 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1857 null, CallingConventions.Any, argst, null);
1859 if (embed_res == null) {
1860 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1864 readonly object[] args;
1866 public EmbededResource (string name, string file, bool isPrivate)
1868 args = new object [3];
1871 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1876 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1879 public string FileName {
1881 return (string)args [1];
1886 class LinkedResource : IResource
1888 readonly string file;
1889 readonly string name;
1890 readonly ResourceAttributes attribute;
1892 public LinkedResource (string name, string file, bool isPrivate)
1896 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1901 CodeGen.Assembly.Builder.AddResourceFile (name, file, attribute);
1904 public string FileName {
1912 IDictionary embedded_resources = new HybridDictionary ();
1914 public void Add (bool embeded, string file, string name)
1916 Add (embeded, file, name, false);
1919 public void Add (bool embeded, string file, string name, bool isPrivate)
1921 if (embedded_resources.Contains (name)) {
1922 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1925 IResource r = embeded ?
1926 (IResource) new EmbededResource (name, file, isPrivate) :
1927 new LinkedResource (name, file, isPrivate);
1929 embedded_resources.Add (name, r);
1934 foreach (IResource r in embedded_resources.Values) {
1935 if (!File.Exists (r.FileName)) {
1936 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1946 // This is the only public entry point
1948 public class CompilerCallableEntryPoint : MarshalByRefObject {
1949 public static bool InvokeCompiler (string [] args, TextWriter error)
1951 Report.Stderr = error;
1953 return Driver.MainDriver (args) && Report.Errors == 0;
1956 Report.Stderr = Console.Error;
1961 public static int[] AllWarningNumbers {
1963 return Report.AllWarnings;
1967 static void Reset ()
1971 RootContext.Reset ();
1973 TypeManager.Reset ();
1974 TypeHandle.Reset ();
1975 RootNamespace.Reset ();
1976 NamespaceEntry.Reset ();
1979 AttributeTester.Reset ();