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);
209 void Parse (SeekableStreamReader reader, CompilationUnit file)
211 CSharpParser parser = new CSharpParser (reader, file, ctx);
214 } catch (Exception ex) {
215 Report.Error(589, parser.Lexer.Location,
216 "Compilation aborted in file `{0}', {1}", file.Name, ex);
220 static void OtherFlags ()
223 "Other flags in the compiler\n" +
224 " --fatal Makes errors fatal\n" +
225 " --parse Only parses the source file\n" +
226 " --typetest Tests the tokenizer's built-in type parser\n" +
227 " --stacktrace Shows stack trace at error location\n" +
228 " --timestamp Displays time stamps of various compiler events\n" +
229 " --expect-error X Expect that error X will be encountered\n" +
230 " -v Verbose parsing (for debugging the parser)\n" +
231 " --mcs-debug X Sets MCS debugging level to X\n");
237 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
238 "mcs [options] source-files\n" +
239 " --about About the Mono C# compiler\n" +
240 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
241 " -checked[+|-] Sets default aritmetic overflow context\n" +
242 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
243 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
244 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
245 " -debug[+|-], -g Generate debugging information\n" +
246 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
247 " -doc:FILE Process documentation comments to XML file\n" +
248 " -help Lists all compiler options (short: -?)\n" +
249 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
250 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
251 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, Default, or Future\n" +
252 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
253 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
254 " -noconfig Disables implicitly referenced assemblies\n" +
255 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
256 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
257 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
258 " -out:FILE Specifies output assembly name\n" +
260 " -pkg:P1[,Pn] References packages P1..Pn\n" +
262 " -platform:ARCH Specifies the target platform of the output assembly\n" +
263 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
264 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
265 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
266 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
267 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
268 " KIND can be one of: exe, winexe, library, module\n" +
269 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
270 " -warnaserror[+|-] Treats all warnings as errors\n" +
271 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
272 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
273 " -help2 Shows internal compiler options\n" +
276 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
277 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
278 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
279 " -win32icon:FILE Use this icon for the output\n" +
280 " @file Read response file for more options\n\n" +
281 "Options can be of the form -option or /option");
286 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
292 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
293 "The compiler source code is released under the terms of the \n"+
294 "MIT X11 or GNU GPL licenses\n\n" +
296 "For more information on Mono, visit the project Web site\n" +
297 " http://www.mono-project.com\n\n" +
299 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
300 Environment.Exit (0);
303 public static int Main (string[] args)
305 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
307 Driver d = Driver.Create (args, true, new ConsoleReportPrinter ());
311 if (d.Compile () && d.Report.Errors == 0) {
312 if (d.Report.Warnings > 0) {
313 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
315 Environment.Exit (0);
320 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
321 d.Report.Errors, d.Report.Warnings);
322 Environment.Exit (1);
326 public void LoadAssembly (string assembly, bool soft)
328 LoadAssembly (assembly, null, soft);
331 void Error6 (string name, string log)
333 if (log != null && log.Length > 0)
334 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
335 Report.Error (6, "cannot find metadata file `{0}'", name);
338 void Error9 (string type, string filename, string log)
340 if (log != null && log.Length > 0)
341 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
342 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
345 void BadAssembly (string filename, string log)
347 MethodInfo adder_method = AssemblyClass.AddModule_Method;
349 if (adder_method != null) {
350 AssemblyName an = new AssemblyName ();
352 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
356 m = adder_method.Invoke (ab, new object [] { filename });
357 } catch (TargetInvocationException ex) {
358 throw ex.InnerException;
362 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
363 Path.GetFileName (filename));
366 } catch (FileNotFoundException) {
367 // did the file get deleted during compilation? who cares? swallow the exception
368 } catch (BadImageFormatException) {
370 } catch (FileLoadException) {
374 Error9 ("assembly", filename, log);
377 public void LoadAssembly (string assembly, string alias, bool soft)
380 string total_log = "";
384 char[] path_chars = { '/', '\\' };
386 if (assembly.IndexOfAny (path_chars) != -1) {
387 a = Assembly.LoadFrom (assembly);
389 string ass = assembly;
390 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
391 ass = assembly.Substring (0, assembly.Length - 4);
392 a = Assembly.Load (ass);
394 } catch (FileNotFoundException) {
396 foreach (string dir in link_paths) {
397 string full_path = Path.Combine (dir, assembly);
398 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
402 a = Assembly.LoadFrom (full_path);
405 } catch (FileNotFoundException ff) {
408 total_log += ff.FusionLog;
412 Error6 (assembly, total_log);
417 // Extern aliased refs require special handling
419 GlobalRootNamespace.Instance.AddAssemblyReference (a);
421 GlobalRootNamespace.Instance.DefineRootNamespace (alias, a, ctx);
423 } catch (BadImageFormatException f) {
424 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
425 BadAssembly (f.FileName, f.FusionLog);
426 } catch (FileLoadException f) {
427 // ... while .NET 1.1 throws this
428 BadAssembly (f.FileName, f.FusionLog);
432 public void LoadModule (string module)
435 string total_log = "";
439 m = CodeGen.Assembly.AddModule (module);
440 } catch (FileNotFoundException) {
442 foreach (string dir in link_paths) {
443 string full_path = Path.Combine (dir, module);
444 if (!module.EndsWith (".netmodule"))
445 full_path += ".netmodule";
448 m = CodeGen.Assembly.AddModule (full_path);
451 } catch (FileNotFoundException ff) {
452 total_log += ff.FusionLog;
456 Error6 (module, total_log);
461 GlobalRootNamespace.Instance.AddModuleReference (m);
463 } catch (BadImageFormatException f) {
464 Error9 ("module", f.FileName, f.FusionLog);
465 } catch (FileLoadException f) {
466 Error9 ("module", f.FileName, f.FusionLog);
471 /// Loads all assemblies referenced on the command line
473 public void LoadReferences ()
475 link_paths.Add (GetSystemDir ());
476 link_paths.Add (Directory.GetCurrentDirectory ());
479 // Load Core Library for default compilation
481 if (RootContext.StdLib)
482 LoadAssembly ("mscorlib", false);
484 foreach (string r in soft_references)
485 LoadAssembly (r, true);
487 foreach (string r in references)
488 LoadAssembly (r, false);
490 foreach (DictionaryEntry entry in external_aliases)
491 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
493 GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
496 static string [] LoadArgs (string file)
499 ArrayList args = new ArrayList ();
502 f = new StreamReader (file);
507 StringBuilder sb = new StringBuilder ();
509 while ((line = f.ReadLine ()) != null){
512 for (int i = 0; i < t; i++){
515 if (c == '"' || c == '\''){
518 for (i++; i < t; i++){
525 } else if (c == ' '){
527 args.Add (sb.ToString ());
534 args.Add (sb.ToString ());
539 string [] ret_value = new string [args.Count];
540 args.CopyTo (ret_value, 0);
546 // Returns the directory where the system assemblies are installed
548 static string GetSystemDir ()
550 return Path.GetDirectoryName (typeof (object).Assembly.Location);
554 // Given a path specification, splits the path from the file/pattern
556 static void SplitPathAndPattern (string spec, out string path, out string pattern)
558 int p = spec.LastIndexOf ('/');
561 // Windows does not like /file.cs, switch that to:
566 pattern = spec.Substring (1);
568 path = spec.Substring (0, p);
569 pattern = spec.Substring (p + 1);
574 p = spec.LastIndexOf ('\\');
576 path = spec.Substring (0, p);
577 pattern = spec.Substring (p + 1);
585 void AddSourceFile (string f)
587 if (first_source == null)
590 Location.AddFile (Report, f);
593 bool ParseArguments (string[] args, bool require_files)
595 references = new ArrayList ();
596 external_aliases = new Hashtable ();
597 soft_references = new ArrayList ();
598 modules = new ArrayList (2);
599 link_paths = new ArrayList ();
601 ArrayList response_file_list = null;
602 bool parsing_options = true;
604 for (int i = 0; i < args.Length; i++) {
605 string arg = args [i];
609 if (arg [0] == '@') {
610 string [] extra_args;
611 string response_file = arg.Substring (1);
613 if (response_file_list == null)
614 response_file_list = new ArrayList ();
616 if (response_file_list.Contains (response_file)) {
618 1515, "Response file `" + response_file +
619 "' specified multiple times");
623 response_file_list.Add (response_file);
625 extra_args = LoadArgs (response_file);
626 if (extra_args == null) {
627 Report.Error (2011, "Unable to open response file: " +
632 args = AddArgs (args, extra_args);
636 if (parsing_options) {
638 parsing_options = false;
642 if (arg [0] == '-') {
643 if (UnixParseOption (arg, ref args, ref i))
647 string csc_opt = "/" + arg.Substring (1);
648 if (CSCParseOption (csc_opt, ref args))
651 Error_WrongOption (arg);
654 if (arg [0] == '/') {
655 if (CSCParseOption (arg, ref args))
658 // Need to skip `/home/test.cs' however /test.cs is considered as error
659 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
660 Error_WrongOption (arg);
666 ProcessSourceFiles (arg, false);
669 if (require_files == false)
673 // If we are an exe, require a source file for the entry point
675 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
676 if (first_source == null) {
677 Report.Error (2008, "No files to compile were specified");
684 // If there is nothing to put in the assembly, and we are not a library
686 if (first_source == null && embedded_resources == null) {
687 Report.Error (2008, "No files to compile were specified");
696 Location.Initialize ();
698 ArrayList cu = Location.SourceFiles;
699 for (int i = 0; i < cu.Count; ++i) {
701 tokenize_file ((CompilationUnit) cu [i], ctx);
703 Parse ((CompilationUnit) cu [i]);
708 void ProcessSourceFiles (string spec, bool recurse)
710 string path, pattern;
712 SplitPathAndPattern (spec, out path, out pattern);
713 if (pattern.IndexOf ('*') == -1){
714 AddSourceFile (spec);
718 string [] files = null;
720 files = Directory.GetFiles (path, pattern);
721 } catch (System.IO.DirectoryNotFoundException) {
722 Report.Error (2001, "Source file `" + spec + "' could not be found");
724 } catch (System.IO.IOException){
725 Report.Error (2001, "Source file `" + spec + "' could not be found");
728 foreach (string f in files) {
735 string [] dirs = null;
738 dirs = Directory.GetDirectories (path);
742 foreach (string d in dirs) {
744 // Don't include path in this string, as each
745 // directory entry already does
746 ProcessSourceFiles (d + "/" + pattern, true);
750 public void ProcessDefaultConfig ()
752 if (!load_default_config)
756 // For now the "default config" is harcoded into the compiler
757 // we can move this outside later
759 string [] default_config = {
765 "System.Windows.Browser",
769 // Is it worth pre-loading all this stuff?
772 "System.Configuration.Install",
775 "System.DirectoryServices",
776 "System.Drawing.Design",
778 "System.EnterpriseServices",
781 "System.Runtime.Remoting",
782 "System.Runtime.Serialization.Formatters.Soap",
784 "System.ServiceProcess",
786 "System.Web.RegularExpressions",
787 "System.Web.Services",
788 "System.Windows.Forms"
792 soft_references.AddRange (default_config);
794 if (RootContext.Version > LanguageVersion.ISO_2)
795 soft_references.Add ("System.Core");
796 if (RootContext.Version > LanguageVersion.V_3)
797 soft_references.Add ("Microsoft.CSharp");
800 public static string OutputFile
806 return Path.GetFileName (output_file);
810 void SetWarningLevel (string s)
815 level = Int32.Parse (s);
818 if (level < 0 || level > 4){
819 Report.Error (1900, "Warning level must be in the range 0-4");
822 Report.WarningLevel = level;
825 static void Version ()
827 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
828 Console.WriteLine ("Mono C# compiler version {0}", version);
829 Environment.Exit (0);
833 // Currently handles the Unix-like command line options, but will be
834 // deprecated in favor of the CSCParseOption, which will also handle the
835 // options that start with a dash in the future.
837 bool UnixParseOption (string arg, ref string [] args, ref int i)
841 CSharpParser.yacc_verbose_flag++;
852 case "--main": case "-m":
853 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
854 if ((i + 1) >= args.Length){
856 Environment.Exit (1);
858 RootContext.MainClass = args [++i];
862 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
863 RootContext.Unsafe = true;
866 case "/?": case "/h": case "/help":
869 Environment.Exit (0);
873 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
874 if ((i + 1) >= args.Length){
876 Environment.Exit (1);
878 RootContext.AddConditional (args [++i]);
887 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
888 if ((i + 1) >= args.Length){
890 Environment.Exit (1);
892 OutputFile = args [++i];
896 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
897 RootContext.Checked = true;
901 Report.Printer.Stacktrace = true;
904 case "--linkresource":
906 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
907 if ((i + 1) >= args.Length){
909 Report.Error (5, "Missing argument to --linkres");
910 Environment.Exit (1);
912 if (embedded_resources == null)
913 embedded_resources = new Resources (ctx);
915 embedded_resources.Add (false, args [++i], args [i]);
920 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
921 if ((i + 1) >= args.Length){
923 Report.Error (5, "Missing argument to --resource");
924 Environment.Exit (1);
926 if (embedded_resources == null)
927 embedded_resources = new Resources (ctx);
929 embedded_resources.Add (true, args [++i], args [i]);
933 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
934 if ((i + 1) >= args.Length){
935 Environment.Exit (1);
939 string type = args [++i];
942 RootContext.Target = Target.Library;
943 RootContext.TargetExt = ".dll";
947 RootContext.Target = Target.Exe;
951 RootContext.Target = Target.WinExe;
955 RootContext.Target = Target.Module;
956 RootContext.TargetExt = ".dll";
965 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
966 if ((i + 1) >= args.Length){
968 Environment.Exit (1);
971 string val = args [++i];
972 int idx = val.IndexOf ('=');
974 string alias = val.Substring (0, idx);
975 string assembly = val.Substring (idx + 1);
976 AddExternAlias (alias, assembly);
980 references.Add (val);
984 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
985 if ((i + 1) >= args.Length){
987 Environment.Exit (1);
989 link_paths.Add (args [++i]);
993 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
994 RootContext.StdLib = false;
1002 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1003 if ((i + 1) >= args.Length){
1005 Environment.Exit (1);
1010 warn = Int32.Parse (args [++i]);
1013 Environment.Exit (1);
1015 Report.SetIgnoreWarning (warn);
1019 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1020 if ((i + 1) >= args.Length){
1023 "--wlevel requires a value from 0 to 4");
1024 Environment.Exit (1);
1027 SetWarningLevel (args [++i]);
1031 if ((i + 1) >= args.Length){
1032 Report.Error (5, "--mcs-debug requires an argument");
1033 Environment.Exit (1);
1037 Report.DebugFlags = Int32.Parse (args [++i]);
1039 Report.Error (5, "Invalid argument to --mcs-debug");
1040 Environment.Exit (1);
1049 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1050 if ((i + 1) >= args.Length){
1051 Report.Error (5, "--recurse requires an argument");
1052 Environment.Exit (1);
1054 ProcessSourceFiles (args [++i], true);
1059 last_time = first_time = DateTime.Now;
1062 case "--debug": case "-g":
1063 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1064 want_debugging_support = true;
1068 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1069 load_default_config = false;
1077 public static string GetPackageFlags (string packages, bool fatal, Report report)
1079 ProcessStartInfo pi = new ProcessStartInfo ();
1080 pi.FileName = "pkg-config";
1081 pi.RedirectStandardOutput = true;
1082 pi.UseShellExecute = false;
1083 pi.Arguments = "--libs " + packages;
1086 p = Process.Start (pi);
1087 } catch (Exception e) {
1088 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1090 Environment.Exit (1);
1095 if (p.StandardOutput == null){
1096 report.Warning (-27, 1, "Specified package did not return any information");
1100 string pkgout = p.StandardOutput.ReadToEnd ();
1102 if (p.ExitCode != 0) {
1103 report.Error (-27, "Error running pkg-config. Check the above output.");
1105 Environment.Exit (1);
1116 // This parses the -arg and /arg options to the compiler, even if the strings
1117 // in the following text use "/arg" on the strings.
1119 bool CSCParseOption (string option, ref string [] args)
1121 int idx = option.IndexOf (':');
1128 arg = option.Substring (0, idx);
1130 value = option.Substring (idx + 1);
1133 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1141 RootContext.Target = Target.Exe;
1145 RootContext.Target = Target.WinExe;
1149 RootContext.Target = Target.Library;
1150 RootContext.TargetExt = ".dll";
1154 RootContext.Target = Target.Module;
1155 RootContext.TargetExt = ".netmodule";
1165 if (value.Length == 0){
1167 Environment.Exit (1);
1176 RootContext.Optimize = true;
1181 RootContext.Optimize = false;
1184 case "/incremental":
1185 case "/incremental+":
1186 case "/incremental-":
1192 if (value.Length == 0){
1194 Environment.Exit (1);
1197 foreach (string d in value.Split (argument_value_separator)) {
1198 string conditional = d.Trim ();
1199 if (!Tokenizer.IsValidIdentifier (conditional)) {
1200 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
1203 RootContext.AddConditional (conditional);
1210 // We should collect data, runtime, etc and store in the file specified
1212 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1218 if (value.Length == 0){
1220 Environment.Exit (1);
1222 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1223 string pkgout = GetPackageFlags (packages, true, Report);
1225 if (pkgout != null){
1226 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1227 Split (new Char [] { ' ', '\t'});
1228 args = AddArgs (args, xargs);
1235 case "/linkresource":
1238 if (embedded_resources == null)
1239 embedded_resources = new Resources (ctx);
1241 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1242 string[] s = value.Split (argument_value_separator);
1245 if (s[0].Length == 0)
1247 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1250 embedded_resources.Add (embeded, s [0], s [1]);
1253 if (s [2] != "public" && s [2] != "private") {
1254 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1257 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1260 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1267 if (value.Length == 0){
1268 Report.Error (5, "-recurse requires an argument");
1269 Environment.Exit (1);
1271 ProcessSourceFiles (value, true);
1275 case "/reference": {
1276 if (value.Length == 0){
1277 Report.Error (5, "-reference requires an argument");
1278 Environment.Exit (1);
1281 string[] refs = value.Split (argument_value_separator);
1282 foreach (string r in refs){
1284 int index = val.IndexOf ('=');
1286 string alias = r.Substring (0, index);
1287 string assembly = r.Substring (index + 1);
1288 AddExternAlias (alias, assembly);
1292 if (val.Length != 0)
1293 references.Add (val);
1297 case "/addmodule": {
1298 if (value.Length == 0){
1299 Report.Error (5, arg + " requires an argument");
1300 Environment.Exit (1);
1303 string[] refs = value.Split (argument_value_separator);
1304 foreach (string r in refs){
1310 if (value.Length == 0) {
1311 Report.Error (5, arg + " requires an argument");
1312 Environment.Exit (1);
1315 if (win32IconFile != null)
1316 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1318 win32ResourceFile = value;
1321 case "/win32icon": {
1322 if (value.Length == 0) {
1323 Report.Error (5, arg + " requires an argument");
1324 Environment.Exit (1);
1327 if (win32ResourceFile != null)
1328 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1330 win32IconFile = value;
1334 if (value.Length == 0){
1335 Report.Error (2006, arg + " requires an argument");
1336 Environment.Exit (1);
1338 RootContext.Documentation = new Documentation (value);
1344 if (value.Length == 0){
1345 Report.Error (5, "/lib requires an argument");
1346 Environment.Exit (1);
1349 libdirs = value.Split (argument_value_separator);
1350 foreach (string dir in libdirs)
1351 link_paths.Add (dir);
1356 want_debugging_support = false;
1360 if (value == "full" || value == "")
1361 want_debugging_support = true;
1366 want_debugging_support = true;
1371 RootContext.Checked = true;
1375 RootContext.Checked = false;
1383 RootContext.VerifyClsCompliance = false;
1388 RootContext.Unsafe = true;
1392 RootContext.Unsafe = false;
1395 case "/warnaserror":
1396 case "/warnaserror+":
1397 if (value.Length == 0) {
1398 Report.WarningsAreErrors = true;
1400 foreach (string wid in value.Split (argument_value_separator))
1401 Report.AddWarningAsError (wid);
1405 case "/warnaserror-":
1406 if (value.Length == 0) {
1407 Report.WarningsAreErrors = false;
1409 foreach (string wid in value.Split (argument_value_separator))
1410 Report.RemoveWarningAsError (wid);
1415 SetWarningLevel (value);
1421 if (value.Length == 0){
1422 Report.Error (5, "/nowarn requires an argument");
1423 Environment.Exit (1);
1426 warns = value.Split (argument_value_separator);
1427 foreach (string wc in warns){
1429 if (wc.Trim ().Length == 0)
1432 int warn = Int32.Parse (wc);
1434 throw new ArgumentOutOfRangeException("warn");
1436 Report.SetIgnoreWarning (warn);
1438 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1445 load_default_config = false;
1450 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1452 RootContext.Platform = Platform.AnyCPU;
1455 RootContext.Platform = Platform.X86;
1458 RootContext.Platform = Platform.X64;
1461 RootContext.Platform = Platform.IA64;
1464 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1470 // We just ignore this.
1471 case "/errorreport":
1477 Environment.Exit(0);
1483 Environment.Exit (0);
1488 if (value.Length == 0){
1489 Report.Error (5, arg + " requires an argument");
1490 Environment.Exit (1);
1492 RootContext.MainClass = value;
1497 RootContext.StdLib = false;
1501 RootContext.StdLib = true;
1508 if (value == String.Empty) {
1509 Report.Error (5, arg + " requires an argument");
1510 Environment.Exit (1);
1512 RootContext.StrongNameKeyFile = value;
1514 case "/keycontainer":
1515 if (value == String.Empty) {
1516 Report.Error (5, arg + " requires an argument");
1517 Environment.Exit (1);
1519 RootContext.StrongNameKeyContainer = value;
1522 RootContext.StrongNameDelaySign = true;
1525 RootContext.StrongNameDelaySign = false;
1528 case "/langversion":
1529 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1531 RootContext.Version = LanguageVersion.ISO_1;
1535 RootContext.Version = LanguageVersion.Default;
1537 RootContext.AddConditional ("__V2__");
1541 RootContext.Version = LanguageVersion.ISO_2;
1544 RootContext.Version = LanguageVersion.V_3;
1547 RootContext.Version = LanguageVersion.Future;
1551 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1557 encoding = new UTF8Encoding();
1560 encoding = Encoding.Default;
1564 encoding = Encoding.GetEncoding (
1565 Int32.Parse (value));
1567 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1577 void Error_WrongOption (string option)
1579 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1582 static string [] AddArgs (string [] args, string [] extra_args)
1585 new_args = new string [extra_args.Length + args.Length];
1587 // if args contains '--' we have to take that into account
1588 // split args into first half and second half based on '--'
1589 // and add the extra_args before --
1590 int split_position = Array.IndexOf (args, "--");
1591 if (split_position != -1)
1593 Array.Copy (args, new_args, split_position);
1594 extra_args.CopyTo (new_args, split_position);
1595 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1599 args.CopyTo (new_args, 0);
1600 extra_args.CopyTo (new_args, args.Length);
1606 void AddExternAlias (string identifier, string assembly)
1608 if (assembly.Length == 0) {
1609 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1613 if (!IsExternAliasValid (identifier)) {
1614 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1618 // Could here hashtable throw an exception?
1619 external_aliases [identifier] = assembly;
1622 static bool IsExternAliasValid (string identifier)
1624 if (identifier.Length == 0)
1626 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1629 for (int i = 1; i < identifier.Length; i++) {
1630 char c = identifier [i];
1631 if (Char.IsLetter (c) || Char.IsDigit (c))
1634 UnicodeCategory category = Char.GetUnicodeCategory (c);
1635 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1636 category != UnicodeCategory.SpacingCombiningMark ||
1637 category != UnicodeCategory.ConnectorPunctuation)
1645 // Main compilation method
1647 public bool Compile ()
1649 // TODO: Should be passed to parser as an argument
1650 RootContext.ToplevelTypes = new ModuleContainer (ctx, RootContext.Unsafe);
1653 if (Report.Errors > 0)
1656 if (tokenize || parse_only)
1659 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1660 throw new InternalErrorException ("who set it?");
1662 ProcessDefaultConfig ();
1667 if (output_file == null){
1668 if (first_source == null){
1669 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1673 int pos = first_source.LastIndexOf ('.');
1676 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1678 output_file = first_source + RootContext.TargetExt;
1681 if (!CodeGen.Init (output_file, output_file, want_debugging_support, ctx))
1684 if (RootContext.Target == Target.Module) {
1685 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1686 if (module_only == null) {
1687 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1688 Environment.Exit (1);
1691 MethodInfo set_method = module_only.GetSetMethod (true);
1692 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1695 GlobalRootNamespace.Instance.AddModuleReference (RootContext.ToplevelTypes.Builder);
1698 // Load assemblies required
1701 ShowTime ("Loading references");
1705 if (modules.Count > 0) {
1706 foreach (string module in modules)
1707 LoadModule (module);
1711 ShowTime ("References loaded");
1713 if (!TypeManager.InitCoreTypes (ctx) || Report.Errors > 0)
1716 TypeManager.InitOptionalCoreTypes (ctx);
1719 ShowTime (" Core Types done");
1722 // The second pass of the compiler
1725 ShowTime ("Resolving tree");
1726 RootContext.ResolveTree ();
1728 if (Report.Errors > 0)
1731 ShowTime ("Populate tree");
1732 if (!RootContext.StdLib)
1733 RootContext.BootCorlib_PopulateCoreTypes ();
1734 RootContext.PopulateTypes ();
1736 if (Report.Errors == 0 &&
1737 RootContext.Documentation != null &&
1738 !RootContext.Documentation.OutputDocComment (
1739 output_file, Report))
1743 // Verify using aliases now
1745 NamespaceEntry.VerifyAllUsing ();
1747 if (Report.Errors > 0){
1751 CodeGen.Assembly.Resolve ();
1753 if (RootContext.VerifyClsCompliance) {
1754 if (CodeGen.Assembly.IsClsCompliant) {
1755 AttributeTester.VerifyModulesClsCompliance (ctx);
1756 TypeManager.LoadAllImportedTypes ();
1759 if (Report.Errors > 0)
1763 // The code generator
1766 ShowTime ("Emitting code");
1767 ShowTotalTime ("Total so far");
1768 RootContext.EmitCode ();
1772 if (Report.Errors > 0){
1777 ShowTime ("Closing types");
1779 RootContext.CloseTypes ();
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 = RootContext.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 CodeGen.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 ();
1834 // Add Win32 resources
1837 if (win32ResourceFile != null) {
1839 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1840 } catch (ArgumentException) {
1841 Report.RuntimeMissingSupport (Location.Null, "resource embedding ");
1844 CodeGen.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 (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1856 if (Report.Errors > 0)
1859 CodeGen.Save (output_file, want_debugging_support, Report);
1861 ShowTime ("Saved output");
1862 ShowTotalTime ("Total");
1865 Timer.ShowTimers ();
1868 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1869 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1871 return (Report.Errors == 0);
1880 string FileName { get; }
1883 class EmbededResource : IResource
1885 static MethodInfo embed_res;
1887 static EmbededResource () {
1888 Type[] argst = new Type [] {
1889 typeof (string), typeof (string), typeof (ResourceAttributes)
1892 embed_res = typeof (AssemblyBuilder).GetMethod (
1893 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1894 null, CallingConventions.Any, argst, null);
1896 if (embed_res == null) {
1897 RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1901 readonly object[] args;
1903 public EmbededResource (string name, string file, bool isPrivate)
1905 args = new object [3];
1908 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1913 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1916 public string FileName {
1918 return (string)args [1];
1923 class LinkedResource : IResource
1925 readonly string file;
1926 readonly string name;
1927 readonly ResourceAttributes attribute;
1929 public LinkedResource (string name, string file, bool isPrivate)
1933 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1938 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1941 public string FileName {
1949 IDictionary embedded_resources = new HybridDictionary ();
1950 readonly CompilerContext ctx;
1952 public Resources (CompilerContext ctx)
1957 public void Add (bool embeded, string file, string name)
1959 Add (embeded, file, name, false);
1962 public void Add (bool embeded, string file, string name, bool isPrivate)
1964 if (embedded_resources.Contains (name)) {
1965 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1968 IResource r = embeded ?
1969 (IResource) new EmbededResource (name, file, isPrivate) :
1970 new LinkedResource (name, file, isPrivate);
1972 embedded_resources.Add (name, r);
1977 foreach (IResource r in embedded_resources.Values) {
1978 if (!File.Exists (r.FileName)) {
1979 ctx.Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1989 // This is the only public entry point
1991 public class CompilerCallableEntryPoint : MarshalByRefObject {
1992 public static bool InvokeCompiler (string [] args, TextWriter error)
1995 StreamReportPrinter srp = new StreamReportPrinter (error);
1996 Driver d = Driver.Create (args, true, srp);
2000 return d.Compile () && srp.ErrorsCount == 0;
2006 public static int[] AllWarningNumbers {
2008 return Report.AllWarnings;
2012 public static void Reset ()
2017 public static void PartialReset ()
2022 public static void Reset (bool full_flag)
2025 RootContext.Reset (full_flag);
2027 TypeManager.Reset ();
2028 PredefinedAttributes.Reset ();
2029 TypeHandle.Reset ();
2032 GlobalRootNamespace.Reset ();
2034 NamespaceEntry.Reset ();
2037 AttributeTester.Reset ();
2038 AnonymousTypeClass.Reset ();
2039 AnonymousMethodBody.Reset ();
2040 AnonymousMethodStorey.Reset ();
2041 SymbolWriter.Reset ();
2043 Linq.QueryBlock.TransparentParameter.Reset ();