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;
858 case "--broken-cycles":
859 RootContext.BrokenCircularDeps = true;
863 Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
864 if ((i + 1) >= args.Length){
866 Environment.Exit (1);
871 warn = Int32.Parse (args [++i]);
874 Environment.Exit (1);
876 Report.SetIgnoreWarning (warn);
880 Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
881 if ((i + 1) >= args.Length){
884 "--wlevel requires a value from 0 to 4");
885 Environment.Exit (1);
888 SetWarningLevel (args [++i]);
892 if ((i + 1) >= args.Length){
893 Report.Error (5, "--mcs-debug requires an argument");
894 Environment.Exit (1);
898 Report.DebugFlags = Int32.Parse (args [++i]);
900 Report.Error (5, "Invalid argument to --mcs-debug");
901 Environment.Exit (1);
910 Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
911 if ((i + 1) >= args.Length){
912 Report.Error (5, "--recurse requires an argument");
913 Environment.Exit (1);
915 CompileFiles (args [++i], true);
920 last_time = first_time = DateTime.Now;
927 case "--debug": case "-g":
928 Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
929 want_debugging_support = true;
933 Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
934 load_default_config = false;
942 // This parses the -arg and /arg options to the compiler, even if the strings
943 // in the following text use "/arg" on the strings.
945 static bool CSCParseOption (string option, ref string [] args, ref int i)
947 int idx = option.IndexOf (':');
954 arg = option.Substring (0, idx);
956 value = option.Substring (idx + 1);
967 RootContext.Target = Target.Exe;
971 RootContext.Target = Target.WinExe;
975 RootContext.Target = Target.Library;
976 RootContext.TargetExt = ".dll";
980 RootContext.Target = Target.Module;
981 RootContext.TargetExt = ".netmodule";
993 Environment.Exit (1);
1000 RootContext.Optimize = true;
1004 RootContext.Optimize = false;
1007 case "/incremental":
1008 case "/incremental+":
1009 case "/incremental-":
1019 Environment.Exit (1);
1022 defs = value.Split (new Char [] {';', ','});
1023 foreach (string d in defs){
1031 // We should collect data, runtime, etc and store in the file specified
1033 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1041 Environment.Exit (1);
1043 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1045 ProcessStartInfo pi = new ProcessStartInfo ();
1046 pi.FileName = "pkg-config";
1047 pi.RedirectStandardOutput = true;
1048 pi.UseShellExecute = false;
1049 pi.Arguments = "--libs " + packages;
1052 p = Process.Start (pi);
1053 } catch (Exception e) {
1054 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1055 Environment.Exit (1);
1058 if (p.StandardOutput == null){
1059 Report.Warning (-27, 1, "Specified package did not return any information");
1062 string pkgout = p.StandardOutput.ReadToEnd ();
1064 if (p.ExitCode != 0) {
1065 Report.Error (-27, "Error running pkg-config. Check the above output.");
1066 Environment.Exit (1);
1069 if (pkgout != null){
1070 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1071 Split (new Char [] { ' ', '\t'});
1072 args = AddArgs (args, xargs);
1080 case "/linkresource":
1083 if (embedded_resources == null)
1084 embedded_resources = new Resources ();
1086 bool embeded = arg.StartsWith ("/r");
1087 string[] s = value.Split (',');
1090 if (s[0].Length == 0)
1092 embedded_resources.Add (embeded, s [0], Path.GetFileName (s[0]));
1095 embedded_resources.Add (embeded, s [0], s [1]);
1098 if (s [2] != "public" && s [2] != "private") {
1099 Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
1102 embedded_resources.Add (embeded, s [0], s [1], s [2] == "private");
1105 Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
1113 Report.Error (5, "-recurse requires an argument");
1114 Environment.Exit (1);
1116 CompileFiles (value, true);
1120 case "/reference": {
1122 Report.Error (5, "-reference requires an argument");
1123 Environment.Exit (1);
1126 string [] refs = value.Split (new char [] { ';', ',' });
1127 foreach (string r in refs){
1129 int index = val.IndexOf ("=");
1131 string alias = r.Substring (0, index);
1132 string assembly = r.Substring (index + 1);
1133 AddExternAlias (alias, assembly);
1137 references.Add (val);
1141 case "/addmodule": {
1143 Report.Error (5, arg + " requires an argument");
1144 Environment.Exit (1);
1147 string [] refs = value.Split (new char [] { ';', ',' });
1148 foreach (string r in refs){
1155 Report.Error (5, arg + " requires an argument");
1156 Environment.Exit (1);
1159 win32ResourceFile = value;
1162 case "/win32icon": {
1164 Report.Error (5, arg + " requires an argument");
1165 Environment.Exit (1);
1168 win32IconFile = value;
1173 Report.Error (2006, arg + " requires an argument");
1174 Environment.Exit (1);
1176 RootContext.Documentation = new Documentation (value);
1183 Report.Error (5, "/lib requires an argument");
1184 Environment.Exit (1);
1187 libdirs = value.Split (new Char [] { ',' });
1188 foreach (string dir in libdirs)
1189 link_paths.Add (dir);
1194 want_debugging_support = false;
1199 want_debugging_support = true;
1204 RootContext.Checked = true;
1208 RootContext.Checked = false;
1216 RootContext.VerifyClsCompliance = false;
1221 RootContext.Unsafe = true;
1225 RootContext.Unsafe = false;
1228 case "/warnaserror":
1229 case "/warnaserror+":
1230 Report.WarningsAreErrors = true;
1233 case "/warnaserror-":
1234 Report.WarningsAreErrors = false;
1238 SetWarningLevel (value);
1245 Report.Error (5, "/nowarn requires an argument");
1246 Environment.Exit (1);
1249 warns = value.Split (new Char [] {','});
1250 foreach (string wc in warns){
1252 int warn = Int32.Parse (wc);
1254 throw new ArgumentOutOfRangeException("warn");
1256 Report.SetIgnoreWarning (warn);
1258 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1265 load_default_config = true;
1270 load_default_config = false;
1275 Environment.Exit(0);
1281 Environment.Exit (0);
1287 Report.Error (5, arg + " requires an argument");
1288 Environment.Exit (1);
1290 RootContext.MainClass = value;
1295 RootContext.StdLib = false;
1299 RootContext.StdLib = true;
1306 if (value == String.Empty) {
1307 Report.Error (5, arg + " requires an argument");
1308 Environment.Exit (1);
1310 RootContext.StrongNameKeyFile = value;
1312 case "/keycontainer":
1313 if (value == String.Empty) {
1314 Report.Error (5, arg + " requires an argument");
1315 Environment.Exit (1);
1317 RootContext.StrongNameKeyContainer = value;
1320 RootContext.StrongNameDelaySign = true;
1323 RootContext.StrongNameDelaySign = false;
1328 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1332 case "/langversion":
1333 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1335 RootContext.Version = LanguageVersion.ISO_1;
1342 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1348 encoding = new UTF8Encoding();
1351 encoding = Encoding.Default;
1355 encoding = Encoding.GetEncoding (
1356 Int32.Parse (value));
1358 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1368 static void Error_WrongOption (string option)
1370 Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
1373 static string [] AddArgs (string [] args, string [] extra_args)
1376 new_args = new string [extra_args.Length + args.Length];
1378 // if args contains '--' we have to take that into account
1379 // split args into first half and second half based on '--'
1380 // and add the extra_args before --
1381 int split_position = Array.IndexOf (args, "--");
1382 if (split_position != -1)
1384 Array.Copy (args, new_args, split_position);
1385 extra_args.CopyTo (new_args, split_position);
1386 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1390 args.CopyTo (new_args, 0);
1391 extra_args.CopyTo (new_args, args.Length);
1397 static void AddExternAlias (string identifier, string assembly)
1399 if (assembly.Length == 0) {
1400 Report.Error (1680, "Invalid reference alias '" + identifier + "='. Missing filename");
1404 if (!IsExternAliasValid (identifier)) {
1405 Report.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier + "' is not a valid identifier");
1409 // Could here hashtable throw an exception?
1410 external_aliases [identifier] = assembly;
1413 static bool IsExternAliasValid (string identifier)
1415 if (identifier.Length == 0)
1417 if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
1420 for (int i = 1; i < identifier.Length; i++) {
1421 char c = identifier [i];
1422 if (Char.IsLetter (c) || Char.IsDigit (c))
1425 UnicodeCategory category = Char.GetUnicodeCategory (c);
1426 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
1427 category != UnicodeCategory.SpacingCombiningMark ||
1428 category != UnicodeCategory.ConnectorPunctuation)
1436 /// Parses the arguments, and drives the compilation
1441 /// TODO: Mostly structured to debug the compiler
1442 /// now, needs to be turned into a real driver soon.
1444 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1445 internal static bool MainDriver (string [] args)
1448 bool parsing_options = true;
1450 encoding = Encoding.Default;
1452 references = new ArrayList ();
1453 external_aliases = new Hashtable ();
1454 soft_references = new ArrayList ();
1455 modules = new ArrayList ();
1456 link_paths = new ArrayList ();
1458 SetupDefaultDefines ();
1463 // This is not required because Assembly.Load knows about this
1467 Hashtable response_file_list = null;
1469 for (i = 0; i < args.Length; i++){
1470 string arg = args [i];
1474 if (arg.StartsWith ("@")){
1475 string [] extra_args;
1476 string response_file = arg.Substring (1);
1478 if (response_file_list == null)
1479 response_file_list = new Hashtable ();
1481 if (response_file_list.Contains (response_file)){
1483 1515, "Response file `" + response_file +
1484 "' specified multiple times");
1485 Environment.Exit (1);
1488 response_file_list.Add (response_file, response_file);
1490 extra_args = LoadArgs (response_file);
1491 if (extra_args == null){
1492 Report.Error (2011, "Unable to open response file: " +
1497 args = AddArgs (args, extra_args);
1501 if (parsing_options){
1503 parsing_options = false;
1507 if (arg.StartsWith ("-")){
1508 if (UnixParseOption (arg, ref args, ref i))
1512 string csc_opt = "/" + arg.Substring (1);
1513 if (CSCParseOption (csc_opt, ref args, ref i))
1516 Error_WrongOption (arg);
1519 if (arg [0] == '/'){
1520 if (CSCParseOption (arg, ref args, ref i))
1523 // Need to skip `/home/test.cs' however /test.cs is considered as error
1524 if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
1525 Error_WrongOption (arg);
1532 CompileFiles (arg, false);
1541 // This will point to the NamespaceEntry of the last file that was parsed, and may
1542 // not be meaningful when resolving classes from other files. So, reset it to prevent
1545 RootContext.Tree.Types.NamespaceEntry = null;
1548 // If we are an exe, require a source file for the entry point
1550 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module){
1551 if (first_source == null){
1552 Report.Error (2008, "No files to compile were specified");
1559 // If there is nothing to put in the assembly, and we are not a library
1561 if (first_source == null && embedded_resources == null){
1562 Report.Error (2008, "No files to compile were specified");
1566 if (Report.Errors > 0)
1573 // Load Core Library for default compilation
1575 if (RootContext.StdLib)
1576 references.Insert (0, "mscorlib");
1578 if (load_default_config)
1579 DefineDefaultConfig ();
1581 if (Report.Errors > 0){
1586 // Load assemblies required
1589 ShowTime ("Loading references");
1590 link_paths.Add (GetSystemDir ());
1591 link_paths.Add (Directory.GetCurrentDirectory ());
1595 ShowTime (" References loaded");
1597 if (Report.Errors > 0){
1604 if (output_file == null){
1605 if (first_source == null){
1606 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
1610 int pos = first_source.LastIndexOf ('.');
1613 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1615 output_file = first_source + RootContext.TargetExt;
1618 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1621 if (RootContext.Target == Target.Module) {
1622 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1623 if (module_only == null) {
1624 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1625 Environment.Exit (1);
1628 MethodInfo set_method = module_only.GetSetMethod (true);
1629 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1632 RootNamespace.Global.AddModuleReference (CodeGen.Module.Builder);
1634 if (modules.Count > 0) {
1635 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1636 if (adder_method == null) {
1637 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1638 Environment.Exit (1);
1641 foreach (string module in modules)
1642 LoadModule (adder_method, module);
1646 // Before emitting, we need to get the core
1647 // types emitted from the user defined types
1648 // or from the system ones.
1651 ShowTime ("Initializing Core Types");
1652 if (!RootContext.StdLib){
1653 RootContext.ResolveCore ();
1654 if (Report.Errors > 0)
1658 TypeManager.InitCoreTypes ();
1660 ShowTime (" Core Types done");
1662 CodeGen.Module.ResolveAttributes ();
1665 // The second pass of the compiler
1668 ShowTime ("Resolving tree");
1669 RootContext.ResolveTree ();
1671 if (Report.Errors > 0)
1674 ShowTime ("Populate tree");
1675 if (!RootContext.StdLib)
1676 RootContext.BootCorlib_PopulateCoreTypes ();
1677 RootContext.PopulateTypes ();
1679 TypeManager.InitCodeHelpers ();
1681 RootContext.DefineTypes ();
1683 if (Report.Errors == 0 &&
1684 RootContext.Documentation != null &&
1685 !RootContext.Documentation.OutputDocComment (
1690 // Verify using aliases now
1692 NamespaceEntry.VerifyAllUsing ();
1694 if (Report.Errors > 0){
1698 CodeGen.Assembly.Resolve ();
1700 if (RootContext.VerifyClsCompliance) {
1701 if (CodeGen.Assembly.IsClsCompliant) {
1702 AttributeTester.VerifyModulesClsCompliance ();
1703 TypeManager.LoadAllImportedTypes ();
1706 if (Report.Errors > 0)
1710 // The code generator
1713 ShowTime ("Emitting code");
1714 ShowTotalTime ("Total so far");
1715 RootContext.EmitCode ();
1719 if (Report.Errors > 0){
1724 ShowTime ("Closing types");
1726 RootContext.CloseTypes ();
1728 PEFileKinds k = PEFileKinds.ConsoleApplication;
1730 switch (RootContext.Target) {
1731 case Target.Library:
1733 k = PEFileKinds.Dll; break;
1735 k = PEFileKinds.ConsoleApplication; break;
1737 k = PEFileKinds.WindowApplication; break;
1740 if (RootContext.NeedsEntryPoint) {
1741 MethodInfo ep = RootContext.EntryPoint;
1744 if (RootContext.MainClass != null) {
1745 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass, Location.Null));
1746 if (main_cont == null) {
1747 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1751 if (!(main_cont is ClassOrStruct)) {
1752 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1756 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1760 if (Report.Errors == 0)
1761 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1766 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1767 } else if (RootContext.MainClass != null) {
1768 Report.Error (2017, "Cannot specify -main if building a module or library");
1771 if (embedded_resources != null){
1772 if (RootContext.Target == Target.Module) {
1773 Report.Error (1507, "Cannot link resource file when building a module");
1777 embedded_resources.Emit ();
1781 // Add Win32 resources
1784 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1786 if (win32ResourceFile != null) {
1788 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1790 catch (ArgumentException) {
1791 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1795 if (win32IconFile != null) {
1796 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1797 if (define_icon == null) {
1798 Report.RuntimeMissingSupport (Location.Null, "resource embeding");
1800 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1803 if (Report.Errors > 0)
1806 CodeGen.Save (output_file);
1808 ShowTime ("Saved output");
1809 ShowTotalTime ("Total");
1812 Timer.ShowTimers ();
1814 if (Report.ExpectedError != 0){
1815 if (Report.Errors == 0) {
1816 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1817 "No other errors reported.");
1819 Environment.Exit (2);
1821 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1822 "However, other errors were reported.");
1824 Environment.Exit (1);
1832 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1833 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1835 return (Report.Errors == 0);
1844 string FileName { get; }
1847 class EmbededResource : IResource
1849 static MethodInfo embed_res;
1851 static EmbededResource () {
1852 Type[] argst = new Type [] {
1853 typeof (string), typeof (string), typeof (ResourceAttributes)
1856 embed_res = typeof (AssemblyBuilder).GetMethod (
1857 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1858 null, CallingConventions.Any, argst, null);
1860 if (embed_res == null) {
1861 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1865 readonly object[] args;
1867 public EmbededResource (string name, string file, bool isPrivate)
1869 args = new object [3];
1872 args [2] = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1877 embed_res.Invoke (CodeGen.Assembly.Builder, args);
1880 public string FileName {
1882 return (string)args [1];
1887 class LinkedResource : IResource
1889 readonly string file;
1890 readonly string name;
1891 readonly ResourceAttributes attribute;
1893 public LinkedResource (string name, string file, bool isPrivate)
1897 this.attribute = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1902 CodeGen.Assembly.Builder.AddResourceFile (name, file, attribute);
1905 public string FileName {
1913 IDictionary embedded_resources = new HybridDictionary ();
1915 public void Add (bool embeded, string file, string name)
1917 Add (embeded, file, name, false);
1920 public void Add (bool embeded, string file, string name, bool isPrivate)
1922 if (embedded_resources.Contains (name)) {
1923 Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
1926 IResource r = embeded ?
1927 (IResource) new EmbededResource (name, file, isPrivate) :
1928 new LinkedResource (name, file, isPrivate);
1930 embedded_resources.Add (name, r);
1935 foreach (IResource r in embedded_resources.Values) {
1936 if (!File.Exists (r.FileName)) {
1937 Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
1947 // This is the only public entry point
1949 public class CompilerCallableEntryPoint : MarshalByRefObject {
1950 public static bool InvokeCompiler (string [] args, TextWriter error)
1952 Report.Stderr = error;
1954 return Driver.MainDriver (args) && Report.Errors == 0;
1957 Report.Stderr = Console.Error;
1962 public static int[] AllWarningNumbers {
1964 return Report.AllWarnings;
1968 static void Reset ()
1972 RootContext.Reset ();
1974 TypeManager.Reset ();
1975 TypeHandle.Reset ();
1976 RootNamespace.Reset ();
1977 NamespaceEntry.Reset ();