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 public void LoadAssembly (string assembly, bool soft)
322 LoadAssembly (assembly, null, soft);
325 void Error6 (string name, 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 (6, "cannot find metadata file `{0}'", name);
332 void Error9 (string type, string filename, string log)
334 if (log != null && log.Length > 0)
335 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
336 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
339 void BadAssembly (string filename, string log)
341 MethodInfo adder_method = AssemblyDefinition.AddModule_Method;
343 if (adder_method != null) {
344 AssemblyName an = new AssemblyName ();
346 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
350 m = adder_method.Invoke (ab, new object [] { filename });
351 } catch (TargetInvocationException ex) {
352 throw ex.InnerException;
356 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
357 Path.GetFileName (filename));
360 } catch (FileNotFoundException) {
361 // did the file get deleted during compilation? who cares? swallow the exception
362 } catch (BadImageFormatException) {
364 } catch (FileLoadException) {
368 Error9 ("assembly", filename, log);
371 public void LoadAssembly (string assembly, string alias, bool soft)
374 string total_log = "";
378 char[] path_chars = { '/', '\\' };
380 if (assembly.IndexOfAny (path_chars) != -1) {
381 a = Assembly.LoadFrom (assembly);
383 string ass = assembly;
384 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
385 ass = assembly.Substring (0, assembly.Length - 4);
386 a = Assembly.Load (ass);
388 } catch (FileNotFoundException) {
390 foreach (string dir in link_paths) {
391 string full_path = Path.Combine (dir, assembly);
392 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
396 a = Assembly.LoadFrom (full_path);
399 } catch (FileNotFoundException ff) {
402 total_log += ff.FusionLog;
406 Error6 (assembly, total_log);
411 // Extern aliased refs require special handling
413 ctx.GlobalRootNamespace.AddAssemblyReference (a);
415 ctx.GlobalRootNamespace.DefineRootNamespace (alias, a, ctx);
417 } catch (BadImageFormatException f) {
418 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
419 BadAssembly (f.FileName, f.FusionLog);
420 } catch (FileLoadException f) {
421 // ... while .NET 1.1 throws this
422 BadAssembly (f.FileName, f.FusionLog);
426 public void LoadModule (AssemblyDefinition assembly, string module)
429 string total_log = "";
433 m = assembly.AddModule (module);
434 } catch (FileNotFoundException) {
436 foreach (string dir in link_paths) {
437 string full_path = Path.Combine (dir, module);
438 if (!module.EndsWith (".netmodule"))
439 full_path += ".netmodule";
442 m = assembly.AddModule (full_path);
445 } catch (FileNotFoundException ff) {
446 total_log += ff.FusionLog;
450 Error6 (module, total_log);
455 ctx.GlobalRootNamespace.AddModuleReference (m);
457 } catch (BadImageFormatException f) {
458 Error9 ("module", f.FileName, f.FusionLog);
459 } catch (FileLoadException f) {
460 Error9 ("module", f.FileName, f.FusionLog);
465 /// Loads all assemblies referenced on the command line
467 public void LoadReferences ()
469 link_paths.Add (GetSystemDir ());
470 link_paths.Add (Directory.GetCurrentDirectory ());
473 // Load Core Library for default compilation
475 if (RootContext.StdLib)
476 LoadAssembly ("mscorlib", false);
478 foreach (string r in soft_references)
479 LoadAssembly (r, true);
481 foreach (string r in references)
482 LoadAssembly (r, false);
484 foreach (var entry in external_aliases)
485 LoadAssembly (entry.Value, entry.Key, false);
487 if (modules.Count > 0) {
488 foreach (string module in modules)
489 LoadModule (null, module);
492 ctx.GlobalRootNamespace.ComputeNamespaces (ctx);
495 static string [] LoadArgs (string file)
498 var args = new List<string> ();
501 f = new StreamReader (file);
506 StringBuilder sb = new StringBuilder ();
508 while ((line = f.ReadLine ()) != null){
511 for (int i = 0; i < t; i++){
514 if (c == '"' || c == '\''){
517 for (i++; i < t; i++){
524 } else if (c == ' '){
526 args.Add (sb.ToString ());
533 args.Add (sb.ToString ());
538 return args.ToArray ();
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 List<string> ();
592 external_aliases = new Dictionary<string, string> ();
593 soft_references = new List<string> ();
594 modules = new List<string> (2);
595 link_paths = new List<string> ();
597 List<string> 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 List<string> ();
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");
690 public void Parse (ModuleContainer module)
692 Location.Initialize ();
694 var cu = Location.SourceFiles;
695 for (int i = 0; i < cu.Count; ++i) {
697 tokenize_file (cu [i], ctx);
699 Parse (cu [i], module);
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 RootContext.EnhancedWarnings = true;
993 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
994 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);
1057 case "--debug": case "-g":
1058 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1059 RootContext.GenerateDebugInfo = true;
1063 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1064 load_default_config = false;
1068 if (arg.StartsWith ("--fatal")){
1069 if (arg.StartsWith ("--fatal=")){
1070 if (!Int32.TryParse (arg.Substring (8), out fatal_errors))
1083 public static string GetPackageFlags (string packages, bool fatal, Report report)
1085 ProcessStartInfo pi = new ProcessStartInfo ();
1086 pi.FileName = "pkg-config";
1087 pi.RedirectStandardOutput = true;
1088 pi.UseShellExecute = false;
1089 pi.Arguments = "--libs " + packages;
1092 p = Process.Start (pi);
1093 } catch (Exception e) {
1094 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1096 Environment.Exit (1);
1101 if (p.StandardOutput == null){
1102 report.Warning (-27, 1, "Specified package did not return any information");
1106 string pkgout = p.StandardOutput.ReadToEnd ();
1108 if (p.ExitCode != 0) {
1109 report.Error (-27, "Error running pkg-config. Check the above output.");
1111 Environment.Exit (1);
1122 // This parses the -arg and /arg options to the compiler, even if the strings
1123 // in the following text use "/arg" on the strings.
1125 bool CSCParseOption (string option, ref string [] args)
1127 int idx = option.IndexOf (':');
1134 arg = option.Substring (0, idx);
1136 value = option.Substring (idx + 1);
1139 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1147 RootContext.Target = Target.Exe;
1151 RootContext.Target = Target.WinExe;
1155 RootContext.Target = Target.Library;
1156 RootContext.TargetExt = ".dll";
1160 RootContext.Target = Target.Module;
1161 RootContext.TargetExt = ".netmodule";
1171 if (value.Length == 0){
1173 Environment.Exit (1);
1182 RootContext.Optimize = true;
1187 RootContext.Optimize = false;
1190 // TODO: Not supported by csc 3.5+
1191 case "/incremental":
1192 case "/incremental+":
1193 case "/incremental-":
1199 if (value.Length == 0){
1201 Environment.Exit (1);
1204 foreach (string d in value.Split (argument_value_separator)) {
1205 string conditional = d.Trim ();
1206 if (!Tokenizer.IsValidIdentifier (conditional)) {
1207 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
1210 RootContext.AddConditional (conditional);
1217 // We should collect data, runtime, etc and store in the file specified
1219 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1225 if (value.Length == 0){
1227 Environment.Exit (1);
1229 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1230 string pkgout = GetPackageFlags (packages, true, Report);
1232 if (pkgout != null){
1233 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1234 Split (new Char [] { ' ', '\t'});
1235 args = AddArgs (args, xargs);
1242 case "/linkresource":
1245 if (embedded_resources == null)
1246 embedded_resources = new Resources (ctx);
1248 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1249 string[] s = value.Split (argument_value_separator);
1252 if (s[0].Length == 0)
1254 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1257 embedded_resources.Add (embeded, s [0], s [1]);
1260 if (s [2] != "public" && s [2] != "private") {
1261 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1264 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1267 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1274 if (value.Length == 0){
1275 Report.Error (5, "-recurse requires an argument");
1276 Environment.Exit (1);
1278 ProcessSourceFiles (value, true);
1282 case "/reference": {
1283 if (value.Length == 0){
1284 Report.Error (5, "-reference requires an argument");
1285 Environment.Exit (1);
1288 string[] refs = value.Split (argument_value_separator);
1289 foreach (string r in refs){
1291 int index = val.IndexOf ('=');
1293 string alias = r.Substring (0, index);
1294 string assembly = r.Substring (index + 1);
1295 AddExternAlias (alias, assembly);
1299 if (val.Length != 0)
1300 references.Add (val);
1304 case "/addmodule": {
1305 if (value.Length == 0){
1306 Report.Error (5, arg + " requires an argument");
1307 Environment.Exit (1);
1310 string[] refs = value.Split (argument_value_separator);
1311 foreach (string r in refs){
1317 if (value.Length == 0) {
1318 Report.Error (5, arg + " requires an argument");
1319 Environment.Exit (1);
1322 if (win32IconFile != null)
1323 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1325 win32ResourceFile = value;
1328 case "/win32icon": {
1329 if (value.Length == 0) {
1330 Report.Error (5, arg + " requires an argument");
1331 Environment.Exit (1);
1334 if (win32ResourceFile != null)
1335 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1337 win32IconFile = value;
1341 if (value.Length == 0){
1342 Report.Error (2006, arg + " requires an argument");
1343 Environment.Exit (1);
1345 RootContext.Documentation = new Documentation (value);
1351 if (value.Length == 0){
1352 Report.Error (5, "/lib requires an argument");
1353 Environment.Exit (1);
1356 libdirs = value.Split (argument_value_separator);
1357 foreach (string dir in libdirs)
1358 link_paths.Add (dir);
1363 RootContext.GenerateDebugInfo = false;
1367 if (value == "full" || value == "")
1368 RootContext.GenerateDebugInfo = true;
1373 RootContext.GenerateDebugInfo = true;
1378 RootContext.Checked = true;
1382 RootContext.Checked = false;
1390 RootContext.VerifyClsCompliance = false;
1395 RootContext.Unsafe = true;
1399 RootContext.Unsafe = false;
1402 case "/warnaserror":
1403 case "/warnaserror+":
1404 if (value.Length == 0) {
1405 Report.WarningsAreErrors = true;
1407 foreach (string wid in value.Split (argument_value_separator))
1408 Report.AddWarningAsError (wid);
1412 case "/warnaserror-":
1413 if (value.Length == 0) {
1414 Report.WarningsAreErrors = false;
1416 foreach (string wid in value.Split (argument_value_separator))
1417 Report.RemoveWarningAsError (wid);
1422 SetWarningLevel (value);
1428 if (value.Length == 0){
1429 Report.Error (5, "/nowarn requires an argument");
1430 Environment.Exit (1);
1433 warns = value.Split (argument_value_separator);
1434 foreach (string wc in warns){
1436 if (wc.Trim ().Length == 0)
1439 int warn = Int32.Parse (wc);
1441 throw new ArgumentOutOfRangeException("warn");
1443 Report.SetIgnoreWarning (warn);
1445 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1452 load_default_config = false;
1456 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1458 RootContext.Platform = Platform.AnyCPU;
1461 RootContext.Platform = Platform.X86;
1464 RootContext.Platform = Platform.X64;
1467 RootContext.Platform = Platform.IA64;
1470 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1476 // We just ignore this.
1477 case "/errorreport":
1483 Environment.Exit(0);
1489 Environment.Exit (0);
1494 if (value.Length == 0){
1495 Report.Error (5, arg + " requires an argument");
1496 Environment.Exit (1);
1498 RootContext.MainClass = value;
1503 RootContext.StdLib = false;
1507 RootContext.StdLib = true;
1514 if (value == String.Empty) {
1515 Report.Error (5, arg + " requires an argument");
1516 Environment.Exit (1);
1518 RootContext.StrongNameKeyFile = value;
1520 case "/keycontainer":
1521 if (value == String.Empty) {
1522 Report.Error (5, arg + " requires an argument");
1523 Environment.Exit (1);
1525 RootContext.StrongNameKeyContainer = value;
1529 RootContext.StrongNameDelaySign = true;
1532 RootContext.StrongNameDelaySign = false;
1535 case "/langversion":
1536 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1538 RootContext.Version = LanguageVersion.ISO_1;
1541 RootContext.Version = LanguageVersion.Default;
1542 RootContext.AddConditional ("__V2__");
1545 RootContext.Version = LanguageVersion.ISO_2;
1548 RootContext.Version = LanguageVersion.V_3;
1551 RootContext.Version = LanguageVersion.Future;
1555 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1561 encoding = new UTF8Encoding();
1564 encoding = Encoding.Default;
1568 encoding = Encoding.GetEncoding (
1569 Int32.Parse (value));
1571 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1581 void Error_WrongOption (string option)
1583 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1586 static string [] AddArgs (string [] args, string [] extra_args)
1589 new_args = new string [extra_args.Length + args.Length];
1591 // if args contains '--' we have to take that into account
1592 // split args into first half and second half based on '--'
1593 // and add the extra_args before --
1594 int split_position = Array.IndexOf (args, "--");
1595 if (split_position != -1)
1597 Array.Copy (args, new_args, split_position);
1598 extra_args.CopyTo (new_args, split_position);
1599 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1603 args.CopyTo (new_args, 0);
1604 extra_args.CopyTo (new_args, args.Length);
1610 void AddExternAlias (string identifier, string assembly)
1612 if (assembly.Length == 0) {
1613 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1617 if (!IsExternAliasValid (identifier)) {
1618 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1622 // Could here hashtable throw an exception?
1623 external_aliases [identifier] = assembly;
1626 static bool IsExternAliasValid (string identifier)
1628 if (identifier.Length == 0)
1630 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1633 for (int i = 1; i < identifier.Length; i++) {
1634 char c = identifier [i];
1635 if (Char.IsLetter (c) || Char.IsDigit (c))
1638 UnicodeCategory category = Char.GetUnicodeCategory (c);
1639 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1640 category != UnicodeCategory.SpacingCombiningMark ||
1641 category != UnicodeCategory.ConnectorPunctuation)
1649 // Main compilation method
1651 public bool Compile ()
1653 var module = new ModuleContainer (ctx);
1654 RootContext.ToplevelTypes = module;
1656 var ctypes = TypeManager.InitCoreTypes ();
1659 stopwatch = Stopwatch.StartNew ();
1660 first_time = DateTime.Now;
1664 ShowTime ("Parsing source files");
1666 if (Report.Errors > 0)
1669 if (tokenize || parse_only)
1672 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1673 throw new InternalErrorException ("who set it?");
1675 ProcessDefaultConfig ();
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 ctx.GlobalRootNamespace.AddModuleReference (RootContext.ToplevelTypes.Builder);
1697 // Load assemblies required
1700 stopwatch = Stopwatch.StartNew ();
1702 ctx.MetaImporter.Initialize ();
1704 var assembly = module.MakeExecutable (output_file, output_file);
1708 ShowTime ("Imporing referenced assemblies");
1710 if (!TypeManager.InitCoreTypes (ctx, ctypes))
1713 TypeManager.InitOptionalCoreTypes (ctx);
1715 ShowTime ("Initializing predefined types");
1717 if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
1720 if (RootContext.Target == Target.Module) {
1721 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1722 if (module_only == null) {
1723 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1724 Environment.Exit (1);
1727 MethodInfo set_method = module_only.GetSetMethod (true);
1728 set_method.Invoke (assembly.Builder, BindingFlags.Default, null, new object[] { true }, null);
1733 ShowTime ("Types definition");
1735 if (Report.Errors > 0)
1738 if (Report.Errors == 0 &&
1739 RootContext.Documentation != null &&
1740 !RootContext.Documentation.OutputDocComment (
1741 output_file, Report))
1745 // Verify using aliases now
1747 NamespaceEntry.VerifyAllUsing ();
1749 if (Report.Errors > 0){
1753 assembly.Resolve ();
1755 if (RootContext.VerifyClsCompliance) {
1756 if (assembly.IsCLSCompliant) {
1757 AttributeTester.VerifyModulesClsCompliance (ctx);
1760 if (Report.Errors > 0)
1764 // The code generator
1767 stopwatch = Stopwatch.StartNew ();
1771 ShowTime ("Resolving and emitting members blocks");
1773 if (Report.Errors > 0){
1777 module.CloseType ();
1779 ShowTime ("Closing types");
1781 PEFileKinds k = PEFileKinds.ConsoleApplication;
1783 switch (RootContext.Target) {
1784 case Target.Library:
1786 k = PEFileKinds.Dll; break;
1788 k = PEFileKinds.ConsoleApplication; break;
1790 k = PEFileKinds.WindowApplication; break;
1793 if (RootContext.NeedsEntryPoint) {
1794 Method ep = module.EntryPoint;
1797 if (RootContext.MainClass != null) {
1798 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1799 if (main_cont == null) {
1800 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1804 if (!(main_cont is ClassOrStruct)) {
1805 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1809 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1813 if (Report.Errors == 0)
1814 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1819 assembly.Builder.SetEntryPoint (ep.MethodBuilder, k);
1820 } else if (RootContext.MainClass != null) {
1821 Report.Error (2017, "Cannot specify -main if building a module or library");
1824 if (embedded_resources != null){
1825 if (RootContext.Target == Target.Module) {
1826 Report.Error (1507, "Cannot link resource file when building a module");
1830 embedded_resources.Emit (assembly);
1834 // Add Win32 resources
1837 if (win32ResourceFile != null) {
1839 assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1840 } catch (ArgumentException) {
1841 Report.RuntimeMissingSupport (Location.Null, "resource embedding ");
1844 assembly.Builder.DefineVersionInfoResource ();
1847 if (win32IconFile != null) {
1848 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1849 if (define_icon == null) {
1850 Report.RuntimeMissingSupport (Location.Null, "resource embedding");
1852 define_icon.Invoke (assembly.Builder, new object [] { win32IconFile });
1856 if (Report.Errors > 0)
1860 stopwatch = Stopwatch.StartNew ();
1864 ShowTime ("Saving output assembly");
1866 if (RootContext.GenerateDebugInfo) {
1867 SymbolWriter.WriteSymbolFile ();
1868 ShowTime ("Saving debug symbols");
1871 ShowTotalTime ("Total");
1873 Timer.ShowTimers ();
1875 return (Report.Errors == 0);
1883 void Emit (AssemblyDefinition assembly);
1884 string FileName { get; }
1887 class EmbededResource : IResource
1889 static MethodInfo embed_res;
1890 readonly object[] args;
1892 public EmbededResource (string name, string file, bool isPrivate)
1894 args = new object [3];
1897 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1900 public void Emit (AssemblyDefinition assembly)
1902 if (embed_res == null) {
1903 var argst = new [] {
1904 typeof (string), typeof (string), typeof (ResourceAttributes)
1907 embed_res = typeof (AssemblyBuilder).GetMethod (
1908 "EmbedResourceFile", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
1909 null, CallingConventions.Any, argst, null);
1911 if (embed_res == null) {
1912 assembly.Compiler.Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1916 embed_res.Invoke (assembly.Builder, args);
1919 public string FileName {
1921 return (string)args [1];
1926 class LinkedResource : IResource
1928 readonly string file;
1929 readonly string name;
1930 readonly ResourceAttributes attribute;
1932 public LinkedResource (string name, string file, bool isPrivate)
1936 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1939 public void Emit (AssemblyDefinition assembly)
1941 assembly.Builder.AddResourceFile (name, Path.GetFileName (file), attribute);
1944 public string FileName {
1952 Dictionary<string, IResource> embedded_resources = new Dictionary<string, IResource> ();
1953 readonly CompilerContext ctx;
1955 public Resources (CompilerContext ctx)
1960 public void Add (bool embeded, string file, string name)
1962 Add (embeded, file, name, false);
1965 public void Add (bool embeded, string file, string name, bool isPrivate)
1967 if (embedded_resources.ContainsKey (name)) {
1968 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1971 IResource r = embeded ?
1972 (IResource) new EmbededResource (name, file, isPrivate) :
1973 new LinkedResource (name, file, isPrivate);
1975 embedded_resources.Add (name, r);
1978 public void Emit (AssemblyDefinition assembly)
1980 foreach (IResource r in embedded_resources.Values) {
1981 if (!File.Exists (r.FileName)) {
1982 ctx.Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1992 // This is the only public entry point
1994 public class CompilerCallableEntryPoint : MarshalByRefObject {
1995 public static bool InvokeCompiler (string [] args, TextWriter error)
1998 StreamReportPrinter srp = new StreamReportPrinter (error);
1999 Driver d = Driver.Create (args, true, srp);
2003 return d.Compile () && srp.ErrorsCount == 0;
2009 public static int[] AllWarningNumbers {
2011 return Report.AllWarnings;
2015 public static void Reset ()
2020 public static void PartialReset ()
2025 public static void Reset (bool full_flag)
2028 CSharpParser.yacc_verbose_flag = 0;
2034 RootContext.Reset (full_flag);
2035 TypeManager.Reset ();
2036 ArrayContainer.Reset ();
2037 ReferenceContainer.Reset ();
2038 PointerContainer.Reset ();
2042 UnaryMutator.Reset ();
2044 ConstantFold.Reset ();
2045 CastFromDecimal.Reset ();
2046 StringConcat.Reset ();
2048 NamespaceEntry.Reset ();
2050 AnonymousTypeClass.Reset ();
2051 AnonymousMethodBody.Reset ();
2052 AnonymousMethodStorey.Reset ();
2053 SymbolWriter.Reset ();
2055 Linq.QueryBlock.TransparentParameter.Reset ();