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 /// The compiler driver.
33 internal int fatal_errors;
36 // Last time we took the time
41 internal readonly CompilerContext ctx;
43 static readonly char[] argument_value_separator = new char [] { ';', ',' };
45 private Driver (CompilerContext ctx)
50 public static Driver Create (string[] args, bool require_files, ReportPrinter printer)
52 Driver d = new Driver (new CompilerContext (new Report (printer)));
54 if (!d.ParseArguments (args, require_files))
61 get { return ctx.Report; }
64 void ShowTime (string msg)
71 Console.WriteLine ("{0,5}ms {1}", stopwatch.ElapsedMilliseconds, msg);
73 stopwatch = Stopwatch.StartNew ();
76 void ShowTotalTime (string msg)
81 DateTime now = DateTime.Now;
82 TimeSpan span = now - first_time;
85 "[{0:00}:{1:000}] {2}",
86 (int) span.TotalSeconds, span.Milliseconds, msg);
89 void tokenize_file (CompilationUnit file, CompilerContext ctx)
94 input = File.OpenRead (file.Name);
96 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
101 SeekableStreamReader reader = new SeekableStreamReader (input, RootContext.Encoding);
102 Tokenizer lexer = new Tokenizer (reader, file, ctx);
103 int token, tokens = 0, errors = 0;
105 while ((token = lexer.token ()) != Token.EOF){
107 if (token == Token.ERROR)
110 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
116 void Parse (CompilationUnit file, ModuleContainer module)
121 input = File.OpenRead (file.Name);
123 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
128 if (input.ReadByte () == 77 && input.ReadByte () == 90) {
129 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
135 SeekableStreamReader reader = new SeekableStreamReader (input, RootContext.Encoding);
137 Parse (reader, file, module);
142 void Parse (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
144 CSharpParser parser = new CSharpParser (reader, file, module);
148 static void OtherFlags ()
151 "Other flags in the compiler\n" +
152 " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
153 " --lint Enhanced warnings\n" +
154 " --parse Only parses the source file\n" +
155 " --stacktrace Shows stack trace at error location\n" +
156 " --timestamp Displays time stamps of various compiler events\n" +
157 " -v Verbose parsing (for debugging the parser)\n" +
158 " --mcs-debug X Sets MCS debugging level to X\n");
164 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
165 "mcs [options] source-files\n" +
166 " --about About the Mono C# compiler\n" +
167 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
168 " -checked[+|-] Sets default aritmetic overflow context\n" +
169 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
170 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
171 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
172 " -debug[+|-], -g Generate debugging information\n" +
173 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
174 " -doc:FILE Process documentation comments to XML file\n" +
175 " -help Lists all compiler options (short: -?)\n" +
176 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
177 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
178 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default, or Future\n" +
179 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
180 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
181 " -noconfig Disables implicitly referenced assemblies\n" +
182 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
183 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
184 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
185 " -out:FILE Specifies output assembly name\n" +
187 " -pkg:P1[,Pn] References packages P1..Pn\n" +
189 " -platform:ARCH Specifies the target platform of the output assembly\n" +
190 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
191 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
192 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
193 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
194 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
195 " KIND can be one of: exe, winexe, library, module\n" +
196 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
197 " -warnaserror[+|-] Treats all warnings as errors\n" +
198 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
199 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
200 " -help2 Shows internal compiler options\n" +
203 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
204 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
205 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
206 " -win32icon:FILE Use this icon for the output\n" +
207 " @file Read response file for more options\n\n" +
208 "Options can be of the form -option or /option");
213 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
219 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
220 "The compiler source code is released under the terms of the \n"+
221 "MIT X11 or GNU GPL licenses\n\n" +
223 "For more information on Mono, visit the project Web site\n" +
224 " http://www.mono-project.com\n\n" +
226 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
227 Environment.Exit (0);
230 public static int Main (string[] args)
232 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
233 var crp = new ConsoleReportPrinter ();
234 Driver d = Driver.Create (args, true, crp);
238 crp.Fatal = d.fatal_errors;
240 if (d.Compile () && d.Report.Errors == 0) {
241 if (d.Report.Warnings > 0) {
242 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
244 Environment.Exit (0);
249 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
250 d.Report.Errors, d.Report.Warnings);
251 Environment.Exit (1);
255 static string [] LoadArgs (string file)
258 var args = new List<string> ();
261 f = new StreamReader (file);
266 StringBuilder sb = new StringBuilder ();
268 while ((line = f.ReadLine ()) != null){
271 for (int i = 0; i < t; i++){
274 if (c == '"' || c == '\''){
277 for (i++; i < t; i++){
284 } else if (c == ' '){
286 args.Add (sb.ToString ());
293 args.Add (sb.ToString ());
298 return args.ToArray ();
302 // Given a path specification, splits the path from the file/pattern
304 static void SplitPathAndPattern (string spec, out string path, out string pattern)
306 int p = spec.LastIndexOf ('/');
309 // Windows does not like /file.cs, switch that to:
314 pattern = spec.Substring (1);
316 path = spec.Substring (0, p);
317 pattern = spec.Substring (p + 1);
322 p = spec.LastIndexOf ('\\');
324 path = spec.Substring (0, p);
325 pattern = spec.Substring (p + 1);
333 void AddSourceFile (string f)
335 if (first_source == null)
338 Location.AddFile (Report, f);
341 bool ParseArguments (string[] args, bool require_files)
343 List<string> response_file_list = null;
344 bool parsing_options = true;
346 for (int i = 0; i < args.Length; i++) {
347 string arg = args [i];
351 if (arg [0] == '@') {
352 string [] extra_args;
353 string response_file = arg.Substring (1);
355 if (response_file_list == null)
356 response_file_list = new List<string> ();
358 if (response_file_list.Contains (response_file)) {
360 1515, "Response file `" + response_file +
361 "' specified multiple times");
365 response_file_list.Add (response_file);
367 extra_args = LoadArgs (response_file);
368 if (extra_args == null) {
369 Report.Error (2011, "Unable to open response file: " +
374 args = AddArgs (args, extra_args);
378 if (parsing_options) {
380 parsing_options = false;
384 if (arg [0] == '-') {
385 if (UnixParseOption (arg, ref args, ref i))
389 string csc_opt = "/" + arg.Substring (1);
390 if (CSCParseOption (csc_opt, ref args))
393 Error_WrongOption (arg);
396 if (arg [0] == '/') {
397 if (CSCParseOption (arg, ref args))
400 // Need to skip `/home/test.cs' however /test.cs is considered as error
401 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
402 Error_WrongOption (arg);
408 ProcessSourceFiles (arg, false);
411 if (require_files == false)
415 // If we are an exe, require a source file for the entry point
417 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
418 if (first_source == null) {
419 Report.Error (2008, "No files to compile were specified");
426 // If there is nothing to put in the assembly, and we are not a library
428 if (first_source == null && RootContext.Resources == null) {
429 Report.Error (2008, "No files to compile were specified");
436 public void Parse (ModuleContainer module)
438 Location.Initialize ();
440 var cu = Location.SourceFiles;
441 for (int i = 0; i < cu.Count; ++i) {
442 if (RootContext.TokenizeOnly) {
443 tokenize_file (cu [i], ctx);
445 Parse (cu [i], module);
450 void ProcessSourceFiles (string spec, bool recurse)
452 string path, pattern;
454 SplitPathAndPattern (spec, out path, out pattern);
455 if (pattern.IndexOf ('*') == -1){
456 AddSourceFile (spec);
460 string [] files = null;
462 files = Directory.GetFiles (path, pattern);
463 } catch (System.IO.DirectoryNotFoundException) {
464 Report.Error (2001, "Source file `" + spec + "' could not be found");
466 } catch (System.IO.IOException){
467 Report.Error (2001, "Source file `" + spec + "' could not be found");
470 foreach (string f in files) {
477 string [] dirs = null;
480 dirs = Directory.GetDirectories (path);
484 foreach (string d in dirs) {
486 // Don't include path in this string, as each
487 // directory entry already does
488 ProcessSourceFiles (d + "/" + pattern, true);
492 void SetWarningLevel (string s)
497 level = Int32.Parse (s);
500 if (level < 0 || level > 4){
501 Report.Error (1900, "Warning level must be in the range 0-4");
504 Report.WarningLevel = level;
507 static void Version ()
509 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
510 Console.WriteLine ("Mono C# compiler version {0}", version);
511 Environment.Exit (0);
515 // Currently handles the Unix-like command line options, but will be
516 // deprecated in favor of the CSCParseOption, which will also handle the
517 // options that start with a dash in the future.
519 bool UnixParseOption (string arg, ref string [] args, ref int i)
523 CSharpParser.yacc_verbose_flag++;
531 RootContext.ParseOnly = true;
534 case "--main": case "-m":
535 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
536 if ((i + 1) >= args.Length){
538 Environment.Exit (1);
540 RootContext.MainClass = args [++i];
544 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
545 RootContext.Unsafe = true;
548 case "/?": case "/h": case "/help":
551 Environment.Exit (0);
555 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
556 if ((i + 1) >= args.Length){
558 Environment.Exit (1);
560 RootContext.AddConditional (args [++i]);
564 RootContext.TokenizeOnly = true;
569 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
570 if ((i + 1) >= args.Length){
572 Environment.Exit (1);
574 RootContext.OutputFile = args [++i];
578 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
579 RootContext.Checked = true;
583 Report.Printer.Stacktrace = true;
586 case "--linkresource":
588 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
589 if ((i + 1) >= args.Length){
591 Report.Error (5, "Missing argument to --linkres");
592 Environment.Exit (1);
595 AddResource (new AssemblyResource (args[++i], args[i]));
600 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
601 if ((i + 1) >= args.Length){
603 Report.Error (5, "Missing argument to --resource");
604 Environment.Exit (1);
607 AddResource (new AssemblyResource (args[++i], args[i], true));
611 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
612 if ((i + 1) >= args.Length){
613 Environment.Exit (1);
617 string type = args [++i];
620 RootContext.Target = Target.Library;
621 RootContext.TargetExt = ".dll";
625 RootContext.Target = Target.Exe;
629 RootContext.Target = Target.WinExe;
633 RootContext.Target = Target.Module;
634 RootContext.TargetExt = ".dll";
643 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
644 if ((i + 1) >= args.Length){
646 Environment.Exit (1);
649 string val = args [++i];
650 int idx = val.IndexOf ('=');
652 string alias = val.Substring (0, idx);
653 string assembly = val.Substring (idx + 1);
654 AddAssemblyReference (alias, assembly);
658 AddAssemblyReference (val);
662 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
663 if ((i + 1) >= args.Length){
665 Environment.Exit (1);
667 RootContext.ReferencesLookupPaths.Add (args [++i]);
671 RootContext.EnhancedWarnings = true;
675 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
676 RootContext.StdLib = false;
680 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
681 if ((i + 1) >= args.Length){
683 Environment.Exit (1);
688 warn = Int32.Parse (args [++i]);
691 Environment.Exit (1);
693 Report.SetIgnoreWarning (warn);
697 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
698 if ((i + 1) >= args.Length){
701 "--wlevel requires a value from 0 to 4");
702 Environment.Exit (1);
705 SetWarningLevel (args [++i]);
709 if ((i + 1) >= args.Length){
710 Report.Error (5, "--mcs-debug requires an argument");
711 Environment.Exit (1);
715 Report.DebugFlags = Int32.Parse (args [++i]);
717 Report.Error (5, "Invalid argument to --mcs-debug");
718 Environment.Exit (1);
727 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
728 if ((i + 1) >= args.Length){
729 Report.Error (5, "--recurse requires an argument");
730 Environment.Exit (1);
732 ProcessSourceFiles (args [++i], true);
739 case "--debug": case "-g":
740 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
741 RootContext.GenerateDebugInfo = true;
745 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
746 RootContext.LoadDefaultReferences = false;
750 if (arg.StartsWith ("--fatal")){
751 if (arg.StartsWith ("--fatal=")){
752 if (!Int32.TryParse (arg.Substring (8), out fatal_errors))
765 public static string GetPackageFlags (string packages, bool fatal, Report report)
767 ProcessStartInfo pi = new ProcessStartInfo ();
768 pi.FileName = "pkg-config";
769 pi.RedirectStandardOutput = true;
770 pi.UseShellExecute = false;
771 pi.Arguments = "--libs " + packages;
774 p = Process.Start (pi);
775 } catch (Exception e) {
776 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
778 Environment.Exit (1);
783 if (p.StandardOutput == null){
784 report.Warning (-27, 1, "Specified package did not return any information");
788 string pkgout = p.StandardOutput.ReadToEnd ();
790 if (p.ExitCode != 0) {
791 report.Error (-27, "Error running pkg-config. Check the above output.");
793 Environment.Exit (1);
804 // This parses the -arg and /arg options to the compiler, even if the strings
805 // in the following text use "/arg" on the strings.
807 bool CSCParseOption (string option, ref string [] args)
809 int idx = option.IndexOf (':');
816 arg = option.Substring (0, idx);
818 value = option.Substring (idx + 1);
821 switch (arg.ToLowerInvariant ()){
829 RootContext.Target = Target.Exe;
833 RootContext.Target = Target.WinExe;
837 RootContext.Target = Target.Library;
838 RootContext.TargetExt = ".dll";
842 RootContext.Target = Target.Module;
843 RootContext.TargetExt = ".netmodule";
853 if (value.Length == 0) {
854 Error_RequiresFileName (option);
857 RootContext.OutputFile = value;
864 RootContext.Optimize = true;
869 RootContext.Optimize = false;
872 // TODO: Not supported by csc 3.5+
874 case "/incremental+":
875 case "/incremental-":
881 if (value.Length == 0){
883 Environment.Exit (1);
886 foreach (string d in value.Split (argument_value_separator)) {
887 string conditional = d.Trim ();
888 if (!Tokenizer.IsValidIdentifier (conditional)) {
889 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
892 RootContext.AddConditional (conditional);
899 // We should collect data, runtime, etc and store in the file specified
901 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
907 if (value.Length == 0){
909 Environment.Exit (1);
911 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
912 string pkgout = GetPackageFlags (packages, true, Report);
915 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
916 Split (new Char [] { ' ', '\t'});
917 args = AddArgs (args, xargs);
924 case "/linkresource":
927 AssemblyResource res = null;
928 string[] s = value.Split (argument_value_separator);
931 if (s[0].Length == 0)
933 res = new AssemblyResource (s [0], Path.GetFileName (s[0]));
936 res = new AssemblyResource (s [0], s [1]);
939 if (s [2] != "public" && s [2] != "private") {
940 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
943 res = new AssemblyResource (s[0], s[1], s[2] == "private");
946 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
951 res.IsEmbeded = arg [1] == 'r' || arg [1] == 'R';
958 if (value.Length == 0) {
959 Error_RequiresFileName (option);
962 ProcessSourceFiles (value, true);
967 if (value.Length == 0) {
968 Error_RequiresFileName (option);
972 string[] refs = value.Split (argument_value_separator);
973 foreach (string r in refs){
978 int index = val.IndexOf ('=');
980 string alias = r.Substring (0, index);
981 string assembly = r.Substring (index + 1);
982 AddAssemblyReference (alias, assembly);
983 if (refs.Length != 1) {
984 Report.Error (2034, "Cannot specify multiple aliases using single /reference option");
988 AddAssemblyReference (val);
994 if (value.Length == 0) {
995 Error_RequiresFileName (option);
999 string[] refs = value.Split (argument_value_separator);
1000 foreach (string r in refs){
1001 RootContext.Modules.Add (r);
1006 if (value.Length == 0) {
1007 Error_RequiresFileName (option);
1011 if (RootContext.Win32IconFile != null)
1012 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1014 RootContext.Win32ResourceFile = value;
1017 case "/win32icon": {
1018 if (value.Length == 0) {
1019 Error_RequiresFileName (option);
1023 if (RootContext.Win32ResourceFile != null)
1024 Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1026 RootContext.Win32IconFile = value;
1030 if (value.Length == 0) {
1031 Error_RequiresFileName (option);
1035 RootContext.Documentation = new Documentation (value);
1041 if (value.Length == 0) {
1042 Error_RequiresFileName (option);
1046 libdirs = value.Split (argument_value_separator);
1047 foreach (string dir in libdirs)
1048 RootContext.ReferencesLookupPaths.Add (dir);
1053 RootContext.GenerateDebugInfo = false;
1057 if (value == "full" || value == "")
1058 RootContext.GenerateDebugInfo = true;
1063 RootContext.GenerateDebugInfo = true;
1068 RootContext.Checked = true;
1072 RootContext.Checked = false;
1077 RootContext.VerifyClsCompliance = true;
1081 RootContext.VerifyClsCompliance = false;
1086 RootContext.Unsafe = true;
1090 RootContext.Unsafe = false;
1093 case "/warnaserror":
1094 case "/warnaserror+":
1095 if (value.Length == 0) {
1096 Report.WarningsAreErrors = true;
1098 foreach (string wid in value.Split (argument_value_separator))
1099 Report.AddWarningAsError (wid);
1103 case "/warnaserror-":
1104 if (value.Length == 0) {
1105 Report.WarningsAreErrors = false;
1107 foreach (string wid in value.Split (argument_value_separator))
1108 Report.RemoveWarningAsError (wid);
1113 SetWarningLevel (value);
1119 if (value.Length == 0){
1120 Report.Error (5, "/nowarn requires an argument");
1121 Environment.Exit (1);
1124 warns = value.Split (argument_value_separator);
1125 foreach (string wc in warns){
1127 if (wc.Trim ().Length == 0)
1130 int warn = Int32.Parse (wc);
1132 throw new ArgumentOutOfRangeException("warn");
1134 Report.SetIgnoreWarning (warn);
1136 Report.Error (1904, "`{0}' is not a valid warning number", wc);
1143 RootContext.LoadDefaultReferences = false;
1147 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1149 RootContext.Platform = Platform.AnyCPU;
1152 RootContext.Platform = Platform.X86;
1155 RootContext.Platform = Platform.X64;
1158 RootContext.Platform = Platform.IA64;
1161 Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1167 // We just ignore this.
1168 case "/errorreport":
1174 Environment.Exit(0);
1180 Environment.Exit (0);
1185 if (value.Length == 0){
1186 Report.Error (5, arg + " requires an argument");
1187 Environment.Exit (1);
1189 RootContext.MainClass = value;
1194 RootContext.StdLib = false;
1198 RootContext.StdLib = true;
1205 if (value.Length == 0) {
1206 Error_RequiresFileName (option);
1210 RootContext.StrongNameKeyFile = value;
1212 case "/keycontainer":
1213 if (value == String.Empty) {
1214 Report.Error (5, arg + " requires an argument");
1215 Environment.Exit (1);
1217 RootContext.StrongNameKeyContainer = value;
1221 RootContext.StrongNameDelaySign = true;
1224 RootContext.StrongNameDelaySign = false;
1227 case "/langversion":
1228 switch (value.ToLowerInvariant ()) {
1230 RootContext.Version = LanguageVersion.ISO_1;
1233 RootContext.Version = LanguageVersion.Default;
1234 RootContext.AddConditional ("__V2__");
1237 RootContext.Version = LanguageVersion.ISO_2;
1240 RootContext.Version = LanguageVersion.V_3;
1243 RootContext.Version = LanguageVersion.Future;
1247 Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1253 RootContext.Encoding = new UTF8Encoding();
1256 RootContext.Encoding = Encoding.Default;
1260 RootContext.Encoding = Encoding.GetEncoding (Int32.Parse (value));
1262 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1272 void Error_WrongOption (string option)
1274 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1277 void Error_RequiresFileName (string option)
1279 Report.Error (2005, "Missing file specification for `{0}' option", option);
1282 static string [] AddArgs (string [] args, string [] extra_args)
1285 new_args = new string [extra_args.Length + args.Length];
1287 // if args contains '--' we have to take that into account
1288 // split args into first half and second half based on '--'
1289 // and add the extra_args before --
1290 int split_position = Array.IndexOf (args, "--");
1291 if (split_position != -1)
1293 Array.Copy (args, new_args, split_position);
1294 extra_args.CopyTo (new_args, split_position);
1295 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1299 args.CopyTo (new_args, 0);
1300 extra_args.CopyTo (new_args, args.Length);
1306 void AddAssemblyReference (string assembly)
1308 RootContext.AssemblyReferences.Add (assembly);
1311 void AddAssemblyReference (string alias, string assembly)
1313 if (assembly.Length == 0) {
1314 Report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
1318 if (!IsExternAliasValid (alias)) {
1319 Report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
1323 RootContext.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
1326 void AddResource (AssemblyResource res)
1328 if (RootContext.Resources == null) {
1329 RootContext.Resources = new List<AssemblyResource> ();
1330 RootContext.Resources.Add (res);
1334 if (RootContext.Resources.Contains (res)) {
1335 ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
1339 RootContext.Resources.Add (res);
1342 static bool IsExternAliasValid (string identifier)
1344 if (identifier.Length == 0)
1346 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1349 for (int i = 1; i < identifier.Length; i++) {
1350 char c = identifier [i];
1351 if (Char.IsLetter (c) || Char.IsDigit (c))
1354 UnicodeCategory category = Char.GetUnicodeCategory (c);
1355 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1356 category != UnicodeCategory.SpacingCombiningMark ||
1357 category != UnicodeCategory.ConnectorPunctuation)
1365 // Main compilation method
1367 public bool Compile ()
1369 var module = new ModuleContainer (ctx);
1370 RootContext.ToplevelTypes = module;
1373 stopwatch = Stopwatch.StartNew ();
1374 first_time = DateTime.Now;
1378 ShowTime ("Parsing source files");
1380 if (Report.Errors > 0)
1383 if (RootContext.TokenizeOnly || RootContext.ParseOnly)
1386 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1387 throw new InternalErrorException ("who set it?");
1392 var output_file = RootContext.OutputFile;
1393 string output_file_name;
1394 if (output_file == null) {
1395 if (first_source == null) {
1396 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1400 int pos = first_source.LastIndexOf ('.');
1403 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1405 output_file = first_source + RootContext.TargetExt;
1407 output_file_name = output_file;
1409 output_file_name = Path.GetFileName (output_file);
1413 // Load assemblies required
1416 stopwatch = Stopwatch.StartNew ();
1418 var assembly = module.MakeExecutable (output_file_name, output_file);
1420 var importer = new ReflectionImporter (ctx.BuildinTypes);
1421 assembly.Importer = importer;
1423 var loader = new DynamicLoader (importer, ctx);
1424 loader.LoadReferences (module);
1426 ShowTime ("Imporing referenced assemblies");
1428 if (!ctx.BuildinTypes.CheckDefinitions (module))
1431 ShowTime ("Initializing predefined types");
1433 if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
1436 loader.LoadModules (assembly);
1440 ShowTime ("Types definition");
1442 if (Report.Errors > 0)
1445 if (Report.Errors == 0 &&
1446 RootContext.Documentation != null &&
1447 !RootContext.Documentation.OutputDocComment (
1448 output_file, Report))
1452 // Verify using aliases now
1454 NamespaceEntry.VerifyAllUsing ();
1456 if (Report.Errors > 0){
1460 assembly.Resolve ();
1462 if (Report.Errors > 0)
1466 // The code generator
1469 stopwatch = Stopwatch.StartNew ();
1473 ShowTime ("Resolving and emitting members blocks");
1475 if (Report.Errors > 0){
1479 module.CloseType ();
1481 ShowTime ("Closing types");
1484 stopwatch = Stopwatch.StartNew ();
1486 assembly.EmbedResources ();
1487 ShowTime ("Embedding resources");
1489 if (Report.Errors > 0)
1493 stopwatch = Stopwatch.StartNew ();
1497 ShowTime ("Saving output assembly");
1499 ShowTotalTime ("Total");
1501 Timer.ShowTimers ();
1503 return (Report.Errors == 0);
1508 // This is the only public entry point
1510 public class CompilerCallableEntryPoint : MarshalByRefObject {
1511 public static bool InvokeCompiler (string [] args, TextWriter error)
1514 StreamReportPrinter srp = new StreamReportPrinter (error);
1515 Driver d = Driver.Create (args, true, srp);
1519 return d.Compile () && srp.ErrorsCount == 0;
1525 public static int[] AllWarningNumbers {
1527 return Report.AllWarnings;
1531 public static void Reset ()
1536 public static void PartialReset ()
1541 public static void Reset (bool full_flag)
1543 CSharpParser.yacc_verbose_flag = 0;
1549 RootContext.Reset (full_flag);
1550 TypeManager.Reset ();
1551 ArrayContainer.Reset ();
1552 ReferenceContainer.Reset ();
1553 PointerContainer.Reset ();
1557 UnaryMutator.Reset ();
1559 ConstantFold.Reset ();
1560 CastFromDecimal.Reset ();
1561 StringConcat.Reset ();
1563 NamespaceEntry.Reset ();
1565 AnonymousTypeClass.Reset ();
1566 AnonymousMethodBody.Reset ();
1567 AnonymousMethodStorey.Reset ();
1568 SymbolWriter.Reset ();
1570 Linq.QueryBlock.TransparentParameter.Reset ();