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
31 /// The compiler driver.
36 // Assemblies references to be linked. Initialized with
38 static ArrayList references;
41 // If any of these fail, we ignore the problem. This is so
42 // that we can list all the assemblies in Windows and not fail
43 // if they are missing on Linux.
45 static ArrayList soft_references;
48 // External aliases for assemblies.
50 static Hashtable external_aliases;
53 // Modules to be linked
55 static ArrayList modules;
58 static ArrayList link_paths;
60 // Whether we want to only run the tokenizer
65 bool want_debugging_support;
70 // Whether to load the initial config file (what CSC.RSP has by default)
72 bool load_default_config = true;
75 // A list of resource files
77 static Resources embedded_resources;
78 static string win32ResourceFile;
79 static string win32IconFile;
84 static string output_file;
87 // Last time we took the time
89 DateTime last_time, first_time;
96 static public void Reset ()
98 embedded_resources = null;
99 win32ResourceFile = win32IconFile = null;
105 encoding = Encoding.Default;
108 public static Driver Create (string [] args, bool require_files)
110 Driver d = new Driver ();
111 if (!d.ParseArguments (args, require_files))
117 void ShowTime (string msg)
122 DateTime now = DateTime.Now;
123 TimeSpan span = now - last_time;
127 "[{0:00}:{1:000}] {2}",
128 (int) span.TotalSeconds, span.Milliseconds, msg);
131 void ShowTotalTime (string msg)
136 DateTime now = DateTime.Now;
137 TimeSpan span = now - first_time;
141 "[{0:00}:{1:000}] {2}",
142 (int) span.TotalSeconds, span.Milliseconds, msg);
145 void tokenize_file (CompilationUnit file)
150 input = File.OpenRead (file.Name);
152 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
157 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
158 Tokenizer lexer = new Tokenizer (reader, file);
159 int token, tokens = 0, errors = 0;
161 while ((token = lexer.token ()) != Token.EOF){
163 if (token == Token.ERROR)
166 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
172 void Parse (CompilationUnit file)
177 input = File.OpenRead (file.Name);
179 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
183 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
186 if (reader.Read () == 77 && reader.Read () == 90) {
187 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
193 Parse (reader, file);
197 void Parse (SeekableStreamReader reader, CompilationUnit file)
199 CSharpParser parser = new CSharpParser (reader, file);
200 parser.ErrorOutput = Report.Stderr;
203 } catch (Exception ex) {
204 Report.Error(589, parser.Lexer.Location,
205 "Compilation aborted in file `{0}', {1}", file.Name, ex);
209 static void OtherFlags ()
212 "Other flags in the compiler\n" +
213 " --fatal Makes errors fatal\n" +
214 " --parse Only parses the source file\n" +
215 " --typetest Tests the tokenizer's built-in type parser\n" +
216 " --stacktrace Shows stack trace at error location\n" +
217 " --timestamp Displays time stamps of various compiler events\n" +
218 " --expect-error X Expect that error X will be encountered\n" +
219 " -v Verbose parsing (for debugging the parser)\n" +
220 " --mcs-debug X Sets MCS debugging level to X\n");
226 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
227 "mcs [options] source-files\n" +
228 " --about About the Mono C# compiler\n" +
229 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
230 " -checked[+|-] Sets default aritmetic overflow context\n" +
231 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
232 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
233 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
234 " -debug[+|-], -g Generate debugging information\n" +
235 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
236 " -doc:FILE Process documentation comments to XML file\n" +
237 " -help Lists all compiler options (short: -?)\n" +
238 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
239 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
240 " -langversion:TEXT Specifies language version modes: ISO-1, ISO-2, or Default\n" +
241 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
242 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
243 " -noconfig Disables implicitly referenced assemblies\n" +
244 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
245 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
246 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
247 " -out:FILE Specifies output assembly name\n" +
249 " -pkg:P1[,Pn] References packages P1..Pn\n" +
251 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
252 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
253 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
254 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
255 " KIND can be one of: exe, winexe, library, module\n" +
256 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
257 " -warnaserror[+|-] Treats all warnings as errors\n" +
258 " -warn:0-4 Sets warning level, the default is 3 (short -w:)\n" +
259 " -help2 Shows internal compiler options\n" +
262 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
263 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
264 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
265 " -win32icon:FILE Use this icon for the output\n" +
266 " @file Read response file for more options\n\n" +
267 "Options can be of the form -option or /option");
270 static void TargetUsage ()
272 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
278 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
279 "The compiler source code is released under the terms of the \n"+
280 "MIT X11 or GNU GPL licenses\n\n" +
282 "For more information on Mono, visit the project Web site\n" +
283 " http://www.mono-project.com\n\n" +
285 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
286 Environment.Exit (0);
289 public static int Main (string[] args)
291 RootContext.Version = LanguageVersion.Default;
293 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
295 Driver d = Driver.Create (args, true);
299 else if (d.Compile () && Report.Errors == 0) {
300 if (Report.Warnings > 0) {
301 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
305 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
306 Report.Errors, Report.Warnings);
311 static public void LoadAssembly (string assembly, bool soft)
313 LoadAssembly (assembly, null, soft);
316 static void Error6 (string name, string log)
318 if (log != null && log.Length > 0)
319 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
320 Report.Error (6, "cannot find metadata file `{0}'", name);
323 static void Error9 (string type, string filename, string log)
325 if (log != null && log.Length > 0)
326 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
327 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
330 static void BadAssembly (string filename, string log)
332 MethodInfo adder_method = AssemblyClass.AddModule_Method;
334 if (adder_method != null) {
335 AssemblyName an = new AssemblyName ();
337 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
341 m = adder_method.Invoke (ab, new object [] { filename });
342 } catch (TargetInvocationException ex) {
343 throw ex.InnerException;
347 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
348 Path.GetFileName (filename));
351 } catch (FileNotFoundException) {
352 // did the file get deleted during compilation? who cares? swallow the exception
353 } catch (BadImageFormatException) {
355 } catch (FileLoadException) {
359 Error9 ("assembly", filename, log);
362 static public void LoadAssembly (string assembly, string alias, bool soft)
365 string total_log = "";
369 char[] path_chars = { '/', '\\' };
371 if (assembly.IndexOfAny (path_chars) != -1) {
372 a = Assembly.LoadFrom (assembly);
374 string ass = assembly;
375 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
376 ass = assembly.Substring (0, assembly.Length - 4);
377 a = Assembly.Load (ass);
379 } catch (FileNotFoundException) {
381 foreach (string dir in link_paths) {
382 string full_path = Path.Combine (dir, assembly);
383 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
387 a = Assembly.LoadFrom (full_path);
390 } catch (FileNotFoundException ff) {
393 total_log += ff.FusionLog;
397 Error6 (assembly, total_log);
402 // Extern aliased refs require special handling
404 RootNamespace.Global.AddAssemblyReference (a);
406 RootNamespace.DefineRootNamespace (alias, a);
408 } catch (BadImageFormatException f) {
409 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
410 BadAssembly (f.FileName, f.FusionLog);
411 } catch (FileLoadException f) {
412 // ... while .NET 1.1 throws this
413 BadAssembly (f.FileName, f.FusionLog);
417 static public void LoadModule (string module)
420 string total_log = "";
424 m = CodeGen.Assembly.AddModule (module);
425 } catch (FileNotFoundException) {
427 foreach (string dir in link_paths) {
428 string full_path = Path.Combine (dir, module);
429 if (!module.EndsWith (".netmodule"))
430 full_path += ".netmodule";
433 m = CodeGen.Assembly.AddModule (full_path);
436 } catch (FileNotFoundException ff) {
437 total_log += ff.FusionLog;
441 Error6 (module, total_log);
446 RootNamespace.Global.AddModuleReference (m);
448 } catch (BadImageFormatException f) {
449 Error9 ("module", f.FileName, f.FusionLog);
450 } catch (FileLoadException f) {
451 Error9 ("module", f.FileName, f.FusionLog);
456 /// Loads all assemblies referenced on the command line
458 static public void LoadReferences ()
460 link_paths.Add (GetSystemDir ());
461 link_paths.Add (Directory.GetCurrentDirectory ());
464 // Load Core Library for default compilation
466 if (RootContext.StdLib)
467 LoadAssembly ("mscorlib", false);
469 foreach (string r in soft_references)
470 LoadAssembly (r, true);
472 foreach (string r in references)
473 LoadAssembly (r, false);
475 foreach (DictionaryEntry entry in external_aliases)
476 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
481 static string [] LoadArgs (string file)
484 ArrayList args = new ArrayList ();
487 f = new StreamReader (file);
492 StringBuilder sb = new StringBuilder ();
494 while ((line = f.ReadLine ()) != null){
497 for (int i = 0; i < t; i++){
500 if (c == '"' || c == '\''){
503 for (i++; i < t; i++){
510 } else if (c == ' '){
512 args.Add (sb.ToString ());
519 args.Add (sb.ToString ());
524 string [] ret_value = new string [args.Count];
525 args.CopyTo (ret_value, 0);
531 // Returns the directory where the system assemblies are installed
533 static string GetSystemDir ()
535 return Path.GetDirectoryName (typeof (object).Assembly.Location);
539 // Given a path specification, splits the path from the file/pattern
541 static void SplitPathAndPattern (string spec, out string path, out string pattern)
543 int p = spec.LastIndexOf ('/');
546 // Windows does not like /file.cs, switch that to:
551 pattern = spec.Substring (1);
553 path = spec.Substring (0, p);
554 pattern = spec.Substring (p + 1);
559 p = spec.LastIndexOf ('\\');
561 path = spec.Substring (0, p);
562 pattern = spec.Substring (p + 1);
570 void AddSourceFile (string f)
572 if (first_source == null)
575 Location.AddFile (f);
578 bool ParseArguments (string[] args, bool require_files)
580 references = new ArrayList ();
581 external_aliases = new Hashtable ();
582 soft_references = new ArrayList ();
583 modules = new ArrayList (2);
584 link_paths = new ArrayList ();
586 ArrayList response_file_list = null;
587 bool parsing_options = true;
589 for (int i = 0; i < args.Length; i++) {
590 string arg = args [i];
594 if (arg [0] == '@') {
595 string [] extra_args;
596 string response_file = arg.Substring (1);
598 if (response_file_list == null)
599 response_file_list = new ArrayList ();
601 if (response_file_list.Contains (response_file)) {
603 1515, "Response file `" + response_file +
604 "' specified multiple times");
608 response_file_list.Add (response_file);
610 extra_args = LoadArgs (response_file);
611 if (extra_args == null) {
612 Report.Error (2011, "Unable to open response file: " +
617 args = AddArgs (args, extra_args);
621 if (parsing_options) {
623 parsing_options = false;
627 if (arg [0] == '-') {
628 if (UnixParseOption (arg, ref args, ref i))
632 string csc_opt = "/" + arg.Substring (1);
633 if (CSCParseOption (csc_opt, ref args))
636 Error_WrongOption (arg);
639 if (arg [0] == '/') {
640 if (CSCParseOption (arg, ref args))
643 // Need to skip `/home/test.cs' however /test.cs is considered as error
644 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
645 Error_WrongOption (arg);
651 ProcessSourceFiles (arg, false);
654 if (require_files == false)
658 // If we are an exe, require a source file for the entry point
660 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
661 if (first_source == null) {
662 Report.Error (2008, "No files to compile were specified");
669 // If there is nothing to put in the assembly, and we are not a library
671 if (first_source == null && embedded_resources == null) {
672 Report.Error (2008, "No files to compile were specified");
681 Location.Initialize ();
683 int files_count = Location.SourceFiles.Length;
684 for (int i = 0; i < files_count; ++i) {
686 tokenize_file (Location.SourceFiles [i]);
688 Parse (Location.SourceFiles [i]);
693 void ProcessSourceFiles (string spec, bool recurse)
695 string path, pattern;
697 SplitPathAndPattern (spec, out path, out pattern);
698 if (pattern.IndexOf ('*') == -1){
699 AddSourceFile (spec);
703 string [] files = null;
705 files = Directory.GetFiles (path, pattern);
706 } catch (System.IO.DirectoryNotFoundException) {
707 Report.Error (2001, "Source file `" + spec + "' could not be found");
709 } catch (System.IO.IOException){
710 Report.Error (2001, "Source file `" + spec + "' could not be found");
713 foreach (string f in files) {
720 string [] dirs = null;
723 dirs = Directory.GetDirectories (path);
727 foreach (string d in dirs) {
729 // Don't include path in this string, as each
730 // directory entry already does
731 ProcessSourceFiles (d + "/" + pattern, true);
735 public void ProcessDefaultConfig ()
737 bool need_system_core = RootContext.Version > LanguageVersion.ISO_2;
739 if (!load_default_config){
741 // Yet another SRE related problem, we have to always load System.Core
742 // even with -noconfig, otherwise the check for ExtensionAttribute in
743 // loaded assemblies won't work
746 if (need_system_core && references.Count != 0) {
748 // TODO: use TypeManager.CoreLookupType (...) when it stops defining types
751 Namespace n = GlobalRootNamespace.Global.GetNamespace ("System.Runtime.CompilerServices", false);
752 if (n == null || !n.HasDefinition ("ExtensionAttribute")) {
753 soft_references.Add ("System.Core");
760 // For now the "default config" is harcoded into the compiler
761 // we can move this outside later
763 string [] default_config = {
769 "System.Windows.Browser",
773 // Is it worth pre-loading all this stuff?
776 "System.Configuration.Install",
779 "System.DirectoryServices",
780 "System.Drawing.Design",
782 "System.EnterpriseServices",
785 "System.Runtime.Remoting",
786 "System.Runtime.Serialization.Formatters.Soap",
788 "System.ServiceProcess",
790 "System.Web.RegularExpressions",
791 "System.Web.Services",
792 "System.Windows.Forms"
796 soft_references.AddRange (default_config);
798 if (need_system_core)
799 soft_references.Add ("System.Core");
802 public static string OutputFile
808 return Path.GetFileName (output_file);
812 static void SetWarningLevel (string s)
817 level = Int32.Parse (s);
820 if (level < 0 || level > 4){
821 Report.Error (1900, "Warning level must be in the range 0-4");
824 Report.WarningLevel = level;
827 static void Version ()
829 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
830 Console.WriteLine ("Mono C# compiler version {0}", version);
831 Environment.Exit (0);
835 // Currently handles the Unix-like command line options, but will be
836 // deprecated in favor of the CSCParseOption, which will also handle the
837 // options that start with a dash in the future.
839 bool UnixParseOption (string arg, ref string [] args, ref int i)
843 CSharpParser.yacc_verbose_flag++;
854 case "--main": case "-m":
855 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
856 if ((i + 1) >= args.Length){
858 Environment.Exit (1);
860 RootContext.MainClass = args [++i];
864 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
865 RootContext.Unsafe = true;
868 case "/?": case "/h": case "/help":
871 Environment.Exit (0);
875 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
876 if ((i + 1) >= args.Length){
878 Environment.Exit (1);
880 RootContext.AddConditional (args [++i]);
889 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
890 if ((i + 1) >= args.Length){
892 Environment.Exit (1);
894 OutputFile = args [++i];
898 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
899 RootContext.Checked = true;
903 Report.Stacktrace = true;
906 case "--linkresource":
908 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
909 if ((i + 1) >= args.Length){
911 Report.Error (5, "Missing argument to --linkres");
912 Environment.Exit (1);
914 if (embedded_resources == null)
915 embedded_resources = new Resources ();
917 embedded_resources.Add (false, args [++i], args [i]);
922 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
923 if ((i + 1) >= args.Length){
925 Report.Error (5, "Missing argument to --resource");
926 Environment.Exit (1);
928 if (embedded_resources == null)
929 embedded_resources = new Resources ();
931 embedded_resources.Add (true, args [++i], args [i]);
935 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
936 if ((i + 1) >= args.Length){
937 Environment.Exit (1);
941 string type = args [++i];
944 RootContext.Target = Target.Library;
945 RootContext.TargetExt = ".dll";
949 RootContext.Target = Target.Exe;
953 RootContext.Target = Target.WinExe;
957 RootContext.Target = Target.Module;
958 RootContext.TargetExt = ".dll";
967 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
968 if ((i + 1) >= args.Length){
970 Environment.Exit (1);
973 string val = args [++i];
974 int idx = val.IndexOf ('=');
976 string alias = val.Substring (0, idx);
977 string assembly = val.Substring (idx + 1);
978 AddExternAlias (alias, assembly);
982 references.Add (val);
986 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
987 if ((i + 1) >= args.Length){
989 Environment.Exit (1);
991 link_paths.Add (args [++i]);
995 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
996 RootContext.StdLib = false;
1000 Report.Fatal = true;
1004 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
1005 Report.WarningsAreErrors = true;
1009 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1010 if ((i + 1) >= args.Length){
1012 Environment.Exit (1);
1017 warn = Int32.Parse (args [++i]);
1020 Environment.Exit (1);
1022 Report.SetIgnoreWarning (warn);
1026 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1027 if ((i + 1) >= args.Length){
1030 "--wlevel requires a value from 0 to 4");
1031 Environment.Exit (1);
1034 SetWarningLevel (args [++i]);
1038 if ((i + 1) >= args.Length){
1039 Report.Error (5, "--mcs-debug requires an argument");
1040 Environment.Exit (1);
1044 Report.DebugFlags = Int32.Parse (args [++i]);
1046 Report.Error (5, "Invalid argument to --mcs-debug");
1047 Environment.Exit (1);
1056 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1057 if ((i + 1) >= args.Length){
1058 Report.Error (5, "--recurse requires an argument");
1059 Environment.Exit (1);
1061 ProcessSourceFiles (args [++i], true);
1066 last_time = first_time = DateTime.Now;
1069 case "--debug": case "-g":
1070 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1071 want_debugging_support = true;
1075 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1076 load_default_config = false;
1084 public static string GetPackageFlags (string packages, bool fatal)
1086 ProcessStartInfo pi = new ProcessStartInfo ();
1087 pi.FileName = "pkg-config";
1088 pi.RedirectStandardOutput = true;
1089 pi.UseShellExecute = false;
1090 pi.Arguments = "--libs " + packages;
1093 p = Process.Start (pi);
1094 } catch (Exception e) {
1095 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1097 Environment.Exit (1);
1102 if (p.StandardOutput == null){
1103 Report.Warning (-27, 1, "Specified package did not return any information");
1107 string pkgout = p.StandardOutput.ReadToEnd ();
1109 if (p.ExitCode != 0) {
1110 Report.Error (-27, "Error running pkg-config. Check the above output.");
1112 Environment.Exit (1);
1123 // This parses the -arg and /arg options to the compiler, even if the strings
1124 // in the following text use "/arg" on the strings.
1126 bool CSCParseOption (string option, ref string [] args)
1128 int idx = option.IndexOf (':');
1135 arg = option.Substring (0, idx);
1137 value = option.Substring (idx + 1);
1140 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1148 RootContext.Target = Target.Exe;
1152 RootContext.Target = Target.WinExe;
1156 RootContext.Target = Target.Library;
1157 RootContext.TargetExt = ".dll";
1161 RootContext.Target = Target.Module;
1162 RootContext.TargetExt = ".netmodule";
1172 if (value.Length == 0){
1174 Environment.Exit (1);
1183 RootContext.Optimize = true;
1188 RootContext.Optimize = false;
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 (';', ',')){
1205 if (!Tokenizer.IsValidIdentifier (d)) {
1206 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1209 RootContext.AddConditional (d);
1216 // We should collect data, runtime, etc and store in the file specified
1218 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1224 if (value.Length == 0){
1226 Environment.Exit (1);
1228 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1229 string pkgout = GetPackageFlags (packages, true);
1231 if (pkgout != null){
1232 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1233 Split (new Char [] { ' ', '\t'});
1234 args = AddArgs (args, xargs);
1241 case "/linkresource":
1244 if (embedded_resources == null)
1245 embedded_resources = new Resources ();
1247 bool embeded = arg.StartsWith ("/r");
1248 string[] s = value.Split (',');
1251 if (s[0].Length == 0)
1253 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1256 embedded_resources.Add (embeded, s [0], s [1]);
1259 if (s [2] != "public" && s [2] != "private") {
1260 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1263 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1266 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1273 if (value.Length == 0){
1274 Report.Error (5, "-recurse requires an argument");
1275 Environment.Exit (1);
1277 ProcessSourceFiles (value, true);
1281 case "/reference": {
1282 if (value.Length == 0){
1283 Report.Error (5, "-reference requires an argument");
1284 Environment.Exit (1);
1287 string [] refs = value.Split (new char [] { ';', ',' });
1288 foreach (string r in refs){
1290 int index = val.IndexOf ('=');
1292 string alias = r.Substring (0, index);
1293 string assembly = r.Substring (index + 1);
1294 AddExternAlias (alias, assembly);
1298 if (val.Length != 0)
1299 references.Add (val);
1303 case "/addmodule": {
1304 if (value.Length == 0){
1305 Report.Error (5, arg + " requires an argument");
1306 Environment.Exit (1);
1309 string [] refs = value.Split (new char [] { ';', ',' });
1310 foreach (string r in refs){
1316 if (value.Length == 0) {
1317 Report.Error (5, arg + " requires an argument");
1318 Environment.Exit (1);
1321 win32ResourceFile = value;
1324 case "/win32icon": {
1325 if (value.Length == 0) {
1326 Report.Error (5, arg + " requires an argument");
1327 Environment.Exit (1);
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 (new Char [] { ',' });
1350 foreach (string dir in libdirs)
1351 link_paths.Add (dir);
1356 want_debugging_support = false;
1361 want_debugging_support = true;
1366 RootContext.Checked = true;
1370 RootContext.Checked = false;
1378 RootContext.VerifyClsCompliance = false;
1383 RootContext.Unsafe = true;
1387 RootContext.Unsafe = false;
1390 case "/warnaserror":
1391 case "/warnaserror+":
1392 Report.WarningsAreErrors = true;
1395 case "/warnaserror-":
1396 Report.WarningsAreErrors = false;
1400 SetWarningLevel (value);
1406 if (value.Length == 0){
1407 Report.Error (5, "/nowarn requires an argument");
1408 Environment.Exit (1);
1411 warns = value.Split (new Char [] {','});
1412 foreach (string wc in warns){
1414 int warn = Int32.Parse (wc);
1416 throw new ArgumentOutOfRangeException("warn");
1418 Report.SetIgnoreWarning (warn);
1420 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1427 load_default_config = false;
1432 Environment.Exit(0);
1438 Environment.Exit (0);
1443 if (value.Length == 0){
1444 Report.Error (5, arg + " requires an argument");
1445 Environment.Exit (1);
1447 RootContext.MainClass = value;
1452 RootContext.StdLib = false;
1456 RootContext.StdLib = true;
1463 if (value == String.Empty) {
1464 Report.Error (5, arg + " requires an argument");
1465 Environment.Exit (1);
1467 RootContext.StrongNameKeyFile = value;
1469 case "/keycontainer":
1470 if (value == String.Empty) {
1471 Report.Error (5, arg + " requires an argument");
1472 Environment.Exit (1);
1474 RootContext.StrongNameKeyContainer = value;
1477 RootContext.StrongNameDelaySign = true;
1480 RootContext.StrongNameDelaySign = false;
1483 case "/langversion":
1484 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1486 RootContext.Version = LanguageVersion.ISO_1;
1490 RootContext.Version = LanguageVersion.Default;
1492 RootContext.AddConditional ("__V2__");
1497 RootContext.Version = LanguageVersion.ISO_2;
1501 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
1507 encoding = new UTF8Encoding();
1510 encoding = Encoding.Default;
1514 encoding = Encoding.GetEncoding (
1515 Int32.Parse (value));
1517 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1527 static void Error_WrongOption (string option)
1529 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1532 static string [] AddArgs (string [] args, string [] extra_args)
1535 new_args = new string [extra_args.Length + args.Length];
1537 // if args contains '--' we have to take that into account
1538 // split args into first half and second half based on '--'
1539 // and add the extra_args before --
1540 int split_position = Array.IndexOf (args, "--");
1541 if (split_position != -1)
1543 Array.Copy (args, new_args, split_position);
1544 extra_args.CopyTo (new_args, split_position);
1545 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1549 args.CopyTo (new_args, 0);
1550 extra_args.CopyTo (new_args, args.Length);
1556 static void AddExternAlias (string identifier, string assembly)
1558 if (assembly.Length == 0) {
1559 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1563 if (!IsExternAliasValid (identifier)) {
1564 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1568 // Could here hashtable throw an exception?
1569 external_aliases [identifier] = assembly;
1572 static bool IsExternAliasValid (string identifier)
1574 if (identifier.Length == 0)
1576 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1579 for (int i = 1; i < identifier.Length; i++) {
1580 char c = identifier [i];
1581 if (Char.IsLetter (c) || Char.IsDigit (c))
1584 UnicodeCategory category = Char.GetUnicodeCategory (c);
1585 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1586 category != UnicodeCategory.SpacingCombiningMark ||
1587 category != UnicodeCategory.ConnectorPunctuation)
1595 // Main compilation method
1597 public bool Compile ()
1600 if (Report.Errors > 0)
1603 if (tokenize || parse_only)
1606 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1607 throw new InternalErrorException ("who set it?");
1609 ProcessDefaultConfig ();
1612 // Load assemblies required
1615 ShowTime ("Loading references");
1619 ShowTime (" References loaded");
1621 if (Report.Errors > 0){
1628 if (output_file == null){
1629 if (first_source == null){
1630 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1634 int pos = first_source.LastIndexOf ('.');
1637 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1639 output_file = first_source + RootContext.TargetExt;
1642 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1645 if (RootContext.Target == Target.Module) {
1646 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1647 if (module_only == null) {
1648 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1649 Environment.Exit (1);
1652 MethodInfo set_method = module_only.GetSetMethod (true);
1653 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1656 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1658 if (modules.Count > 0) {
1659 foreach (string module in modules)
1660 LoadModule (module);
1663 if (!TypeManager.InitCoreTypes ())
1666 TypeManager.InitOptionalCoreTypes ();
1669 ShowTime (" Core Types done");
1671 CodeGen.Module.Resolve ();
1674 // The second pass of the compiler
1677 ShowTime ("Resolving tree");
1678 RootContext.ResolveTree ();
1680 if (Report.Errors > 0)
1683 ShowTime ("Populate tree");
1684 if (!RootContext.StdLib)
1685 RootContext.BootCorlib_PopulateCoreTypes ();
1686 RootContext.PopulateTypes ();
1688 RootContext.DefineTypes ();
1690 if (Report.Errors == 0 &&
1691 RootContext.Documentation != null &&
1692 !RootContext.Documentation.OutputDocComment (
1697 // Verify using aliases now
1699 NamespaceEntry.VerifyAllUsing ();
1701 if (Report.Errors > 0){
1705 CodeGen.Assembly.Resolve ();
1707 if (RootContext.VerifyClsCompliance) {
1708 if (CodeGen.Assembly.IsClsCompliant) {
1709 AttributeTester.VerifyModulesClsCompliance ();
1710 TypeManager.LoadAllImportedTypes ();
1713 if (Report.Errors > 0)
1717 // The code generator
1720 ShowTime ("Emitting code");
1721 ShowTotalTime ("Total so far");
1722 RootContext.EmitCode ();
1726 if (Report.Errors > 0){
1731 ShowTime ("Closing types");
1733 RootContext.CloseTypes ();
1735 PEFileKinds k = PEFileKinds.ConsoleApplication;
1737 switch (RootContext.Target) {
1738 case Target.Library:
1740 k = PEFileKinds.Dll; break;
1742 k = PEFileKinds.ConsoleApplication; break;
1744 k = PEFileKinds.WindowApplication; break;
1747 if (RootContext.NeedsEntryPoint) {
1748 MethodInfo ep = RootContext.EntryPoint;
1751 if (RootContext.MainClass != null) {
1752 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1753 if (main_cont == null) {
1754 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1758 if (!(main_cont is ClassOrStruct)) {
1759 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1763 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1767 if (Report.Errors == 0)
1768 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1773 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1774 } else if (RootContext.MainClass != null) {
1775 Report.Error (2017, "Cannot specify -main if building a module or library");
1778 if (embedded_resources != null){
1779 if (RootContext.Target == Target.Module) {
1780 Report.Error (1507, "Cannot link resource file when building a module");
1784 embedded_resources.Emit ();
1788 // Add Win32 resources
1791 if (win32ResourceFile != null) {
1793 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1794 } catch (ArgumentException) {
1795 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1798 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1801 if (win32IconFile != null) {
1802 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1803 if (define_icon == null) {
1804 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1806 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1809 if (Report.Errors > 0)
1812 CodeGen.Save (output_file, want_debugging_support);
1814 ShowTime ("Saved output");
1815 ShowTotalTime ("Total");
1818 Timer.ShowTimers ();
1820 if (Report.ExpectedError != 0) {
1821 if (Report.Errors == 0) {
1822 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1823 "No other errors reported.");
1825 Environment.Exit (2);
1827 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1828 "However, other errors were reported.");
1830 Environment.Exit (1);
1838 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1839 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1841 return (Report.Errors == 0);
1850 string FileName { get; }
1853 class EmbededResource : IResource
1855 static MethodInfo embed_res;
1857 static EmbededResource () {
1858 Type[] argst = new Type [] {
1859 typeof (string), typeof (string), typeof (ResourceAttributes)
1862 embed_res = typeof (AssemblyBuilder).GetMethod (
1863 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1864 null, CallingConventions.Any, argst, null);
1866 if (embed_res == null) {
1867 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1871 readonly object[] args;
1873 public EmbededResource (string name, string file, bool isPrivate)
1875 args = new object [3];
1878 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1883 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1886 public string FileName {
1888 return (string)args [1];
1893 class LinkedResource : IResource
1895 readonly string file;
1896 readonly string name;
1897 readonly ResourceAttributes attribute;
1899 public LinkedResource (string name, string file, bool isPrivate)
1903 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1908 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1911 public string FileName {
1919 IDictionary embedded_resources = new HybridDictionary ();
1921 public void Add (bool embeded, string file, string name)
1923 Add (embeded, file, name, false);
1926 public void Add (bool embeded, string file, string name, bool isPrivate)
1928 if (embedded_resources.Contains (name)) {
1929 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1932 IResource r = embeded ?
1933 (IResource) new EmbededResource (name, file, isPrivate) :
1934 new LinkedResource (name, file, isPrivate);
1936 embedded_resources.Add (name, r);
1941 foreach (IResource r in embedded_resources.Values) {
1942 if (!File.Exists (r.FileName)) {
1943 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1953 // This is the only public entry point
1955 public class CompilerCallableEntryPoint : MarshalByRefObject {
1956 public static bool InvokeCompiler (string [] args, TextWriter error)
1958 Report.Stderr = error;
1960 Driver d = Driver.Create (args, true);
1964 return d.Compile () && Report.Errors == 0;
1967 Report.Stderr = Console.Error;
1972 public static int[] AllWarningNumbers {
1974 return Report.AllWarnings;
1978 public static void Reset ()
1983 public static void PartialReset ()
1988 public static void Reset (bool full_flag)
1991 RootContext.Reset (full_flag);
1995 TypeManager.Reset ();
1996 TypeHandle.Reset ();
1999 RootNamespace.Reset ();
2001 NamespaceEntry.Reset ();
2004 AttributeTester.Reset ();
2005 AnonymousTypeClass.Reset ();
2006 AnonymousMethodBody.Reset ();
2007 AnonymousMethodStorey.Reset ();
2008 SymbolWriter.Reset ();