2 // driver.cs: The compiler command line driver.
5 // Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Collections;
20 using System.Collections.Specialized;
23 using System.Globalization;
24 using System.Diagnostics;
27 Library, Exe, Module, WinExe
30 public enum Platform {
31 AnyCPU, X86, X64, IA64
35 /// The compiler driver.
40 // Assemblies references to be linked. Initialized with
45 // If any of these fail, we ignore the problem. This is so
46 // that we can list all the assemblies in Windows and not fail
47 // if they are missing on Linux.
49 ArrayList soft_references;
52 // External aliases for assemblies.
54 Hashtable external_aliases;
57 // Modules to be linked
62 static ArrayList link_paths;
64 // Whether we want to only run the tokenizer
69 bool want_debugging_support;
74 // Whether to load the initial config file (what CSC.RSP has by default)
76 bool load_default_config = true;
79 // A list of resource files
81 Resources embedded_resources;
82 string win32ResourceFile;
88 static string output_file;
91 // Last time we took the time
93 DateTime last_time, first_time;
100 readonly CompilerContext ctx;
102 static readonly char[] argument_value_separator = new char [] { ';', ',' };
104 static public void Reset ()
109 private Driver (CompilerContext ctx)
112 encoding = Encoding.Default;
115 public static Driver Create (string[] args, bool require_files, ReportPrinter printer)
117 Driver d = new Driver (new CompilerContext (new Report (printer)));
119 if (!d.ParseArguments (args, require_files))
126 get { return ctx.Report; }
129 void ShowTime (string msg)
134 DateTime now = DateTime.Now;
135 TimeSpan span = now - last_time;
139 "[{0:00}:{1:000}] {2}",
140 (int) span.TotalSeconds, span.Milliseconds, msg);
143 void ShowTotalTime (string msg)
148 DateTime now = DateTime.Now;
149 TimeSpan span = now - first_time;
153 "[{0:00}:{1:000}] {2}",
154 (int) span.TotalSeconds, span.Milliseconds, msg);
157 void tokenize_file (CompilationUnit file, CompilerContext ctx)
162 input = File.OpenRead (file.Name);
164 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
169 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
170 Tokenizer lexer = new Tokenizer (reader, file, ctx);
171 int token, tokens = 0, errors = 0;
173 while ((token = lexer.token ()) != Token.EOF){
175 if (token == Token.ERROR)
178 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
184 void Parse (CompilationUnit file)
189 input = File.OpenRead (file.Name);
191 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
195 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
198 if (reader.Read () == 77 && reader.Read () == 90) {
199 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
205 Parse (reader, file);
210 void Parse (SeekableStreamReader reader, CompilationUnit file)
212 CSharpParser parser = new CSharpParser (reader, file, ctx);
216 static void OtherFlags ()
219 "Other flags in the compiler\n" +
220 " --fatal Makes errors fatal\n" +
221 " --parse Only parses the source file\n" +
222 " --typetest Tests the tokenizer's built-in type parser\n" +
223 " --stacktrace Shows stack trace at error location\n" +
224 " --timestamp Displays time stamps of various compiler events\n" +
225 " --expect-error X Expect that error X will be encountered\n" +
226 " -v Verbose parsing (for debugging the parser)\n" +
227 " --mcs-debug X Sets MCS debugging level to X\n");
233 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
234 "mcs [options] source-files\n" +
235 " --about About the Mono C# compiler\n" +
236 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
237 " -checked[+|-] Sets default aritmetic overflow context\n" +
238 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
239 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
240 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
241 " -debug[+|-], -g Generate debugging information\n" +
242 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
243 " -doc:FILE Process documentation comments to XML file\n" +
244 " -help Lists all compiler options (short: -?)\n" +
245 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
246 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
247 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, Default, or Future\n" +
248 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
249 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
250 " -noconfig Disables implicitly referenced assemblies\n" +
251 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
252 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
253 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
254 " -out:FILE Specifies output assembly name\n" +
256 " -pkg:P1[,Pn] References packages P1..Pn\n" +
258 " -platform:ARCH Specifies the target platform of the output assembly\n" +
259 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
260 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
261 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
262 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
263 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
264 " KIND can be one of: exe, winexe, library, module\n" +
265 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
266 " -warnaserror[+|-] Treats all warnings as errors\n" +
267 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
268 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
269 " -help2 Shows internal compiler options\n" +
272 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
273 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
274 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
275 " -win32icon:FILE Use this icon for the output\n" +
276 " @file Read response file for more options\n\n" +
277 "Options can be of the form -option or /option");
282 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
288 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
289 "The compiler source code is released under the terms of the \n"+
290 "MIT X11 or GNU GPL licenses\n\n" +
292 "For more information on Mono, visit the project Web site\n" +
293 " http://www.mono-project.com\n\n" +
295 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
296 Environment.Exit (0);
299 public static int Main (string[] args)
301 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
303 Driver d = Driver.Create (args, true, new ConsoleReportPrinter ());
307 if (d.Compile () && d.Report.Errors == 0) {
308 if (d.Report.Warnings > 0) {
309 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
311 Environment.Exit (0);
316 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
317 d.Report.Errors, d.Report.Warnings);
318 Environment.Exit (1);
322 public void LoadAssembly (string assembly, bool soft)
324 LoadAssembly (assembly, null, soft);
327 void Error6 (string name, string log)
329 if (log != null && log.Length > 0)
330 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
331 Report.Error (6, "cannot find metadata file `{0}'", name);
334 void Error9 (string type, string filename, string log)
336 if (log != null && log.Length > 0)
337 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
338 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
341 void BadAssembly (string filename, string log)
343 MethodInfo adder_method = AssemblyClass.AddModule_Method;
345 if (adder_method != null) {
346 AssemblyName an = new AssemblyName ();
348 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
352 m = adder_method.Invoke (ab, new object [] { filename });
353 } catch (TargetInvocationException ex) {
354 throw ex.InnerException;
358 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
359 Path.GetFileName (filename));
362 } catch (FileNotFoundException) {
363 // did the file get deleted during compilation? who cares? swallow the exception
364 } catch (BadImageFormatException) {
366 } catch (FileLoadException) {
370 Error9 ("assembly", filename, log);
373 public void LoadAssembly (string assembly, string alias, bool soft)
376 string total_log = "";
380 char[] path_chars = { '/', '\\' };
382 if (assembly.IndexOfAny (path_chars) != -1) {
383 a = Assembly.LoadFrom (assembly);
385 string ass = assembly;
386 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
387 ass = assembly.Substring (0, assembly.Length - 4);
388 a = Assembly.Load (ass);
390 } catch (FileNotFoundException) {
392 foreach (string dir in link_paths) {
393 string full_path = Path.Combine (dir, assembly);
394 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
398 a = Assembly.LoadFrom (full_path);
401 } catch (FileNotFoundException ff) {
404 total_log += ff.FusionLog;
408 Error6 (assembly, total_log);
413 // Extern aliased refs require special handling
415 GlobalRootNamespace.Instance.AddAssemblyReference (a);
417 GlobalRootNamespace.Instance.DefineRootNamespace (alias, a, ctx);
419 } catch (BadImageFormatException f) {
420 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
421 BadAssembly (f.FileName, f.FusionLog);
422 } catch (FileLoadException f) {
423 // ... while .NET 1.1 throws this
424 BadAssembly (f.FileName, f.FusionLog);
428 public void LoadModule (string module)
431 string total_log = "";
435 m = CodeGen.Assembly.AddModule (module);
436 } catch (FileNotFoundException) {
438 foreach (string dir in link_paths) {
439 string full_path = Path.Combine (dir, module);
440 if (!module.EndsWith (".netmodule"))
441 full_path += ".netmodule";
444 m = CodeGen.Assembly.AddModule (full_path);
447 } catch (FileNotFoundException ff) {
448 total_log += ff.FusionLog;
452 Error6 (module, total_log);
457 GlobalRootNamespace.Instance.AddModuleReference (m);
459 } catch (BadImageFormatException f) {
460 Error9 ("module", f.FileName, f.FusionLog);
461 } catch (FileLoadException f) {
462 Error9 ("module", f.FileName, f.FusionLog);
467 /// Loads all assemblies referenced on the command line
469 public void LoadReferences ()
471 link_paths.Add (GetSystemDir ());
472 link_paths.Add (Directory.GetCurrentDirectory ());
475 // Load Core Library for default compilation
477 if (RootContext.StdLib)
478 LoadAssembly ("mscorlib", false);
480 foreach (string r in soft_references)
481 LoadAssembly (r, true);
483 foreach (string r in references)
484 LoadAssembly (r, false);
486 foreach (DictionaryEntry entry in external_aliases)
487 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
489 GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
492 static string [] LoadArgs (string file)
495 ArrayList args = new ArrayList ();
498 f = new StreamReader (file);
503 StringBuilder sb = new StringBuilder ();
505 while ((line = f.ReadLine ()) != null){
508 for (int i = 0; i < t; i++){
511 if (c == '"' || c == '\''){
514 for (i++; i < t; i++){
521 } else if (c == ' '){
523 args.Add (sb.ToString ());
530 args.Add (sb.ToString ());
535 string [] ret_value = new string [args.Count];
536 args.CopyTo (ret_value, 0);
542 // Returns the directory where the system assemblies are installed
544 static string GetSystemDir ()
546 return Path.GetDirectoryName (typeof (object).Assembly.Location);
550 // Given a path specification, splits the path from the file/pattern
552 static void SplitPathAndPattern (string spec, out string path, out string pattern)
554 int p = spec.LastIndexOf ('/');
557 // Windows does not like /file.cs, switch that to:
562 pattern = spec.Substring (1);
564 path = spec.Substring (0, p);
565 pattern = spec.Substring (p + 1);
570 p = spec.LastIndexOf ('\\');
572 path = spec.Substring (0, p);
573 pattern = spec.Substring (p + 1);
581 void AddSourceFile (string f)
583 if (first_source == null)
586 Location.AddFile (Report, f);
589 bool ParseArguments (string[] args, bool require_files)
591 references = new ArrayList ();
592 external_aliases = new Hashtable ();
593 soft_references = new ArrayList ();
594 modules = new ArrayList (2);
595 link_paths = new ArrayList ();
597 ArrayList response_file_list = null;
598 bool parsing_options = true;
600 for (int i = 0; i < args.Length; i++) {
601 string arg = args [i];
605 if (arg [0] == '@') {
606 string [] extra_args;
607 string response_file = arg.Substring (1);
609 if (response_file_list == null)
610 response_file_list = new ArrayList ();
612 if (response_file_list.Contains (response_file)) {
614 1515, "Response file `" + response_file +
615 "' specified multiple times");
619 response_file_list.Add (response_file);
621 extra_args = LoadArgs (response_file);
622 if (extra_args == null) {
623 Report.Error (2011, "Unable to open response file: " +
628 args = AddArgs (args, extra_args);
632 if (parsing_options) {
634 parsing_options = false;
638 if (arg [0] == '-') {
639 if (UnixParseOption (arg, ref args, ref i))
643 string csc_opt = "/" + arg.Substring (1);
644 if (CSCParseOption (csc_opt, ref args))
647 Error_WrongOption (arg);
650 if (arg [0] == '/') {
651 if (CSCParseOption (arg, ref args))
654 // Need to skip `/home/test.cs' however /test.cs is considered as error
655 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
656 Error_WrongOption (arg);
662 ProcessSourceFiles (arg, false);
665 if (require_files == false)
669 // If we are an exe, require a source file for the entry point
671 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
672 if (first_source == null) {
673 Report.Error (2008, "No files to compile were specified");
680 // If there is nothing to put in the assembly, and we are not a library
682 if (first_source == null && embedded_resources == null) {
683 Report.Error (2008, "No files to compile were specified");
692 Location.Initialize ();
694 ArrayList cu = Location.SourceFiles;
695 for (int i = 0; i < cu.Count; ++i) {
697 tokenize_file ((CompilationUnit) cu [i], ctx);
699 Parse ((CompilationUnit) cu [i]);
704 void ProcessSourceFiles (string spec, bool recurse)
706 string path, pattern;
708 SplitPathAndPattern (spec, out path, out pattern);
709 if (pattern.IndexOf ('*') == -1){
710 AddSourceFile (spec);
714 string [] files = null;
716 files = Directory.GetFiles (path, pattern);
717 } catch (System.IO.DirectoryNotFoundException) {
718 Report.Error (2001, "Source file `" + spec + "' could not be found");
720 } catch (System.IO.IOException){
721 Report.Error (2001, "Source file `" + spec + "' could not be found");
724 foreach (string f in files) {
731 string [] dirs = null;
734 dirs = Directory.GetDirectories (path);
738 foreach (string d in dirs) {
740 // Don't include path in this string, as each
741 // directory entry already does
742 ProcessSourceFiles (d + "/" + pattern, true);
746 public void ProcessDefaultConfig ()
748 if (!load_default_config)
752 // For now the "default config" is harcoded into the compiler
753 // we can move this outside later
755 string [] default_config = {
761 "System.Windows.Browser",
765 // Is it worth pre-loading all this stuff?
768 "System.Configuration.Install",
771 "System.DirectoryServices",
772 "System.Drawing.Design",
774 "System.EnterpriseServices",
777 "System.Runtime.Remoting",
778 "System.Runtime.Serialization.Formatters.Soap",
780 "System.ServiceProcess",
782 "System.Web.RegularExpressions",
783 "System.Web.Services",
784 "System.Windows.Forms"
788 soft_references.AddRange (default_config);
790 if (RootContext.Version > LanguageVersion.ISO_2)
791 soft_references.Add ("System.Core");
792 if (RootContext.Version > LanguageVersion.V_3)
793 soft_references.Add ("Microsoft.CSharp");
796 public static string OutputFile
802 return Path.GetFileName (output_file);
806 void SetWarningLevel (string s)
811 level = Int32.Parse (s);
814 if (level < 0 || level > 4){
815 Report.Error (1900, "Warning level must be in the range 0-4");
818 Report.WarningLevel = level;
821 static void Version ()
823 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
824 Console.WriteLine ("Mono C# compiler version {0}", version);
825 Environment.Exit (0);
829 // Currently handles the Unix-like command line options, but will be
830 // deprecated in favor of the CSCParseOption, which will also handle the
831 // options that start with a dash in the future.
833 bool UnixParseOption (string arg, ref string [] args, ref int i)
837 CSharpParser.yacc_verbose_flag++;
848 case "--main": case "-m":
849 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
850 if ((i + 1) >= args.Length){
852 Environment.Exit (1);
854 RootContext.MainClass = args [++i];
858 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
859 RootContext.Unsafe = true;
862 case "/?": case "/h": case "/help":
865 Environment.Exit (0);
869 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
870 if ((i + 1) >= args.Length){
872 Environment.Exit (1);
874 RootContext.AddConditional (args [++i]);
883 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
884 if ((i + 1) >= args.Length){
886 Environment.Exit (1);
888 OutputFile = args [++i];
892 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
893 RootContext.Checked = true;
897 Report.Printer.Stacktrace = true;
900 case "--linkresource":
902 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
903 if ((i + 1) >= args.Length){
905 Report.Error (5, "Missing argument to --linkres");
906 Environment.Exit (1);
908 if (embedded_resources == null)
909 embedded_resources = new Resources (ctx);
911 embedded_resources.Add (false, args [++i], args [i]);
916 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
917 if ((i + 1) >= args.Length){
919 Report.Error (5, "Missing argument to --resource");
920 Environment.Exit (1);
922 if (embedded_resources == null)
923 embedded_resources = new Resources (ctx);
925 embedded_resources.Add (true, args [++i], args [i]);
929 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
930 if ((i + 1) >= args.Length){
931 Environment.Exit (1);
935 string type = args [++i];
938 RootContext.Target = Target.Library;
939 RootContext.TargetExt = ".dll";
943 RootContext.Target = Target.Exe;
947 RootContext.Target = Target.WinExe;
951 RootContext.Target = Target.Module;
952 RootContext.TargetExt = ".dll";
961 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
962 if ((i + 1) >= args.Length){
964 Environment.Exit (1);
967 string val = args [++i];
968 int idx = val.IndexOf ('=');
970 string alias = val.Substring (0, idx);
971 string assembly = val.Substring (idx + 1);
972 AddExternAlias (alias, assembly);
976 references.Add (val);
980 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
981 if ((i + 1) >= args.Length){
983 Environment.Exit (1);
985 link_paths.Add (args [++i]);
989 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
990 RootContext.StdLib = false;
998 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
999 if ((i + 1) >= args.Length){
1001 Environment.Exit (1);
1006 warn = Int32.Parse (args [++i]);
1009 Environment.Exit (1);
1011 Report.SetIgnoreWarning (warn);
1015 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1016 if ((i + 1) >= args.Length){
1019 "--wlevel requires a value from 0 to 4");
1020 Environment.Exit (1);
1023 SetWarningLevel (args [++i]);
1027 if ((i + 1) >= args.Length){
1028 Report.Error (5, "--mcs-debug requires an argument");
1029 Environment.Exit (1);
1033 Report.DebugFlags = Int32.Parse (args [++i]);
1035 Report.Error (5, "Invalid argument to --mcs-debug");
1036 Environment.Exit (1);
1045 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1046 if ((i + 1) >= args.Length){
1047 Report.Error (5, "--recurse requires an argument");
1048 Environment.Exit (1);
1050 ProcessSourceFiles (args [++i], true);
1055 last_time = first_time = DateTime.Now;
1058 case "--debug": case "-g":
1059 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1060 want_debugging_support = true;
1064 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1065 load_default_config = false;
1073 public static string GetPackageFlags (string packages, bool fatal, Report report)
1075 ProcessStartInfo pi = new ProcessStartInfo ();
1076 pi.FileName = "pkg-config";
1077 pi.RedirectStandardOutput = true;
1078 pi.UseShellExecute = false;
1079 pi.Arguments = "--libs " + packages;
1082 p = Process.Start (pi);
1083 } catch (Exception e) {
1084 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1086 Environment.Exit (1);
1091 if (p.StandardOutput == null){
1092 report.Warning (-27, 1, "Specified package did not return any information");
1096 string pkgout = p.StandardOutput.ReadToEnd ();
1098 if (p.ExitCode != 0) {
1099 report.Error (-27, "Error running pkg-config. Check the above output.");
1101 Environment.Exit (1);
1112 // This parses the -arg and /arg options to the compiler, even if the strings
1113 // in the following text use "/arg" on the strings.
1115 bool CSCParseOption (string option, ref string [] args)
1117 int idx = option.IndexOf (':');
1124 arg = option.Substring (0, idx);
1126 value = option.Substring (idx + 1);
1129 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1137 RootContext.Target = Target.Exe;
1141 RootContext.Target = Target.WinExe;
1145 RootContext.Target = Target.Library;
1146 RootContext.TargetExt = ".dll";
1150 RootContext.Target = Target.Module;
1151 RootContext.TargetExt = ".netmodule";
1161 if (value.Length == 0){
1163 Environment.Exit (1);
1172 RootContext.Optimize = true;
1177 RootContext.Optimize = false;
1180 case "/incremental":
1181 case "/incremental+":
1182 case "/incremental-":
1188 if (value.Length == 0){
1190 Environment.Exit (1);
1193 foreach (string d in value.Split (argument_value_separator)) {
1194 string conditional = d.Trim ();
1195 if (!Tokenizer.IsValidIdentifier (conditional)) {
1196 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
1199 RootContext.AddConditional (conditional);
1206 // We should collect data, runtime, etc and store in the file specified
1208 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1214 if (value.Length == 0){
1216 Environment.Exit (1);
1218 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1219 string pkgout = GetPackageFlags (packages, true, Report);
1221 if (pkgout != null){
1222 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1223 Split (new Char [] { ' ', '\t'});
1224 args = AddArgs (args, xargs);
1231 case "/linkresource":
1234 if (embedded_resources == null)
1235 embedded_resources = new Resources (ctx);
1237 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1238 string[] s = value.Split (argument_value_separator);
1241 if (s[0].Length == 0)
1243 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1246 embedded_resources.Add (embeded, s [0], s [1]);
1249 if (s [2] != "public" && s [2] != "private") {
1250 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1253 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1256 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1263 if (value.Length == 0){
1264 Report.Error (5, "-recurse requires an argument");
1265 Environment.Exit (1);
1267 ProcessSourceFiles (value, true);
1271 case "/reference": {
1272 if (value.Length == 0){
1273 Report.Error (5, "-reference requires an argument");
1274 Environment.Exit (1);
1277 string[] refs = value.Split (argument_value_separator);
1278 foreach (string r in refs){
1280 int index = val.IndexOf ('=');
1282 string alias = r.Substring (0, index);
1283 string assembly = r.Substring (index + 1);
1284 AddExternAlias (alias, assembly);
1288 if (val.Length != 0)
1289 references.Add (val);
1293 case "/addmodule": {
1294 if (value.Length == 0){
1295 Report.Error (5, arg + " requires an argument");
1296 Environment.Exit (1);
1299 string[] refs = value.Split (argument_value_separator);
1300 foreach (string r in refs){
1306 if (value.Length == 0) {
1307 Report.Error (5, arg + " requires an argument");
1308 Environment.Exit (1);
1311 if (win32IconFile != null)
1312 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1314 win32ResourceFile = value;
1317 case "/win32icon": {
1318 if (value.Length == 0) {
1319 Report.Error (5, arg + " requires an argument");
1320 Environment.Exit (1);
1323 if (win32ResourceFile != null)
1324 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1326 win32IconFile = value;
1330 if (value.Length == 0){
1331 Report.Error (2006, arg + " requires an argument");
1332 Environment.Exit (1);
1334 RootContext.Documentation = new Documentation (value);
1340 if (value.Length == 0){
1341 Report.Error (5, "/lib requires an argument");
1342 Environment.Exit (1);
1345 libdirs = value.Split (argument_value_separator);
1346 foreach (string dir in libdirs)
1347 link_paths.Add (dir);
1352 want_debugging_support = false;
1356 if (value == "full" || value == "")
1357 want_debugging_support = true;
1362 want_debugging_support = true;
1367 RootContext.Checked = true;
1371 RootContext.Checked = false;
1379 RootContext.VerifyClsCompliance = false;
1384 RootContext.Unsafe = true;
1388 RootContext.Unsafe = false;
1391 case "/warnaserror":
1392 case "/warnaserror+":
1393 if (value.Length == 0) {
1394 Report.WarningsAreErrors = true;
1396 foreach (string wid in value.Split (argument_value_separator))
1397 Report.AddWarningAsError (wid);
1401 case "/warnaserror-":
1402 if (value.Length == 0) {
1403 Report.WarningsAreErrors = false;
1405 foreach (string wid in value.Split (argument_value_separator))
1406 Report.RemoveWarningAsError (wid);
1411 SetWarningLevel (value);
1417 if (value.Length == 0){
1418 Report.Error (5, "/nowarn requires an argument");
1419 Environment.Exit (1);
1422 warns = value.Split (argument_value_separator);
1423 foreach (string wc in warns){
1425 if (wc.Trim ().Length == 0)
1428 int warn = Int32.Parse (wc);
1430 throw new ArgumentOutOfRangeException("warn");
1432 Report.SetIgnoreWarning (warn);
1434 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1441 load_default_config = false;
1445 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1447 RootContext.Platform = Platform.AnyCPU;
1450 RootContext.Platform = Platform.X86;
1453 RootContext.Platform = Platform.X64;
1456 RootContext.Platform = Platform.IA64;
1459 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1465 // We just ignore this.
1466 case "/errorreport":
1472 Environment.Exit(0);
1478 Environment.Exit (0);
1483 if (value.Length == 0){
1484 Report.Error (5, arg + " requires an argument");
1485 Environment.Exit (1);
1487 RootContext.MainClass = value;
1492 RootContext.StdLib = false;
1496 RootContext.StdLib = true;
1503 if (value == String.Empty) {
1504 Report.Error (5, arg + " requires an argument");
1505 Environment.Exit (1);
1507 RootContext.StrongNameKeyFile = value;
1509 case "/keycontainer":
1510 if (value == String.Empty) {
1511 Report.Error (5, arg + " requires an argument");
1512 Environment.Exit (1);
1514 RootContext.StrongNameKeyContainer = value;
1517 RootContext.StrongNameDelaySign = true;
1520 RootContext.StrongNameDelaySign = false;
1523 case "/langversion":
1524 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1526 RootContext.Version = LanguageVersion.ISO_1;
1529 RootContext.Version = LanguageVersion.Default;
1530 RootContext.AddConditional ("__V2__");
1533 RootContext.Version = LanguageVersion.ISO_2;
1536 RootContext.Version = LanguageVersion.V_3;
1539 RootContext.Version = LanguageVersion.Future;
1543 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1549 encoding = new UTF8Encoding();
1552 encoding = Encoding.Default;
1556 encoding = Encoding.GetEncoding (
1557 Int32.Parse (value));
1559 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1569 void Error_WrongOption (string option)
1571 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1574 static string [] AddArgs (string [] args, string [] extra_args)
1577 new_args = new string [extra_args.Length + args.Length];
1579 // if args contains '--' we have to take that into account
1580 // split args into first half and second half based on '--'
1581 // and add the extra_args before --
1582 int split_position = Array.IndexOf (args, "--");
1583 if (split_position != -1)
1585 Array.Copy (args, new_args, split_position);
1586 extra_args.CopyTo (new_args, split_position);
1587 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1591 args.CopyTo (new_args, 0);
1592 extra_args.CopyTo (new_args, args.Length);
1598 void AddExternAlias (string identifier, string assembly)
1600 if (assembly.Length == 0) {
1601 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1605 if (!IsExternAliasValid (identifier)) {
1606 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1610 // Could here hashtable throw an exception?
1611 external_aliases [identifier] = assembly;
1614 static bool IsExternAliasValid (string identifier)
1616 if (identifier.Length == 0)
1618 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1621 for (int i = 1; i < identifier.Length; i++) {
1622 char c = identifier [i];
1623 if (Char.IsLetter (c) || Char.IsDigit (c))
1626 UnicodeCategory category = Char.GetUnicodeCategory (c);
1627 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1628 category != UnicodeCategory.SpacingCombiningMark ||
1629 category != UnicodeCategory.ConnectorPunctuation)
1637 // Main compilation method
1639 public bool Compile ()
1641 // TODO: Should be passed to parser as an argument
1642 RootContext.ToplevelTypes = new ModuleCompiled (ctx, RootContext.Unsafe);
1645 if (Report.Errors > 0)
1648 if (tokenize || parse_only)
1651 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1652 throw new InternalErrorException ("who set it?");
1654 ProcessDefaultConfig ();
1659 if (output_file == null){
1660 if (first_source == null){
1661 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1665 int pos = first_source.LastIndexOf ('.');
1668 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1670 output_file = first_source + RootContext.TargetExt;
1673 if (!CodeGen.Init (output_file, output_file, want_debugging_support, ctx))
1676 if (RootContext.Target == Target.Module) {
1677 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1678 if (module_only == null) {
1679 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1680 Environment.Exit (1);
1683 MethodInfo set_method = module_only.GetSetMethod (true);
1684 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1687 GlobalRootNamespace.Instance.AddModuleReference (RootContext.ToplevelTypes.Builder);
1690 // Load assemblies required
1693 ShowTime ("Loading references");
1697 if (modules.Count > 0) {
1698 foreach (string module in modules)
1699 LoadModule (module);
1703 ShowTime ("References loaded");
1705 if (!TypeManager.InitCoreTypes (ctx) || Report.Errors > 0)
1708 TypeManager.InitOptionalCoreTypes (ctx);
1711 ShowTime (" Core Types done");
1714 // The second pass of the compiler
1717 ShowTime ("Resolving tree");
1718 RootContext.ResolveTree ();
1720 if (Report.Errors > 0)
1723 ShowTime ("Populate tree");
1724 if (!RootContext.StdLib)
1725 RootContext.BootCorlib_PopulateCoreTypes ();
1726 RootContext.PopulateTypes ();
1728 if (Report.Errors == 0 &&
1729 RootContext.Documentation != null &&
1730 !RootContext.Documentation.OutputDocComment (
1731 output_file, Report))
1735 // Verify using aliases now
1737 NamespaceEntry.VerifyAllUsing ();
1739 if (Report.Errors > 0){
1743 CodeGen.Assembly.Resolve ();
1745 if (RootContext.VerifyClsCompliance) {
1746 if (CodeGen.Assembly.IsClsCompliant) {
1747 AttributeTester.VerifyModulesClsCompliance (ctx);
1748 TypeManager.LoadAllImportedTypes ();
1751 if (Report.Errors > 0)
1755 // The code generator
1758 ShowTime ("Emitting code");
1759 ShowTotalTime ("Total so far");
1760 RootContext.EmitCode ();
1764 if (Report.Errors > 0){
1769 ShowTime ("Closing types");
1771 RootContext.CloseTypes ();
1773 PEFileKinds k = PEFileKinds.ConsoleApplication;
1775 switch (RootContext.Target) {
1776 case Target.Library:
1778 k = PEFileKinds.Dll; break;
1780 k = PEFileKinds.ConsoleApplication; break;
1782 k = PEFileKinds.WindowApplication; break;
1785 if (RootContext.NeedsEntryPoint) {
1786 Method ep = RootContext.EntryPoint;
1789 if (RootContext.MainClass != null) {
1790 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1791 if (main_cont == null) {
1792 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1796 if (!(main_cont is ClassOrStruct)) {
1797 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1801 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1805 if (Report.Errors == 0)
1806 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1811 CodeGen.Assembly.Builder.SetEntryPoint (ep.MethodBuilder, k);
1812 } else if (RootContext.MainClass != null) {
1813 Report.Error (2017, "Cannot specify -main if building a module or library");
1816 if (embedded_resources != null){
1817 if (RootContext.Target == Target.Module) {
1818 Report.Error (1507, "Cannot link resource file when building a module");
1822 embedded_resources.Emit ();
1826 // Add Win32 resources
1829 if (win32ResourceFile != null) {
1831 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1832 } catch (ArgumentException) {
1833 Report.RuntimeMissingSupport (Location.Null, "resource embedding ");
1836 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1839 if (win32IconFile != null) {
1840 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1841 if (define_icon == null) {
1842 Report.RuntimeMissingSupport (Location.Null, "resource embedding");
1844 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1848 if (Report.Errors > 0)
1851 CodeGen.Save (output_file, want_debugging_support, Report);
1853 ShowTime ("Saved output");
1854 ShowTotalTime ("Total");
1857 Timer.ShowTimers ();
1860 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1861 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1863 return (Report.Errors == 0);
1871 void Emit (CompilerContext cc);
1872 string FileName { get; }
1875 class EmbededResource : IResource
1877 static MethodInfo embed_res;
1878 readonly object[] args;
1880 public EmbededResource (string name, string file, bool isPrivate)
1882 args = new object [3];
1885 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1888 public void Emit (CompilerContext cc)
1890 if (embed_res == null) {
1891 var argst = new [] {
1892 typeof (string), typeof (string), typeof (ResourceAttributes)
1895 embed_res = typeof (AssemblyBuilder).GetMethod (
1896 "EmbedResourceFile", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
1897 null, CallingConventions.Any, argst, null);
1899 if (embed_res == null) {
1900 cc.Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1904 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1907 public string FileName {
1909 return (string)args [1];
1914 class LinkedResource : IResource
1916 readonly string file;
1917 readonly string name;
1918 readonly ResourceAttributes attribute;
1920 public LinkedResource (string name, string file, bool isPrivate)
1924 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1927 public void Emit (CompilerContext cc)
1929 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1932 public string FileName {
1940 IDictionary embedded_resources = new HybridDictionary ();
1941 readonly CompilerContext ctx;
1943 public Resources (CompilerContext ctx)
1948 public void Add (bool embeded, string file, string name)
1950 Add (embeded, file, name, false);
1953 public void Add (bool embeded, string file, string name, bool isPrivate)
1955 if (embedded_resources.Contains (name)) {
1956 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1959 IResource r = embeded ?
1960 (IResource) new EmbededResource (name, file, isPrivate) :
1961 new LinkedResource (name, file, isPrivate);
1963 embedded_resources.Add (name, r);
1968 foreach (IResource r in embedded_resources.Values) {
1969 if (!File.Exists (r.FileName)) {
1970 ctx.Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1980 // This is the only public entry point
1982 public class CompilerCallableEntryPoint : MarshalByRefObject {
1983 public static bool InvokeCompiler (string [] args, TextWriter error)
1986 StreamReportPrinter srp = new StreamReportPrinter (error);
1987 Driver d = Driver.Create (args, true, srp);
1991 return d.Compile () && srp.ErrorsCount == 0;
1997 public static int[] AllWarningNumbers {
1999 return Report.AllWarnings;
2003 public static void Reset ()
2008 public static void PartialReset ()
2013 public static void Reset (bool full_flag)
2016 CSharpParser.yacc_verbose_flag = 0;
2017 RootContext.Reset (full_flag);
2019 TypeManager.Reset ();
2020 PredefinedAttributes.Reset ();
2021 TypeHandle.Reset ();
2024 GlobalRootNamespace.Reset ();
2026 NamespaceEntry.Reset ();
2029 AttributeTester.Reset ();
2030 AnonymousTypeClass.Reset ();
2031 AnonymousMethodBody.Reset ();
2032 AnonymousMethodStorey.Reset ();
2033 SymbolWriter.Reset ();
2035 Linq.QueryBlock.TransparentParameter.Reset ();
2038 DynamicExpressionStatement.Reset ();