2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
20 using System.Globalization;
21 using System.Diagnostics;
24 Library, Exe, Module, WinExe
28 /// The compiler driver.
34 // Assemblies references to be linked. Initialized with
36 static ArrayList references;
39 // If any of these fail, we ignore the problem. This is so
40 // that we can list all the assemblies in Windows and not fail
41 // if they are missing on Linux.
43 static ArrayList soft_references;
46 // Modules to be linked
48 static ArrayList modules;
51 static ArrayList link_paths;
53 // Whether we want to only run the tokenizer
54 static bool tokenize = false;
56 static string first_source;
58 static bool want_debugging_support = false;
60 static bool parse_only = false;
61 static bool timestamps = false;
62 static bool pause = false;
63 static bool show_counters = false;
66 // Whether to load the initial config file (what CSC.RSP has by default)
68 static bool load_default_config = true;
71 // A list of resource files
73 static ArrayList resources;
74 static ArrayList embedded_resources;
75 static string win32ResourceFile;
76 static string win32IconFile;
79 // An array of the defines from the command line
81 static ArrayList defines;
86 static string output_file = null;
89 // Last time we took the time
91 static DateTime last_time, first_time;
94 // Encoding: ISO-Latin1 is 28591
96 static Encoding encoding;
99 // Whether the user has specified a different encoder manually
101 static bool using_default_encoder = true;
104 static public void Reset ()
106 want_debugging_support = false;
110 show_counters = false;
111 load_default_config = true;
112 resources = embedded_resources = null;
113 win32ResourceFile = win32IconFile = null;
117 using_default_encoder = true;
120 public static void ShowTime (string msg)
125 DateTime now = DateTime.Now;
126 TimeSpan span = now - last_time;
130 "[{0:00}:{1:000}] {2}",
131 (int) span.TotalSeconds, span.Milliseconds, msg);
134 public static void ShowTotalTime (string msg)
139 DateTime now = DateTime.Now;
140 TimeSpan span = now - first_time;
144 "[{0:00}:{1:000}] {2}",
145 (int) span.TotalSeconds, span.Milliseconds, msg);
148 static void tokenize_file (SourceFile file)
153 input = File.OpenRead (file.Name);
155 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
160 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
161 Tokenizer lexer = new Tokenizer (reader, file, defines);
162 int token, tokens = 0, errors = 0;
164 while ((token = lexer.token ()) != Token.EOF){
166 if (token == Token.ERROR)
169 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
175 // MonoTODO("Change error code for aborted compilation to something reasonable")]
176 static void parse (SourceFile file)
182 input = File.OpenRead (file.Name);
184 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
188 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
190 parser = new CSharpParser (reader, file, defines);
191 parser.ErrorOutput = Report.Stderr;
194 } catch (Exception ex) {
195 Report.Error(666, "Compilation aborted: " + ex);
201 static void OtherFlags ()
204 "Other flags in the compiler\n" +
205 " --fatal Makes errors fatal\n" +
206 " --parse Only parses the source file\n" +
207 " --stacktrace Shows stack trace at error location\n" +
208 " --timestamp Displays time stamps of various compiler events\n" +
209 " --expect-error X Expect that error X will be encountered\n" +
210 " -2 Enables experimental C# features\n" +
211 " -v Verbose parsing (for debugging the parser)\n" +
212 " --mcs-debug X Sets MCS debugging level to X\n");
218 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
219 "mcs [options] source-files\n" +
220 " --about About the Mono C# compiler\n" +
221 " -addmodule:MODULE Adds the module to the generated assembly\n" +
222 " -checked[+|-] Set default context to checked\n" +
223 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
224 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
225 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
226 " -debug[+|-], -g Generate debugging information\n" +
227 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
228 " -doc:FILE XML Documentation file to generate\n" +
229 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
230 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
231 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
232 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
233 " -main:class Specified the class that contains the entry point\n" +
234 " -noconfig[+|-] Disables implicit references to assemblies\n" +
235 " -nostdlib[+|-] Does not load core libraries\n" +
236 " -nowarn:W1[,W2] Disables one or more warnings\n" +
237 " -optimize[+|-] Enables code optimalizations\n" +
238 " -out:FNAME Specifies output file\n" +
239 " -pkg:P1[,Pn] References packages P1..Pn\n" +
240 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
241 " -reference:ASS References the specified assembly (-r:ASS)\n" +
242 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
243 " library, module), (short: /t:)\n" +
244 " -unsafe[+|-] Allows unsafe code\n" +
245 " -warnaserror[+|-] Treat warnings as errors\n" +
246 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
247 " -help2 Show other help flags\n" +
250 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
251 " -resource:FILE[,ID] Embed FILE as a resource\n" +
252 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
253 " -win32icon:FILE Use this icon for the output\n" +
254 " @file Read response file for more options\n\n" +
255 "Options can be of the form -option or /option");
258 static void TargetUsage ()
260 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
266 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
267 "The compiler source code is released under the terms of the GNU GPL\n\n" +
269 "For more information on Mono, visit the project Web site\n" +
270 " http://www.go-mono.com\n\n" +
272 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
273 Environment.Exit (0);
276 public static int counter1, counter2;
278 public static int Main (string[] args)
280 bool ok = MainDriver (args);
282 if (ok && Report.Errors == 0) {
283 if (Report.Warnings > 0) {
284 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
287 Console.WriteLine ("Counter1: " + counter1);
288 Console.WriteLine ("Counter2: " + counter2);
294 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
295 Report.Errors, Report.Warnings);
300 static public void LoadAssembly (string assembly, bool soft)
303 string total_log = "";
306 char[] path_chars = { '/', '\\' };
308 if (assembly.IndexOfAny (path_chars) != -1) {
309 a = Assembly.LoadFrom (assembly);
311 string ass = assembly;
312 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
313 ass = assembly.Substring (0, assembly.Length - 4);
314 a = Assembly.Load (ass);
316 TypeManager.AddAssembly (a);
318 } catch (FileNotFoundException){
319 foreach (string dir in link_paths){
320 string full_path = Path.Combine (dir, assembly);
321 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
325 a = Assembly.LoadFrom (full_path);
326 TypeManager.AddAssembly (a);
328 } catch (FileNotFoundException ff) {
329 total_log += ff.FusionLog;
334 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
335 Console.WriteLine ("Log: \n" + total_log);
337 } catch (BadImageFormatException f) {
338 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
339 } catch (FileLoadException f){
340 Report.Error(6, "Cannot load assembly " + f.FusionLog);
341 } catch (ArgumentNullException){
342 Report.Error(6, "Cannot load assembly (null argument)");
346 static public void LoadModule (MethodInfo adder_method, string module)
349 string total_log = "";
353 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
355 catch (TargetInvocationException ex) {
356 throw ex.InnerException;
358 TypeManager.AddModule (m);
361 catch (FileNotFoundException){
362 foreach (string dir in link_paths){
363 string full_path = Path.Combine (dir, module);
364 if (!module.EndsWith (".netmodule"))
365 full_path += ".netmodule";
369 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
371 catch (TargetInvocationException ex) {
372 throw ex.InnerException;
374 TypeManager.AddModule (m);
376 } catch (FileNotFoundException ff) {
377 total_log += ff.FusionLog;
381 Report.Error (6, "Cannot find module `" + module + "'" );
382 Console.WriteLine ("Log: \n" + total_log);
383 } catch (BadImageFormatException f) {
384 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
385 } catch (FileLoadException f){
386 Report.Error(6, "Cannot load module " + f.FusionLog);
387 } catch (ArgumentNullException){
388 Report.Error(6, "Cannot load module (null argument)");
393 /// Loads all assemblies referenced on the command line
395 static public void LoadReferences ()
397 foreach (string r in references)
398 LoadAssembly (r, false);
400 foreach (string r in soft_references)
401 LoadAssembly (r, true);
406 static void SetupDefaultDefines ()
408 defines = new ArrayList ();
409 defines.Add ("__MonoCS__");
412 static string [] LoadArgs (string file)
415 ArrayList args = new ArrayList ();
418 f = new StreamReader (file);
423 StringBuilder sb = new StringBuilder ();
425 while ((line = f.ReadLine ()) != null){
428 for (int i = 0; i < t; i++){
431 if (c == '"' || c == '\''){
434 for (i++; i < t; i++){
441 } else if (c == ' '){
443 args.Add (sb.ToString ());
450 args.Add (sb.ToString ());
455 string [] ret_value = new string [args.Count];
456 args.CopyTo (ret_value, 0);
462 // Returns the directory where the system assemblies are installed
464 static string GetSystemDir ()
466 return Path.GetDirectoryName (typeof (object).Assembly.Location);
470 // Given a path specification, splits the path from the file/pattern
472 static void SplitPathAndPattern (string spec, out string path, out string pattern)
474 int p = spec.LastIndexOf ('/');
477 // Windows does not like /file.cs, switch that to:
482 pattern = spec.Substring (1);
484 path = spec.Substring (0, p);
485 pattern = spec.Substring (p + 1);
490 p = spec.LastIndexOf ('\\');
492 path = spec.Substring (0, p);
493 pattern = spec.Substring (p + 1);
501 static void ProcessFile (string f)
503 if (first_source == null)
506 Location.AddFile (f);
509 static void ProcessFiles ()
511 Location.Initialize ();
513 foreach (SourceFile file in Location.SourceFiles) {
515 tokenize_file (file);
522 static void CompileFiles (string spec, bool recurse)
524 string path, pattern;
526 SplitPathAndPattern (spec, out path, out pattern);
527 if (pattern.IndexOf ('*') == -1){
532 string [] files = null;
534 files = Directory.GetFiles (path, pattern);
535 } catch (System.IO.DirectoryNotFoundException) {
536 Report.Error (2001, "Source file `" + spec + "' could not be found");
538 } catch (System.IO.IOException){
539 Report.Error (2001, "Source file `" + spec + "' could not be found");
542 foreach (string f in files) {
549 string [] dirs = null;
552 dirs = Directory.GetDirectories (path);
556 foreach (string d in dirs) {
558 // Don't include path in this string, as each
559 // directory entry already does
560 CompileFiles (d + "/" + pattern, true);
564 static void DefineDefaultConfig ()
567 // For now the "default config" is harcoded into the compiler
568 // we can move this outside later
570 string [] default_config = {
575 // Is it worth pre-loading all this stuff?
578 "System.Configuration.Install",
581 "System.DirectoryServices",
582 "System.Drawing.Design",
584 "System.EnterpriseServices",
587 "System.Runtime.Remoting",
588 "System.Runtime.Serialization.Formatters.Soap",
590 "System.ServiceProcess",
592 "System.Web.RegularExpressions",
593 "System.Web.Services",
594 "System.Windows.Forms"
599 foreach (string def in default_config)
600 soft_references.Insert (p++, def);
603 static void SetOutputFile (string name)
608 static void SetWarningLevel (string s)
613 level = Int32.Parse (s);
617 "--wlevel requires a value from 0 to 4");
620 if (level < 0 || level > 4){
621 Report.Error (1900, "Warning level must be 0 to 4");
624 RootContext.WarningLevel = level;
627 static void SetupV2 ()
629 RootContext.Version = LanguageVersion.Default;
630 defines.Add ("__V2__");
633 static void Version ()
635 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
636 Console.WriteLine ("Mono C# compiler version {0}", version);
637 Environment.Exit (0);
641 // Currently handles the Unix-like command line options, but will be
642 // deprecated in favor of the CSCParseOption, which will also handle the
643 // options that start with a dash in the future.
645 static bool UnixParseOption (string arg, ref string [] args, ref int i)
649 CSharpParser.yacc_verbose_flag++;
660 case "--main": case "-m":
661 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
662 if ((i + 1) >= args.Length){
664 Environment.Exit (1);
666 RootContext.MainClass = args [++i];
670 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
671 RootContext.Unsafe = true;
674 case "/?": case "/h": case "/help":
677 Environment.Exit (0);
681 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
682 if ((i + 1) >= args.Length){
684 Environment.Exit (1);
686 defines.Add (args [++i]);
689 case "--show-counters":
690 show_counters = true;
693 case "--expect-error": {
698 args [++i], NumberStyles.AllowLeadingSign);
699 Report.ExpectedError = code;
701 Report.Error (-14, "Invalid number specified");
712 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
713 if ((i + 1) >= args.Length){
715 Environment.Exit (1);
717 SetOutputFile (args [++i]);
721 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
722 RootContext.Checked = true;
726 Report.Stacktrace = true;
729 case "--linkresource":
731 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
732 if ((i + 1) >= args.Length){
734 Report.Error (5, "Missing argument to --linkres");
735 Environment.Exit (1);
737 if (resources == null)
738 resources = new ArrayList ();
740 resources.Add (args [++i]);
745 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
746 if ((i + 1) >= args.Length){
748 Report.Error (5, "Missing argument to --resource");
749 Environment.Exit (1);
751 if (embedded_resources == null)
752 embedded_resources = new ArrayList ();
754 embedded_resources.Add (args [++i]);
758 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
759 if ((i + 1) >= args.Length){
760 Environment.Exit (1);
764 string type = args [++i];
767 RootContext.Target = Target.Library;
768 RootContext.TargetExt = ".dll";
772 RootContext.Target = Target.Exe;
776 RootContext.Target = Target.WinExe;
780 RootContext.Target = Target.Module;
781 RootContext.TargetExt = ".dll";
790 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
791 if ((i + 1) >= args.Length){
793 Environment.Exit (1);
796 references.Add (args [++i]);
800 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
801 if ((i + 1) >= args.Length){
803 Environment.Exit (1);
805 link_paths.Add (args [++i]);
809 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
810 RootContext.StdLib = false;
818 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
819 Report.WarningsAreErrors = true;
823 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
824 if ((i + 1) >= args.Length){
826 Environment.Exit (1);
831 warn = Int32.Parse (args [++i]);
834 Environment.Exit (1);
836 Report.SetIgnoreWarning (warn);
840 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
841 if ((i + 1) >= args.Length){
844 "--wlevel requires a value from 0 to 4");
845 Environment.Exit (1);
848 SetWarningLevel (args [++i]);
852 if ((i + 1) >= args.Length){
853 Report.Error (5, "--mcs-debug requires an argument");
854 Environment.Exit (1);
858 Report.DebugFlags = Int32.Parse (args [++i]);
860 Report.Error (5, "Invalid argument to --mcs-debug");
861 Environment.Exit (1);
870 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
871 if ((i + 1) >= args.Length){
872 Report.Error (5, "--recurse requires an argument");
873 Environment.Exit (1);
875 CompileFiles (args [++i], true);
880 last_time = first_time = DateTime.Now;
887 case "--debug": case "-g":
888 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
889 want_debugging_support = true;
893 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
894 load_default_config = false;
902 // This parses the -arg and /arg options to the compiler, even if the strings
903 // in the following text use "/arg" on the strings.
905 static bool CSCParseOption (string option, ref string [] args, ref int i)
907 int idx = option.IndexOf (':');
914 arg = option.Substring (0, idx);
916 value = option.Substring (idx + 1);
927 RootContext.Target = Target.Exe;
931 RootContext.Target = Target.WinExe;
935 RootContext.Target = Target.Library;
936 RootContext.TargetExt = ".dll";
940 RootContext.Target = Target.Module;
941 RootContext.TargetExt = ".netmodule";
953 Environment.Exit (1);
955 SetOutputFile (value);
960 RootContext.Optimize = true;
964 RootContext.Optimize = false;
968 case "/incremental+":
969 case "/incremental-":
979 Environment.Exit (1);
982 defs = value.Split (new Char [] {';', ','});
983 foreach (string d in defs){
991 // We should collect data, runtime, etc and store in the file specified
993 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
997 case "/linkresource":
999 Report.Error (5, arg + " requires an argument");
1000 Environment.Exit (1);
1002 if (resources == null)
1003 resources = new ArrayList ();
1005 resources.Add (value);
1013 Environment.Exit (1);
1015 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1017 ProcessStartInfo pi = new ProcessStartInfo ();
1018 pi.FileName = "pkg-config";
1019 pi.RedirectStandardOutput = true;
1020 pi.UseShellExecute = false;
1021 pi.Arguments = "--libs " + packages;
1024 p = Process.Start (pi);
1025 } catch (Exception e) {
1026 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1027 Environment.Exit (1);
1030 if (p.StandardOutput == null){
1031 Report.Warning (-27, "Specified package did not return any information");
1034 string pkgout = p.StandardOutput.ReadToEnd ();
1036 if (p.ExitCode != 0) {
1037 Report.Error (-27, "Error running pkg-config. Check the above output.");
1038 Environment.Exit (1);
1041 if (pkgout != null){
1042 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1043 Split (new Char [] { ' ', '\t'});
1044 args = AddArgs (args, xargs);
1054 Report.Error (5, "-resource requires an argument");
1055 Environment.Exit (1);
1057 if (embedded_resources == null)
1058 embedded_resources = new ArrayList ();
1060 if (embedded_resources.Contains (value)) {
1061 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1063 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1064 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1067 embedded_resources.Add (value);
1073 Report.Error (5, "-recurse requires an argument");
1074 Environment.Exit (1);
1076 CompileFiles (value, true);
1080 case "/reference": {
1082 Report.Error (5, "-reference requires an argument");
1083 Environment.Exit (1);
1086 string [] refs = value.Split (new char [] { ';', ',' });
1087 foreach (string r in refs){
1092 case "/addmodule": {
1094 Report.Error (5, arg + " requires an argument");
1095 Environment.Exit (1);
1098 string [] refs = value.Split (new char [] { ';', ',' });
1099 foreach (string r in refs){
1106 Report.Error (5, arg + " requires an argument");
1107 Environment.Exit (1);
1110 win32ResourceFile = value;
1113 case "/win32icon": {
1115 Report.Error (5, arg + " requires an argument");
1116 Environment.Exit (1);
1119 win32IconFile = value;
1124 Report.Error (2006, arg + " requires an argument");
1125 Environment.Exit (1);
1127 RootContext.Documentation = new Documentation (value);
1134 Report.Error (5, "/lib requires an argument");
1135 Environment.Exit (1);
1138 libdirs = value.Split (new Char [] { ',' });
1139 foreach (string dir in libdirs)
1140 link_paths.Add (dir);
1145 want_debugging_support = false;
1150 want_debugging_support = true;
1155 RootContext.Checked = true;
1159 RootContext.Checked = false;
1167 RootContext.VerifyClsCompliance = false;
1172 RootContext.Unsafe = true;
1176 RootContext.Unsafe = false;
1179 case "/warnaserror":
1180 case "/warnaserror+":
1181 Report.WarningsAreErrors = true;
1184 case "/warnaserror-":
1185 Report.WarningsAreErrors = false;
1189 SetWarningLevel (value);
1196 Report.Error (5, "/nowarn requires an argument");
1197 Environment.Exit (1);
1200 warns = value.Split (new Char [] {','});
1201 foreach (string wc in warns){
1203 int warn = Int32.Parse (wc);
1205 throw new ArgumentOutOfRangeException("warn");
1207 Report.SetIgnoreWarning (warn);
1209 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1216 load_default_config = true;
1221 load_default_config = false;
1226 Environment.Exit(0);
1232 Environment.Exit (0);
1238 Report.Error (5, arg + " requires an argument");
1239 Environment.Exit (1);
1241 RootContext.MainClass = value;
1246 RootContext.StdLib = false;
1250 RootContext.StdLib = true;
1257 if (value == String.Empty) {
1258 Report.Error (5, arg + " requires an argument");
1259 Environment.Exit (1);
1261 RootContext.StrongNameKeyFile = value;
1263 case "/keycontainer":
1264 if (value == String.Empty) {
1265 Report.Error (5, arg + " requires an argument");
1266 Environment.Exit (1);
1268 RootContext.StrongNameKeyContainer = value;
1271 RootContext.StrongNameDelaySign = true;
1274 RootContext.StrongNameDelaySign = false;
1279 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1283 case "/langversion":
1284 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1286 RootContext.Version = LanguageVersion.ISO_1;
1293 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1299 if (value == "utf8"){
1300 encoding = new UTF8Encoding();
1301 using_default_encoder = false;
1304 if (value == "reset"){
1306 // 28591 is the code page for ISO-8859-1 encoding.
1309 using_default_encoder = true;
1313 cp = Int32.Parse (value);
1314 encoding = Encoding.GetEncoding (cp);
1315 using_default_encoder = false;
1317 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1322 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1323 //Environment.Exit (1);
1327 static string [] AddArgs (string [] args, string [] extra_args)
1330 new_args = new string [extra_args.Length + args.Length];
1332 // if args contains '--' we have to take that into account
1333 // split args into first half and second half based on '--'
1334 // and add the extra_args before --
1335 int split_position = Array.IndexOf (args, "--");
1336 if (split_position != -1)
1338 Array.Copy (args, new_args, split_position);
1339 extra_args.CopyTo (new_args, split_position);
1340 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1344 args.CopyTo (new_args, 0);
1345 extra_args.CopyTo (new_args, args.Length);
1352 /// Parses the arguments, and drives the compilation
1357 /// TODO: Mostly structured to debug the compiler
1358 /// now, needs to be turned into a real driver soon.
1360 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1361 internal static bool MainDriver (string [] args)
1364 bool parsing_options = true;
1367 encoding = Encoding.GetEncoding (28591);
1369 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1370 encoding = Encoding.GetEncoding (1252);
1373 references = new ArrayList ();
1374 soft_references = new ArrayList ();
1375 modules = new ArrayList ();
1376 link_paths = new ArrayList ();
1378 SetupDefaultDefines ();
1383 // This is not required because Assembly.Load knows about this
1387 Hashtable response_file_list = null;
1389 for (i = 0; i < args.Length; i++){
1390 string arg = args [i];
1394 if (arg.StartsWith ("@")){
1395 string [] extra_args;
1396 string response_file = arg.Substring (1);
1398 if (response_file_list == null)
1399 response_file_list = new Hashtable ();
1401 if (response_file_list.Contains (response_file)){
1403 1515, "Response file `" + response_file +
1404 "' specified multiple times");
1405 Environment.Exit (1);
1408 response_file_list.Add (response_file, response_file);
1410 extra_args = LoadArgs (response_file);
1411 if (extra_args == null){
1412 Report.Error (2011, "Unable to open response file: " +
1417 args = AddArgs (args, extra_args);
1421 if (parsing_options){
1423 parsing_options = false;
1427 if (arg.StartsWith ("-")){
1428 if (UnixParseOption (arg, ref args, ref i))
1432 string csc_opt = "/" + arg.Substring (1);
1433 if (CSCParseOption (csc_opt, ref args, ref i))
1436 if (arg.StartsWith ("/")){
1437 if (CSCParseOption (arg, ref args, ref i))
1443 CompileFiles (arg, false);
1452 // This will point to the NamespaceEntry of the last file that was parsed, and may
1453 // not be meaningful when resolving classes from other files. So, reset it to prevent
1456 RootContext.Tree.Types.NamespaceEntry = null;
1459 // If we are an exe, require a source file for the entry point
1461 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1462 if (first_source == null){
1463 Report.Error (2008, "No files to compile were specified");
1470 // If there is nothing to put in the assembly, and we are not a library
1472 if (first_source == null && embedded_resources == null && resources == null){
1473 Report.Error (2008, "No files to compile were specified");
1477 if (Report.Errors > 0)
1484 // Load Core Library for default compilation
1486 if (RootContext.StdLib)
1487 references.Insert (0, "mscorlib");
1489 if (load_default_config)
1490 DefineDefaultConfig ();
1492 if (Report.Errors > 0){
1497 // Load assemblies required
1500 ShowTime ("Loading references");
1501 link_paths.Add (GetSystemDir ());
1502 link_paths.Add (Directory.GetCurrentDirectory ());
1506 ShowTime (" References loaded");
1508 if (Report.Errors > 0){
1515 if (output_file == null){
1516 int pos = first_source.LastIndexOf ('.');
1519 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1521 output_file = first_source + RootContext.TargetExt;
1524 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1527 if (RootContext.Target == Target.Module) {
1528 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1529 if (module_only == null) {
1530 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1531 Environment.Exit (1);
1534 MethodInfo set_method = module_only.GetSetMethod (true);
1535 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1538 TypeManager.AddModule (CodeGen.Module.Builder);
1540 if (modules.Count > 0) {
1541 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1542 if (adder_method == null) {
1543 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1544 Environment.Exit (1);
1547 foreach (string module in modules)
1548 LoadModule (adder_method, module);
1551 TypeManager.ComputeNamespaces ();
1554 // Before emitting, we need to get the core
1555 // types emitted from the user defined types
1556 // or from the system ones.
1559 ShowTime ("Initializing Core Types");
1560 if (!RootContext.StdLib){
1561 RootContext.ResolveCore ();
1562 if (Report.Errors > 0)
1566 TypeManager.InitCoreTypes ();
1568 ShowTime (" Core Types done");
1570 CodeGen.Module.ResolveAttributes ();
1573 // The second pass of the compiler
1576 ShowTime ("Resolving tree");
1577 RootContext.ResolveTree ();
1579 if (Report.Errors > 0)
1582 ShowTime ("Populate tree");
1583 if (!RootContext.StdLib)
1584 RootContext.BootCorlib_PopulateCoreTypes ();
1586 RootContext.PopulateTypes ();
1587 RootContext.DefineTypes ();
1589 if (RootContext.Documentation != null &&
1590 !RootContext.Documentation.OutputDocComment (
1594 TypeManager.InitCodeHelpers ();
1597 // Verify using aliases now
1599 Namespace.VerifyUsing ();
1601 if (Report.Errors > 0){
1605 if (RootContext.VerifyClsCompliance) {
1606 CodeGen.Assembly.ResolveClsCompliance ();
1607 if (CodeGen.Assembly.IsClsCompliant) {
1608 AttributeTester.VerifyModulesClsCompliance ();
1609 TypeManager.LoadAllImportedTypes ();
1610 AttributeTester.VerifyTopLevelNameClsCompliance ();
1613 if (Report.Errors > 0)
1617 // The code generator
1620 ShowTime ("Emitting code");
1621 ShowTotalTime ("Total so far");
1622 RootContext.EmitCode ();
1626 if (Report.Errors > 0){
1631 ShowTime ("Closing types");
1633 RootContext.CloseTypes ();
1635 PEFileKinds k = PEFileKinds.ConsoleApplication;
1637 switch (RootContext.Target) {
1638 case Target.Library:
1640 k = PEFileKinds.Dll; break;
1642 k = PEFileKinds.ConsoleApplication; break;
1644 k = PEFileKinds.WindowApplication; break;
1647 if (RootContext.NeedsEntryPoint) {
1648 MethodInfo ep = RootContext.EntryPoint;
1651 if (RootContext.MainClass != null) {
1652 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1653 if (main_cont == null) {
1654 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1658 if (!(main_cont is ClassOrStruct)) {
1659 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1663 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1667 if (Report.Errors == 0)
1668 Report.Error (5001, "Program " + output_file +
1669 " does not have an entry point defined");
1673 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1674 } else if (RootContext.MainClass != null) {
1675 Report.Error (2017, "Can not specify -main: when building module or library");
1679 // Add the resources
1681 if (resources != null){
1682 foreach (string spec in resources){
1686 cp = spec.IndexOf (',');
1688 file = spec.Substring (0, cp);
1689 res = spec.Substring (cp + 1);
1693 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1697 if (embedded_resources != null){
1698 object[] margs = new object [2];
1699 Type[] argst = new Type [2];
1700 argst [0] = argst [1] = typeof (string);
1702 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1703 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1704 null, CallingConventions.Any, argst, null);
1706 if (embed_res == null) {
1707 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1709 foreach (string spec in embedded_resources) {
1712 cp = spec.IndexOf (',');
1714 margs [0] = spec.Substring (cp + 1);
1715 margs [1] = spec.Substring (0, cp);
1718 margs [0] = Path.GetFileName (spec);
1721 if (File.Exists ((string) margs [1]))
1722 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1724 Report.Error (1566, "Can not find the resource " + margs [1]);
1731 // Add Win32 resources
1734 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1736 if (win32ResourceFile != null) {
1738 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1740 catch (ArgumentException) {
1741 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1745 if (win32IconFile != null) {
1746 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1747 if (define_icon == null) {
1748 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1750 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1753 if (Report.Errors > 0)
1756 CodeGen.Save (output_file);
1758 ShowTime ("Saved output");
1759 ShowTotalTime ("Total");
1762 Timer.ShowTimers ();
1764 if (Report.ExpectedError != 0) {
1765 if (Report.Errors == 0) {
1766 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1767 "No other errors reported.");
1769 Environment.Exit (2);
1771 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1772 "However, other errors were reported.");
1774 Environment.Exit (1);
1782 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1783 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1785 return (Report.Errors == 0);
1790 // This is the only public entry point
1792 public class CompilerCallableEntryPoint : MarshalByRefObject {
1793 public static bool InvokeCompiler (string [] args, TextWriter error)
1795 Report.Stderr = error;
1796 bool ret = Driver.MainDriver (args) && Report.Errors == 0;
1797 Report.Stderr = Console.Error;
1803 static void Reset ()
1807 RootContext.Reset ();
1809 TypeManager.Reset ();
1810 TypeHandle.Reset ();