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 readonly char[] argument_value_separator = new char [] { ';', ',' };
98 static public void Reset ()
100 embedded_resources = null;
101 win32ResourceFile = win32IconFile = null;
107 encoding = Encoding.Default;
110 public static Driver Create (string [] args, bool require_files)
112 Driver d = new Driver ();
113 if (!d.ParseArguments (args, require_files))
119 void ShowTime (string msg)
124 DateTime now = DateTime.Now;
125 TimeSpan span = now - last_time;
129 "[{0:00}:{1:000}] {2}",
130 (int) span.TotalSeconds, span.Milliseconds, msg);
133 void ShowTotalTime (string msg)
138 DateTime now = DateTime.Now;
139 TimeSpan span = now - first_time;
143 "[{0:00}:{1:000}] {2}",
144 (int) span.TotalSeconds, span.Milliseconds, msg);
147 void tokenize_file (CompilationUnit file)
152 input = File.OpenRead (file.Name);
154 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
159 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
160 Tokenizer lexer = new Tokenizer (reader, file);
161 int token, tokens = 0, errors = 0;
163 while ((token = lexer.token ()) != Token.EOF){
165 if (token == Token.ERROR)
168 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
174 void Parse (CompilationUnit file)
179 input = File.OpenRead (file.Name);
181 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
185 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
188 if (reader.Read () == 77 && reader.Read () == 90) {
189 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
195 Parse (reader, file);
199 void Parse (SeekableStreamReader reader, CompilationUnit file)
201 CSharpParser parser = new CSharpParser (reader, file);
202 parser.ErrorOutput = Report.Stderr;
205 } catch (Exception ex) {
206 Report.Error(589, parser.Lexer.Location,
207 "Compilation aborted in file `{0}', {1}", file.Name, ex);
211 static void OtherFlags ()
214 "Other flags in the compiler\n" +
215 " --fatal Makes errors fatal\n" +
216 " --parse Only parses the source file\n" +
217 " --typetest Tests the tokenizer's built-in type parser\n" +
218 " --stacktrace Shows stack trace at error location\n" +
219 " --timestamp Displays time stamps of various compiler events\n" +
220 " --expect-error X Expect that error X will be encountered\n" +
221 " -v Verbose parsing (for debugging the parser)\n" +
222 " --mcs-debug X Sets MCS debugging level to X\n");
228 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
229 "mcs [options] source-files\n" +
230 " --about About the Mono C# compiler\n" +
231 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
232 " -checked[+|-] Sets default aritmetic overflow context\n" +
233 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
234 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
235 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
236 " -debug[+|-], -g Generate debugging information\n" +
237 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
238 " -doc:FILE Process documentation comments to XML file\n" +
239 " -help Lists all compiler options (short: -?)\n" +
240 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
241 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
242 " -langversion:TEXT Specifies language version modes: ISO-1, ISO-2, or Default\n" +
243 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
244 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
245 " -noconfig Disables implicitly referenced assemblies\n" +
246 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
247 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
248 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
249 " -out:FILE Specifies output assembly name\n" +
251 " -pkg:P1[,Pn] References packages P1..Pn\n" +
253 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
254 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
255 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
256 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
257 " KIND can be one of: exe, winexe, library, module\n" +
258 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
259 " -warnaserror[+|-] Treats all warnings as errors\n" +
260 " -warnaserror:W1[,Wn] Treats one or more compiler warnings as errors\n" +
261 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
262 " -help2 Shows internal compiler options\n" +
265 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
266 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
267 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
268 " -win32icon:FILE Use this icon for the output\n" +
269 " @file Read response file for more options\n\n" +
270 "Options can be of the form -option or /option");
273 static void TargetUsage ()
275 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
281 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
282 "The compiler source code is released under the terms of the \n"+
283 "MIT X11 or GNU GPL licenses\n\n" +
285 "For more information on Mono, visit the project Web site\n" +
286 " http://www.mono-project.com\n\n" +
288 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
289 Environment.Exit (0);
292 public static int Main (string[] args)
294 RootContext.Version = LanguageVersion.Default;
296 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
298 Driver d = Driver.Create (args, true);
302 else if (d.Compile () && Report.Errors == 0) {
303 if (Report.Warnings > 0) {
304 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
308 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
309 Report.Errors, Report.Warnings);
314 static public void LoadAssembly (string assembly, bool soft)
316 LoadAssembly (assembly, null, soft);
319 static void Error6 (string name, string log)
321 if (log != null && log.Length > 0)
322 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
323 Report.Error (6, "cannot find metadata file `{0}'", name);
326 static void Error9 (string type, string filename, string log)
328 if (log != null && log.Length > 0)
329 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
330 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
333 static void BadAssembly (string filename, string log)
335 MethodInfo adder_method = AssemblyClass.AddModule_Method;
337 if (adder_method != null) {
338 AssemblyName an = new AssemblyName ();
340 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
344 m = adder_method.Invoke (ab, new object [] { filename });
345 } catch (TargetInvocationException ex) {
346 throw ex.InnerException;
350 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
351 Path.GetFileName (filename));
354 } catch (FileNotFoundException) {
355 // did the file get deleted during compilation? who cares? swallow the exception
356 } catch (BadImageFormatException) {
358 } catch (FileLoadException) {
362 Error9 ("assembly", filename, log);
365 static public void LoadAssembly (string assembly, string alias, bool soft)
368 string total_log = "";
372 char[] path_chars = { '/', '\\' };
374 if (assembly.IndexOfAny (path_chars) != -1) {
375 a = Assembly.LoadFrom (assembly);
377 string ass = assembly;
378 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
379 ass = assembly.Substring (0, assembly.Length - 4);
380 a = Assembly.Load (ass);
382 } catch (FileNotFoundException) {
384 foreach (string dir in link_paths) {
385 string full_path = Path.Combine (dir, assembly);
386 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
390 a = Assembly.LoadFrom (full_path);
393 } catch (FileNotFoundException ff) {
396 total_log += ff.FusionLog;
400 Error6 (assembly, total_log);
405 // Extern aliased refs require special handling
407 RootNamespace.Global.AddAssemblyReference (a);
409 RootNamespace.DefineRootNamespace (alias, a);
411 } catch (BadImageFormatException f) {
412 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
413 BadAssembly (f.FileName, f.FusionLog);
414 } catch (FileLoadException f) {
415 // ... while .NET 1.1 throws this
416 BadAssembly (f.FileName, f.FusionLog);
420 static public void LoadModule (string module)
423 string total_log = "";
427 m = CodeGen.Assembly.AddModule (module);
428 } catch (FileNotFoundException) {
430 foreach (string dir in link_paths) {
431 string full_path = Path.Combine (dir, module);
432 if (!module.EndsWith (".netmodule"))
433 full_path += ".netmodule";
436 m = CodeGen.Assembly.AddModule (full_path);
439 } catch (FileNotFoundException ff) {
440 total_log += ff.FusionLog;
444 Error6 (module, total_log);
449 RootNamespace.Global.AddModuleReference (m);
451 } catch (BadImageFormatException f) {
452 Error9 ("module", f.FileName, f.FusionLog);
453 } catch (FileLoadException f) {
454 Error9 ("module", f.FileName, f.FusionLog);
459 /// Loads all assemblies referenced on the command line
461 static public void LoadReferences ()
463 link_paths.Add (GetSystemDir ());
464 link_paths.Add (Directory.GetCurrentDirectory ());
467 // Load Core Library for default compilation
469 if (RootContext.StdLib)
470 LoadAssembly ("mscorlib", false);
472 foreach (string r in soft_references)
473 LoadAssembly (r, true);
475 foreach (string r in references)
476 LoadAssembly (r, false);
478 foreach (DictionaryEntry entry in external_aliases)
479 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
481 RootNamespace.ComputeNamespaces ();
484 static string [] LoadArgs (string file)
487 ArrayList args = new ArrayList ();
490 f = new StreamReader (file);
495 StringBuilder sb = new StringBuilder ();
497 while ((line = f.ReadLine ()) != null){
500 for (int i = 0; i < t; i++){
503 if (c == '"' || c == '\''){
506 for (i++; i < t; i++){
513 } else if (c == ' '){
515 args.Add (sb.ToString ());
522 args.Add (sb.ToString ());
527 string [] ret_value = new string [args.Count];
528 args.CopyTo (ret_value, 0);
534 // Returns the directory where the system assemblies are installed
536 static string GetSystemDir ()
538 return Path.GetDirectoryName (typeof (object).Assembly.Location);
542 // Given a path specification, splits the path from the file/pattern
544 static void SplitPathAndPattern (string spec, out string path, out string pattern)
546 int p = spec.LastIndexOf ('/');
549 // Windows does not like /file.cs, switch that to:
554 pattern = spec.Substring (1);
556 path = spec.Substring (0, p);
557 pattern = spec.Substring (p + 1);
562 p = spec.LastIndexOf ('\\');
564 path = spec.Substring (0, p);
565 pattern = spec.Substring (p + 1);
573 void AddSourceFile (string f)
575 if (first_source == null)
578 Location.AddFile (f);
581 bool ParseArguments (string[] args, bool require_files)
583 references = new ArrayList ();
584 external_aliases = new Hashtable ();
585 soft_references = new ArrayList ();
586 modules = new ArrayList (2);
587 link_paths = new ArrayList ();
589 ArrayList response_file_list = null;
590 bool parsing_options = true;
592 for (int i = 0; i < args.Length; i++) {
593 string arg = args [i];
597 if (arg [0] == '@') {
598 string [] extra_args;
599 string response_file = arg.Substring (1);
601 if (response_file_list == null)
602 response_file_list = new ArrayList ();
604 if (response_file_list.Contains (response_file)) {
606 1515, "Response file `" + response_file +
607 "' specified multiple times");
611 response_file_list.Add (response_file);
613 extra_args = LoadArgs (response_file);
614 if (extra_args == null) {
615 Report.Error (2011, "Unable to open response file: " +
620 args = AddArgs (args, extra_args);
624 if (parsing_options) {
626 parsing_options = false;
630 if (arg [0] == '-') {
631 if (UnixParseOption (arg, ref args, ref i))
635 string csc_opt = "/" + arg.Substring (1);
636 if (CSCParseOption (csc_opt, ref args))
639 Error_WrongOption (arg);
642 if (arg [0] == '/') {
643 if (CSCParseOption (arg, ref args))
646 // Need to skip `/home/test.cs' however /test.cs is considered as error
647 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
648 Error_WrongOption (arg);
654 ProcessSourceFiles (arg, false);
657 if (require_files == false)
661 // If we are an exe, require a source file for the entry point
663 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
664 if (first_source == null) {
665 Report.Error (2008, "No files to compile were specified");
672 // If there is nothing to put in the assembly, and we are not a library
674 if (first_source == null && embedded_resources == null) {
675 Report.Error (2008, "No files to compile were specified");
684 Location.Initialize ();
686 ArrayList cu = Location.SourceFiles;
687 for (int i = 0; i < cu.Count; ++i) {
689 tokenize_file ((CompilationUnit) cu [i]);
691 Parse ((CompilationUnit) cu [i]);
696 void ProcessSourceFiles (string spec, bool recurse)
698 string path, pattern;
700 SplitPathAndPattern (spec, out path, out pattern);
701 if (pattern.IndexOf ('*') == -1){
702 AddSourceFile (spec);
706 string [] files = null;
708 files = Directory.GetFiles (path, pattern);
709 } catch (System.IO.DirectoryNotFoundException) {
710 Report.Error (2001, "Source file `" + spec + "' could not be found");
712 } catch (System.IO.IOException){
713 Report.Error (2001, "Source file `" + spec + "' could not be found");
716 foreach (string f in files) {
723 string [] dirs = null;
726 dirs = Directory.GetDirectories (path);
730 foreach (string d in dirs) {
732 // Don't include path in this string, as each
733 // directory entry already does
734 ProcessSourceFiles (d + "/" + pattern, true);
738 public void ProcessDefaultConfig ()
740 if (!load_default_config)
744 // For now the "default config" is harcoded into the compiler
745 // we can move this outside later
747 string [] default_config = {
753 "System.Windows.Browser",
757 // Is it worth pre-loading all this stuff?
760 "System.Configuration.Install",
763 "System.DirectoryServices",
764 "System.Drawing.Design",
766 "System.EnterpriseServices",
769 "System.Runtime.Remoting",
770 "System.Runtime.Serialization.Formatters.Soap",
772 "System.ServiceProcess",
774 "System.Web.RegularExpressions",
775 "System.Web.Services",
776 "System.Windows.Forms"
780 soft_references.AddRange (default_config);
782 if (RootContext.Version > LanguageVersion.ISO_2)
783 soft_references.Add ("System.Core");
786 public static string OutputFile
792 return Path.GetFileName (output_file);
796 static void SetWarningLevel (string s)
801 level = Int32.Parse (s);
804 if (level < 0 || level > 4){
805 Report.Error (1900, "Warning level must be in the range 0-4");
808 Report.WarningLevel = level;
811 static void Version ()
813 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
814 Console.WriteLine ("Mono C# compiler version {0}", version);
815 Environment.Exit (0);
819 // Currently handles the Unix-like command line options, but will be
820 // deprecated in favor of the CSCParseOption, which will also handle the
821 // options that start with a dash in the future.
823 bool UnixParseOption (string arg, ref string [] args, ref int i)
827 CSharpParser.yacc_verbose_flag++;
838 case "--main": case "-m":
839 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
840 if ((i + 1) >= args.Length){
842 Environment.Exit (1);
844 RootContext.MainClass = args [++i];
848 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
849 RootContext.Unsafe = true;
852 case "/?": case "/h": case "/help":
855 Environment.Exit (0);
859 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
860 if ((i + 1) >= args.Length){
862 Environment.Exit (1);
864 RootContext.AddConditional (args [++i]);
873 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
874 if ((i + 1) >= args.Length){
876 Environment.Exit (1);
878 OutputFile = args [++i];
882 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
883 RootContext.Checked = true;
887 Report.Stacktrace = true;
890 case "--linkresource":
892 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
893 if ((i + 1) >= args.Length){
895 Report.Error (5, "Missing argument to --linkres");
896 Environment.Exit (1);
898 if (embedded_resources == null)
899 embedded_resources = new Resources ();
901 embedded_resources.Add (false, args [++i], args [i]);
906 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
907 if ((i + 1) >= args.Length){
909 Report.Error (5, "Missing argument to --resource");
910 Environment.Exit (1);
912 if (embedded_resources == null)
913 embedded_resources = new Resources ();
915 embedded_resources.Add (true, args [++i], args [i]);
919 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
920 if ((i + 1) >= args.Length){
921 Environment.Exit (1);
925 string type = args [++i];
928 RootContext.Target = Target.Library;
929 RootContext.TargetExt = ".dll";
933 RootContext.Target = Target.Exe;
937 RootContext.Target = Target.WinExe;
941 RootContext.Target = Target.Module;
942 RootContext.TargetExt = ".dll";
951 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
952 if ((i + 1) >= args.Length){
954 Environment.Exit (1);
957 string val = args [++i];
958 int idx = val.IndexOf ('=');
960 string alias = val.Substring (0, idx);
961 string assembly = val.Substring (idx + 1);
962 AddExternAlias (alias, assembly);
966 references.Add (val);
970 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
971 if ((i + 1) >= args.Length){
973 Environment.Exit (1);
975 link_paths.Add (args [++i]);
979 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
980 RootContext.StdLib = false;
988 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
989 Report.WarningsAreErrors = true;
993 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
994 if ((i + 1) >= args.Length){
996 Environment.Exit (1);
1001 warn = Int32.Parse (args [++i]);
1004 Environment.Exit (1);
1006 Report.SetIgnoreWarning (warn);
1010 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1011 if ((i + 1) >= args.Length){
1014 "--wlevel requires a value from 0 to 4");
1015 Environment.Exit (1);
1018 SetWarningLevel (args [++i]);
1022 if ((i + 1) >= args.Length){
1023 Report.Error (5, "--mcs-debug requires an argument");
1024 Environment.Exit (1);
1028 Report.DebugFlags = Int32.Parse (args [++i]);
1030 Report.Error (5, "Invalid argument to --mcs-debug");
1031 Environment.Exit (1);
1040 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1041 if ((i + 1) >= args.Length){
1042 Report.Error (5, "--recurse requires an argument");
1043 Environment.Exit (1);
1045 ProcessSourceFiles (args [++i], true);
1050 last_time = first_time = DateTime.Now;
1053 case "--debug": case "-g":
1054 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1055 want_debugging_support = true;
1059 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1060 load_default_config = false;
1068 public static string GetPackageFlags (string packages, bool fatal)
1070 ProcessStartInfo pi = new ProcessStartInfo ();
1071 pi.FileName = "pkg-config";
1072 pi.RedirectStandardOutput = true;
1073 pi.UseShellExecute = false;
1074 pi.Arguments = "--libs " + packages;
1077 p = Process.Start (pi);
1078 } catch (Exception e) {
1079 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1081 Environment.Exit (1);
1086 if (p.StandardOutput == null){
1087 Report.Warning (-27, 1, "Specified package did not return any information");
1091 string pkgout = p.StandardOutput.ReadToEnd ();
1093 if (p.ExitCode != 0) {
1094 Report.Error (-27, "Error running pkg-config. Check the above output.");
1096 Environment.Exit (1);
1107 // This parses the -arg and /arg options to the compiler, even if the strings
1108 // in the following text use "/arg" on the strings.
1110 bool CSCParseOption (string option, ref string [] args)
1112 int idx = option.IndexOf (':');
1119 arg = option.Substring (0, idx);
1121 value = option.Substring (idx + 1);
1124 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1132 RootContext.Target = Target.Exe;
1136 RootContext.Target = Target.WinExe;
1140 RootContext.Target = Target.Library;
1141 RootContext.TargetExt = ".dll";
1145 RootContext.Target = Target.Module;
1146 RootContext.TargetExt = ".netmodule";
1156 if (value.Length == 0){
1158 Environment.Exit (1);
1167 RootContext.Optimize = true;
1172 RootContext.Optimize = false;
1175 case "/incremental":
1176 case "/incremental+":
1177 case "/incremental-":
1183 if (value.Length == 0){
1185 Environment.Exit (1);
1188 foreach (string d in value.Split (argument_value_separator)) {
1189 if (!Tokenizer.IsValidIdentifier (d)) {
1190 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1193 RootContext.AddConditional (d);
1200 // We should collect data, runtime, etc and store in the file specified
1202 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1208 if (value.Length == 0){
1210 Environment.Exit (1);
1212 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1213 string pkgout = GetPackageFlags (packages, true);
1215 if (pkgout != null){
1216 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1217 Split (new Char [] { ' ', '\t'});
1218 args = AddArgs (args, xargs);
1225 case "/linkresource":
1228 if (embedded_resources == null)
1229 embedded_resources = new Resources ();
1231 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1232 string[] s = value.Split (argument_value_separator);
1235 if (s[0].Length == 0)
1237 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1240 embedded_resources.Add (embeded, s [0], s [1]);
1243 if (s [2] != "public" && s [2] != "private") {
1244 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1247 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1250 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1257 if (value.Length == 0){
1258 Report.Error (5, "-recurse requires an argument");
1259 Environment.Exit (1);
1261 ProcessSourceFiles (value, true);
1265 case "/reference": {
1266 if (value.Length == 0){
1267 Report.Error (5, "-reference requires an argument");
1268 Environment.Exit (1);
1271 string[] refs = value.Split (argument_value_separator);
1272 foreach (string r in refs){
1274 int index = val.IndexOf ('=');
1276 string alias = r.Substring (0, index);
1277 string assembly = r.Substring (index + 1);
1278 AddExternAlias (alias, assembly);
1282 if (val.Length != 0)
1283 references.Add (val);
1287 case "/addmodule": {
1288 if (value.Length == 0){
1289 Report.Error (5, arg + " requires an argument");
1290 Environment.Exit (1);
1293 string[] refs = value.Split (argument_value_separator);
1294 foreach (string r in refs){
1300 if (value.Length == 0) {
1301 Report.Error (5, arg + " requires an argument");
1302 Environment.Exit (1);
1305 if (win32IconFile != null)
1306 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1308 win32ResourceFile = value;
1311 case "/win32icon": {
1312 if (value.Length == 0) {
1313 Report.Error (5, arg + " requires an argument");
1314 Environment.Exit (1);
1317 if (win32ResourceFile != null)
1318 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1320 win32IconFile = value;
1324 if (value.Length == 0){
1325 Report.Error (2006, arg + " requires an argument");
1326 Environment.Exit (1);
1328 RootContext.Documentation = new Documentation (value);
1334 if (value.Length == 0){
1335 Report.Error (5, "/lib requires an argument");
1336 Environment.Exit (1);
1339 libdirs = value.Split (argument_value_separator);
1340 foreach (string dir in libdirs)
1341 link_paths.Add (dir);
1346 want_debugging_support = false;
1351 want_debugging_support = true;
1356 RootContext.Checked = true;
1360 RootContext.Checked = false;
1368 RootContext.VerifyClsCompliance = false;
1373 RootContext.Unsafe = true;
1377 RootContext.Unsafe = false;
1380 case "/warnaserror":
1381 if (value.Length == 0) {
1382 Report.WarningsAreErrors = true;
1384 foreach (string wid in value.Split (argument_value_separator))
1385 Report.AddWarningAsError (wid);
1389 case "/warnaserror+":
1390 Report.WarningsAreErrors = true;
1393 case "/warnaserror-":
1394 Report.WarningsAreErrors = false;
1398 SetWarningLevel (value);
1404 if (value.Length == 0){
1405 Report.Error (5, "/nowarn requires an argument");
1406 Environment.Exit (1);
1409 warns = value.Split (argument_value_separator);
1410 foreach (string wc in warns){
1412 if (wc.Trim ().Length == 0)
1415 int warn = Int32.Parse (wc);
1417 throw new ArgumentOutOfRangeException("warn");
1419 Report.SetIgnoreWarning (warn);
1421 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1428 load_default_config = false;
1433 Environment.Exit(0);
1439 Environment.Exit (0);
1444 if (value.Length == 0){
1445 Report.Error (5, arg + " requires an argument");
1446 Environment.Exit (1);
1448 RootContext.MainClass = value;
1453 RootContext.StdLib = false;
1457 RootContext.StdLib = true;
1464 if (value == String.Empty) {
1465 Report.Error (5, arg + " requires an argument");
1466 Environment.Exit (1);
1468 RootContext.StrongNameKeyFile = value;
1470 case "/keycontainer":
1471 if (value == String.Empty) {
1472 Report.Error (5, arg + " requires an argument");
1473 Environment.Exit (1);
1475 RootContext.StrongNameKeyContainer = value;
1478 RootContext.StrongNameDelaySign = true;
1481 RootContext.StrongNameDelaySign = false;
1484 case "/langversion":
1485 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1487 RootContext.Version = LanguageVersion.ISO_1;
1491 RootContext.Version = LanguageVersion.Default;
1493 RootContext.AddConditional ("__V2__");
1498 RootContext.Version = LanguageVersion.ISO_2;
1502 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
1508 encoding = new UTF8Encoding();
1511 encoding = Encoding.Default;
1515 encoding = Encoding.GetEncoding (
1516 Int32.Parse (value));
1518 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1528 static void Error_WrongOption (string option)
1530 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1533 static string [] AddArgs (string [] args, string [] extra_args)
1536 new_args = new string [extra_args.Length + args.Length];
1538 // if args contains '--' we have to take that into account
1539 // split args into first half and second half based on '--'
1540 // and add the extra_args before --
1541 int split_position = Array.IndexOf (args, "--");
1542 if (split_position != -1)
1544 Array.Copy (args, new_args, split_position);
1545 extra_args.CopyTo (new_args, split_position);
1546 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1550 args.CopyTo (new_args, 0);
1551 extra_args.CopyTo (new_args, args.Length);
1557 static void AddExternAlias (string identifier, string assembly)
1559 if (assembly.Length == 0) {
1560 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1564 if (!IsExternAliasValid (identifier)) {
1565 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1569 // Could here hashtable throw an exception?
1570 external_aliases [identifier] = assembly;
1573 static bool IsExternAliasValid (string identifier)
1575 if (identifier.Length == 0)
1577 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1580 for (int i = 1; i < identifier.Length; i++) {
1581 char c = identifier [i];
1582 if (Char.IsLetter (c) || Char.IsDigit (c))
1585 UnicodeCategory category = Char.GetUnicodeCategory (c);
1586 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1587 category != UnicodeCategory.SpacingCombiningMark ||
1588 category != UnicodeCategory.ConnectorPunctuation)
1596 // Main compilation method
1598 public bool Compile ()
1601 if (Report.Errors > 0)
1604 if (tokenize || parse_only)
1607 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1608 throw new InternalErrorException ("who set it?");
1610 ProcessDefaultConfig ();
1615 if (output_file == null){
1616 if (first_source == null){
1617 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1621 int pos = first_source.LastIndexOf ('.');
1624 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1626 output_file = first_source + RootContext.TargetExt;
1629 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1632 if (RootContext.Target == Target.Module) {
1633 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1634 if (module_only == null) {
1635 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1636 Environment.Exit (1);
1639 MethodInfo set_method = module_only.GetSetMethod (true);
1640 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1643 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1646 // Load assemblies required
1649 ShowTime ("Loading references");
1653 if (modules.Count > 0) {
1654 foreach (string module in modules)
1655 LoadModule (module);
1659 ShowTime ("References loaded");
1661 if (!TypeManager.InitCoreTypes () || Report.Errors > 0)
1664 TypeManager.InitOptionalCoreTypes ();
1667 ShowTime (" Core Types done");
1669 CodeGen.Module.Resolve ();
1672 // The second pass of the compiler
1675 ShowTime ("Resolving tree");
1676 RootContext.ResolveTree ();
1678 if (Report.Errors > 0)
1681 ShowTime ("Populate tree");
1682 if (!RootContext.StdLib)
1683 RootContext.BootCorlib_PopulateCoreTypes ();
1684 RootContext.PopulateTypes ();
1686 if (Report.Errors == 0 &&
1687 RootContext.Documentation != null &&
1688 !RootContext.Documentation.OutputDocComment (
1693 // Verify using aliases now
1695 NamespaceEntry.VerifyAllUsing ();
1697 if (Report.Errors > 0){
1701 CodeGen.Assembly.Resolve ();
1703 if (RootContext.VerifyClsCompliance) {
1704 if (CodeGen.Assembly.IsClsCompliant) {
1705 AttributeTester.VerifyModulesClsCompliance ();
1706 TypeManager.LoadAllImportedTypes ();
1709 if (Report.Errors > 0)
1713 // The code generator
1716 ShowTime ("Emitting code");
1717 ShowTotalTime ("Total so far");
1718 RootContext.EmitCode ();
1722 if (Report.Errors > 0){
1727 ShowTime ("Closing types");
1729 RootContext.CloseTypes ();
1731 PEFileKinds k = PEFileKinds.ConsoleApplication;
1733 switch (RootContext.Target) {
1734 case Target.Library:
1736 k = PEFileKinds.Dll; break;
1738 k = PEFileKinds.ConsoleApplication; break;
1740 k = PEFileKinds.WindowApplication; break;
1743 if (RootContext.NeedsEntryPoint) {
1744 MethodInfo ep = RootContext.EntryPoint;
1747 if (RootContext.MainClass != null) {
1748 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1749 if (main_cont == null) {
1750 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1754 if (!(main_cont is ClassOrStruct)) {
1755 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1759 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1763 if (Report.Errors == 0)
1764 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1769 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1770 } else if (RootContext.MainClass != null) {
1771 Report.Error (2017, "Cannot specify -main if building a module or library");
1774 if (embedded_resources != null){
1775 if (RootContext.Target == Target.Module) {
1776 Report.Error (1507, "Cannot link resource file when building a module");
1780 embedded_resources.Emit ();
1784 // Add Win32 resources
1787 if (win32ResourceFile != null) {
1789 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1790 } catch (ArgumentException) {
1791 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1794 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1797 if (win32IconFile != null) {
1798 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1799 if (define_icon == null) {
1800 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1802 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1806 if (Report.Errors > 0)
1809 CodeGen.Save (output_file, want_debugging_support);
1811 ShowTime ("Saved output");
1812 ShowTotalTime ("Total");
1815 Timer.ShowTimers ();
1817 if (Report.ExpectedError != 0) {
1818 if (Report.Errors == 0) {
1819 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1820 "No other errors reported.");
1822 Environment.Exit (2);
1824 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1825 "However, other errors were reported.");
1827 Environment.Exit (1);
1835 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1836 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1838 return (Report.Errors == 0);
1847 string FileName { get; }
1850 class EmbededResource : IResource
1852 static MethodInfo embed_res;
1854 static EmbededResource () {
1855 Type[] argst = new Type [] {
1856 typeof (string), typeof (string), typeof (ResourceAttributes)
1859 embed_res = typeof (AssemblyBuilder).GetMethod (
1860 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1861 null, CallingConventions.Any, argst, null);
1863 if (embed_res == null) {
1864 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1868 readonly object[] args;
1870 public EmbededResource (string name, string file, bool isPrivate)
1872 args = new object [3];
1875 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1880 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1883 public string FileName {
1885 return (string)args [1];
1890 class LinkedResource : IResource
1892 readonly string file;
1893 readonly string name;
1894 readonly ResourceAttributes attribute;
1896 public LinkedResource (string name, string file, bool isPrivate)
1900 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1905 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1908 public string FileName {
1916 IDictionary embedded_resources = new HybridDictionary ();
1918 public void Add (bool embeded, string file, string name)
1920 Add (embeded, file, name, false);
1923 public void Add (bool embeded, string file, string name, bool isPrivate)
1925 if (embedded_resources.Contains (name)) {
1926 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1929 IResource r = embeded ?
1930 (IResource) new EmbededResource (name, file, isPrivate) :
1931 new LinkedResource (name, file, isPrivate);
1933 embedded_resources.Add (name, r);
1938 foreach (IResource r in embedded_resources.Values) {
1939 if (!File.Exists (r.FileName)) {
1940 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1950 // This is the only public entry point
1952 public class CompilerCallableEntryPoint : MarshalByRefObject {
1953 public static bool InvokeCompiler (string [] args, TextWriter error)
1955 Report.Stderr = error;
1957 Driver d = Driver.Create (args, true);
1961 return d.Compile () && Report.Errors == 0;
1964 Report.Stderr = Console.Error;
1969 public static int[] AllWarningNumbers {
1971 return Report.AllWarnings;
1975 public static void Reset ()
1980 public static void PartialReset ()
1985 public static void Reset (bool full_flag)
1988 RootContext.Reset (full_flag);
1992 TypeManager.Reset ();
1993 TypeHandle.Reset ();
1996 RootNamespace.Reset ();
1998 NamespaceEntry.Reset ();
2001 AttributeTester.Reset ();
2002 AnonymousTypeClass.Reset ();
2003 AnonymousMethodBody.Reset ();
2004 AnonymousMethodStorey.Reset ();
2005 SymbolWriter.Reset ();
2007 Linq.QueryBlock.TransparentParameter.Reset ();