2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004, 2005 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.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 defaultEncoding;
98 static Encoding encoding;
100 static public void Reset ()
102 want_debugging_support = false;
106 show_counters = false;
107 load_default_config = true;
108 resources = embedded_resources = null;
109 win32ResourceFile = win32IconFile = null;
112 encoding = defaultEncoding = null;
116 public static void ShowTime (string msg)
121 DateTime now = DateTime.Now;
122 TimeSpan span = now - last_time;
126 "[{0:00}:{1:000}] {2}",
127 (int) span.TotalSeconds, span.Milliseconds, msg);
130 public static void ShowTotalTime (string msg)
135 DateTime now = DateTime.Now;
136 TimeSpan span = now - first_time;
140 "[{0:00}:{1:000}] {2}",
141 (int) span.TotalSeconds, span.Milliseconds, msg);
144 static void tokenize_file (SourceFile file)
149 input = File.OpenRead (file.Name);
151 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
156 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
157 Tokenizer lexer = new Tokenizer (reader, file, defines);
158 int token, tokens = 0, errors = 0;
160 while ((token = lexer.token ()) != Token.EOF){
162 if (token == Token.ERROR)
165 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
171 // MonoTODO("Change error code for aborted compilation to something reasonable")]
172 static void parse (SourceFile file)
178 input = File.OpenRead (file.Name);
180 Report.Error (2001, "Source file `" + file.Name + "' could not be found");
184 SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
187 if (reader.Read () == 77 && reader.Read () == 90) {
188 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
194 parser = new CSharpParser (reader, file, defines);
195 parser.ErrorOutput = Report.Stderr;
199 } catch (Exception ex) {
200 Report.Error(666, "Compilation aborted: " + ex);
213 static void OtherFlags ()
216 "Other flags in the compiler\n" +
217 " --fatal Makes errors fatal\n" +
218 " --parse Only parses the source file\n" +
219 " --stacktrace Shows stack trace at error location\n" +
220 " --timestamp Displays time stamps of various compiler events\n" +
221 " --expect-error X Expect that error X will be encountered\n" +
222 " -2 Enables experimental C# features\n" +
223 " -v Verbose parsing (for debugging the parser)\n" +
224 " --mcs-debug X Sets MCS debugging level to X\n");
230 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
231 "mcs [options] source-files\n" +
232 " --about About the Mono C# compiler\n" +
233 " -addmodule:MODULE Adds the module to the generated assembly\n" +
234 " -checked[+|-] Set default context to checked\n" +
235 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
236 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
237 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
238 " -debug[+|-], -g Generate debugging information\n" +
239 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
240 " -doc:FILE XML Documentation file to generate\n" +
241 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
242 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
243 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
244 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
245 " -main:class Specified the class that contains the entry point\n" +
246 " -noconfig[+|-] Disables implicit references to assemblies\n" +
247 " -nostdlib[+|-] Does not load core libraries\n" +
248 " -nowarn:W1[,W2] Disables one or more warnings\n" +
249 " -optimize[+|-] Enables code optimalizations\n" +
250 " -out:FNAME Specifies output file\n" +
251 " -pkg:P1[,Pn] References packages P1..Pn\n" +
252 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
253 " -reference:ASS References the specified assembly (-r:ASS)\n" +
254 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
255 " library, module), (short: /t:)\n" +
256 " -unsafe[+|-] Allows unsafe code\n" +
257 " -warnaserror[+|-] Treat warnings as errors\n" +
258 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
259 " -help2 Show other help flags\n" +
262 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
263 " -resource:FILE[,ID] Embed FILE as a resource\n" +
264 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
265 " -win32icon:FILE Use this icon for the output\n" +
266 " @file Read response file for more options\n\n" +
267 "Options can be of the form -option or /option");
270 static void TargetUsage ()
272 Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
278 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
279 "The compiler source code is released under the terms of the GNU GPL\n\n" +
281 "For more information on Mono, visit the project Web site\n" +
282 " http://www.go-mono.com\n\n" +
284 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
285 Environment.Exit (0);
288 public static int counter1, counter2;
290 public static int Main (string[] args)
292 RootContext.Version = LanguageVersion.Default;
293 bool ok = MainDriver (args);
295 if (ok && Report.Errors == 0) {
296 if (Report.Warnings > 0) {
297 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
300 Console.WriteLine ("Counter1: " + counter1);
301 Console.WriteLine ("Counter2: " + counter2);
307 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
308 Report.Errors, Report.Warnings);
313 static public void LoadAssembly (string assembly, bool soft)
316 string total_log = "";
319 char[] path_chars = { '/', '\\' };
321 if (assembly.IndexOfAny (path_chars) != -1) {
322 a = Assembly.LoadFrom (assembly);
324 string ass = assembly;
325 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
326 ass = assembly.Substring (0, assembly.Length - 4);
327 a = Assembly.Load (ass);
329 TypeManager.AddAssembly (a);
331 } catch (FileNotFoundException){
332 foreach (string dir in link_paths){
333 string full_path = Path.Combine (dir, assembly);
334 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
338 a = Assembly.LoadFrom (full_path);
339 TypeManager.AddAssembly (a);
341 } catch (FileNotFoundException ff) {
342 total_log += ff.FusionLog;
347 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
348 Console.WriteLine ("Log: \n" + total_log);
350 } catch (BadImageFormatException f) {
351 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
352 } catch (FileLoadException f){
353 Report.Error(6, "Cannot load assembly " + f.FusionLog);
354 } catch (ArgumentNullException){
355 Report.Error(6, "Cannot load assembly (null argument)");
359 static public void LoadModule (MethodInfo adder_method, string module)
362 string total_log = "";
366 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
368 catch (TargetInvocationException ex) {
369 throw ex.InnerException;
371 TypeManager.AddModule (m);
374 catch (FileNotFoundException){
375 foreach (string dir in link_paths){
376 string full_path = Path.Combine (dir, module);
377 if (!module.EndsWith (".netmodule"))
378 full_path += ".netmodule";
382 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
384 catch (TargetInvocationException ex) {
385 throw ex.InnerException;
387 TypeManager.AddModule (m);
389 } catch (FileNotFoundException ff) {
390 total_log += ff.FusionLog;
394 Report.Error (6, "Cannot find module `" + module + "'" );
395 Console.WriteLine ("Log: \n" + total_log);
396 } catch (BadImageFormatException f) {
397 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
398 } catch (FileLoadException f){
399 Report.Error(6, "Cannot load module " + f.FusionLog);
400 } catch (ArgumentNullException){
401 Report.Error(6, "Cannot load module (null argument)");
406 /// Loads all assemblies referenced on the command line
408 static public void LoadReferences ()
410 foreach (string r in references)
411 LoadAssembly (r, false);
413 foreach (string r in soft_references)
414 LoadAssembly (r, true);
419 static void SetupDefaultDefines ()
421 defines = new ArrayList ();
422 defines.Add ("__MonoCS__");
425 static string [] LoadArgs (string file)
428 ArrayList args = new ArrayList ();
431 f = new StreamReader (file);
436 StringBuilder sb = new StringBuilder ();
438 while ((line = f.ReadLine ()) != null){
441 for (int i = 0; i < t; i++){
444 if (c == '"' || c == '\''){
447 for (i++; i < t; i++){
454 } else if (c == ' '){
456 args.Add (sb.ToString ());
463 args.Add (sb.ToString ());
468 string [] ret_value = new string [args.Count];
469 args.CopyTo (ret_value, 0);
475 // Returns the directory where the system assemblies are installed
477 static string GetSystemDir ()
479 return Path.GetDirectoryName (typeof (object).Assembly.Location);
483 // Given a path specification, splits the path from the file/pattern
485 static void SplitPathAndPattern (string spec, out string path, out string pattern)
487 int p = spec.LastIndexOf ('/');
490 // Windows does not like /file.cs, switch that to:
495 pattern = spec.Substring (1);
497 path = spec.Substring (0, p);
498 pattern = spec.Substring (p + 1);
503 p = spec.LastIndexOf ('\\');
505 path = spec.Substring (0, p);
506 pattern = spec.Substring (p + 1);
514 static void ProcessFile (string f)
516 if (first_source == null)
519 Location.AddFile (f);
522 static void ProcessFiles ()
524 Location.Initialize ();
526 foreach (SourceFile file in Location.SourceFiles) {
528 tokenize_file (file);
535 static void CompileFiles (string spec, bool recurse)
537 string path, pattern;
539 SplitPathAndPattern (spec, out path, out pattern);
540 if (pattern.IndexOf ('*') == -1){
545 string [] files = null;
547 files = Directory.GetFiles (path, pattern);
548 } catch (System.IO.DirectoryNotFoundException) {
549 Report.Error (2001, "Source file `" + spec + "' could not be found");
551 } catch (System.IO.IOException){
552 Report.Error (2001, "Source file `" + spec + "' could not be found");
555 foreach (string f in files) {
562 string [] dirs = null;
565 dirs = Directory.GetDirectories (path);
569 foreach (string d in dirs) {
571 // Don't include path in this string, as each
572 // directory entry already does
573 CompileFiles (d + "/" + pattern, true);
577 static void DefineDefaultConfig ()
580 // For now the "default config" is harcoded into the compiler
581 // we can move this outside later
583 string [] default_config = {
588 // Is it worth pre-loading all this stuff?
591 "System.Configuration.Install",
594 "System.DirectoryServices",
595 "System.Drawing.Design",
597 "System.EnterpriseServices",
600 "System.Runtime.Remoting",
601 "System.Runtime.Serialization.Formatters.Soap",
603 "System.ServiceProcess",
605 "System.Web.RegularExpressions",
606 "System.Web.Services",
607 "System.Windows.Forms"
612 foreach (string def in default_config)
613 soft_references.Insert (p++, def);
616 public static string OutputFile
622 return Path.GetFileName (output_file);
626 static void SetWarningLevel (string s)
631 level = Int32.Parse (s);
634 if (level < 0 || level > 4){
635 Report.Error (1900, "Warning level must be in the range 0-4");
638 RootContext.WarningLevel = level;
641 static void SetupV2 ()
643 RootContext.Version = LanguageVersion.Default;
644 defines.Add ("__V2__");
647 static void Version ()
649 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
650 Console.WriteLine ("Mono C# compiler version {0}", version);
651 Environment.Exit (0);
655 // Currently handles the Unix-like command line options, but will be
656 // deprecated in favor of the CSCParseOption, which will also handle the
657 // options that start with a dash in the future.
659 static bool UnixParseOption (string arg, ref string [] args, ref int i)
663 CSharpParser.yacc_verbose_flag++;
674 case "--main": case "-m":
675 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
676 if ((i + 1) >= args.Length){
678 Environment.Exit (1);
680 RootContext.MainClass = args [++i];
684 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
685 RootContext.Unsafe = true;
688 case "/?": case "/h": case "/help":
691 Environment.Exit (0);
695 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
696 if ((i + 1) >= args.Length){
698 Environment.Exit (1);
700 defines.Add (args [++i]);
703 case "--show-counters":
704 show_counters = true;
707 case "--expect-error": {
712 args [++i], NumberStyles.AllowLeadingSign);
713 Report.ExpectedError = code;
715 Report.Error (-14, "Invalid number specified");
726 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
727 if ((i + 1) >= args.Length){
729 Environment.Exit (1);
731 OutputFile = args [++i];
735 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
736 RootContext.Checked = true;
740 Report.Stacktrace = true;
743 case "--linkresource":
745 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
746 if ((i + 1) >= args.Length){
748 Report.Error (5, "Missing argument to --linkres");
749 Environment.Exit (1);
751 if (resources == null)
752 resources = new ArrayList ();
754 resources.Add (args [++i]);
759 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
760 if ((i + 1) >= args.Length){
762 Report.Error (5, "Missing argument to --resource");
763 Environment.Exit (1);
765 if (embedded_resources == null)
766 embedded_resources = new ArrayList ();
768 embedded_resources.Add (args [++i]);
772 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
773 if ((i + 1) >= args.Length){
774 Environment.Exit (1);
778 string type = args [++i];
781 RootContext.Target = Target.Library;
782 RootContext.TargetExt = ".dll";
786 RootContext.Target = Target.Exe;
790 RootContext.Target = Target.WinExe;
794 RootContext.Target = Target.Module;
795 RootContext.TargetExt = ".dll";
804 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
805 if ((i + 1) >= args.Length){
807 Environment.Exit (1);
810 references.Add (args [++i]);
814 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
815 if ((i + 1) >= args.Length){
817 Environment.Exit (1);
819 link_paths.Add (args [++i]);
823 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
824 RootContext.StdLib = false;
832 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
833 Report.WarningsAreErrors = true;
837 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
838 if ((i + 1) >= args.Length){
840 Environment.Exit (1);
845 warn = Int32.Parse (args [++i]);
848 Environment.Exit (1);
850 Report.SetIgnoreWarning (warn);
854 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
855 if ((i + 1) >= args.Length){
858 "--wlevel requires a value from 0 to 4");
859 Environment.Exit (1);
862 SetWarningLevel (args [++i]);
866 if ((i + 1) >= args.Length){
867 Report.Error (5, "--mcs-debug requires an argument");
868 Environment.Exit (1);
872 Report.DebugFlags = Int32.Parse (args [++i]);
874 Report.Error (5, "Invalid argument to --mcs-debug");
875 Environment.Exit (1);
884 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
885 if ((i + 1) >= args.Length){
886 Report.Error (5, "--recurse requires an argument");
887 Environment.Exit (1);
889 CompileFiles (args [++i], true);
894 last_time = first_time = DateTime.Now;
901 case "--debug": case "-g":
902 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
903 want_debugging_support = true;
907 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
908 load_default_config = false;
916 // This parses the -arg and /arg options to the compiler, even if the strings
917 // in the following text use "/arg" on the strings.
919 static bool CSCParseOption (string option, ref string [] args, ref int i)
921 int idx = option.IndexOf (':');
928 arg = option.Substring (0, idx);
930 value = option.Substring (idx + 1);
941 RootContext.Target = Target.Exe;
945 RootContext.Target = Target.WinExe;
949 RootContext.Target = Target.Library;
950 RootContext.TargetExt = ".dll";
954 RootContext.Target = Target.Module;
955 RootContext.TargetExt = ".netmodule";
967 Environment.Exit (1);
974 RootContext.Optimize = true;
978 RootContext.Optimize = false;
982 case "/incremental+":
983 case "/incremental-":
993 Environment.Exit (1);
996 defs = value.Split (new Char [] {';', ','});
997 foreach (string d in defs){
1005 // We should collect data, runtime, etc and store in the file specified
1007 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1011 case "/linkresource":
1013 Report.Error (5, arg + " requires an argument");
1014 Environment.Exit (1);
1016 if (resources == null)
1017 resources = new ArrayList ();
1019 resources.Add (value);
1027 Environment.Exit (1);
1029 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1031 ProcessStartInfo pi = new ProcessStartInfo ();
1032 pi.FileName = "pkg-config";
1033 pi.RedirectStandardOutput = true;
1034 pi.UseShellExecute = false;
1035 pi.Arguments = "--libs " + packages;
1038 p = Process.Start (pi);
1039 } catch (Exception e) {
1040 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1041 Environment.Exit (1);
1044 if (p.StandardOutput == null){
1045 Report.Warning (-27, "Specified package did not return any information");
1048 string pkgout = p.StandardOutput.ReadToEnd ();
1050 if (p.ExitCode != 0) {
1051 Report.Error (-27, "Error running pkg-config. Check the above output.");
1052 Environment.Exit (1);
1055 if (pkgout != null){
1056 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1057 Split (new Char [] { ' ', '\t'});
1058 args = AddArgs (args, xargs);
1068 Report.Error (5, "-resource requires an argument");
1069 Environment.Exit (1);
1071 if (embedded_resources == null)
1072 embedded_resources = new ArrayList ();
1074 if (embedded_resources.Contains (value)) {
1075 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1077 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1078 Report.Error (1508, String.Format ("The resource identifier `{0}' has already been used in this assembly.", value));
1081 embedded_resources.Add (value);
1087 Report.Error (5, "-recurse requires an argument");
1088 Environment.Exit (1);
1090 CompileFiles (value, true);
1094 case "/reference": {
1096 Report.Error (5, "-reference requires an argument");
1097 Environment.Exit (1);
1100 string [] refs = value.Split (new char [] { ';', ',' });
1101 foreach (string r in refs){
1106 case "/addmodule": {
1108 Report.Error (5, arg + " requires an argument");
1109 Environment.Exit (1);
1112 string [] refs = value.Split (new char [] { ';', ',' });
1113 foreach (string r in refs){
1120 Report.Error (5, arg + " requires an argument");
1121 Environment.Exit (1);
1124 win32ResourceFile = value;
1127 case "/win32icon": {
1129 Report.Error (5, arg + " requires an argument");
1130 Environment.Exit (1);
1133 win32IconFile = value;
1138 Report.Error (2006, arg + " requires an argument");
1139 Environment.Exit (1);
1141 RootContext.Documentation = new Documentation (value);
1148 Report.Error (5, "/lib requires an argument");
1149 Environment.Exit (1);
1152 libdirs = value.Split (new Char [] { ',' });
1153 foreach (string dir in libdirs)
1154 link_paths.Add (dir);
1159 want_debugging_support = false;
1164 want_debugging_support = true;
1169 RootContext.Checked = true;
1173 RootContext.Checked = false;
1181 RootContext.VerifyClsCompliance = false;
1186 RootContext.Unsafe = true;
1190 RootContext.Unsafe = false;
1193 case "/warnaserror":
1194 case "/warnaserror+":
1195 Report.WarningsAreErrors = true;
1198 case "/warnaserror-":
1199 Report.WarningsAreErrors = false;
1203 SetWarningLevel (value);
1210 Report.Error (5, "/nowarn requires an argument");
1211 Environment.Exit (1);
1214 warns = value.Split (new Char [] {','});
1215 foreach (string wc in warns){
1217 int warn = Int32.Parse (wc);
1219 throw new ArgumentOutOfRangeException("warn");
1221 Report.SetIgnoreWarning (warn);
1223 Report.Error (1904, String.Format("`{0}' is not a valid warning number", wc));
1230 load_default_config = true;
1235 load_default_config = false;
1240 Environment.Exit(0);
1246 Environment.Exit (0);
1252 Report.Error (5, arg + " requires an argument");
1253 Environment.Exit (1);
1255 RootContext.MainClass = value;
1260 RootContext.StdLib = false;
1264 RootContext.StdLib = true;
1271 if (value == String.Empty) {
1272 Report.Error (5, arg + " requires an argument");
1273 Environment.Exit (1);
1275 RootContext.StrongNameKeyFile = value;
1277 case "/keycontainer":
1278 if (value == String.Empty) {
1279 Report.Error (5, arg + " requires an argument");
1280 Environment.Exit (1);
1282 RootContext.StrongNameKeyContainer = value;
1285 RootContext.StrongNameDelaySign = true;
1288 RootContext.StrongNameDelaySign = false;
1293 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1297 case "/langversion":
1298 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1300 RootContext.Version = LanguageVersion.ISO_1;
1307 Report.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1313 encoding = new UTF8Encoding();
1316 encoding = defaultEncoding;
1320 encoding = Encoding.GetEncoding (
1321 Int32.Parse (value));
1323 Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1329 //Report.Error (2007, String.Format ("Unrecognized command-line option: `{0}'", option));
1330 //Environment.Exit (1);
1334 static string [] AddArgs (string [] args, string [] extra_args)
1337 new_args = new string [extra_args.Length + args.Length];
1339 // if args contains '--' we have to take that into account
1340 // split args into first half and second half based on '--'
1341 // and add the extra_args before --
1342 int split_position = Array.IndexOf (args, "--");
1343 if (split_position != -1)
1345 Array.Copy (args, new_args, split_position);
1346 extra_args.CopyTo (new_args, split_position);
1347 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1351 args.CopyTo (new_args, 0);
1352 extra_args.CopyTo (new_args, args.Length);
1359 /// Parses the arguments, and drives the compilation
1364 /// TODO: Mostly structured to debug the compiler
1365 /// now, needs to be turned into a real driver soon.
1367 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1368 internal static bool MainDriver (string [] args)
1371 bool parsing_options = true;
1375 defaultEncoding = Encoding.GetEncoding (28591);
1376 } catch (Exception) {
1378 defaultEncoding = Encoding.GetEncoding (1252);
1380 encoding = defaultEncoding;
1382 references = new ArrayList ();
1383 soft_references = new ArrayList ();
1384 modules = new ArrayList ();
1385 link_paths = new ArrayList ();
1387 SetupDefaultDefines ();
1392 // This is not required because Assembly.Load knows about this
1396 Hashtable response_file_list = null;
1398 for (i = 0; i < args.Length; i++){
1399 string arg = args [i];
1403 if (arg.StartsWith ("@")){
1404 string [] extra_args;
1405 string response_file = arg.Substring (1);
1407 if (response_file_list == null)
1408 response_file_list = new Hashtable ();
1410 if (response_file_list.Contains (response_file)){
1412 1515, "Response file `" + response_file +
1413 "' specified multiple times");
1414 Environment.Exit (1);
1417 response_file_list.Add (response_file, response_file);
1419 extra_args = LoadArgs (response_file);
1420 if (extra_args == null){
1421 Report.Error (2011, "Unable to open response file: " +
1426 args = AddArgs (args, extra_args);
1430 if (parsing_options){
1432 parsing_options = false;
1436 if (arg.StartsWith ("-")){
1437 if (UnixParseOption (arg, ref args, ref i))
1441 string csc_opt = "/" + arg.Substring (1);
1442 if (CSCParseOption (csc_opt, ref args, ref i))
1445 if (arg.StartsWith ("/")){
1446 if (CSCParseOption (arg, ref args, ref i))
1452 CompileFiles (arg, false);
1461 // This will point to the NamespaceEntry of the last file that was parsed, and may
1462 // not be meaningful when resolving classes from other files. So, reset it to prevent
1465 RootContext.Tree.Types.NamespaceEntry = null;
1468 // If we are an exe, require a source file for the entry point
1470 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1471 if (first_source == null){
1472 Report.Error (2008, "No files to compile were specified");
1479 // If there is nothing to put in the assembly, and we are not a library
1481 if (first_source == null && embedded_resources == null && resources == null){
1482 Report.Error (2008, "No files to compile were specified");
1486 if (Report.Errors > 0)
1493 // Load Core Library for default compilation
1495 if (RootContext.StdLib)
1496 references.Insert (0, "mscorlib");
1498 if (load_default_config)
1499 DefineDefaultConfig ();
1501 if (Report.Errors > 0){
1506 // Load assemblies required
1509 ShowTime ("Loading references");
1510 link_paths.Add (GetSystemDir ());
1511 link_paths.Add (Directory.GetCurrentDirectory ());
1515 ShowTime (" References loaded");
1517 if (Report.Errors > 0){
1524 if (output_file == null){
1525 int pos = first_source.LastIndexOf ('.');
1528 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1530 output_file = first_source + RootContext.TargetExt;
1533 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1536 if (RootContext.Target == Target.Module) {
1537 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1538 if (module_only == null) {
1539 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1540 Environment.Exit (1);
1543 MethodInfo set_method = module_only.GetSetMethod (true);
1544 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1547 TypeManager.AddModule (CodeGen.Module.Builder);
1549 if (modules.Count > 0) {
1550 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1551 if (adder_method == null) {
1552 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1553 Environment.Exit (1);
1556 foreach (string module in modules)
1557 LoadModule (adder_method, module);
1560 TypeManager.ComputeNamespaces ();
1563 // Before emitting, we need to get the core
1564 // types emitted from the user defined types
1565 // or from the system ones.
1568 ShowTime ("Initializing Core Types");
1569 if (!RootContext.StdLib){
1570 RootContext.ResolveCore ();
1571 if (Report.Errors > 0)
1575 TypeManager.InitCoreTypes ();
1577 ShowTime (" Core Types done");
1579 CodeGen.Module.ResolveAttributes ();
1582 // The second pass of the compiler
1585 ShowTime ("Resolving tree");
1586 RootContext.ResolveTree ();
1588 if (Report.Errors > 0)
1591 ShowTime ("Populate tree");
1592 if (!RootContext.StdLib)
1593 RootContext.BootCorlib_PopulateCoreTypes ();
1594 RootContext.PopulateTypes ();
1596 TypeManager.InitCodeHelpers ();
1598 RootContext.DefineTypes ();
1600 if (RootContext.Documentation != null &&
1601 !RootContext.Documentation.OutputDocComment (
1606 // Verify using aliases now
1608 Namespace.VerifyUsing ();
1610 if (Report.Errors > 0){
1614 if (RootContext.VerifyClsCompliance) {
1615 CodeGen.Assembly.ResolveClsCompliance ();
1616 if (CodeGen.Assembly.IsClsCompliant) {
1617 AttributeTester.VerifyModulesClsCompliance ();
1618 TypeManager.LoadAllImportedTypes ();
1621 if (Report.Errors > 0)
1625 // The code generator
1628 ShowTime ("Emitting code");
1629 ShowTotalTime ("Total so far");
1630 RootContext.EmitCode ();
1634 if (Report.Errors > 0){
1639 ShowTime ("Closing types");
1641 RootContext.CloseTypes ();
1643 PEFileKinds k = PEFileKinds.ConsoleApplication;
1645 switch (RootContext.Target) {
1646 case Target.Library:
1648 k = PEFileKinds.Dll; break;
1650 k = PEFileKinds.ConsoleApplication; break;
1652 k = PEFileKinds.WindowApplication; break;
1655 if (RootContext.NeedsEntryPoint) {
1656 MethodInfo ep = RootContext.EntryPoint;
1659 if (RootContext.MainClass != null) {
1660 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass, Location.Null));
1661 if (main_cont == null) {
1662 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
1666 if (!(main_cont is ClassOrStruct)) {
1667 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1671 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1675 if (Report.Errors == 0)
1676 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1681 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1682 } else if (RootContext.MainClass != null) {
1683 Report.Error (2017, "Cannot specify -main if building a module or library");
1687 // Add the resources
1689 if (resources != null){
1690 foreach (string spec in resources){
1694 cp = spec.IndexOf (',');
1696 file = spec.Substring (0, cp);
1697 res = spec.Substring (cp + 1);
1701 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1705 if (embedded_resources != null){
1706 object[] margs = new object [2];
1707 Type[] argst = new Type [2];
1708 argst [0] = argst [1] = typeof (string);
1710 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1711 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1712 null, CallingConventions.Any, argst, null);
1714 if (embed_res == null) {
1715 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1717 foreach (string spec in embedded_resources) {
1720 cp = spec.IndexOf (',');
1722 margs [0] = spec.Substring (cp + 1);
1723 margs [1] = spec.Substring (0, cp);
1726 margs [0] = Path.GetFileName (spec);
1729 if (File.Exists ((string) margs [1]))
1730 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1732 Report.Error (1566, "Can not find the resource " + margs [1]);
1739 // Add Win32 resources
1742 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1744 if (win32ResourceFile != null) {
1746 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1748 catch (ArgumentException) {
1749 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1753 if (win32IconFile != null) {
1754 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1755 if (define_icon == null) {
1756 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1758 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1761 if (Report.Errors > 0)
1764 CodeGen.Save (output_file);
1766 ShowTime ("Saved output");
1767 ShowTotalTime ("Total");
1770 Timer.ShowTimers ();
1772 if (Report.ExpectedError != 0){
1773 if (Report.Errors == 0) {
1774 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1775 "No other errors reported.");
1777 Environment.Exit (2);
1779 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1780 "However, other errors were reported.");
1782 Environment.Exit (1);
1790 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1791 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1793 return (Report.Errors == 0);
1798 // This is the only public entry point
1800 public class CompilerCallableEntryPoint : MarshalByRefObject {
1801 public static bool InvokeCompiler (string [] args, TextWriter error)
1803 Report.Stderr = error;
1805 return Driver.MainDriver (args) && Report.Errors == 0;
1808 Report.Stderr = Console.Error;
1813 static void Reset ()
1817 RootContext.Reset ();
1819 TypeManager.Reset ();
1820 TypeHandle.Reset ();