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
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections.Generic;
20 using System.Globalization;
21 using System.Diagnostics;
26 Library, Exe, Module, WinExe
29 public enum Platform {
30 AnyCPU, X86, X64, IA64
34 /// The compiler driver.
39 // Assemblies references to be linked. Initialized with
41 List<string> references;
44 // If any of these fail, we ignore the problem. This is so
45 // that we can list all the assemblies in Windows and not fail
46 // if they are missing on Linux.
48 List<string> soft_references;
51 // External aliases for assemblies.
53 Dictionary<string, string> external_aliases;
56 // Modules to be linked
61 List<string> link_paths;
63 // Whether we want to only run the tokenizer
70 internal int fatal_errors;
73 // Whether to load the initial config file (what CSC.RSP has by default)
75 bool load_default_config = true;
80 static string output_file;
83 // Last time we took the time
93 internal readonly CompilerContext ctx;
95 static readonly char[] argument_value_separator = new char [] { ';', ',' };
97 static public void Reset ()
102 private Driver (CompilerContext ctx)
105 encoding = Encoding.Default;
108 public static Driver Create (string[] args, bool require_files, ReportPrinter printer)
110 Driver d = new Driver (new CompilerContext (new Report (printer)));
112 if (!d.ParseArguments (args, require_files))
119 get { return ctx.Report; }
122 void ShowTime (string msg)
129 Console.WriteLine ("{0,5}ms {1}", stopwatch.ElapsedMilliseconds, msg);
131 stopwatch = Stopwatch.StartNew ();
134 void ShowTotalTime (string msg)
139 DateTime now = DateTime.Now;
140 TimeSpan span = now - first_time;
143 "[{0:00}:{1:000}] {2}",
144 (int) span.TotalSeconds, span.Milliseconds, msg);
147 void tokenize_file (CompilationUnit file, CompilerContext ctx)
152 input = File.OpenRead (file.Name);
154 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
159 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
160 Tokenizer lexer = new Tokenizer (reader, file, ctx);
161 int token, tokens = 0, errors = 0;
163 while ((token = lexer.token ()) != Token.EOF){
165 if (token == Token.ERROR)
168 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
174 void Parse (CompilationUnit file, ModuleContainer module)
179 input = File.OpenRead (file.Name);
181 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
186 if (input.ReadByte () == 77 && input.ReadByte () == 90) {
187 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
193 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
195 Parse (reader, file, module);
200 void Parse (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
202 CSharpParser parser = new CSharpParser (reader, file, module);
206 static void OtherFlags ()
209 "Other flags in the compiler\n" +
210 " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
211 " --lint Enhanced warnings\n" +
212 " --parse Only parses the source file\n" +
213 " --stacktrace Shows stack trace at error location\n" +
214 " --timestamp Displays time stamps of various compiler events\n" +
215 " -v Verbose parsing (for debugging the parser)\n" +
216 " --mcs-debug X Sets MCS debugging level to X\n");
222 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
223 "mcs [options] source-files\n" +
224 " --about About the Mono C# compiler\n" +
225 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
226 " -checked[+|-] Sets default aritmetic overflow context\n" +
227 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
228 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
229 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
230 " -debug[+|-], -g Generate debugging information\n" +
231 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
232 " -doc:FILE Process documentation comments to XML file\n" +
233 " -help Lists all compiler options (short: -?)\n" +
234 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
235 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
236 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default, or Future\n" +
237 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
238 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
239 " -noconfig Disables implicitly referenced assemblies\n" +
240 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
241 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
242 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
243 " -out:FILE Specifies output assembly name\n" +
245 " -pkg:P1[,Pn] References packages P1..Pn\n" +
247 " -platform:ARCH Specifies the target platform of the output assembly\n" +
248 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
249 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
250 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
251 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
252 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
253 " KIND can be one of: exe, winexe, library, module\n" +
254 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
255 " -warnaserror[+|-] Treats all warnings as errors\n" +
256 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
257 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
258 " -help2 Shows internal compiler options\n" +
261 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
262 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
263 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
264 " -win32icon:FILE Use this icon for the output\n" +
265 " @file Read response file for more options\n\n" +
266 "Options can be of the form -option or /option");
271 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
277 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
278 "The compiler source code is released under the terms of the \n"+
279 "MIT X11 or GNU GPL licenses\n\n" +
281 "For more information on Mono, visit the project Web site\n" +
282 " http://www.mono-project.com\n\n" +
284 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
285 Environment.Exit (0);
288 public static int Main (string[] args)
290 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
291 var crp = new ConsoleReportPrinter ();
292 Driver d = Driver.Create (args, true, crp);
296 crp.Fatal = d.fatal_errors;
298 if (d.Compile () && d.Report.Errors == 0) {
299 if (d.Report.Warnings > 0) {
300 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
302 Environment.Exit (0);
307 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
308 d.Report.Errors, d.Report.Warnings);
309 Environment.Exit (1);
313 void Error6 (string name, string log)
315 if (log != null && log.Length > 0)
316 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
317 Report.Error (6, "cannot find metadata file `{0}'", name);
320 void Error9 (string type, string filename, string log)
322 if (log != null && log.Length > 0)
323 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
324 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
327 void BadAssembly (string filename, string log)
330 MethodInfo adder_method = null; // AssemblyDefinition.AddModule_Method;
332 if (adder_method != null) {
333 AssemblyName an = new AssemblyName ();
335 var ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
339 m = adder_method.Invoke (ab, new object [] { filename });
340 } catch (TargetInvocationException ex) {
341 throw ex.InnerException;
345 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
346 Path.GetFileName (filename));
349 } catch (FileNotFoundException) {
350 // did the file get deleted during compilation? who cares? swallow the exception
351 } catch (BadImageFormatException) {
353 } catch (FileLoadException) {
358 Error9 ("assembly", filename, log);
361 public Assembly LoadAssemblyFile (string assembly, bool soft)
364 string total_log = "";
368 char[] path_chars = { '/', '\\' };
370 if (assembly.IndexOfAny (path_chars) != -1) {
371 a = Assembly.LoadFrom (assembly);
373 string ass = assembly;
374 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
375 ass = assembly.Substring (0, assembly.Length - 4);
376 a = Assembly.Load (ass);
378 } catch (FileNotFoundException) {
380 foreach (string dir in link_paths) {
381 string full_path = Path.Combine (dir, assembly);
382 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
386 a = Assembly.LoadFrom (full_path);
389 } catch (FileNotFoundException ff) {
392 total_log += ff.FusionLog;
396 Error6 (assembly, total_log);
400 } catch (BadImageFormatException f) {
401 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
402 BadAssembly (f.FileName, f.FusionLog);
403 } catch (FileLoadException f) {
404 // ... while .NET 1.1 throws this
405 BadAssembly (f.FileName, f.FusionLog);
411 void LoadModule (AssemblyDefinition assembly, string module)
413 string total_log = "";
417 assembly.AddModule (module);
418 } catch (FileNotFoundException) {
420 foreach (string dir in link_paths) {
421 string full_path = Path.Combine (dir, module);
422 if (!module.EndsWith (".netmodule"))
423 full_path += ".netmodule";
426 assembly.AddModule (full_path);
429 } catch (FileNotFoundException ff) {
430 total_log += ff.FusionLog;
434 Error6 (module, total_log);
438 } catch (BadImageFormatException f) {
439 Error9 ("module", f.FileName, f.FusionLog);
440 } catch (FileLoadException f) {
441 Error9 ("module", f.FileName, f.FusionLog);
446 /// Loads all assemblies referenced on the command line
448 public void LoadReferences (ModuleContainer module, MetadataImporter importer)
450 link_paths.Add (GetSystemDir ());
451 link_paths.Add (Directory.GetCurrentDirectory ());
453 var loaded = new List<Tuple<RootNamespace, Assembly>> ();
456 // Load Core Library for default compilation
458 if (RootContext.StdLib) {
459 a = LoadAssemblyFile ("mscorlib", false);
461 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
464 foreach (string r in soft_references) {
465 a = LoadAssemblyFile (r, true);
467 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
470 foreach (string r in references) {
471 a = LoadAssemblyFile (r, false);
475 var key = Tuple.Create (module.GlobalRootNamespace, a);
476 if (loaded.Contains (key))
482 foreach (var entry in external_aliases) {
483 a = LoadAssemblyFile (entry.Value, false);
487 var key = Tuple.Create (module.CreateRootNamespace (entry.Key), a);
488 if (loaded.Contains (key))
494 foreach (var entry in loaded) {
495 importer.ImportAssembly (entry.Item2, entry.Item1);
499 void LoadModules (AssemblyDefinition assembly)
501 if (modules.Count == 0)
504 foreach (var module in modules) {
505 LoadModule (assembly, module);
509 static string [] LoadArgs (string file)
512 var args = new List<string> ();
515 f = new StreamReader (file);
520 StringBuilder sb = new StringBuilder ();
522 while ((line = f.ReadLine ()) != null){
525 for (int i = 0; i < t; i++){
528 if (c == '"' || c == '\''){
531 for (i++; i < t; i++){
538 } else if (c == ' '){
540 args.Add (sb.ToString ());
547 args.Add (sb.ToString ());
552 return args.ToArray ();
556 // Returns the directory where the system assemblies are installed
558 static string GetSystemDir ()
560 return Path.GetDirectoryName (typeof (object).Assembly.Location);
564 // Given a path specification, splits the path from the file/pattern
566 static void SplitPathAndPattern (string spec, out string path, out string pattern)
568 int p = spec.LastIndexOf ('/');
571 // Windows does not like /file.cs, switch that to:
576 pattern = spec.Substring (1);
578 path = spec.Substring (0, p);
579 pattern = spec.Substring (p + 1);
584 p = spec.LastIndexOf ('\\');
586 path = spec.Substring (0, p);
587 pattern = spec.Substring (p + 1);
595 void AddSourceFile (string f)
597 if (first_source == null)
600 Location.AddFile (Report, f);
603 bool ParseArguments (string[] args, bool require_files)
605 references = new List<string> ();
606 external_aliases = new Dictionary<string, string> ();
607 soft_references = new List<string> ();
608 modules = new List<string> (2);
609 link_paths = new List<string> ();
611 List<string> response_file_list = null;
612 bool parsing_options = true;
614 for (int i = 0; i < args.Length; i++) {
615 string arg = args [i];
619 if (arg [0] == '@') {
620 string [] extra_args;
621 string response_file = arg.Substring (1);
623 if (response_file_list == null)
624 response_file_list = new List<string> ();
626 if (response_file_list.Contains (response_file)) {
628 1515, "Response file `" + response_file +
629 "' specified multiple times");
633 response_file_list.Add (response_file);
635 extra_args = LoadArgs (response_file);
636 if (extra_args == null) {
637 Report.Error (2011, "Unable to open response file: " +
642 args = AddArgs (args, extra_args);
646 if (parsing_options) {
648 parsing_options = false;
652 if (arg [0] == '-') {
653 if (UnixParseOption (arg, ref args, ref i))
657 string csc_opt = "/" + arg.Substring (1);
658 if (CSCParseOption (csc_opt, ref args))
661 Error_WrongOption (arg);
664 if (arg [0] == '/') {
665 if (CSCParseOption (arg, ref args))
668 // Need to skip `/home/test.cs' however /test.cs is considered as error
669 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
670 Error_WrongOption (arg);
676 ProcessSourceFiles (arg, false);
679 if (require_files == false)
683 // If we are an exe, require a source file for the entry point
685 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
686 if (first_source == null) {
687 Report.Error (2008, "No files to compile were specified");
694 // If there is nothing to put in the assembly, and we are not a library
696 if (first_source == null && RootContext.Resources == null) {
697 Report.Error (2008, "No files to compile were specified");
704 public void Parse (ModuleContainer module)
706 Location.Initialize ();
708 var cu = Location.SourceFiles;
709 for (int i = 0; i < cu.Count; ++i) {
711 tokenize_file (cu [i], ctx);
713 Parse (cu [i], module);
718 void ProcessSourceFiles (string spec, bool recurse)
720 string path, pattern;
722 SplitPathAndPattern (spec, out path, out pattern);
723 if (pattern.IndexOf ('*') == -1){
724 AddSourceFile (spec);
728 string [] files = null;
730 files = Directory.GetFiles (path, pattern);
731 } catch (System.IO.DirectoryNotFoundException) {
732 Report.Error (2001, "Source file `" + spec + "' could not be found");
734 } catch (System.IO.IOException){
735 Report.Error (2001, "Source file `" + spec + "' could not be found");
738 foreach (string f in files) {
745 string [] dirs = null;
748 dirs = Directory.GetDirectories (path);
752 foreach (string d in dirs) {
754 // Don't include path in this string, as each
755 // directory entry already does
756 ProcessSourceFiles (d + "/" + pattern, true);
760 public void ProcessDefaultConfig ()
762 if (!load_default_config)
766 // For now the "default config" is harcoded into the compiler
767 // we can move this outside later
769 string [] default_config = {
775 "System.Windows.Browser",
779 // Is it worth pre-loading all this stuff?
782 "System.Configuration.Install",
785 "System.DirectoryServices",
786 "System.Drawing.Design",
788 "System.EnterpriseServices",
791 "System.Runtime.Remoting",
792 "System.Runtime.Serialization.Formatters.Soap",
794 "System.ServiceProcess",
796 "System.Web.RegularExpressions",
797 "System.Web.Services",
798 "System.Windows.Forms"
802 soft_references.AddRange (default_config);
804 if (RootContext.Version > LanguageVersion.ISO_2)
805 soft_references.Add ("System.Core");
806 if (RootContext.Version > LanguageVersion.V_3)
807 soft_references.Add ("Microsoft.CSharp");
810 public static string OutputFile
816 return Path.GetFileName (output_file);
820 void SetWarningLevel (string s)
825 level = Int32.Parse (s);
828 if (level < 0 || level > 4){
829 Report.Error (1900, "Warning level must be in the range 0-4");
832 Report.WarningLevel = level;
835 static void Version ()
837 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
838 Console.WriteLine ("Mono C# compiler version {0}", version);
839 Environment.Exit (0);
843 // Currently handles the Unix-like command line options, but will be
844 // deprecated in favor of the CSCParseOption, which will also handle the
845 // options that start with a dash in the future.
847 bool UnixParseOption (string arg, ref string [] args, ref int i)
851 CSharpParser.yacc_verbose_flag++;
862 case "--main": case "-m":
863 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
864 if ((i + 1) >= args.Length){
866 Environment.Exit (1);
868 RootContext.MainClass = args [++i];
872 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
873 RootContext.Unsafe = true;
876 case "/?": case "/h": case "/help":
879 Environment.Exit (0);
883 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
884 if ((i + 1) >= args.Length){
886 Environment.Exit (1);
888 RootContext.AddConditional (args [++i]);
897 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
898 if ((i + 1) >= args.Length){
900 Environment.Exit (1);
902 OutputFile = args [++i];
906 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
907 RootContext.Checked = true;
911 Report.Printer.Stacktrace = true;
914 case "--linkresource":
916 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
917 if ((i + 1) >= args.Length){
919 Report.Error (5, "Missing argument to --linkres");
920 Environment.Exit (1);
923 AddResource (new AssemblyResource (args[++i], args[i]));
928 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
929 if ((i + 1) >= args.Length){
931 Report.Error (5, "Missing argument to --resource");
932 Environment.Exit (1);
935 AddResource (new AssemblyResource (args[++i], args[i], true));
939 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
940 if ((i + 1) >= args.Length){
941 Environment.Exit (1);
945 string type = args [++i];
948 RootContext.Target = Target.Library;
949 RootContext.TargetExt = ".dll";
953 RootContext.Target = Target.Exe;
957 RootContext.Target = Target.WinExe;
961 RootContext.Target = Target.Module;
962 RootContext.TargetExt = ".dll";
971 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
972 if ((i + 1) >= args.Length){
974 Environment.Exit (1);
977 string val = args [++i];
978 int idx = val.IndexOf ('=');
980 string alias = val.Substring (0, idx);
981 string assembly = val.Substring (idx + 1);
982 AddExternAlias (alias, assembly);
986 references.Add (val);
990 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
991 if ((i + 1) >= args.Length){
993 Environment.Exit (1);
995 link_paths.Add (args [++i]);
999 RootContext.EnhancedWarnings = true;
1003 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1004 RootContext.StdLib = false;
1008 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1009 if ((i + 1) >= args.Length){
1011 Environment.Exit (1);
1016 warn = Int32.Parse (args [++i]);
1019 Environment.Exit (1);
1021 Report.SetIgnoreWarning (warn);
1025 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1026 if ((i + 1) >= args.Length){
1029 "--wlevel requires a value from 0 to 4");
1030 Environment.Exit (1);
1033 SetWarningLevel (args [++i]);
1037 if ((i + 1) >= args.Length){
1038 Report.Error (5, "--mcs-debug requires an argument");
1039 Environment.Exit (1);
1043 Report.DebugFlags = Int32.Parse (args [++i]);
1045 Report.Error (5, "Invalid argument to --mcs-debug");
1046 Environment.Exit (1);
1055 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1056 if ((i + 1) >= args.Length){
1057 Report.Error (5, "--recurse requires an argument");
1058 Environment.Exit (1);
1060 ProcessSourceFiles (args [++i], true);
1067 case "--debug": case "-g":
1068 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1069 RootContext.GenerateDebugInfo = true;
1073 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1074 load_default_config = false;
1078 if (arg.StartsWith ("--fatal")){
1079 if (arg.StartsWith ("--fatal=")){
1080 if (!Int32.TryParse (arg.Substring (8), out fatal_errors))
1093 public static string GetPackageFlags (string packages, bool fatal, Report report)
1095 ProcessStartInfo pi = new ProcessStartInfo ();
1096 pi.FileName = "pkg-config";
1097 pi.RedirectStandardOutput = true;
1098 pi.UseShellExecute = false;
1099 pi.Arguments = "--libs " + packages;
1102 p = Process.Start (pi);
1103 } catch (Exception e) {
1104 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1106 Environment.Exit (1);
1111 if (p.StandardOutput == null){
1112 report.Warning (-27, 1, "Specified package did not return any information");
1116 string pkgout = p.StandardOutput.ReadToEnd ();
1118 if (p.ExitCode != 0) {
1119 report.Error (-27, "Error running pkg-config. Check the above output.");
1121 Environment.Exit (1);
1132 // This parses the -arg and /arg options to the compiler, even if the strings
1133 // in the following text use "/arg" on the strings.
1135 bool CSCParseOption (string option, ref string [] args)
1137 int idx = option.IndexOf (':');
1144 arg = option.Substring (0, idx);
1146 value = option.Substring (idx + 1);
1149 switch (arg.ToLower (CultureInfo.InvariantCulture)){
1157 RootContext.Target = Target.Exe;
1161 RootContext.Target = Target.WinExe;
1165 RootContext.Target = Target.Library;
1166 RootContext.TargetExt = ".dll";
1170 RootContext.Target = Target.Module;
1171 RootContext.TargetExt = ".netmodule";
1181 if (value.Length == 0){
1183 Environment.Exit (1);
1192 RootContext.Optimize = true;
1197 RootContext.Optimize = false;
1200 // TODO: Not supported by csc 3.5+
1201 case "/incremental":
1202 case "/incremental+":
1203 case "/incremental-":
1209 if (value.Length == 0){
1211 Environment.Exit (1);
1214 foreach (string d in value.Split (argument_value_separator)) {
1215 string conditional = d.Trim ();
1216 if (!Tokenizer.IsValidIdentifier (conditional)) {
1217 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
1220 RootContext.AddConditional (conditional);
1227 // We should collect data, runtime, etc and store in the file specified
1229 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1235 if (value.Length == 0){
1237 Environment.Exit (1);
1239 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1240 string pkgout = GetPackageFlags (packages, true, Report);
1242 if (pkgout != null){
1243 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1244 Split (new Char [] { ' ', '\t'});
1245 args = AddArgs (args, xargs);
1252 case "/linkresource":
1255 AssemblyResource res = null;
1256 string[] s = value.Split (argument_value_separator);
1259 if (s[0].Length == 0)
1261 res = new AssemblyResource (s [0], Path.GetFileName (s[0]));
1264 res = new AssemblyResource (s [0], s [1]);
1267 if (s [2] != "public" && s [2] != "private") {
1268 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1271 res = new AssemblyResource (s[0], s[1], s[2] == "private");
1274 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1279 res.IsEmbeded = arg [1] == 'r' || arg [1] == 'R';
1286 if (value.Length == 0){
1287 Report.Error (5, "-recurse requires an argument");
1288 Environment.Exit (1);
1290 ProcessSourceFiles (value, true);
1294 case "/reference": {
1295 if (value.Length == 0){
1296 Report.Error (5, "-reference requires an argument");
1297 Environment.Exit (1);
1300 string[] refs = value.Split (argument_value_separator);
1301 foreach (string r in refs){
1303 int index = val.IndexOf ('=');
1305 string alias = r.Substring (0, index);
1306 string assembly = r.Substring (index + 1);
1307 AddExternAlias (alias, assembly);
1311 if (val.Length != 0)
1312 references.Add (val);
1316 case "/addmodule": {
1317 if (value.Length == 0){
1318 Report.Error (5, arg + " requires an argument");
1319 Environment.Exit (1);
1322 string[] refs = value.Split (argument_value_separator);
1323 foreach (string r in refs){
1329 if (value.Length == 0) {
1330 Report.Error (5, arg + " requires an argument");
1331 Environment.Exit (1);
1334 if (RootContext.Win32IconFile != null)
1335 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1337 RootContext.Win32ResourceFile = value;
1340 case "/win32icon": {
1341 if (value.Length == 0) {
1342 Report.Error (5, arg + " requires an argument");
1343 Environment.Exit (1);
1346 if (RootContext.Win32ResourceFile != null)
1347 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1349 RootContext.Win32IconFile = value;
1353 if (value.Length == 0){
1354 Report.Error (2006, arg + " requires an argument");
1355 Environment.Exit (1);
1357 RootContext.Documentation = new Documentation (value);
1363 if (value.Length == 0){
1364 Report.Error (5, "/lib requires an argument");
1365 Environment.Exit (1);
1368 libdirs = value.Split (argument_value_separator);
1369 foreach (string dir in libdirs)
1370 link_paths.Add (dir);
1375 RootContext.GenerateDebugInfo = false;
1379 if (value == "full" || value == "")
1380 RootContext.GenerateDebugInfo = true;
1385 RootContext.GenerateDebugInfo = true;
1390 RootContext.Checked = true;
1394 RootContext.Checked = false;
1402 RootContext.VerifyClsCompliance = false;
1407 RootContext.Unsafe = true;
1411 RootContext.Unsafe = false;
1414 case "/warnaserror":
1415 case "/warnaserror+":
1416 if (value.Length == 0) {
1417 Report.WarningsAreErrors = true;
1419 foreach (string wid in value.Split (argument_value_separator))
1420 Report.AddWarningAsError (wid);
1424 case "/warnaserror-":
1425 if (value.Length == 0) {
1426 Report.WarningsAreErrors = false;
1428 foreach (string wid in value.Split (argument_value_separator))
1429 Report.RemoveWarningAsError (wid);
1434 SetWarningLevel (value);
1440 if (value.Length == 0){
1441 Report.Error (5, "/nowarn requires an argument");
1442 Environment.Exit (1);
1445 warns = value.Split (argument_value_separator);
1446 foreach (string wc in warns){
1448 if (wc.Trim ().Length == 0)
1451 int warn = Int32.Parse (wc);
1453 throw new ArgumentOutOfRangeException("warn");
1455 Report.SetIgnoreWarning (warn);
1457 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1464 load_default_config = false;
1468 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1470 RootContext.Platform = Platform.AnyCPU;
1473 RootContext.Platform = Platform.X86;
1476 RootContext.Platform = Platform.X64;
1479 RootContext.Platform = Platform.IA64;
1482 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1488 // We just ignore this.
1489 case "/errorreport":
1495 Environment.Exit(0);
1501 Environment.Exit (0);
1506 if (value.Length == 0){
1507 Report.Error (5, arg + " requires an argument");
1508 Environment.Exit (1);
1510 RootContext.MainClass = value;
1515 RootContext.StdLib = false;
1519 RootContext.StdLib = true;
1526 if (value == String.Empty) {
1527 Report.Error (5, arg + " requires an argument");
1528 Environment.Exit (1);
1530 RootContext.StrongNameKeyFile = value;
1532 case "/keycontainer":
1533 if (value == String.Empty) {
1534 Report.Error (5, arg + " requires an argument");
1535 Environment.Exit (1);
1537 RootContext.StrongNameKeyContainer = value;
1541 RootContext.StrongNameDelaySign = true;
1544 RootContext.StrongNameDelaySign = false;
1547 case "/langversion":
1548 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1550 RootContext.Version = LanguageVersion.ISO_1;
1553 RootContext.Version = LanguageVersion.Default;
1554 RootContext.AddConditional ("__V2__");
1557 RootContext.Version = LanguageVersion.ISO_2;
1560 RootContext.Version = LanguageVersion.V_3;
1563 RootContext.Version = LanguageVersion.Future;
1567 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1573 encoding = new UTF8Encoding();
1576 encoding = Encoding.Default;
1580 encoding = Encoding.GetEncoding (
1581 Int32.Parse (value));
1583 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1593 void Error_WrongOption (string option)
1595 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1598 static string [] AddArgs (string [] args, string [] extra_args)
1601 new_args = new string [extra_args.Length + args.Length];
1603 // if args contains '--' we have to take that into account
1604 // split args into first half and second half based on '--'
1605 // and add the extra_args before --
1606 int split_position = Array.IndexOf (args, "--");
1607 if (split_position != -1)
1609 Array.Copy (args, new_args, split_position);
1610 extra_args.CopyTo (new_args, split_position);
1611 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1615 args.CopyTo (new_args, 0);
1616 extra_args.CopyTo (new_args, args.Length);
1622 void AddExternAlias (string identifier, string assembly)
1624 if (assembly.Length == 0) {
1625 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1629 if (!IsExternAliasValid (identifier)) {
1630 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1634 // Could here hashtable throw an exception?
1635 external_aliases [identifier] = assembly;
1638 void AddResource (AssemblyResource res)
1640 if (RootContext.Resources == null) {
1641 RootContext.Resources = new List<AssemblyResource> ();
1642 RootContext.Resources.Add (res);
1646 if (RootContext.Resources.Contains (res)) {
1647 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
1651 RootContext.Resources.Add (res);
1654 static bool IsExternAliasValid (string identifier)
1656 if (identifier.Length == 0)
1658 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1661 for (int i = 1; i < identifier.Length; i++) {
1662 char c = identifier [i];
1663 if (Char.IsLetter (c) || Char.IsDigit (c))
1666 UnicodeCategory category = Char.GetUnicodeCategory (c);
1667 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1668 category != UnicodeCategory.SpacingCombiningMark ||
1669 category != UnicodeCategory.ConnectorPunctuation)
1677 // Main compilation method
1679 public bool Compile ()
1681 var module = new ModuleContainer (ctx);
1682 RootContext.ToplevelTypes = module;
1685 stopwatch = Stopwatch.StartNew ();
1686 first_time = DateTime.Now;
1690 ShowTime ("Parsing source files");
1692 if (Report.Errors > 0)
1695 if (tokenize || parse_only)
1698 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1699 throw new InternalErrorException ("who set it?");
1701 ProcessDefaultConfig ();
1706 if (output_file == null){
1707 if (first_source == null){
1708 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1712 int pos = first_source.LastIndexOf ('.');
1715 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1717 output_file = first_source + RootContext.TargetExt;
1721 // Load assemblies required
1724 stopwatch = Stopwatch.StartNew ();
1726 var assembly = module.MakeExecutable (output_file, output_file);
1728 var importer = new ReflectionImporter (ctx.BuildinTypes);
1729 assembly.Importer = importer;
1731 LoadReferences (module, importer);
1733 ShowTime ("Imporing referenced assemblies");
1735 if (!TypeManager.InitCoreTypes (module, ctx.BuildinTypes))
1738 TypeManager.InitOptionalCoreTypes (ctx);
1740 ShowTime ("Initializing predefined types");
1742 if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
1745 LoadModules (assembly);
1749 ShowTime ("Types definition");
1751 if (Report.Errors > 0)
1754 if (Report.Errors == 0 &&
1755 RootContext.Documentation != null &&
1756 !RootContext.Documentation.OutputDocComment (
1757 output_file, Report))
1761 // Verify using aliases now
1763 NamespaceEntry.VerifyAllUsing ();
1765 if (Report.Errors > 0){
1769 assembly.Resolve ();
1771 if (Report.Errors > 0)
1775 // The code generator
1778 stopwatch = Stopwatch.StartNew ();
1782 ShowTime ("Resolving and emitting members blocks");
1784 if (Report.Errors > 0){
1788 module.CloseType ();
1790 ShowTime ("Closing types");
1793 stopwatch = Stopwatch.StartNew ();
1795 assembly.EmbedResources ();
1796 ShowTime ("Embedding resources");
1798 if (Report.Errors > 0)
1802 stopwatch = Stopwatch.StartNew ();
1806 ShowTime ("Saving output assembly");
1808 if (RootContext.GenerateDebugInfo) {
1809 SymbolWriter.WriteSymbolFile ();
1810 ShowTime ("Saving debug symbols");
1813 ShowTotalTime ("Total");
1815 Timer.ShowTimers ();
1817 return (Report.Errors == 0);
1821 public class AssemblyResource : IEquatable<AssemblyResource>
1823 public AssemblyResource (string fileName, string name)
1824 : this (fileName, name, false)
1828 public AssemblyResource (string fileName, string name, bool isPrivate)
1830 FileName = fileName;
1832 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1835 public ResourceAttributes Attributes { get; private set; }
1836 public string Name { get; private set; }
1837 public string FileName { get; private set; }
1838 public bool IsEmbeded { get; set; }
1840 #region IEquatable<AssemblyResource> Members
1842 public bool Equals (AssemblyResource other)
1844 return Name == other.Name;
1851 // This is the only public entry point
1853 public class CompilerCallableEntryPoint : MarshalByRefObject {
1854 public static bool InvokeCompiler (string [] args, TextWriter error)
1857 StreamReportPrinter srp = new StreamReportPrinter (error);
1858 Driver d = Driver.Create (args, true, srp);
1862 return d.Compile () && srp.ErrorsCount == 0;
1868 public static int[] AllWarningNumbers {
1870 return Report.AllWarnings;
1874 public static void Reset ()
1879 public static void PartialReset ()
1884 public static void Reset (bool full_flag)
1887 CSharpParser.yacc_verbose_flag = 0;
1893 RootContext.Reset (full_flag);
1894 TypeManager.Reset ();
1895 ArrayContainer.Reset ();
1896 ReferenceContainer.Reset ();
1897 PointerContainer.Reset ();
1901 UnaryMutator.Reset ();
1903 ConstantFold.Reset ();
1904 CastFromDecimal.Reset ();
1905 StringConcat.Reset ();
1907 NamespaceEntry.Reset ();
1909 AnonymousTypeClass.Reset ();
1910 AnonymousMethodBody.Reset ();
1911 AnonymousMethodStorey.Reset ();
1912 SymbolWriter.Reset ();
1914 Linq.QueryBlock.TransparentParameter.Reset ();