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;
18 using System.Diagnostics;
21 using System.Globalization;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references;
47 // Modules to be linked
49 static ArrayList modules;
52 static ArrayList link_paths;
54 // Whether we want to only run the tokenizer
55 static bool tokenize = false;
57 static string first_source;
59 static bool want_debugging_support = false;
61 static bool parse_only = false;
62 static bool timestamps = false;
63 static bool pause = false;
64 static bool show_counters = false;
67 // Whether to load the initial config file (what CSC.RSP has by default)
69 static bool load_default_config = true;
72 // A list of resource files
74 static ArrayList resources;
75 static ArrayList embedded_resources;
76 static string win32ResourceFile;
77 static string win32IconFile;
80 // An array of the defines from the command line
82 static ArrayList defines;
87 static string output_file = null;
90 // Last time we took the time
92 static DateTime last_time, first_time;
95 // Encoding: ISO-Latin1 is 28591
97 static Encoding encoding;
100 // Whether the user has specified a different encoder manually
102 static bool using_default_encoder = true;
105 static public void Reset ()
107 want_debugging_support = false;
111 show_counters = false;
112 load_default_config = true;
113 resources = embedded_resources = null;
114 win32ResourceFile = win32IconFile = null;
118 using_default_encoder = true;
122 public static void ShowTime (string msg)
127 DateTime now = DateTime.Now;
128 TimeSpan span = now - last_time;
132 "[{0:00}:{1:000}] {2}",
133 (int) span.TotalSeconds, span.Milliseconds, msg);
136 public static void ShowTotalTime (string msg)
141 DateTime now = DateTime.Now;
142 TimeSpan span = now - first_time;
146 "[{0:00}:{1:000}] {2}",
147 (int) span.TotalSeconds, span.Milliseconds, msg);
150 static void tokenize_file (SourceFile file)
155 input = File.OpenRead (file.Name);
157 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
162 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
163 Tokenizer lexer = new Tokenizer (reader, file, defines);
164 int token, tokens = 0, errors = 0;
166 while ((token = lexer.token ()) != Token.EOF){
168 if (token == Token.ERROR)
171 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
177 // MonoTODO("Change error code for aborted compilation to something reasonable")]
178 static void parse (SourceFile file)
184 input = File.OpenRead (file.Name);
186 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
190 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
192 parser = new CSharpParser (reader, file, defines);
193 parser.ErrorOutput = Report.Stderr;
196 } catch (Exception ex) {
197 Report.Error(666, "Compilation aborted: " + ex);
203 static void OtherFlags ()
206 "Other flags in the compiler\n" +
207 " --fatal Makes errors fatal\n" +
208 " --parse Only parses the source file\n" +
209 " --stacktrace Shows stack trace at error location\n" +
210 " --timestamp Displays time stamps of various compiler events\n" +
211 " --expect-error X Expect that error X will be encountered\n" +
212 " -2 Enables experimental C# features\n" +
213 " -v Verbose parsing (for debugging the parser)\n" +
214 " --mcs-debug X Sets MCS debugging level to X\n");
220 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
221 "mcs [options] source-files\n" +
222 " --about About the Mono C# compiler\n" +
223 " -addmodule:MODULE Adds the module to the generated assembly\n" +
224 " -checked[+|-] Set default context to checked\n" +
225 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
226 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
227 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
228 " -debug[+|-], -g Generate debugging information\n" +
229 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
230 " -doc:FILE XML Documentation file to generate\n" +
231 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
232 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
233 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
234 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
235 " -main:class Specified the class that contains the entry point\n" +
236 " -noconfig[+|-] Disables implicit references to assemblies\n" +
237 " -nostdlib[+|-] Does not load core libraries\n" +
238 " -nowarn:W1[,W2] Disables one or more warnings\n" +
239 " -optimize[+|-] Enables code optimalizations\n" +
240 " -out:FNAME Specifies output file\n" +
241 " -pkg:P1[,Pn] References packages P1..Pn\n" +
242 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
243 " -reference:ASS References the specified assembly (-r:ASS)\n" +
244 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
245 " library, module), (short: /t:)\n" +
246 " -unsafe[+|-] Allows unsafe code\n" +
247 " -warnaserror[+|-] Treat warnings as errors\n" +
248 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
249 " -help2 Show other help flags\n" +
252 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
253 " -resource:FILE[,ID] Embed FILE as a resource\n" +
254 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
255 " -win32icon:FILE Use this icon for the output\n" +
256 " @file Read response file for more options\n\n" +
257 "Options can be of the form -option or /option");
260 static void TargetUsage ()
262 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
268 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
269 "The compiler source code is released under the terms of the GNU GPL\n\n" +
271 "For more information on Mono, visit the project Web site\n" +
272 " http://www.go-mono.com\n\n" +
274 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
275 Environment.Exit (0);
278 public static int counter1, counter2;
280 public static int Main (string[] args)
282 RootContext.Version = LanguageVersion.Default;
283 bool ok = MainDriver (args);
285 if (ok && Report.Errors == 0) {
286 if (Report.Warnings > 0) {
287 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
290 Console.WriteLine ("Counter1: " + counter1);
291 Console.WriteLine ("Counter2: " + counter2);
297 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
298 Report.Errors, Report.Warnings);
303 static public void LoadAssembly (string assembly, bool soft)
306 string total_log = "";
309 char[] path_chars = { '/', '\\' };
311 if (assembly.IndexOfAny (path_chars) != -1) {
312 a = Assembly.LoadFrom (assembly);
314 string ass = assembly;
315 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
316 ass = assembly.Substring (0, assembly.Length - 4);
317 a = Assembly.Load (ass);
319 TypeManager.AddAssembly (a);
321 } catch (FileNotFoundException){
322 foreach (string dir in link_paths){
323 string full_path = Path.Combine (dir, assembly);
324 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
328 a = Assembly.LoadFrom (full_path);
329 TypeManager.AddAssembly (a);
331 } catch (FileNotFoundException ff) {
332 total_log += ff.FusionLog;
337 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
338 Console.WriteLine ("Log: \n" + total_log);
340 } catch (BadImageFormatException f) {
341 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
342 } catch (FileLoadException f){
343 Report.Error(6, "Cannot load assembly " + f.FusionLog);
344 } catch (ArgumentNullException){
345 Report.Error(6, "Cannot load assembly (null argument)");
349 static public void LoadModule (MethodInfo adder_method, string module)
352 string total_log = "";
356 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
358 catch (TargetInvocationException ex) {
359 throw ex.InnerException;
361 TypeManager.AddModule (m);
364 catch (FileNotFoundException){
365 foreach (string dir in link_paths){
366 string full_path = Path.Combine (dir, module);
367 if (!module.EndsWith (".netmodule"))
368 full_path += ".netmodule";
372 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
374 catch (TargetInvocationException ex) {
375 throw ex.InnerException;
377 TypeManager.AddModule (m);
379 } catch (FileNotFoundException ff) {
380 total_log += ff.FusionLog;
384 Report.Error (6, "Cannot find module `" + module + "'" );
385 Console.WriteLine ("Log: \n" + total_log);
386 } catch (BadImageFormatException f) {
387 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
388 } catch (FileLoadException f){
389 Report.Error(6, "Cannot load module " + f.FusionLog);
390 } catch (ArgumentNullException){
391 Report.Error(6, "Cannot load module (null argument)");
396 /// Loads all assemblies referenced on the command line
398 static public void LoadReferences ()
400 foreach (string r in references)
401 LoadAssembly (r, false);
403 foreach (string r in soft_references)
404 LoadAssembly (r, true);
409 static void SetupDefaultDefines ()
411 defines = new ArrayList ();
412 defines.Add ("__MonoCS__");
415 static string [] LoadArgs (string file)
418 ArrayList args = new ArrayList ();
421 f = new StreamReader (file);
426 StringBuilder sb = new StringBuilder ();
428 while ((line = f.ReadLine ()) != null){
431 for (int i = 0; i < t; i++){
434 if (c == '"' || c == '\''){
437 for (i++; i < t; i++){
444 } else if (c == ' '){
446 args.Add (sb.ToString ());
453 args.Add (sb.ToString ());
458 string [] ret_value = new string [args.Count];
459 args.CopyTo (ret_value, 0);
465 // Returns the directory where the system assemblies are installed
467 static string GetSystemDir ()
469 return Path.GetDirectoryName (typeof (object).Assembly.Location);
473 // Given a path specification, splits the path from the file/pattern
475 static void SplitPathAndPattern (string spec, out string path, out string pattern)
477 int p = spec.LastIndexOf ('/');
480 // Windows does not like /file.cs, switch that to:
485 pattern = spec.Substring (1);
487 path = spec.Substring (0, p);
488 pattern = spec.Substring (p + 1);
493 p = spec.LastIndexOf ('\\');
495 path = spec.Substring (0, p);
496 pattern = spec.Substring (p + 1);
504 static void ProcessFile (string f)
506 if (first_source == null)
509 Location.AddFile (f);
512 static void ProcessFiles ()
514 Location.Initialize ();
516 foreach (SourceFile file in Location.SourceFiles) {
518 tokenize_file (file);
525 static void CompileFiles (string spec, bool recurse)
527 string path, pattern;
529 SplitPathAndPattern (spec, out path, out pattern);
530 if (pattern.IndexOf ('*') == -1){
535 string [] files = null;
537 files = Directory.GetFiles (path, pattern);
538 } catch (System.IO.DirectoryNotFoundException) {
539 Report.Error (2001, "Source file `" + spec + "' could not be found");
541 } catch (System.IO.IOException){
542 Report.Error (2001, "Source file `" + spec + "' could not be found");
545 foreach (string f in files) {
552 string [] dirs = null;
555 dirs = Directory.GetDirectories (path);
559 foreach (string d in dirs) {
561 // Don't include path in this string, as each
562 // directory entry already does
563 CompileFiles (d + "/" + pattern, true);
567 static void DefineDefaultConfig ()
570 // For now the "default config" is harcoded into the compiler
571 // we can move this outside later
573 string [] default_config = {
578 // Is it worth pre-loading all this stuff?
581 "System.Configuration.Install",
584 "System.DirectoryServices",
585 "System.Drawing.Design",
587 "System.EnterpriseServices",
590 "System.Runtime.Remoting",
591 "System.Runtime.Serialization.Formatters.Soap",
593 "System.ServiceProcess",
595 "System.Web.RegularExpressions",
596 "System.Web.Services",
597 "System.Windows.Forms"
602 foreach (string def in default_config)
603 soft_references.Insert (p++, def);
606 static void SetOutputFile (string name)
611 static void SetWarningLevel (string s)
616 level = Int32.Parse (s);
620 "--wlevel requires a value from 0 to 4");
623 if (level < 0 || level > 4){
624 Report.Error (1900, "Warning level must be 0 to 4");
627 RootContext.WarningLevel = level;
630 static void SetupV2 ()
632 RootContext.Version = LanguageVersion.Default;
633 defines.Add ("__V2__");
636 static void Version ()
638 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
639 Console.WriteLine ("Mono C# compiler version {0}", version);
640 Environment.Exit (0);
644 // Currently handles the Unix-like command line options, but will be
645 // deprecated in favor of the CSCParseOption, which will also handle the
646 // options that start with a dash in the future.
648 static bool UnixParseOption (string arg, ref string [] args, ref int i)
652 CSharpParser.yacc_verbose_flag++;
663 case "--main": case "-m":
664 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
665 if ((i + 1) >= args.Length){
667 Environment.Exit (1);
669 RootContext.MainClass = args [++i];
673 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
674 RootContext.Unsafe = true;
677 case "/?": case "/h": case "/help":
680 Environment.Exit (0);
684 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
685 if ((i + 1) >= args.Length){
687 Environment.Exit (1);
689 defines.Add (args [++i]);
692 case "--show-counters":
693 show_counters = true;
696 case "--expect-error": {
701 args [++i], NumberStyles.AllowLeadingSign);
702 Report.ExpectedError = code;
704 Report.Error (-14, "Invalid number specified");
715 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
716 if ((i + 1) >= args.Length){
718 Environment.Exit (1);
720 SetOutputFile (args [++i]);
724 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
725 RootContext.Checked = true;
729 Report.Stacktrace = true;
732 case "--linkresource":
734 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
735 if ((i + 1) >= args.Length){
737 Report.Error (5, "Missing argument to --linkres");
738 Environment.Exit (1);
740 if (resources == null)
741 resources = new ArrayList ();
743 resources.Add (args [++i]);
748 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
749 if ((i + 1) >= args.Length){
751 Report.Error (5, "Missing argument to --resource");
752 Environment.Exit (1);
754 if (embedded_resources == null)
755 embedded_resources = new ArrayList ();
757 embedded_resources.Add (args [++i]);
761 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
762 if ((i + 1) >= args.Length){
763 Environment.Exit (1);
767 string type = args [++i];
770 RootContext.Target = Target.Library;
771 RootContext.TargetExt = ".dll";
775 RootContext.Target = Target.Exe;
779 RootContext.Target = Target.WinExe;
783 RootContext.Target = Target.Module;
784 RootContext.TargetExt = ".dll";
793 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
794 if ((i + 1) >= args.Length){
796 Environment.Exit (1);
799 references.Add (args [++i]);
803 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
804 if ((i + 1) >= args.Length){
806 Environment.Exit (1);
808 link_paths.Add (args [++i]);
812 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
813 RootContext.StdLib = false;
821 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
822 Report.WarningsAreErrors = true;
826 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
827 if ((i + 1) >= args.Length){
829 Environment.Exit (1);
834 warn = Int32.Parse (args [++i]);
837 Environment.Exit (1);
839 Report.SetIgnoreWarning (warn);
843 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
844 if ((i + 1) >= args.Length){
847 "--wlevel requires a value from 0 to 4");
848 Environment.Exit (1);
851 SetWarningLevel (args [++i]);
855 if ((i + 1) >= args.Length){
856 Report.Error (5, "--mcs-debug requires an argument");
857 Environment.Exit (1);
861 Report.DebugFlags = Int32.Parse (args [++i]);
863 Report.Error (5, "Invalid argument to --mcs-debug");
864 Environment.Exit (1);
873 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
874 if ((i + 1) >= args.Length){
875 Report.Error (5, "--recurse requires an argument");
876 Environment.Exit (1);
878 CompileFiles (args [++i], true);
883 last_time = first_time = DateTime.Now;
890 case "--debug": case "-g":
891 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
892 want_debugging_support = true;
896 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
897 load_default_config = false;
905 // This parses the -arg and /arg options to the compiler, even if the strings
906 // in the following text use "/arg" on the strings.
908 static bool CSCParseOption (string option, ref string [] args, ref int i)
910 int idx = option.IndexOf (':');
917 arg = option.Substring (0, idx);
919 value = option.Substring (idx + 1);
930 RootContext.Target = Target.Exe;
934 RootContext.Target = Target.WinExe;
938 RootContext.Target = Target.Library;
939 RootContext.TargetExt = ".dll";
943 RootContext.Target = Target.Module;
944 RootContext.TargetExt = ".netmodule";
956 Environment.Exit (1);
958 SetOutputFile (value);
963 RootContext.Optimize = true;
967 RootContext.Optimize = false;
971 case "/incremental+":
972 case "/incremental-":
982 Environment.Exit (1);
985 defs = value.Split (new Char [] {';', ','});
986 foreach (string d in defs){
994 // We should collect data, runtime, etc and store in the file specified
996 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1000 case "/linkresource":
1002 Report.Error (5, arg + " requires an argument");
1003 Environment.Exit (1);
1005 if (resources == null)
1006 resources = new ArrayList ();
1008 resources.Add (value);
1016 Environment.Exit (1);
1018 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1020 ProcessStartInfo pi = new ProcessStartInfo ();
1021 pi.FileName = "pkg-config";
1022 pi.RedirectStandardOutput = true;
1023 pi.UseShellExecute = false;
1024 pi.Arguments = "--libs " + packages;
1027 p = Process.Start (pi);
1028 } catch (Exception e) {
1029 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1030 Environment.Exit (1);
1033 if (p.StandardOutput == null){
1034 Report.Warning (-27, "Specified package did not return any information");
1037 string pkgout = p.StandardOutput.ReadToEnd ();
1039 if (p.ExitCode != 0) {
1040 Report.Error (-27, "Error running pkg-config. Check the above output.");
1041 Environment.Exit (1);
1044 if (pkgout != null){
1045 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1046 Split (new Char [] { ' ', '\t'});
1047 args = AddArgs (args, xargs);
1057 Report.Error (5, "-resource requires an argument");
1058 Environment.Exit (1);
1060 if (embedded_resources == null)
1061 embedded_resources = new ArrayList ();
1063 if (embedded_resources.Contains (value)) {
1064 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1066 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1067 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1070 embedded_resources.Add (value);
1076 Report.Error (5, "-recurse requires an argument");
1077 Environment.Exit (1);
1079 CompileFiles (value, true);
1083 case "/reference": {
1085 Report.Error (5, "-reference requires an argument");
1086 Environment.Exit (1);
1089 string [] refs = value.Split (new char [] { ';', ',' });
1090 foreach (string r in refs){
1095 case "/addmodule": {
1097 Report.Error (5, arg + " requires an argument");
1098 Environment.Exit (1);
1101 string [] refs = value.Split (new char [] { ';', ',' });
1102 foreach (string r in refs){
1109 Report.Error (5, arg + " requires an argument");
1110 Environment.Exit (1);
1113 win32ResourceFile = value;
1116 case "/win32icon": {
1118 Report.Error (5, arg + " requires an argument");
1119 Environment.Exit (1);
1122 win32IconFile = value;
1127 Report.Error (2006, arg + " requires an argument");
1128 Environment.Exit (1);
1130 RootContext.Documentation = new Documentation (value);
1137 Report.Error (5, "/lib requires an argument");
1138 Environment.Exit (1);
1141 libdirs = value.Split (new Char [] { ',' });
1142 foreach (string dir in libdirs)
1143 link_paths.Add (dir);
1148 want_debugging_support = false;
1153 want_debugging_support = true;
1158 RootContext.Checked = true;
1162 RootContext.Checked = false;
1170 RootContext.VerifyClsCompliance = false;
1175 RootContext.Unsafe = true;
1179 RootContext.Unsafe = false;
1182 case "/warnaserror":
1183 case "/warnaserror+":
1184 Report.WarningsAreErrors = true;
1187 case "/warnaserror-":
1188 Report.WarningsAreErrors = false;
1192 SetWarningLevel (value);
1199 Report.Error (5, "/nowarn requires an argument");
1200 Environment.Exit (1);
1203 warns = value.Split (new Char [] {','});
1204 foreach (string wc in warns){
1206 int warn = Int32.Parse (wc);
1208 throw new ArgumentOutOfRangeException("warn");
1210 Report.SetIgnoreWarning (warn);
1212 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1219 load_default_config = true;
1224 load_default_config = false;
1229 Environment.Exit(0);
1235 Environment.Exit (0);
1241 Report.Error (5, arg + " requires an argument");
1242 Environment.Exit (1);
1244 RootContext.MainClass = value;
1249 RootContext.StdLib = false;
1253 RootContext.StdLib = true;
1260 if (value == String.Empty) {
1261 Report.Error (5, arg + " requires an argument");
1262 Environment.Exit (1);
1264 RootContext.StrongNameKeyFile = value;
1266 case "/keycontainer":
1267 if (value == String.Empty) {
1268 Report.Error (5, arg + " requires an argument");
1269 Environment.Exit (1);
1271 RootContext.StrongNameKeyContainer = value;
1274 RootContext.StrongNameDelaySign = true;
1277 RootContext.StrongNameDelaySign = false;
1282 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1286 case "/langversion":
1287 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1289 RootContext.Version = LanguageVersion.ISO_1;
1296 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1302 if (value == "utf8"){
1303 encoding = new UTF8Encoding();
1304 using_default_encoder = false;
1307 if (value == "reset"){
1309 // 28591 is the code page for ISO-8859-1 encoding.
1312 using_default_encoder = true;
1316 cp = Int32.Parse (value);
1317 encoding = Encoding.GetEncoding (cp);
1318 using_default_encoder = false;
1320 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1324 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1325 //Environment.Exit (1);
1329 static string [] AddArgs (string [] args, string [] extra_args)
1332 new_args = new string [extra_args.Length + args.Length];
1334 // if args contains '--' we have to take that into account
1335 // split args into first half and second half based on '--'
1336 // and add the extra_args before --
1337 int split_position = Array.IndexOf (args, "--");
1338 if (split_position != -1)
1340 Array.Copy (args, new_args, split_position);
1341 extra_args.CopyTo (new_args, split_position);
1342 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1346 args.CopyTo (new_args, 0);
1347 extra_args.CopyTo (new_args, args.Length);
1354 /// Parses the arguments, and drives the compilation
1359 /// TODO: Mostly structured to debug the compiler
1360 /// now, needs to be turned into a real driver soon.
1362 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1363 internal static bool MainDriver (string [] args)
1366 bool parsing_options = true;
1369 encoding = Encoding.GetEncoding (28591);
1371 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1372 encoding = Encoding.GetEncoding (1252);
1375 references = new ArrayList ();
1376 soft_references = new ArrayList ();
1377 modules = new ArrayList ();
1378 link_paths = new ArrayList ();
1380 SetupDefaultDefines ();
1385 // This is not required because Assembly.Load knows about this
1389 Hashtable response_file_list = null;
1391 for (i = 0; i < args.Length; i++){
1392 string arg = args [i];
1396 if (arg.StartsWith ("@")){
1397 string [] extra_args;
1398 string response_file = arg.Substring (1);
1400 if (response_file_list == null)
1401 response_file_list = new Hashtable ();
1403 if (response_file_list.Contains (response_file)){
1405 1515, "Response file `" + response_file +
1406 "' specified multiple times");
1407 Environment.Exit (1);
1410 response_file_list.Add (response_file, response_file);
1412 extra_args = LoadArgs (response_file);
1413 if (extra_args == null){
1414 Report.Error (2011, "Unable to open response file: " +
1419 args = AddArgs (args, extra_args);
1423 if (parsing_options){
1425 parsing_options = false;
1429 if (arg.StartsWith ("-")){
1430 if (UnixParseOption (arg, ref args, ref i))
1434 string csc_opt = "/" + arg.Substring (1);
1435 if (CSCParseOption (csc_opt, ref args, ref i))
1438 if (arg.StartsWith ("/")){
1439 if (CSCParseOption (arg, ref args, ref i))
1445 CompileFiles (arg, false);
1454 // This will point to the NamespaceEntry of the last file that was parsed, and may
1455 // not be meaningful when resolving classes from other files. So, reset it to prevent
1458 RootContext.Tree.Types.NamespaceEntry = null;
1461 // If we are an exe, require a source file for the entry point
1463 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1464 if (first_source == null){
1465 Report.Error (2008, "No files to compile were specified");
1472 // If there is nothing to put in the assembly, and we are not a library
1474 if (first_source == null && embedded_resources == null && resources == null){
1475 Report.Error (2008, "No files to compile were specified");
1479 if (Report.Errors > 0)
1486 // Load Core Library for default compilation
1488 if (RootContext.StdLib)
1489 references.Insert (0, "mscorlib");
1491 if (load_default_config)
1492 DefineDefaultConfig ();
1494 if (Report.Errors > 0){
1499 // Load assemblies required
1502 ShowTime ("Loading references");
1503 link_paths.Add (GetSystemDir ());
1504 link_paths.Add (Directory.GetCurrentDirectory ());
1508 ShowTime (" References loaded");
1510 if (Report.Errors > 0){
1517 if (output_file == null){
1518 int pos = first_source.LastIndexOf ('.');
1521 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1523 output_file = first_source + RootContext.TargetExt;
1526 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1529 if (RootContext.Target == Target.Module) {
1530 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1531 if (module_only == null) {
1532 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1533 Environment.Exit (1);
1536 MethodInfo set_method = module_only.GetSetMethod (true);
1537 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1540 TypeManager.AddModule (CodeGen.Module.Builder);
1542 if (modules.Count > 0) {
1543 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1544 if (adder_method == null) {
1545 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1546 Environment.Exit (1);
1549 foreach (string module in modules)
1550 LoadModule (adder_method, module);
1553 TypeManager.ComputeNamespaces ();
1556 // Before emitting, we need to get the core
1557 // types emitted from the user defined types
1558 // or from the system ones.
1561 ShowTime ("Initializing Core Types");
1562 if (!RootContext.StdLib){
1563 RootContext.ResolveCore ();
1564 if (Report.Errors > 0)
1568 TypeManager.InitCoreTypes ();
1570 ShowTime (" Core Types done");
1572 CodeGen.Module.ResolveAttributes ();
1575 // The second pass of the compiler
1578 ShowTime ("Resolving tree");
1579 RootContext.ResolveTree ();
1581 if (Report.Errors > 0)
1584 ShowTime ("Populate tree");
1585 if (!RootContext.StdLib)
1586 RootContext.BootCorlib_PopulateCoreTypes ();
1587 RootContext.PopulateTypes ();
1589 TypeManager.InitCodeHelpers ();
1591 RootContext.DefineTypes ();
1593 if (RootContext.Documentation != null &&
1594 !RootContext.Documentation.OutputDocComment (
1599 // Verify using aliases now
1601 Namespace.VerifyUsing ();
1603 if (Report.Errors > 0){
1607 if (RootContext.VerifyClsCompliance) {
1608 CodeGen.Assembly.ResolveClsCompliance ();
1609 if (CodeGen.Assembly.IsClsCompliant) {
1610 AttributeTester.VerifyModulesClsCompliance ();
1611 TypeManager.LoadAllImportedTypes ();
1612 AttributeTester.VerifyTopLevelNameClsCompliance ();
1615 if (Report.Errors > 0)
1619 // The code generator
1622 ShowTime ("Emitting code");
1623 ShowTotalTime ("Total so far");
1624 RootContext.EmitCode ();
1628 if (Report.Errors > 0){
1633 ShowTime ("Closing types");
1635 RootContext.CloseTypes ();
1637 PEFileKinds k = PEFileKinds.ConsoleApplication;
1639 switch (RootContext.Target) {
1640 case Target.Library:
1642 k = PEFileKinds.Dll; break;
1644 k = PEFileKinds.ConsoleApplication; break;
1646 k = PEFileKinds.WindowApplication; break;
1649 if (RootContext.NeedsEntryPoint) {
1650 MethodInfo ep = RootContext.EntryPoint;
1653 if (RootContext.MainClass != null) {
1654 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1655 if (main_cont == null) {
1656 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1660 if (!(main_cont is ClassOrStruct)) {
1661 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1665 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1669 if (Report.Errors == 0)
1670 Report.Error (5001, "Program " + output_file +
1671 " does not have an entry point defined");
1675 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1676 } else if (RootContext.MainClass != null) {
1677 Report.Error (2017, "Can not specify -main: when building module or library");
1681 // Add the resources
1683 if (resources != null){
1684 foreach (string spec in resources){
1688 cp = spec.IndexOf (',');
1690 file = spec.Substring (0, cp);
1691 res = spec.Substring (cp + 1);
1695 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1699 if (embedded_resources != null){
1700 object[] margs = new object [2];
1701 Type[] argst = new Type [2];
1702 argst [0] = argst [1] = typeof (string);
1704 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1705 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1706 null, CallingConventions.Any, argst, null);
1708 if (embed_res == null) {
1709 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1711 foreach (string spec in embedded_resources) {
1714 cp = spec.IndexOf (',');
1716 margs [0] = spec.Substring (cp + 1);
1717 margs [1] = spec.Substring (0, cp);
1720 margs [0] = Path.GetFileName (spec);
1723 if (File.Exists ((string) margs [1]))
1724 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1726 Report.Error (1566, "Can not find the resource " + margs [1]);
1733 // Add Win32 resources
1736 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1738 if (win32ResourceFile != null) {
1740 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1742 catch (ArgumentException) {
1743 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1747 if (win32IconFile != null) {
1748 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1749 if (define_icon == null) {
1750 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1752 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1755 if (Report.Errors > 0)
1758 CodeGen.Save (output_file);
1760 ShowTime ("Saved output");
1761 ShowTotalTime ("Total");
1764 Timer.ShowTimers ();
1766 if (Report.ExpectedError != 0){
1767 if (Report.Errors == 0) {
1768 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1769 "No other errors reported.");
1771 Environment.Exit (2);
1773 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1774 "However, other errors were reported.");
1776 Environment.Exit (1);
1784 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1785 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1787 return (Report.Errors == 0);
1792 // This is the only public entry point
1794 public class CompilerCallableEntryPoint : MarshalByRefObject {
1795 public static bool InvokeCompiler (string [] args, TextWriter error)
1797 Report.Stderr = error;
1799 return Driver.MainDriver (args) && Report.Errors == 0;
1802 Report.Stderr = Console.Error;
1807 static void Reset ()
1811 RootContext.Reset ();
1813 TypeManager.Reset ();
1814 TypeHandle.Reset ();