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 4 (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);
478 RootNamespace.ComputeNamespaces ();
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 if (!load_default_config)
741 // For now the "default config" is harcoded into the compiler
742 // we can move this outside later
744 string [] default_config = {
750 "System.Windows.Browser",
754 // Is it worth pre-loading all this stuff?
757 "System.Configuration.Install",
760 "System.DirectoryServices",
761 "System.Drawing.Design",
763 "System.EnterpriseServices",
766 "System.Runtime.Remoting",
767 "System.Runtime.Serialization.Formatters.Soap",
769 "System.ServiceProcess",
771 "System.Web.RegularExpressions",
772 "System.Web.Services",
773 "System.Windows.Forms"
777 soft_references.AddRange (default_config);
779 if (RootContext.Version > LanguageVersion.ISO_2)
780 soft_references.Add ("System.Core");
783 public static string OutputFile
789 return Path.GetFileName (output_file);
793 static void SetWarningLevel (string s)
798 level = Int32.Parse (s);
801 if (level < 0 || level > 4){
802 Report.Error (1900, "Warning level must be in the range 0-4");
805 Report.WarningLevel = level;
808 static void Version ()
810 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
811 Console.WriteLine ("Mono C# compiler version {0}", version);
812 Environment.Exit (0);
816 // Currently handles the Unix-like command line options, but will be
817 // deprecated in favor of the CSCParseOption, which will also handle the
818 // options that start with a dash in the future.
820 bool UnixParseOption (string arg, ref string [] args, ref int i)
824 CSharpParser.yacc_verbose_flag++;
835 case "--main": case "-m":
836 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
837 if ((i + 1) >= args.Length){
839 Environment.Exit (1);
841 RootContext.MainClass = args [++i];
845 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
846 RootContext.Unsafe = true;
849 case "/?": case "/h": case "/help":
852 Environment.Exit (0);
856 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
857 if ((i + 1) >= args.Length){
859 Environment.Exit (1);
861 RootContext.AddConditional (args [++i]);
870 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
871 if ((i + 1) >= args.Length){
873 Environment.Exit (1);
875 OutputFile = args [++i];
879 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
880 RootContext.Checked = true;
884 Report.Stacktrace = true;
887 case "--linkresource":
889 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
890 if ((i + 1) >= args.Length){
892 Report.Error (5, "Missing argument to --linkres");
893 Environment.Exit (1);
895 if (embedded_resources == null)
896 embedded_resources = new Resources ();
898 embedded_resources.Add (false, args [++i], args [i]);
903 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
904 if ((i + 1) >= args.Length){
906 Report.Error (5, "Missing argument to --resource");
907 Environment.Exit (1);
909 if (embedded_resources == null)
910 embedded_resources = new Resources ();
912 embedded_resources.Add (true, args [++i], args [i]);
916 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
917 if ((i + 1) >= args.Length){
918 Environment.Exit (1);
922 string type = args [++i];
925 RootContext.Target = Target.Library;
926 RootContext.TargetExt = ".dll";
930 RootContext.Target = Target.Exe;
934 RootContext.Target = Target.WinExe;
938 RootContext.Target = Target.Module;
939 RootContext.TargetExt = ".dll";
948 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
949 if ((i + 1) >= args.Length){
951 Environment.Exit (1);
954 string val = args [++i];
955 int idx = val.IndexOf ('=');
957 string alias = val.Substring (0, idx);
958 string assembly = val.Substring (idx + 1);
959 AddExternAlias (alias, assembly);
963 references.Add (val);
967 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
968 if ((i + 1) >= args.Length){
970 Environment.Exit (1);
972 link_paths.Add (args [++i]);
976 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
977 RootContext.StdLib = false;
985 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
986 Report.WarningsAreErrors = true;
990 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
991 if ((i + 1) >= args.Length){
993 Environment.Exit (1);
998 warn = Int32.Parse (args [++i]);
1001 Environment.Exit (1);
1003 Report.SetIgnoreWarning (warn);
1007 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1008 if ((i + 1) >= args.Length){
1011 "--wlevel requires a value from 0 to 4");
1012 Environment.Exit (1);
1015 SetWarningLevel (args [++i]);
1019 if ((i + 1) >= args.Length){
1020 Report.Error (5, "--mcs-debug requires an argument");
1021 Environment.Exit (1);
1025 Report.DebugFlags = Int32.Parse (args [++i]);
1027 Report.Error (5, "Invalid argument to --mcs-debug");
1028 Environment.Exit (1);
1037 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1038 if ((i + 1) >= args.Length){
1039 Report.Error (5, "--recurse requires an argument");
1040 Environment.Exit (1);
1042 ProcessSourceFiles (args [++i], true);
1047 last_time = first_time = DateTime.Now;
1050 case "--debug": case "-g":
1051 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1052 want_debugging_support = true;
1056 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1057 load_default_config = false;
1065 public static string GetPackageFlags (string packages, bool fatal)
1067 ProcessStartInfo pi = new ProcessStartInfo ();
1068 pi.FileName = "pkg-config";
1069 pi.RedirectStandardOutput = true;
1070 pi.UseShellExecute = false;
1071 pi.Arguments = "--libs " + packages;
1074 p = Process.Start (pi);
1075 } catch (Exception e) {
1076 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1078 Environment.Exit (1);
1083 if (p.StandardOutput == null){
1084 Report.Warning (-27, 1, "Specified package did not return any information");
1088 string pkgout = p.StandardOutput.ReadToEnd ();
1090 if (p.ExitCode != 0) {
1091 Report.Error (-27, "Error running pkg-config. Check the above output.");
1093 Environment.Exit (1);
1104 // This parses the -arg and /arg options to the compiler, even if the strings
1105 // in the following text use "/arg" on the strings.
1107 bool CSCParseOption (string option, ref string [] args)
1109 int idx = option.IndexOf (':');
1116 arg = option.Substring (0, idx);
1118 value = option.Substring (idx + 1);
1121 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1129 RootContext.Target = Target.Exe;
1133 RootContext.Target = Target.WinExe;
1137 RootContext.Target = Target.Library;
1138 RootContext.TargetExt = ".dll";
1142 RootContext.Target = Target.Module;
1143 RootContext.TargetExt = ".netmodule";
1153 if (value.Length == 0){
1155 Environment.Exit (1);
1164 RootContext.Optimize = true;
1169 RootContext.Optimize = false;
1172 case "/incremental":
1173 case "/incremental+":
1174 case "/incremental-":
1180 if (value.Length == 0){
1182 Environment.Exit (1);
1185 foreach (string d in value.Split (';', ',')){
1186 if (!Tokenizer.IsValidIdentifier (d)) {
1187 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1190 RootContext.AddConditional (d);
1197 // We should collect data, runtime, etc and store in the file specified
1199 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1205 if (value.Length == 0){
1207 Environment.Exit (1);
1209 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1210 string pkgout = GetPackageFlags (packages, true);
1212 if (pkgout != null){
1213 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1214 Split (new Char [] { ' ', '\t'});
1215 args = AddArgs (args, xargs);
1222 case "/linkresource":
1225 if (embedded_resources == null)
1226 embedded_resources = new Resources ();
1228 bool embeded = arg.StartsWith ("/r");
1229 string[] s = value.Split (',');
1232 if (s[0].Length == 0)
1234 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1237 embedded_resources.Add (embeded, s [0], s [1]);
1240 if (s [2] != "public" && s [2] != "private") {
1241 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1244 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1247 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1254 if (value.Length == 0){
1255 Report.Error (5, "-recurse requires an argument");
1256 Environment.Exit (1);
1258 ProcessSourceFiles (value, true);
1262 case "/reference": {
1263 if (value.Length == 0){
1264 Report.Error (5, "-reference requires an argument");
1265 Environment.Exit (1);
1268 string [] refs = value.Split (new char [] { ';', ',' });
1269 foreach (string r in refs){
1271 int index = val.IndexOf ('=');
1273 string alias = r.Substring (0, index);
1274 string assembly = r.Substring (index + 1);
1275 AddExternAlias (alias, assembly);
1279 if (val.Length != 0)
1280 references.Add (val);
1284 case "/addmodule": {
1285 if (value.Length == 0){
1286 Report.Error (5, arg + " requires an argument");
1287 Environment.Exit (1);
1290 string [] refs = value.Split (new char [] { ';', ',' });
1291 foreach (string r in refs){
1297 if (value.Length == 0) {
1298 Report.Error (5, arg + " requires an argument");
1299 Environment.Exit (1);
1302 if (win32IconFile != null)
1303 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1305 win32ResourceFile = value;
1308 case "/win32icon": {
1309 if (value.Length == 0) {
1310 Report.Error (5, arg + " requires an argument");
1311 Environment.Exit (1);
1314 if (win32ResourceFile != null)
1315 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1317 win32IconFile = value;
1321 if (value.Length == 0){
1322 Report.Error (2006, arg + " requires an argument");
1323 Environment.Exit (1);
1325 RootContext.Documentation = new Documentation (value);
1331 if (value.Length == 0){
1332 Report.Error (5, "/lib requires an argument");
1333 Environment.Exit (1);
1336 libdirs = value.Split (new Char [] { ',' });
1337 foreach (string dir in libdirs)
1338 link_paths.Add (dir);
1343 want_debugging_support = false;
1348 want_debugging_support = true;
1353 RootContext.Checked = true;
1357 RootContext.Checked = false;
1365 RootContext.VerifyClsCompliance = false;
1370 RootContext.Unsafe = true;
1374 RootContext.Unsafe = false;
1377 case "/warnaserror":
1378 case "/warnaserror+":
1379 Report.WarningsAreErrors = true;
1382 case "/warnaserror-":
1383 Report.WarningsAreErrors = false;
1387 SetWarningLevel (value);
1393 if (value.Length == 0){
1394 Report.Error (5, "/nowarn requires an argument");
1395 Environment.Exit (1);
1398 warns = value.Split (new Char [] {','});
1399 foreach (string wc in warns){
1401 int warn = Int32.Parse (wc);
1403 throw new ArgumentOutOfRangeException("warn");
1405 Report.SetIgnoreWarning (warn);
1407 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1414 load_default_config = false;
1419 Environment.Exit(0);
1425 Environment.Exit (0);
1430 if (value.Length == 0){
1431 Report.Error (5, arg + " requires an argument");
1432 Environment.Exit (1);
1434 RootContext.MainClass = value;
1439 RootContext.StdLib = false;
1443 RootContext.StdLib = true;
1450 if (value == String.Empty) {
1451 Report.Error (5, arg + " requires an argument");
1452 Environment.Exit (1);
1454 RootContext.StrongNameKeyFile = value;
1456 case "/keycontainer":
1457 if (value == String.Empty) {
1458 Report.Error (5, arg + " requires an argument");
1459 Environment.Exit (1);
1461 RootContext.StrongNameKeyContainer = value;
1464 RootContext.StrongNameDelaySign = true;
1467 RootContext.StrongNameDelaySign = false;
1470 case "/langversion":
1471 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1473 RootContext.Version = LanguageVersion.ISO_1;
1477 RootContext.Version = LanguageVersion.Default;
1479 RootContext.AddConditional ("__V2__");
1484 RootContext.Version = LanguageVersion.ISO_2;
1488 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
1494 encoding = new UTF8Encoding();
1497 encoding = Encoding.Default;
1501 encoding = Encoding.GetEncoding (
1502 Int32.Parse (value));
1504 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1514 static void Error_WrongOption (string option)
1516 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1519 static string [] AddArgs (string [] args, string [] extra_args)
1522 new_args = new string [extra_args.Length + args.Length];
1524 // if args contains '--' we have to take that into account
1525 // split args into first half and second half based on '--'
1526 // and add the extra_args before --
1527 int split_position = Array.IndexOf (args, "--");
1528 if (split_position != -1)
1530 Array.Copy (args, new_args, split_position);
1531 extra_args.CopyTo (new_args, split_position);
1532 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1536 args.CopyTo (new_args, 0);
1537 extra_args.CopyTo (new_args, args.Length);
1543 static void AddExternAlias (string identifier, string assembly)
1545 if (assembly.Length == 0) {
1546 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1550 if (!IsExternAliasValid (identifier)) {
1551 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1555 // Could here hashtable throw an exception?
1556 external_aliases [identifier] = assembly;
1559 static bool IsExternAliasValid (string identifier)
1561 if (identifier.Length == 0)
1563 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1566 for (int i = 1; i < identifier.Length; i++) {
1567 char c = identifier [i];
1568 if (Char.IsLetter (c) || Char.IsDigit (c))
1571 UnicodeCategory category = Char.GetUnicodeCategory (c);
1572 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1573 category != UnicodeCategory.SpacingCombiningMark ||
1574 category != UnicodeCategory.ConnectorPunctuation)
1582 // Main compilation method
1584 public bool Compile ()
1587 if (Report.Errors > 0)
1590 if (tokenize || parse_only)
1593 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1594 throw new InternalErrorException ("who set it?");
1596 ProcessDefaultConfig ();
1599 // Load assemblies required
1602 ShowTime ("Loading references");
1606 ShowTime (" References loaded");
1608 if (Report.Errors > 0){
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);
1645 if (modules.Count > 0) {
1646 foreach (string module in modules)
1647 LoadModule (module);
1650 if (!TypeManager.InitCoreTypes ())
1653 TypeManager.InitOptionalCoreTypes ();
1656 ShowTime (" Core Types done");
1658 CodeGen.Module.Resolve ();
1661 // The second pass of the compiler
1664 ShowTime ("Resolving tree");
1665 RootContext.ResolveTree ();
1667 if (Report.Errors > 0)
1670 ShowTime ("Populate tree");
1671 if (!RootContext.StdLib)
1672 RootContext.BootCorlib_PopulateCoreTypes ();
1673 RootContext.PopulateTypes ();
1675 if (Report.Errors == 0 &&
1676 RootContext.Documentation != null &&
1677 !RootContext.Documentation.OutputDocComment (
1682 // Verify using aliases now
1684 NamespaceEntry.VerifyAllUsing ();
1686 if (Report.Errors > 0){
1690 CodeGen.Assembly.Resolve ();
1692 if (RootContext.VerifyClsCompliance) {
1693 if (CodeGen.Assembly.IsClsCompliant) {
1694 AttributeTester.VerifyModulesClsCompliance ();
1695 TypeManager.LoadAllImportedTypes ();
1698 if (Report.Errors > 0)
1702 // The code generator
1705 ShowTime ("Emitting code");
1706 ShowTotalTime ("Total so far");
1707 RootContext.EmitCode ();
1711 if (Report.Errors > 0){
1716 ShowTime ("Closing types");
1718 RootContext.CloseTypes ();
1720 PEFileKinds k = PEFileKinds.ConsoleApplication;
1722 switch (RootContext.Target) {
1723 case Target.Library:
1725 k = PEFileKinds.Dll; break;
1727 k = PEFileKinds.ConsoleApplication; break;
1729 k = PEFileKinds.WindowApplication; break;
1732 if (RootContext.NeedsEntryPoint) {
1733 MethodInfo ep = RootContext.EntryPoint;
1736 if (RootContext.MainClass != null) {
1737 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1738 if (main_cont == null) {
1739 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1743 if (!(main_cont is ClassOrStruct)) {
1744 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1748 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1752 if (Report.Errors == 0)
1753 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1758 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1759 } else if (RootContext.MainClass != null) {
1760 Report.Error (2017, "Cannot specify -main if building a module or library");
1763 if (embedded_resources != null){
1764 if (RootContext.Target == Target.Module) {
1765 Report.Error (1507, "Cannot link resource file when building a module");
1769 embedded_resources.Emit ();
1773 // Add Win32 resources
1776 if (win32ResourceFile != null) {
1778 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1779 } catch (ArgumentException) {
1780 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1783 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1786 if (win32IconFile != null) {
1787 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1788 if (define_icon == null) {
1789 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1791 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1795 if (Report.Errors > 0)
1798 CodeGen.Save (output_file, want_debugging_support);
1800 ShowTime ("Saved output");
1801 ShowTotalTime ("Total");
1804 Timer.ShowTimers ();
1806 if (Report.ExpectedError != 0) {
1807 if (Report.Errors == 0) {
1808 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1809 "No other errors reported.");
1811 Environment.Exit (2);
1813 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1814 "However, other errors were reported.");
1816 Environment.Exit (1);
1824 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1825 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1827 return (Report.Errors == 0);
1836 string FileName { get; }
1839 class EmbededResource : IResource
1841 static MethodInfo embed_res;
1843 static EmbededResource () {
1844 Type[] argst = new Type [] {
1845 typeof (string), typeof (string), typeof (ResourceAttributes)
1848 embed_res = typeof (AssemblyBuilder).GetMethod (
1849 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1850 null, CallingConventions.Any, argst, null);
1852 if (embed_res == null) {
1853 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1857 readonly object[] args;
1859 public EmbededResource (string name, string file, bool isPrivate)
1861 args = new object [3];
1864 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1869 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1872 public string FileName {
1874 return (string)args [1];
1879 class LinkedResource : IResource
1881 readonly string file;
1882 readonly string name;
1883 readonly ResourceAttributes attribute;
1885 public LinkedResource (string name, string file, bool isPrivate)
1889 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1894 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1897 public string FileName {
1905 IDictionary embedded_resources = new HybridDictionary ();
1907 public void Add (bool embeded, string file, string name)
1909 Add (embeded, file, name, false);
1912 public void Add (bool embeded, string file, string name, bool isPrivate)
1914 if (embedded_resources.Contains (name)) {
1915 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1918 IResource r = embeded ?
1919 (IResource) new EmbededResource (name, file, isPrivate) :
1920 new LinkedResource (name, file, isPrivate);
1922 embedded_resources.Add (name, r);
1927 foreach (IResource r in embedded_resources.Values) {
1928 if (!File.Exists (r.FileName)) {
1929 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1939 // This is the only public entry point
1941 public class CompilerCallableEntryPoint : MarshalByRefObject {
1942 public static bool InvokeCompiler (string [] args, TextWriter error)
1944 Report.Stderr = error;
1946 Driver d = Driver.Create (args, true);
1950 return d.Compile () && Report.Errors == 0;
1953 Report.Stderr = Console.Error;
1958 public static int[] AllWarningNumbers {
1960 return Report.AllWarnings;
1964 public static void Reset ()
1969 public static void PartialReset ()
1974 public static void Reset (bool full_flag)
1977 RootContext.Reset (full_flag);
1981 TypeManager.Reset ();
1982 TypeHandle.Reset ();
1985 RootNamespace.Reset ();
1987 NamespaceEntry.Reset ();
1990 AttributeTester.Reset ();
1991 AnonymousTypeClass.Reset ();
1992 AnonymousMethodBody.Reset ();
1993 AnonymousMethodStorey.Reset ();
1994 SymbolWriter.Reset ();