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;
97 static Encoding encoding;
99 static public void Reset ()
101 want_debugging_support = false;
105 show_counters = false;
106 load_default_config = true;
107 resources = embedded_resources = null;
108 win32ResourceFile = win32IconFile = null;
115 public static void ShowTime (string msg)
120 DateTime now = DateTime.Now;
121 TimeSpan span = now - last_time;
125 "[{0:00}:{1:000}] {2}",
126 (int) span.TotalSeconds, span.Milliseconds, msg);
129 public static void ShowTotalTime (string msg)
134 DateTime now = DateTime.Now;
135 TimeSpan span = now - first_time;
139 "[{0:00}:{1:000}] {2}",
140 (int) span.TotalSeconds, span.Milliseconds, msg);
143 static void tokenize_file (SourceFile file)
148 input = File.OpenRead (file.Name);
150 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
155 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
156 Tokenizer lexer = new Tokenizer (reader, file, defines);
157 int token, tokens = 0, errors = 0;
159 while ((token = lexer.token ()) != Token.EOF){
161 if (token == Token.ERROR)
164 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
170 // MonoTODO("Change error code for aborted compilation to something reasonable")]
171 static void parse (SourceFile file)
177 input = File.OpenRead (file.Name);
179 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
183 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
185 parser = new CSharpParser (reader, file, defines);
186 parser.ErrorOutput = Report.Stderr;
189 } catch (Exception ex) {
190 Report.Error(666, "Compilation aborted: " + ex);
196 static void OtherFlags ()
199 "Other flags in the compiler\n" +
200 " --fatal Makes errors fatal\n" +
201 " --parse Only parses the source file\n" +
202 " --stacktrace Shows stack trace at error location\n" +
203 " --timestamp Displays time stamps of various compiler events\n" +
204 " --expect-error X Expect that error X will be encountered\n" +
205 " -2 Enables experimental C# features\n" +
206 " -v Verbose parsing (for debugging the parser)\n" +
207 " --mcs-debug X Sets MCS debugging level to X\n");
213 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
214 "mcs [options] source-files\n" +
215 " --about About the Mono C# compiler\n" +
216 " -addmodule:MODULE Adds the module to the generated assembly\n" +
217 " -checked[+|-] Set default context to checked\n" +
218 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
219 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
220 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
221 " -debug[+|-], -g Generate debugging information\n" +
222 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
223 " -doc:FILE XML Documentation file to generate\n" +
224 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
225 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
226 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
227 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
228 " -main:class Specified the class that contains the entry point\n" +
229 " -noconfig[+|-] Disables implicit references to assemblies\n" +
230 " -nostdlib[+|-] Does not load core libraries\n" +
231 " -nowarn:W1[,W2] Disables one or more warnings\n" +
232 " -optimize[+|-] Enables code optimalizations\n" +
233 " -out:FNAME Specifies output file\n" +
234 " -pkg:P1[,Pn] References packages P1..Pn\n" +
235 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
236 " -reference:ASS References the specified assembly (-r:ASS)\n" +
237 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
238 " library, module), (short: /t:)\n" +
239 " -unsafe[+|-] Allows unsafe code\n" +
240 " -warnaserror[+|-] Treat warnings as errors\n" +
241 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
242 " -help2 Show other help flags\n" +
245 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
246 " -resource:FILE[,ID] Embed FILE as a resource\n" +
247 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
248 " -win32icon:FILE Use this icon for the output\n" +
249 " @file Read response file for more options\n\n" +
250 "Options can be of the form -option or /option");
253 static void TargetUsage ()
255 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
261 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
262 "The compiler source code is released under the terms of the GNU GPL\n\n" +
264 "For more information on Mono, visit the project Web site\n" +
265 " http://www.go-mono.com\n\n" +
267 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
268 Environment.Exit (0);
271 public static int counter1, counter2;
273 public static int Main (string[] args)
275 RootContext.Version = LanguageVersion.Default;
276 bool ok = MainDriver (args);
278 if (ok && Report.Errors == 0) {
279 if (Report.Warnings > 0) {
280 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
283 Console.WriteLine ("Counter1: " + counter1);
284 Console.WriteLine ("Counter2: " + counter2);
290 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
291 Report.Errors, Report.Warnings);
296 static public void LoadAssembly (string assembly, bool soft)
299 string total_log = "";
302 char[] path_chars = { '/', '\\' };
304 if (assembly.IndexOfAny (path_chars) != -1) {
305 a = Assembly.LoadFrom (assembly);
307 string ass = assembly;
308 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
309 ass = assembly.Substring (0, assembly.Length - 4);
310 a = Assembly.Load (ass);
312 TypeManager.AddAssembly (a);
314 } catch (FileNotFoundException){
315 foreach (string dir in link_paths){
316 string full_path = Path.Combine (dir, assembly);
317 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
321 a = Assembly.LoadFrom (full_path);
322 TypeManager.AddAssembly (a);
324 } catch (FileNotFoundException ff) {
325 total_log += ff.FusionLog;
330 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
331 Console.WriteLine ("Log: \n" + total_log);
333 } catch (BadImageFormatException f) {
334 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
335 } catch (FileLoadException f){
336 Report.Error(6, "Cannot load assembly " + f.FusionLog);
337 } catch (ArgumentNullException){
338 Report.Error(6, "Cannot load assembly (null argument)");
342 static public void LoadModule (MethodInfo adder_method, string module)
345 string total_log = "";
349 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
351 catch (TargetInvocationException ex) {
352 throw ex.InnerException;
354 TypeManager.AddModule (m);
357 catch (FileNotFoundException){
358 foreach (string dir in link_paths){
359 string full_path = Path.Combine (dir, module);
360 if (!module.EndsWith (".netmodule"))
361 full_path += ".netmodule";
365 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
367 catch (TargetInvocationException ex) {
368 throw ex.InnerException;
370 TypeManager.AddModule (m);
372 } catch (FileNotFoundException ff) {
373 total_log += ff.FusionLog;
377 Report.Error (6, "Cannot find module `" + module + "'" );
378 Console.WriteLine ("Log: \n" + total_log);
379 } catch (BadImageFormatException f) {
380 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
381 } catch (FileLoadException f){
382 Report.Error(6, "Cannot load module " + f.FusionLog);
383 } catch (ArgumentNullException){
384 Report.Error(6, "Cannot load module (null argument)");
389 /// Loads all assemblies referenced on the command line
391 static public void LoadReferences ()
393 foreach (string r in references)
394 LoadAssembly (r, false);
396 foreach (string r in soft_references)
397 LoadAssembly (r, true);
402 static void SetupDefaultDefines ()
404 defines = new ArrayList ();
405 defines.Add ("__MonoCS__");
408 static string [] LoadArgs (string file)
411 ArrayList args = new ArrayList ();
414 f = new StreamReader (file);
419 StringBuilder sb = new StringBuilder ();
421 while ((line = f.ReadLine ()) != null){
424 for (int i = 0; i < t; i++){
427 if (c == '"' || c == '\''){
430 for (i++; i < t; i++){
437 } else if (c == ' '){
439 args.Add (sb.ToString ());
446 args.Add (sb.ToString ());
451 string [] ret_value = new string [args.Count];
452 args.CopyTo (ret_value, 0);
458 // Returns the directory where the system assemblies are installed
460 static string GetSystemDir ()
462 return Path.GetDirectoryName (typeof (object).Assembly.Location);
466 // Given a path specification, splits the path from the file/pattern
468 static void SplitPathAndPattern (string spec, out string path, out string pattern)
470 int p = spec.LastIndexOf ('/');
473 // Windows does not like /file.cs, switch that to:
478 pattern = spec.Substring (1);
480 path = spec.Substring (0, p);
481 pattern = spec.Substring (p + 1);
486 p = spec.LastIndexOf ('\\');
488 path = spec.Substring (0, p);
489 pattern = spec.Substring (p + 1);
497 static void ProcessFile (string f)
499 if (first_source == null)
502 Location.AddFile (f);
505 static void ProcessFiles ()
507 Location.Initialize ();
509 foreach (SourceFile file in Location.SourceFiles) {
511 tokenize_file (file);
518 static void CompileFiles (string spec, bool recurse)
520 string path, pattern;
522 SplitPathAndPattern (spec, out path, out pattern);
523 if (pattern.IndexOf ('*') == -1){
528 string [] files = null;
530 files = Directory.GetFiles (path, pattern);
531 } catch (System.IO.DirectoryNotFoundException) {
532 Report.Error (2001, "Source file `" + spec + "' could not be found");
534 } catch (System.IO.IOException){
535 Report.Error (2001, "Source file `" + spec + "' could not be found");
538 foreach (string f in files) {
545 string [] dirs = null;
548 dirs = Directory.GetDirectories (path);
552 foreach (string d in dirs) {
554 // Don't include path in this string, as each
555 // directory entry already does
556 CompileFiles (d + "/" + pattern, true);
560 static void DefineDefaultConfig ()
563 // For now the "default config" is harcoded into the compiler
564 // we can move this outside later
566 string [] default_config = {
571 // Is it worth pre-loading all this stuff?
574 "System.Configuration.Install",
577 "System.DirectoryServices",
578 "System.Drawing.Design",
580 "System.EnterpriseServices",
583 "System.Runtime.Remoting",
584 "System.Runtime.Serialization.Formatters.Soap",
586 "System.ServiceProcess",
588 "System.Web.RegularExpressions",
589 "System.Web.Services",
590 "System.Windows.Forms"
595 foreach (string def in default_config)
596 soft_references.Insert (p++, def);
599 public static string OutputFile
605 return Path.GetFileName (output_file);
609 static void SetWarningLevel (string s)
614 level = Int32.Parse (s);
617 if (level < 0 || level > 4){
618 Report.Error (1900, "Warning level must be in the range 0-4");
621 RootContext.WarningLevel = level;
624 static void SetupV2 ()
626 RootContext.Version = LanguageVersion.Default;
627 defines.Add ("__V2__");
630 static void Version ()
632 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
633 Console.WriteLine ("Mono C# compiler version {0}", version);
634 Environment.Exit (0);
638 // Currently handles the Unix-like command line options, but will be
639 // deprecated in favor of the CSCParseOption, which will also handle the
640 // options that start with a dash in the future.
642 static bool UnixParseOption (string arg, ref string [] args, ref int i)
646 CSharpParser.yacc_verbose_flag++;
657 case "--main": case "-m":
658 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
659 if ((i + 1) >= args.Length){
661 Environment.Exit (1);
663 RootContext.MainClass = args [++i];
667 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
668 RootContext.Unsafe = true;
671 case "/?": case "/h": case "/help":
674 Environment.Exit (0);
678 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
679 if ((i + 1) >= args.Length){
681 Environment.Exit (1);
683 defines.Add (args [++i]);
686 case "--show-counters":
687 show_counters = true;
690 case "--expect-error": {
695 args [++i], NumberStyles.AllowLeadingSign);
696 Report.ExpectedError = code;
698 Report.Error (-14, "Invalid number specified");
709 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
710 if ((i + 1) >= args.Length){
712 Environment.Exit (1);
714 OutputFile = args [++i];
718 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
719 RootContext.Checked = true;
723 Report.Stacktrace = true;
726 case "--linkresource":
728 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
729 if ((i + 1) >= args.Length){
731 Report.Error (5, "Missing argument to --linkres");
732 Environment.Exit (1);
734 if (resources == null)
735 resources = new ArrayList ();
737 resources.Add (args [++i]);
742 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
743 if ((i + 1) >= args.Length){
745 Report.Error (5, "Missing argument to --resource");
746 Environment.Exit (1);
748 if (embedded_resources == null)
749 embedded_resources = new ArrayList ();
751 embedded_resources.Add (args [++i]);
755 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
756 if ((i + 1) >= args.Length){
757 Environment.Exit (1);
761 string type = args [++i];
764 RootContext.Target = Target.Library;
765 RootContext.TargetExt = ".dll";
769 RootContext.Target = Target.Exe;
773 RootContext.Target = Target.WinExe;
777 RootContext.Target = Target.Module;
778 RootContext.TargetExt = ".dll";
787 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
788 if ((i + 1) >= args.Length){
790 Environment.Exit (1);
793 references.Add (args [++i]);
797 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
798 if ((i + 1) >= args.Length){
800 Environment.Exit (1);
802 link_paths.Add (args [++i]);
806 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
807 RootContext.StdLib = false;
815 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
816 Report.WarningsAreErrors = true;
820 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
821 if ((i + 1) >= args.Length){
823 Environment.Exit (1);
828 warn = Int32.Parse (args [++i]);
831 Environment.Exit (1);
833 Report.SetIgnoreWarning (warn);
837 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
838 if ((i + 1) >= args.Length){
841 "--wlevel requires a value from 0 to 4");
842 Environment.Exit (1);
845 SetWarningLevel (args [++i]);
849 if ((i + 1) >= args.Length){
850 Report.Error (5, "--mcs-debug requires an argument");
851 Environment.Exit (1);
855 Report.DebugFlags = Int32.Parse (args [++i]);
857 Report.Error (5, "Invalid argument to --mcs-debug");
858 Environment.Exit (1);
867 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
868 if ((i + 1) >= args.Length){
869 Report.Error (5, "--recurse requires an argument");
870 Environment.Exit (1);
872 CompileFiles (args [++i], true);
877 last_time = first_time = DateTime.Now;
884 case "--debug": case "-g":
885 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
886 want_debugging_support = true;
890 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
891 load_default_config = false;
899 // This parses the -arg and /arg options to the compiler, even if the strings
900 // in the following text use "/arg" on the strings.
902 static bool CSCParseOption (string option, ref string [] args, ref int i)
904 int idx = option.IndexOf (':');
911 arg = option.Substring (0, idx);
913 value = option.Substring (idx + 1);
924 RootContext.Target = Target.Exe;
928 RootContext.Target = Target.WinExe;
932 RootContext.Target = Target.Library;
933 RootContext.TargetExt = ".dll";
937 RootContext.Target = Target.Module;
938 RootContext.TargetExt = ".netmodule";
950 Environment.Exit (1);
957 RootContext.Optimize = true;
961 RootContext.Optimize = false;
965 case "/incremental+":
966 case "/incremental-":
976 Environment.Exit (1);
979 defs = value.Split (new Char [] {';', ','});
980 foreach (string d in defs){
988 // We should collect data, runtime, etc and store in the file specified
990 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
994 case "/linkresource":
996 Report.Error (5, arg + " requires an argument");
997 Environment.Exit (1);
999 if (resources == null)
1000 resources = new ArrayList ();
1002 resources.Add (value);
1010 Environment.Exit (1);
1012 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1014 ProcessStartInfo pi = new ProcessStartInfo ();
1015 pi.FileName = "pkg-config";
1016 pi.RedirectStandardOutput = true;
1017 pi.UseShellExecute = false;
1018 pi.Arguments = "--libs " + packages;
1021 p = Process.Start (pi);
1022 } catch (Exception e) {
1023 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1024 Environment.Exit (1);
1027 if (p.StandardOutput == null){
1028 Report.Warning (-27, "Specified package did not return any information");
1031 string pkgout = p.StandardOutput.ReadToEnd ();
1033 if (p.ExitCode != 0) {
1034 Report.Error (-27, "Error running pkg-config. Check the above output.");
1035 Environment.Exit (1);
1038 if (pkgout != null){
1039 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1040 Split (new Char [] { ' ', '\t'});
1041 args = AddArgs (args, xargs);
1051 Report.Error (5, "-resource requires an argument");
1052 Environment.Exit (1);
1054 if (embedded_resources == null)
1055 embedded_resources = new ArrayList ();
1057 if (embedded_resources.Contains (value)) {
1058 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1060 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1061 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1064 embedded_resources.Add (value);
1070 Report.Error (5, "-recurse requires an argument");
1071 Environment.Exit (1);
1073 CompileFiles (value, true);
1077 case "/reference": {
1079 Report.Error (5, "-reference requires an argument");
1080 Environment.Exit (1);
1083 string [] refs = value.Split (new char [] { ';', ',' });
1084 foreach (string r in refs){
1089 case "/addmodule": {
1091 Report.Error (5, arg + " requires an argument");
1092 Environment.Exit (1);
1095 string [] refs = value.Split (new char [] { ';', ',' });
1096 foreach (string r in refs){
1103 Report.Error (5, arg + " requires an argument");
1104 Environment.Exit (1);
1107 win32ResourceFile = value;
1110 case "/win32icon": {
1112 Report.Error (5, arg + " requires an argument");
1113 Environment.Exit (1);
1116 win32IconFile = value;
1121 Report.Error (2006, arg + " requires an argument");
1122 Environment.Exit (1);
1124 RootContext.Documentation = new Documentation (value);
1131 Report.Error (5, "/lib requires an argument");
1132 Environment.Exit (1);
1135 libdirs = value.Split (new Char [] { ',' });
1136 foreach (string dir in libdirs)
1137 link_paths.Add (dir);
1142 want_debugging_support = false;
1147 want_debugging_support = true;
1152 RootContext.Checked = true;
1156 RootContext.Checked = false;
1164 RootContext.VerifyClsCompliance = false;
1169 RootContext.Unsafe = true;
1173 RootContext.Unsafe = false;
1176 case "/warnaserror":
1177 case "/warnaserror+":
1178 Report.WarningsAreErrors = true;
1181 case "/warnaserror-":
1182 Report.WarningsAreErrors = false;
1186 SetWarningLevel (value);
1193 Report.Error (5, "/nowarn requires an argument");
1194 Environment.Exit (1);
1197 warns = value.Split (new Char [] {','});
1198 foreach (string wc in warns){
1200 int warn = Int32.Parse (wc);
1202 throw new ArgumentOutOfRangeException("warn");
1204 Report.SetIgnoreWarning (warn);
1206 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1213 load_default_config = true;
1218 load_default_config = false;
1223 Environment.Exit(0);
1229 Environment.Exit (0);
1235 Report.Error (5, arg + " requires an argument");
1236 Environment.Exit (1);
1238 RootContext.MainClass = value;
1243 RootContext.StdLib = false;
1247 RootContext.StdLib = true;
1254 if (value == String.Empty) {
1255 Report.Error (5, arg + " requires an argument");
1256 Environment.Exit (1);
1258 RootContext.StrongNameKeyFile = value;
1260 case "/keycontainer":
1261 if (value == String.Empty) {
1262 Report.Error (5, arg + " requires an argument");
1263 Environment.Exit (1);
1265 RootContext.StrongNameKeyContainer = value;
1268 RootContext.StrongNameDelaySign = true;
1271 RootContext.StrongNameDelaySign = false;
1276 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1280 case "/langversion":
1281 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1283 RootContext.Version = LanguageVersion.ISO_1;
1290 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1296 encoding = new UTF8Encoding();
1299 encoding = Encoding.Default;
1303 encoding = Encoding.GetEncoding (
1304 Int32.Parse (value));
1306 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1312 //Report.Error (2007, String.Format ("Unrecognized command-line option: `{0}'", option));
1313 //Environment.Exit (1);
1317 static string [] AddArgs (string [] args, string [] extra_args)
1320 new_args = new string [extra_args.Length + args.Length];
1322 // if args contains '--' we have to take that into account
1323 // split args into first half and second half based on '--'
1324 // and add the extra_args before --
1325 int split_position = Array.IndexOf (args, "--");
1326 if (split_position != -1)
1328 Array.Copy (args, new_args, split_position);
1329 extra_args.CopyTo (new_args, split_position);
1330 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1334 args.CopyTo (new_args, 0);
1335 extra_args.CopyTo (new_args, args.Length);
1342 /// Parses the arguments, and drives the compilation
1347 /// TODO: Mostly structured to debug the compiler
1348 /// now, needs to be turned into a real driver soon.
1350 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1351 internal static bool MainDriver (string [] args)
1354 bool parsing_options = true;
1356 encoding = Encoding.Default;
1358 references = new ArrayList ();
1359 soft_references = new ArrayList ();
1360 modules = new ArrayList ();
1361 link_paths = new ArrayList ();
1363 SetupDefaultDefines ();
1368 // This is not required because Assembly.Load knows about this
1372 Hashtable response_file_list = null;
1374 for (i = 0; i < args.Length; i++){
1375 string arg = args [i];
1379 if (arg.StartsWith ("@")){
1380 string [] extra_args;
1381 string response_file = arg.Substring (1);
1383 if (response_file_list == null)
1384 response_file_list = new Hashtable ();
1386 if (response_file_list.Contains (response_file)){
1388 1515, "Response file `" + response_file +
1389 "' specified multiple times");
1390 Environment.Exit (1);
1393 response_file_list.Add (response_file, response_file);
1395 extra_args = LoadArgs (response_file);
1396 if (extra_args == null){
1397 Report.Error (2011, "Unable to open response file: " +
1402 args = AddArgs (args, extra_args);
1406 if (parsing_options){
1408 parsing_options = false;
1412 if (arg.StartsWith ("-")){
1413 if (UnixParseOption (arg, ref args, ref i))
1417 string csc_opt = "/" + arg.Substring (1);
1418 if (CSCParseOption (csc_opt, ref args, ref i))
1421 if (arg.StartsWith ("/")){
1422 if (CSCParseOption (arg, ref args, ref i))
1428 CompileFiles (arg, false);
1437 // This will point to the NamespaceEntry of the last file that was parsed, and may
1438 // not be meaningful when resolving classes from other files. So, reset it to prevent
1441 RootContext.Tree.Types.NamespaceEntry = null;
1444 // If we are an exe, require a source file for the entry point
1446 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1447 if (first_source == null){
1448 Report.Error (2008, "No files to compile were specified");
1455 // If there is nothing to put in the assembly, and we are not a library
1457 if (first_source == null && embedded_resources == null && resources == null){
1458 Report.Error (2008, "No files to compile were specified");
1462 if (Report.Errors > 0)
1469 // Load Core Library for default compilation
1471 if (RootContext.StdLib)
1472 references.Insert (0, "mscorlib");
1474 if (load_default_config)
1475 DefineDefaultConfig ();
1477 if (Report.Errors > 0){
1482 // Load assemblies required
1485 ShowTime ("Loading references");
1486 link_paths.Add (GetSystemDir ());
1487 link_paths.Add (Directory.GetCurrentDirectory ());
1491 ShowTime (" References loaded");
1493 if (Report.Errors > 0){
1500 if (output_file == null){
1501 int pos = first_source.LastIndexOf ('.');
1504 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1506 output_file = first_source + RootContext.TargetExt;
1509 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1512 if (RootContext.Target == Target.Module) {
1513 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1514 if (module_only == null) {
1515 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1516 Environment.Exit (1);
1519 MethodInfo set_method = module_only.GetSetMethod (true);
1520 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1523 TypeManager.AddModule (CodeGen.Module.Builder);
1525 if (modules.Count > 0) {
1526 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1527 if (adder_method == null) {
1528 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1529 Environment.Exit (1);
1532 foreach (string module in modules)
1533 LoadModule (adder_method, module);
1536 TypeManager.ComputeNamespaces ();
1539 // Before emitting, we need to get the core
1540 // types emitted from the user defined types
1541 // or from the system ones.
1544 ShowTime ("Initializing Core Types");
1545 if (!RootContext.StdLib){
1546 RootContext.ResolveCore ();
1547 if (Report.Errors > 0)
1551 TypeManager.InitCoreTypes ();
1553 ShowTime (" Core Types done");
1555 CodeGen.Module.ResolveAttributes ();
1558 // The second pass of the compiler
1561 ShowTime ("Resolving tree");
1562 RootContext.ResolveTree ();
1564 if (Report.Errors > 0)
1567 ShowTime ("Populate tree");
1568 if (!RootContext.StdLib)
1569 RootContext.BootCorlib_PopulateCoreTypes ();
1570 RootContext.PopulateTypes ();
1572 TypeManager.InitCodeHelpers ();
1574 RootContext.DefineTypes ();
1576 if (RootContext.Documentation != null &&
1577 !RootContext.Documentation.OutputDocComment (
1582 // Verify using aliases now
1584 Namespace.VerifyUsing ();
1586 if (Report.Errors > 0){
1590 if (RootContext.VerifyClsCompliance) {
1591 CodeGen.Assembly.ResolveClsCompliance ();
1592 if (CodeGen.Assembly.IsClsCompliant) {
1593 AttributeTester.VerifyModulesClsCompliance ();
1594 TypeManager.LoadAllImportedTypes ();
1595 AttributeTester.VerifyTopLevelNameClsCompliance ();
1598 if (Report.Errors > 0)
1602 // The code generator
1605 ShowTime ("Emitting code");
1606 ShowTotalTime ("Total so far");
1607 RootContext.EmitCode ();
1611 if (Report.Errors > 0){
1616 ShowTime ("Closing types");
1618 RootContext.CloseTypes ();
1620 PEFileKinds k = PEFileKinds.ConsoleApplication;
1622 switch (RootContext.Target) {
1623 case Target.Library:
1625 k = PEFileKinds.Dll; break;
1627 k = PEFileKinds.ConsoleApplication; break;
1629 k = PEFileKinds.WindowApplication; break;
1632 if (RootContext.NeedsEntryPoint) {
1633 MethodInfo ep = RootContext.EntryPoint;
1636 if (RootContext.MainClass != null) {
1637 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1638 if (main_cont == null) {
1639 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1643 if (!(main_cont is ClassOrStruct)) {
1644 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1648 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1652 if (Report.Errors == 0)
1653 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1658 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1659 } else if (RootContext.MainClass != null) {
1660 Report.Error (2017, "Cannot specify -main if building a module or library");
1664 // Add the resources
1666 if (resources != null){
1667 foreach (string spec in resources){
1671 cp = spec.IndexOf (',');
1673 file = spec.Substring (0, cp);
1674 res = spec.Substring (cp + 1);
1678 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1682 if (embedded_resources != null){
1683 object[] margs = new object [2];
1684 Type[] argst = new Type [2];
1685 argst [0] = argst [1] = typeof (string);
1687 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1688 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1689 null, CallingConventions.Any, argst, null);
1691 if (embed_res == null) {
1692 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1694 foreach (string spec in embedded_resources) {
1697 cp = spec.IndexOf (',');
1699 margs [0] = spec.Substring (cp + 1);
1700 margs [1] = spec.Substring (0, cp);
1703 margs [0] = Path.GetFileName (spec);
1706 if (File.Exists ((string) margs [1]))
1707 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1709 Report.Error (1566, "Can not find the resource " + margs [1]);
1716 // Add Win32 resources
1719 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1721 if (win32ResourceFile != null) {
1723 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1725 catch (ArgumentException) {
1726 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1730 if (win32IconFile != null) {
1731 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1732 if (define_icon == null) {
1733 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1735 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1738 if (Report.Errors > 0)
1741 CodeGen.Save (output_file);
1743 ShowTime ("Saved output");
1744 ShowTotalTime ("Total");
1747 Timer.ShowTimers ();
1749 if (Report.ExpectedError != 0){
1750 if (Report.Errors == 0) {
1751 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1752 "No other errors reported.");
1754 Environment.Exit (2);
1756 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1757 "However, other errors were reported.");
1759 Environment.Exit (1);
1767 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1768 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1770 return (Report.Errors == 0);
1775 // This is the only public entry point
1777 public class CompilerCallableEntryPoint : MarshalByRefObject {
1778 public static bool InvokeCompiler (string [] args, TextWriter error)
1780 Report.Stderr = error;
1782 return Driver.MainDriver (args) && Report.Errors == 0;
1785 Report.Stderr = Console.Error;
1790 static void Reset ()
1794 RootContext.Reset ();
1796 TypeManager.Reset ();
1797 TypeHandle.Reset ();