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 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
20 using System.Globalization;
21 using System.Diagnostics;
24 Library, Exe, Module, WinExe
28 /// The compiler driver.
34 // Assemblies references to be linked. Initialized with
36 static ArrayList references;
39 // If any of these fail, we ignore the problem. This is so
40 // that we can list all the assemblies in Windows and not fail
41 // if they are missing on Linux.
43 static ArrayList soft_references;
46 // Modules to be linked
48 static ArrayList modules;
51 static ArrayList link_paths;
53 // Whether we want to only run the tokenizer
54 static bool tokenize = false;
56 static string first_source;
58 static bool want_debugging_support = false;
60 static bool parse_only = false;
61 static bool timestamps = false;
62 static bool pause = false;
63 static bool show_counters = false;
66 // Whether to load the initial config file (what CSC.RSP has by default)
68 static bool load_default_config = true;
71 // A list of resource files
73 static ArrayList resources;
74 static ArrayList embedded_resources;
75 static string win32ResourceFile;
76 static string win32IconFile;
79 // An array of the defines from the command line
81 static ArrayList defines;
86 static string output_file = null;
89 // Last time we took the time
91 static DateTime last_time, first_time;
94 // Encoding: ISO-Latin1 is 28591
96 static Encoding encoding;
99 // Whether the user has specified a different encoder manually
101 static bool using_default_encoder = true;
104 static public void Reset ()
106 want_debugging_support = false;
110 show_counters = false;
111 load_default_config = true;
112 resources = embedded_resources = null;
113 win32ResourceFile = win32IconFile = null;
117 using_default_encoder = true;
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 opened");
160 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
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 opened");
188 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
190 parser = new CSharpParser (reader, file, defines);
193 } catch (Exception ex) {
194 Report.Error(666, "Compilation aborted: " + ex);
200 static void OtherFlags ()
203 "Other flags in the compiler\n" +
204 " --fatal Makes errors fatal\n" +
205 " --parse Only parses the source file\n" +
206 " --stacktrace Shows stack trace at error location\n" +
207 " --timestamp Displays time stamps of various compiler events\n" +
208 " --expect-error X Expect that error X will be encountered\n" +
209 " -2 Enables experimental C# features\n" +
210 " -v Verbose parsing (for debugging the parser)\n" +
211 " --mcs-debug X Sets MCS debugging level to X\n");
217 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
218 "mcs [options] source-files\n" +
219 " --about About the Mono C# compiler\n" +
220 " -addmodule:MODULE Adds the module to the generated assembly\n" +
221 " -checked[+|-] Set default context to checked\n" +
222 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
223 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
224 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
225 " -debug[+|-], -g Generate debugging information\n" +
226 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
227 " -doc:FILE XML Documentation file to generate\n" +
228 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
229 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
230 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
231 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
232 " -main:class Specified the class that contains the entry point\n" +
233 " -noconfig[+|-] Disables implicit references to assemblies\n" +
234 " -nostdlib[+|-] Does not load core libraries\n" +
235 " -nowarn:W1[,W2] Disables one or more warnings\n" +
236 " -optimize[+|-] Enables code optimalizations\n" +
237 " -out:FNAME Specifies output file\n" +
238 " -pkg:P1[,Pn] References packages P1..Pn\n" +
239 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
240 " -reference:ASS References the specified assembly (-r:ASS)\n" +
241 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
242 " library, module), (short: /t:)\n" +
243 " -unsafe[+|-] Allows unsafe code\n" +
244 " -warnaserror[+|-] Treat warnings as errors\n" +
245 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
246 " -help2 Show other help flags\n" +
249 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
250 " -resource:FILE[,ID] Embed FILE as a resource\n" +
251 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
252 " -win32icon:FILE Use this icon for the output\n" +
253 " @file Read response file for more options\n\n" +
254 "Options can be of the form -option or /option");
257 static void TargetUsage ()
259 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
265 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
266 "The compiler source code is released under the terms of the GNU GPL\n\n" +
268 "For more information on Mono, visit the project Web site\n" +
269 " http://www.go-mono.com\n\n" +
271 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
272 Environment.Exit (0);
275 public static int counter1, counter2;
277 public static int Main (string[] args)
279 bool ok = MainDriver (args);
281 if (ok && Report.Errors == 0) {
282 if (Report.Warnings > 0) {
283 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
286 Console.WriteLine ("Counter1: " + counter1);
287 Console.WriteLine ("Counter2: " + counter2);
293 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
294 Report.Errors, Report.Warnings);
299 static public void LoadAssembly (string assembly, bool soft)
302 string total_log = "";
305 char[] path_chars = { '/', '\\' };
307 if (assembly.IndexOfAny (path_chars) != -1) {
308 a = Assembly.LoadFrom (assembly);
310 string ass = assembly;
311 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
312 ass = assembly.Substring (0, assembly.Length - 4);
313 a = Assembly.Load (ass);
315 TypeManager.AddAssembly (a);
317 } catch (FileNotFoundException){
318 foreach (string dir in link_paths){
319 string full_path = Path.Combine (dir, assembly);
320 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
324 a = Assembly.LoadFrom (full_path);
325 TypeManager.AddAssembly (a);
327 } catch (FileNotFoundException ff) {
328 total_log += ff.FusionLog;
333 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
334 Console.WriteLine ("Log: \n" + total_log);
336 } catch (BadImageFormatException f) {
337 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
338 } catch (FileLoadException f){
339 Report.Error(6, "Cannot load assembly " + f.FusionLog);
340 } catch (ArgumentNullException){
341 Report.Error(6, "Cannot load assembly (null argument)");
345 static public void LoadModule (MethodInfo adder_method, string module)
348 string total_log = "";
352 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
354 catch (TargetInvocationException ex) {
355 throw ex.InnerException;
357 TypeManager.AddModule (m);
360 catch (FileNotFoundException){
361 foreach (string dir in link_paths){
362 string full_path = Path.Combine (dir, module);
363 if (!module.EndsWith (".netmodule"))
364 full_path += ".netmodule";
368 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
370 catch (TargetInvocationException ex) {
371 throw ex.InnerException;
373 TypeManager.AddModule (m);
375 } catch (FileNotFoundException ff) {
376 total_log += ff.FusionLog;
380 Report.Error (6, "Cannot find module `" + module + "'" );
381 Console.WriteLine ("Log: \n" + total_log);
382 } catch (BadImageFormatException f) {
383 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
384 } catch (FileLoadException f){
385 Report.Error(6, "Cannot load module " + f.FusionLog);
386 } catch (ArgumentNullException){
387 Report.Error(6, "Cannot load module (null argument)");
392 /// Loads all assemblies referenced on the command line
394 static public void LoadReferences ()
396 foreach (string r in references)
397 LoadAssembly (r, false);
399 foreach (string r in soft_references)
400 LoadAssembly (r, true);
405 static void SetupDefaultDefines ()
407 defines = new ArrayList ();
408 defines.Add ("__MonoCS__");
411 static string [] LoadArgs (string file)
414 ArrayList args = new ArrayList ();
417 f = new StreamReader (file);
422 StringBuilder sb = new StringBuilder ();
424 while ((line = f.ReadLine ()) != null){
427 for (int i = 0; i < t; i++){
430 if (c == '"' || c == '\''){
433 for (i++; i < t; i++){
440 } else if (c == ' '){
442 args.Add (sb.ToString ());
449 args.Add (sb.ToString ());
454 string [] ret_value = new string [args.Count];
455 args.CopyTo (ret_value, 0);
461 // Returns the directory where the system assemblies are installed
463 static string GetSystemDir ()
465 return Path.GetDirectoryName (typeof (object).Assembly.Location);
469 // Given a path specification, splits the path from the file/pattern
471 static void SplitPathAndPattern (string spec, out string path, out string pattern)
473 int p = spec.LastIndexOf ('/');
476 // Windows does not like /file.cs, switch that to:
481 pattern = spec.Substring (1);
483 path = spec.Substring (0, p);
484 pattern = spec.Substring (p + 1);
489 p = spec.LastIndexOf ('\\');
491 path = spec.Substring (0, p);
492 pattern = spec.Substring (p + 1);
500 static void ProcessFile (string f)
502 if (first_source == null)
505 Location.AddFile (f);
508 static void ProcessFiles ()
510 Location.Initialize ();
512 foreach (SourceFile file in Location.SourceFiles) {
514 tokenize_file (file);
521 static void CompileFiles (string spec, bool recurse)
523 string path, pattern;
525 SplitPathAndPattern (spec, out path, out pattern);
526 if (pattern.IndexOf ('*') == -1){
531 string [] files = null;
533 files = Directory.GetFiles (path, pattern);
534 } catch (System.IO.DirectoryNotFoundException) {
535 Report.Error (2001, "Source file `" + spec + "' could not be found");
537 } catch (System.IO.IOException){
538 Report.Error (2001, "Source file `" + spec + "' could not be found");
541 foreach (string f in files) {
548 string [] dirs = null;
551 dirs = Directory.GetDirectories (path);
555 foreach (string d in dirs) {
557 // Don't include path in this string, as each
558 // directory entry already does
559 CompileFiles (d + "/" + pattern, true);
563 static void DefineDefaultConfig ()
566 // For now the "default config" is harcoded into the compiler
567 // we can move this outside later
569 string [] default_config = {
574 // Is it worth pre-loading all this stuff?
577 "System.Configuration.Install",
580 "System.DirectoryServices",
581 "System.Drawing.Design",
583 "System.EnterpriseServices",
586 "System.Runtime.Remoting",
587 "System.Runtime.Serialization.Formatters.Soap",
589 "System.ServiceProcess",
591 "System.Web.RegularExpressions",
592 "System.Web.Services",
593 "System.Windows.Forms"
598 foreach (string def in default_config)
599 soft_references.Insert (p++, def);
602 static void SetOutputFile (string name)
607 static void SetWarningLevel (string s)
612 level = Int32.Parse (s);
616 "--wlevel requires a value from 0 to 4");
619 if (level < 0 || level > 4){
620 Report.Error (1900, "Warning level must be 0 to 4");
623 RootContext.WarningLevel = level;
626 static void SetupV2 ()
628 RootContext.Version = LanguageVersion.Default;
629 defines.Add ("__V2__");
632 static void Version ()
634 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
635 Console.WriteLine ("Mono C# compiler version {0}", version);
636 Environment.Exit (0);
640 // Currently handles the Unix-like command line options, but will be
641 // deprecated in favor of the CSCParseOption, which will also handle the
642 // options that start with a dash in the future.
644 static bool UnixParseOption (string arg, ref string [] args, ref int i)
648 CSharpParser.yacc_verbose_flag++;
659 case "--main": case "-m":
660 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
661 if ((i + 1) >= args.Length){
663 Environment.Exit (1);
665 RootContext.MainClass = args [++i];
669 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
670 RootContext.Unsafe = true;
673 case "/?": case "/h": case "/help":
676 Environment.Exit (0);
680 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
681 if ((i + 1) >= args.Length){
683 Environment.Exit (1);
685 defines.Add (args [++i]);
688 case "--show-counters":
689 show_counters = true;
692 case "--expect-error": {
697 args [++i], NumberStyles.AllowLeadingSign);
698 Report.ExpectedError = code;
700 Report.Error (-14, "Invalid number specified");
711 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --outout FILE or -o FILE");
712 if ((i + 1) >= args.Length){
714 Environment.Exit (1);
716 SetOutputFile (args [++i]);
720 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
721 RootContext.Checked = true;
725 Report.Stacktrace = true;
728 case "--linkresource":
730 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
731 if ((i + 1) >= args.Length){
733 Report.Error (5, "Missing argument to --linkres");
734 Environment.Exit (1);
736 if (resources == null)
737 resources = new ArrayList ();
739 resources.Add (args [++i]);
744 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
745 if ((i + 1) >= args.Length){
747 Report.Error (5, "Missing argument to --resource");
748 Environment.Exit (1);
750 if (embedded_resources == null)
751 embedded_resources = new ArrayList ();
753 embedded_resources.Add (args [++i]);
757 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
758 if ((i + 1) >= args.Length){
759 Environment.Exit (1);
763 string type = args [++i];
766 RootContext.Target = Target.Library;
767 RootContext.TargetExt = ".dll";
771 RootContext.Target = Target.Exe;
775 RootContext.Target = Target.WinExe;
779 RootContext.Target = Target.Module;
780 RootContext.TargetExt = ".dll";
789 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
790 if ((i + 1) >= args.Length){
792 Environment.Exit (1);
795 references.Add (args [++i]);
799 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
800 if ((i + 1) >= args.Length){
802 Environment.Exit (1);
804 link_paths.Add (args [++i]);
808 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
809 RootContext.StdLib = false;
817 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
818 Report.WarningsAreErrors = true;
822 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
823 if ((i + 1) >= args.Length){
825 Environment.Exit (1);
830 warn = Int32.Parse (args [++i]);
833 Environment.Exit (1);
835 Report.SetIgnoreWarning (warn);
839 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
840 if ((i + 1) >= args.Length){
843 "--wlevel requires a value from 0 to 4");
844 Environment.Exit (1);
847 SetWarningLevel (args [++i]);
851 if ((i + 1) >= args.Length){
852 Report.Error (5, "--mcs-debug requires an argument");
853 Environment.Exit (1);
857 Report.DebugFlags = Int32.Parse (args [++i]);
859 Report.Error (5, "Invalid argument to --mcs-debug");
860 Environment.Exit (1);
869 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
870 if ((i + 1) >= args.Length){
871 Report.Error (5, "--recurse requires an argument");
872 Environment.Exit (1);
874 CompileFiles (args [++i], true);
879 last_time = first_time = DateTime.Now;
886 case "--debug": case "-g":
887 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
888 want_debugging_support = true;
892 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
893 load_default_config = false;
901 // This parses the -arg and /arg options to the compiler, even if the strings
902 // in the following text use "/arg" on the strings.
904 static bool CSCParseOption (string option, ref string [] args, ref int i)
906 int idx = option.IndexOf (':');
913 arg = option.Substring (0, idx);
915 value = option.Substring (idx + 1);
926 RootContext.Target = Target.Exe;
930 RootContext.Target = Target.WinExe;
934 RootContext.Target = Target.Library;
935 RootContext.TargetExt = ".dll";
939 RootContext.Target = Target.Module;
940 RootContext.TargetExt = ".netmodule";
952 Environment.Exit (1);
954 SetOutputFile (value);
959 RootContext.Optimize = true;
963 RootContext.Optimize = false;
967 case "/incremental+":
968 case "/incremental-":
978 Environment.Exit (1);
981 defs = value.Split (new Char [] {';', ','});
982 foreach (string d in defs){
990 // We should collect data, runtime, etc and store in the file specified
992 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
996 case "/linkresource":
998 Report.Error (5, arg + " requires an argument");
999 Environment.Exit (1);
1001 if (resources == null)
1002 resources = new ArrayList ();
1004 resources.Add (value);
1012 Environment.Exit (1);
1014 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1016 ProcessStartInfo pi = new ProcessStartInfo ();
1017 pi.FileName = "pkg-config";
1018 pi.RedirectStandardOutput = true;
1019 pi.UseShellExecute = false;
1020 pi.Arguments = "--libs " + packages;
1023 p = Process.Start (pi);
1024 } catch (Exception e) {
1025 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1026 Environment.Exit (1);
1029 if (p.StandardOutput == null){
1030 Report.Warning (-27, "Specified package did not return any information");
1033 string pkgout = p.StandardOutput.ReadToEnd ();
1035 if (p.ExitCode != 0) {
1036 Report.Error (-27, "Error running pkg-config. Check the above output.");
1037 Environment.Exit (1);
1040 if (pkgout != null){
1041 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1042 Split (new Char [] { ' ', '\t'});
1043 args = AddArgs (args, xargs);
1053 Report.Error (5, "-resource requires an argument");
1054 Environment.Exit (1);
1056 if (embedded_resources == null)
1057 embedded_resources = new ArrayList ();
1059 if (embedded_resources.Contains (value)) {
1060 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1062 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1063 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1066 embedded_resources.Add (value);
1072 Report.Error (5, "-recurse requires an argument");
1073 Environment.Exit (1);
1075 CompileFiles (value, true);
1079 case "/reference": {
1081 Report.Error (5, "-reference requires an argument");
1082 Environment.Exit (1);
1085 string [] refs = value.Split (new char [] { ';', ',' });
1086 foreach (string r in refs){
1091 case "/addmodule": {
1093 Report.Error (5, arg + " requires an argument");
1094 Environment.Exit (1);
1097 string [] refs = value.Split (new char [] { ';', ',' });
1098 foreach (string r in refs){
1105 Report.Error (5, arg + " requires an argument");
1106 Environment.Exit (1);
1109 win32ResourceFile = value;
1112 case "/win32icon": {
1114 Report.Error (5, arg + " requires an argument");
1115 Environment.Exit (1);
1118 win32IconFile = value;
1123 Report.Error (2006, arg + " requires an argument");
1124 Environment.Exit (1);
1126 RootContext.Documentation = new Documentation (value);
1133 Report.Error (5, "/lib requires an argument");
1134 Environment.Exit (1);
1137 libdirs = value.Split (new Char [] { ',' });
1138 foreach (string dir in libdirs)
1139 link_paths.Add (dir);
1144 want_debugging_support = false;
1149 want_debugging_support = true;
1154 RootContext.Checked = true;
1158 RootContext.Checked = false;
1166 RootContext.VerifyClsCompliance = false;
1171 RootContext.Unsafe = true;
1175 RootContext.Unsafe = false;
1178 case "/warnaserror":
1179 case "/warnaserror+":
1180 Report.WarningsAreErrors = true;
1183 case "/warnaserror-":
1184 Report.WarningsAreErrors = false;
1188 SetWarningLevel (value);
1195 Report.Error (5, "/nowarn requires an argument");
1196 Environment.Exit (1);
1199 warns = value.Split (new Char [] {','});
1200 foreach (string wc in warns){
1202 int warn = Int32.Parse (wc);
1204 throw new ArgumentOutOfRangeException("warn");
1206 Report.SetIgnoreWarning (warn);
1208 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1215 load_default_config = true;
1220 load_default_config = false;
1225 Environment.Exit(0);
1231 Environment.Exit (0);
1237 Report.Error (5, arg + " requires an argument");
1238 Environment.Exit (1);
1240 RootContext.MainClass = value;
1245 RootContext.StdLib = false;
1249 RootContext.StdLib = true;
1256 if (value == String.Empty) {
1257 Report.Error (5, arg + " requires an argument");
1258 Environment.Exit (1);
1260 RootContext.StrongNameKeyFile = value;
1262 case "/keycontainer":
1263 if (value == String.Empty) {
1264 Report.Error (5, arg + " requires an argument");
1265 Environment.Exit (1);
1267 RootContext.StrongNameKeyContainer = value;
1270 RootContext.StrongNameDelaySign = true;
1273 RootContext.StrongNameDelaySign = false;
1278 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1282 case "/langversion":
1283 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1285 RootContext.Version = LanguageVersion.ISO_1;
1292 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1298 if (value == "utf8"){
1299 encoding = new UTF8Encoding();
1300 using_default_encoder = false;
1303 if (value == "reset"){
1305 // 28591 is the code page for ISO-8859-1 encoding.
1308 using_default_encoder = true;
1312 cp = Int32.Parse (value);
1313 encoding = Encoding.GetEncoding (cp);
1314 using_default_encoder = false;
1316 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1321 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1322 //Environment.Exit (1);
1326 static string [] AddArgs (string [] args, string [] extra_args)
1329 new_args = new string [extra_args.Length + args.Length];
1331 // if args contains '--' we have to take that into account
1332 // split args into first half and second half based on '--'
1333 // and add the extra_args before --
1334 int split_position = Array.IndexOf (args, "--");
1335 if (split_position != -1)
1337 Array.Copy (args, new_args, split_position);
1338 extra_args.CopyTo (new_args, split_position);
1339 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1343 args.CopyTo (new_args, 0);
1344 extra_args.CopyTo (new_args, args.Length);
1351 /// Parses the arguments, and drives the compilation
1356 /// TODO: Mostly structured to debug the compiler
1357 /// now, needs to be turned into a real driver soon.
1359 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1360 internal static bool MainDriver (string [] args)
1363 bool parsing_options = true;
1366 encoding = Encoding.GetEncoding (28591);
1368 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1369 encoding = Encoding.GetEncoding (1252);
1372 references = new ArrayList ();
1373 soft_references = new ArrayList ();
1374 modules = new ArrayList ();
1375 link_paths = new ArrayList ();
1377 SetupDefaultDefines ();
1382 // This is not required because Assembly.Load knows about this
1386 Hashtable response_file_list = null;
1388 for (i = 0; i < args.Length; i++){
1389 string arg = args [i];
1393 if (arg.StartsWith ("@")){
1394 string [] extra_args;
1395 string response_file = arg.Substring (1);
1397 if (response_file_list == null)
1398 response_file_list = new Hashtable ();
1400 if (response_file_list.Contains (response_file)){
1402 1515, "Response file `" + response_file +
1403 "' specified multiple times");
1404 Environment.Exit (1);
1407 response_file_list.Add (response_file, response_file);
1409 extra_args = LoadArgs (response_file);
1410 if (extra_args == null){
1411 Report.Error (2011, "Unable to open response file: " +
1416 args = AddArgs (args, extra_args);
1420 if (parsing_options){
1422 parsing_options = false;
1426 if (arg.StartsWith ("-")){
1427 if (UnixParseOption (arg, ref args, ref i))
1431 string csc_opt = "/" + arg.Substring (1);
1432 if (CSCParseOption (csc_opt, ref args, ref i))
1435 if (arg.StartsWith ("/")){
1436 if (CSCParseOption (arg, ref args, ref i))
1442 CompileFiles (arg, false);
1451 // This will point to the NamespaceEntry of the last file that was parsed, and may
1452 // not be meaningful when resolving classes from other files. So, reset it to prevent
1455 RootContext.Tree.Types.NamespaceEntry = null;
1458 // If we are an exe, require a source file for the entry point
1460 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1461 if (first_source == null){
1462 Report.Error (2008, "No files to compile were specified");
1469 // If there is nothing to put in the assembly, and we are not a library
1471 if (first_source == null && embedded_resources == null && resources == null){
1472 Report.Error (2008, "No files to compile were specified");
1476 if (Report.Errors > 0)
1483 // Load Core Library for default compilation
1485 if (RootContext.StdLib)
1486 references.Insert (0, "mscorlib");
1488 if (load_default_config)
1489 DefineDefaultConfig ();
1491 if (Report.Errors > 0){
1496 // Load assemblies required
1499 ShowTime ("Loading references");
1500 link_paths.Add (GetSystemDir ());
1501 link_paths.Add (Directory.GetCurrentDirectory ());
1505 ShowTime (" References loaded");
1507 if (Report.Errors > 0){
1514 if (output_file == null){
1515 int pos = first_source.LastIndexOf ('.');
1518 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1520 output_file = first_source + RootContext.TargetExt;
1523 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1526 if (RootContext.Target == Target.Module) {
1527 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1528 if (module_only == null) {
1529 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1530 Environment.Exit (1);
1533 MethodInfo set_method = module_only.GetSetMethod (true);
1534 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1537 TypeManager.AddModule (CodeGen.Module.Builder);
1539 if (modules.Count > 0) {
1540 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1541 if (adder_method == null) {
1542 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1543 Environment.Exit (1);
1546 foreach (string module in modules)
1547 LoadModule (adder_method, module);
1550 TypeManager.ComputeNamespaces ();
1553 // Before emitting, we need to get the core
1554 // types emitted from the user defined types
1555 // or from the system ones.
1558 ShowTime ("Initializing Core Types");
1559 if (!RootContext.StdLib){
1560 RootContext.ResolveCore ();
1561 if (Report.Errors > 0)
1565 TypeManager.InitCoreTypes ();
1567 ShowTime (" Core Types done");
1569 CodeGen.Module.ResolveAttributes ();
1572 // The second pass of the compiler
1575 ShowTime ("Resolving tree");
1576 RootContext.ResolveTree ();
1578 if (Report.Errors > 0)
1581 ShowTime ("Populate tree");
1582 if (!RootContext.StdLib)
1583 RootContext.BootCorlib_PopulateCoreTypes ();
1585 RootContext.PopulateTypes ();
1586 RootContext.DefineTypes ();
1588 if (RootContext.Documentation != null &&
1589 !RootContext.Documentation.OutputDocComment (
1593 TypeManager.InitCodeHelpers ();
1596 // Verify using aliases now
1598 Namespace.VerifyUsing ();
1600 if (Report.Errors > 0){
1604 if (RootContext.VerifyClsCompliance) {
1605 CodeGen.Assembly.ResolveClsCompliance ();
1606 if (CodeGen.Assembly.IsClsCompliant) {
1607 AttributeTester.VerifyModulesClsCompliance ();
1608 TypeManager.LoadAllImportedTypes ();
1609 AttributeTester.VerifyTopLevelNameClsCompliance ();
1612 if (Report.Errors > 0)
1616 // The code generator
1619 ShowTime ("Emitting code");
1620 ShowTotalTime ("Total so far");
1621 RootContext.EmitCode ();
1625 if (Report.Errors > 0){
1630 ShowTime ("Closing types");
1632 RootContext.CloseTypes ();
1634 PEFileKinds k = PEFileKinds.ConsoleApplication;
1636 switch (RootContext.Target) {
1637 case Target.Library:
1639 k = PEFileKinds.Dll; break;
1641 k = PEFileKinds.ConsoleApplication; break;
1643 k = PEFileKinds.WindowApplication; break;
1646 if (RootContext.NeedsEntryPoint) {
1647 MethodInfo ep = RootContext.EntryPoint;
1650 if (RootContext.MainClass != null) {
1651 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1652 if (main_cont == null) {
1653 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1657 if (!(main_cont is ClassOrStruct)) {
1658 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1662 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1666 if (Report.Errors == 0)
1667 Report.Error (5001, "Program " + output_file +
1668 " does not have an entry point defined");
1672 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1673 } else if (RootContext.MainClass != null) {
1674 Report.Error (2017, "Can not specify -main: when building module or library");
1678 // Add the resources
1680 if (resources != null){
1681 foreach (string spec in resources){
1685 cp = spec.IndexOf (',');
1687 file = spec.Substring (0, cp);
1688 res = spec.Substring (cp + 1);
1692 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1696 if (embedded_resources != null){
1697 object[] margs = new object [2];
1698 Type[] argst = new Type [2];
1699 argst [0] = argst [1] = typeof (string);
1701 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1702 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1703 null, CallingConventions.Any, argst, null);
1705 if (embed_res == null) {
1706 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1708 foreach (string spec in embedded_resources) {
1711 cp = spec.IndexOf (',');
1713 margs [0] = spec.Substring (cp + 1);
1714 margs [1] = spec.Substring (0, cp);
1717 margs [0] = Path.GetFileName (spec);
1720 if (File.Exists ((string) margs [1]))
1721 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1723 Report.Error (1566, "Can not find the resource " + margs [1]);
1730 // Add Win32 resources
1733 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1735 if (win32ResourceFile != null) {
1737 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1739 catch (ArgumentException) {
1740 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1744 if (win32IconFile != null) {
1745 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1746 if (define_icon == null) {
1747 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1749 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1752 if (Report.Errors > 0)
1755 CodeGen.Save (output_file);
1757 ShowTime ("Saved output");
1758 ShowTotalTime ("Total");
1761 Timer.ShowTimers ();
1763 if (Report.ExpectedError != 0) {
1764 if (Report.Errors == 0) {
1765 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1766 "No other errors reported.");
1768 Environment.Exit (2);
1770 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1771 "However, other errors were reported.");
1773 Environment.Exit (1);
1781 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1782 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1784 return (Report.Errors == 0);
1789 // This is the only public entry point
1791 public class CompilerCallableEntryPoint : MarshalByRefObject {
1792 public static bool InvokeCompiler (string [] args, TextWriter error)
1794 Report.Stderr = error;
1795 bool ret = Driver.MainDriver (args) && Report.Errors == 0;
1796 Report.Stderr = Console.Error;
1802 static void Reset ()
1806 RootContext.Reset ();
1808 TypeManager.Reset ();
1809 TypeHandle.Reset ();