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 " -2 Enables experimental C# features\n" +
221 " -v Verbose parsing (for debugging the parser)\n" +
222 " --mcs-debug X Sets MCS debugging level to X\n");
228 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
229 "mcs [options] source-files\n" +
230 " --about About the Mono C# compiler\n" +
231 " -addmodule:MODULE Adds the module to the generated assembly\n" +
232 " -checked[+|-] Set default context to checked\n" +
233 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
234 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
235 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
236 " -debug[+|-], -g Generate debugging information\n" +
237 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
238 " -doc:FILE XML Documentation file to generate\n" +
239 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
240 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
241 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
242 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
243 " -main:class Specified the class that contains the entry point\n" +
244 " -noconfig[+|-] Disables implicit references to assemblies\n" +
245 " -nostdlib[+|-] Does not load core libraries\n" +
246 " -nowarn:W1[,W2] Disables one or more warnings\n" +
247 " -optimize[+|-] Enables code optimalizations\n" +
248 " -out:FNAME Specifies output file\n" +
249 " -pkg:P1[,Pn] References packages P1..Pn\n" +
250 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
251 " -reference:ASS References the specified assembly (-r:ASS)\n" +
252 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
253 " library, module), (short: /t:)\n" +
254 " -unsafe[+|-] Allows unsafe code\n" +
255 " -warnaserror[+|-] Treat warnings as errors\n" +
256 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
257 " -help2 Show other help flags\n" +
260 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
261 " -resource:FILE[,ID] Embed FILE as a resource\n" +
262 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
263 " -win32icon:FILE Use this icon for the output\n" +
264 " @file Read response file for more options\n\n" +
265 "Options can be of the form -option or /option");
268 static void TargetUsage ()
270 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
276 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
277 "The compiler source code is released under the terms of the GNU GPL\n\n" +
279 "For more information on Mono, visit the project Web site\n" +
280 " http://www.go-mono.com\n\n" +
282 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
283 Environment.Exit (0);
286 public static int counter1, counter2;
288 public static int Main (string[] args)
290 RootContext.Version = LanguageVersion.Default;
291 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
293 bool ok = MainDriver (args);
295 if (ok && Report.Errors == 0) {
296 if (Report.Warnings > 0) {
297 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
300 Console.WriteLine ("Counter1: " + counter1);
301 Console.WriteLine ("Counter2: " + counter2);
307 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
308 Report.Errors, Report.Warnings);
313 static public void LoadAssembly (string assembly, bool soft)
315 LoadAssembly (assembly, null, soft);
318 static void Error6 (string name, string log)
320 if (log != null && log.Length > 0)
321 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
322 Report.Error (6, "cannot find metadata file `{0}'", name);
325 static void Error9 (string type, string filename, string log)
327 if (log != null && log.Length > 0)
328 Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
329 Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
332 static void BadAssembly (string filename, string log)
334 MethodInfo adder_method = AssemblyClass.AddModule_Method;
336 if (adder_method != null) {
337 AssemblyName an = new AssemblyName ();
339 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
343 m = adder_method.Invoke (ab, new object [] { filename });
344 } catch (TargetInvocationException ex) {
345 throw ex.InnerException;
349 Report.Error (1509, "referenced file `{0}' is not an assembly; try using the '-addmodule' option", filename);
352 } catch (FileNotFoundException) {
353 // did the file get deleted during compilation? who cares? swallow the exception
354 } catch (BadImageFormatException) {
356 } catch (FileLoadException) {
360 Error9 ("assembly", filename, log);
363 static public void LoadAssembly (string assembly, string alias, bool soft)
366 string total_log = "";
370 char[] path_chars = { '/', '\\' };
372 if (assembly.IndexOfAny (path_chars) != -1) {
373 a = Assembly.LoadFrom (assembly);
375 string ass = assembly;
376 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
377 ass = assembly.Substring (0, assembly.Length - 4);
378 a = Assembly.Load (ass);
380 } catch (FileNotFoundException) {
382 foreach (string dir in link_paths) {
383 string full_path = Path.Combine (dir, assembly);
384 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
388 a = Assembly.LoadFrom (full_path);
391 } catch (FileNotFoundException ff) {
394 total_log += ff.FusionLog;
398 Error6 (assembly, total_log);
403 // Extern aliased refs require special handling
405 RootNamespace.Global.AddAssemblyReference (a);
407 RootNamespace.DefineRootNamespace (alias, a);
409 } catch (BadImageFormatException f) {
410 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
411 BadAssembly (f.FileName, f.FusionLog);
412 } catch (FileLoadException f) {
413 // ... while .NET 1.1 throws this
414 BadAssembly (f.FileName, f.FusionLog);
418 static public void LoadModule (string module)
421 string total_log = "";
425 m = CodeGen.Assembly.AddModule (module);
426 } catch (FileNotFoundException) {
428 foreach (string dir in link_paths) {
429 string full_path = Path.Combine (dir, module);
430 if (!module.EndsWith (".netmodule"))
431 full_path += ".netmodule";
434 m = CodeGen.Assembly.AddModule (full_path);
437 } catch (FileNotFoundException ff) {
438 total_log += ff.FusionLog;
442 Error6 (module, total_log);
447 RootNamespace.Global.AddModuleReference (m);
449 } catch (BadImageFormatException f) {
450 Error9 ("module", f.FileName, f.FusionLog);
451 } catch (FileLoadException f) {
452 Error9 ("module", f.FileName, f.FusionLog);
457 /// Loads all assemblies referenced on the command line
459 static public void LoadReferences ()
462 // Load Core Library for default compilation
464 if (RootContext.StdLib)
465 LoadAssembly ("mscorlib", false);
467 foreach (string r in soft_references)
468 LoadAssembly (r, true);
470 foreach (string r in references)
471 LoadAssembly (r, false);
473 foreach (DictionaryEntry entry in external_aliases)
474 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
479 static void SetupDefaultDefines ()
481 defines = new ArrayList ();
482 defines.Add ("__MonoCS__");
485 static string [] LoadArgs (string file)
488 ArrayList args = new ArrayList ();
491 f = new StreamReader (file);
496 StringBuilder sb = new StringBuilder ();
498 while ((line = f.ReadLine ()) != null){
501 for (int i = 0; i < t; i++){
504 if (c == '"' || c == '\''){
507 for (i++; i < t; i++){
514 } else if (c == ' '){
516 args.Add (sb.ToString ());
523 args.Add (sb.ToString ());
528 string [] ret_value = new string [args.Count];
529 args.CopyTo (ret_value, 0);
535 // Returns the directory where the system assemblies are installed
537 static string GetSystemDir ()
539 return Path.GetDirectoryName (typeof (object).Assembly.Location);
543 // Given a path specification, splits the path from the file/pattern
545 static void SplitPathAndPattern (string spec, out string path, out string pattern)
547 int p = spec.LastIndexOf ('/');
550 // Windows does not like /file.cs, switch that to:
555 pattern = spec.Substring (1);
557 path = spec.Substring (0, p);
558 pattern = spec.Substring (p + 1);
563 p = spec.LastIndexOf ('\\');
565 path = spec.Substring (0, p);
566 pattern = spec.Substring (p + 1);
574 static void ProcessFile (string f)
576 if (first_source == null)
579 Location.AddFile (f);
582 static void ProcessFiles ()
584 Location.Initialize ();
586 foreach (SourceFile file in Location.SourceFiles) {
588 tokenize_file (file);
595 static void CompileFiles (string spec, bool recurse)
597 string path, pattern;
599 SplitPathAndPattern (spec, out path, out pattern);
600 if (pattern.IndexOf ('*') == -1){
605 string [] files = null;
607 files = Directory.GetFiles (path, pattern);
608 } catch (System.IO.DirectoryNotFoundException) {
609 Report.Error (2001, "Source file `" + spec + "' could not be found");
611 } catch (System.IO.IOException){
612 Report.Error (2001, "Source file `" + spec + "' could not be found");
615 foreach (string f in files) {
622 string [] dirs = null;
625 dirs = Directory.GetDirectories (path);
629 foreach (string d in dirs) {
631 // Don't include path in this string, as each
632 // directory entry already does
633 CompileFiles (d + "/" + pattern, true);
637 static void DefineDefaultConfig ()
640 // For now the "default config" is harcoded into the compiler
641 // we can move this outside later
643 string [] default_config = {
648 // Is it worth pre-loading all this stuff?
651 "System.Configuration.Install",
654 "System.DirectoryServices",
655 "System.Drawing.Design",
657 "System.EnterpriseServices",
660 "System.Runtime.Remoting",
661 "System.Runtime.Serialization.Formatters.Soap",
663 "System.ServiceProcess",
665 "System.Web.RegularExpressions",
666 "System.Web.Services",
667 "System.Windows.Forms"
671 if (RootContext.Version == LanguageVersion.LINQ)
672 soft_references.Add ("System.Core");
674 soft_references.AddRange (default_config);
677 public static string OutputFile
683 return Path.GetFileName (output_file);
687 static void SetWarningLevel (string s)
692 level = Int32.Parse (s);
695 if (level < 0 || level > 4){
696 Report.Error (1900, "Warning level must be in the range 0-4");
699 RootContext.WarningLevel = level;
702 static void SetupV2 ()
704 RootContext.Version = LanguageVersion.Default;
705 defines.Add ("__V2__");
708 static void Version ()
710 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
711 Console.WriteLine ("Mono C# compiler version {0}", version);
712 Environment.Exit (0);
716 // This is to test the tokenizer internal parser that is used to deambiguate
717 // '(' type identifier from '(' type others so that we are able to parse
718 // without introducing reduce/reduce conflicts in the grammar.
720 static void LambdaTypeParseTest (string fname)
724 using (FileStream fs = File.OpenRead (fname)){
725 StreamReader r = new StreamReader (fs, encoding);
728 while ((line = r.ReadLine ())!= null){
731 bool must_pass = line [0] == '+';
732 StringReader test = new StringReader (line.Substring (1));
733 SeekableStreamReader reader = new SeekableStreamReader (test);
734 SourceFile file = new SourceFile (fname, fname, 0);
736 Tokenizer lexer = new Tokenizer (reader, file, defines);
737 bool res = lexer.parse_lambda_parameters ();
739 Console.WriteLine ("{3} ({1}=={2}): {0}", line.Substring (1), res, must_pass, res == must_pass);
740 if (res != must_pass)
744 Console.WriteLine ("fail={0}", fail);
745 Environment.Exit (fail ? 1 : 0);
749 // Currently handles the Unix-like command line options, but will be
750 // deprecated in favor of the CSCParseOption, which will also handle the
751 // options that start with a dash in the future.
753 static bool UnixParseOption (string arg, ref string [] args, ref int i)
757 CSharpParser.yacc_verbose_flag++;
768 case "--main": case "-m":
769 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
770 if ((i + 1) >= args.Length){
772 Environment.Exit (1);
774 RootContext.MainClass = args [++i];
778 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
779 RootContext.Unsafe = true;
782 case "/?": case "/h": case "/help":
785 Environment.Exit (0);
789 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
790 if ((i + 1) >= args.Length){
792 Environment.Exit (1);
794 defines.Add (args [++i]);
797 case "--show-counters":
798 show_counters = true;
801 case "--expect-error": {
806 args [++i], NumberStyles.AllowLeadingSign);
807 Report.ExpectedError = code;
809 Report.Error (-14, "Invalid number specified");
820 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
821 if ((i + 1) >= args.Length){
823 Environment.Exit (1);
825 OutputFile = args [++i];
829 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
830 RootContext.Checked = true;
834 Report.Stacktrace = true;
837 case "--linkresource":
839 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
840 if ((i + 1) >= args.Length){
842 Report.Error (5, "Missing argument to --linkres");
843 Environment.Exit (1);
845 if (embedded_resources == null)
846 embedded_resources = new Resources ();
848 embedded_resources.Add (false, args [++i], args [i]);
853 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
854 if ((i + 1) >= args.Length){
856 Report.Error (5, "Missing argument to --resource");
857 Environment.Exit (1);
859 if (embedded_resources == null)
860 embedded_resources = new Resources ();
862 embedded_resources.Add (true, args [++i], args [i]);
866 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
867 if ((i + 1) >= args.Length){
868 Environment.Exit (1);
872 string type = args [++i];
875 RootContext.Target = Target.Library;
876 RootContext.TargetExt = ".dll";
880 RootContext.Target = Target.Exe;
884 RootContext.Target = Target.WinExe;
888 RootContext.Target = Target.Module;
889 RootContext.TargetExt = ".dll";
898 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
899 if ((i + 1) >= args.Length){
901 Environment.Exit (1);
904 string val = args [++i];
905 int idx = val.IndexOf ('=');
907 string alias = val.Substring (0, idx);
908 string assembly = val.Substring (idx + 1);
909 AddExternAlias (alias, assembly);
913 references.Add (val);
917 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
918 if ((i + 1) >= args.Length){
920 Environment.Exit (1);
922 link_paths.Add (args [++i]);
926 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
927 RootContext.StdLib = false;
935 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
936 Report.WarningsAreErrors = true;
940 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
941 if ((i + 1) >= args.Length){
943 Environment.Exit (1);
948 warn = Int32.Parse (args [++i]);
951 Environment.Exit (1);
953 Report.SetIgnoreWarning (warn);
957 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
958 if ((i + 1) >= args.Length){
961 "--wlevel requires a value from 0 to 4");
962 Environment.Exit (1);
965 SetWarningLevel (args [++i]);
969 if ((i + 1) >= args.Length){
970 Report.Error (5, "--mcs-debug requires an argument");
971 Environment.Exit (1);
975 Report.DebugFlags = Int32.Parse (args [++i]);
977 Report.Error (5, "Invalid argument to --mcs-debug");
978 Environment.Exit (1);
987 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
988 if ((i + 1) >= args.Length){
989 Report.Error (5, "--recurse requires an argument");
990 Environment.Exit (1);
992 CompileFiles (args [++i], true);
997 last_time = first_time = DateTime.Now;
1004 case "--debug": case "-g":
1005 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1006 want_debugging_support = true;
1010 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1011 load_default_config = false;
1015 if ((i + 1) >= args.Length){
1016 Report.Error (5, "--typetest requires a filename argument");
1017 Environment.Exit (1);
1019 LambdaTypeParseTest (args [++i]);
1027 // This parses the -arg and /arg options to the compiler, even if the strings
1028 // in the following text use "/arg" on the strings.
1030 static bool CSCParseOption (string option, ref string [] args, ref int i)
1032 int idx = option.IndexOf (':');
1039 arg = option.Substring (0, idx);
1041 value = option.Substring (idx + 1);
1052 RootContext.Target = Target.Exe;
1056 RootContext.Target = Target.WinExe;
1060 RootContext.Target = Target.Library;
1061 RootContext.TargetExt = ".dll";
1065 RootContext.Target = Target.Module;
1066 RootContext.TargetExt = ".netmodule";
1076 if (value.Length == 0){
1078 Environment.Exit (1);
1087 RootContext.Optimize = true;
1092 RootContext.Optimize = false;
1095 case "/incremental":
1096 case "/incremental+":
1097 case "/incremental-":
1103 if (value.Length == 0){
1105 Environment.Exit (1);
1108 foreach (string d in value.Split (';', ',')){
1109 if (!Tokenizer.IsValidIdentifier (d)) {
1110 Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", d);
1120 // We should collect data, runtime, etc and store in the file specified
1122 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1128 if (value.Length == 0){
1130 Environment.Exit (1);
1132 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1134 ProcessStartInfo pi = new ProcessStartInfo ();
1135 pi.FileName = "pkg-config";
1136 pi.RedirectStandardOutput = true;
1137 pi.UseShellExecute = false;
1138 pi.Arguments = "--libs " + packages;
1141 p = Process.Start (pi);
1142 } catch (Exception e) {
1143 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1144 Environment.Exit (1);
1147 if (p.StandardOutput == null){
1148 Report.Warning (-27, 1, "Specified package did not return any information");
1151 string pkgout = p.StandardOutput.ReadToEnd ();
1153 if (p.ExitCode != 0) {
1154 Report.Error (-27, "Error running pkg-config. Check the above output.");
1155 Environment.Exit (1);
1158 if (pkgout != null){
1159 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1160 Split (new Char [] { ' ', '\t'});
1161 args = AddArgs (args, xargs);
1169 case "/linkresource":
1172 if (embedded_resources == null)
1173 embedded_resources = new Resources ();
1175 bool embeded = arg.StartsWith ("/r");
1176 string[] s = value.Split (',');
1179 if (s[0].Length == 0)
1181 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1184 embedded_resources.Add (embeded, s [0], s [1]);
1187 if (s [2] != "public" && s [2] != "private") {
1188 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1191 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1194 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1201 if (value.Length == 0){
1202 Report.Error (5, "-recurse requires an argument");
1203 Environment.Exit (1);
1205 CompileFiles (value, true);
1209 case "/reference": {
1210 if (value.Length == 0){
1211 Report.Error (5, "-reference requires an argument");
1212 Environment.Exit (1);
1215 string [] refs = value.Split (new char [] { ';', ',' });
1216 foreach (string r in refs){
1218 int index = val.IndexOf ('=');
1220 string alias = r.Substring (0, index);
1221 string assembly = r.Substring (index + 1);
1222 AddExternAlias (alias, assembly);
1226 references.Add (val);
1230 case "/addmodule": {
1231 if (value.Length == 0){
1232 Report.Error (5, arg + " requires an argument");
1233 Environment.Exit (1);
1236 string [] refs = value.Split (new char [] { ';', ',' });
1237 foreach (string r in refs){
1243 if (value.Length == 0) {
1244 Report.Error (5, arg + " requires an argument");
1245 Environment.Exit (1);
1248 win32ResourceFile = value;
1251 case "/win32icon": {
1252 if (value.Length == 0) {
1253 Report.Error (5, arg + " requires an argument");
1254 Environment.Exit (1);
1257 win32IconFile = value;
1261 if (value.Length == 0){
1262 Report.Error (2006, arg + " requires an argument");
1263 Environment.Exit (1);
1265 RootContext.Documentation = new Documentation (value);
1271 if (value.Length == 0){
1272 Report.Error (5, "/lib requires an argument");
1273 Environment.Exit (1);
1276 libdirs = value.Split (new Char [] { ',' });
1277 foreach (string dir in libdirs)
1278 link_paths.Add (dir);
1283 want_debugging_support = false;
1288 want_debugging_support = true;
1293 RootContext.Checked = true;
1297 RootContext.Checked = false;
1305 RootContext.VerifyClsCompliance = false;
1310 RootContext.Unsafe = true;
1314 RootContext.Unsafe = false;
1317 case "/warnaserror":
1318 case "/warnaserror+":
1319 Report.WarningsAreErrors = true;
1322 case "/warnaserror-":
1323 Report.WarningsAreErrors = false;
1327 SetWarningLevel (value);
1333 if (value.Length == 0){
1334 Report.Error (5, "/nowarn requires an argument");
1335 Environment.Exit (1);
1338 warns = value.Split (new Char [] {','});
1339 foreach (string wc in warns){
1341 int warn = Int32.Parse (wc);
1343 throw new ArgumentOutOfRangeException("warn");
1345 Report.SetIgnoreWarning (warn);
1347 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1354 load_default_config = true;
1359 load_default_config = false;
1364 Environment.Exit(0);
1370 Environment.Exit (0);
1375 if (value.Length == 0){
1376 Report.Error (5, arg + " requires an argument");
1377 Environment.Exit (1);
1379 RootContext.MainClass = value;
1384 RootContext.StdLib = false;
1388 RootContext.StdLib = true;
1395 if (value == String.Empty) {
1396 Report.Error (5, arg + " requires an argument");
1397 Environment.Exit (1);
1399 RootContext.StrongNameKeyFile = value;
1401 case "/keycontainer":
1402 if (value == String.Empty) {
1403 Report.Error (5, arg + " requires an argument");
1404 Environment.Exit (1);
1406 RootContext.StrongNameKeyContainer = value;
1409 RootContext.StrongNameDelaySign = true;
1412 RootContext.StrongNameDelaySign = false;
1417 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1421 case "/langversion":
1422 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1424 RootContext.Version = LanguageVersion.ISO_1;
1432 RootContext.Version = LanguageVersion.LINQ;
1433 Tokenizer.InitializeLinqKeywords ();
1437 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1443 encoding = new UTF8Encoding();
1446 encoding = Encoding.Default;
1450 encoding = Encoding.GetEncoding (
1451 Int32.Parse (value));
1453 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1463 static void Error_WrongOption (string option)
1465 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1468 static string [] AddArgs (string [] args, string [] extra_args)
1471 new_args = new string [extra_args.Length + args.Length];
1473 // if args contains '--' we have to take that into account
1474 // split args into first half and second half based on '--'
1475 // and add the extra_args before --
1476 int split_position = Array.IndexOf (args, "--");
1477 if (split_position != -1)
1479 Array.Copy (args, new_args, split_position);
1480 extra_args.CopyTo (new_args, split_position);
1481 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1485 args.CopyTo (new_args, 0);
1486 extra_args.CopyTo (new_args, args.Length);
1492 static void AddExternAlias (string identifier, string assembly)
1494 if (assembly.Length == 0) {
1495 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1499 if (!IsExternAliasValid (identifier)) {
1500 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1504 // Could here hashtable throw an exception?
1505 external_aliases [identifier] = assembly;
1508 static bool IsExternAliasValid (string identifier)
1510 if (identifier.Length == 0)
1512 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1515 for (int i = 1; i < identifier.Length; i++) {
1516 char c = identifier [i];
1517 if (Char.IsLetter (c) || Char.IsDigit (c))
1520 UnicodeCategory category = Char.GetUnicodeCategory (c);
1521 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1522 category != UnicodeCategory.SpacingCombiningMark ||
1523 category != UnicodeCategory.ConnectorPunctuation)
1531 /// Parses the arguments, and drives the compilation
1536 /// TODO: Mostly structured to debug the compiler
1537 /// now, needs to be turned into a real driver soon.
1539 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1540 internal static bool MainDriver (string [] args)
1543 bool parsing_options = true;
1545 encoding = Encoding.Default;
1547 references = new ArrayList ();
1548 external_aliases = new Hashtable ();
1549 soft_references = new ArrayList ();
1550 modules = new ArrayList ();
1551 link_paths = new ArrayList ();
1553 SetupDefaultDefines ();
1558 // This is not required because Assembly.Load knows about this
1562 Hashtable response_file_list = null;
1564 for (i = 0; i < args.Length; i++){
1565 string arg = args [i];
1566 if (arg.Length == 0)
1569 if (arg.StartsWith ("@")){
1570 string [] extra_args;
1571 string response_file = arg.Substring (1);
1573 if (response_file_list == null)
1574 response_file_list = new Hashtable ();
1576 if (response_file_list.Contains (response_file)){
1578 1515, "Response file `" + response_file +
1579 "' specified multiple times");
1580 Environment.Exit (1);
1583 response_file_list.Add (response_file, response_file);
1585 extra_args = LoadArgs (response_file);
1586 if (extra_args == null){
1587 Report.Error (2011, "Unable to open response file: " +
1592 args = AddArgs (args, extra_args);
1596 if (parsing_options){
1598 parsing_options = false;
1602 if (arg.StartsWith ("-")){
1603 if (UnixParseOption (arg, ref args, ref i))
1607 string csc_opt = "/" + arg.Substring (1);
1608 if (CSCParseOption (csc_opt, ref args, ref i))
1611 Error_WrongOption (arg);
1614 if (arg [0] == '/'){
1615 if (CSCParseOption (arg, ref args, ref i))
1618 // Need to skip `/home/test.cs' however /test.cs is considered as error
1619 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1620 Error_WrongOption (arg);
1627 CompileFiles (arg, false);
1635 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1636 throw new InternalErrorException ("who set it?");
1639 // If we are an exe, require a source file for the entry point
1641 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1642 if (first_source == null){
1643 Report.Error (2008, "No files to compile were specified");
1650 // If there is nothing to put in the assembly, and we are not a library
1652 if (first_source == null && embedded_resources == null){
1653 Report.Error (2008, "No files to compile were specified");
1657 if (Report.Errors > 0)
1663 if (load_default_config)
1664 DefineDefaultConfig ();
1666 if (Report.Errors > 0){
1671 // Load assemblies required
1674 ShowTime ("Loading references");
1675 link_paths.Add (GetSystemDir ());
1676 link_paths.Add (Directory.GetCurrentDirectory ());
1680 ShowTime (" References loaded");
1682 if (Report.Errors > 0){
1689 if (output_file == null){
1690 if (first_source == null){
1691 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1695 int pos = first_source.LastIndexOf ('.');
1698 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1700 output_file = first_source + RootContext.TargetExt;
1703 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1706 if (RootContext.Target == Target.Module) {
1707 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1708 if (module_only == null) {
1709 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1710 Environment.Exit (1);
1713 MethodInfo set_method = module_only.GetSetMethod (true);
1714 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1717 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1719 if (modules.Count > 0) {
1720 foreach (string module in modules)
1721 LoadModule (module);
1725 // Before emitting, we need to get the core
1726 // types emitted from the user defined types
1727 // or from the system ones.
1730 ShowTime ("Initializing Core Types");
1731 if (!RootContext.StdLib){
1732 RootContext.ResolveCore ();
1733 if (Report.Errors > 0)
1737 TypeManager.InitCoreTypes ();
1739 ShowTime (" Core Types done");
1741 CodeGen.Module.Resolve ();
1744 // The second pass of the compiler
1747 ShowTime ("Resolving tree");
1748 RootContext.ResolveTree ();
1750 if (Report.Errors > 0)
1753 ShowTime ("Populate tree");
1754 if (!RootContext.StdLib)
1755 RootContext.BootCorlib_PopulateCoreTypes ();
1756 RootContext.PopulateTypes ();
1758 TypeManager.InitCodeHelpers ();
1760 RootContext.DefineTypes ();
1762 if (Report.Errors == 0 &&
1763 RootContext.Documentation != null &&
1764 !RootContext.Documentation.OutputDocComment (
1769 // Verify using aliases now
1771 NamespaceEntry.VerifyAllUsing ();
1773 if (Report.Errors > 0){
1777 CodeGen.Assembly.Resolve ();
1779 if (RootContext.VerifyClsCompliance) {
1780 if (CodeGen.Assembly.IsClsCompliant) {
1781 AttributeTester.VerifyModulesClsCompliance ();
1782 TypeManager.LoadAllImportedTypes ();
1785 if (Report.Errors > 0)
1789 // The code generator
1792 ShowTime ("Emitting code");
1793 ShowTotalTime ("Total so far");
1794 RootContext.EmitCode ();
1798 if (Report.Errors > 0){
1803 ShowTime ("Closing types");
1805 RootContext.CloseTypes ();
1807 PEFileKinds k = PEFileKinds.ConsoleApplication;
1809 switch (RootContext.Target) {
1810 case Target.Library:
1812 k = PEFileKinds.Dll; break;
1814 k = PEFileKinds.ConsoleApplication; break;
1816 k = PEFileKinds.WindowApplication; break;
1819 if (RootContext.NeedsEntryPoint) {
1820 MethodInfo ep = RootContext.EntryPoint;
1823 if (RootContext.MainClass != null) {
1824 DeclSpace main_cont = RootContext.ToplevelTypes.GetDefinition (RootContext.MainClass) as DeclSpace;
1825 if (main_cont == null) {
1826 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1830 if (!(main_cont is ClassOrStruct)) {
1831 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1835 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1839 if (Report.Errors == 0)
1840 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1845 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1846 } else if (RootContext.MainClass != null) {
1847 Report.Error (2017, "Cannot specify -main if building a module or library");
1850 if (embedded_resources != null){
1851 if (RootContext.Target == Target.Module) {
1852 Report.Error (1507, "Cannot link resource file when building a module");
1856 embedded_resources.Emit ();
1860 // Add Win32 resources
1863 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1865 if (win32ResourceFile != null) {
1867 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1869 catch (ArgumentException) {
1870 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1874 if (win32IconFile != null) {
1875 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1876 if (define_icon == null) {
1877 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1879 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1882 if (Report.Errors > 0)
1885 CodeGen.Save (output_file);
1887 ShowTime ("Saved output");
1888 ShowTotalTime ("Total");
1891 Timer.ShowTimers ();
1893 if (Report.ExpectedError != 0) {
1894 if (Report.Errors == 0) {
1895 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1896 "No other errors reported.");
1898 Environment.Exit (2);
1900 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1901 "However, other errors were reported.");
1903 Environment.Exit (1);
1911 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1912 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1914 return (Report.Errors == 0);
1923 string FileName { get; }
1926 class EmbededResource : IResource
1928 static MethodInfo embed_res;
1930 static EmbededResource () {
1931 Type[] argst = new Type [] {
1932 typeof (string), typeof (string), typeof (ResourceAttributes)
1935 embed_res = typeof (AssemblyBuilder).GetMethod (
1936 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1937 null, CallingConventions.Any, argst, null);
1939 if (embed_res == null) {
1940 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1944 readonly object[] args;
1946 public EmbededResource (string name, string file, bool isPrivate)
1948 args = new object [3];
1951 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1956 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1959 public string FileName {
1961 return (string)args [1];
1966 class LinkedResource : IResource
1968 readonly string file;
1969 readonly string name;
1970 readonly ResourceAttributes attribute;
1972 public LinkedResource (string name, string file, bool isPrivate)
1976 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1981 CodeGen.Assembly.Builder.AddResourceFile (name, Path.GetFileName(file), attribute);
1984 public string FileName {
1992 IDictionary embedded_resources = new HybridDictionary ();
1994 public void Add (bool embeded, string file, string name)
1996 Add (embeded, file, name, false);
1999 public void Add (bool embeded, string file, string name, bool isPrivate)
2001 if (embedded_resources.Contains (name)) {
2002 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
2005 IResource r = embeded ?
2006 (IResource) new EmbededResource (name, file, isPrivate) :
2007 new LinkedResource (name, file, isPrivate);
2009 embedded_resources.Add (name, r);
2014 foreach (IResource r in embedded_resources.Values) {
2015 if (!File.Exists (r.FileName)) {
2016 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
2026 // This is the only public entry point
2028 public class CompilerCallableEntryPoint : MarshalByRefObject {
2029 public static bool InvokeCompiler (string [] args, TextWriter error)
2031 Report.Stderr = error;
2033 return Driver.MainDriver (args) && Report.Errors == 0;
2036 Report.Stderr = Console.Error;
2041 public static int[] AllWarningNumbers {
2043 return Report.AllWarnings;
2047 static void Reset ()
2050 RootContext.Reset ();
2054 TypeManager.Reset ();
2055 TypeHandle.Reset ();
2056 RootNamespace.Reset ();
2057 NamespaceEntry.Reset ();
2060 AttributeTester.Reset ();