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 " --typetest Tests the tokenizer's built-in type parser\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)
289 RootContext.Version = LanguageVersion.Default;
291 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
293 bool ok = MainDriver (args);
295 if (ok && Report.Errors == 0) {
296 if (Report.Warnings > 0) {
297 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
300 Console.WriteLine ("Counter1: " + counter1);
301 Console.WriteLine ("Counter2: " + counter2);
307 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
308 Report.Errors, Report.Warnings);
313 static public void LoadAssembly (string assembly, bool soft)
315 LoadAssembly (assembly, null, soft);
318 static void Error6 (string name, string log)
320 if (log != null && log.Length > 0)
321 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
322 Report.Error (6, "cannot find metadata file `{0}'", name);
325 static void Error9 (string type, string filename, string log)
327 if (log != null && log.Length > 0)
328 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
329 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
332 static void BadAssembly (string filename, string log)
334 MethodInfo adder_method = AssemblyClass.AddModule_Method;
336 if (adder_method != null) {
337 AssemblyName an = new AssemblyName ();
339 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
343 m = adder_method.Invoke (ab, new object [] { filename });
344 } catch (TargetInvocationException ex) {
345 throw ex.InnerException;
349 Report.Error (1509, "referenced file `{0}' is not an assembly; try using the '-addmodule' option", filename);
352 } catch (FileNotFoundException) {
353 // did the file get deleted during compilation? who cares? swallow the exception
354 } catch (BadImageFormatException) {
356 } catch (FileLoadException) {
360 Error9 ("assembly", filename, log);
363 static public void LoadAssembly (string assembly, string alias, bool soft)
366 string total_log = "";
370 char[] path_chars = { '/', '\\' };
372 if (assembly.IndexOfAny (path_chars) != -1) {
373 a = Assembly.LoadFrom (assembly);
375 string ass = assembly;
376 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
377 ass = assembly.Substring (0, assembly.Length - 4);
378 a = Assembly.Load (ass);
380 } catch (FileNotFoundException) {
382 foreach (string dir in link_paths) {
383 string full_path = Path.Combine (dir, assembly);
384 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
388 a = Assembly.LoadFrom (full_path);
391 } catch (FileNotFoundException ff) {
392 total_log += ff.FusionLog;
396 Error6 (assembly, total_log);
401 // Extern aliased refs require special handling
403 RootNamespace.Global.AddAssemblyReference (a);
405 RootNamespace.DefineRootNamespace (alias, a);
407 } catch (BadImageFormatException f) {
408 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
409 BadAssembly (f.FileName, f.FusionLog);
410 } catch (FileLoadException f) {
411 // ... while .NET 1.1 throws this
412 BadAssembly (f.FileName, f.FusionLog);
416 static public void LoadModule (string module)
419 string total_log = "";
423 m = CodeGen.Assembly.AddModule (module);
424 } catch (FileNotFoundException) {
426 foreach (string dir in link_paths) {
427 string full_path = Path.Combine (dir, module);
428 if (!module.EndsWith (".netmodule"))
429 full_path += ".netmodule";
432 m = CodeGen.Assembly.AddModule (full_path);
435 } catch (FileNotFoundException ff) {
436 total_log += ff.FusionLog;
440 Error6 (module, total_log);
445 RootNamespace.Global.AddModuleReference (m);
447 } catch (BadImageFormatException f) {
448 Error9 ("module", f.FileName, f.FusionLog);
449 } catch (FileLoadException f) {
450 Error9 ("module", f.FileName, f.FusionLog);
455 /// Loads all assemblies referenced on the command line
457 static public void LoadReferences ()
459 foreach (string r in references)
460 LoadAssembly (r, false);
462 foreach (string r in soft_references)
463 LoadAssembly (r, true);
465 foreach (DictionaryEntry entry in external_aliases)
466 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
471 static void SetupDefaultDefines ()
473 defines = new ArrayList ();
474 defines.Add ("__MonoCS__");
477 static string [] LoadArgs (string file)
480 ArrayList args = new ArrayList ();
483 f = new StreamReader (file);
488 StringBuilder sb = new StringBuilder ();
490 while ((line = f.ReadLine ()) != null){
493 for (int i = 0; i < t; i++){
496 if (c == '"' || c == '\''){
499 for (i++; i < t; i++){
506 } else if (c == ' '){
508 args.Add (sb.ToString ());
515 args.Add (sb.ToString ());
520 string [] ret_value = new string [args.Count];
521 args.CopyTo (ret_value, 0);
527 // Returns the directory where the system assemblies are installed
529 static string GetSystemDir ()
531 return Path.GetDirectoryName (typeof (object).Assembly.Location);
535 // Given a path specification, splits the path from the file/pattern
537 static void SplitPathAndPattern (string spec, out string path, out string pattern)
539 int p = spec.LastIndexOf ('/');
542 // Windows does not like /file.cs, switch that to:
547 pattern = spec.Substring (1);
549 path = spec.Substring (0, p);
550 pattern = spec.Substring (p + 1);
555 p = spec.LastIndexOf ('\\');
557 path = spec.Substring (0, p);
558 pattern = spec.Substring (p + 1);
566 static void ProcessFile (string f)
568 if (first_source == null)
571 Location.AddFile (f);
574 static void ProcessFiles ()
576 Location.Initialize ();
578 foreach (SourceFile file in Location.SourceFiles) {
580 tokenize_file (file);
587 static void CompileFiles (string spec, bool recurse)
589 string path, pattern;
591 SplitPathAndPattern (spec, out path, out pattern);
592 if (pattern.IndexOf ('*') == -1){
597 string [] files = null;
599 files = Directory.GetFiles (path, pattern);
600 } catch (System.IO.DirectoryNotFoundException) {
601 Report.Error (2001, "Source file `" + spec + "' could not be found");
603 } catch (System.IO.IOException){
604 Report.Error (2001, "Source file `" + spec + "' could not be found");
607 foreach (string f in files) {
614 string [] dirs = null;
617 dirs = Directory.GetDirectories (path);
621 foreach (string d in dirs) {
623 // Don't include path in this string, as each
624 // directory entry already does
625 CompileFiles (d + "/" + pattern, true);
629 static void DefineDefaultConfig ()
632 // For now the "default config" is harcoded into the compiler
633 // we can move this outside later
635 string [] default_config = {
640 // Is it worth pre-loading all this stuff?
643 "System.Configuration.Install",
646 "System.DirectoryServices",
647 "System.Drawing.Design",
649 "System.EnterpriseServices",
652 "System.Runtime.Remoting",
653 "System.Runtime.Serialization.Formatters.Soap",
655 "System.ServiceProcess",
657 "System.Web.RegularExpressions",
658 "System.Web.Services",
659 "System.Windows.Forms"
664 foreach (string def in default_config)
665 soft_references.Insert (p++, def);
668 public static string OutputFile
674 return Path.GetFileName (output_file);
678 static void SetWarningLevel (string s)
683 level = Int32.Parse (s);
686 if (level < 0 || level > 4){
687 Report.Error (1900, "Warning level must be in the range 0-4");
690 RootContext.WarningLevel = level;
693 static void SetupV2 ()
695 RootContext.Version = LanguageVersion.Default;
696 defines.Add ("__V2__");
699 static void Version ()
701 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
702 Console.WriteLine ("Mono C# compiler version {0}", version);
703 Environment.Exit (0);
707 // This is to test the tokenizer internal parser that is used to deambiguate
708 // '(' type identifier from '(' type others so that we are able to parse
709 // without introducing reduce/reduce conflicts in the grammar.
711 static void LambdaTypeParseTest (string fname)
715 using (FileStream fs = File.OpenRead (fname)){
716 StreamReader r = new StreamReader (fs, encoding);
719 while ((line = r.ReadLine ())!= null){
722 bool must_pass = line [0] == '+';
723 StringReader test = new StringReader (line.Substring (1));
724 SeekableStreamReader reader = new SeekableStreamReader (test);
725 SourceFile file = new SourceFile (fname, fname, 0);
727 Tokenizer lexer = new Tokenizer (reader, file, defines);
728 bool res = lexer.parse_type_and_parameter ();
730 Console.WriteLine ("{3} ({1}=={2}): {0}", line.Substring (1), res, must_pass, res == must_pass);
731 if (res != must_pass)
735 Console.WriteLine ("fail={0}", fail);
736 Environment.Exit (fail ? 1 : 0);
740 // Currently handles the Unix-like command line options, but will be
741 // deprecated in favor of the CSCParseOption, which will also handle the
742 // options that start with a dash in the future.
744 static bool UnixParseOption (string arg, ref string [] args, ref int i)
748 CSharpParser.yacc_verbose_flag++;
759 case "--main": case "-m":
760 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
761 if ((i + 1) >= args.Length){
763 Environment.Exit (1);
765 RootContext.MainClass = args [++i];
769 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
770 RootContext.Unsafe = true;
773 case "/?": case "/h": case "/help":
776 Environment.Exit (0);
780 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
781 if ((i + 1) >= args.Length){
783 Environment.Exit (1);
785 defines.Add (args [++i]);
788 case "--show-counters":
789 show_counters = true;
792 case "--expect-error": {
797 args [++i], NumberStyles.AllowLeadingSign);
798 Report.ExpectedError = code;
800 Report.Error (-14, "Invalid number specified");
811 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
812 if ((i + 1) >= args.Length){
814 Environment.Exit (1);
816 OutputFile = args [++i];
820 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
821 RootContext.Checked = true;
825 Report.Stacktrace = true;
828 case "--linkresource":
830 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
831 if ((i + 1) >= args.Length){
833 Report.Error (5, "Missing argument to --linkres");
834 Environment.Exit (1);
836 if (embedded_resources == null)
837 embedded_resources = new Resources ();
839 embedded_resources.Add (false, args [++i], args [i]);
844 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
845 if ((i + 1) >= args.Length){
847 Report.Error (5, "Missing argument to --resource");
848 Environment.Exit (1);
850 if (embedded_resources == null)
851 embedded_resources = new Resources ();
853 embedded_resources.Add (true, args [++i], args [i]);
857 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
858 if ((i + 1) >= args.Length){
859 Environment.Exit (1);
863 string type = args [++i];
866 RootContext.Target = Target.Library;
867 RootContext.TargetExt = ".dll";
871 RootContext.Target = Target.Exe;
875 RootContext.Target = Target.WinExe;
879 RootContext.Target = Target.Module;
880 RootContext.TargetExt = ".dll";
889 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
890 if ((i + 1) >= args.Length){
892 Environment.Exit (1);
895 string val = args [++i];
896 int idx = val.IndexOf ('=');
898 string alias = val.Substring (0, idx);
899 string assembly = val.Substring (idx + 1);
900 AddExternAlias (alias, assembly);
904 references.Add (val);
908 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
909 if ((i + 1) >= args.Length){
911 Environment.Exit (1);
913 link_paths.Add (args [++i]);
917 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
918 RootContext.StdLib = false;
926 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
927 Report.WarningsAreErrors = true;
931 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
932 if ((i + 1) >= args.Length){
934 Environment.Exit (1);
939 warn = Int32.Parse (args [++i]);
942 Environment.Exit (1);
944 Report.SetIgnoreWarning (warn);
948 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
949 if ((i + 1) >= args.Length){
952 "--wlevel requires a value from 0 to 4");
953 Environment.Exit (1);
956 SetWarningLevel (args [++i]);
960 if ((i + 1) >= args.Length){
961 Report.Error (5, "--mcs-debug requires an argument");
962 Environment.Exit (1);
966 Report.DebugFlags = Int32.Parse (args [++i]);
968 Report.Error (5, "Invalid argument to --mcs-debug");
969 Environment.Exit (1);
978 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
979 if ((i + 1) >= args.Length){
980 Report.Error (5, "--recurse requires an argument");
981 Environment.Exit (1);
983 CompileFiles (args [++i], true);
988 last_time = first_time = DateTime.Now;
995 case "--debug": case "-g":
996 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
997 want_debugging_support = true;
1001 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1002 load_default_config = false;
1006 if ((i + 1) >= args.Length){
1007 Report.Error (5, "--typetest requires a filename argument");
1008 Environment.Exit (1);
1010 LambdaTypeParseTest (args [++i]);
1018 // This parses the -arg and /arg options to the compiler, even if the strings
1019 // in the following text use "/arg" on the strings.
1021 static bool CSCParseOption (string option, ref string [] args, ref int i)
1023 int idx = option.IndexOf (':');
1030 arg = option.Substring (0, idx);
1032 value = option.Substring (idx + 1);
1043 RootContext.Target = Target.Exe;
1047 RootContext.Target = Target.WinExe;
1051 RootContext.Target = Target.Library;
1052 RootContext.TargetExt = ".dll";
1056 RootContext.Target = Target.Module;
1057 RootContext.TargetExt = ".netmodule";
1067 if (value.Length == 0){
1069 Environment.Exit (1);
1076 RootContext.Optimize = true;
1080 RootContext.Optimize = false;
1083 case "/incremental":
1084 case "/incremental+":
1085 case "/incremental-":
1093 if (value.Length == 0){
1095 Environment.Exit (1);
1098 defs = value.Split (new Char [] {';', ','});
1099 foreach (string d in defs){
1107 // We should collect data, runtime, etc and store in the file specified
1109 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1115 if (value.Length == 0){
1117 Environment.Exit (1);
1119 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1121 ProcessStartInfo pi = new ProcessStartInfo ();
1122 pi.FileName = "pkg-config";
1123 pi.RedirectStandardOutput = true;
1124 pi.UseShellExecute = false;
1125 pi.Arguments = "--libs " + packages;
1128 p = Process.Start (pi);
1129 } catch (Exception e) {
1130 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1131 Environment.Exit (1);
1134 if (p.StandardOutput == null){
1135 Report.Warning (-27, 1, "Specified package did not return any information");
1138 string pkgout = p.StandardOutput.ReadToEnd ();
1140 if (p.ExitCode != 0) {
1141 Report.Error (-27, "Error running pkg-config. Check the above output.");
1142 Environment.Exit (1);
1145 if (pkgout != null){
1146 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1147 Split (new Char [] { ' ', '\t'});
1148 args = AddArgs (args, xargs);
1156 case "/linkresource":
1159 if (embedded_resources == null)
1160 embedded_resources = new Resources ();
1162 bool embeded = arg.StartsWith ("/r");
1163 string[] s = value.Split (',');
1166 if (s[0].Length == 0)
1168 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1171 embedded_resources.Add (embeded, s [0], s [1]);
1174 if (s [2] != "public" && s [2] != "private") {
1175 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1178 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1181 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1188 if (value.Length == 0){
1189 Report.Error (5, "-recurse requires an argument");
1190 Environment.Exit (1);
1192 CompileFiles (value, true);
1196 case "/reference": {
1197 if (value.Length == 0){
1198 Report.Error (5, "-reference requires an argument");
1199 Environment.Exit (1);
1202 string [] refs = value.Split (new char [] { ';', ',' });
1203 foreach (string r in refs){
1205 int index = val.IndexOf ('=');
1207 string alias = r.Substring (0, index);
1208 string assembly = r.Substring (index + 1);
1209 AddExternAlias (alias, assembly);
1213 references.Add (val);
1217 case "/addmodule": {
1218 if (value.Length == 0){
1219 Report.Error (5, arg + " requires an argument");
1220 Environment.Exit (1);
1223 string [] refs = value.Split (new char [] { ';', ',' });
1224 foreach (string r in refs){
1230 if (value.Length == 0) {
1231 Report.Error (5, arg + " requires an argument");
1232 Environment.Exit (1);
1235 win32ResourceFile = value;
1238 case "/win32icon": {
1239 if (value.Length == 0) {
1240 Report.Error (5, arg + " requires an argument");
1241 Environment.Exit (1);
1244 win32IconFile = value;
1248 if (value.Length == 0){
1249 Report.Error (2006, arg + " requires an argument");
1250 Environment.Exit (1);
1252 RootContext.Documentation = new Documentation (value);
1258 if (value.Length == 0){
1259 Report.Error (5, "/lib requires an argument");
1260 Environment.Exit (1);
1263 libdirs = value.Split (new Char [] { ',' });
1264 foreach (string dir in libdirs)
1265 link_paths.Add (dir);
1270 want_debugging_support = false;
1275 want_debugging_support = true;
1280 RootContext.Checked = true;
1284 RootContext.Checked = false;
1292 RootContext.VerifyClsCompliance = false;
1297 RootContext.Unsafe = true;
1301 RootContext.Unsafe = false;
1304 case "/warnaserror":
1305 case "/warnaserror+":
1306 Report.WarningsAreErrors = true;
1309 case "/warnaserror-":
1310 Report.WarningsAreErrors = false;
1314 SetWarningLevel (value);
1320 if (value.Length == 0){
1321 Report.Error (5, "/nowarn requires an argument");
1322 Environment.Exit (1);
1325 warns = value.Split (new Char [] {','});
1326 foreach (string wc in warns){
1328 int warn = Int32.Parse (wc);
1330 throw new ArgumentOutOfRangeException("warn");
1332 Report.SetIgnoreWarning (warn);
1334 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1341 load_default_config = true;
1346 load_default_config = false;
1351 Environment.Exit(0);
1357 Environment.Exit (0);
1362 if (value.Length == 0){
1363 Report.Error (5, arg + " requires an argument");
1364 Environment.Exit (1);
1366 RootContext.MainClass = value;
1371 RootContext.StdLib = false;
1375 RootContext.StdLib = true;
1382 if (value == String.Empty) {
1383 Report.Error (5, arg + " requires an argument");
1384 Environment.Exit (1);
1386 RootContext.StrongNameKeyFile = value;
1388 case "/keycontainer":
1389 if (value == String.Empty) {
1390 Report.Error (5, arg + " requires an argument");
1391 Environment.Exit (1);
1393 RootContext.StrongNameKeyContainer = value;
1396 RootContext.StrongNameDelaySign = true;
1399 RootContext.StrongNameDelaySign = false;
1404 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1408 case "/langversion":
1409 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1411 RootContext.Version = LanguageVersion.ISO_1;
1419 RootContext.Version = LanguageVersion.LINQ;
1422 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1428 encoding = new UTF8Encoding();
1431 encoding = Encoding.Default;
1435 encoding = Encoding.GetEncoding (
1436 Int32.Parse (value));
1438 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1448 static void Error_WrongOption (string option)
1450 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1453 static string [] AddArgs (string [] args, string [] extra_args)
1456 new_args = new string [extra_args.Length + args.Length];
1458 // if args contains '--' we have to take that into account
1459 // split args into first half and second half based on '--'
1460 // and add the extra_args before --
1461 int split_position = Array.IndexOf (args, "--");
1462 if (split_position != -1)
1464 Array.Copy (args, new_args, split_position);
1465 extra_args.CopyTo (new_args, split_position);
1466 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1470 args.CopyTo (new_args, 0);
1471 extra_args.CopyTo (new_args, args.Length);
1477 static void AddExternAlias (string identifier, string assembly)
1479 if (assembly.Length == 0) {
1480 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1484 if (!IsExternAliasValid (identifier)) {
1485 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1489 // Could here hashtable throw an exception?
1490 external_aliases [identifier] = assembly;
1493 static bool IsExternAliasValid (string identifier)
1495 if (identifier.Length == 0)
1497 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1500 for (int i = 1; i < identifier.Length; i++) {
1501 char c = identifier [i];
1502 if (Char.IsLetter (c) || Char.IsDigit (c))
1505 UnicodeCategory category = Char.GetUnicodeCategory (c);
1506 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1507 category != UnicodeCategory.SpacingCombiningMark ||
1508 category != UnicodeCategory.ConnectorPunctuation)
1516 /// Parses the arguments, and drives the compilation
1521 /// TODO: Mostly structured to debug the compiler
1522 /// now, needs to be turned into a real driver soon.
1524 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1525 internal static bool MainDriver (string [] args)
1528 bool parsing_options = true;
1530 encoding = Encoding.Default;
1532 references = new ArrayList ();
1533 external_aliases = new Hashtable ();
1534 soft_references = new ArrayList ();
1535 modules = new ArrayList ();
1536 link_paths = new ArrayList ();
1538 SetupDefaultDefines ();
1543 // This is not required because Assembly.Load knows about this
1547 Hashtable response_file_list = null;
1549 for (i = 0; i < args.Length; i++){
1550 string arg = args [i];
1551 if (arg.Length == 0)
1554 if (arg.StartsWith ("@")){
1555 string [] extra_args;
1556 string response_file = arg.Substring (1);
1558 if (response_file_list == null)
1559 response_file_list = new Hashtable ();
1561 if (response_file_list.Contains (response_file)){
1563 1515, "Response file `" + response_file +
1564 "' specified multiple times");
1565 Environment.Exit (1);
1568 response_file_list.Add (response_file, response_file);
1570 extra_args = LoadArgs (response_file);
1571 if (extra_args == null){
1572 Report.Error (2011, "Unable to open response file: " +
1577 args = AddArgs (args, extra_args);
1581 if (parsing_options){
1583 parsing_options = false;
1587 if (arg.StartsWith ("-")){
1588 if (UnixParseOption (arg, ref args, ref i))
1592 string csc_opt = "/" + arg.Substring (1);
1593 if (CSCParseOption (csc_opt, ref args, ref i))
1596 Error_WrongOption (arg);
1599 if (arg [0] == '/'){
1600 if (CSCParseOption (arg, ref args, ref i))
1603 // Need to skip `/home/test.cs' however /test.cs is considered as error
1604 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1605 Error_WrongOption (arg);
1612 CompileFiles (arg, false);
1620 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1621 throw new InternalErrorException ("who set it?");
1624 // If we are an exe, require a source file for the entry point
1626 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1627 if (first_source == null){
1628 Report.Error (2008, "No files to compile were specified");
1635 // If there is nothing to put in the assembly, and we are not a library
1637 if (first_source == null && embedded_resources == null){
1638 Report.Error (2008, "No files to compile were specified");
1642 if (Report.Errors > 0)
1649 // Load Core Library for default compilation
1651 if (RootContext.StdLib)
1652 references.Insert (0, "mscorlib");
1654 if (load_default_config)
1655 DefineDefaultConfig ();
1657 if (Report.Errors > 0){
1662 // Load assemblies required
1665 ShowTime ("Loading references");
1666 link_paths.Add (GetSystemDir ());
1667 link_paths.Add (Directory.GetCurrentDirectory ());
1671 ShowTime (" References loaded");
1673 if (Report.Errors > 0){
1680 if (output_file == null){
1681 if (first_source == null){
1682 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1686 int pos = first_source.LastIndexOf ('.');
1689 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1691 output_file = first_source + RootContext.TargetExt;
1694 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1697 if (RootContext.Target == Target.Module) {
1698 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1699 if (module_only == null) {
1700 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1701 Environment.Exit (1);
1704 MethodInfo set_method = module_only.GetSetMethod (true);
1705 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1708 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1710 if (modules.Count > 0) {
1711 foreach (string module in modules)
1712 LoadModule (module);
1716 // Before emitting, we need to get the core
1717 // types emitted from the user defined types
1718 // or from the system ones.
1721 ShowTime ("Initializing Core Types");
1722 if (!RootContext.StdLib){
1723 RootContext.ResolveCore ();
1724 if (Report.Errors > 0)
1728 TypeManager.InitCoreTypes ();
1730 ShowTime (" Core Types done");
1732 CodeGen.Module.Resolve ();
1735 // The second pass of the compiler
1738 ShowTime ("Resolving tree");
1739 RootContext.ResolveTree ();
1741 if (Report.Errors > 0)
1744 ShowTime ("Populate tree");
1745 if (!RootContext.StdLib)
1746 RootContext.BootCorlib_PopulateCoreTypes ();
1747 RootContext.PopulateTypes ();
1749 TypeManager.InitCodeHelpers ();
1751 RootContext.DefineTypes ();
1753 if (Report.Errors == 0 &&
1754 RootContext.Documentation != null &&
1755 !RootContext.Documentation.OutputDocComment (
1760 // Verify using aliases now
1762 NamespaceEntry.VerifyAllUsing ();
1764 if (Report.Errors > 0){
1768 CodeGen.Assembly.Resolve ();
1770 if (RootContext.VerifyClsCompliance) {
1771 if (CodeGen.Assembly.IsClsCompliant) {
1772 AttributeTester.VerifyModulesClsCompliance ();
1773 TypeManager.LoadAllImportedTypes ();
1776 if (Report.Errors > 0)
1780 // The code generator
1783 ShowTime ("Emitting code");
1784 ShowTotalTime ("Total so far");
1785 RootContext.EmitCode ();
1789 if (Report.Errors > 0){
1794 ShowTime ("Closing types");
1796 RootContext.CloseTypes ();
1798 PEFileKinds k = PEFileKinds.ConsoleApplication;
1800 switch (RootContext.Target) {
1801 case Target.Library:
1803 k = PEFileKinds.Dll; break;
1805 k = PEFileKinds.ConsoleApplication; break;
1807 k = PEFileKinds.WindowApplication; break;
1810 if (RootContext.NeedsEntryPoint) {
1811 MethodInfo ep = RootContext.EntryPoint;
1814 if (RootContext.MainClass != null) {
1815 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1816 if (main_cont == null) {
1817 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1821 if (!(main_cont is ClassOrStruct)) {
1822 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1826 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1830 if (Report.Errors == 0)
1831 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1836 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1837 } else if (RootContext.MainClass != null) {
1838 Report.Error (2017, "Cannot specify -main if building a module or library");
1841 if (embedded_resources != null){
1842 if (RootContext.Target == Target.Module) {
1843 Report.Error (1507, "Cannot link resource file when building a module");
1847 embedded_resources.Emit ();
1851 // Add Win32 resources
1854 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1856 if (win32ResourceFile != null) {
1858 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1860 catch (ArgumentException) {
1861 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1865 if (win32IconFile != null) {
1866 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1867 if (define_icon == null) {
1868 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1870 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1873 if (Report.Errors > 0)
1876 CodeGen.Save (output_file);
1878 ShowTime ("Saved output");
1879 ShowTotalTime ("Total");
1882 Timer.ShowTimers ();
1884 if (Report.ExpectedError != 0) {
1885 if (Report.Errors == 0) {
1886 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1887 "No other errors reported.");
1889 Environment.Exit (2);
1891 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1892 "However, other errors were reported.");
1894 Environment.Exit (1);
1902 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1903 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1905 return (Report.Errors == 0);
1914 string FileName { get; }
1917 class EmbededResource : IResource
1919 static MethodInfo embed_res;
1921 static EmbededResource () {
1922 Type[] argst = new Type [] {
1923 typeof (string), typeof (string), typeof (ResourceAttributes)
1926 embed_res = typeof (AssemblyBuilder).GetMethod (
1927 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1928 null, CallingConventions.Any, argst, null);
1930 if (embed_res == null) {
1931 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1935 readonly object[] args;
1937 public EmbededResource (string name, string file, bool isPrivate)
1939 args = new object [3];
1942 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1947 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1950 public string FileName {
1952 return (string)args [1];
1957 class LinkedResource : IResource
1959 readonly string file;
1960 readonly string name;
1961 readonly ResourceAttributes attribute;
1963 public LinkedResource (string name, string file, bool isPrivate)
1967 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1972 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1975 public string FileName {
1983 IDictionary embedded_resources = new HybridDictionary ();
1985 public void Add (bool embeded, string file, string name)
1987 Add (embeded, file, name, false);
1990 public void Add (bool embeded, string file, string name, bool isPrivate)
1992 if (embedded_resources.Contains (name)) {
1993 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1996 IResource r = embeded ?
1997 (IResource) new EmbededResource (name, file, isPrivate) :
1998 new LinkedResource (name, file, isPrivate);
2000 embedded_resources.Add (name, r);
2005 foreach (IResource r in embedded_resources.Values) {
2006 if (!File.Exists (r.FileName)) {
2007 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
2017 // This is the only public entry point
2019 public class CompilerCallableEntryPoint : MarshalByRefObject {
2020 public static bool InvokeCompiler (string [] args, TextWriter error)
2022 Report.Stderr = error;
2024 return Driver.MainDriver (args) && Report.Errors == 0;
2027 Report.Stderr = Console.Error;
2032 public static int[] AllWarningNumbers {
2034 return Report.AllWarnings;
2038 static void Reset ()
2042 RootContext.Reset ();
2044 TypeManager.Reset ();
2045 TypeHandle.Reset ();
2046 RootNamespace.Reset ();
2047 NamespaceEntry.Reset ();
2050 AttributeTester.Reset ();