2 // driver.cs: The compiler command line driver.
5 // Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Collections;
20 using System.Collections.Specialized;
23 using System.Globalization;
24 using System.Diagnostics;
27 Library, Exe, Module, WinExe
31 /// The compiler driver.
36 // Assemblies references to be linked. Initialized with
38 static ArrayList references;
41 // If any of these fail, we ignore the problem. This is so
42 // that we can list all the assemblies in Windows and not fail
43 // if they are missing on Linux.
45 static ArrayList soft_references;
48 // External aliases for assemblies.
50 static Hashtable external_aliases;
53 // Modules to be linked
55 static ArrayList modules;
58 static ArrayList link_paths;
60 // Whether we want to only run the tokenizer
65 bool want_debugging_support;
70 // Whether to load the initial config file (what CSC.RSP has by default)
72 bool load_default_config = true;
75 // A list of resource files
77 static Resources embedded_resources;
78 static string win32ResourceFile;
79 static string win32IconFile;
82 // An array of the defines from the command line
89 static string output_file;
92 // Last time we took the time
94 DateTime last_time, first_time;
101 static public void Reset ()
103 embedded_resources = null;
104 win32ResourceFile = win32IconFile = null;
110 encoding = Encoding.Default;
113 // Setup default defines
115 defines = new ArrayList ();
116 defines.Add ("__MonoCS__");
119 public static Driver Create (string [] args)
121 Driver d = new Driver ();
122 if (!d.ParseArguments (args))
128 void ShowTime (string msg)
133 DateTime now = DateTime.Now;
134 TimeSpan span = now - last_time;
138 "[{0:00}:{1:000}] {2}",
139 (int) span.TotalSeconds, span.Milliseconds, msg);
142 void ShowTotalTime (string msg)
147 DateTime now = DateTime.Now;
148 TimeSpan span = now - first_time;
152 "[{0:00}:{1:000}] {2}",
153 (int) span.TotalSeconds, span.Milliseconds, msg);
156 void tokenize_file (SourceFile file)
161 input = File.OpenRead (file.Name);
163 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
168 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
169 Tokenizer lexer = new Tokenizer (reader, file, defines);
170 int token, tokens = 0, errors = 0;
172 while ((token = lexer.token ()) != Token.EOF){
174 if (token == Token.ERROR)
177 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
183 void Parse (SourceFile file)
188 input = File.OpenRead (file.Name);
190 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
194 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
197 if (reader.Read () == 77 && reader.Read () == 90) {
198 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
204 Parse (reader, file);
208 void Parse (SeekableStreamReader reader, SourceFile file)
210 CSharpParser parser = new CSharpParser (reader, file, defines);
211 parser.ErrorOutput = Report.Stderr;
214 } catch (Exception ex) {
215 Report.Error(589, parser.Lexer.Location,
216 "Compilation aborted in file `{0}', {1}", file.Name, ex);
220 static void OtherFlags ()
223 "Other flags in the compiler\n" +
224 " --fatal Makes errors fatal\n" +
225 " --parse Only parses the source file\n" +
226 " --typetest Tests the tokenizer's built-in type parser\n" +
227 " --stacktrace Shows stack trace at error location\n" +
228 " --timestamp Displays time stamps of various compiler events\n" +
229 " --expect-error X Expect that error X will be encountered\n" +
230 " -v Verbose parsing (for debugging the parser)\n" +
231 " --mcs-debug X Sets MCS debugging level to X\n");
237 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
238 "mcs [options] source-files\n" +
239 " --about About the Mono C# compiler\n" +
240 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
241 " -checked[+|-] Sets default aritmetic overflow context\n" +
242 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
243 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
244 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
245 " -debug[+|-], -g Generate debugging information\n" +
246 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
247 " -doc:FILE Process documentation comments to XML file\n" +
248 " -help Lists all compiler options (short: -?)\n" +
249 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
250 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
251 " -langversion:TEXT Specifies language version modes: ISO-1, ISO-2, or Default\n" +
252 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
253 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
254 " -noconfig[+|-] Disables implicit references to assemblies\n" +
255 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
256 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
257 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
258 " -out:FILE Specifies output assembly name\n" +
259 " -pkg:P1[,Pn] References packages P1..Pn\n" +
260 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
261 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
262 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
263 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
264 " KIND can be one of: exe, winexe, library, module\n" +
265 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
266 " -warnaserror[+|-] Treats all warnings as errors\n" +
267 " -warn:0-4 Sets warning level, the default is 3 (short -w:)\n" +
268 " -help2 Shows internal compiler options\n" +
271 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
272 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
273 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
274 " -win32icon:FILE Use this icon for the output\n" +
275 " @file Read response file for more options\n\n" +
276 "Options can be of the form -option or /option");
279 static void TargetUsage ()
281 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
287 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
288 "The compiler source code is released under the terms of the \n"+
289 "MIT X11 or GNU GPL licenses\n\n" +
291 "For more information on Mono, visit the project Web site\n" +
292 " http://www.mono-project.com\n\n" +
294 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
295 Environment.Exit (0);
298 public static int Main (string[] args)
300 RootContext.Version = LanguageVersion.Default;
302 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
304 Driver d = Driver.Create (args);
308 if (d.Compile () && Report.Errors == 0) {
309 if (Report.Warnings > 0) {
310 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
314 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
315 Report.Errors, Report.Warnings);
320 static public void LoadAssembly (string assembly, bool soft)
322 LoadAssembly (assembly, null, soft);
325 static void Error6 (string name, 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 (6, "cannot find metadata file `{0}'", name);
332 static void Error9 (string type, string filename, string log)
334 if (log != null && log.Length > 0)
335 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
336 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
339 static void BadAssembly (string filename, string log)
341 MethodInfo adder_method = AssemblyClass.AddModule_Method;
343 if (adder_method != null) {
344 AssemblyName an = new AssemblyName ();
346 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
350 m = adder_method.Invoke (ab, new object [] { filename });
351 } catch (TargetInvocationException ex) {
352 throw ex.InnerException;
356 Report.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
357 Path.GetFileName (filename));
360 } catch (FileNotFoundException) {
361 // did the file get deleted during compilation? who cares? swallow the exception
362 } catch (BadImageFormatException) {
364 } catch (FileLoadException) {
368 Error9 ("assembly", filename, log);
371 static public void LoadAssembly (string assembly, string alias, bool soft)
374 string total_log = "";
378 char[] path_chars = { '/', '\\' };
380 if (assembly.IndexOfAny (path_chars) != -1) {
381 a = Assembly.LoadFrom (assembly);
383 string ass = assembly;
384 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
385 ass = assembly.Substring (0, assembly.Length - 4);
386 a = Assembly.Load (ass);
388 } catch (FileNotFoundException) {
390 foreach (string dir in link_paths) {
391 string full_path = Path.Combine (dir, assembly);
392 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
396 a = Assembly.LoadFrom (full_path);
399 } catch (FileNotFoundException ff) {
402 total_log += ff.FusionLog;
406 Error6 (assembly, total_log);
411 // Extern aliased refs require special handling
413 RootNamespace.Global.AddAssemblyReference (a);
415 RootNamespace.DefineRootNamespace (alias, a);
417 } catch (BadImageFormatException f) {
418 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
419 BadAssembly (f.FileName, f.FusionLog);
420 } catch (FileLoadException f) {
421 // ... while .NET 1.1 throws this
422 BadAssembly (f.FileName, f.FusionLog);
426 static public void LoadModule (string module)
429 string total_log = "";
433 m = CodeGen.Assembly.AddModule (module);
434 } catch (FileNotFoundException) {
436 foreach (string dir in link_paths) {
437 string full_path = Path.Combine (dir, module);
438 if (!module.EndsWith (".netmodule"))
439 full_path += ".netmodule";
442 m = CodeGen.Assembly.AddModule (full_path);
445 } catch (FileNotFoundException ff) {
446 total_log += ff.FusionLog;
450 Error6 (module, total_log);
455 RootNamespace.Global.AddModuleReference (m);
457 } catch (BadImageFormatException f) {
458 Error9 ("module", f.FileName, f.FusionLog);
459 } catch (FileLoadException f) {
460 Error9 ("module", f.FileName, f.FusionLog);
465 /// Loads all assemblies referenced on the command line
467 static public void LoadReferences ()
470 // Load Core Library for default compilation
472 if (RootContext.StdLib)
473 LoadAssembly ("mscorlib", false);
475 foreach (string r in soft_references)
476 LoadAssembly (r, true);
478 foreach (string r in references)
479 LoadAssembly (r, false);
481 foreach (DictionaryEntry entry in external_aliases)
482 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
487 static string [] LoadArgs (string file)
490 ArrayList args = new ArrayList ();
493 f = new StreamReader (file);
498 StringBuilder sb = new StringBuilder ();
500 while ((line = f.ReadLine ()) != null){
503 for (int i = 0; i < t; i++){
506 if (c == '"' || c == '\''){
509 for (i++; i < t; i++){
516 } else if (c == ' '){
518 args.Add (sb.ToString ());
525 args.Add (sb.ToString ());
530 string [] ret_value = new string [args.Count];
531 args.CopyTo (ret_value, 0);
537 // Returns the directory where the system assemblies are installed
539 static string GetSystemDir ()
541 return Path.GetDirectoryName (typeof (object).Assembly.Location);
545 // Given a path specification, splits the path from the file/pattern
547 static void SplitPathAndPattern (string spec, out string path, out string pattern)
549 int p = spec.LastIndexOf ('/');
552 // Windows does not like /file.cs, switch that to:
557 pattern = spec.Substring (1);
559 path = spec.Substring (0, p);
560 pattern = spec.Substring (p + 1);
565 p = spec.LastIndexOf ('\\');
567 path = spec.Substring (0, p);
568 pattern = spec.Substring (p + 1);
576 void AddSourceFile (string f)
578 if (first_source == null)
581 Location.AddFile (f);
584 bool ParseArguments (string[] args)
586 references = new ArrayList ();
587 external_aliases = new Hashtable ();
588 soft_references = new ArrayList ();
589 modules = new ArrayList (2);
590 link_paths = new ArrayList ();
592 ArrayList response_file_list = null;
593 bool parsing_options = true;
595 for (int i = 0; i < args.Length; i++) {
596 string arg = args [i];
600 if (arg.StartsWith ("@")) {
601 string [] extra_args;
602 string response_file = arg.Substring (1);
604 if (response_file_list == null)
605 response_file_list = new ArrayList ();
607 if (response_file_list.Contains (response_file)) {
609 1515, "Response file `" + response_file +
610 "' specified multiple times");
614 response_file_list.Add (response_file);
616 extra_args = LoadArgs (response_file);
617 if (extra_args == null) {
618 Report.Error (2011, "Unable to open response file: " +
623 args = AddArgs (args, extra_args);
627 if (parsing_options) {
629 parsing_options = false;
633 if (arg.StartsWith ("-")) {
634 if (UnixParseOption (arg, ref args, ref i))
638 string csc_opt = "/" + arg.Substring (1);
639 if (CSCParseOption (csc_opt, ref args, ref i))
642 Error_WrongOption (arg);
645 if (arg [0] == '/') {
646 if (CSCParseOption (arg, ref args, ref i))
649 // Need to skip `/home/test.cs' however /test.cs is considered as error
650 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
651 Error_WrongOption (arg);
657 ProcessSourceFiles (arg, false);
661 // If we are an exe, require a source file for the entry point
663 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
664 if (first_source == null) {
665 Report.Error (2008, "No files to compile were specified");
672 // If there is nothing to put in the assembly, and we are not a library
674 if (first_source == null && embedded_resources == null) {
675 Report.Error (2008, "No files to compile were specified");
684 Location.Initialize ();
686 int files_count = Location.SourceFiles.Length;
687 for (int i = 0; i < files_count; ++i) {
689 tokenize_file (Location.SourceFiles [i]);
691 Parse (Location.SourceFiles [i]);
696 void ProcessSourceFiles (string spec, bool recurse)
698 string path, pattern;
700 SplitPathAndPattern (spec, out path, out pattern);
701 if (pattern.IndexOf ('*') == -1){
702 AddSourceFile (spec);
706 string [] files = null;
708 files = Directory.GetFiles (path, pattern);
709 } catch (System.IO.DirectoryNotFoundException) {
710 Report.Error (2001, "Source file `" + spec + "' could not be found");
712 } catch (System.IO.IOException){
713 Report.Error (2001, "Source file `" + spec + "' could not be found");
716 foreach (string f in files) {
723 string [] dirs = null;
726 dirs = Directory.GetDirectories (path);
730 foreach (string d in dirs) {
732 // Don't include path in this string, as each
733 // directory entry already does
734 ProcessSourceFiles (d + "/" + pattern, true);
738 static void DefineDefaultConfig ()
741 // For now the "default config" is harcoded into the compiler
742 // we can move this outside later
744 string [] default_config = {
751 "System.Windows.Browser",
755 // Is it worth pre-loading all this stuff?
758 "System.Configuration.Install",
761 "System.DirectoryServices",
762 "System.Drawing.Design",
764 "System.EnterpriseServices",
767 "System.Runtime.Remoting",
768 "System.Runtime.Serialization.Formatters.Soap",
770 "System.ServiceProcess",
772 "System.Web.RegularExpressions",
773 "System.Web.Services",
774 "System.Windows.Forms"
778 if (RootContext.Version == LanguageVersion.LINQ)
779 soft_references.Add ("System.Core");
781 soft_references.AddRange (default_config);
784 public static string OutputFile
790 return Path.GetFileName (output_file);
794 static void SetWarningLevel (string s)
799 level = Int32.Parse (s);
802 if (level < 0 || level > 4){
803 Report.Error (1900, "Warning level must be in the range 0-4");
806 Report.WarningLevel = level;
809 static void Version ()
811 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
812 Console.WriteLine ("Mono C# compiler version {0}", version);
813 Environment.Exit (0);
817 // Currently handles the Unix-like command line options, but will be
818 // deprecated in favor of the CSCParseOption, which will also handle the
819 // options that start with a dash in the future.
821 bool UnixParseOption (string arg, ref string [] args, ref int i)
825 CSharpParser.yacc_verbose_flag++;
836 case "--main": case "-m":
837 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
838 if ((i + 1) >= args.Length){
840 Environment.Exit (1);
842 RootContext.MainClass = args [++i];
846 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
847 RootContext.Unsafe = true;
850 case "/?": case "/h": case "/help":
853 Environment.Exit (0);
857 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
858 if ((i + 1) >= args.Length){
860 Environment.Exit (1);
862 defines.Add (args [++i]);
871 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
872 if ((i + 1) >= args.Length){
874 Environment.Exit (1);
876 OutputFile = args [++i];
880 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
881 RootContext.Checked = true;
885 Report.Stacktrace = true;
888 case "--linkresource":
890 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
891 if ((i + 1) >= args.Length){
893 Report.Error (5, "Missing argument to --linkres");
894 Environment.Exit (1);
896 if (embedded_resources == null)
897 embedded_resources = new Resources ();
899 embedded_resources.Add (false, args [++i], args [i]);
904 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
905 if ((i + 1) >= args.Length){
907 Report.Error (5, "Missing argument to --resource");
908 Environment.Exit (1);
910 if (embedded_resources == null)
911 embedded_resources = new Resources ();
913 embedded_resources.Add (true, args [++i], args [i]);
917 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
918 if ((i + 1) >= args.Length){
919 Environment.Exit (1);
923 string type = args [++i];
926 RootContext.Target = Target.Library;
927 RootContext.TargetExt = ".dll";
931 RootContext.Target = Target.Exe;
935 RootContext.Target = Target.WinExe;
939 RootContext.Target = Target.Module;
940 RootContext.TargetExt = ".dll";
949 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
950 if ((i + 1) >= args.Length){
952 Environment.Exit (1);
955 string val = args [++i];
956 int idx = val.IndexOf ('=');
958 string alias = val.Substring (0, idx);
959 string assembly = val.Substring (idx + 1);
960 AddExternAlias (alias, assembly);
964 references.Add (val);
968 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
969 if ((i + 1) >= args.Length){
971 Environment.Exit (1);
973 link_paths.Add (args [++i]);
977 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
978 RootContext.StdLib = false;
986 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
987 Report.WarningsAreErrors = true;
991 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
992 if ((i + 1) >= args.Length){
994 Environment.Exit (1);
999 warn = Int32.Parse (args [++i]);
1002 Environment.Exit (1);
1004 Report.SetIgnoreWarning (warn);
1008 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1009 if ((i + 1) >= args.Length){
1012 "--wlevel requires a value from 0 to 4");
1013 Environment.Exit (1);
1016 SetWarningLevel (args [++i]);
1020 if ((i + 1) >= args.Length){
1021 Report.Error (5, "--mcs-debug requires an argument");
1022 Environment.Exit (1);
1026 Report.DebugFlags = Int32.Parse (args [++i]);
1028 Report.Error (5, "Invalid argument to --mcs-debug");
1029 Environment.Exit (1);
1038 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1039 if ((i + 1) >= args.Length){
1040 Report.Error (5, "--recurse requires an argument");
1041 Environment.Exit (1);
1043 ProcessSourceFiles (args [++i], true);
1048 last_time = first_time = DateTime.Now;
1051 case "--debug": case "-g":
1052 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1053 want_debugging_support = true;
1057 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1058 load_default_config = false;
1066 // This parses the -arg and /arg options to the compiler, even if the strings
1067 // in the following text use "/arg" on the strings.
1069 bool CSCParseOption (string option, ref string [] args, ref int i)
1071 int idx = option.IndexOf (':');
1078 arg = option.Substring (0, idx);
1080 value = option.Substring (idx + 1);
1091 RootContext.Target = Target.Exe;
1095 RootContext.Target = Target.WinExe;
1099 RootContext.Target = Target.Library;
1100 RootContext.TargetExt = ".dll";
1104 RootContext.Target = Target.Module;
1105 RootContext.TargetExt = ".netmodule";
1115 if (value.Length == 0){
1117 Environment.Exit (1);
1126 RootContext.Optimize = true;
1131 RootContext.Optimize = false;
1134 case "/incremental":
1135 case "/incremental+":
1136 case "/incremental-":
1142 if (value.Length == 0){
1144 Environment.Exit (1);
1147 foreach (string d in value.Split (';', ',')){
1148 if (!Tokenizer.IsValidIdentifier (d)) {
1149 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1159 // We should collect data, runtime, etc and store in the file specified
1161 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1167 if (value.Length == 0){
1169 Environment.Exit (1);
1171 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1173 ProcessStartInfo pi = new ProcessStartInfo ();
1174 pi.FileName = "pkg-config";
1175 pi.RedirectStandardOutput = true;
1176 pi.UseShellExecute = false;
1177 pi.Arguments = "--libs " + packages;
1180 p = Process.Start (pi);
1181 } catch (Exception e) {
1182 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1183 Environment.Exit (1);
1186 if (p.StandardOutput == null){
1187 Report.Warning (-27, 1, "Specified package did not return any information");
1190 string pkgout = p.StandardOutput.ReadToEnd ();
1192 if (p.ExitCode != 0) {
1193 Report.Error (-27, "Error running pkg-config. Check the above output.");
1194 Environment.Exit (1);
1197 if (pkgout != null){
1198 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1199 Split (new Char [] { ' ', '\t'});
1200 args = AddArgs (args, xargs);
1208 case "/linkresource":
1211 if (embedded_resources == null)
1212 embedded_resources = new Resources ();
1214 bool embeded = arg.StartsWith ("/r");
1215 string[] s = value.Split (',');
1218 if (s[0].Length == 0)
1220 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1223 embedded_resources.Add (embeded, s [0], s [1]);
1226 if (s [2] != "public" && s [2] != "private") {
1227 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1230 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1233 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1240 if (value.Length == 0){
1241 Report.Error (5, "-recurse requires an argument");
1242 Environment.Exit (1);
1244 ProcessSourceFiles (value, true);
1248 case "/reference": {
1249 if (value.Length == 0){
1250 Report.Error (5, "-reference requires an argument");
1251 Environment.Exit (1);
1254 string [] refs = value.Split (new char [] { ';', ',' });
1255 foreach (string r in refs){
1257 int index = val.IndexOf ('=');
1259 string alias = r.Substring (0, index);
1260 string assembly = r.Substring (index + 1);
1261 AddExternAlias (alias, assembly);
1265 references.Add (val);
1269 case "/addmodule": {
1270 if (value.Length == 0){
1271 Report.Error (5, arg + " requires an argument");
1272 Environment.Exit (1);
1275 string [] refs = value.Split (new char [] { ';', ',' });
1276 foreach (string r in refs){
1282 if (value.Length == 0) {
1283 Report.Error (5, arg + " requires an argument");
1284 Environment.Exit (1);
1287 win32ResourceFile = value;
1290 case "/win32icon": {
1291 if (value.Length == 0) {
1292 Report.Error (5, arg + " requires an argument");
1293 Environment.Exit (1);
1296 win32IconFile = value;
1300 if (value.Length == 0){
1301 Report.Error (2006, arg + " requires an argument");
1302 Environment.Exit (1);
1304 RootContext.Documentation = new Documentation (value);
1310 if (value.Length == 0){
1311 Report.Error (5, "/lib requires an argument");
1312 Environment.Exit (1);
1315 libdirs = value.Split (new Char [] { ',' });
1316 foreach (string dir in libdirs)
1317 link_paths.Add (dir);
1322 want_debugging_support = false;
1327 want_debugging_support = true;
1332 RootContext.Checked = true;
1336 RootContext.Checked = false;
1344 RootContext.VerifyClsCompliance = false;
1349 RootContext.Unsafe = true;
1353 RootContext.Unsafe = false;
1356 case "/warnaserror":
1357 case "/warnaserror+":
1358 Report.WarningsAreErrors = true;
1361 case "/warnaserror-":
1362 Report.WarningsAreErrors = false;
1366 SetWarningLevel (value);
1372 if (value.Length == 0){
1373 Report.Error (5, "/nowarn requires an argument");
1374 Environment.Exit (1);
1377 warns = value.Split (new Char [] {','});
1378 foreach (string wc in warns){
1380 int warn = Int32.Parse (wc);
1382 throw new ArgumentOutOfRangeException("warn");
1384 Report.SetIgnoreWarning (warn);
1386 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1393 load_default_config = true;
1398 load_default_config = false;
1403 Environment.Exit(0);
1409 Environment.Exit (0);
1414 if (value.Length == 0){
1415 Report.Error (5, arg + " requires an argument");
1416 Environment.Exit (1);
1418 RootContext.MainClass = value;
1423 RootContext.StdLib = false;
1427 RootContext.StdLib = true;
1434 if (value == String.Empty) {
1435 Report.Error (5, arg + " requires an argument");
1436 Environment.Exit (1);
1438 RootContext.StrongNameKeyFile = value;
1440 case "/keycontainer":
1441 if (value == String.Empty) {
1442 Report.Error (5, arg + " requires an argument");
1443 Environment.Exit (1);
1445 RootContext.StrongNameKeyContainer = value;
1448 RootContext.StrongNameDelaySign = true;
1451 RootContext.StrongNameDelaySign = false;
1454 case "/langversion":
1455 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1457 RootContext.Version = LanguageVersion.ISO_1;
1461 RootContext.Version = LanguageVersion.Default;
1463 defines.Add ("__V2__");
1468 RootContext.Version = LanguageVersion.ISO_2;
1472 Report.Warning (-30, 1, "Deprecated: The `linq' option is no longer required and should not be used");
1476 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
1482 encoding = new UTF8Encoding();
1485 encoding = Encoding.Default;
1489 encoding = Encoding.GetEncoding (
1490 Int32.Parse (value));
1492 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1502 static void Error_WrongOption (string option)
1504 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1507 static string [] AddArgs (string [] args, string [] extra_args)
1510 new_args = new string [extra_args.Length + args.Length];
1512 // if args contains '--' we have to take that into account
1513 // split args into first half and second half based on '--'
1514 // and add the extra_args before --
1515 int split_position = Array.IndexOf (args, "--");
1516 if (split_position != -1)
1518 Array.Copy (args, new_args, split_position);
1519 extra_args.CopyTo (new_args, split_position);
1520 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1524 args.CopyTo (new_args, 0);
1525 extra_args.CopyTo (new_args, args.Length);
1531 static void AddExternAlias (string identifier, string assembly)
1533 if (assembly.Length == 0) {
1534 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1538 if (!IsExternAliasValid (identifier)) {
1539 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1543 // Could here hashtable throw an exception?
1544 external_aliases [identifier] = assembly;
1547 static bool IsExternAliasValid (string identifier)
1549 if (identifier.Length == 0)
1551 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1554 for (int i = 1; i < identifier.Length; i++) {
1555 char c = identifier [i];
1556 if (Char.IsLetter (c) || Char.IsDigit (c))
1559 UnicodeCategory category = Char.GetUnicodeCategory (c);
1560 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1561 category != UnicodeCategory.SpacingCombiningMark ||
1562 category != UnicodeCategory.ConnectorPunctuation)
1570 // Main compilation method
1572 public bool Compile ()
1575 if (Report.Errors > 0)
1578 if (tokenize || parse_only)
1581 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1582 throw new InternalErrorException ("who set it?");
1584 if (load_default_config)
1585 DefineDefaultConfig ();
1587 if (Report.Errors > 0){
1592 // Load assemblies required
1595 ShowTime ("Loading references");
1596 link_paths.Add (GetSystemDir ());
1597 link_paths.Add (Directory.GetCurrentDirectory ());
1601 ShowTime (" References loaded");
1603 if (Report.Errors > 0){
1610 if (output_file == null){
1611 if (first_source == null){
1612 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1616 int pos = first_source.LastIndexOf ('.');
1619 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1621 output_file = first_source + RootContext.TargetExt;
1624 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1627 if (RootContext.Target == Target.Module) {
1628 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1629 if (module_only == null) {
1630 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1631 Environment.Exit (1);
1634 MethodInfo set_method = module_only.GetSetMethod (true);
1635 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1638 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1640 if (modules.Count > 0) {
1641 foreach (string module in modules)
1642 LoadModule (module);
1645 if (!TypeManager.InitCoreTypes ())
1648 TypeManager.InitOptionalCoreTypes ();
1651 ShowTime (" Core Types done");
1653 CodeGen.Module.Resolve ();
1656 // The second pass of the compiler
1659 ShowTime ("Resolving tree");
1660 RootContext.ResolveTree ();
1662 if (Report.Errors > 0)
1665 ShowTime ("Populate tree");
1666 if (!RootContext.StdLib)
1667 RootContext.BootCorlib_PopulateCoreTypes ();
1668 RootContext.PopulateTypes ();
1670 RootContext.DefineTypes ();
1672 if (Report.Errors == 0 &&
1673 RootContext.Documentation != null &&
1674 !RootContext.Documentation.OutputDocComment (
1679 // Verify using aliases now
1681 NamespaceEntry.VerifyAllUsing ();
1683 if (Report.Errors > 0){
1687 CodeGen.Assembly.Resolve ();
1689 if (RootContext.VerifyClsCompliance) {
1690 if (CodeGen.Assembly.IsClsCompliant) {
1691 AttributeTester.VerifyModulesClsCompliance ();
1692 TypeManager.LoadAllImportedTypes ();
1695 if (Report.Errors > 0)
1699 // The code generator
1702 ShowTime ("Emitting code");
1703 ShowTotalTime ("Total so far");
1704 RootContext.EmitCode ();
1708 if (Report.Errors > 0){
1713 ShowTime ("Closing types");
1715 RootContext.CloseTypes ();
1717 PEFileKinds k = PEFileKinds.ConsoleApplication;
1719 switch (RootContext.Target) {
1720 case Target.Library:
1722 k = PEFileKinds.Dll; break;
1724 k = PEFileKinds.ConsoleApplication; break;
1726 k = PEFileKinds.WindowApplication; break;
1729 if (RootContext.NeedsEntryPoint) {
1730 MethodInfo ep = RootContext.EntryPoint;
1733 if (RootContext.MainClass != null) {
1734 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1735 if (main_cont == null) {
1736 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1740 if (!(main_cont is ClassOrStruct)) {
1741 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1745 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1749 if (Report.Errors == 0)
1750 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1755 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1756 } else if (RootContext.MainClass != null) {
1757 Report.Error (2017, "Cannot specify -main if building a module or library");
1760 if (embedded_resources != null){
1761 if (RootContext.Target == Target.Module) {
1762 Report.Error (1507, "Cannot link resource file when building a module");
1766 embedded_resources.Emit ();
1770 // Add Win32 resources
1773 if (win32ResourceFile != null) {
1775 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1776 } catch (ArgumentException) {
1777 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1780 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1783 if (win32IconFile != null) {
1784 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1785 if (define_icon == null) {
1786 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1788 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1791 if (Report.Errors > 0)
1794 CodeGen.Save (output_file);
1796 ShowTime ("Saved output");
1797 ShowTotalTime ("Total");
1800 Timer.ShowTimers ();
1802 if (Report.ExpectedError != 0) {
1803 if (Report.Errors == 0) {
1804 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1805 "No other errors reported.");
1807 Environment.Exit (2);
1809 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1810 "However, other errors were reported.");
1812 Environment.Exit (1);
1820 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1821 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1823 return (Report.Errors == 0);
1832 string FileName { get; }
1835 class EmbededResource : IResource
1837 static MethodInfo embed_res;
1839 static EmbededResource () {
1840 Type[] argst = new Type [] {
1841 typeof (string), typeof (string), typeof (ResourceAttributes)
1844 embed_res = typeof (AssemblyBuilder).GetMethod (
1845 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1846 null, CallingConventions.Any, argst, null);
1848 if (embed_res == null) {
1849 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1853 readonly object[] args;
1855 public EmbededResource (string name, string file, bool isPrivate)
1857 args = new object [3];
1860 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1865 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1868 public string FileName {
1870 return (string)args [1];
1875 class LinkedResource : IResource
1877 readonly string file;
1878 readonly string name;
1879 readonly ResourceAttributes attribute;
1881 public LinkedResource (string name, string file, bool isPrivate)
1885 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1890 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1893 public string FileName {
1901 IDictionary embedded_resources = new HybridDictionary ();
1903 public void Add (bool embeded, string file, string name)
1905 Add (embeded, file, name, false);
1908 public void Add (bool embeded, string file, string name, bool isPrivate)
1910 if (embedded_resources.Contains (name)) {
1911 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1914 IResource r = embeded ?
1915 (IResource) new EmbededResource (name, file, isPrivate) :
1916 new LinkedResource (name, file, isPrivate);
1918 embedded_resources.Add (name, r);
1923 foreach (IResource r in embedded_resources.Values) {
1924 if (!File.Exists (r.FileName)) {
1925 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1935 // This is the only public entry point
1937 public class CompilerCallableEntryPoint : MarshalByRefObject {
1938 public static bool InvokeCompiler (string [] args, TextWriter error)
1940 Report.Stderr = error;
1942 Driver d = Driver.Create (args);
1946 return d.Compile () && Report.Errors == 0;
1949 Report.Stderr = Console.Error;
1954 public static int[] AllWarningNumbers {
1956 return Report.AllWarnings;
1960 static void Reset ()
1963 RootContext.Reset ();
1967 TypeManager.Reset ();
1968 TypeHandle.Reset ();
1969 RootNamespace.Reset ();
1970 NamespaceEntry.Reset ();
1973 AttributeTester.Reset ();
1974 CompilerGeneratedClass.Reset ();
1975 AnonymousTypeClass.Reset ();