2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004, 2005 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.Collections.Specialized;
21 using System.Globalization;
22 using System.Diagnostics;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references;
47 // External aliases for assemblies.
49 static Hashtable external_aliases;
52 // Modules to be linked
54 static ArrayList modules;
57 static ArrayList link_paths;
59 // Whether we want to only run the tokenizer
60 static bool tokenize = false;
62 static string first_source;
64 static bool want_debugging_support = false;
66 static bool parse_only = false;
67 static bool timestamps = false;
68 static bool pause = false;
69 static bool show_counters = false;
72 // Whether to load the initial config file (what CSC.RSP has by default)
74 static bool load_default_config = true;
77 // A list of resource files
79 static Resources embedded_resources;
80 static string win32ResourceFile;
81 static string win32IconFile;
84 // An array of the defines from the command line
86 static ArrayList defines;
91 static string output_file = null;
94 // Last time we took the time
96 static DateTime last_time, first_time;
101 static Encoding encoding;
103 static public void Reset ()
105 want_debugging_support = false;
109 show_counters = false;
110 load_default_config = true;
111 embedded_resources = null;
112 win32ResourceFile = win32IconFile = null;
119 public static void ShowTime (string msg)
124 DateTime now = DateTime.Now;
125 TimeSpan span = now - last_time;
129 "[{0:00}:{1:000}] {2}",
130 (int) span.TotalSeconds, span.Milliseconds, msg);
133 public static void ShowTotalTime (string msg)
138 DateTime now = DateTime.Now;
139 TimeSpan span = now - first_time;
143 "[{0:00}:{1:000}] {2}",
144 (int) span.TotalSeconds, span.Milliseconds, msg);
147 static void tokenize_file (SourceFile file)
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, defines);
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 // MonoTODO("Change error code for aborted compilation to something reasonable")]
175 static void parse (SourceFile file)
181 input = File.OpenRead (file.Name);
183 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
187 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
190 if (reader.Read () == 77 && reader.Read () == 90) {
191 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
197 parser = new CSharpParser (reader, file, defines);
198 parser.ErrorOutput = Report.Stderr;
201 } catch (Exception ex) {
203 666, String.Format ("Compilation aborted in file {0}, parser at {1}: {2}",
204 file.Name, parser.Lexer.Location, ex));
210 static void OtherFlags ()
213 "Other flags in the compiler\n" +
214 " --fatal Makes errors fatal\n" +
215 " --parse Only parses the source file\n" +
216 " --typetest Tests the tokenizer's built-in type parser\n" +
217 " --stacktrace Shows stack trace at error location\n" +
218 " --timestamp Displays time stamps of various compiler events\n" +
219 " --expect-error X Expect that error X will be encountered\n" +
220 " -v Verbose parsing (for debugging the parser)\n" +
221 " --mcs-debug X Sets MCS debugging level to X\n");
227 "Mono C# compiler, (C) 2001 - 2007 Novell, Inc.\n" +
228 "mcs [options] source-files\n" +
229 " --about About the Mono C# compiler\n" +
230 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
231 " -checked[+|-] Sets default aritmetic overflow context\n" +
232 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
233 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
234 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
235 " -debug[+|-], -g Generate debugging information\n" +
236 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
237 " -doc:FILE Process documentation comments to XML file\n" +
238 " -help Lists all compiler options (short: -?)\n" +
239 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
240 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
241 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
242 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
243 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
244 " -noconfig[+|-] Disables implicit references to assemblies\n" +
245 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
246 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
247 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
248 " -out:FILE Specifies output assembly name\n" +
249 " -pkg:P1[,Pn] References packages P1..Pn\n" +
250 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
251 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
252 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
253 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
254 " KIND can be one of: exe, winexe, library, module\n" +
255 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
256 " -warnaserror[+|-] Treats all warnings as errors\n" +
257 " -warn:0-4 Sets warning level, the default is 3 (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");
269 static void TargetUsage ()
271 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
277 "The Mono C# compiler is (C) 2001-2007, Novell, Inc.\n\n" +
278 "The compiler source code is released under the terms of the GNU GPL\n\n" +
280 "For more information on Mono, visit the project Web site\n" +
281 " http://www.mono-project.com\n\n" +
283 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
284 Environment.Exit (0);
287 public static int counter1, counter2;
289 public static int Main (string[] args)
291 RootContext.Version = LanguageVersion.Default;
292 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
294 bool ok = MainDriver (args);
296 if (ok && Report.Errors == 0) {
297 if (Report.Warnings > 0) {
298 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
301 Console.WriteLine ("Counter1: " + counter1);
302 Console.WriteLine ("Counter2: " + counter2);
308 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
309 Report.Errors, Report.Warnings);
314 static public void LoadAssembly (string assembly, bool soft)
316 LoadAssembly (assembly, null, soft);
319 static void Error6 (string name, string log)
321 if (log != null && log.Length > 0)
322 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
323 Report.Error (6, "cannot find metadata file `{0}'", name);
326 static void Error9 (string type, string filename, string log)
328 if (log != null && log.Length > 0)
329 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
330 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
333 static void BadAssembly (string filename, string log)
335 MethodInfo adder_method = AssemblyClass.AddModule_Method;
337 if (adder_method != null) {
338 AssemblyName an = new AssemblyName ();
340 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
344 m = adder_method.Invoke (ab, new object [] { filename });
345 } catch (TargetInvocationException ex) {
346 throw ex.InnerException;
350 Report.Error (1509, "referenced file `{0}' is not an assembly; try using the '-addmodule' option", filename);
353 } catch (FileNotFoundException) {
354 // did the file get deleted during compilation? who cares? swallow the exception
355 } catch (BadImageFormatException) {
357 } catch (FileLoadException) {
361 Error9 ("assembly", filename, log);
364 static public void LoadAssembly (string assembly, string alias, bool soft)
367 string total_log = "";
371 char[] path_chars = { '/', '\\' };
373 if (assembly.IndexOfAny (path_chars) != -1) {
374 a = Assembly.LoadFrom (assembly);
376 string ass = assembly;
377 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
378 ass = assembly.Substring (0, assembly.Length - 4);
379 a = Assembly.Load (ass);
381 } catch (FileNotFoundException) {
383 foreach (string dir in link_paths) {
384 string full_path = Path.Combine (dir, assembly);
385 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
389 a = Assembly.LoadFrom (full_path);
392 } catch (FileNotFoundException ff) {
395 total_log += ff.FusionLog;
399 Error6 (assembly, total_log);
404 // Extern aliased refs require special handling
406 RootNamespace.Global.AddAssemblyReference (a);
408 RootNamespace.DefineRootNamespace (alias, a);
410 } catch (BadImageFormatException f) {
411 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
412 BadAssembly (f.FileName, f.FusionLog);
413 } catch (FileLoadException f) {
414 // ... while .NET 1.1 throws this
415 BadAssembly (f.FileName, f.FusionLog);
419 static public void LoadModule (string module)
422 string total_log = "";
426 m = CodeGen.Assembly.AddModule (module);
427 } catch (FileNotFoundException) {
429 foreach (string dir in link_paths) {
430 string full_path = Path.Combine (dir, module);
431 if (!module.EndsWith (".netmodule"))
432 full_path += ".netmodule";
435 m = CodeGen.Assembly.AddModule (full_path);
438 } catch (FileNotFoundException ff) {
439 total_log += ff.FusionLog;
443 Error6 (module, total_log);
448 RootNamespace.Global.AddModuleReference (m);
450 } catch (BadImageFormatException f) {
451 Error9 ("module", f.FileName, f.FusionLog);
452 } catch (FileLoadException f) {
453 Error9 ("module", f.FileName, f.FusionLog);
458 /// Loads all assemblies referenced on the command line
460 static public void LoadReferences ()
463 // Load Core Library for default compilation
465 if (RootContext.StdLib)
466 LoadAssembly ("mscorlib", false);
468 foreach (string r in soft_references)
469 LoadAssembly (r, true);
471 foreach (string r in references)
472 LoadAssembly (r, false);
474 foreach (DictionaryEntry entry in external_aliases)
475 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
480 static void SetupDefaultDefines ()
482 defines = new ArrayList ();
483 defines.Add ("__MonoCS__");
486 static string [] LoadArgs (string file)
489 ArrayList args = new ArrayList ();
492 f = new StreamReader (file);
497 StringBuilder sb = new StringBuilder ();
499 while ((line = f.ReadLine ()) != null){
502 for (int i = 0; i < t; i++){
505 if (c == '"' || c == '\''){
508 for (i++; i < t; i++){
515 } else if (c == ' '){
517 args.Add (sb.ToString ());
524 args.Add (sb.ToString ());
529 string [] ret_value = new string [args.Count];
530 args.CopyTo (ret_value, 0);
536 // Returns the directory where the system assemblies are installed
538 static string GetSystemDir ()
540 return Path.GetDirectoryName (typeof (object).Assembly.Location);
544 // Given a path specification, splits the path from the file/pattern
546 static void SplitPathAndPattern (string spec, out string path, out string pattern)
548 int p = spec.LastIndexOf ('/');
551 // Windows does not like /file.cs, switch that to:
556 pattern = spec.Substring (1);
558 path = spec.Substring (0, p);
559 pattern = spec.Substring (p + 1);
564 p = spec.LastIndexOf ('\\');
566 path = spec.Substring (0, p);
567 pattern = spec.Substring (p + 1);
575 static void ProcessFile (string f)
577 if (first_source == null)
580 Location.AddFile (f);
583 static void ProcessFiles ()
585 Location.Initialize ();
587 foreach (SourceFile file in Location.SourceFiles) {
589 tokenize_file (file);
596 static void CompileFiles (string spec, bool recurse)
598 string path, pattern;
600 SplitPathAndPattern (spec, out path, out pattern);
601 if (pattern.IndexOf ('*') == -1){
606 string [] files = null;
608 files = Directory.GetFiles (path, pattern);
609 } catch (System.IO.DirectoryNotFoundException) {
610 Report.Error (2001, "Source file `" + spec + "' could not be found");
612 } catch (System.IO.IOException){
613 Report.Error (2001, "Source file `" + spec + "' could not be found");
616 foreach (string f in files) {
623 string [] dirs = null;
626 dirs = Directory.GetDirectories (path);
630 foreach (string d in dirs) {
632 // Don't include path in this string, as each
633 // directory entry already does
634 CompileFiles (d + "/" + pattern, true);
638 static void DefineDefaultConfig ()
641 // For now the "default config" is harcoded into the compiler
642 // we can move this outside later
644 string [] default_config = {
649 // Is it worth pre-loading all this stuff?
652 "System.Configuration.Install",
655 "System.DirectoryServices",
656 "System.Drawing.Design",
658 "System.EnterpriseServices",
661 "System.Runtime.Remoting",
662 "System.Runtime.Serialization.Formatters.Soap",
664 "System.ServiceProcess",
666 "System.Web.RegularExpressions",
667 "System.Web.Services",
668 "System.Windows.Forms"
672 if (RootContext.Version == LanguageVersion.LINQ)
673 soft_references.Add ("System.Core");
675 soft_references.AddRange (default_config);
678 public static string OutputFile
684 return Path.GetFileName (output_file);
688 static void SetWarningLevel (string s)
693 level = Int32.Parse (s);
696 if (level < 0 || level > 4){
697 Report.Error (1900, "Warning level must be in the range 0-4");
700 Report.WarningLevel = RootContext.WarningLevel = level;
703 static void SetupV2 ()
705 RootContext.Version = LanguageVersion.Default;
706 defines.Add ("__V2__");
709 static void Version ()
711 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
712 Console.WriteLine ("Mono C# compiler version {0}", version);
713 Environment.Exit (0);
717 // This is to test the tokenizer internal parser that is used to deambiguate
718 // '(' type identifier from '(' type others so that we are able to parse
719 // without introducing reduce/reduce conflicts in the grammar.
721 static void LambdaTypeParseTest (string fname)
725 using (FileStream fs = File.OpenRead (fname)){
726 StreamReader r = new StreamReader (fs, encoding);
729 while ((line = r.ReadLine ())!= null){
732 bool must_pass = line [0] == '+';
733 StringReader test = new StringReader (line.Substring (1));
734 SeekableStreamReader reader = new SeekableStreamReader (test);
735 SourceFile file = new SourceFile (fname, fname, 0);
737 Tokenizer lexer = new Tokenizer (reader, file, defines);
738 bool res = lexer.parse_lambda_parameters ();
740 Console.WriteLine ("{3} ({1}=={2}): {0}", line.Substring (1), res, must_pass, res == must_pass);
741 if (res != must_pass)
745 Console.WriteLine ("fail={0}", fail);
746 Environment.Exit (fail ? 1 : 0);
750 // Currently handles the Unix-like command line options, but will be
751 // deprecated in favor of the CSCParseOption, which will also handle the
752 // options that start with a dash in the future.
754 static bool UnixParseOption (string arg, ref string [] args, ref int i)
758 CSharpParser.yacc_verbose_flag++;
769 case "--main": case "-m":
770 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
771 if ((i + 1) >= args.Length){
773 Environment.Exit (1);
775 RootContext.MainClass = args [++i];
779 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
780 RootContext.Unsafe = true;
783 case "/?": case "/h": case "/help":
786 Environment.Exit (0);
790 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
791 if ((i + 1) >= args.Length){
793 Environment.Exit (1);
795 defines.Add (args [++i]);
798 case "--show-counters":
799 show_counters = true;
802 case "--expect-error": {
807 args [++i], NumberStyles.AllowLeadingSign);
808 Report.ExpectedError = code;
810 Report.Error (-14, "Invalid number specified");
821 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
822 if ((i + 1) >= args.Length){
824 Environment.Exit (1);
826 OutputFile = args [++i];
830 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
831 RootContext.Checked = true;
835 Report.Stacktrace = true;
838 case "--linkresource":
840 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
841 if ((i + 1) >= args.Length){
843 Report.Error (5, "Missing argument to --linkres");
844 Environment.Exit (1);
846 if (embedded_resources == null)
847 embedded_resources = new Resources ();
849 embedded_resources.Add (false, args [++i], args [i]);
854 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
855 if ((i + 1) >= args.Length){
857 Report.Error (5, "Missing argument to --resource");
858 Environment.Exit (1);
860 if (embedded_resources == null)
861 embedded_resources = new Resources ();
863 embedded_resources.Add (true, args [++i], args [i]);
867 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
868 if ((i + 1) >= args.Length){
869 Environment.Exit (1);
873 string type = args [++i];
876 RootContext.Target = Target.Library;
877 RootContext.TargetExt = ".dll";
881 RootContext.Target = Target.Exe;
885 RootContext.Target = Target.WinExe;
889 RootContext.Target = Target.Module;
890 RootContext.TargetExt = ".dll";
899 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
900 if ((i + 1) >= args.Length){
902 Environment.Exit (1);
905 string val = args [++i];
906 int idx = val.IndexOf ('=');
908 string alias = val.Substring (0, idx);
909 string assembly = val.Substring (idx + 1);
910 AddExternAlias (alias, assembly);
914 references.Add (val);
918 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
919 if ((i + 1) >= args.Length){
921 Environment.Exit (1);
923 link_paths.Add (args [++i]);
927 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
928 RootContext.StdLib = false;
936 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
937 Report.WarningsAreErrors = true;
941 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
942 if ((i + 1) >= args.Length){
944 Environment.Exit (1);
949 warn = Int32.Parse (args [++i]);
952 Environment.Exit (1);
954 Report.SetIgnoreWarning (warn);
958 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
959 if ((i + 1) >= args.Length){
962 "--wlevel requires a value from 0 to 4");
963 Environment.Exit (1);
966 SetWarningLevel (args [++i]);
970 if ((i + 1) >= args.Length){
971 Report.Error (5, "--mcs-debug requires an argument");
972 Environment.Exit (1);
976 Report.DebugFlags = Int32.Parse (args [++i]);
978 Report.Error (5, "Invalid argument to --mcs-debug");
979 Environment.Exit (1);
988 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
989 if ((i + 1) >= args.Length){
990 Report.Error (5, "--recurse requires an argument");
991 Environment.Exit (1);
993 CompileFiles (args [++i], true);
998 last_time = first_time = DateTime.Now;
1005 case "--debug": case "-g":
1006 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1007 want_debugging_support = true;
1011 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1012 load_default_config = false;
1016 if ((i + 1) >= args.Length){
1017 Report.Error (5, "--typetest requires a filename argument");
1018 Environment.Exit (1);
1020 LambdaTypeParseTest (args [++i]);
1028 // This parses the -arg and /arg options to the compiler, even if the strings
1029 // in the following text use "/arg" on the strings.
1031 static bool CSCParseOption (string option, ref string [] args, ref int i)
1033 int idx = option.IndexOf (':');
1040 arg = option.Substring (0, idx);
1042 value = option.Substring (idx + 1);
1053 RootContext.Target = Target.Exe;
1057 RootContext.Target = Target.WinExe;
1061 RootContext.Target = Target.Library;
1062 RootContext.TargetExt = ".dll";
1066 RootContext.Target = Target.Module;
1067 RootContext.TargetExt = ".netmodule";
1077 if (value.Length == 0){
1079 Environment.Exit (1);
1088 RootContext.Optimize = true;
1093 RootContext.Optimize = false;
1096 case "/incremental":
1097 case "/incremental+":
1098 case "/incremental-":
1104 if (value.Length == 0){
1106 Environment.Exit (1);
1109 foreach (string d in value.Split (';', ',')){
1110 if (!Tokenizer.IsValidIdentifier (d)) {
1111 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1121 // We should collect data, runtime, etc and store in the file specified
1123 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1129 if (value.Length == 0){
1131 Environment.Exit (1);
1133 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1135 ProcessStartInfo pi = new ProcessStartInfo ();
1136 pi.FileName = "pkg-config";
1137 pi.RedirectStandardOutput = true;
1138 pi.UseShellExecute = false;
1139 pi.Arguments = "--libs " + packages;
1142 p = Process.Start (pi);
1143 } catch (Exception e) {
1144 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1145 Environment.Exit (1);
1148 if (p.StandardOutput == null){
1149 Report.Warning (-27, 1, "Specified package did not return any information");
1152 string pkgout = p.StandardOutput.ReadToEnd ();
1154 if (p.ExitCode != 0) {
1155 Report.Error (-27, "Error running pkg-config. Check the above output.");
1156 Environment.Exit (1);
1159 if (pkgout != null){
1160 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1161 Split (new Char [] { ' ', '\t'});
1162 args = AddArgs (args, xargs);
1170 case "/linkresource":
1173 if (embedded_resources == null)
1174 embedded_resources = new Resources ();
1176 bool embeded = arg.StartsWith ("/r");
1177 string[] s = value.Split (',');
1180 if (s[0].Length == 0)
1182 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1185 embedded_resources.Add (embeded, s [0], s [1]);
1188 if (s [2] != "public" && s [2] != "private") {
1189 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1192 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1195 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1202 if (value.Length == 0){
1203 Report.Error (5, "-recurse requires an argument");
1204 Environment.Exit (1);
1206 CompileFiles (value, true);
1210 case "/reference": {
1211 if (value.Length == 0){
1212 Report.Error (5, "-reference requires an argument");
1213 Environment.Exit (1);
1216 string [] refs = value.Split (new char [] { ';', ',' });
1217 foreach (string r in refs){
1219 int index = val.IndexOf ('=');
1221 string alias = r.Substring (0, index);
1222 string assembly = r.Substring (index + 1);
1223 AddExternAlias (alias, assembly);
1227 references.Add (val);
1231 case "/addmodule": {
1232 if (value.Length == 0){
1233 Report.Error (5, arg + " requires an argument");
1234 Environment.Exit (1);
1237 string [] refs = value.Split (new char [] { ';', ',' });
1238 foreach (string r in refs){
1244 if (value.Length == 0) {
1245 Report.Error (5, arg + " requires an argument");
1246 Environment.Exit (1);
1249 win32ResourceFile = value;
1252 case "/win32icon": {
1253 if (value.Length == 0) {
1254 Report.Error (5, arg + " requires an argument");
1255 Environment.Exit (1);
1258 win32IconFile = value;
1262 if (value.Length == 0){
1263 Report.Error (2006, arg + " requires an argument");
1264 Environment.Exit (1);
1266 RootContext.Documentation = new Documentation (value);
1272 if (value.Length == 0){
1273 Report.Error (5, "/lib requires an argument");
1274 Environment.Exit (1);
1277 libdirs = value.Split (new Char [] { ',' });
1278 foreach (string dir in libdirs)
1279 link_paths.Add (dir);
1284 want_debugging_support = false;
1289 want_debugging_support = true;
1294 RootContext.Checked = true;
1298 RootContext.Checked = false;
1306 RootContext.VerifyClsCompliance = false;
1311 RootContext.Unsafe = true;
1315 RootContext.Unsafe = false;
1318 case "/warnaserror":
1319 case "/warnaserror+":
1320 Report.WarningsAreErrors = true;
1323 case "/warnaserror-":
1324 Report.WarningsAreErrors = false;
1328 SetWarningLevel (value);
1334 if (value.Length == 0){
1335 Report.Error (5, "/nowarn requires an argument");
1336 Environment.Exit (1);
1339 warns = value.Split (new Char [] {','});
1340 foreach (string wc in warns){
1342 int warn = Int32.Parse (wc);
1344 throw new ArgumentOutOfRangeException("warn");
1346 Report.SetIgnoreWarning (warn);
1348 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1355 load_default_config = true;
1360 load_default_config = false;
1365 Environment.Exit(0);
1371 Environment.Exit (0);
1376 if (value.Length == 0){
1377 Report.Error (5, arg + " requires an argument");
1378 Environment.Exit (1);
1380 RootContext.MainClass = value;
1385 RootContext.StdLib = false;
1389 RootContext.StdLib = true;
1396 if (value == String.Empty) {
1397 Report.Error (5, arg + " requires an argument");
1398 Environment.Exit (1);
1400 RootContext.StrongNameKeyFile = value;
1402 case "/keycontainer":
1403 if (value == String.Empty) {
1404 Report.Error (5, arg + " requires an argument");
1405 Environment.Exit (1);
1407 RootContext.StrongNameKeyContainer = value;
1410 RootContext.StrongNameDelaySign = true;
1413 RootContext.StrongNameDelaySign = false;
1418 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1422 case "/langversion":
1423 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1425 RootContext.Version = LanguageVersion.ISO_1;
1433 RootContext.Version = LanguageVersion.LINQ;
1434 Tokenizer.InitializeLinqKeywords ();
1438 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1444 encoding = new UTF8Encoding();
1447 encoding = Encoding.Default;
1451 encoding = Encoding.GetEncoding (
1452 Int32.Parse (value));
1454 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1464 static void Error_WrongOption (string option)
1466 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1469 static string [] AddArgs (string [] args, string [] extra_args)
1472 new_args = new string [extra_args.Length + args.Length];
1474 // if args contains '--' we have to take that into account
1475 // split args into first half and second half based on '--'
1476 // and add the extra_args before --
1477 int split_position = Array.IndexOf (args, "--");
1478 if (split_position != -1)
1480 Array.Copy (args, new_args, split_position);
1481 extra_args.CopyTo (new_args, split_position);
1482 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1486 args.CopyTo (new_args, 0);
1487 extra_args.CopyTo (new_args, args.Length);
1493 static void AddExternAlias (string identifier, string assembly)
1495 if (assembly.Length == 0) {
1496 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1500 if (!IsExternAliasValid (identifier)) {
1501 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1505 // Could here hashtable throw an exception?
1506 external_aliases [identifier] = assembly;
1509 static bool IsExternAliasValid (string identifier)
1511 if (identifier.Length == 0)
1513 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1516 for (int i = 1; i < identifier.Length; i++) {
1517 char c = identifier [i];
1518 if (Char.IsLetter (c) || Char.IsDigit (c))
1521 UnicodeCategory category = Char.GetUnicodeCategory (c);
1522 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1523 category != UnicodeCategory.SpacingCombiningMark ||
1524 category != UnicodeCategory.ConnectorPunctuation)
1532 /// Parses the arguments, and drives the compilation
1537 /// TODO: Mostly structured to debug the compiler
1538 /// now, needs to be turned into a real driver soon.
1540 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1541 internal static bool MainDriver (string [] args)
1544 bool parsing_options = true;
1546 encoding = Encoding.Default;
1548 references = new ArrayList ();
1549 external_aliases = new Hashtable ();
1550 soft_references = new ArrayList ();
1551 modules = new ArrayList ();
1552 link_paths = new ArrayList ();
1554 SetupDefaultDefines ();
1559 // This is not required because Assembly.Load knows about this
1563 Hashtable response_file_list = null;
1565 for (i = 0; i < args.Length; i++){
1566 string arg = args [i];
1567 if (arg.Length == 0)
1570 if (arg.StartsWith ("@")){
1571 string [] extra_args;
1572 string response_file = arg.Substring (1);
1574 if (response_file_list == null)
1575 response_file_list = new Hashtable ();
1577 if (response_file_list.Contains (response_file)){
1579 1515, "Response file `" + response_file +
1580 "' specified multiple times");
1581 Environment.Exit (1);
1584 response_file_list.Add (response_file, response_file);
1586 extra_args = LoadArgs (response_file);
1587 if (extra_args == null){
1588 Report.Error (2011, "Unable to open response file: " +
1593 args = AddArgs (args, extra_args);
1597 if (parsing_options){
1599 parsing_options = false;
1603 if (arg.StartsWith ("-")){
1604 if (UnixParseOption (arg, ref args, ref i))
1608 string csc_opt = "/" + arg.Substring (1);
1609 if (CSCParseOption (csc_opt, ref args, ref i))
1612 Error_WrongOption (arg);
1615 if (arg [0] == '/'){
1616 if (CSCParseOption (arg, ref args, ref i))
1619 // Need to skip `/home/test.cs' however /test.cs is considered as error
1620 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1621 Error_WrongOption (arg);
1628 CompileFiles (arg, false);
1636 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1637 throw new InternalErrorException ("who set it?");
1640 // If we are an exe, require a source file for the entry point
1642 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1643 if (first_source == null){
1644 Report.Error (2008, "No files to compile were specified");
1651 // If there is nothing to put in the assembly, and we are not a library
1653 if (first_source == null && embedded_resources == null){
1654 Report.Error (2008, "No files to compile were specified");
1658 if (Report.Errors > 0)
1664 if (load_default_config)
1665 DefineDefaultConfig ();
1667 if (Report.Errors > 0){
1672 // Load assemblies required
1675 ShowTime ("Loading references");
1676 link_paths.Add (GetSystemDir ());
1677 link_paths.Add (Directory.GetCurrentDirectory ());
1681 ShowTime (" References loaded");
1683 if (Report.Errors > 0){
1690 if (output_file == null){
1691 if (first_source == null){
1692 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1696 int pos = first_source.LastIndexOf ('.');
1699 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1701 output_file = first_source + RootContext.TargetExt;
1704 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1707 if (RootContext.Target == Target.Module) {
1708 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1709 if (module_only == null) {
1710 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1711 Environment.Exit (1);
1714 MethodInfo set_method = module_only.GetSetMethod (true);
1715 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1718 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1720 if (modules.Count > 0) {
1721 foreach (string module in modules)
1722 LoadModule (module);
1726 // Before emitting, we need to get the core
1727 // types emitted from the user defined types
1728 // or from the system ones.
1731 ShowTime ("Initializing Core Types");
1732 if (!RootContext.StdLib){
1733 RootContext.ResolveCore ();
1734 if (Report.Errors > 0)
1738 TypeManager.InitCoreTypes ();
1740 ShowTime (" Core Types done");
1742 CodeGen.Module.Resolve ();
1745 // The second pass of the compiler
1748 ShowTime ("Resolving tree");
1749 RootContext.ResolveTree ();
1751 if (Report.Errors > 0)
1754 ShowTime ("Populate tree");
1755 if (!RootContext.StdLib)
1756 RootContext.BootCorlib_PopulateCoreTypes ();
1757 RootContext.PopulateTypes ();
1759 TypeManager.InitCodeHelpers ();
1761 RootContext.DefineTypes ();
1763 if (Report.Errors == 0 &&
1764 RootContext.Documentation != null &&
1765 !RootContext.Documentation.OutputDocComment (
1770 // Verify using aliases now
1772 NamespaceEntry.VerifyAllUsing ();
1774 if (Report.Errors > 0){
1778 CodeGen.Assembly.Resolve ();
1780 if (RootContext.VerifyClsCompliance) {
1781 if (CodeGen.Assembly.IsClsCompliant) {
1782 AttributeTester.VerifyModulesClsCompliance ();
1783 TypeManager.LoadAllImportedTypes ();
1786 if (Report.Errors > 0)
1790 // The code generator
1793 ShowTime ("Emitting code");
1794 ShowTotalTime ("Total so far");
1795 RootContext.EmitCode ();
1799 if (Report.Errors > 0){
1804 ShowTime ("Closing types");
1806 RootContext.CloseTypes ();
1808 PEFileKinds k = PEFileKinds.ConsoleApplication;
1810 switch (RootContext.Target) {
1811 case Target.Library:
1813 k = PEFileKinds.Dll; break;
1815 k = PEFileKinds.ConsoleApplication; break;
1817 k = PEFileKinds.WindowApplication; break;
1820 if (RootContext.NeedsEntryPoint) {
1821 MethodInfo ep = RootContext.EntryPoint;
1824 if (RootContext.MainClass != null) {
1825 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1826 if (main_cont == null) {
1827 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1831 if (!(main_cont is ClassOrStruct)) {
1832 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1836 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1840 if (Report.Errors == 0)
1841 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1846 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1847 } else if (RootContext.MainClass != null) {
1848 Report.Error (2017, "Cannot specify -main if building a module or library");
1851 if (embedded_resources != null){
1852 if (RootContext.Target == Target.Module) {
1853 Report.Error (1507, "Cannot link resource file when building a module");
1857 embedded_resources.Emit ();
1861 // Add Win32 resources
1864 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1866 if (win32ResourceFile != null) {
1868 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1870 catch (ArgumentException) {
1871 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1875 if (win32IconFile != null) {
1876 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1877 if (define_icon == null) {
1878 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1880 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1883 if (Report.Errors > 0)
1886 CodeGen.Save (output_file);
1888 ShowTime ("Saved output");
1889 ShowTotalTime ("Total");
1892 Timer.ShowTimers ();
1894 if (Report.ExpectedError != 0) {
1895 if (Report.Errors == 0) {
1896 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1897 "No other errors reported.");
1899 Environment.Exit (2);
1901 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1902 "However, other errors were reported.");
1904 Environment.Exit (1);
1912 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1913 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1915 return (Report.Errors == 0);
1924 string FileName { get; }
1927 class EmbededResource : IResource
1929 static MethodInfo embed_res;
1931 static EmbededResource () {
1932 Type[] argst = new Type [] {
1933 typeof (string), typeof (string), typeof (ResourceAttributes)
1936 embed_res = typeof (AssemblyBuilder).GetMethod (
1937 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1938 null, CallingConventions.Any, argst, null);
1940 if (embed_res == null) {
1941 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1945 readonly object[] args;
1947 public EmbededResource (string name, string file, bool isPrivate)
1949 args = new object [3];
1952 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1957 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1960 public string FileName {
1962 return (string)args [1];
1967 class LinkedResource : IResource
1969 readonly string file;
1970 readonly string name;
1971 readonly ResourceAttributes attribute;
1973 public LinkedResource (string name, string file, bool isPrivate)
1977 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1982 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1985 public string FileName {
1993 IDictionary embedded_resources = new HybridDictionary ();
1995 public void Add (bool embeded, string file, string name)
1997 Add (embeded, file, name, false);
2000 public void Add (bool embeded, string file, string name, bool isPrivate)
2002 if (embedded_resources.Contains (name)) {
2003 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
2006 IResource r = embeded ?
2007 (IResource) new EmbededResource (name, file, isPrivate) :
2008 new LinkedResource (name, file, isPrivate);
2010 embedded_resources.Add (name, r);
2015 foreach (IResource r in embedded_resources.Values) {
2016 if (!File.Exists (r.FileName)) {
2017 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
2027 // This is the only public entry point
2029 public class CompilerCallableEntryPoint : MarshalByRefObject {
2030 public static bool InvokeCompiler (string [] args, TextWriter error)
2032 Report.Stderr = error;
2034 return Driver.MainDriver (args) && Report.Errors == 0;
2037 Report.Stderr = Console.Error;
2042 public static int[] AllWarningNumbers {
2044 return Report.AllWarnings;
2048 static void Reset ()
2051 RootContext.Reset ();
2055 TypeManager.Reset ();
2056 TypeHandle.Reset ();
2057 RootNamespace.Reset ();
2058 NamespaceEntry.Reset ();
2061 AttributeTester.Reset ();