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)
288 RootContext.Version = LanguageVersion.Default;
290 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
292 bool ok = MainDriver (args);
294 if (ok && Report.Errors == 0) {
295 if (Report.Warnings > 0) {
296 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
299 Console.WriteLine ("Counter1: " + counter1);
300 Console.WriteLine ("Counter2: " + counter2);
306 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
307 Report.Errors, Report.Warnings);
312 static public void LoadAssembly (string assembly, bool soft)
314 LoadAssembly (assembly, null, soft);
317 static public void LoadAssembly (string assembly, string alias, bool soft)
320 string total_log = "";
323 char[] path_chars = { '/', '\\' };
325 if (assembly.IndexOfAny (path_chars) != -1) {
326 a = Assembly.LoadFrom (assembly);
328 string ass = assembly;
329 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
330 ass = assembly.Substring (0, assembly.Length - 4);
331 a = Assembly.Load (ass);
333 // Extern aliased refs require special handling
335 RootNamespace.Global.AddAssemblyReference (a);
337 RootNamespace.DefineRootNamespace (alias, a);
339 } catch (FileNotFoundException){
340 foreach (string dir in link_paths){
341 string full_path = Path.Combine (dir, assembly);
342 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
346 a = Assembly.LoadFrom (full_path);
348 RootNamespace.Global.AddAssemblyReference (a);
350 RootNamespace.DefineRootNamespace (alias, a);
352 } catch (FileNotFoundException ff) {
353 total_log += ff.FusionLog;
358 Report.Error (6, "Cannot find assembly file `{0}'", assembly);
359 Report.Stderr.WriteLine ("Log: \n" + total_log);
361 } catch (BadImageFormatException f) {
362 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
363 } catch (FileLoadException f){
364 Report.SymbolRelatedToPreviousError (Location.Null, f.FusionLog);
365 Report.Error(6, "Cannot load assembly file `{0}'", f.FileName);
366 } catch (ArgumentNullException){
367 Report.Error(6, "Cannot load assembly (null argument)");
371 static public void LoadModule (MethodInfo adder_method, string module)
374 string total_log = "";
378 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
380 catch (TargetInvocationException ex) {
381 throw ex.InnerException;
383 RootNamespace.Global.AddModuleReference (m);
386 catch (FileNotFoundException){
387 foreach (string dir in link_paths){
388 string full_path = Path.Combine (dir, module);
389 if (!module.EndsWith (".netmodule"))
390 full_path += ".netmodule";
394 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
396 catch (TargetInvocationException ex) {
397 throw ex.InnerException;
399 RootNamespace.Global.AddModuleReference (m);
401 } catch (FileNotFoundException ff) {
402 total_log += ff.FusionLog;
406 Report.Error (6, "Cannot find module `" + module + "'" );
407 Console.WriteLine ("Log: \n" + total_log);
408 } catch (BadImageFormatException f) {
409 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
410 } catch (FileLoadException f){
411 Report.Error(6, "Cannot load module " + f.FusionLog);
412 } catch (ArgumentNullException){
413 Report.Error(6, "Cannot load module (null argument)");
418 /// Loads all assemblies referenced on the command line
420 static public void LoadReferences ()
422 foreach (string r in references)
423 LoadAssembly (r, false);
425 foreach (string r in soft_references)
426 LoadAssembly (r, true);
428 foreach (DictionaryEntry entry in external_aliases)
429 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
434 static void SetupDefaultDefines ()
436 defines = new ArrayList ();
437 defines.Add ("__MonoCS__");
440 static string [] LoadArgs (string file)
443 ArrayList args = new ArrayList ();
446 f = new StreamReader (file);
451 StringBuilder sb = new StringBuilder ();
453 while ((line = f.ReadLine ()) != null){
456 for (int i = 0; i < t; i++){
459 if (c == '"' || c == '\''){
462 for (i++; i < t; i++){
469 } else if (c == ' '){
471 args.Add (sb.ToString ());
478 args.Add (sb.ToString ());
483 string [] ret_value = new string [args.Count];
484 args.CopyTo (ret_value, 0);
490 // Returns the directory where the system assemblies are installed
492 static string GetSystemDir ()
494 return Path.GetDirectoryName (typeof (object).Assembly.Location);
498 // Given a path specification, splits the path from the file/pattern
500 static void SplitPathAndPattern (string spec, out string path, out string pattern)
502 int p = spec.LastIndexOf ('/');
505 // Windows does not like /file.cs, switch that to:
510 pattern = spec.Substring (1);
512 path = spec.Substring (0, p);
513 pattern = spec.Substring (p + 1);
518 p = spec.LastIndexOf ('\\');
520 path = spec.Substring (0, p);
521 pattern = spec.Substring (p + 1);
529 static void ProcessFile (string f)
531 if (first_source == null)
534 Location.AddFile (f);
537 static void ProcessFiles ()
539 Location.Initialize ();
541 foreach (SourceFile file in Location.SourceFiles) {
543 tokenize_file (file);
550 static void CompileFiles (string spec, bool recurse)
552 string path, pattern;
554 SplitPathAndPattern (spec, out path, out pattern);
555 if (pattern.IndexOf ('*') == -1){
560 string [] files = null;
562 files = Directory.GetFiles (path, pattern);
563 } catch (System.IO.DirectoryNotFoundException) {
564 Report.Error (2001, "Source file `" + spec + "' could not be found");
566 } catch (System.IO.IOException){
567 Report.Error (2001, "Source file `" + spec + "' could not be found");
570 foreach (string f in files) {
577 string [] dirs = null;
580 dirs = Directory.GetDirectories (path);
584 foreach (string d in dirs) {
586 // Don't include path in this string, as each
587 // directory entry already does
588 CompileFiles (d + "/" + pattern, true);
592 static void DefineDefaultConfig ()
595 // For now the "default config" is harcoded into the compiler
596 // we can move this outside later
598 string [] default_config = {
603 // Is it worth pre-loading all this stuff?
606 "System.Configuration.Install",
609 "System.DirectoryServices",
610 "System.Drawing.Design",
612 "System.EnterpriseServices",
615 "System.Runtime.Remoting",
616 "System.Runtime.Serialization.Formatters.Soap",
618 "System.ServiceProcess",
620 "System.Web.RegularExpressions",
621 "System.Web.Services",
622 "System.Windows.Forms"
627 foreach (string def in default_config)
628 soft_references.Insert (p++, def);
631 public static string OutputFile
637 return Path.GetFileName (output_file);
641 static void SetWarningLevel (string s)
646 level = Int32.Parse (s);
649 if (level < 0 || level > 4){
650 Report.Error (1900, "Warning level must be in the range 0-4");
653 RootContext.WarningLevel = level;
656 static void SetupV2 ()
658 RootContext.Version = LanguageVersion.Default;
659 defines.Add ("__V2__");
662 static void Version ()
664 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
665 Console.WriteLine ("Mono C# compiler version {0}", version);
666 Environment.Exit (0);
670 // Currently handles the Unix-like command line options, but will be
671 // deprecated in favor of the CSCParseOption, which will also handle the
672 // options that start with a dash in the future.
674 static bool UnixParseOption (string arg, ref string [] args, ref int i)
678 CSharpParser.yacc_verbose_flag++;
689 case "--main": case "-m":
690 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
691 if ((i + 1) >= args.Length){
693 Environment.Exit (1);
695 RootContext.MainClass = args [++i];
699 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
700 RootContext.Unsafe = true;
703 case "/?": case "/h": case "/help":
706 Environment.Exit (0);
710 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
711 if ((i + 1) >= args.Length){
713 Environment.Exit (1);
715 defines.Add (args [++i]);
718 case "--show-counters":
719 show_counters = true;
722 case "--expect-error": {
727 args [++i], NumberStyles.AllowLeadingSign);
728 Report.ExpectedError = code;
730 Report.Error (-14, "Invalid number specified");
741 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
742 if ((i + 1) >= args.Length){
744 Environment.Exit (1);
746 OutputFile = args [++i];
750 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
751 RootContext.Checked = true;
755 Report.Stacktrace = true;
758 case "--linkresource":
760 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
761 if ((i + 1) >= args.Length){
763 Report.Error (5, "Missing argument to --linkres");
764 Environment.Exit (1);
766 if (embedded_resources == null)
767 embedded_resources = new Resources ();
769 embedded_resources.Add (false, args [++i], args [i]);
774 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
775 if ((i + 1) >= args.Length){
777 Report.Error (5, "Missing argument to --resource");
778 Environment.Exit (1);
780 if (embedded_resources == null)
781 embedded_resources = new Resources ();
783 embedded_resources.Add (true, args [++i], args [i]);
787 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
788 if ((i + 1) >= args.Length){
789 Environment.Exit (1);
793 string type = args [++i];
796 RootContext.Target = Target.Library;
797 RootContext.TargetExt = ".dll";
801 RootContext.Target = Target.Exe;
805 RootContext.Target = Target.WinExe;
809 RootContext.Target = Target.Module;
810 RootContext.TargetExt = ".dll";
819 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
820 if ((i + 1) >= args.Length){
822 Environment.Exit (1);
825 string val = args [++i];
826 int idx = val.IndexOf ('=');
828 string alias = val.Substring (0, idx);
829 string assembly = val.Substring (idx + 1);
830 AddExternAlias (alias, assembly);
834 references.Add (val);
838 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
839 if ((i + 1) >= args.Length){
841 Environment.Exit (1);
843 link_paths.Add (args [++i]);
847 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
848 RootContext.StdLib = false;
856 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
857 Report.WarningsAreErrors = true;
861 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
862 if ((i + 1) >= args.Length){
864 Environment.Exit (1);
869 warn = Int32.Parse (args [++i]);
872 Environment.Exit (1);
874 Report.SetIgnoreWarning (warn);
878 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
879 if ((i + 1) >= args.Length){
882 "--wlevel requires a value from 0 to 4");
883 Environment.Exit (1);
886 SetWarningLevel (args [++i]);
890 if ((i + 1) >= args.Length){
891 Report.Error (5, "--mcs-debug requires an argument");
892 Environment.Exit (1);
896 Report.DebugFlags = Int32.Parse (args [++i]);
898 Report.Error (5, "Invalid argument to --mcs-debug");
899 Environment.Exit (1);
908 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
909 if ((i + 1) >= args.Length){
910 Report.Error (5, "--recurse requires an argument");
911 Environment.Exit (1);
913 CompileFiles (args [++i], true);
918 last_time = first_time = DateTime.Now;
925 case "--debug": case "-g":
926 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
927 want_debugging_support = true;
931 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
932 load_default_config = false;
940 // This parses the -arg and /arg options to the compiler, even if the strings
941 // in the following text use "/arg" on the strings.
943 static bool CSCParseOption (string option, ref string [] args, ref int i)
945 int idx = option.IndexOf (':');
952 arg = option.Substring (0, idx);
954 value = option.Substring (idx + 1);
965 RootContext.Target = Target.Exe;
969 RootContext.Target = Target.WinExe;
973 RootContext.Target = Target.Library;
974 RootContext.TargetExt = ".dll";
978 RootContext.Target = Target.Module;
979 RootContext.TargetExt = ".netmodule";
989 if (value.Length == 0){
991 Environment.Exit (1);
998 RootContext.Optimize = true;
1002 RootContext.Optimize = false;
1005 case "/incremental":
1006 case "/incremental+":
1007 case "/incremental-":
1015 if (value.Length == 0){
1017 Environment.Exit (1);
1020 defs = value.Split (new Char [] {';', ','});
1021 foreach (string d in defs){
1029 // We should collect data, runtime, etc and store in the file specified
1031 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1037 if (value.Length == 0){
1039 Environment.Exit (1);
1041 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1043 ProcessStartInfo pi = new ProcessStartInfo ();
1044 pi.FileName = "pkg-config";
1045 pi.RedirectStandardOutput = true;
1046 pi.UseShellExecute = false;
1047 pi.Arguments = "--libs " + packages;
1050 p = Process.Start (pi);
1051 } catch (Exception e) {
1052 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1053 Environment.Exit (1);
1056 if (p.StandardOutput == null){
1057 Report.Warning (-27, 1, "Specified package did not return any information");
1060 string pkgout = p.StandardOutput.ReadToEnd ();
1062 if (p.ExitCode != 0) {
1063 Report.Error (-27, "Error running pkg-config. Check the above output.");
1064 Environment.Exit (1);
1067 if (pkgout != null){
1068 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1069 Split (new Char [] { ' ', '\t'});
1070 args = AddArgs (args, xargs);
1078 case "/linkresource":
1081 if (embedded_resources == null)
1082 embedded_resources = new Resources ();
1084 bool embeded = arg.StartsWith ("/r");
1085 string[] s = value.Split (',');
1088 if (s[0].Length == 0)
1090 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1093 embedded_resources.Add (embeded, s [0], s [1]);
1096 if (s [2] != "public" && s [2] != "private") {
1097 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1100 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1103 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1110 if (value.Length == 0){
1111 Report.Error (5, "-recurse requires an argument");
1112 Environment.Exit (1);
1114 CompileFiles (value, true);
1118 case "/reference": {
1119 if (value.Length == 0){
1120 Report.Error (5, "-reference requires an argument");
1121 Environment.Exit (1);
1124 string [] refs = value.Split (new char [] { ';', ',' });
1125 foreach (string r in refs){
1127 int index = val.IndexOf ("=");
1129 string alias = r.Substring (0, index);
1130 string assembly = r.Substring (index + 1);
1131 AddExternAlias (alias, assembly);
1135 references.Add (val);
1139 case "/addmodule": {
1140 if (value.Length == 0){
1141 Report.Error (5, arg + " requires an argument");
1142 Environment.Exit (1);
1145 string [] refs = value.Split (new char [] { ';', ',' });
1146 foreach (string r in refs){
1152 if (value.Length == 0) {
1153 Report.Error (5, arg + " requires an argument");
1154 Environment.Exit (1);
1157 win32ResourceFile = value;
1160 case "/win32icon": {
1161 if (value.Length == 0) {
1162 Report.Error (5, arg + " requires an argument");
1163 Environment.Exit (1);
1166 win32IconFile = value;
1170 if (value.Length == 0){
1171 Report.Error (2006, arg + " requires an argument");
1172 Environment.Exit (1);
1174 RootContext.Documentation = new Documentation (value);
1180 if (value.Length == 0){
1181 Report.Error (5, "/lib requires an argument");
1182 Environment.Exit (1);
1185 libdirs = value.Split (new Char [] { ',' });
1186 foreach (string dir in libdirs)
1187 link_paths.Add (dir);
1192 want_debugging_support = false;
1197 want_debugging_support = true;
1202 RootContext.Checked = true;
1206 RootContext.Checked = false;
1214 RootContext.VerifyClsCompliance = false;
1219 RootContext.Unsafe = true;
1223 RootContext.Unsafe = false;
1226 case "/warnaserror":
1227 case "/warnaserror+":
1228 Report.WarningsAreErrors = true;
1231 case "/warnaserror-":
1232 Report.WarningsAreErrors = false;
1236 SetWarningLevel (value);
1242 if (value.Length == 0){
1243 Report.Error (5, "/nowarn requires an argument");
1244 Environment.Exit (1);
1247 warns = value.Split (new Char [] {','});
1248 foreach (string wc in warns){
1250 int warn = Int32.Parse (wc);
1252 throw new ArgumentOutOfRangeException("warn");
1254 Report.SetIgnoreWarning (warn);
1256 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1263 load_default_config = true;
1268 load_default_config = false;
1273 Environment.Exit(0);
1279 Environment.Exit (0);
1284 if (value.Length == 0){
1285 Report.Error (5, arg + " requires an argument");
1286 Environment.Exit (1);
1288 RootContext.MainClass = value;
1293 RootContext.StdLib = false;
1297 RootContext.StdLib = true;
1304 if (value == String.Empty) {
1305 Report.Error (5, arg + " requires an argument");
1306 Environment.Exit (1);
1308 RootContext.StrongNameKeyFile = value;
1310 case "/keycontainer":
1311 if (value == String.Empty) {
1312 Report.Error (5, arg + " requires an argument");
1313 Environment.Exit (1);
1315 RootContext.StrongNameKeyContainer = value;
1318 RootContext.StrongNameDelaySign = true;
1321 RootContext.StrongNameDelaySign = false;
1326 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1330 case "/langversion":
1331 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1333 RootContext.Version = LanguageVersion.ISO_1;
1340 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1346 encoding = new UTF8Encoding();
1349 encoding = Encoding.Default;
1353 encoding = Encoding.GetEncoding (
1354 Int32.Parse (value));
1356 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1366 static void Error_WrongOption (string option)
1368 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1371 static string [] AddArgs (string [] args, string [] extra_args)
1374 new_args = new string [extra_args.Length + args.Length];
1376 // if args contains '--' we have to take that into account
1377 // split args into first half and second half based on '--'
1378 // and add the extra_args before --
1379 int split_position = Array.IndexOf (args, "--");
1380 if (split_position != -1)
1382 Array.Copy (args, new_args, split_position);
1383 extra_args.CopyTo (new_args, split_position);
1384 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1388 args.CopyTo (new_args, 0);
1389 extra_args.CopyTo (new_args, args.Length);
1395 static void AddExternAlias (string identifier, string assembly)
1397 if (assembly.Length == 0) {
1398 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1402 if (!IsExternAliasValid (identifier)) {
1403 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1407 // Could here hashtable throw an exception?
1408 external_aliases [identifier] = assembly;
1411 static bool IsExternAliasValid (string identifier)
1413 if (identifier.Length == 0)
1415 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1418 for (int i = 1; i < identifier.Length; i++) {
1419 char c = identifier [i];
1420 if (Char.IsLetter (c) || Char.IsDigit (c))
1423 UnicodeCategory category = Char.GetUnicodeCategory (c);
1424 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1425 category != UnicodeCategory.SpacingCombiningMark ||
1426 category != UnicodeCategory.ConnectorPunctuation)
1434 /// Parses the arguments, and drives the compilation
1439 /// TODO: Mostly structured to debug the compiler
1440 /// now, needs to be turned into a real driver soon.
1442 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1443 internal static bool MainDriver (string [] args)
1446 bool parsing_options = true;
1448 encoding = Encoding.Default;
1450 references = new ArrayList ();
1451 external_aliases = new Hashtable ();
1452 soft_references = new ArrayList ();
1453 modules = new ArrayList ();
1454 link_paths = new ArrayList ();
1456 SetupDefaultDefines ();
1461 // This is not required because Assembly.Load knows about this
1465 Hashtable response_file_list = null;
1467 for (i = 0; i < args.Length; i++){
1468 string arg = args [i];
1469 if (arg.Length == 0)
1472 if (arg.StartsWith ("@")){
1473 string [] extra_args;
1474 string response_file = arg.Substring (1);
1476 if (response_file_list == null)
1477 response_file_list = new Hashtable ();
1479 if (response_file_list.Contains (response_file)){
1481 1515, "Response file `" + response_file +
1482 "' specified multiple times");
1483 Environment.Exit (1);
1486 response_file_list.Add (response_file, response_file);
1488 extra_args = LoadArgs (response_file);
1489 if (extra_args == null){
1490 Report.Error (2011, "Unable to open response file: " +
1495 args = AddArgs (args, extra_args);
1499 if (parsing_options){
1501 parsing_options = false;
1505 if (arg.StartsWith ("-")){
1506 if (UnixParseOption (arg, ref args, ref i))
1510 string csc_opt = "/" + arg.Substring (1);
1511 if (CSCParseOption (csc_opt, ref args, ref i))
1514 Error_WrongOption (arg);
1517 if (arg [0] == '/'){
1518 if (CSCParseOption (arg, ref args, ref i))
1521 // Need to skip `/home/test.cs' however /test.cs is considered as error
1522 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1523 Error_WrongOption (arg);
1530 CompileFiles (arg, false);
1538 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1539 throw new InternalErrorException ("who set it?");
1542 // If we are an exe, require a source file for the entry point
1544 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1545 if (first_source == null){
1546 Report.Error (2008, "No files to compile were specified");
1553 // If there is nothing to put in the assembly, and we are not a library
1555 if (first_source == null && embedded_resources == null){
1556 Report.Error (2008, "No files to compile were specified");
1560 if (Report.Errors > 0)
1567 // Load Core Library for default compilation
1569 if (RootContext.StdLib)
1570 references.Insert (0, "mscorlib");
1572 if (load_default_config)
1573 DefineDefaultConfig ();
1575 if (Report.Errors > 0){
1580 // Load assemblies required
1583 ShowTime ("Loading references");
1584 link_paths.Add (GetSystemDir ());
1585 link_paths.Add (Directory.GetCurrentDirectory ());
1589 ShowTime (" References loaded");
1591 if (Report.Errors > 0){
1598 if (output_file == null){
1599 if (first_source == null){
1600 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1604 int pos = first_source.LastIndexOf ('.');
1607 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1609 output_file = first_source + RootContext.TargetExt;
1612 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1615 if (RootContext.Target == Target.Module) {
1616 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1617 if (module_only == null) {
1618 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1619 Environment.Exit (1);
1622 MethodInfo set_method = module_only.GetSetMethod (true);
1623 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1626 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1628 if (modules.Count > 0) {
1629 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1630 if (adder_method == null) {
1631 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1632 Environment.Exit (1);
1635 foreach (string module in modules)
1636 LoadModule (adder_method, module);
1640 // Before emitting, we need to get the core
1641 // types emitted from the user defined types
1642 // or from the system ones.
1645 ShowTime ("Initializing Core Types");
1646 if (!RootContext.StdLib){
1647 RootContext.ResolveCore ();
1648 if (Report.Errors > 0)
1652 TypeManager.InitCoreTypes ();
1654 ShowTime (" Core Types done");
1656 CodeGen.Module.Resolve ();
1659 // The second pass of the compiler
1662 ShowTime ("Resolving tree");
1663 RootContext.ResolveTree ();
1665 if (Report.Errors > 0)
1668 ShowTime ("Populate tree");
1669 if (!RootContext.StdLib)
1670 RootContext.BootCorlib_PopulateCoreTypes ();
1671 RootContext.PopulateTypes ();
1673 TypeManager.InitCodeHelpers ();
1675 RootContext.DefineTypes ();
1677 if (Report.Errors == 0 &&
1678 RootContext.Documentation != null &&
1679 !RootContext.Documentation.OutputDocComment (
1684 // Verify using aliases now
1686 NamespaceEntry.VerifyAllUsing ();
1688 if (Report.Errors > 0){
1692 CodeGen.Assembly.Resolve ();
1694 if (RootContext.VerifyClsCompliance) {
1695 if (CodeGen.Assembly.IsClsCompliant) {
1696 AttributeTester.VerifyModulesClsCompliance ();
1697 TypeManager.LoadAllImportedTypes ();
1700 if (Report.Errors > 0)
1704 // The code generator
1707 ShowTime ("Emitting code");
1708 ShowTotalTime ("Total so far");
1709 RootContext.EmitCode ();
1713 if (Report.Errors > 0){
1718 ShowTime ("Closing types");
1720 RootContext.CloseTypes ();
1722 PEFileKinds k = PEFileKinds.ConsoleApplication;
1724 switch (RootContext.Target) {
1725 case Target.Library:
1727 k = PEFileKinds.Dll; break;
1729 k = PEFileKinds.ConsoleApplication; break;
1731 k = PEFileKinds.WindowApplication; break;
1734 if (RootContext.NeedsEntryPoint) {
1735 MethodInfo ep = RootContext.EntryPoint;
1738 if (RootContext.MainClass != null) {
1739 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1740 if (main_cont == null) {
1741 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1745 if (!(main_cont is ClassOrStruct)) {
1746 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1750 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1754 if (Report.Errors == 0)
1755 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1760 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1761 } else if (RootContext.MainClass != null) {
1762 Report.Error (2017, "Cannot specify -main if building a module or library");
1765 if (embedded_resources != null){
1766 if (RootContext.Target == Target.Module) {
1767 Report.Error (1507, "Cannot link resource file when building a module");
1771 embedded_resources.Emit ();
1775 // Add Win32 resources
1778 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1780 if (win32ResourceFile != null) {
1782 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1784 catch (ArgumentException) {
1785 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1789 if (win32IconFile != null) {
1790 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1791 if (define_icon == null) {
1792 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1794 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1797 if (Report.Errors > 0)
1800 CodeGen.Save (output_file);
1802 ShowTime ("Saved output");
1803 ShowTotalTime ("Total");
1806 Timer.ShowTimers ();
1808 if (Report.ExpectedError != 0) {
1809 if (Report.Errors == 0) {
1810 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1811 "No other errors reported.");
1813 Environment.Exit (2);
1815 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1816 "However, other errors were reported.");
1818 Environment.Exit (1);
1826 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1827 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1829 return (Report.Errors == 0);
1838 string FileName { get; }
1841 class EmbededResource : IResource
1843 static MethodInfo embed_res;
1845 static EmbededResource () {
1846 Type[] argst = new Type [] {
1847 typeof (string), typeof (string), typeof (ResourceAttributes)
1850 embed_res = typeof (AssemblyBuilder).GetMethod (
1851 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1852 null, CallingConventions.Any, argst, null);
1854 if (embed_res == null) {
1855 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1859 readonly object[] args;
1861 public EmbededResource (string name, string file, bool isPrivate)
1863 args = new object [3];
1866 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1871 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1874 public string FileName {
1876 return (string)args [1];
1881 class LinkedResource : IResource
1883 readonly string file;
1884 readonly string name;
1885 readonly ResourceAttributes attribute;
1887 public LinkedResource (string name, string file, bool isPrivate)
1891 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1896 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1899 public string FileName {
1907 IDictionary embedded_resources = new HybridDictionary ();
1909 public void Add (bool embeded, string file, string name)
1911 Add (embeded, file, name, false);
1914 public void Add (bool embeded, string file, string name, bool isPrivate)
1916 if (embedded_resources.Contains (name)) {
1917 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1920 IResource r = embeded ?
1921 (IResource) new EmbededResource (name, file, isPrivate) :
1922 new LinkedResource (name, file, isPrivate);
1924 embedded_resources.Add (name, r);
1929 foreach (IResource r in embedded_resources.Values) {
1930 if (!File.Exists (r.FileName)) {
1931 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1941 // This is the only public entry point
1943 public class CompilerCallableEntryPoint : MarshalByRefObject {
1944 public static bool InvokeCompiler (string [] args, TextWriter error)
1946 Report.Stderr = error;
1948 return Driver.MainDriver (args) && Report.Errors == 0;
1951 Report.Stderr = Console.Error;
1956 public static int[] AllWarningNumbers {
1958 return Report.AllWarnings;
1962 static void Reset ()
1966 RootContext.Reset ();
1968 TypeManager.Reset ();
1969 TypeHandle.Reset ();
1970 RootNamespace.Reset ();
1971 NamespaceEntry.Reset ();
1974 AttributeTester.Reset ();