2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004, 2005 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
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;
121 public static void ShowTime (string msg)
126 DateTime now = DateTime.Now;
127 TimeSpan span = now - last_time;
131 "[{0:00}:{1:000}] {2}",
132 (int) span.TotalSeconds, span.Milliseconds, msg);
135 public static void ShowTotalTime (string msg)
140 DateTime now = DateTime.Now;
141 TimeSpan span = now - first_time;
145 "[{0:00}:{1:000}] {2}",
146 (int) span.TotalSeconds, span.Milliseconds, msg);
149 static void tokenize_file (SourceFile file)
154 input = File.OpenRead (file.Name);
156 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
161 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
162 Tokenizer lexer = new Tokenizer (reader, file, defines);
163 int token, tokens = 0, errors = 0;
165 while ((token = lexer.token ()) != Token.EOF){
167 if (token == Token.ERROR)
170 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
176 // MonoTODO("Change error code for aborted compilation to something reasonable")]
177 static void parse (SourceFile file)
183 input = File.OpenRead (file.Name);
185 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
189 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
192 if (reader.Read () == 77 && reader.Read () == 90) {
193 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
199 parser = new CSharpParser (reader, file, defines);
200 parser.ErrorOutput = Report.Stderr;
203 } catch (Exception ex) {
204 Report.Error(666, "Compilation aborted: " + ex);
210 static void OtherFlags ()
213 "Other flags in the compiler\n" +
214 " --fatal Makes errors fatal\n" +
215 " --parse Only parses the source file\n" +
216 " --stacktrace Shows stack trace at error location\n" +
217 " --timestamp Displays time stamps of various compiler events\n" +
218 " --expect-error X Expect that error X will be encountered\n" +
219 " -2 Enables experimental C# features\n" +
220 " -v Verbose parsing (for debugging the parser)\n" +
221 " --mcs-debug X Sets MCS debugging level to X\n");
227 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
228 "mcs [options] source-files\n" +
229 " --about About the Mono C# compiler\n" +
230 " -addmodule:MODULE Adds the module to the generated assembly\n" +
231 " -checked[+|-] Set default context to checked\n" +
232 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
233 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
234 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
235 " -debug[+|-], -g Generate debugging information\n" +
236 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
237 " -doc:FILE XML Documentation file to generate\n" +
238 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
239 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
240 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
241 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
242 " -main:class Specified the class that contains the entry point\n" +
243 " -noconfig[+|-] Disables implicit references to assemblies\n" +
244 " -nostdlib[+|-] Does not load core libraries\n" +
245 " -nowarn:W1[,W2] Disables one or more warnings\n" +
246 " -optimize[+|-] Enables code optimalizations\n" +
247 " -out:FNAME Specifies output file\n" +
248 " -pkg:P1[,Pn] References packages P1..Pn\n" +
249 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
250 " -reference:ASS References the specified assembly (-r:ASS)\n" +
251 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
252 " library, module), (short: /t:)\n" +
253 " -unsafe[+|-] Allows unsafe code\n" +
254 " -warnaserror[+|-] Treat warnings as errors\n" +
255 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
256 " -help2 Show other help flags\n" +
259 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
260 " -resource:FILE[,ID] Embed FILE as a resource\n" +
261 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
262 " -win32icon:FILE Use this icon for the output\n" +
263 " @file Read response file for more options\n\n" +
264 "Options can be of the form -option or /option");
267 static void TargetUsage ()
269 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
275 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
276 "The compiler source code is released under the terms of the GNU GPL\n\n" +
278 "For more information on Mono, visit the project Web site\n" +
279 " http://www.go-mono.com\n\n" +
281 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
282 Environment.Exit (0);
285 public static int counter1, counter2;
287 public static int Main (string[] args)
289 bool ok = MainDriver (args);
291 if (ok && Report.Errors == 0) {
292 if (Report.Warnings > 0) {
293 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
296 Console.WriteLine ("Counter1: " + counter1);
297 Console.WriteLine ("Counter2: " + counter2);
303 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
304 Report.Errors, Report.Warnings);
309 static public void LoadAssembly (string assembly, bool soft)
312 string total_log = "";
315 char[] path_chars = { '/', '\\' };
317 if (assembly.IndexOfAny (path_chars) != -1) {
318 a = Assembly.LoadFrom (assembly);
320 string ass = assembly;
321 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
322 ass = assembly.Substring (0, assembly.Length - 4);
323 a = Assembly.Load (ass);
325 TypeManager.AddAssembly (a);
327 } catch (FileNotFoundException){
328 foreach (string dir in link_paths){
329 string full_path = Path.Combine (dir, assembly);
330 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
334 a = Assembly.LoadFrom (full_path);
335 TypeManager.AddAssembly (a);
337 } catch (FileNotFoundException ff) {
338 total_log += ff.FusionLog;
343 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
344 Console.WriteLine ("Log: \n" + total_log);
346 } catch (BadImageFormatException f) {
347 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
348 } catch (FileLoadException f){
349 Report.Error(6, "Cannot load assembly " + f.FusionLog);
350 } catch (ArgumentNullException){
351 Report.Error(6, "Cannot load assembly (null argument)");
355 static public void LoadModule (MethodInfo adder_method, string module)
358 string total_log = "";
362 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
364 catch (TargetInvocationException ex) {
365 throw ex.InnerException;
367 TypeManager.AddModule (m);
370 catch (FileNotFoundException){
371 foreach (string dir in link_paths){
372 string full_path = Path.Combine (dir, module);
373 if (!module.EndsWith (".netmodule"))
374 full_path += ".netmodule";
378 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
380 catch (TargetInvocationException ex) {
381 throw ex.InnerException;
383 TypeManager.AddModule (m);
385 } catch (FileNotFoundException ff) {
386 total_log += ff.FusionLog;
390 Report.Error (6, "Cannot find module `" + module + "'" );
391 Console.WriteLine ("Log: \n" + total_log);
392 } catch (BadImageFormatException f) {
393 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
394 } catch (FileLoadException f){
395 Report.Error(6, "Cannot load module " + f.FusionLog);
396 } catch (ArgumentNullException){
397 Report.Error(6, "Cannot load module (null argument)");
402 /// Loads all assemblies referenced on the command line
404 static public void LoadReferences ()
406 foreach (string r in references)
407 LoadAssembly (r, false);
409 foreach (string r in soft_references)
410 LoadAssembly (r, true);
415 static void SetupDefaultDefines ()
417 defines = new ArrayList ();
418 defines.Add ("__MonoCS__");
421 static string [] LoadArgs (string file)
424 ArrayList args = new ArrayList ();
427 f = new StreamReader (file);
432 StringBuilder sb = new StringBuilder ();
434 while ((line = f.ReadLine ()) != null){
437 for (int i = 0; i < t; i++){
440 if (c == '"' || c == '\''){
443 for (i++; i < t; i++){
450 } else if (c == ' '){
452 args.Add (sb.ToString ());
459 args.Add (sb.ToString ());
464 string [] ret_value = new string [args.Count];
465 args.CopyTo (ret_value, 0);
471 // Returns the directory where the system assemblies are installed
473 static string GetSystemDir ()
475 return Path.GetDirectoryName (typeof (object).Assembly.Location);
479 // Given a path specification, splits the path from the file/pattern
481 static void SplitPathAndPattern (string spec, out string path, out string pattern)
483 int p = spec.LastIndexOf ('/');
486 // Windows does not like /file.cs, switch that to:
491 pattern = spec.Substring (1);
493 path = spec.Substring (0, p);
494 pattern = spec.Substring (p + 1);
499 p = spec.LastIndexOf ('\\');
501 path = spec.Substring (0, p);
502 pattern = spec.Substring (p + 1);
510 static void ProcessFile (string f)
512 if (first_source == null)
515 Location.AddFile (f);
518 static void ProcessFiles ()
520 Location.Initialize ();
522 foreach (SourceFile file in Location.SourceFiles) {
524 tokenize_file (file);
531 static void CompileFiles (string spec, bool recurse)
533 string path, pattern;
535 SplitPathAndPattern (spec, out path, out pattern);
536 if (pattern.IndexOf ('*') == -1){
541 string [] files = null;
543 files = Directory.GetFiles (path, pattern);
544 } catch (System.IO.DirectoryNotFoundException) {
545 Report.Error (2001, "Source file `" + spec + "' could not be found");
547 } catch (System.IO.IOException){
548 Report.Error (2001, "Source file `" + spec + "' could not be found");
551 foreach (string f in files) {
558 string [] dirs = null;
561 dirs = Directory.GetDirectories (path);
565 foreach (string d in dirs) {
567 // Don't include path in this string, as each
568 // directory entry already does
569 CompileFiles (d + "/" + pattern, true);
573 static void DefineDefaultConfig ()
576 // For now the "default config" is harcoded into the compiler
577 // we can move this outside later
579 string [] default_config = {
584 // Is it worth pre-loading all this stuff?
587 "System.Configuration.Install",
590 "System.DirectoryServices",
591 "System.Drawing.Design",
593 "System.EnterpriseServices",
596 "System.Runtime.Remoting",
597 "System.Runtime.Serialization.Formatters.Soap",
599 "System.ServiceProcess",
601 "System.Web.RegularExpressions",
602 "System.Web.Services",
603 "System.Windows.Forms"
608 foreach (string def in default_config)
609 soft_references.Insert (p++, def);
612 public static string OutputFile
618 return Path.GetFileName (output_file);
622 static void SetWarningLevel (string s)
627 level = Int32.Parse (s);
630 if (level < 0 || level > 4){
631 Report.Error (1900, "Warning level must be in the range 0-4");
634 RootContext.WarningLevel = level;
637 static void SetupV2 ()
639 RootContext.Version = LanguageVersion.Default;
640 defines.Add ("__V2__");
643 static void Version ()
645 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
646 Console.WriteLine ("Mono C# compiler version {0}", version);
647 Environment.Exit (0);
651 // Currently handles the Unix-like command line options, but will be
652 // deprecated in favor of the CSCParseOption, which will also handle the
653 // options that start with a dash in the future.
655 static bool UnixParseOption (string arg, ref string [] args, ref int i)
659 CSharpParser.yacc_verbose_flag++;
670 case "--main": case "-m":
671 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
672 if ((i + 1) >= args.Length){
674 Environment.Exit (1);
676 RootContext.MainClass = args [++i];
680 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
681 RootContext.Unsafe = true;
684 case "/?": case "/h": case "/help":
687 Environment.Exit (0);
691 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
692 if ((i + 1) >= args.Length){
694 Environment.Exit (1);
696 defines.Add (args [++i]);
699 case "--show-counters":
700 show_counters = true;
703 case "--expect-error": {
708 args [++i], NumberStyles.AllowLeadingSign);
709 Report.ExpectedError = code;
711 Report.Error (-14, "Invalid number specified");
722 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
723 if ((i + 1) >= args.Length){
725 Environment.Exit (1);
727 OutputFile = args [++i];
731 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
732 RootContext.Checked = true;
736 Report.Stacktrace = true;
739 case "--linkresource":
741 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
742 if ((i + 1) >= args.Length){
744 Report.Error (5, "Missing argument to --linkres");
745 Environment.Exit (1);
747 if (resources == null)
748 resources = new ArrayList ();
750 resources.Add (args [++i]);
755 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
756 if ((i + 1) >= args.Length){
758 Report.Error (5, "Missing argument to --resource");
759 Environment.Exit (1);
761 if (embedded_resources == null)
762 embedded_resources = new ArrayList ();
764 embedded_resources.Add (args [++i]);
768 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
769 if ((i + 1) >= args.Length){
770 Environment.Exit (1);
774 string type = args [++i];
777 RootContext.Target = Target.Library;
778 RootContext.TargetExt = ".dll";
782 RootContext.Target = Target.Exe;
786 RootContext.Target = Target.WinExe;
790 RootContext.Target = Target.Module;
791 RootContext.TargetExt = ".dll";
800 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
801 if ((i + 1) >= args.Length){
803 Environment.Exit (1);
806 references.Add (args [++i]);
810 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
811 if ((i + 1) >= args.Length){
813 Environment.Exit (1);
815 link_paths.Add (args [++i]);
819 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
820 RootContext.StdLib = false;
828 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
829 Report.WarningsAreErrors = true;
833 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
834 if ((i + 1) >= args.Length){
836 Environment.Exit (1);
841 warn = Int32.Parse (args [++i]);
844 Environment.Exit (1);
846 Report.SetIgnoreWarning (warn);
850 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
851 if ((i + 1) >= args.Length){
854 "--wlevel requires a value from 0 to 4");
855 Environment.Exit (1);
858 SetWarningLevel (args [++i]);
862 if ((i + 1) >= args.Length){
863 Report.Error (5, "--mcs-debug requires an argument");
864 Environment.Exit (1);
868 Report.DebugFlags = Int32.Parse (args [++i]);
870 Report.Error (5, "Invalid argument to --mcs-debug");
871 Environment.Exit (1);
880 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
881 if ((i + 1) >= args.Length){
882 Report.Error (5, "--recurse requires an argument");
883 Environment.Exit (1);
885 CompileFiles (args [++i], true);
890 last_time = first_time = DateTime.Now;
897 case "--debug": case "-g":
898 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
899 want_debugging_support = true;
903 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
904 load_default_config = false;
912 // This parses the -arg and /arg options to the compiler, even if the strings
913 // in the following text use "/arg" on the strings.
915 static bool CSCParseOption (string option, ref string [] args, ref int i)
917 int idx = option.IndexOf (':');
924 arg = option.Substring (0, idx);
926 value = option.Substring (idx + 1);
937 RootContext.Target = Target.Exe;
941 RootContext.Target = Target.WinExe;
945 RootContext.Target = Target.Library;
946 RootContext.TargetExt = ".dll";
950 RootContext.Target = Target.Module;
951 RootContext.TargetExt = ".netmodule";
963 Environment.Exit (1);
970 RootContext.Optimize = true;
974 RootContext.Optimize = false;
978 case "/incremental+":
979 case "/incremental-":
989 Environment.Exit (1);
992 defs = value.Split (new Char [] {';', ','});
993 foreach (string d in defs){
1001 // We should collect data, runtime, etc and store in the file specified
1003 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1007 case "/linkresource":
1009 Report.Error (5, arg + " requires an argument");
1010 Environment.Exit (1);
1012 if (resources == null)
1013 resources = new ArrayList ();
1015 resources.Add (value);
1023 Environment.Exit (1);
1025 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1027 ProcessStartInfo pi = new ProcessStartInfo ();
1028 pi.FileName = "pkg-config";
1029 pi.RedirectStandardOutput = true;
1030 pi.UseShellExecute = false;
1031 pi.Arguments = "--libs " + packages;
1034 p = Process.Start (pi);
1035 } catch (Exception e) {
1036 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1037 Environment.Exit (1);
1040 if (p.StandardOutput == null){
1041 Report.Warning (-27, "Specified package did not return any information");
1044 string pkgout = p.StandardOutput.ReadToEnd ();
1046 if (p.ExitCode != 0) {
1047 Report.Error (-27, "Error running pkg-config. Check the above output.");
1048 Environment.Exit (1);
1051 if (pkgout != null){
1052 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1053 Split (new Char [] { ' ', '\t'});
1054 args = AddArgs (args, xargs);
1064 Report.Error (5, "-resource requires an argument");
1065 Environment.Exit (1);
1067 if (embedded_resources == null)
1068 embedded_resources = new ArrayList ();
1070 if (embedded_resources.Contains (value)) {
1071 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1073 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1074 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1077 embedded_resources.Add (value);
1083 Report.Error (5, "-recurse requires an argument");
1084 Environment.Exit (1);
1086 CompileFiles (value, true);
1090 case "/reference": {
1092 Report.Error (5, "-reference requires an argument");
1093 Environment.Exit (1);
1096 string [] refs = value.Split (new char [] { ';', ',' });
1097 foreach (string r in refs){
1102 case "/addmodule": {
1104 Report.Error (5, arg + " requires an argument");
1105 Environment.Exit (1);
1108 string [] refs = value.Split (new char [] { ';', ',' });
1109 foreach (string r in refs){
1116 Report.Error (5, arg + " requires an argument");
1117 Environment.Exit (1);
1120 win32ResourceFile = value;
1123 case "/win32icon": {
1125 Report.Error (5, arg + " requires an argument");
1126 Environment.Exit (1);
1129 win32IconFile = value;
1134 Report.Error (2006, arg + " requires an argument");
1135 Environment.Exit (1);
1137 RootContext.Documentation = new Documentation (value);
1144 Report.Error (5, "/lib requires an argument");
1145 Environment.Exit (1);
1148 libdirs = value.Split (new Char [] { ',' });
1149 foreach (string dir in libdirs)
1150 link_paths.Add (dir);
1155 want_debugging_support = false;
1160 want_debugging_support = true;
1165 RootContext.Checked = true;
1169 RootContext.Checked = false;
1177 RootContext.VerifyClsCompliance = false;
1182 RootContext.Unsafe = true;
1186 RootContext.Unsafe = false;
1189 case "/warnaserror":
1190 case "/warnaserror+":
1191 Report.WarningsAreErrors = true;
1194 case "/warnaserror-":
1195 Report.WarningsAreErrors = false;
1199 SetWarningLevel (value);
1206 Report.Error (5, "/nowarn requires an argument");
1207 Environment.Exit (1);
1210 warns = value.Split (new Char [] {','});
1211 foreach (string wc in warns){
1213 int warn = Int32.Parse (wc);
1215 throw new ArgumentOutOfRangeException("warn");
1217 Report.SetIgnoreWarning (warn);
1219 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1226 load_default_config = true;
1231 load_default_config = false;
1236 Environment.Exit(0);
1242 Environment.Exit (0);
1248 Report.Error (5, arg + " requires an argument");
1249 Environment.Exit (1);
1251 RootContext.MainClass = value;
1256 RootContext.StdLib = false;
1260 RootContext.StdLib = true;
1267 if (value == String.Empty) {
1268 Report.Error (5, arg + " requires an argument");
1269 Environment.Exit (1);
1271 RootContext.StrongNameKeyFile = value;
1273 case "/keycontainer":
1274 if (value == String.Empty) {
1275 Report.Error (5, arg + " requires an argument");
1276 Environment.Exit (1);
1278 RootContext.StrongNameKeyContainer = value;
1281 RootContext.StrongNameDelaySign = true;
1284 RootContext.StrongNameDelaySign = false;
1289 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1293 case "/langversion":
1294 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1296 RootContext.Version = LanguageVersion.ISO_1;
1303 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1309 if (value == "utf8"){
1310 encoding = new UTF8Encoding();
1311 using_default_encoder = false;
1314 if (value == "reset"){
1316 // 28591 is the code page for ISO-8859-1 encoding.
1319 using_default_encoder = true;
1323 cp = Int32.Parse (value);
1324 encoding = Encoding.GetEncoding (cp);
1325 using_default_encoder = false;
1327 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1332 //Report.Error (2007, String.Format ("Unrecognized command-line option: `{0}'", option));
1333 //Environment.Exit (1);
1337 static string [] AddArgs (string [] args, string [] extra_args)
1340 new_args = new string [extra_args.Length + args.Length];
1342 // if args contains '--' we have to take that into account
1343 // split args into first half and second half based on '--'
1344 // and add the extra_args before --
1345 int split_position = Array.IndexOf (args, "--");
1346 if (split_position != -1)
1348 Array.Copy (args, new_args, split_position);
1349 extra_args.CopyTo (new_args, split_position);
1350 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1354 args.CopyTo (new_args, 0);
1355 extra_args.CopyTo (new_args, args.Length);
1362 /// Parses the arguments, and drives the compilation
1367 /// TODO: Mostly structured to debug the compiler
1368 /// now, needs to be turned into a real driver soon.
1370 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1371 internal static bool MainDriver (string [] args)
1374 bool parsing_options = true;
1377 encoding = Encoding.GetEncoding (28591);
1379 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1380 encoding = Encoding.GetEncoding (1252);
1383 references = new ArrayList ();
1384 soft_references = new ArrayList ();
1385 modules = new ArrayList ();
1386 link_paths = new ArrayList ();
1388 SetupDefaultDefines ();
1393 // This is not required because Assembly.Load knows about this
1397 Hashtable response_file_list = null;
1399 for (i = 0; i < args.Length; i++){
1400 string arg = args [i];
1404 if (arg.StartsWith ("@")){
1405 string [] extra_args;
1406 string response_file = arg.Substring (1);
1408 if (response_file_list == null)
1409 response_file_list = new Hashtable ();
1411 if (response_file_list.Contains (response_file)){
1413 1515, "Response file `" + response_file +
1414 "' specified multiple times");
1415 Environment.Exit (1);
1418 response_file_list.Add (response_file, response_file);
1420 extra_args = LoadArgs (response_file);
1421 if (extra_args == null){
1422 Report.Error (2011, "Unable to open response file: " +
1427 args = AddArgs (args, extra_args);
1431 if (parsing_options){
1433 parsing_options = false;
1437 if (arg.StartsWith ("-")){
1438 if (UnixParseOption (arg, ref args, ref i))
1442 string csc_opt = "/" + arg.Substring (1);
1443 if (CSCParseOption (csc_opt, ref args, ref i))
1446 if (arg.StartsWith ("/")){
1447 if (CSCParseOption (arg, ref args, ref i))
1453 CompileFiles (arg, false);
1462 // This will point to the NamespaceEntry of the last file that was parsed, and may
1463 // not be meaningful when resolving classes from other files. So, reset it to prevent
1466 RootContext.Tree.Types.NamespaceEntry = null;
1469 // If we are an exe, require a source file for the entry point
1471 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1472 if (first_source == null){
1473 Report.Error (2008, "No files to compile were specified");
1480 // If there is nothing to put in the assembly, and we are not a library
1482 if (first_source == null && embedded_resources == null && resources == null){
1483 Report.Error (2008, "No files to compile were specified");
1487 if (Report.Errors > 0)
1494 // Load Core Library for default compilation
1496 if (RootContext.StdLib)
1497 references.Insert (0, "mscorlib");
1499 if (load_default_config)
1500 DefineDefaultConfig ();
1502 if (Report.Errors > 0){
1507 // Load assemblies required
1510 ShowTime ("Loading references");
1511 link_paths.Add (GetSystemDir ());
1512 link_paths.Add (Directory.GetCurrentDirectory ());
1516 ShowTime (" References loaded");
1518 if (Report.Errors > 0){
1525 if (output_file == null){
1526 int pos = first_source.LastIndexOf ('.');
1529 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1531 output_file = first_source + RootContext.TargetExt;
1534 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1537 if (RootContext.Target == Target.Module) {
1538 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1539 if (module_only == null) {
1540 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1541 Environment.Exit (1);
1544 MethodInfo set_method = module_only.GetSetMethod (true);
1545 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1548 TypeManager.AddModule (CodeGen.Module.Builder);
1550 if (modules.Count > 0) {
1551 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1552 if (adder_method == null) {
1553 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1554 Environment.Exit (1);
1557 foreach (string module in modules)
1558 LoadModule (adder_method, module);
1561 TypeManager.ComputeNamespaces ();
1564 // Before emitting, we need to get the core
1565 // types emitted from the user defined types
1566 // or from the system ones.
1569 ShowTime ("Initializing Core Types");
1570 if (!RootContext.StdLib){
1571 RootContext.ResolveCore ();
1572 if (Report.Errors > 0)
1576 TypeManager.InitCoreTypes ();
1578 ShowTime (" Core Types done");
1580 CodeGen.Module.ResolveAttributes ();
1583 // The second pass of the compiler
1586 ShowTime ("Resolving tree");
1587 RootContext.ResolveTree ();
1589 if (Report.Errors > 0)
1592 ShowTime ("Populate tree");
1593 if (!RootContext.StdLib)
1594 RootContext.BootCorlib_PopulateCoreTypes ();
1596 RootContext.PopulateTypes ();
1598 TypeManager.InitCodeHelpers ();
1600 RootContext.DefineTypes ();
1602 if (RootContext.Documentation != null &&
1603 !RootContext.Documentation.OutputDocComment (
1608 // Verify using aliases now
1610 Namespace.VerifyUsing ();
1612 if (Report.Errors > 0){
1616 if (RootContext.VerifyClsCompliance) {
1617 CodeGen.Assembly.ResolveClsCompliance ();
1618 if (CodeGen.Assembly.IsClsCompliant) {
1619 AttributeTester.VerifyModulesClsCompliance ();
1620 TypeManager.LoadAllImportedTypes ();
1623 if (Report.Errors > 0)
1627 // The code generator
1630 ShowTime ("Emitting code");
1631 ShowTotalTime ("Total so far");
1632 RootContext.EmitCode ();
1636 if (Report.Errors > 0){
1641 ShowTime ("Closing types");
1643 RootContext.CloseTypes ();
1645 PEFileKinds k = PEFileKinds.ConsoleApplication;
1647 switch (RootContext.Target) {
1648 case Target.Library:
1650 k = PEFileKinds.Dll; break;
1652 k = PEFileKinds.ConsoleApplication; break;
1654 k = PEFileKinds.WindowApplication; break;
1657 if (RootContext.NeedsEntryPoint) {
1658 MethodInfo ep = RootContext.EntryPoint;
1661 if (RootContext.MainClass != null) {
1662 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1663 if (main_cont == null) {
1664 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1668 if (!(main_cont is ClassOrStruct)) {
1669 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1673 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1677 if (Report.Errors == 0)
1678 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1683 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1684 } else if (RootContext.MainClass != null) {
1685 Report.Error (2017, "Cannot specify -main if building a module or library");
1689 // Add the resources
1691 if (resources != null){
1692 foreach (string spec in resources){
1696 cp = spec.IndexOf (',');
1698 file = spec.Substring (0, cp);
1699 res = spec.Substring (cp + 1);
1703 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1707 if (embedded_resources != null){
1708 object[] margs = new object [2];
1709 Type[] argst = new Type [2];
1710 argst [0] = argst [1] = typeof (string);
1712 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1713 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1714 null, CallingConventions.Any, argst, null);
1716 if (embed_res == null) {
1717 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1719 foreach (string spec in embedded_resources) {
1722 cp = spec.IndexOf (',');
1724 margs [0] = spec.Substring (cp + 1);
1725 margs [1] = spec.Substring (0, cp);
1728 margs [0] = Path.GetFileName (spec);
1731 if (File.Exists ((string) margs [1]))
1732 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1734 Report.Error (1566, "Can not find the resource " + margs [1]);
1741 // Add Win32 resources
1744 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1746 if (win32ResourceFile != null) {
1748 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1750 catch (ArgumentException) {
1751 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1755 if (win32IconFile != null) {
1756 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1757 if (define_icon == null) {
1758 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1760 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1763 if (Report.Errors > 0)
1766 CodeGen.Save (output_file);
1768 ShowTime ("Saved output");
1769 ShowTotalTime ("Total");
1772 Timer.ShowTimers ();
1774 if (Report.ExpectedError != 0) {
1775 if (Report.Errors == 0) {
1776 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1777 "No other errors reported.");
1779 Environment.Exit (2);
1781 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1782 "However, other errors were reported.");
1784 Environment.Exit (1);
1792 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1793 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1795 return (Report.Errors == 0);
1800 // This is the only public entry point
1802 public class CompilerCallableEntryPoint : MarshalByRefObject {
1803 public static bool InvokeCompiler (string [] args, TextWriter error)
1805 Report.Stderr = error;
1807 return Driver.MainDriver (args) && Report.Errors == 0;
1810 Report.Stderr = Console.Error;
1815 static void Reset ()
1819 RootContext.Reset ();
1821 TypeManager.Reset ();
1822 TypeHandle.Reset ();