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 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
294 Driver d = Driver.Create (args, true);
298 if (d.Compile () && Report.Errors == 0) {
299 if (Report.Warnings > 0) {
300 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
302 Environment.Exit (0);
307 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
308 Report.Errors, Report.Warnings);
309 Environment.Exit (1);
313 static public void LoadAssembly (string assembly, bool soft)
315 LoadAssembly (assembly, null, soft);
318 static void Error6 (string name, string log)
320 if (log != null && log.Length > 0)
321 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
322 Report.Error (6, "cannot find metadata file `{0}'", name);
325 static void Error9 (string type, string filename, string log)
327 if (log != null && log.Length > 0)
328 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
329 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
332 static void BadAssembly (string filename, string log)
334 MethodInfo adder_method = AssemblyClass.AddModule_Method;
336 if (adder_method != null) {
337 AssemblyName an = new AssemblyName ();
339 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
343 m = adder_method.Invoke (ab, new object [] { filename });
344 } catch (TargetInvocationException ex) {
345 throw ex.InnerException;
349 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
350 Path.GetFileName (filename));
353 } catch (FileNotFoundException) {
354 // did the file get deleted during compilation? who cares? swallow the exception
355 } catch (BadImageFormatException) {
357 } catch (FileLoadException) {
361 Error9 ("assembly", filename, log);
364 static public void LoadAssembly (string assembly, string alias, bool soft)
367 string total_log = "";
371 char[] path_chars = { '/', '\\' };
373 if (assembly.IndexOfAny (path_chars) != -1) {
374 a = Assembly.LoadFrom (assembly);
376 string ass = assembly;
377 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
378 ass = assembly.Substring (0, assembly.Length - 4);
379 a = Assembly.Load (ass);
381 } catch (FileNotFoundException) {
383 foreach (string dir in link_paths) {
384 string full_path = Path.Combine (dir, assembly);
385 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
389 a = Assembly.LoadFrom (full_path);
392 } catch (FileNotFoundException ff) {
395 total_log += ff.FusionLog;
399 Error6 (assembly, total_log);
404 // Extern aliased refs require special handling
406 GlobalRootNamespace.Instance.AddAssemblyReference (a);
408 GlobalRootNamespace.Instance.DefineRootNamespace (alias, a);
410 } catch (BadImageFormatException f) {
411 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
412 BadAssembly (f.FileName, f.FusionLog);
413 } catch (FileLoadException f) {
414 // ... while .NET 1.1 throws this
415 BadAssembly (f.FileName, f.FusionLog);
419 static public void LoadModule (string module)
422 string total_log = "";
426 m = CodeGen.Assembly.AddModule (module);
427 } catch (FileNotFoundException) {
429 foreach (string dir in link_paths) {
430 string full_path = Path.Combine (dir, module);
431 if (!module.EndsWith (".netmodule"))
432 full_path += ".netmodule";
435 m = CodeGen.Assembly.AddModule (full_path);
438 } catch (FileNotFoundException ff) {
439 total_log += ff.FusionLog;
443 Error6 (module, total_log);
448 GlobalRootNamespace.Instance.AddModuleReference (m);
450 } catch (BadImageFormatException f) {
451 Error9 ("module", f.FileName, f.FusionLog);
452 } catch (FileLoadException f) {
453 Error9 ("module", f.FileName, f.FusionLog);
458 /// Loads all assemblies referenced on the command line
460 public void LoadReferences ()
462 link_paths.Add (GetSystemDir ());
463 link_paths.Add (Directory.GetCurrentDirectory ());
466 // Load Core Library for default compilation
468 if (RootContext.StdLib)
469 LoadAssembly ("mscorlib", false);
471 foreach (string r in soft_references)
472 LoadAssembly (r, true);
474 foreach (string r in references)
475 LoadAssembly (r, false);
477 foreach (DictionaryEntry entry in external_aliases)
478 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
480 GlobalRootNamespace.Instance.ComputeNamespaces ();
483 static string [] LoadArgs (string file)
486 ArrayList args = new ArrayList ();
489 f = new StreamReader (file);
494 StringBuilder sb = new StringBuilder ();
496 while ((line = f.ReadLine ()) != null){
499 for (int i = 0; i < t; i++){
502 if (c == '"' || c == '\''){
505 for (i++; i < t; i++){
512 } else if (c == ' '){
514 args.Add (sb.ToString ());
521 args.Add (sb.ToString ());
526 string [] ret_value = new string [args.Count];
527 args.CopyTo (ret_value, 0);
533 // Returns the directory where the system assemblies are installed
535 static string GetSystemDir ()
537 return Path.GetDirectoryName (typeof (object).Assembly.Location);
541 // Given a path specification, splits the path from the file/pattern
543 static void SplitPathAndPattern (string spec, out string path, out string pattern)
545 int p = spec.LastIndexOf ('/');
548 // Windows does not like /file.cs, switch that to:
553 pattern = spec.Substring (1);
555 path = spec.Substring (0, p);
556 pattern = spec.Substring (p + 1);
561 p = spec.LastIndexOf ('\\');
563 path = spec.Substring (0, p);
564 pattern = spec.Substring (p + 1);
572 void AddSourceFile (string f)
574 if (first_source == null)
577 Location.AddFile (f);
580 bool ParseArguments (string[] args, bool require_files)
582 references = new ArrayList ();
583 external_aliases = new Hashtable ();
584 soft_references = new ArrayList ();
585 modules = new ArrayList (2);
586 link_paths = new ArrayList ();
588 ArrayList response_file_list = null;
589 bool parsing_options = true;
591 for (int i = 0; i < args.Length; i++) {
592 string arg = args [i];
596 if (arg [0] == '@') {
597 string [] extra_args;
598 string response_file = arg.Substring (1);
600 if (response_file_list == null)
601 response_file_list = new ArrayList ();
603 if (response_file_list.Contains (response_file)) {
605 1515, "Response file `" + response_file +
606 "' specified multiple times");
610 response_file_list.Add (response_file);
612 extra_args = LoadArgs (response_file);
613 if (extra_args == null) {
614 Report.Error (2011, "Unable to open response file: " +
619 args = AddArgs (args, extra_args);
623 if (parsing_options) {
625 parsing_options = false;
629 if (arg [0] == '-') {
630 if (UnixParseOption (arg, ref args, ref i))
634 string csc_opt = "/" + arg.Substring (1);
635 if (CSCParseOption (csc_opt, ref args))
638 Error_WrongOption (arg);
641 if (arg [0] == '/') {
642 if (CSCParseOption (arg, ref args))
645 // Need to skip `/home/test.cs' however /test.cs is considered as error
646 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
647 Error_WrongOption (arg);
653 ProcessSourceFiles (arg, false);
656 if (require_files == false)
660 // If we are an exe, require a source file for the entry point
662 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
663 if (first_source == null) {
664 Report.Error (2008, "No files to compile were specified");
671 // If there is nothing to put in the assembly, and we are not a library
673 if (first_source == null && embedded_resources == null) {
674 Report.Error (2008, "No files to compile were specified");
683 Location.Initialize ();
685 ArrayList cu = Location.SourceFiles;
686 for (int i = 0; i < cu.Count; ++i) {
688 tokenize_file ((CompilationUnit) cu [i]);
690 Parse ((CompilationUnit) cu [i]);
695 void ProcessSourceFiles (string spec, bool recurse)
697 string path, pattern;
699 SplitPathAndPattern (spec, out path, out pattern);
700 if (pattern.IndexOf ('*') == -1){
701 AddSourceFile (spec);
705 string [] files = null;
707 files = Directory.GetFiles (path, pattern);
708 } catch (System.IO.DirectoryNotFoundException) {
709 Report.Error (2001, "Source file `" + spec + "' could not be found");
711 } catch (System.IO.IOException){
712 Report.Error (2001, "Source file `" + spec + "' could not be found");
715 foreach (string f in files) {
722 string [] dirs = null;
725 dirs = Directory.GetDirectories (path);
729 foreach (string d in dirs) {
731 // Don't include path in this string, as each
732 // directory entry already does
733 ProcessSourceFiles (d + "/" + pattern, true);
737 public void ProcessDefaultConfig ()
739 if (!load_default_config)
743 // For now the "default config" is harcoded into the compiler
744 // we can move this outside later
746 string [] default_config = {
752 "System.Windows.Browser",
756 // Is it worth pre-loading all this stuff?
759 "System.Configuration.Install",
762 "System.DirectoryServices",
763 "System.Drawing.Design",
765 "System.EnterpriseServices",
768 "System.Runtime.Remoting",
769 "System.Runtime.Serialization.Formatters.Soap",
771 "System.ServiceProcess",
773 "System.Web.RegularExpressions",
774 "System.Web.Services",
775 "System.Windows.Forms"
779 soft_references.AddRange (default_config);
781 if (RootContext.Version > LanguageVersion.ISO_2)
782 soft_references.Add ("System.Core");
785 public static string OutputFile
791 return Path.GetFileName (output_file);
795 static void SetWarningLevel (string s)
800 level = Int32.Parse (s);
803 if (level < 0 || level > 4){
804 Report.Error (1900, "Warning level must be in the range 0-4");
807 Report.WarningLevel = level;
810 static void Version ()
812 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
813 Console.WriteLine ("Mono C# compiler version {0}", version);
814 Environment.Exit (0);
818 // Currently handles the Unix-like command line options, but will be
819 // deprecated in favor of the CSCParseOption, which will also handle the
820 // options that start with a dash in the future.
822 bool UnixParseOption (string arg, ref string [] args, ref int i)
826 CSharpParser.yacc_verbose_flag++;
837 case "--main": case "-m":
838 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
839 if ((i + 1) >= args.Length){
841 Environment.Exit (1);
843 RootContext.MainClass = args [++i];
847 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
848 RootContext.Unsafe = true;
851 case "/?": case "/h": case "/help":
854 Environment.Exit (0);
858 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
859 if ((i + 1) >= args.Length){
861 Environment.Exit (1);
863 RootContext.AddConditional (args [++i]);
872 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
873 if ((i + 1) >= args.Length){
875 Environment.Exit (1);
877 OutputFile = args [++i];
881 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
882 RootContext.Checked = true;
886 Report.Stacktrace = true;
889 case "--linkresource":
891 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
892 if ((i + 1) >= args.Length){
894 Report.Error (5, "Missing argument to --linkres");
895 Environment.Exit (1);
897 if (embedded_resources == null)
898 embedded_resources = new Resources ();
900 embedded_resources.Add (false, args [++i], args [i]);
905 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
906 if ((i + 1) >= args.Length){
908 Report.Error (5, "Missing argument to --resource");
909 Environment.Exit (1);
911 if (embedded_resources == null)
912 embedded_resources = new Resources ();
914 embedded_resources.Add (true, args [++i], args [i]);
918 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
919 if ((i + 1) >= args.Length){
920 Environment.Exit (1);
924 string type = args [++i];
927 RootContext.Target = Target.Library;
928 RootContext.TargetExt = ".dll";
932 RootContext.Target = Target.Exe;
936 RootContext.Target = Target.WinExe;
940 RootContext.Target = Target.Module;
941 RootContext.TargetExt = ".dll";
950 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
951 if ((i + 1) >= args.Length){
953 Environment.Exit (1);
956 string val = args [++i];
957 int idx = val.IndexOf ('=');
959 string alias = val.Substring (0, idx);
960 string assembly = val.Substring (idx + 1);
961 AddExternAlias (alias, assembly);
965 references.Add (val);
969 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
970 if ((i + 1) >= args.Length){
972 Environment.Exit (1);
974 link_paths.Add (args [++i]);
978 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
979 RootContext.StdLib = false;
987 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
988 if ((i + 1) >= args.Length){
990 Environment.Exit (1);
995 warn = Int32.Parse (args [++i]);
998 Environment.Exit (1);
1000 Report.SetIgnoreWarning (warn);
1004 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1005 if ((i + 1) >= args.Length){
1008 "--wlevel requires a value from 0 to 4");
1009 Environment.Exit (1);
1012 SetWarningLevel (args [++i]);
1016 if ((i + 1) >= args.Length){
1017 Report.Error (5, "--mcs-debug requires an argument");
1018 Environment.Exit (1);
1022 Report.DebugFlags = Int32.Parse (args [++i]);
1024 Report.Error (5, "Invalid argument to --mcs-debug");
1025 Environment.Exit (1);
1034 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1035 if ((i + 1) >= args.Length){
1036 Report.Error (5, "--recurse requires an argument");
1037 Environment.Exit (1);
1039 ProcessSourceFiles (args [++i], true);
1044 last_time = first_time = DateTime.Now;
1047 case "--debug": case "-g":
1048 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1049 want_debugging_support = true;
1053 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1054 load_default_config = false;
1062 public static string GetPackageFlags (string packages, bool fatal)
1064 ProcessStartInfo pi = new ProcessStartInfo ();
1065 pi.FileName = "pkg-config";
1066 pi.RedirectStandardOutput = true;
1067 pi.UseShellExecute = false;
1068 pi.Arguments = "--libs " + packages;
1071 p = Process.Start (pi);
1072 } catch (Exception e) {
1073 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1075 Environment.Exit (1);
1080 if (p.StandardOutput == null){
1081 Report.Warning (-27, 1, "Specified package did not return any information");
1085 string pkgout = p.StandardOutput.ReadToEnd ();
1087 if (p.ExitCode != 0) {
1088 Report.Error (-27, "Error running pkg-config. Check the above output.");
1090 Environment.Exit (1);
1101 // This parses the -arg and /arg options to the compiler, even if the strings
1102 // in the following text use "/arg" on the strings.
1104 bool CSCParseOption (string option, ref string [] args)
1106 int idx = option.IndexOf (':');
1113 arg = option.Substring (0, idx);
1115 value = option.Substring (idx + 1);
1118 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1126 RootContext.Target = Target.Exe;
1130 RootContext.Target = Target.WinExe;
1134 RootContext.Target = Target.Library;
1135 RootContext.TargetExt = ".dll";
1139 RootContext.Target = Target.Module;
1140 RootContext.TargetExt = ".netmodule";
1150 if (value.Length == 0){
1152 Environment.Exit (1);
1161 RootContext.Optimize = true;
1166 RootContext.Optimize = false;
1169 case "/incremental":
1170 case "/incremental+":
1171 case "/incremental-":
1177 if (value.Length == 0){
1179 Environment.Exit (1);
1182 foreach (string d in value.Split (argument_value_separator)) {
1183 if (!Tokenizer.IsValidIdentifier (d)) {
1184 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1187 RootContext.AddConditional (d);
1194 // We should collect data, runtime, etc and store in the file specified
1196 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1202 if (value.Length == 0){
1204 Environment.Exit (1);
1206 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1207 string pkgout = GetPackageFlags (packages, true);
1209 if (pkgout != null){
1210 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1211 Split (new Char [] { ' ', '\t'});
1212 args = AddArgs (args, xargs);
1219 case "/linkresource":
1222 if (embedded_resources == null)
1223 embedded_resources = new Resources ();
1225 bool embeded = arg [1] == 'r' || arg [1] == 'R';
1226 string[] s = value.Split (argument_value_separator);
1229 if (s[0].Length == 0)
1231 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1234 embedded_resources.Add (embeded, s [0], s [1]);
1237 if (s [2] != "public" && s [2] != "private") {
1238 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1241 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1244 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1251 if (value.Length == 0){
1252 Report.Error (5, "-recurse requires an argument");
1253 Environment.Exit (1);
1255 ProcessSourceFiles (value, true);
1259 case "/reference": {
1260 if (value.Length == 0){
1261 Report.Error (5, "-reference requires an argument");
1262 Environment.Exit (1);
1265 string[] refs = value.Split (argument_value_separator);
1266 foreach (string r in refs){
1268 int index = val.IndexOf ('=');
1270 string alias = r.Substring (0, index);
1271 string assembly = r.Substring (index + 1);
1272 AddExternAlias (alias, assembly);
1276 if (val.Length != 0)
1277 references.Add (val);
1281 case "/addmodule": {
1282 if (value.Length == 0){
1283 Report.Error (5, arg + " requires an argument");
1284 Environment.Exit (1);
1287 string[] refs = value.Split (argument_value_separator);
1288 foreach (string r in refs){
1294 if (value.Length == 0) {
1295 Report.Error (5, arg + " requires an argument");
1296 Environment.Exit (1);
1299 if (win32IconFile != null)
1300 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1302 win32ResourceFile = value;
1305 case "/win32icon": {
1306 if (value.Length == 0) {
1307 Report.Error (5, arg + " requires an argument");
1308 Environment.Exit (1);
1311 if (win32ResourceFile != null)
1312 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1314 win32IconFile = value;
1318 if (value.Length == 0){
1319 Report.Error (2006, arg + " requires an argument");
1320 Environment.Exit (1);
1322 RootContext.Documentation = new Documentation (value);
1328 if (value.Length == 0){
1329 Report.Error (5, "/lib requires an argument");
1330 Environment.Exit (1);
1333 libdirs = value.Split (argument_value_separator);
1334 foreach (string dir in libdirs)
1335 link_paths.Add (dir);
1340 want_debugging_support = false;
1344 if (value == "full" || value == "")
1345 want_debugging_support = true;
1350 want_debugging_support = true;
1355 RootContext.Checked = true;
1359 RootContext.Checked = false;
1367 RootContext.VerifyClsCompliance = false;
1372 RootContext.Unsafe = true;
1376 RootContext.Unsafe = false;
1379 case "/warnaserror":
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 if (value.Length == 0) {
1391 Report.WarningsAreErrors = false;
1393 foreach (string wid in value.Split (argument_value_separator))
1394 Report.RemoveWarningAsError (wid);
1399 SetWarningLevel (value);
1405 if (value.Length == 0){
1406 Report.Error (5, "/nowarn requires an argument");
1407 Environment.Exit (1);
1410 warns = value.Split (argument_value_separator);
1411 foreach (string wc in warns){
1413 if (wc.Trim ().Length == 0)
1416 int warn = Int32.Parse (wc);
1418 throw new ArgumentOutOfRangeException("warn");
1420 Report.SetIgnoreWarning (warn);
1422 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1429 load_default_config = false;
1432 // We just ignore this.
1433 case "/errorreport":
1440 Environment.Exit(0);
1446 Environment.Exit (0);
1451 if (value.Length == 0){
1452 Report.Error (5, arg + " requires an argument");
1453 Environment.Exit (1);
1455 RootContext.MainClass = value;
1460 RootContext.StdLib = false;
1464 RootContext.StdLib = true;
1471 if (value == String.Empty) {
1472 Report.Error (5, arg + " requires an argument");
1473 Environment.Exit (1);
1475 RootContext.StrongNameKeyFile = value;
1477 case "/keycontainer":
1478 if (value == String.Empty) {
1479 Report.Error (5, arg + " requires an argument");
1480 Environment.Exit (1);
1482 RootContext.StrongNameKeyContainer = value;
1485 RootContext.StrongNameDelaySign = true;
1488 RootContext.StrongNameDelaySign = false;
1491 case "/langversion":
1492 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1494 RootContext.Version = LanguageVersion.ISO_1;
1498 RootContext.Version = LanguageVersion.Default;
1500 RootContext.AddConditional ("__V2__");
1504 RootContext.Version = LanguageVersion.ISO_2;
1507 RootContext.Version = LanguageVersion.V_3;
1510 RootContext.Version = LanguageVersion.Future;
1514 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1520 encoding = new UTF8Encoding();
1523 encoding = Encoding.Default;
1527 encoding = Encoding.GetEncoding (
1528 Int32.Parse (value));
1530 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1540 static void Error_WrongOption (string option)
1542 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1545 static string [] AddArgs (string [] args, string [] extra_args)
1548 new_args = new string [extra_args.Length + args.Length];
1550 // if args contains '--' we have to take that into account
1551 // split args into first half and second half based on '--'
1552 // and add the extra_args before --
1553 int split_position = Array.IndexOf (args, "--");
1554 if (split_position != -1)
1556 Array.Copy (args, new_args, split_position);
1557 extra_args.CopyTo (new_args, split_position);
1558 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1562 args.CopyTo (new_args, 0);
1563 extra_args.CopyTo (new_args, args.Length);
1569 void AddExternAlias (string identifier, string assembly)
1571 if (assembly.Length == 0) {
1572 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1576 if (!IsExternAliasValid (identifier)) {
1577 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1581 // Could here hashtable throw an exception?
1582 external_aliases [identifier] = assembly;
1585 static bool IsExternAliasValid (string identifier)
1587 if (identifier.Length == 0)
1589 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1592 for (int i = 1; i < identifier.Length; i++) {
1593 char c = identifier [i];
1594 if (Char.IsLetter (c) || Char.IsDigit (c))
1597 UnicodeCategory category = Char.GetUnicodeCategory (c);
1598 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1599 category != UnicodeCategory.SpacingCombiningMark ||
1600 category != UnicodeCategory.ConnectorPunctuation)
1608 // Main compilation method
1610 public bool Compile ()
1612 // TODO: Should be passed to parser as an argument
1613 RootContext.ToplevelTypes = new ModuleContainer (RootContext.Unsafe);
1616 if (Report.Errors > 0)
1619 if (tokenize || parse_only)
1622 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1623 throw new InternalErrorException ("who set it?");
1625 ProcessDefaultConfig ();
1630 if (output_file == null){
1631 if (first_source == null){
1632 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1636 int pos = first_source.LastIndexOf ('.');
1639 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1641 output_file = first_source + RootContext.TargetExt;
1644 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1647 if (RootContext.Target == Target.Module) {
1648 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1649 if (module_only == null) {
1650 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1651 Environment.Exit (1);
1654 MethodInfo set_method = module_only.GetSetMethod (true);
1655 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1658 GlobalRootNamespace.Instance.AddModuleReference (RootContext.ToplevelTypes.Builder);
1661 // Load assemblies required
1664 ShowTime ("Loading references");
1668 if (modules.Count > 0) {
1669 foreach (string module in modules)
1670 LoadModule (module);
1674 ShowTime ("References loaded");
1676 if (!TypeManager.InitCoreTypes () || Report.Errors > 0)
1679 TypeManager.InitOptionalCoreTypes ();
1682 ShowTime (" Core Types done");
1685 // The second pass of the compiler
1688 ShowTime ("Resolving tree");
1689 RootContext.ResolveTree ();
1691 if (Report.Errors > 0)
1694 ShowTime ("Populate tree");
1695 if (!RootContext.StdLib)
1696 RootContext.BootCorlib_PopulateCoreTypes ();
1697 RootContext.PopulateTypes ();
1699 if (Report.Errors == 0 &&
1700 RootContext.Documentation != null &&
1701 !RootContext.Documentation.OutputDocComment (
1706 // Verify using aliases now
1708 NamespaceEntry.VerifyAllUsing ();
1710 if (Report.Errors > 0){
1714 CodeGen.Assembly.Resolve ();
1716 if (RootContext.VerifyClsCompliance) {
1717 if (CodeGen.Assembly.IsClsCompliant) {
1718 AttributeTester.VerifyModulesClsCompliance ();
1719 TypeManager.LoadAllImportedTypes ();
1722 if (Report.Errors > 0)
1726 // The code generator
1729 ShowTime ("Emitting code");
1730 ShowTotalTime ("Total so far");
1731 RootContext.EmitCode ();
1735 if (Report.Errors > 0){
1740 ShowTime ("Closing types");
1742 RootContext.CloseTypes ();
1744 PEFileKinds k = PEFileKinds.ConsoleApplication;
1746 switch (RootContext.Target) {
1747 case Target.Library:
1749 k = PEFileKinds.Dll; break;
1751 k = PEFileKinds.ConsoleApplication; break;
1753 k = PEFileKinds.WindowApplication; break;
1756 if (RootContext.NeedsEntryPoint) {
1757 Method ep = RootContext.EntryPoint;
1760 if (RootContext.MainClass != null) {
1761 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1762 if (main_cont == null) {
1763 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1767 if (!(main_cont is ClassOrStruct)) {
1768 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1772 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1776 if (Report.Errors == 0)
1777 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1782 CodeGen.Assembly.Builder.SetEntryPoint (ep.MethodBuilder, k);
1783 } else if (RootContext.MainClass != null) {
1784 Report.Error (2017, "Cannot specify -main if building a module or library");
1787 if (embedded_resources != null){
1788 if (RootContext.Target == Target.Module) {
1789 Report.Error (1507, "Cannot link resource file when building a module");
1793 embedded_resources.Emit ();
1797 // Add Win32 resources
1800 if (win32ResourceFile != null) {
1802 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1803 } catch (ArgumentException) {
1804 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1807 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1810 if (win32IconFile != null) {
1811 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1812 if (define_icon == null) {
1813 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1815 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1819 if (Report.Errors > 0)
1822 CodeGen.Save (output_file, want_debugging_support);
1824 ShowTime ("Saved output");
1825 ShowTotalTime ("Total");
1828 Timer.ShowTimers ();
1830 if (Report.ExpectedError != 0) {
1831 if (Report.Errors == 0) {
1832 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1833 "No other errors reported.");
1835 Environment.Exit (2);
1837 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1838 "However, other errors were reported.");
1840 Environment.Exit (1);
1848 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1849 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1851 return (Report.Errors == 0);
1860 string FileName { get; }
1863 class EmbededResource : IResource
1868 ResourceAttributes attributes;
1870 public EmbededResource (string name, string file, bool isPrivate)
1874 this.attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1879 RootContext.ToplevelTypes.Builder.DefineManifestResource (
1880 name, new FileStream (file, FileMode.Open, FileAccess.Read), attributes);
1883 public string FileName {
1884 get { return file; }
1887 static MethodInfo embed_res;
1889 static EmbededResource () {
1890 Type[] argst = new Type [] {
1891 typeof (string), typeof (string), typeof (ResourceAttributes)
1894 embed_res = typeof (AssemblyBuilder).GetMethod (
1895 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1896 null, CallingConventions.Any, argst, null);
1898 if (embed_res == null) {
1899 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1903 readonly object[] args;
1905 public EmbededResource (string name, string file, bool isPrivate)
1907 args = new object [3];
1910 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1915 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1918 public string FileName {
1920 return (string)args [1];
1926 class LinkedResource : IResource
1928 readonly string file;
1929 readonly string name;
1930 readonly ResourceAttributes attribute;
1932 public LinkedResource (string name, string file, bool isPrivate)
1936 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1941 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1944 public string FileName {
1952 IDictionary embedded_resources = new HybridDictionary ();
1954 public void Add (bool embeded, string file, string name)
1956 Add (embeded, file, name, false);
1959 public void Add (bool embeded, string file, string name, bool isPrivate)
1961 if (embedded_resources.Contains (name)) {
1962 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1965 IResource r = embeded ?
1966 (IResource) new EmbededResource (name, file, isPrivate) :
1967 new LinkedResource (name, file, isPrivate);
1969 embedded_resources.Add (name, r);
1974 foreach (IResource r in embedded_resources.Values) {
1975 if (!File.Exists (r.FileName)) {
1976 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1986 // This is the only public entry point
1988 public class CompilerCallableEntryPoint : MarshalByRefObject {
1989 public static bool InvokeCompiler (string [] args, TextWriter error)
1991 Report.Stderr = error;
1993 Driver d = Driver.Create (args, true);
1997 return d.Compile () && Report.Errors == 0;
2000 Report.Stderr = Console.Error;
2005 public static int[] AllWarningNumbers {
2007 return Report.AllWarnings;
2011 public static void Reset ()
2016 public static void PartialReset ()
2021 public static void Reset (bool full_flag)
2024 RootContext.Reset (full_flag);
2027 TypeManager.Reset ();
2028 PredefinedAttributes.Reset ();
2029 TypeHandle.Reset ();
2032 GlobalRootNamespace.Reset ();
2034 NamespaceEntry.Reset ();
2037 AttributeTester.Reset ();
2038 AnonymousTypeClass.Reset ();
2039 AnonymousMethodBody.Reset ();
2040 AnonymousMethodStorey.Reset ();
2041 SymbolWriter.Reset ();
2043 Linq.QueryBlock.TransparentParameter.Reset ();