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.Generic;
22 using System.Globalization;
23 using System.Diagnostics;
26 Library, Exe, Module, WinExe
29 public enum Platform {
30 AnyCPU, X86, X64, IA64
34 /// The compiler driver.
39 // Assemblies references to be linked. Initialized with
41 List<string> references;
44 // If any of these fail, we ignore the problem. This is so
45 // that we can list all the assemblies in Windows and not fail
46 // if they are missing on Linux.
48 List<string> soft_references;
51 // External aliases for assemblies.
53 Dictionary<string, string> external_aliases;
56 // Modules to be linked
61 List<string> link_paths;
63 // Whether we want to only run the tokenizer
70 internal int fatal_errors;
73 // Whether to load the initial config file (what CSC.RSP has by default)
75 bool load_default_config = true;
78 // A list of resource files
80 Resources embedded_resources;
81 string win32ResourceFile;
87 static string output_file;
90 // Last time we took the time
100 internal 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 ReflectionMetaImporter (), new Report (printer)));
119 if (!d.ParseArguments (args, require_files))
126 get { return ctx.Report; }
129 void ShowTime (string msg)
136 Console.WriteLine ("{0,5}ms {1}", stopwatch.ElapsedMilliseconds, msg);
138 stopwatch = Stopwatch.StartNew ();
141 void ShowTotalTime (string msg)
146 DateTime now = DateTime.Now;
147 TimeSpan span = now - first_time;
150 "[{0:00}:{1:000}] {2}",
151 (int) span.TotalSeconds, span.Milliseconds, msg);
154 void tokenize_file (CompilationUnit file, CompilerContext ctx)
159 input = File.OpenRead (file.Name);
161 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
166 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
167 Tokenizer lexer = new Tokenizer (reader, file, ctx);
168 int token, tokens = 0, errors = 0;
170 while ((token = lexer.token ()) != Token.EOF){
172 if (token == Token.ERROR)
175 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
181 void Parse (CompilationUnit file, ModuleContainer module)
186 input = File.OpenRead (file.Name);
188 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
193 if (input.ReadByte () == 77 && input.ReadByte () == 90) {
194 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
200 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
202 Parse (reader, file, module);
207 void Parse (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
209 CSharpParser parser = new CSharpParser (reader, file, module);
213 static void OtherFlags ()
216 "Other flags in the compiler\n" +
217 " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
218 " --lint Enhanced warnings\n" +
219 " --parse Only parses the source file\n" +
220 " --stacktrace Shows stack trace at error location\n" +
221 " --timestamp Displays time stamps of various compiler events\n" +
222 " -v Verbose parsing (for debugging the parser)\n" +
223 " --mcs-debug X Sets MCS debugging level to X\n");
229 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
230 "mcs [options] source-files\n" +
231 " --about About the Mono C# compiler\n" +
232 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
233 " -checked[+|-] Sets default aritmetic overflow context\n" +
234 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
235 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
236 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
237 " -debug[+|-], -g Generate debugging information\n" +
238 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
239 " -doc:FILE Process documentation comments to XML file\n" +
240 " -help Lists all compiler options (short: -?)\n" +
241 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
242 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
243 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default, or Future\n" +
244 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
245 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
246 " -noconfig Disables implicitly referenced assemblies\n" +
247 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
248 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
249 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
250 " -out:FILE Specifies output assembly name\n" +
252 " -pkg:P1[,Pn] References packages P1..Pn\n" +
254 " -platform:ARCH Specifies the target platform of the output assembly\n" +
255 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
256 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
257 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
258 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
259 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
260 " KIND can be one of: exe, winexe, library, module\n" +
261 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
262 " -warnaserror[+|-] Treats all warnings as errors\n" +
263 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
264 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
265 " -help2 Shows internal compiler options\n" +
268 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
269 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
270 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
271 " -win32icon:FILE Use this icon for the output\n" +
272 " @file Read response file for more options\n\n" +
273 "Options can be of the form -option or /option");
278 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
284 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
285 "The compiler source code is released under the terms of the \n"+
286 "MIT X11 or GNU GPL licenses\n\n" +
288 "For more information on Mono, visit the project Web site\n" +
289 " http://www.mono-project.com\n\n" +
291 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
292 Environment.Exit (0);
295 public static int Main (string[] args)
297 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
298 var crp = new ConsoleReportPrinter ();
299 Driver d = Driver.Create (args, true, crp);
303 crp.Fatal = d.fatal_errors;
305 if (d.Compile () && d.Report.Errors == 0) {
306 if (d.Report.Warnings > 0) {
307 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
309 Environment.Exit (0);
314 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
315 d.Report.Errors, d.Report.Warnings);
316 Environment.Exit (1);
320 void Error6 (string name, string log)
322 if (log != null && log.Length > 0)
323 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
324 Report.Error (6, "cannot find metadata file `{0}'", name);
327 void Error9 (string type, string filename, 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 (9, "file `{0}' has invalid `{1}' metadata", filename, type);
334 void BadAssembly (string filename, string log)
336 MethodInfo adder_method = null; // AssemblyDefinition.AddModule_Method;
338 if (adder_method != null) {
339 AssemblyName an = new AssemblyName ();
341 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
345 m = adder_method.Invoke (ab, new object [] { filename });
346 } catch (TargetInvocationException ex) {
347 throw ex.InnerException;
351 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
352 Path.GetFileName (filename));
355 } catch (FileNotFoundException) {
356 // did the file get deleted during compilation? who cares? swallow the exception
357 } catch (BadImageFormatException) {
359 } catch (FileLoadException) {
363 Error9 ("assembly", filename, log);
366 public Assembly LoadAssemblyFile (string assembly, bool soft)
369 string total_log = "";
373 char[] path_chars = { '/', '\\' };
375 if (assembly.IndexOfAny (path_chars) != -1) {
376 a = Assembly.LoadFrom (assembly);
378 string ass = assembly;
379 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
380 ass = assembly.Substring (0, assembly.Length - 4);
381 a = Assembly.Load (ass);
383 } catch (FileNotFoundException) {
385 foreach (string dir in link_paths) {
386 string full_path = Path.Combine (dir, assembly);
387 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
391 a = Assembly.LoadFrom (full_path);
394 } catch (FileNotFoundException ff) {
397 total_log += ff.FusionLog;
401 Error6 (assembly, total_log);
405 } catch (BadImageFormatException f) {
406 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
407 BadAssembly (f.FileName, f.FusionLog);
408 } catch (FileLoadException f) {
409 // ... while .NET 1.1 throws this
410 BadAssembly (f.FileName, f.FusionLog);
416 void LoadModule (AssemblyDefinition assembly, string module)
418 string total_log = "";
422 assembly.AddModule (module);
423 } catch (FileNotFoundException) {
425 foreach (string dir in link_paths) {
426 string full_path = Path.Combine (dir, module);
427 if (!module.EndsWith (".netmodule"))
428 full_path += ".netmodule";
431 assembly.AddModule (full_path);
434 } catch (FileNotFoundException ff) {
435 total_log += ff.FusionLog;
439 Error6 (module, total_log);
443 } catch (BadImageFormatException f) {
444 Error9 ("module", f.FileName, f.FusionLog);
445 } catch (FileLoadException f) {
446 Error9 ("module", f.FileName, f.FusionLog);
451 /// Loads all assemblies referenced on the command line
453 public void LoadReferences (ModuleContainer module)
455 link_paths.Add (GetSystemDir ());
456 link_paths.Add (Directory.GetCurrentDirectory ());
458 var loaded = new List<Tuple<RootNamespace, Assembly>> ();
461 // Load Core Library for default compilation
463 if (RootContext.StdLib) {
464 a = LoadAssemblyFile ("mscorlib", false);
466 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
469 foreach (string r in soft_references) {
470 a = LoadAssemblyFile (r, true);
472 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
475 foreach (string r in references) {
476 a = LoadAssemblyFile (r, false);
480 var key = Tuple.Create (module.GlobalRootNamespace, a);
481 if (loaded.Contains (key))
487 foreach (var entry in external_aliases) {
488 a = LoadAssemblyFile (entry.Value, false);
492 var key = Tuple.Create (module.CreateRootNamespace (entry.Key), a);
493 if (loaded.Contains (key))
499 foreach (var entry in loaded) {
500 ctx.MetaImporter.ImportAssembly (entry.Item2, entry.Item1);
504 void LoadModules (AssemblyDefinition assembly)
506 if (modules.Count == 0)
509 foreach (var module in modules) {
510 LoadModule (assembly, module);
514 static string [] LoadArgs (string file)
517 var args = new List<string> ();
520 f = new StreamReader (file);
525 StringBuilder sb = new StringBuilder ();
527 while ((line = f.ReadLine ()) != null){
530 for (int i = 0; i < t; i++){
533 if (c == '"' || c == '\''){
536 for (i++; i < t; i++){
543 } else if (c == ' '){
545 args.Add (sb.ToString ());
552 args.Add (sb.ToString ());
557 return args.ToArray ();
561 // Returns the directory where the system assemblies are installed
563 static string GetSystemDir ()
565 return Path.GetDirectoryName (typeof (object).Assembly.Location);
569 // Given a path specification, splits the path from the file/pattern
571 static void SplitPathAndPattern (string spec, out string path, out string pattern)
573 int p = spec.LastIndexOf ('/');
576 // Windows does not like /file.cs, switch that to:
581 pattern = spec.Substring (1);
583 path = spec.Substring (0, p);
584 pattern = spec.Substring (p + 1);
589 p = spec.LastIndexOf ('\\');
591 path = spec.Substring (0, p);
592 pattern = spec.Substring (p + 1);
600 void AddSourceFile (string f)
602 if (first_source == null)
605 Location.AddFile (Report, f);
608 bool ParseArguments (string[] args, bool require_files)
610 references = new List<string> ();
611 external_aliases = new Dictionary<string, string> ();
612 soft_references = new List<string> ();
613 modules = new List<string> (2);
614 link_paths = new List<string> ();
616 List<string> response_file_list = null;
617 bool parsing_options = true;
619 for (int i = 0; i < args.Length; i++) {
620 string arg = args [i];
624 if (arg [0] == '@') {
625 string [] extra_args;
626 string response_file = arg.Substring (1);
628 if (response_file_list == null)
629 response_file_list = new List<string> ();
631 if (response_file_list.Contains (response_file)) {
633 1515, "Response file `" + response_file +
634 "' specified multiple times");
638 response_file_list.Add (response_file);
640 extra_args = LoadArgs (response_file);
641 if (extra_args == null) {
642 Report.Error (2011, "Unable to open response file: " +
647 args = AddArgs (args, extra_args);
651 if (parsing_options) {
653 parsing_options = false;
657 if (arg [0] == '-') {
658 if (UnixParseOption (arg, ref args, ref i))
662 string csc_opt = "/" + arg.Substring (1);
663 if (CSCParseOption (csc_opt, ref args))
666 Error_WrongOption (arg);
669 if (arg [0] == '/') {
670 if (CSCParseOption (arg, ref args))
673 // Need to skip `/home/test.cs' however /test.cs is considered as error
674 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
675 Error_WrongOption (arg);
681 ProcessSourceFiles (arg, false);
684 if (require_files == false)
688 // If we are an exe, require a source file for the entry point
690 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
691 if (first_source == null) {
692 Report.Error (2008, "No files to compile were specified");
699 // If there is nothing to put in the assembly, and we are not a library
701 if (first_source == null && embedded_resources == null) {
702 Report.Error (2008, "No files to compile were specified");
709 public void Parse (ModuleContainer module)
711 Location.Initialize ();
713 var cu = Location.SourceFiles;
714 for (int i = 0; i < cu.Count; ++i) {
716 tokenize_file (cu [i], ctx);
718 Parse (cu [i], module);
723 void ProcessSourceFiles (string spec, bool recurse)
725 string path, pattern;
727 SplitPathAndPattern (spec, out path, out pattern);
728 if (pattern.IndexOf ('*') == -1){
729 AddSourceFile (spec);
733 string [] files = null;
735 files = Directory.GetFiles (path, pattern);
736 } catch (System.IO.DirectoryNotFoundException) {
737 Report.Error (2001, "Source file `" + spec + "' could not be found");
739 } catch (System.IO.IOException){
740 Report.Error (2001, "Source file `" + spec + "' could not be found");
743 foreach (string f in files) {
750 string [] dirs = null;
753 dirs = Directory.GetDirectories (path);
757 foreach (string d in dirs) {
759 // Don't include path in this string, as each
760 // directory entry already does
761 ProcessSourceFiles (d + "/" + pattern, true);
765 public void ProcessDefaultConfig ()
767 if (!load_default_config)
771 // For now the "default config" is harcoded into the compiler
772 // we can move this outside later
774 string [] default_config = {
780 "System.Windows.Browser",
784 // Is it worth pre-loading all this stuff?
787 "System.Configuration.Install",
790 "System.DirectoryServices",
791 "System.Drawing.Design",
793 "System.EnterpriseServices",
796 "System.Runtime.Remoting",
797 "System.Runtime.Serialization.Formatters.Soap",
799 "System.ServiceProcess",
801 "System.Web.RegularExpressions",
802 "System.Web.Services",
803 "System.Windows.Forms"
807 soft_references.AddRange (default_config);
809 if (RootContext.Version > LanguageVersion.ISO_2)
810 soft_references.Add ("System.Core");
811 if (RootContext.Version > LanguageVersion.V_3)
812 soft_references.Add ("Microsoft.CSharp");
815 public static string OutputFile
821 return Path.GetFileName (output_file);
825 void SetWarningLevel (string s)
830 level = Int32.Parse (s);
833 if (level < 0 || level > 4){
834 Report.Error (1900, "Warning level must be in the range 0-4");
837 Report.WarningLevel = level;
840 static void Version ()
842 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
843 Console.WriteLine ("Mono C# compiler version {0}", version);
844 Environment.Exit (0);
848 // Currently handles the Unix-like command line options, but will be
849 // deprecated in favor of the CSCParseOption, which will also handle the
850 // options that start with a dash in the future.
852 bool UnixParseOption (string arg, ref string [] args, ref int i)
856 CSharpParser.yacc_verbose_flag++;
867 case "--main": case "-m":
868 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
869 if ((i + 1) >= args.Length){
871 Environment.Exit (1);
873 RootContext.MainClass = args [++i];
877 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
878 RootContext.Unsafe = true;
881 case "/?": case "/h": case "/help":
884 Environment.Exit (0);
888 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
889 if ((i + 1) >= args.Length){
891 Environment.Exit (1);
893 RootContext.AddConditional (args [++i]);
902 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
903 if ((i + 1) >= args.Length){
905 Environment.Exit (1);
907 OutputFile = args [++i];
911 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
912 RootContext.Checked = true;
916 Report.Printer.Stacktrace = true;
919 case "--linkresource":
921 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
922 if ((i + 1) >= args.Length){
924 Report.Error (5, "Missing argument to --linkres");
925 Environment.Exit (1);
927 if (embedded_resources == null)
928 embedded_resources = new Resources (ctx);
930 embedded_resources.Add (false, args [++i], args [i]);
935 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
936 if ((i + 1) >= args.Length){
938 Report.Error (5, "Missing argument to --resource");
939 Environment.Exit (1);
941 if (embedded_resources == null)
942 embedded_resources = new Resources (ctx);
944 embedded_resources.Add (true, args [++i], args [i]);
948 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
949 if ((i + 1) >= args.Length){
950 Environment.Exit (1);
954 string type = args [++i];
957 RootContext.Target = Target.Library;
958 RootContext.TargetExt = ".dll";
962 RootContext.Target = Target.Exe;
966 RootContext.Target = Target.WinExe;
970 RootContext.Target = Target.Module;
971 RootContext.TargetExt = ".dll";
980 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
981 if ((i + 1) >= args.Length){
983 Environment.Exit (1);
986 string val = args [++i];
987 int idx = val.IndexOf ('=');
989 string alias = val.Substring (0, idx);
990 string assembly = val.Substring (idx + 1);
991 AddExternAlias (alias, assembly);
995 references.Add (val);
999 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
1000 if ((i + 1) >= args.Length){
1002 Environment.Exit (1);
1004 link_paths.Add (args [++i]);
1008 RootContext.EnhancedWarnings = true;
1012 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1013 RootContext.StdLib = false;
1017 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1018 if ((i + 1) >= args.Length){
1020 Environment.Exit (1);
1025 warn = Int32.Parse (args [++i]);
1028 Environment.Exit (1);
1030 Report.SetIgnoreWarning (warn);
1034 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1035 if ((i + 1) >= args.Length){
1038 "--wlevel requires a value from 0 to 4");
1039 Environment.Exit (1);
1042 SetWarningLevel (args [++i]);
1046 if ((i + 1) >= args.Length){
1047 Report.Error (5, "--mcs-debug requires an argument");
1048 Environment.Exit (1);
1052 Report.DebugFlags = Int32.Parse (args [++i]);
1054 Report.Error (5, "Invalid argument to --mcs-debug");
1055 Environment.Exit (1);
1064 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1065 if ((i + 1) >= args.Length){
1066 Report.Error (5, "--recurse requires an argument");
1067 Environment.Exit (1);
1069 ProcessSourceFiles (args [++i], true);
1076 case "--debug": case "-g":
1077 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1078 RootContext.GenerateDebugInfo = true;
1082 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1083 load_default_config = false;
1087 if (arg.StartsWith ("--fatal")){
1088 if (arg.StartsWith ("--fatal=")){
1089 if (!Int32.TryParse (arg.Substring (8), out fatal_errors))
1102 public static string GetPackageFlags (string packages, bool fatal, Report report)
1104 ProcessStartInfo pi = new ProcessStartInfo ();
1105 pi.FileName = "pkg-config";
1106 pi.RedirectStandardOutput = true;
1107 pi.UseShellExecute = false;
1108 pi.Arguments = "--libs " + packages;
1111 p = Process.Start (pi);
1112 } catch (Exception e) {
1113 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1115 Environment.Exit (1);
1120 if (p.StandardOutput == null){
1121 report.Warning (-27, 1, "Specified package did not return any information");
1125 string pkgout = p.StandardOutput.ReadToEnd ();
1127 if (p.ExitCode != 0) {
1128 report.Error (-27, "Error running pkg-config. Check the above output.");
1130 Environment.Exit (1);
1141 // This parses the -arg and /arg options to the compiler, even if the strings
1142 // in the following text use "/arg" on the strings.
1144 bool CSCParseOption (string option, ref string [] args)
1146 int idx = option.IndexOf (':');
1153 arg = option.Substring (0, idx);
1155 value = option.Substring (idx + 1);
1158 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1166 RootContext.Target = Target.Exe;
1170 RootContext.Target = Target.WinExe;
1174 RootContext.Target = Target.Library;
1175 RootContext.TargetExt = ".dll";
1179 RootContext.Target = Target.Module;
1180 RootContext.TargetExt = ".netmodule";
1190 if (value.Length == 0){
1192 Environment.Exit (1);
1201 RootContext.Optimize = true;
1206 RootContext.Optimize = false;
1209 // TODO: Not supported by csc 3.5+
1210 case "/incremental":
1211 case "/incremental+":
1212 case "/incremental-":
1218 if (value.Length == 0){
1220 Environment.Exit (1);
1223 foreach (string d in value.Split (argument_value_separator)) {
1224 string conditional = d.Trim ();
1225 if (!Tokenizer.IsValidIdentifier (conditional)) {
1226 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
1229 RootContext.AddConditional (conditional);
1236 // We should collect data, runtime, etc and store in the file specified
1238 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1244 if (value.Length == 0){
1246 Environment.Exit (1);
1248 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1249 string pkgout = GetPackageFlags (packages, true, Report);
1251 if (pkgout != null){
1252 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1253 Split (new Char [] { ' ', '\t'});
1254 args = AddArgs (args, xargs);
1261 case "/linkresource":
1264 if (embedded_resources == null)
1265 embedded_resources = new Resources (ctx);
1267 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1268 string[] s = value.Split (argument_value_separator);
1271 if (s[0].Length == 0)
1273 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1276 embedded_resources.Add (embeded, s [0], s [1]);
1279 if (s [2] != "public" && s [2] != "private") {
1280 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1283 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1286 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1293 if (value.Length == 0){
1294 Report.Error (5, "-recurse requires an argument");
1295 Environment.Exit (1);
1297 ProcessSourceFiles (value, true);
1301 case "/reference": {
1302 if (value.Length == 0){
1303 Report.Error (5, "-reference requires an argument");
1304 Environment.Exit (1);
1307 string[] refs = value.Split (argument_value_separator);
1308 foreach (string r in refs){
1310 int index = val.IndexOf ('=');
1312 string alias = r.Substring (0, index);
1313 string assembly = r.Substring (index + 1);
1314 AddExternAlias (alias, assembly);
1318 if (val.Length != 0)
1319 references.Add (val);
1323 case "/addmodule": {
1324 if (value.Length == 0){
1325 Report.Error (5, arg + " requires an argument");
1326 Environment.Exit (1);
1329 string[] refs = value.Split (argument_value_separator);
1330 foreach (string r in refs){
1336 if (value.Length == 0) {
1337 Report.Error (5, arg + " requires an argument");
1338 Environment.Exit (1);
1341 if (win32IconFile != null)
1342 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1344 win32ResourceFile = value;
1347 case "/win32icon": {
1348 if (value.Length == 0) {
1349 Report.Error (5, arg + " requires an argument");
1350 Environment.Exit (1);
1353 if (win32ResourceFile != null)
1354 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1356 win32IconFile = value;
1360 if (value.Length == 0){
1361 Report.Error (2006, arg + " requires an argument");
1362 Environment.Exit (1);
1364 RootContext.Documentation = new Documentation (value);
1370 if (value.Length == 0){
1371 Report.Error (5, "/lib requires an argument");
1372 Environment.Exit (1);
1375 libdirs = value.Split (argument_value_separator);
1376 foreach (string dir in libdirs)
1377 link_paths.Add (dir);
1382 RootContext.GenerateDebugInfo = false;
1386 if (value == "full" || value == "")
1387 RootContext.GenerateDebugInfo = true;
1392 RootContext.GenerateDebugInfo = true;
1397 RootContext.Checked = true;
1401 RootContext.Checked = false;
1409 RootContext.VerifyClsCompliance = false;
1414 RootContext.Unsafe = true;
1418 RootContext.Unsafe = false;
1421 case "/warnaserror":
1422 case "/warnaserror+":
1423 if (value.Length == 0) {
1424 Report.WarningsAreErrors = true;
1426 foreach (string wid in value.Split (argument_value_separator))
1427 Report.AddWarningAsError (wid);
1431 case "/warnaserror-":
1432 if (value.Length == 0) {
1433 Report.WarningsAreErrors = false;
1435 foreach (string wid in value.Split (argument_value_separator))
1436 Report.RemoveWarningAsError (wid);
1441 SetWarningLevel (value);
1447 if (value.Length == 0){
1448 Report.Error (5, "/nowarn requires an argument");
1449 Environment.Exit (1);
1452 warns = value.Split (argument_value_separator);
1453 foreach (string wc in warns){
1455 if (wc.Trim ().Length == 0)
1458 int warn = Int32.Parse (wc);
1460 throw new ArgumentOutOfRangeException("warn");
1462 Report.SetIgnoreWarning (warn);
1464 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1471 load_default_config = false;
1475 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1477 RootContext.Platform = Platform.AnyCPU;
1480 RootContext.Platform = Platform.X86;
1483 RootContext.Platform = Platform.X64;
1486 RootContext.Platform = Platform.IA64;
1489 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1495 // We just ignore this.
1496 case "/errorreport":
1502 Environment.Exit(0);
1508 Environment.Exit (0);
1513 if (value.Length == 0){
1514 Report.Error (5, arg + " requires an argument");
1515 Environment.Exit (1);
1517 RootContext.MainClass = value;
1522 RootContext.StdLib = false;
1526 RootContext.StdLib = true;
1533 if (value == String.Empty) {
1534 Report.Error (5, arg + " requires an argument");
1535 Environment.Exit (1);
1537 RootContext.StrongNameKeyFile = value;
1539 case "/keycontainer":
1540 if (value == String.Empty) {
1541 Report.Error (5, arg + " requires an argument");
1542 Environment.Exit (1);
1544 RootContext.StrongNameKeyContainer = value;
1548 RootContext.StrongNameDelaySign = true;
1551 RootContext.StrongNameDelaySign = false;
1554 case "/langversion":
1555 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1557 RootContext.Version = LanguageVersion.ISO_1;
1560 RootContext.Version = LanguageVersion.Default;
1561 RootContext.AddConditional ("__V2__");
1564 RootContext.Version = LanguageVersion.ISO_2;
1567 RootContext.Version = LanguageVersion.V_3;
1570 RootContext.Version = LanguageVersion.Future;
1574 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1580 encoding = new UTF8Encoding();
1583 encoding = Encoding.Default;
1587 encoding = Encoding.GetEncoding (
1588 Int32.Parse (value));
1590 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1600 void Error_WrongOption (string option)
1602 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1605 static string [] AddArgs (string [] args, string [] extra_args)
1608 new_args = new string [extra_args.Length + args.Length];
1610 // if args contains '--' we have to take that into account
1611 // split args into first half and second half based on '--'
1612 // and add the extra_args before --
1613 int split_position = Array.IndexOf (args, "--");
1614 if (split_position != -1)
1616 Array.Copy (args, new_args, split_position);
1617 extra_args.CopyTo (new_args, split_position);
1618 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1622 args.CopyTo (new_args, 0);
1623 extra_args.CopyTo (new_args, args.Length);
1629 void AddExternAlias (string identifier, string assembly)
1631 if (assembly.Length == 0) {
1632 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1636 if (!IsExternAliasValid (identifier)) {
1637 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1641 // Could here hashtable throw an exception?
1642 external_aliases [identifier] = assembly;
1645 static bool IsExternAliasValid (string identifier)
1647 if (identifier.Length == 0)
1649 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1652 for (int i = 1; i < identifier.Length; i++) {
1653 char c = identifier [i];
1654 if (Char.IsLetter (c) || Char.IsDigit (c))
1657 UnicodeCategory category = Char.GetUnicodeCategory (c);
1658 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1659 category != UnicodeCategory.SpacingCombiningMark ||
1660 category != UnicodeCategory.ConnectorPunctuation)
1668 // Main compilation method
1670 public bool Compile ()
1672 var module = new ModuleContainer (ctx);
1673 RootContext.ToplevelTypes = module;
1675 var ctypes = TypeManager.InitCoreTypes ();
1678 stopwatch = Stopwatch.StartNew ();
1679 first_time = DateTime.Now;
1683 ShowTime ("Parsing source files");
1685 if (Report.Errors > 0)
1688 if (tokenize || parse_only)
1691 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1692 throw new InternalErrorException ("who set it?");
1694 ProcessDefaultConfig ();
1699 if (output_file == null){
1700 if (first_source == null){
1701 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1705 int pos = first_source.LastIndexOf ('.');
1708 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1710 output_file = first_source + RootContext.TargetExt;
1714 // Load assemblies required
1717 stopwatch = Stopwatch.StartNew ();
1719 ctx.MetaImporter.Initialize ();
1721 var assembly = module.MakeExecutable (output_file, output_file);
1723 LoadReferences (module);
1725 ShowTime ("Imporing referenced assemblies");
1727 if (!TypeManager.InitCoreTypes (module, ctypes))
1730 TypeManager.InitOptionalCoreTypes (ctx);
1732 ShowTime ("Initializing predefined types");
1734 if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
1737 LoadModules (assembly);
1741 ShowTime ("Types definition");
1743 if (Report.Errors > 0)
1746 if (Report.Errors == 0 &&
1747 RootContext.Documentation != null &&
1748 !RootContext.Documentation.OutputDocComment (
1749 output_file, Report))
1753 // Verify using aliases now
1755 NamespaceEntry.VerifyAllUsing ();
1757 if (Report.Errors > 0){
1761 assembly.Resolve ();
1763 if (Report.Errors > 0)
1767 // The code generator
1770 stopwatch = Stopwatch.StartNew ();
1774 ShowTime ("Resolving and emitting members blocks");
1776 if (Report.Errors > 0){
1780 module.CloseType ();
1782 ShowTime ("Closing types");
1784 PEFileKinds k = PEFileKinds.ConsoleApplication;
1786 switch (RootContext.Target) {
1787 case Target.Library:
1789 k = PEFileKinds.Dll; break;
1791 k = PEFileKinds.ConsoleApplication; break;
1793 k = PEFileKinds.WindowApplication; break;
1796 if (RootContext.NeedsEntryPoint) {
1797 Method ep = module.EntryPoint;
1800 if (RootContext.MainClass != null) {
1801 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1802 if (main_cont == null) {
1803 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1807 if (!(main_cont is ClassOrStruct)) {
1808 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1812 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1816 if (Report.Errors == 0)
1817 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1822 assembly.Builder.SetEntryPoint (ep.MethodBuilder, k);
1823 } else if (RootContext.MainClass != null) {
1824 Report.Error (2017, "Cannot specify -main if building a module or library");
1827 if (embedded_resources != null){
1828 if (RootContext.Target == Target.Module) {
1829 Report.Error (1507, "Cannot link resource file when building a module");
1833 embedded_resources.Emit (assembly);
1837 // Add Win32 resources
1840 if (win32ResourceFile != null) {
1842 assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1843 } catch (ArgumentException) {
1844 Report.RuntimeMissingSupport (Location.Null, "resource embedding ");
1847 assembly.Builder.DefineVersionInfoResource ();
1850 if (win32IconFile != null) {
1851 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1852 if (define_icon == null) {
1853 Report.RuntimeMissingSupport (Location.Null, "resource embedding");
1855 define_icon.Invoke (assembly.Builder, new object [] { win32IconFile });
1859 if (Report.Errors > 0)
1863 stopwatch = Stopwatch.StartNew ();
1867 ShowTime ("Saving output assembly");
1869 if (RootContext.GenerateDebugInfo) {
1870 SymbolWriter.WriteSymbolFile ();
1871 ShowTime ("Saving debug symbols");
1874 ShowTotalTime ("Total");
1876 Timer.ShowTimers ();
1878 return (Report.Errors == 0);
1886 void Emit (AssemblyDefinition assembly);
1887 string FileName { get; }
1890 class EmbededResource : IResource
1892 static MethodInfo embed_res;
1893 readonly object[] args;
1895 public EmbededResource (string name, string file, bool isPrivate)
1897 args = new object [3];
1900 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1903 public void Emit (AssemblyDefinition assembly)
1905 if (embed_res == null) {
1906 var argst = new [] {
1907 typeof (string), typeof (string), typeof (ResourceAttributes)
1910 embed_res = typeof (AssemblyBuilder).GetMethod (
1911 "EmbedResourceFile", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
1912 null, CallingConventions.Any, argst, null);
1914 if (embed_res == null) {
1915 assembly.Compiler.Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1919 embed_res.Invoke (assembly.Builder, args);
1922 public string FileName {
1924 return (string)args [1];
1929 class LinkedResource : IResource
1931 readonly string file;
1932 readonly string name;
1933 readonly ResourceAttributes attribute;
1935 public LinkedResource (string name, string file, bool isPrivate)
1939 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1942 public void Emit (AssemblyDefinition assembly)
1944 assembly.Builder.AddResourceFile (name, Path.GetFileName (file), attribute);
1947 public string FileName {
1955 Dictionary<string, IResource> embedded_resources = new Dictionary<string, IResource> ();
1956 readonly CompilerContext ctx;
1958 public Resources (CompilerContext ctx)
1963 public void Add (bool embeded, string file, string name)
1965 Add (embeded, file, name, false);
1968 public void Add (bool embeded, string file, string name, bool isPrivate)
1970 if (embedded_resources.ContainsKey (name)) {
1971 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1974 IResource r = embeded ?
1975 (IResource) new EmbededResource (name, file, isPrivate) :
1976 new LinkedResource (name, file, isPrivate);
1978 embedded_resources.Add (name, r);
1981 public void Emit (AssemblyDefinition assembly)
1983 foreach (IResource r in embedded_resources.Values) {
1984 if (!File.Exists (r.FileName)) {
1985 ctx.Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1995 // This is the only public entry point
1997 public class CompilerCallableEntryPoint : MarshalByRefObject {
1998 public static bool InvokeCompiler (string [] args, TextWriter error)
2001 StreamReportPrinter srp = new StreamReportPrinter (error);
2002 Driver d = Driver.Create (args, true, srp);
2006 return d.Compile () && srp.ErrorsCount == 0;
2012 public static int[] AllWarningNumbers {
2014 return Report.AllWarnings;
2018 public static void Reset ()
2023 public static void PartialReset ()
2028 public static void Reset (bool full_flag)
2031 CSharpParser.yacc_verbose_flag = 0;
2037 RootContext.Reset (full_flag);
2038 TypeManager.Reset ();
2039 ArrayContainer.Reset ();
2040 ReferenceContainer.Reset ();
2041 PointerContainer.Reset ();
2045 UnaryMutator.Reset ();
2047 ConstantFold.Reset ();
2048 CastFromDecimal.Reset ();
2049 StringConcat.Reset ();
2051 NamespaceEntry.Reset ();
2053 AnonymousTypeClass.Reset ();
2054 AnonymousMethodBody.Reset ();
2055 AnonymousMethodStorey.Reset ();
2056 SymbolWriter.Reset ();
2058 Linq.QueryBlock.TransparentParameter.Reset ();