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;
19 using System.Diagnostics;
22 using System.Globalization;
26 Library, Exe, Module, WinExe
30 /// 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
61 static bool tokenize = false;
63 static string first_source;
65 static bool want_debugging_support = false;
67 static bool parse_only = false;
68 static bool timestamps = false;
69 static bool pause = false;
70 static bool show_counters = false;
73 // Whether to load the initial config file (what CSC.RSP has by default)
75 static bool load_default_config = true;
78 // A list of resource files
80 static Resources embedded_resources;
81 static string win32ResourceFile;
82 static string win32IconFile;
85 // An array of the defines from the command line
87 static ArrayList defines;
92 static string output_file = null;
95 // Last time we took the time
97 static DateTime last_time, first_time;
102 static Encoding encoding;
104 static public void Reset ()
106 want_debugging_support = false;
110 show_counters = false;
111 load_default_config = true;
112 embedded_resources = null;
113 win32ResourceFile = win32IconFile = null;
120 public static void ShowTime (string msg)
125 DateTime now = DateTime.Now;
126 TimeSpan span = now - last_time;
130 "[{0:00}:{1:000}] {2}",
131 (int) span.TotalSeconds, span.Milliseconds, msg);
134 public static void ShowTotalTime (string msg)
139 DateTime now = DateTime.Now;
140 TimeSpan span = now - first_time;
144 "[{0:00}:{1:000}] {2}",
145 (int) span.TotalSeconds, span.Milliseconds, msg);
148 static void tokenize_file (SourceFile file)
153 input = File.OpenRead (file.Name);
155 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
160 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
161 Tokenizer lexer = new Tokenizer (reader, file, defines);
162 int token, tokens = 0, errors = 0;
164 while ((token = lexer.token ()) != Token.EOF){
166 if (token == Token.ERROR)
169 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
175 // MonoTODO("Change error code for aborted compilation to something reasonable")]
176 static void parse (SourceFile file)
182 input = File.OpenRead (file.Name);
184 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
188 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
191 if (reader.Read () == 77 && reader.Read () == 90) {
192 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
198 parser = new CSharpParser (reader, file, defines);
199 parser.ErrorOutput = Report.Stderr;
202 } catch (Exception ex) {
203 Report.Error(666, "Compilation aborted: " + ex);
209 static void OtherFlags ()
212 "Other flags in the compiler\n" +
213 " --fatal Makes errors fatal\n" +
214 " --parse Only parses the source file\n" +
215 " --stacktrace Shows stack trace at error location\n" +
216 " --timestamp Displays time stamps of various compiler events\n" +
217 " --expect-error X Expect that error X will be encountered\n" +
218 " -2 Enables experimental C# features\n" +
219 " -v Verbose parsing (for debugging the parser)\n" +
220 " --mcs-debug X Sets MCS debugging level to X\n");
226 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
227 "mcs [options] source-files\n" +
228 " --about About the Mono C# compiler\n" +
229 " -addmodule:MODULE Adds the module to the generated assembly\n" +
230 " -checked[+|-] Set default context to checked\n" +
231 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
232 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
233 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
234 " -debug[+|-], -g Generate debugging information\n" +
235 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
236 " -doc:FILE XML Documentation file to generate\n" +
237 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
238 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
239 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
240 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
241 " -main:class Specified the class that contains the entry point\n" +
242 " -noconfig[+|-] Disables implicit references to assemblies\n" +
243 " -nostdlib[+|-] Does not load core libraries\n" +
244 " -nowarn:W1[,W2] Disables one or more warnings\n" +
245 " -optimize[+|-] Enables code optimalizations\n" +
246 " -out:FNAME Specifies output file\n" +
247 " -pkg:P1[,Pn] References packages P1..Pn\n" +
248 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
249 " -reference:ASS References the specified assembly (-r:ASS)\n" +
250 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
251 " library, module), (short: /t:)\n" +
252 " -unsafe[+|-] Allows unsafe code\n" +
253 " -warnaserror[+|-] Treat warnings as errors\n" +
254 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
255 " -help2 Show other help flags\n" +
258 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
259 " -resource:FILE[,ID] Embed FILE as a resource\n" +
260 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
261 " -win32icon:FILE Use this icon for the output\n" +
262 " @file Read response file for more options\n\n" +
263 "Options can be of the form -option or /option");
266 static void TargetUsage ()
268 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
274 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
275 "The compiler source code is released under the terms of the GNU GPL\n\n" +
277 "For more information on Mono, visit the project Web site\n" +
278 " http://www.go-mono.com\n\n" +
280 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
281 Environment.Exit (0);
284 public static int counter1, counter2;
286 public static int Main (string[] args)
288 RootContext.Version = LanguageVersion.Default;
289 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
291 bool ok = MainDriver (args);
293 if (ok && Report.Errors == 0) {
294 if (Report.Warnings > 0) {
295 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
298 Console.WriteLine ("Counter1: " + counter1);
299 Console.WriteLine ("Counter2: " + counter2);
305 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
306 Report.Errors, Report.Warnings);
311 static public void LoadAssembly (string assembly, bool soft)
313 LoadAssembly (assembly, null, soft);
316 static public void LoadAssembly (string assembly, string alias, bool soft)
319 string total_log = "";
322 char[] path_chars = { '/', '\\' };
324 if (assembly.IndexOfAny (path_chars) != -1) {
325 a = Assembly.LoadFrom (assembly);
327 string ass = assembly;
328 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
329 ass = assembly.Substring (0, assembly.Length - 4);
330 a = Assembly.Load (ass);
332 // Extern aliased refs require special handling
334 RootNamespace.Global.AddAssemblyReference (a);
336 RootNamespace.DefineRootNamespace (alias, a);
338 } catch (FileNotFoundException){
339 foreach (string dir in link_paths){
340 string full_path = Path.Combine (dir, assembly);
341 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
345 a = Assembly.LoadFrom (full_path);
347 RootNamespace.Global.AddAssemblyReference (a);
349 RootNamespace.DefineRootNamespace (alias, a);
351 } catch (FileNotFoundException ff) {
352 total_log += ff.FusionLog;
357 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
358 Console.WriteLine ("Log: \n" + total_log);
360 } catch (BadImageFormatException f) {
361 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
362 } catch (FileLoadException f){
363 Report.Error(6, "Cannot load assembly " + f.FusionLog);
364 } catch (ArgumentNullException){
365 Report.Error(6, "Cannot load assembly (null argument)");
369 static public void LoadModule (MethodInfo adder_method, string module)
372 string total_log = "";
376 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
378 catch (TargetInvocationException ex) {
379 throw ex.InnerException;
381 RootNamespace.Global.AddModuleReference (m);
384 catch (FileNotFoundException){
385 foreach (string dir in link_paths){
386 string full_path = Path.Combine (dir, module);
387 if (!module.EndsWith (".netmodule"))
388 full_path += ".netmodule";
392 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
394 catch (TargetInvocationException ex) {
395 throw ex.InnerException;
397 RootNamespace.Global.AddModuleReference (m);
399 } catch (FileNotFoundException ff) {
400 total_log += ff.FusionLog;
404 Report.Error (6, "Cannot find module `" + module + "'" );
405 Console.WriteLine ("Log: \n" + total_log);
406 } catch (BadImageFormatException f) {
407 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
408 } catch (FileLoadException f){
409 Report.Error(6, "Cannot load module " + f.FusionLog);
410 } catch (ArgumentNullException){
411 Report.Error(6, "Cannot load module (null argument)");
416 /// Loads all assemblies referenced on the command line
418 static public void LoadReferences ()
420 foreach (string r in references)
421 LoadAssembly (r, false);
423 foreach (string r in soft_references)
424 LoadAssembly (r, true);
426 foreach (DictionaryEntry entry in external_aliases)
427 LoadAssembly ((string) entry.Value, (string) entry.Key, false);
432 static void SetupDefaultDefines ()
434 defines = new ArrayList ();
435 defines.Add ("__MonoCS__");
438 static string [] LoadArgs (string file)
441 ArrayList args = new ArrayList ();
444 f = new StreamReader (file);
449 StringBuilder sb = new StringBuilder ();
451 while ((line = f.ReadLine ()) != null){
454 for (int i = 0; i < t; i++){
457 if (c == '"' || c == '\''){
460 for (i++; i < t; i++){
467 } else if (c == ' '){
469 args.Add (sb.ToString ());
476 args.Add (sb.ToString ());
481 string [] ret_value = new string [args.Count];
482 args.CopyTo (ret_value, 0);
488 // Returns the directory where the system assemblies are installed
490 static string GetSystemDir ()
492 return Path.GetDirectoryName (typeof (object).Assembly.Location);
496 // Given a path specification, splits the path from the file/pattern
498 static void SplitPathAndPattern (string spec, out string path, out string pattern)
500 int p = spec.LastIndexOf ('/');
503 // Windows does not like /file.cs, switch that to:
508 pattern = spec.Substring (1);
510 path = spec.Substring (0, p);
511 pattern = spec.Substring (p + 1);
516 p = spec.LastIndexOf ('\\');
518 path = spec.Substring (0, p);
519 pattern = spec.Substring (p + 1);
527 static void ProcessFile (string f)
529 if (first_source == null)
532 Location.AddFile (f);
535 static void ProcessFiles ()
537 Location.Initialize ();
539 foreach (SourceFile file in Location.SourceFiles) {
541 tokenize_file (file);
548 static void CompileFiles (string spec, bool recurse)
550 string path, pattern;
552 SplitPathAndPattern (spec, out path, out pattern);
553 if (pattern.IndexOf ('*') == -1){
558 string [] files = null;
560 files = Directory.GetFiles (path, pattern);
561 } catch (System.IO.DirectoryNotFoundException) {
562 Report.Error (2001, "Source file `" + spec + "' could not be found");
564 } catch (System.IO.IOException){
565 Report.Error (2001, "Source file `" + spec + "' could not be found");
568 foreach (string f in files) {
575 string [] dirs = null;
578 dirs = Directory.GetDirectories (path);
582 foreach (string d in dirs) {
584 // Don't include path in this string, as each
585 // directory entry already does
586 CompileFiles (d + "/" + pattern, true);
590 static void DefineDefaultConfig ()
593 // For now the "default config" is harcoded into the compiler
594 // we can move this outside later
596 string [] default_config = {
601 // Is it worth pre-loading all this stuff?
604 "System.Configuration.Install",
607 "System.DirectoryServices",
608 "System.Drawing.Design",
610 "System.EnterpriseServices",
613 "System.Runtime.Remoting",
614 "System.Runtime.Serialization.Formatters.Soap",
616 "System.ServiceProcess",
618 "System.Web.RegularExpressions",
619 "System.Web.Services",
620 "System.Windows.Forms"
625 foreach (string def in default_config)
626 soft_references.Insert (p++, def);
629 public static string OutputFile
635 return Path.GetFileName (output_file);
639 static void SetWarningLevel (string s)
644 level = Int32.Parse (s);
647 if (level < 0 || level > 4){
648 Report.Error (1900, "Warning level must be in the range 0-4");
651 RootContext.WarningLevel = level;
654 static void SetupV2 ()
656 RootContext.Version = LanguageVersion.Default;
657 defines.Add ("__V2__");
660 static void Version ()
662 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
663 Console.WriteLine ("Mono C# compiler version {0}", version);
664 Environment.Exit (0);
668 // Currently handles the Unix-like command line options, but will be
669 // deprecated in favor of the CSCParseOption, which will also handle the
670 // options that start with a dash in the future.
672 static bool UnixParseOption (string arg, ref string [] args, ref int i)
676 CSharpParser.yacc_verbose_flag++;
687 case "--main": case "-m":
688 Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
689 if ((i + 1) >= args.Length){
691 Environment.Exit (1);
693 RootContext.MainClass = args [++i];
697 Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
698 RootContext.Unsafe = true;
701 case "/?": case "/h": case "/help":
704 Environment.Exit (0);
708 Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
709 if ((i + 1) >= args.Length){
711 Environment.Exit (1);
713 defines.Add (args [++i]);
716 case "--show-counters":
717 show_counters = true;
720 case "--expect-error": {
725 args [++i], NumberStyles.AllowLeadingSign);
726 Report.ExpectedError = code;
728 Report.Error (-14, "Invalid number specified");
739 Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
740 if ((i + 1) >= args.Length){
742 Environment.Exit (1);
744 OutputFile = args [++i];
748 Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
749 RootContext.Checked = true;
753 Report.Stacktrace = true;
756 case "--linkresource":
758 Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
759 if ((i + 1) >= args.Length){
761 Report.Error (5, "Missing argument to --linkres");
762 Environment.Exit (1);
764 if (embedded_resources == null)
765 embedded_resources = new Resources ();
767 embedded_resources.Add (false, args [++i], args [i]);
772 Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
773 if ((i + 1) >= args.Length){
775 Report.Error (5, "Missing argument to --resource");
776 Environment.Exit (1);
778 if (embedded_resources == null)
779 embedded_resources = new Resources ();
781 embedded_resources.Add (true, args [++i], args [i]);
785 Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
786 if ((i + 1) >= args.Length){
787 Environment.Exit (1);
791 string type = args [++i];
794 RootContext.Target = Target.Library;
795 RootContext.TargetExt = ".dll";
799 RootContext.Target = Target.Exe;
803 RootContext.Target = Target.WinExe;
807 RootContext.Target = Target.Module;
808 RootContext.TargetExt = ".dll";
817 Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
818 if ((i + 1) >= args.Length){
820 Environment.Exit (1);
823 string val = args [++i];
824 int idx = val.IndexOf ('=');
826 string alias = val.Substring (0, idx);
827 string assembly = val.Substring (idx + 1);
828 AddExternAlias (alias, assembly);
832 references.Add (val);
836 Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
837 if ((i + 1) >= args.Length){
839 Environment.Exit (1);
841 link_paths.Add (args [++i]);
845 Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
846 RootContext.StdLib = false;
854 Report.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
855 Report.WarningsAreErrors = true;
859 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
860 if ((i + 1) >= args.Length){
862 Environment.Exit (1);
867 warn = Int32.Parse (args [++i]);
870 Environment.Exit (1);
872 Report.SetIgnoreWarning (warn);
876 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
877 if ((i + 1) >= args.Length){
880 "--wlevel requires a value from 0 to 4");
881 Environment.Exit (1);
884 SetWarningLevel (args [++i]);
888 if ((i + 1) >= args.Length){
889 Report.Error (5, "--mcs-debug requires an argument");
890 Environment.Exit (1);
894 Report.DebugFlags = Int32.Parse (args [++i]);
896 Report.Error (5, "Invalid argument to --mcs-debug");
897 Environment.Exit (1);
906 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
907 if ((i + 1) >= args.Length){
908 Report.Error (5, "--recurse requires an argument");
909 Environment.Exit (1);
911 CompileFiles (args [++i], true);
916 last_time = first_time = DateTime.Now;
923 case "--debug": case "-g":
924 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
925 want_debugging_support = true;
929 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
930 load_default_config = false;
938 // This parses the -arg and /arg options to the compiler, even if the strings
939 // in the following text use "/arg" on the strings.
941 static bool CSCParseOption (string option, ref string [] args, ref int i)
943 int idx = option.IndexOf (':');
950 arg = option.Substring (0, idx);
952 value = option.Substring (idx + 1);
963 RootContext.Target = Target.Exe;
967 RootContext.Target = Target.WinExe;
971 RootContext.Target = Target.Library;
972 RootContext.TargetExt = ".dll";
976 RootContext.Target = Target.Module;
977 RootContext.TargetExt = ".netmodule";
989 Environment.Exit (1);
996 RootContext.Optimize = true;
1000 RootContext.Optimize = false;
1003 case "/incremental":
1004 case "/incremental+":
1005 case "/incremental-":
1015 Environment.Exit (1);
1018 defs = value.Split (new Char [] {';', ','});
1019 foreach (string d in defs){
1027 // We should collect data, runtime, etc and store in the file specified
1029 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1037 Environment.Exit (1);
1039 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1041 ProcessStartInfo pi = new ProcessStartInfo ();
1042 pi.FileName = "pkg-config";
1043 pi.RedirectStandardOutput = true;
1044 pi.UseShellExecute = false;
1045 pi.Arguments = "--libs " + packages;
1048 p = Process.Start (pi);
1049 } catch (Exception e) {
1050 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1051 Environment.Exit (1);
1054 if (p.StandardOutput == null){
1055 Report.Warning (-27, 1, "Specified package did not return any information");
1058 string pkgout = p.StandardOutput.ReadToEnd ();
1060 if (p.ExitCode != 0) {
1061 Report.Error (-27, "Error running pkg-config. Check the above output.");
1062 Environment.Exit (1);
1065 if (pkgout != null){
1066 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1067 Split (new Char [] { ' ', '\t'});
1068 args = AddArgs (args, xargs);
1076 case "/linkresource":
1079 if (embedded_resources == null)
1080 embedded_resources = new Resources ();
1082 bool embeded = arg.StartsWith ("/r");
1083 string[] s = value.Split (',');
1086 if (s[0].Length == 0)
1088 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1091 embedded_resources.Add (embeded, s [0], s [1]);
1094 if (s [2] != "public" && s [2] != "private") {
1095 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1098 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1101 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1109 Report.Error (5, "-recurse requires an argument");
1110 Environment.Exit (1);
1112 CompileFiles (value, true);
1116 case "/reference": {
1118 Report.Error (5, "-reference requires an argument");
1119 Environment.Exit (1);
1122 string [] refs = value.Split (new char [] { ';', ',' });
1123 foreach (string r in refs){
1125 int index = val.IndexOf ("=");
1127 string alias = r.Substring (0, index);
1128 string assembly = r.Substring (index + 1);
1129 AddExternAlias (alias, assembly);
1133 references.Add (val);
1137 case "/addmodule": {
1139 Report.Error (5, arg + " requires an argument");
1140 Environment.Exit (1);
1143 string [] refs = value.Split (new char [] { ';', ',' });
1144 foreach (string r in refs){
1151 Report.Error (5, arg + " requires an argument");
1152 Environment.Exit (1);
1155 win32ResourceFile = value;
1158 case "/win32icon": {
1160 Report.Error (5, arg + " requires an argument");
1161 Environment.Exit (1);
1164 win32IconFile = value;
1169 Report.Error (2006, arg + " requires an argument");
1170 Environment.Exit (1);
1172 RootContext.Documentation = new Documentation (value);
1179 Report.Error (5, "/lib requires an argument");
1180 Environment.Exit (1);
1183 libdirs = value.Split (new Char [] { ',' });
1184 foreach (string dir in libdirs)
1185 link_paths.Add (dir);
1190 want_debugging_support = false;
1195 want_debugging_support = true;
1200 RootContext.Checked = true;
1204 RootContext.Checked = false;
1212 RootContext.VerifyClsCompliance = false;
1217 RootContext.Unsafe = true;
1221 RootContext.Unsafe = false;
1224 case "/warnaserror":
1225 case "/warnaserror+":
1226 Report.WarningsAreErrors = true;
1229 case "/warnaserror-":
1230 Report.WarningsAreErrors = false;
1234 SetWarningLevel (value);
1241 Report.Error (5, "/nowarn requires an argument");
1242 Environment.Exit (1);
1245 warns = value.Split (new Char [] {','});
1246 foreach (string wc in warns){
1248 int warn = Int32.Parse (wc);
1250 throw new ArgumentOutOfRangeException("warn");
1252 Report.SetIgnoreWarning (warn);
1254 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1261 load_default_config = true;
1266 load_default_config = false;
1271 Environment.Exit(0);
1277 Environment.Exit (0);
1283 Report.Error (5, arg + " requires an argument");
1284 Environment.Exit (1);
1286 RootContext.MainClass = value;
1291 RootContext.StdLib = false;
1295 RootContext.StdLib = true;
1302 if (value == String.Empty) {
1303 Report.Error (5, arg + " requires an argument");
1304 Environment.Exit (1);
1306 RootContext.StrongNameKeyFile = value;
1308 case "/keycontainer":
1309 if (value == String.Empty) {
1310 Report.Error (5, arg + " requires an argument");
1311 Environment.Exit (1);
1313 RootContext.StrongNameKeyContainer = value;
1316 RootContext.StrongNameDelaySign = true;
1319 RootContext.StrongNameDelaySign = false;
1324 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1328 case "/langversion":
1329 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1331 RootContext.Version = LanguageVersion.ISO_1;
1338 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1344 encoding = new UTF8Encoding();
1347 encoding = Encoding.Default;
1351 encoding = Encoding.GetEncoding (
1352 Int32.Parse (value));
1354 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1364 static void Error_WrongOption (string option)
1366 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1369 static string [] AddArgs (string [] args, string [] extra_args)
1372 new_args = new string [extra_args.Length + args.Length];
1374 // if args contains '--' we have to take that into account
1375 // split args into first half and second half based on '--'
1376 // and add the extra_args before --
1377 int split_position = Array.IndexOf (args, "--");
1378 if (split_position != -1)
1380 Array.Copy (args, new_args, split_position);
1381 extra_args.CopyTo (new_args, split_position);
1382 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1386 args.CopyTo (new_args, 0);
1387 extra_args.CopyTo (new_args, args.Length);
1393 static void AddExternAlias (string identifier, string assembly)
1395 if (assembly.Length == 0) {
1396 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1400 if (!IsExternAliasValid (identifier)) {
1401 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1405 // Could here hashtable throw an exception?
1406 external_aliases [identifier] = assembly;
1409 static bool IsExternAliasValid (string identifier)
1411 if (identifier.Length == 0)
1413 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1416 for (int i = 1; i < identifier.Length; i++) {
1417 char c = identifier [i];
1418 if (Char.IsLetter (c) || Char.IsDigit (c))
1421 UnicodeCategory category = Char.GetUnicodeCategory (c);
1422 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1423 category != UnicodeCategory.SpacingCombiningMark ||
1424 category != UnicodeCategory.ConnectorPunctuation)
1432 /// Parses the arguments, and drives the compilation
1437 /// TODO: Mostly structured to debug the compiler
1438 /// now, needs to be turned into a real driver soon.
1440 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1441 internal static bool MainDriver (string [] args)
1444 bool parsing_options = true;
1446 encoding = Encoding.Default;
1448 references = new ArrayList ();
1449 external_aliases = new Hashtable ();
1450 soft_references = new ArrayList ();
1451 modules = new ArrayList ();
1452 link_paths = new ArrayList ();
1454 SetupDefaultDefines ();
1459 // This is not required because Assembly.Load knows about this
1463 Hashtable response_file_list = null;
1465 for (i = 0; i < args.Length; i++){
1466 string arg = args [i];
1470 if (arg.StartsWith ("@")){
1471 string [] extra_args;
1472 string response_file = arg.Substring (1);
1474 if (response_file_list == null)
1475 response_file_list = new Hashtable ();
1477 if (response_file_list.Contains (response_file)){
1479 1515, "Response file `" + response_file +
1480 "' specified multiple times");
1481 Environment.Exit (1);
1484 response_file_list.Add (response_file, response_file);
1486 extra_args = LoadArgs (response_file);
1487 if (extra_args == null){
1488 Report.Error (2011, "Unable to open response file: " +
1493 args = AddArgs (args, extra_args);
1497 if (parsing_options){
1499 parsing_options = false;
1503 if (arg.StartsWith ("-")){
1504 if (UnixParseOption (arg, ref args, ref i))
1508 string csc_opt = "/" + arg.Substring (1);
1509 if (CSCParseOption (csc_opt, ref args, ref i))
1512 Error_WrongOption (arg);
1515 if (arg [0] == '/'){
1516 if (CSCParseOption (arg, ref args, ref i))
1519 // Need to skip `/home/test.cs' however /test.cs is considered as error
1520 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1521 Error_WrongOption (arg);
1528 CompileFiles (arg, false);
1537 // This will point to the NamespaceEntry of the last file that was parsed, and may
1538 // not be meaningful when resolving classes from other files. So, reset it to prevent
1541 RootContext.Tree.Types.NamespaceEntry = null;
1544 // If we are an exe, require a source file for the entry point
1546 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1547 if (first_source == null){
1548 Report.Error (2008, "No files to compile were specified");
1555 // If there is nothing to put in the assembly, and we are not a library
1557 if (first_source == null && embedded_resources == null){
1558 Report.Error (2008, "No files to compile were specified");
1562 if (Report.Errors > 0)
1569 // Load Core Library for default compilation
1571 if (RootContext.StdLib)
1572 references.Insert (0, "mscorlib");
1574 if (load_default_config)
1575 DefineDefaultConfig ();
1577 if (Report.Errors > 0){
1582 // Load assemblies required
1585 ShowTime ("Loading references");
1586 link_paths.Add (GetSystemDir ());
1587 link_paths.Add (Directory.GetCurrentDirectory ());
1591 ShowTime (" References loaded");
1593 if (Report.Errors > 0){
1600 if (output_file == null){
1601 int pos = first_source.LastIndexOf ('.');
1604 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1606 output_file = first_source + RootContext.TargetExt;
1609 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1612 if (RootContext.Target == Target.Module) {
1613 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1614 if (module_only == null) {
1615 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1616 Environment.Exit (1);
1619 MethodInfo set_method = module_only.GetSetMethod (true);
1620 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1623 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1625 if (modules.Count > 0) {
1626 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1627 if (adder_method == null) {
1628 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1629 Environment.Exit (1);
1632 foreach (string module in modules)
1633 LoadModule (adder_method, module);
1637 // Before emitting, we need to get the core
1638 // types emitted from the user defined types
1639 // or from the system ones.
1642 ShowTime ("Initializing Core Types");
1643 if (!RootContext.StdLib){
1644 RootContext.ResolveCore ();
1645 if (Report.Errors > 0)
1649 TypeManager.InitCoreTypes ();
1651 ShowTime (" Core Types done");
1653 CodeGen.Module.ResolveAttributes ();
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 TypeManager.InitCodeHelpers ();
1672 RootContext.DefineTypes ();
1674 if (RootContext.Documentation != null &&
1675 !RootContext.Documentation.OutputDocComment (
1680 // Verify using aliases now
1682 NamespaceEntry.VerifyAllUsing ();
1684 if (Report.Errors > 0){
1688 CodeGen.Assembly.Resolve ();
1690 if (RootContext.VerifyClsCompliance) {
1691 if (CodeGen.Assembly.IsClsCompliant) {
1692 AttributeTester.VerifyModulesClsCompliance ();
1693 TypeManager.LoadAllImportedTypes ();
1696 if (Report.Errors > 0)
1700 // The code generator
1703 ShowTime ("Emitting code");
1704 ShowTotalTime ("Total so far");
1705 RootContext.EmitCode ();
1709 if (Report.Errors > 0){
1714 ShowTime ("Closing types");
1716 RootContext.CloseTypes ();
1718 PEFileKinds k = PEFileKinds.ConsoleApplication;
1720 switch (RootContext.Target) {
1721 case Target.Library:
1723 k = PEFileKinds.Dll; break;
1725 k = PEFileKinds.ConsoleApplication; break;
1727 k = PEFileKinds.WindowApplication; break;
1730 if (RootContext.NeedsEntryPoint) {
1731 MethodInfo ep = RootContext.EntryPoint;
1734 if (RootContext.MainClass != null) {
1735 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass, Location.Null));
1736 if (main_cont == null) {
1737 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1741 if (!(main_cont is ClassOrStruct)) {
1742 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1746 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1750 if (Report.Errors == 0)
1751 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1756 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1757 } else if (RootContext.MainClass != null) {
1758 Report.Error (2017, "Cannot specify -main if building a module or library");
1761 if (embedded_resources != null){
1762 if (RootContext.Target == Target.Module) {
1763 Report.Error (1507, "Cannot link resource file when building a module");
1767 embedded_resources.Emit ();
1771 // Add Win32 resources
1774 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1776 if (win32ResourceFile != null) {
1778 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1780 catch (ArgumentException) {
1781 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1785 if (win32IconFile != null) {
1786 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1787 if (define_icon == null) {
1788 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1790 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1793 if (Report.Errors > 0)
1796 CodeGen.Save (output_file);
1798 ShowTime ("Saved output");
1799 ShowTotalTime ("Total");
1802 Timer.ShowTimers ();
1804 if (Report.ExpectedError != 0){
1805 if (Report.Errors == 0) {
1806 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1807 "No other errors reported.");
1809 Environment.Exit (2);
1811 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1812 "However, other errors were reported.");
1814 Environment.Exit (1);
1822 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1823 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1825 return (Report.Errors == 0);
1834 string FileName { get; }
1837 class EmbededResource : IResource
1839 static MethodInfo embed_res;
1841 static EmbededResource () {
1842 Type[] argst = new Type [] {
1843 typeof (string), typeof (string), typeof (ResourceAttributes)
1846 embed_res = typeof (AssemblyBuilder).GetMethod (
1847 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1848 null, CallingConventions.Any, argst, null);
1850 if (embed_res == null) {
1851 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1855 readonly object[] args;
1857 public EmbededResource (string name, string file, bool isPrivate)
1859 args = new object [3];
1862 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1867 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1870 public string FileName {
1872 return (string)args [1];
1877 class LinkedResource : IResource
1879 readonly string file;
1880 readonly string name;
1881 readonly ResourceAttributes attribute;
1883 public LinkedResource (string name, string file, bool isPrivate)
1887 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1892 CodeGen.Assembly.Builder.AddResourceFile (name, file, attribute);
1895 public string FileName {
1903 IDictionary embedded_resources = new HybridDictionary ();
1905 public void Add (bool embeded, string file, string name)
1907 Add (embeded, file, name, false);
1910 public void Add (bool embeded, string file, string name, bool isPrivate)
1912 if (embedded_resources.Contains (name)) {
1913 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1916 IResource r = embeded ?
1917 (IResource) new EmbededResource (name, file, isPrivate) :
1918 new LinkedResource (name, file, isPrivate);
1920 embedded_resources.Add (name, r);
1925 foreach (IResource r in embedded_resources.Values) {
1926 if (!File.Exists (r.FileName)) {
1927 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1937 // This is the only public entry point
1939 public class CompilerCallableEntryPoint : MarshalByRefObject {
1940 public static bool InvokeCompiler (string [] args, TextWriter error)
1942 Report.Stderr = error;
1944 return Driver.MainDriver (args) && Report.Errors == 0;
1947 Report.Stderr = Console.Error;
1952 public static int[] AllWarningNumbers {
1954 return Report.AllWarnings;
1958 static void Reset ()
1962 RootContext.Reset ();
1964 TypeManager.Reset ();
1965 TypeHandle.Reset ();
1966 RootNamespace.Reset ();
1967 NamespaceEntry.Reset ();