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;
104 static public void Reset ()
106 want_debugging_support = false;
110 show_counters = false;
111 load_default_config = true;
112 embedded_resources = null;
113 win32ResourceFile = win32IconFile = null;
120 public static void ShowTime (string msg)
125 DateTime now = DateTime.Now;
126 TimeSpan span = now - last_time;
130 "[{0:00}:{1:000}] {2}",
131 (int) span.TotalSeconds, span.Milliseconds, msg);
134 public static void ShowTotalTime (string msg)
139 DateTime now = DateTime.Now;
140 TimeSpan span = now - first_time;
144 "[{0:00}:{1:000}] {2}",
145 (int) span.TotalSeconds, span.Milliseconds, msg);
148 static void tokenize_file (SourceFile file)
153 input = File.OpenRead (file.Name);
155 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
160 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
161 Tokenizer lexer = new Tokenizer (reader, file, defines);
162 int token, tokens = 0, errors = 0;
164 while ((token = lexer.token ()) != Token.EOF){
166 if (token == Token.ERROR)
169 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
175 // MonoTODO("Change error code for aborted compilation to something reasonable")]
176 static void parse (SourceFile file)
182 input = File.OpenRead (file.Name);
184 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
188 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
191 if (reader.Read () == 77 && reader.Read () == 90) {
192 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
198 parser = new CSharpParser (reader, file, defines);
199 parser.ErrorOutput = Report.Stderr;
202 } catch (Exception ex) {
203 Report.Error(666, "Compilation aborted: " + ex);
209 static void OtherFlags ()
212 "Other flags in the compiler\n" +
213 " --fatal Makes errors fatal\n" +
214 " --parse Only parses the source file\n" +
215 " --stacktrace Shows stack trace at error location\n" +
216 " --timestamp Displays time stamps of various compiler events\n" +
217 " --expect-error X Expect that error X will be encountered\n" +
218 " -2 Enables experimental C# features\n" +
219 " -v Verbose parsing (for debugging the parser)\n" +
220 " --mcs-debug X Sets MCS debugging level to X\n");
226 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
227 "mcs [options] source-files\n" +
228 " --about About the Mono C# compiler\n" +
229 " -addmodule:MODULE Adds the module to the generated assembly\n" +
230 " -checked[+|-] Set default context to checked\n" +
231 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
232 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
233 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
234 " -debug[+|-], -g Generate debugging information\n" +
235 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
236 " -doc:FILE XML Documentation file to generate\n" +
237 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
238 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
239 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
240 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
241 " -main:class Specified the class that contains the entry point\n" +
242 " -noconfig[+|-] Disables implicit references to assemblies\n" +
243 " -nostdlib[+|-] Does not load core libraries\n" +
244 " -nowarn:W1[,W2] Disables one or more warnings\n" +
245 " -optimize[+|-] Enables code optimalizations\n" +
246 " -out:FNAME Specifies output file\n" +
247 " -pkg:P1[,Pn] References packages P1..Pn\n" +
248 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
249 " -reference:ASS References the specified assembly (-r:ASS)\n" +
250 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
251 " library, module), (short: /t:)\n" +
252 " -unsafe[+|-] Allows unsafe code\n" +
253 " -warnaserror[+|-] Treat warnings as errors\n" +
254 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
255 " -help2 Show other help flags\n" +
258 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
259 " -resource:FILE[,ID] Embed FILE as a resource\n" +
260 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
261 " -win32icon:FILE Use this icon for the output\n" +
262 " @file Read response file for more options\n\n" +
263 "Options can be of the form -option or /option");
266 static void TargetUsage ()
268 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
274 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
275 "The compiler source code is released under the terms of the GNU GPL\n\n" +
277 "For more information on Mono, visit the project Web site\n" +
278 " http://www.go-mono.com\n\n" +
280 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
281 Environment.Exit (0);
284 public static int counter1, counter2;
286 public static int Main (string[] args)
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;
858 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
859 if ((i + 1) >= args.Length){
861 Environment.Exit (1);
866 warn = Int32.Parse (args [++i]);
869 Environment.Exit (1);
871 Report.SetIgnoreWarning (warn);
875 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
876 if ((i + 1) >= args.Length){
879 "--wlevel requires a value from 0 to 4");
880 Environment.Exit (1);
883 SetWarningLevel (args [++i]);
887 if ((i + 1) >= args.Length){
888 Report.Error (5, "--mcs-debug requires an argument");
889 Environment.Exit (1);
893 Report.DebugFlags = Int32.Parse (args [++i]);
895 Report.Error (5, "Invalid argument to --mcs-debug");
896 Environment.Exit (1);
905 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
906 if ((i + 1) >= args.Length){
907 Report.Error (5, "--recurse requires an argument");
908 Environment.Exit (1);
910 CompileFiles (args [++i], true);
915 last_time = first_time = DateTime.Now;
922 case "--debug": case "-g":
923 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
924 want_debugging_support = true;
928 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
929 load_default_config = false;
937 // This parses the -arg and /arg options to the compiler, even if the strings
938 // in the following text use "/arg" on the strings.
940 static bool CSCParseOption (string option, ref string [] args, ref int i)
942 int idx = option.IndexOf (':');
949 arg = option.Substring (0, idx);
951 value = option.Substring (idx + 1);
962 RootContext.Target = Target.Exe;
966 RootContext.Target = Target.WinExe;
970 RootContext.Target = Target.Library;
971 RootContext.TargetExt = ".dll";
975 RootContext.Target = Target.Module;
976 RootContext.TargetExt = ".netmodule";
986 if (value.Length == 0){
988 Environment.Exit (1);
995 RootContext.Optimize = true;
999 RootContext.Optimize = false;
1002 case "/incremental":
1003 case "/incremental+":
1004 case "/incremental-":
1012 if (value.Length == 0){
1014 Environment.Exit (1);
1017 defs = value.Split (new Char [] {';', ','});
1018 foreach (string d in defs){
1026 // We should collect data, runtime, etc and store in the file specified
1028 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1034 if (value.Length == 0){
1036 Environment.Exit (1);
1038 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1040 ProcessStartInfo pi = new ProcessStartInfo ();
1041 pi.FileName = "pkg-config";
1042 pi.RedirectStandardOutput = true;
1043 pi.UseShellExecute = false;
1044 pi.Arguments = "--libs " + packages;
1047 p = Process.Start (pi);
1048 } catch (Exception e) {
1049 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1050 Environment.Exit (1);
1053 if (p.StandardOutput == null){
1054 Report.Warning (-27, 1, "Specified package did not return any information");
1057 string pkgout = p.StandardOutput.ReadToEnd ();
1059 if (p.ExitCode != 0) {
1060 Report.Error (-27, "Error running pkg-config. Check the above output.");
1061 Environment.Exit (1);
1064 if (pkgout != null){
1065 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1066 Split (new Char [] { ' ', '\t'});
1067 args = AddArgs (args, xargs);
1075 case "/linkresource":
1078 if (embedded_resources == null)
1079 embedded_resources = new Resources ();
1081 bool embeded = arg.StartsWith ("/r");
1082 string[] s = value.Split (',');
1085 if (s[0].Length == 0)
1087 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1090 embedded_resources.Add (embeded, s [0], s [1]);
1093 if (s [2] != "public" && s [2] != "private") {
1094 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1097 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1100 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1107 if (value.Length == 0){
1108 Report.Error (5, "-recurse requires an argument");
1109 Environment.Exit (1);
1111 CompileFiles (value, true);
1115 case "/reference": {
1116 if (value.Length == 0){
1117 Report.Error (5, "-reference requires an argument");
1118 Environment.Exit (1);
1121 string [] refs = value.Split (new char [] { ';', ',' });
1122 foreach (string r in refs){
1124 int index = val.IndexOf ("=");
1126 string alias = r.Substring (0, index);
1127 string assembly = r.Substring (index + 1);
1128 AddExternAlias (alias, assembly);
1132 references.Add (val);
1136 case "/addmodule": {
1137 if (value.Length == 0){
1138 Report.Error (5, arg + " requires an argument");
1139 Environment.Exit (1);
1142 string [] refs = value.Split (new char [] { ';', ',' });
1143 foreach (string r in refs){
1149 if (value.Length == 0) {
1150 Report.Error (5, arg + " requires an argument");
1151 Environment.Exit (1);
1154 win32ResourceFile = value;
1157 case "/win32icon": {
1158 if (value.Length == 0) {
1159 Report.Error (5, arg + " requires an argument");
1160 Environment.Exit (1);
1163 win32IconFile = value;
1167 if (value.Length == 0){
1168 Report.Error (2006, arg + " requires an argument");
1169 Environment.Exit (1);
1171 RootContext.Documentation = new Documentation (value);
1177 if (value.Length == 0){
1178 Report.Error (5, "/lib requires an argument");
1179 Environment.Exit (1);
1182 libdirs = value.Split (new Char [] { ',' });
1183 foreach (string dir in libdirs)
1184 link_paths.Add (dir);
1189 want_debugging_support = false;
1194 want_debugging_support = true;
1199 RootContext.Checked = true;
1203 RootContext.Checked = false;
1211 RootContext.VerifyClsCompliance = false;
1216 RootContext.Unsafe = true;
1220 RootContext.Unsafe = false;
1223 case "/warnaserror":
1224 case "/warnaserror+":
1225 Report.WarningsAreErrors = true;
1228 case "/warnaserror-":
1229 Report.WarningsAreErrors = false;
1233 SetWarningLevel (value);
1239 if (value.Length == 0){
1240 Report.Error (5, "/nowarn requires an argument");
1241 Environment.Exit (1);
1244 warns = value.Split (new Char [] {','});
1245 foreach (string wc in warns){
1247 int warn = Int32.Parse (wc);
1249 throw new ArgumentOutOfRangeException("warn");
1251 Report.SetIgnoreWarning (warn);
1253 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1260 load_default_config = true;
1265 load_default_config = false;
1270 Environment.Exit(0);
1276 Environment.Exit (0);
1281 if (value.Length == 0){
1282 Report.Error (5, arg + " requires an argument");
1283 Environment.Exit (1);
1285 RootContext.MainClass = value;
1290 RootContext.StdLib = false;
1294 RootContext.StdLib = true;
1301 if (value == String.Empty) {
1302 Report.Error (5, arg + " requires an argument");
1303 Environment.Exit (1);
1305 RootContext.StrongNameKeyFile = value;
1307 case "/keycontainer":
1308 if (value == String.Empty) {
1309 Report.Error (5, arg + " requires an argument");
1310 Environment.Exit (1);
1312 RootContext.StrongNameKeyContainer = value;
1315 RootContext.StrongNameDelaySign = true;
1318 RootContext.StrongNameDelaySign = false;
1323 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1327 case "/langversion":
1328 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1330 RootContext.Version = LanguageVersion.ISO_1;
1337 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1343 encoding = new UTF8Encoding();
1346 encoding = Encoding.Default;
1350 encoding = Encoding.GetEncoding (
1351 Int32.Parse (value));
1353 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1363 static void Error_WrongOption (string option)
1365 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1368 static string [] AddArgs (string [] args, string [] extra_args)
1371 new_args = new string [extra_args.Length + args.Length];
1373 // if args contains '--' we have to take that into account
1374 // split args into first half and second half based on '--'
1375 // and add the extra_args before --
1376 int split_position = Array.IndexOf (args, "--");
1377 if (split_position != -1)
1379 Array.Copy (args, new_args, split_position);
1380 extra_args.CopyTo (new_args, split_position);
1381 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1385 args.CopyTo (new_args, 0);
1386 extra_args.CopyTo (new_args, args.Length);
1392 static void AddExternAlias (string identifier, string assembly)
1394 if (assembly.Length == 0) {
1395 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1399 if (!IsExternAliasValid (identifier)) {
1400 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1404 // Could here hashtable throw an exception?
1405 external_aliases [identifier] = assembly;
1408 static bool IsExternAliasValid (string identifier)
1410 if (identifier.Length == 0)
1412 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1415 for (int i = 1; i < identifier.Length; i++) {
1416 char c = identifier [i];
1417 if (Char.IsLetter (c) || Char.IsDigit (c))
1420 UnicodeCategory category = Char.GetUnicodeCategory (c);
1421 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1422 category != UnicodeCategory.SpacingCombiningMark ||
1423 category != UnicodeCategory.ConnectorPunctuation)
1431 /// Parses the arguments, and drives the compilation
1436 /// TODO: Mostly structured to debug the compiler
1437 /// now, needs to be turned into a real driver soon.
1439 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1440 internal static bool MainDriver (string [] args)
1443 bool parsing_options = true;
1445 encoding = Encoding.Default;
1447 references = new ArrayList ();
1448 external_aliases = new Hashtable ();
1449 soft_references = new ArrayList ();
1450 modules = new ArrayList ();
1451 link_paths = new ArrayList ();
1453 SetupDefaultDefines ();
1458 // This is not required because Assembly.Load knows about this
1462 Hashtable response_file_list = null;
1464 for (i = 0; i < args.Length; i++){
1465 string arg = args [i];
1466 if (arg.Length == 0)
1469 if (arg.StartsWith ("@")){
1470 string [] extra_args;
1471 string response_file = arg.Substring (1);
1473 if (response_file_list == null)
1474 response_file_list = new Hashtable ();
1476 if (response_file_list.Contains (response_file)){
1478 1515, "Response file `" + response_file +
1479 "' specified multiple times");
1480 Environment.Exit (1);
1483 response_file_list.Add (response_file, response_file);
1485 extra_args = LoadArgs (response_file);
1486 if (extra_args == null){
1487 Report.Error (2011, "Unable to open response file: " +
1492 args = AddArgs (args, extra_args);
1496 if (parsing_options){
1498 parsing_options = false;
1502 if (arg.StartsWith ("-")){
1503 if (UnixParseOption (arg, ref args, ref i))
1507 string csc_opt = "/" + arg.Substring (1);
1508 if (CSCParseOption (csc_opt, ref args, ref i))
1511 Error_WrongOption (arg);
1514 if (arg [0] == '/'){
1515 if (CSCParseOption (arg, ref args, ref i))
1518 // Need to skip `/home/test.cs' however /test.cs is considered as error
1519 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1520 Error_WrongOption (arg);
1527 CompileFiles (arg, false);
1536 // This will point to the NamespaceEntry of the last file that was parsed, and may
1537 // not be meaningful when resolving classes from other files. So, reset it to prevent
1540 RootContext.Tree.Types.NamespaceEntry = null;
1543 // If we are an exe, require a source file for the entry point
1545 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1546 if (first_source == null){
1547 Report.Error (2008, "No files to compile were specified");
1554 // If there is nothing to put in the assembly, and we are not a library
1556 if (first_source == null && embedded_resources == null){
1557 Report.Error (2008, "No files to compile were specified");
1561 if (Report.Errors > 0)
1568 // Load Core Library for default compilation
1570 if (RootContext.StdLib)
1571 references.Insert (0, "mscorlib");
1573 if (load_default_config)
1574 DefineDefaultConfig ();
1576 if (Report.Errors > 0){
1581 // Load assemblies required
1584 ShowTime ("Loading references");
1585 link_paths.Add (GetSystemDir ());
1586 link_paths.Add (Directory.GetCurrentDirectory ());
1590 ShowTime (" References loaded");
1592 if (Report.Errors > 0){
1599 if (output_file == null){
1600 if (first_source == null){
1601 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1605 int pos = first_source.LastIndexOf ('.');
1608 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1610 output_file = first_source + RootContext.TargetExt;
1613 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1616 if (RootContext.Target == Target.Module) {
1617 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1618 if (module_only == null) {
1619 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1620 Environment.Exit (1);
1623 MethodInfo set_method = module_only.GetSetMethod (true);
1624 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1627 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1629 if (modules.Count > 0) {
1630 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1631 if (adder_method == null) {
1632 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1633 Environment.Exit (1);
1636 foreach (string module in modules)
1637 LoadModule (adder_method, module);
1641 // Before emitting, we need to get the core
1642 // types emitted from the user defined types
1643 // or from the system ones.
1646 ShowTime ("Initializing Core Types");
1647 if (!RootContext.StdLib){
1648 RootContext.ResolveCore ();
1649 if (Report.Errors > 0)
1653 TypeManager.InitCoreTypes ();
1655 ShowTime (" Core Types done");
1657 CodeGen.Module.ResolveAttributes ();
1660 // The second pass of the compiler
1663 ShowTime ("Resolving tree");
1664 RootContext.ResolveTree ();
1666 if (Report.Errors > 0)
1669 ShowTime ("Populate tree");
1670 if (!RootContext.StdLib)
1671 RootContext.BootCorlib_PopulateCoreTypes ();
1673 RootContext.PopulateTypes ();
1675 TypeManager.InitCodeHelpers ();
1677 RootContext.DefineTypes ();
1679 if (Report.Errors == 0 &&
1680 RootContext.Documentation != null &&
1681 !RootContext.Documentation.OutputDocComment (
1686 // Verify using aliases now
1688 NamespaceEntry.VerifyAllUsing ();
1690 if (Report.Errors > 0){
1694 CodeGen.Assembly.Resolve ();
1696 if (RootContext.VerifyClsCompliance) {
1697 if (CodeGen.Assembly.IsClsCompliant) {
1698 AttributeTester.VerifyModulesClsCompliance ();
1699 TypeManager.LoadAllImportedTypes ();
1702 if (Report.Errors > 0)
1706 // The code generator
1709 ShowTime ("Emitting code");
1710 ShowTotalTime ("Total so far");
1711 RootContext.EmitCode ();
1715 if (Report.Errors > 0){
1720 ShowTime ("Closing types");
1722 RootContext.CloseTypes ();
1724 PEFileKinds k = PEFileKinds.ConsoleApplication;
1726 switch (RootContext.Target) {
1727 case Target.Library:
1729 k = PEFileKinds.Dll; break;
1731 k = PEFileKinds.ConsoleApplication; break;
1733 k = PEFileKinds.WindowApplication; break;
1736 if (RootContext.NeedsEntryPoint) {
1737 MethodInfo ep = RootContext.EntryPoint;
1740 if (RootContext.MainClass != null) {
1741 DeclSpace main_cont = RootContext.Tree.Types.GetDefinition (RootContext.MainClass) as DeclSpace;
1742 if (main_cont == null) {
1743 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1747 if (!(main_cont is ClassOrStruct)) {
1748 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1752 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1756 if (Report.Errors == 0)
1757 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1762 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1763 } else if (RootContext.MainClass != null) {
1764 Report.Error (2017, "Cannot specify -main if building a module or library");
1767 if (embedded_resources != null){
1768 if (RootContext.Target == Target.Module) {
1769 Report.Error (1507, "Cannot link resource file when building a module");
1773 embedded_resources.Emit ();
1777 // Add Win32 resources
1780 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1782 if (win32ResourceFile != null) {
1784 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1786 catch (ArgumentException) {
1787 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1791 if (win32IconFile != null) {
1792 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1793 if (define_icon == null) {
1794 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1796 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1799 if (Report.Errors > 0)
1802 CodeGen.Save (output_file);
1804 ShowTime ("Saved output");
1805 ShowTotalTime ("Total");
1808 Timer.ShowTimers ();
1810 if (Report.ExpectedError != 0) {
1811 if (Report.Errors == 0) {
1812 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1813 "No other errors reported.");
1815 Environment.Exit (2);
1817 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1818 "However, other errors were reported.");
1820 Environment.Exit (1);
1828 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1829 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1831 return (Report.Errors == 0);
1840 string FileName { get; }
1843 class EmbededResource : IResource
1845 static MethodInfo embed_res;
1847 static EmbededResource () {
1848 Type[] argst = new Type [] {
1849 typeof (string), typeof (string), typeof (ResourceAttributes)
1852 embed_res = typeof (AssemblyBuilder).GetMethod (
1853 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1854 null, CallingConventions.Any, argst, null);
1856 if (embed_res == null) {
1857 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1861 readonly object[] args;
1863 public EmbededResource (string name, string file, bool isPrivate)
1865 args = new object [3];
1868 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1873 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1876 public string FileName {
1878 return (string)args [1];
1883 class LinkedResource : IResource
1885 readonly string file;
1886 readonly string name;
1887 readonly ResourceAttributes attribute;
1889 public LinkedResource (string name, string file, bool isPrivate)
1893 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1898 CodeGen.Assembly.Builder.AddResourceFile (name, file, attribute);
1901 public string FileName {
1909 IDictionary embedded_resources = new HybridDictionary ();
1911 public void Add (bool embeded, string file, string name)
1913 Add (embeded, file, name, false);
1916 public void Add (bool embeded, string file, string name, bool isPrivate)
1918 if (embedded_resources.Contains (name)) {
1919 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1922 IResource r = embeded ?
1923 (IResource) new EmbededResource (name, file, isPrivate) :
1924 new LinkedResource (name, file, isPrivate);
1926 embedded_resources.Add (name, r);
1931 foreach (IResource r in embedded_resources.Values) {
1932 if (!File.Exists (r.FileName)) {
1933 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1943 // This is the only public entry point
1945 public class CompilerCallableEntryPoint : MarshalByRefObject {
1946 public static bool InvokeCompiler (string [] args, TextWriter error)
1948 Report.Stderr = error;
1950 return Driver.MainDriver (args) && Report.Errors == 0;
1953 Report.Stderr = Console.Error;
1958 public static int[] AllWarningNumbers {
1960 return Report.AllWarnings;
1964 static void Reset ()
1968 RootContext.Reset ();
1970 TypeManager.Reset ();
1971 TypeHandle.Reset ();
1972 RootNamespace.Reset ();
1973 NamespaceEntry.Reset ();