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
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 ArrayList soft_references;
48 // External aliases for assemblies.
50 Hashtable external_aliases;
53 // Modules to be linked
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 Resources embedded_resources;
78 string win32ResourceFile;
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 ()
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: ISO-1, ISO-2, Default, or Future\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 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
259 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
260 " -help2 Shows internal compiler options\n" +
263 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
264 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
265 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
266 " -win32icon:FILE Use this icon for the output\n" +
267 " @file Read response file for more options\n\n" +
268 "Options can be of the form -option or /option");
271 static void TargetUsage ()
273 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
279 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
280 "The compiler source code is released under the terms of the \n"+
281 "MIT X11 or GNU GPL licenses\n\n" +
283 "For more information on Mono, visit the project Web site\n" +
284 " http://www.mono-project.com\n\n" +
286 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
287 Environment.Exit (0);
290 public static int Main (string[] args)
292 RootContext.Version = LanguageVersion.Default;
294 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
296 Driver d = Driver.Create (args, true);
300 else if (d.Compile () && Report.Errors == 0) {
301 if (Report.Warnings > 0) {
302 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
306 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
307 Report.Errors, Report.Warnings);
312 static public void LoadAssembly (string assembly, bool soft)
314 LoadAssembly (assembly, null, soft);
317 static void Error6 (string name, string log)
319 if (log != null && log.Length > 0)
320 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
321 Report.Error (6, "cannot find metadata file `{0}'", name);
324 static void Error9 (string type, string filename, string log)
326 if (log != null && log.Length > 0)
327 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
328 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
331 static void BadAssembly (string filename, string log)
333 MethodInfo adder_method = AssemblyClass.AddModule_Method;
335 if (adder_method != null) {
336 AssemblyName an = new AssemblyName ();
338 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
342 m = adder_method.Invoke (ab, new object [] { filename });
343 } catch (TargetInvocationException ex) {
344 throw ex.InnerException;
348 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
349 Path.GetFileName (filename));
352 } catch (FileNotFoundException) {
353 // did the file get deleted during compilation? who cares? swallow the exception
354 } catch (BadImageFormatException) {
356 } catch (FileLoadException) {
360 Error9 ("assembly", filename, log);
363 static public void LoadAssembly (string assembly, string alias, bool soft)
366 string total_log = "";
370 char[] path_chars = { '/', '\\' };
372 if (assembly.IndexOfAny (path_chars) != -1) {
373 a = Assembly.LoadFrom (assembly);
375 string ass = assembly;
376 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
377 ass = assembly.Substring (0, assembly.Length - 4);
378 a = Assembly.Load (ass);
380 } catch (FileNotFoundException) {
382 foreach (string dir in link_paths) {
383 string full_path = Path.Combine (dir, assembly);
384 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
388 a = Assembly.LoadFrom (full_path);
391 } catch (FileNotFoundException ff) {
394 total_log += ff.FusionLog;
398 Error6 (assembly, total_log);
403 // Extern aliased refs require special handling
405 RootNamespace.Global.AddAssemblyReference (a);
407 RootNamespace.DefineRootNamespace (alias, a);
409 } catch (BadImageFormatException f) {
410 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
411 BadAssembly (f.FileName, f.FusionLog);
412 } catch (FileLoadException f) {
413 // ... while .NET 1.1 throws this
414 BadAssembly (f.FileName, f.FusionLog);
418 static public void LoadModule (string module)
421 string total_log = "";
425 m = CodeGen.Assembly.AddModule (module);
426 } catch (FileNotFoundException) {
428 foreach (string dir in link_paths) {
429 string full_path = Path.Combine (dir, module);
430 if (!module.EndsWith (".netmodule"))
431 full_path += ".netmodule";
434 m = CodeGen.Assembly.AddModule (full_path);
437 } catch (FileNotFoundException ff) {
438 total_log += ff.FusionLog;
442 Error6 (module, total_log);
447 RootNamespace.Global.AddModuleReference (m);
449 } catch (BadImageFormatException f) {
450 Error9 ("module", f.FileName, f.FusionLog);
451 } catch (FileLoadException f) {
452 Error9 ("module", f.FileName, f.FusionLog);
457 /// Loads all assemblies referenced on the command line
459 public void LoadReferences ()
461 link_paths.Add (GetSystemDir ());
462 link_paths.Add (Directory.GetCurrentDirectory ());
465 // Load Core Library for default compilation
467 if (RootContext.StdLib)
468 LoadAssembly ("mscorlib", false);
470 foreach (string r in soft_references)
471 LoadAssembly (r, true);
473 foreach (string r in references)
474 LoadAssembly (r, false);
476 foreach (DictionaryEntry entry in external_aliases)
477 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
479 RootNamespace.ComputeNamespaces ();
482 static string [] LoadArgs (string file)
485 ArrayList args = new ArrayList ();
488 f = new StreamReader (file);
493 StringBuilder sb = new StringBuilder ();
495 while ((line = f.ReadLine ()) != null){
498 for (int i = 0; i < t; i++){
501 if (c == '"' || c == '\''){
504 for (i++; i < t; i++){
511 } else if (c == ' '){
513 args.Add (sb.ToString ());
520 args.Add (sb.ToString ());
525 string [] ret_value = new string [args.Count];
526 args.CopyTo (ret_value, 0);
532 // Returns the directory where the system assemblies are installed
534 static string GetSystemDir ()
536 return Path.GetDirectoryName (typeof (object).Assembly.Location);
540 // Given a path specification, splits the path from the file/pattern
542 static void SplitPathAndPattern (string spec, out string path, out string pattern)
544 int p = spec.LastIndexOf ('/');
547 // Windows does not like /file.cs, switch that to:
552 pattern = spec.Substring (1);
554 path = spec.Substring (0, p);
555 pattern = spec.Substring (p + 1);
560 p = spec.LastIndexOf ('\\');
562 path = spec.Substring (0, p);
563 pattern = spec.Substring (p + 1);
571 void AddSourceFile (string f)
573 if (first_source == null)
576 Location.AddFile (f);
579 bool ParseArguments (string[] args, bool require_files)
581 references = new ArrayList ();
582 external_aliases = new Hashtable ();
583 soft_references = new ArrayList ();
584 modules = new ArrayList (2);
585 link_paths = new ArrayList ();
587 ArrayList response_file_list = null;
588 bool parsing_options = true;
590 for (int i = 0; i < args.Length; i++) {
591 string arg = args [i];
595 if (arg [0] == '@') {
596 string [] extra_args;
597 string response_file = arg.Substring (1);
599 if (response_file_list == null)
600 response_file_list = new ArrayList ();
602 if (response_file_list.Contains (response_file)) {
604 1515, "Response file `" + response_file +
605 "' specified multiple times");
609 response_file_list.Add (response_file);
611 extra_args = LoadArgs (response_file);
612 if (extra_args == null) {
613 Report.Error (2011, "Unable to open response file: " +
618 args = AddArgs (args, extra_args);
622 if (parsing_options) {
624 parsing_options = false;
628 if (arg [0] == '-') {
629 if (UnixParseOption (arg, ref args, ref i))
633 string csc_opt = "/" + arg.Substring (1);
634 if (CSCParseOption (csc_opt, ref args))
637 Error_WrongOption (arg);
640 if (arg [0] == '/') {
641 if (CSCParseOption (arg, ref args))
644 // Need to skip `/home/test.cs' however /test.cs is considered as error
645 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
646 Error_WrongOption (arg);
652 ProcessSourceFiles (arg, false);
655 if (require_files == false)
659 // If we are an exe, require a source file for the entry point
661 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
662 if (first_source == null) {
663 Report.Error (2008, "No files to compile were specified");
670 // If there is nothing to put in the assembly, and we are not a library
672 if (first_source == null && embedded_resources == null) {
673 Report.Error (2008, "No files to compile were specified");
682 Location.Initialize ();
684 ArrayList cu = Location.SourceFiles;
685 for (int i = 0; i < cu.Count; ++i) {
687 tokenize_file ((CompilationUnit) cu [i]);
689 Parse ((CompilationUnit) cu [i]);
694 void ProcessSourceFiles (string spec, bool recurse)
696 string path, pattern;
698 SplitPathAndPattern (spec, out path, out pattern);
699 if (pattern.IndexOf ('*') == -1){
700 AddSourceFile (spec);
704 string [] files = null;
706 files = Directory.GetFiles (path, pattern);
707 } catch (System.IO.DirectoryNotFoundException) {
708 Report.Error (2001, "Source file `" + spec + "' could not be found");
710 } catch (System.IO.IOException){
711 Report.Error (2001, "Source file `" + spec + "' could not be found");
714 foreach (string f in files) {
721 string [] dirs = null;
724 dirs = Directory.GetDirectories (path);
728 foreach (string d in dirs) {
730 // Don't include path in this string, as each
731 // directory entry already does
732 ProcessSourceFiles (d + "/" + pattern, true);
736 public void ProcessDefaultConfig ()
738 if (!load_default_config)
742 // For now the "default config" is harcoded into the compiler
743 // we can move this outside later
745 string [] default_config = {
751 "System.Windows.Browser",
755 // Is it worth pre-loading all this stuff?
758 "System.Configuration.Install",
761 "System.DirectoryServices",
762 "System.Drawing.Design",
764 "System.EnterpriseServices",
767 "System.Runtime.Remoting",
768 "System.Runtime.Serialization.Formatters.Soap",
770 "System.ServiceProcess",
772 "System.Web.RegularExpressions",
773 "System.Web.Services",
774 "System.Windows.Forms"
778 soft_references.AddRange (default_config);
780 if (RootContext.Version > LanguageVersion.ISO_2)
781 soft_references.Add ("System.Core");
784 public static string OutputFile
790 return Path.GetFileName (output_file);
794 static void SetWarningLevel (string s)
799 level = Int32.Parse (s);
802 if (level < 0 || level > 4){
803 Report.Error (1900, "Warning level must be in the range 0-4");
806 Report.WarningLevel = level;
809 static void Version ()
811 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
812 Console.WriteLine ("Mono C# compiler version {0}", version);
813 Environment.Exit (0);
817 // Currently handles the Unix-like command line options, but will be
818 // deprecated in favor of the CSCParseOption, which will also handle the
819 // options that start with a dash in the future.
821 bool UnixParseOption (string arg, ref string [] args, ref int i)
825 CSharpParser.yacc_verbose_flag++;
836 case "--main": case "-m":
837 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
838 if ((i + 1) >= args.Length){
840 Environment.Exit (1);
842 RootContext.MainClass = args [++i];
846 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
847 RootContext.Unsafe = true;
850 case "/?": case "/h": case "/help":
853 Environment.Exit (0);
857 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
858 if ((i + 1) >= args.Length){
860 Environment.Exit (1);
862 RootContext.AddConditional (args [++i]);
871 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
872 if ((i + 1) >= args.Length){
874 Environment.Exit (1);
876 OutputFile = args [++i];
880 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
881 RootContext.Checked = true;
885 Report.Stacktrace = true;
888 case "--linkresource":
890 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
891 if ((i + 1) >= args.Length){
893 Report.Error (5, "Missing argument to --linkres");
894 Environment.Exit (1);
896 if (embedded_resources == null)
897 embedded_resources = new Resources ();
899 embedded_resources.Add (false, args [++i], args [i]);
904 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
905 if ((i + 1) >= args.Length){
907 Report.Error (5, "Missing argument to --resource");
908 Environment.Exit (1);
910 if (embedded_resources == null)
911 embedded_resources = new Resources ();
913 embedded_resources.Add (true, args [++i], args [i]);
917 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
918 if ((i + 1) >= args.Length){
919 Environment.Exit (1);
923 string type = args [++i];
926 RootContext.Target = Target.Library;
927 RootContext.TargetExt = ".dll";
931 RootContext.Target = Target.Exe;
935 RootContext.Target = Target.WinExe;
939 RootContext.Target = Target.Module;
940 RootContext.TargetExt = ".dll";
949 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
950 if ((i + 1) >= args.Length){
952 Environment.Exit (1);
955 string val = args [++i];
956 int idx = val.IndexOf ('=');
958 string alias = val.Substring (0, idx);
959 string assembly = val.Substring (idx + 1);
960 AddExternAlias (alias, assembly);
964 references.Add (val);
968 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
969 if ((i + 1) >= args.Length){
971 Environment.Exit (1);
973 link_paths.Add (args [++i]);
977 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
978 RootContext.StdLib = false;
986 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
987 if ((i + 1) >= args.Length){
989 Environment.Exit (1);
994 warn = Int32.Parse (args [++i]);
997 Environment.Exit (1);
999 Report.SetIgnoreWarning (warn);
1003 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1004 if ((i + 1) >= args.Length){
1007 "--wlevel requires a value from 0 to 4");
1008 Environment.Exit (1);
1011 SetWarningLevel (args [++i]);
1015 if ((i + 1) >= args.Length){
1016 Report.Error (5, "--mcs-debug requires an argument");
1017 Environment.Exit (1);
1021 Report.DebugFlags = Int32.Parse (args [++i]);
1023 Report.Error (5, "Invalid argument to --mcs-debug");
1024 Environment.Exit (1);
1033 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1034 if ((i + 1) >= args.Length){
1035 Report.Error (5, "--recurse requires an argument");
1036 Environment.Exit (1);
1038 ProcessSourceFiles (args [++i], true);
1043 last_time = first_time = DateTime.Now;
1046 case "--debug": case "-g":
1047 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1048 want_debugging_support = true;
1052 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1053 load_default_config = false;
1061 public static string GetPackageFlags (string packages, bool fatal)
1063 ProcessStartInfo pi = new ProcessStartInfo ();
1064 pi.FileName = "pkg-config";
1065 pi.RedirectStandardOutput = true;
1066 pi.UseShellExecute = false;
1067 pi.Arguments = "--libs " + packages;
1070 p = Process.Start (pi);
1071 } catch (Exception e) {
1072 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1074 Environment.Exit (1);
1079 if (p.StandardOutput == null){
1080 Report.Warning (-27, 1, "Specified package did not return any information");
1084 string pkgout = p.StandardOutput.ReadToEnd ();
1086 if (p.ExitCode != 0) {
1087 Report.Error (-27, "Error running pkg-config. Check the above output.");
1089 Environment.Exit (1);
1100 // This parses the -arg and /arg options to the compiler, even if the strings
1101 // in the following text use "/arg" on the strings.
1103 bool CSCParseOption (string option, ref string [] args)
1105 int idx = option.IndexOf (':');
1112 arg = option.Substring (0, idx);
1114 value = option.Substring (idx + 1);
1117 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1125 RootContext.Target = Target.Exe;
1129 RootContext.Target = Target.WinExe;
1133 RootContext.Target = Target.Library;
1134 RootContext.TargetExt = ".dll";
1138 RootContext.Target = Target.Module;
1139 RootContext.TargetExt = ".netmodule";
1149 if (value.Length == 0){
1151 Environment.Exit (1);
1160 RootContext.Optimize = true;
1165 RootContext.Optimize = false;
1168 case "/incremental":
1169 case "/incremental+":
1170 case "/incremental-":
1176 if (value.Length == 0){
1178 Environment.Exit (1);
1181 foreach (string d in value.Split (argument_value_separator)) {
1182 if (!Tokenizer.IsValidIdentifier (d)) {
1183 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1186 RootContext.AddConditional (d);
1193 // We should collect data, runtime, etc and store in the file specified
1195 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1201 if (value.Length == 0){
1203 Environment.Exit (1);
1205 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1206 string pkgout = GetPackageFlags (packages, true);
1208 if (pkgout != null){
1209 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1210 Split (new Char [] { ' ', '\t'});
1211 args = AddArgs (args, xargs);
1218 case "/linkresource":
1221 if (embedded_resources == null)
1222 embedded_resources = new Resources ();
1224 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1225 string[] s = value.Split (argument_value_separator);
1228 if (s[0].Length == 0)
1230 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1233 embedded_resources.Add (embeded, s [0], s [1]);
1236 if (s [2] != "public" && s [2] != "private") {
1237 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1240 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1243 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1250 if (value.Length == 0){
1251 Report.Error (5, "-recurse requires an argument");
1252 Environment.Exit (1);
1254 ProcessSourceFiles (value, true);
1258 case "/reference": {
1259 if (value.Length == 0){
1260 Report.Error (5, "-reference requires an argument");
1261 Environment.Exit (1);
1264 string[] refs = value.Split (argument_value_separator);
1265 foreach (string r in refs){
1267 int index = val.IndexOf ('=');
1269 string alias = r.Substring (0, index);
1270 string assembly = r.Substring (index + 1);
1271 AddExternAlias (alias, assembly);
1275 if (val.Length != 0)
1276 references.Add (val);
1280 case "/addmodule": {
1281 if (value.Length == 0){
1282 Report.Error (5, arg + " requires an argument");
1283 Environment.Exit (1);
1286 string[] refs = value.Split (argument_value_separator);
1287 foreach (string r in refs){
1293 if (value.Length == 0) {
1294 Report.Error (5, arg + " requires an argument");
1295 Environment.Exit (1);
1298 if (win32IconFile != null)
1299 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1301 win32ResourceFile = value;
1304 case "/win32icon": {
1305 if (value.Length == 0) {
1306 Report.Error (5, arg + " requires an argument");
1307 Environment.Exit (1);
1310 if (win32ResourceFile != null)
1311 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1313 win32IconFile = value;
1317 if (value.Length == 0){
1318 Report.Error (2006, arg + " requires an argument");
1319 Environment.Exit (1);
1321 RootContext.Documentation = new Documentation (value);
1327 if (value.Length == 0){
1328 Report.Error (5, "/lib requires an argument");
1329 Environment.Exit (1);
1332 libdirs = value.Split (argument_value_separator);
1333 foreach (string dir in libdirs)
1334 link_paths.Add (dir);
1339 want_debugging_support = false;
1344 want_debugging_support = true;
1349 RootContext.Checked = true;
1353 RootContext.Checked = false;
1361 RootContext.VerifyClsCompliance = false;
1366 RootContext.Unsafe = true;
1370 RootContext.Unsafe = false;
1373 case "/warnaserror":
1374 case "/warnaserror+":
1375 if (value.Length == 0) {
1376 Report.WarningsAreErrors = true;
1378 foreach (string wid in value.Split (argument_value_separator))
1379 Report.AddWarningAsError (wid);
1383 case "/warnaserror-":
1384 if (value.Length == 0) {
1385 Report.WarningsAreErrors = false;
1387 foreach (string wid in value.Split (argument_value_separator))
1388 Report.RemoveWarningAsError (wid);
1393 SetWarningLevel (value);
1399 if (value.Length == 0){
1400 Report.Error (5, "/nowarn requires an argument");
1401 Environment.Exit (1);
1404 warns = value.Split (argument_value_separator);
1405 foreach (string wc in warns){
1407 if (wc.Trim ().Length == 0)
1410 int warn = Int32.Parse (wc);
1412 throw new ArgumentOutOfRangeException("warn");
1414 Report.SetIgnoreWarning (warn);
1416 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1423 load_default_config = false;
1428 Environment.Exit(0);
1434 Environment.Exit (0);
1439 if (value.Length == 0){
1440 Report.Error (5, arg + " requires an argument");
1441 Environment.Exit (1);
1443 RootContext.MainClass = value;
1448 RootContext.StdLib = false;
1452 RootContext.StdLib = true;
1459 if (value == String.Empty) {
1460 Report.Error (5, arg + " requires an argument");
1461 Environment.Exit (1);
1463 RootContext.StrongNameKeyFile = value;
1465 case "/keycontainer":
1466 if (value == String.Empty) {
1467 Report.Error (5, arg + " requires an argument");
1468 Environment.Exit (1);
1470 RootContext.StrongNameKeyContainer = value;
1473 RootContext.StrongNameDelaySign = true;
1476 RootContext.StrongNameDelaySign = false;
1479 case "/langversion":
1480 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1482 RootContext.Version = LanguageVersion.ISO_1;
1486 RootContext.Version = LanguageVersion.Default;
1488 RootContext.AddConditional ("__V2__");
1493 RootContext.Version = LanguageVersion.ISO_2;
1496 RootContext.Version = LanguageVersion.Future;
1500 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
1506 encoding = new UTF8Encoding();
1509 encoding = Encoding.Default;
1513 encoding = Encoding.GetEncoding (
1514 Int32.Parse (value));
1516 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1526 static void Error_WrongOption (string option)
1528 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1531 static string [] AddArgs (string [] args, string [] extra_args)
1534 new_args = new string [extra_args.Length + args.Length];
1536 // if args contains '--' we have to take that into account
1537 // split args into first half and second half based on '--'
1538 // and add the extra_args before --
1539 int split_position = Array.IndexOf (args, "--");
1540 if (split_position != -1)
1542 Array.Copy (args, new_args, split_position);
1543 extra_args.CopyTo (new_args, split_position);
1544 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1548 args.CopyTo (new_args, 0);
1549 extra_args.CopyTo (new_args, args.Length);
1555 void AddExternAlias (string identifier, string assembly)
1557 if (assembly.Length == 0) {
1558 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1562 if (!IsExternAliasValid (identifier)) {
1563 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1567 // Could here hashtable throw an exception?
1568 external_aliases [identifier] = assembly;
1571 static bool IsExternAliasValid (string identifier)
1573 if (identifier.Length == 0)
1575 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1578 for (int i = 1; i < identifier.Length; i++) {
1579 char c = identifier [i];
1580 if (Char.IsLetter (c) || Char.IsDigit (c))
1583 UnicodeCategory category = Char.GetUnicodeCategory (c);
1584 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1585 category != UnicodeCategory.SpacingCombiningMark ||
1586 category != UnicodeCategory.ConnectorPunctuation)
1594 // Main compilation method
1596 public bool Compile ()
1599 if (Report.Errors > 0)
1602 if (tokenize || parse_only)
1605 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1606 throw new InternalErrorException ("who set it?");
1608 ProcessDefaultConfig ();
1613 if (output_file == null){
1614 if (first_source == null){
1615 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1619 int pos = first_source.LastIndexOf ('.');
1622 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1624 output_file = first_source + RootContext.TargetExt;
1627 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1630 if (RootContext.Target == Target.Module) {
1631 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1632 if (module_only == null) {
1633 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1634 Environment.Exit (1);
1637 MethodInfo set_method = module_only.GetSetMethod (true);
1638 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1641 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1644 // Load assemblies required
1647 ShowTime ("Loading references");
1651 if (modules.Count > 0) {
1652 foreach (string module in modules)
1653 LoadModule (module);
1657 ShowTime ("References loaded");
1659 if (!TypeManager.InitCoreTypes () || Report.Errors > 0)
1662 TypeManager.InitOptionalCoreTypes ();
1665 ShowTime (" Core Types done");
1667 CodeGen.Module.Resolve ();
1670 // The second pass of the compiler
1673 ShowTime ("Resolving tree");
1674 RootContext.ResolveTree ();
1676 if (Report.Errors > 0)
1679 ShowTime ("Populate tree");
1680 if (!RootContext.StdLib)
1681 RootContext.BootCorlib_PopulateCoreTypes ();
1682 RootContext.PopulateTypes ();
1684 if (Report.Errors == 0 &&
1685 RootContext.Documentation != null &&
1686 !RootContext.Documentation.OutputDocComment (
1691 // Verify using aliases now
1693 NamespaceEntry.VerifyAllUsing ();
1695 if (Report.Errors > 0){
1699 CodeGen.Assembly.Resolve ();
1701 if (RootContext.VerifyClsCompliance) {
1702 if (CodeGen.Assembly.IsClsCompliant) {
1703 AttributeTester.VerifyModulesClsCompliance ();
1704 TypeManager.LoadAllImportedTypes ();
1707 if (Report.Errors > 0)
1711 // The code generator
1714 ShowTime ("Emitting code");
1715 ShowTotalTime ("Total so far");
1716 RootContext.EmitCode ();
1720 if (Report.Errors > 0){
1725 ShowTime ("Closing types");
1727 RootContext.CloseTypes ();
1729 PEFileKinds k = PEFileKinds.ConsoleApplication;
1731 switch (RootContext.Target) {
1732 case Target.Library:
1734 k = PEFileKinds.Dll; break;
1736 k = PEFileKinds.ConsoleApplication; break;
1738 k = PEFileKinds.WindowApplication; break;
1741 if (RootContext.NeedsEntryPoint) {
1742 Method ep = RootContext.EntryPoint;
1745 if (RootContext.MainClass != null) {
1746 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1747 if (main_cont == null) {
1748 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1752 if (!(main_cont is ClassOrStruct)) {
1753 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1757 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1761 if (Report.Errors == 0)
1762 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1767 CodeGen.Assembly.Builder.SetEntryPoint (ep.MethodBuilder, k);
1768 } else if (RootContext.MainClass != null) {
1769 Report.Error (2017, "Cannot specify -main if building a module or library");
1772 if (embedded_resources != null){
1773 if (RootContext.Target == Target.Module) {
1774 Report.Error (1507, "Cannot link resource file when building a module");
1778 embedded_resources.Emit ();
1782 // Add Win32 resources
1785 if (win32ResourceFile != null) {
1787 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1788 } catch (ArgumentException) {
1789 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1792 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1795 if (win32IconFile != null) {
1796 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1797 if (define_icon == null) {
1798 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1800 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1804 if (Report.Errors > 0)
1807 CodeGen.Save (output_file, want_debugging_support);
1809 ShowTime ("Saved output");
1810 ShowTotalTime ("Total");
1813 Timer.ShowTimers ();
1815 if (Report.ExpectedError != 0) {
1816 if (Report.Errors == 0) {
1817 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1818 "No other errors reported.");
1820 Environment.Exit (2);
1822 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1823 "However, other errors were reported.");
1825 Environment.Exit (1);
1833 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1834 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1836 return (Report.Errors == 0);
1845 string FileName { get; }
1848 class EmbededResource : IResource
1850 static MethodInfo embed_res;
1852 static EmbededResource () {
1853 Type[] argst = new Type [] {
1854 typeof (string), typeof (string), typeof (ResourceAttributes)
1857 embed_res = typeof (AssemblyBuilder).GetMethod (
1858 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1859 null, CallingConventions.Any, argst, null);
1861 if (embed_res == null) {
1862 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1866 readonly object[] args;
1868 public EmbededResource (string name, string file, bool isPrivate)
1870 args = new object [3];
1873 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1878 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1881 public string FileName {
1883 return (string)args [1];
1888 class LinkedResource : IResource
1890 readonly string file;
1891 readonly string name;
1892 readonly ResourceAttributes attribute;
1894 public LinkedResource (string name, string file, bool isPrivate)
1898 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1903 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1906 public string FileName {
1914 IDictionary embedded_resources = new HybridDictionary ();
1916 public void Add (bool embeded, string file, string name)
1918 Add (embeded, file, name, false);
1921 public void Add (bool embeded, string file, string name, bool isPrivate)
1923 if (embedded_resources.Contains (name)) {
1924 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1927 IResource r = embeded ?
1928 (IResource) new EmbededResource (name, file, isPrivate) :
1929 new LinkedResource (name, file, isPrivate);
1931 embedded_resources.Add (name, r);
1936 foreach (IResource r in embedded_resources.Values) {
1937 if (!File.Exists (r.FileName)) {
1938 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1948 // This is the only public entry point
1950 public class CompilerCallableEntryPoint : MarshalByRefObject {
1951 public static bool InvokeCompiler (string [] args, TextWriter error)
1953 Report.Stderr = error;
1955 Driver d = Driver.Create (args, true);
1959 return d.Compile () && Report.Errors == 0;
1962 Report.Stderr = Console.Error;
1967 public static int[] AllWarningNumbers {
1969 return Report.AllWarnings;
1973 public static void Reset ()
1978 public static void PartialReset ()
1983 public static void Reset (bool full_flag)
1986 RootContext.Reset (full_flag);
1990 TypeManager.Reset ();
1991 TypeHandle.Reset ();
1994 RootNamespace.Reset ();
1996 NamespaceEntry.Reset ();
1999 AttributeTester.Reset ();
2000 AnonymousTypeClass.Reset ();
2001 AnonymousMethodBody.Reset ();
2002 AnonymousMethodStorey.Reset ();
2003 SymbolWriter.Reset ();
2005 Linq.QueryBlock.TransparentParameter.Reset ();