2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
18 using System.Diagnostics;
21 using System.Globalization;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references;
47 // Modules to be linked
49 static ArrayList modules;
52 static ArrayList link_paths;
54 // Whether we want to only run the tokenizer
55 static bool tokenize = false;
57 static string first_source;
59 static bool want_debugging_support = false;
61 static bool parse_only = false;
62 static bool timestamps = false;
63 static bool pause = false;
64 static bool show_counters = false;
67 // Whether to load the initial config file (what CSC.RSP has by default)
69 static bool load_default_config = true;
72 // A list of resource files
74 static ArrayList resources;
75 static ArrayList embedded_resources;
76 static string win32ResourceFile;
77 static string win32IconFile;
80 // An array of the defines from the command line
82 static ArrayList defines;
87 static string output_file = null;
90 // Last time we took the time
92 static DateTime last_time, first_time;
95 // Encoding: ISO-Latin1 is 28591
97 static Encoding encoding;
100 // Whether the user has specified a different encoder manually
102 static bool using_default_encoder = true;
104 public static void ShowTime (string msg)
109 DateTime now = DateTime.Now;
110 TimeSpan span = now - last_time;
114 "[{0:00}:{1:000}] {2}",
115 (int) span.TotalSeconds, span.Milliseconds, msg);
118 public static void ShowTotalTime (string msg)
123 DateTime now = DateTime.Now;
124 TimeSpan span = now - first_time;
128 "[{0:00}:{1:000}] {2}",
129 (int) span.TotalSeconds, span.Milliseconds, msg);
132 static void tokenize_file (SourceFile file)
137 input = File.OpenRead (file.Name);
139 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
144 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
145 Tokenizer lexer = new Tokenizer (reader, file, defines);
146 int token, tokens = 0, errors = 0;
148 while ((token = lexer.token ()) != Token.EOF){
150 if (token == Token.ERROR)
153 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
159 // MonoTODO("Change error code for aborted compilation to something reasonable")]
160 static void parse (SourceFile file)
166 input = File.OpenRead (file.Name);
168 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
172 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
174 parser = new CSharpParser (reader, file, defines);
177 } catch (Exception ex) {
178 Report.Error(666, "Compilation aborted: " + ex);
184 static void OtherFlags ()
187 "Other flags in the compiler\n" +
188 " --fatal Makes errors fatal\n" +
189 " --parse Only parses the source file\n" +
190 " --stacktrace Shows stack trace at error location\n" +
191 " --timestamp Displays time stamps of various compiler events\n" +
192 " -2 Enables experimental C# features\n" +
193 " -v Verbose parsing (for debugging the parser)\n" +
194 " --mcs-debug X Sets MCS debugging level to X\n");
200 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
201 "mcs [options] source-files\n" +
202 " --about About the Mono C# compiler\n" +
203 " -addmodule:MODULE Adds the module to the generated assembly\n" +
204 " -checked[+|-] Set default context to checked\n" +
205 " -codepage:ID Sets code page to the one in ID\n" +
206 " (number, `utf8' or `reset')\n" +
207 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
208 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
209 " -debug[+|-] Generate debugging information\n" +
210 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
211 " -doc:FILE XML Documentation file to generate\n" +
212 " -g Generate debugging information\n" +
213 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
214 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
215 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
216 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
217 " -main:class Specified the class that contains the entry point\n" +
218 " -noconfig[+|-] Disables implicit references to assemblies\n" +
219 " -nostdlib[+|-] Does not load core libraries\n" +
220 " -nowarn:W1[,W2] Disables one or more warnings\n" +
221 " -optimize[+|-] Enables code optimalizations" + Environment.NewLine +
222 " -out:FNAME Specifies output file\n" +
223 " -pkg:P1[,Pn] References packages P1..Pn\n" +
224 " --expect-error X Expect that error X will be encountered\n" +
225 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
226 " -reference:ASS References the specified assembly (-r:ASS)\n" +
227 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
228 " library, module), (short: /t:)\n" +
229 " -unsafe[+|-] Allows unsafe code\n" +
230 " -warnaserror[+|-] Treat warnings as errors\n" +
231 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
232 " -help2 Show other help flags\n" +
235 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
236 " -resource:FILE[,ID] Embed FILE as a resource\n" +
237 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
238 " -win32icon:FILE Use this icon for the output\n" +
239 " @file Read response file for more options\n\n" +
240 "Options can be of the form -option or /option");
243 static void TargetUsage ()
245 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
251 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
252 "The compiler source code is released under the terms of the GNU GPL\n\n" +
254 "For more information on Mono, visit the project Web site\n" +
255 " http://www.go-mono.com\n\n" +
257 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
258 Environment.Exit (0);
261 public static int counter1, counter2;
263 public static int Main (string[] args)
265 RootContext.Version = LanguageVersion.Default;
266 bool ok = MainDriver (args);
268 if (ok && Report.Errors == 0) {
269 if (Report.Warnings > 0) {
270 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
273 Console.WriteLine ("Counter1: " + counter1);
274 Console.WriteLine ("Counter2: " + counter2);
280 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
281 Report.Errors, Report.Warnings);
286 static public void LoadAssembly (string assembly, bool soft)
289 string total_log = "";
292 char[] path_chars = { '/', '\\' };
294 if (assembly.IndexOfAny (path_chars) != -1) {
295 a = Assembly.LoadFrom (assembly);
297 string ass = assembly;
298 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
299 ass = assembly.Substring (0, assembly.Length - 4);
300 a = Assembly.Load (ass);
302 TypeManager.AddAssembly (a);
304 } catch (FileNotFoundException){
305 foreach (string dir in link_paths){
306 string full_path = Path.Combine (dir, assembly);
307 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
311 a = Assembly.LoadFrom (full_path);
312 TypeManager.AddAssembly (a);
314 } catch (FileNotFoundException ff) {
315 total_log += ff.FusionLog;
320 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
321 Console.WriteLine ("Log: \n" + total_log);
323 } catch (BadImageFormatException f) {
324 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
325 } catch (FileLoadException f){
326 Report.Error(6, "Cannot load assembly " + f.FusionLog);
327 } catch (ArgumentNullException){
328 Report.Error(6, "Cannot load assembly (null argument)");
332 static public void LoadModule (MethodInfo adder_method, string module)
335 string total_log = "";
339 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
341 catch (TargetInvocationException ex) {
342 throw ex.InnerException;
344 TypeManager.AddModule (m);
347 catch (FileNotFoundException){
348 foreach (string dir in link_paths){
349 string full_path = Path.Combine (dir, module);
350 if (!module.EndsWith (".netmodule"))
351 full_path += ".netmodule";
355 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
357 catch (TargetInvocationException ex) {
358 throw ex.InnerException;
360 TypeManager.AddModule (m);
362 } catch (FileNotFoundException ff) {
363 total_log += ff.FusionLog;
367 Report.Error (6, "Cannot find module `" + module + "'" );
368 Console.WriteLine ("Log: \n" + total_log);
369 } catch (BadImageFormatException f) {
370 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
371 } catch (FileLoadException f){
372 Report.Error(6, "Cannot load module " + f.FusionLog);
373 } catch (ArgumentNullException){
374 Report.Error(6, "Cannot load module (null argument)");
379 /// Loads all assemblies referenced on the command line
381 static public void LoadReferences ()
383 foreach (string r in references)
384 LoadAssembly (r, false);
386 foreach (string r in soft_references)
387 LoadAssembly (r, true);
392 static void SetupDefaultDefines ()
394 defines = new ArrayList ();
395 defines.Add ("__MonoCS__");
398 static string [] LoadArgs (string file)
401 ArrayList args = new ArrayList ();
404 f = new StreamReader (file);
409 StringBuilder sb = new StringBuilder ();
411 while ((line = f.ReadLine ()) != null){
414 for (int i = 0; i < t; i++){
417 if (c == '"' || c == '\''){
420 for (i++; i < t; i++){
427 } else if (c == ' '){
429 args.Add (sb.ToString ());
436 args.Add (sb.ToString ());
441 string [] ret_value = new string [args.Count];
442 args.CopyTo (ret_value, 0);
448 // Returns the directory where the system assemblies are installed
450 static string GetSystemDir ()
452 return Path.GetDirectoryName (typeof (object).Assembly.Location);
456 // Given a path specification, splits the path from the file/pattern
458 static void SplitPathAndPattern (string spec, out string path, out string pattern)
460 int p = spec.LastIndexOf ('/');
463 // Windows does not like /file.cs, switch that to:
468 pattern = spec.Substring (1);
470 path = spec.Substring (0, p);
471 pattern = spec.Substring (p + 1);
476 p = spec.LastIndexOf ('\\');
478 path = spec.Substring (0, p);
479 pattern = spec.Substring (p + 1);
487 static void ProcessFile (string f)
489 if (first_source == null)
492 Location.AddFile (f);
495 static void ProcessFiles ()
497 Location.Initialize ();
499 foreach (SourceFile file in Location.SourceFiles) {
501 tokenize_file (file);
508 static void CompileFiles (string spec, bool recurse)
510 string path, pattern;
512 SplitPathAndPattern (spec, out path, out pattern);
513 if (pattern.IndexOf ('*') == -1){
518 string [] files = null;
520 files = Directory.GetFiles (path, pattern);
521 } catch (System.IO.DirectoryNotFoundException) {
522 Report.Error (2001, "Source file `" + spec + "' could not be found");
524 } catch (System.IO.IOException){
525 Report.Error (2001, "Source file `" + spec + "' could not be found");
528 foreach (string f in files) {
535 string [] dirs = null;
538 dirs = Directory.GetDirectories (path);
542 foreach (string d in dirs) {
544 // Don't include path in this string, as each
545 // directory entry already does
546 CompileFiles (d + "/" + pattern, true);
550 static void DefineDefaultConfig ()
553 // For now the "default config" is harcoded into the compiler
554 // we can move this outside later
556 string [] default_config = {
561 // Is it worth pre-loading all this stuff?
564 "System.Configuration.Install",
567 "System.DirectoryServices",
568 "System.Drawing.Design",
570 "System.EnterpriseServices",
573 "System.Runtime.Remoting",
574 "System.Runtime.Serialization.Formatters.Soap",
576 "System.ServiceProcess",
578 "System.Web.RegularExpressions",
579 "System.Web.Services",
580 "System.Windows.Forms"
585 foreach (string def in default_config)
586 soft_references.Insert (p++, def);
589 static void SetOutputFile (string name)
594 static void SetWarningLevel (string s)
599 level = Int32.Parse (s);
603 "--wlevel requires a value from 0 to 4");
606 if (level < 0 || level > 4){
607 Report.Error (1900, "Warning level must be 0 to 4");
610 RootContext.WarningLevel = level;
613 static void SetupV2 ()
615 RootContext.Version = LanguageVersion.Default;
616 defines.Add ("__V2__");
619 static void Version ()
621 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
622 Console.WriteLine ("Mono C# compiler version {0}", version);
623 Environment.Exit (0);
627 // Currently handles the Unix-like command line options, but will be
628 // deprecated in favor of the CSCParseOption, which will also handle the
629 // options that start with a dash in the future.
631 static bool UnixParseOption (string arg, ref string [] args, ref int i)
635 CSharpParser.yacc_verbose_flag++;
646 case "--main": case "-m":
647 if ((i + 1) >= args.Length){
649 Environment.Exit (1);
651 RootContext.MainClass = args [++i];
655 RootContext.Unsafe = true;
658 case "/?": case "/h": case "/help":
661 Environment.Exit (0);
665 if ((i + 1) >= args.Length){
667 Environment.Exit (1);
669 defines.Add (args [++i]);
672 case "--show-counters":
673 show_counters = true;
676 case "--expect-error": {
681 args [++i], NumberStyles.AllowLeadingSign);
682 Report.ExpectedError = code;
684 Report.Error (-14, "Invalid number specified");
695 if ((i + 1) >= args.Length){
697 Environment.Exit (1);
699 SetOutputFile (args [++i]);
703 RootContext.Checked = true;
707 Report.Stacktrace = true;
710 case "--linkresource":
712 if ((i + 1) >= args.Length){
714 Report.Error (5, "Missing argument to --linkres");
715 Environment.Exit (1);
717 if (resources == null)
718 resources = new ArrayList ();
720 resources.Add (args [++i]);
725 if ((i + 1) >= args.Length){
727 Report.Error (5, "Missing argument to --resource");
728 Environment.Exit (1);
730 if (embedded_resources == null)
731 embedded_resources = new ArrayList ();
733 embedded_resources.Add (args [++i]);
737 if ((i + 1) >= args.Length){
738 Environment.Exit (1);
742 string type = args [++i];
745 RootContext.Target = Target.Library;
746 RootContext.TargetExt = ".dll";
750 RootContext.Target = Target.Exe;
754 RootContext.Target = Target.WinExe;
758 RootContext.Target = Target.Module;
759 RootContext.TargetExt = ".dll";
768 if ((i + 1) >= args.Length){
770 Environment.Exit (1);
773 references.Add (args [++i]);
777 if ((i + 1) >= args.Length){
779 Environment.Exit (1);
781 link_paths.Add (args [++i]);
785 RootContext.StdLib = false;
793 Report.WarningsAreErrors = true;
797 if ((i + 1) >= args.Length){
799 Environment.Exit (1);
804 warn = Int32.Parse (args [++i]);
807 Environment.Exit (1);
809 Report.SetIgnoreWarning (warn);
813 if ((i + 1) >= args.Length){
816 "--wlevel requires a value from 0 to 4");
817 Environment.Exit (1);
820 SetWarningLevel (args [++i]);
824 if ((i + 1) >= args.Length){
825 Report.Error (5, "--mcs-debug requires an argument");
826 Environment.Exit (1);
830 Report.DebugFlags = Int32.Parse (args [++i]);
832 Report.Error (5, "Invalid argument to --mcs-debug");
833 Environment.Exit (1);
842 if ((i + 1) >= args.Length){
843 Report.Error (5, "--recurse requires an argument");
844 Environment.Exit (1);
846 CompileFiles (args [++i], true);
851 last_time = first_time = DateTime.Now;
858 case "--debug": case "-g":
859 want_debugging_support = true;
863 load_default_config = false;
871 // Currently it is very basic option parsing, but eventually, this will
872 // be the complete option parser
874 static bool CSCParseOption (string option, ref string [] args, ref int i)
876 int idx = option.IndexOf (':');
883 arg = option.Substring (0, idx);
885 value = option.Substring (idx + 1);
896 RootContext.Target = Target.Exe;
900 RootContext.Target = Target.WinExe;
904 RootContext.Target = Target.Library;
905 RootContext.TargetExt = ".dll";
909 RootContext.Target = Target.Module;
910 RootContext.TargetExt = ".netmodule";
922 Environment.Exit (1);
924 SetOutputFile (value);
929 RootContext.Optimize = true;
933 RootContext.Optimize = false;
937 case "/incremental+":
938 case "/incremental-":
948 Environment.Exit (1);
951 defs = value.Split (new Char [] {';', ','});
952 foreach (string d in defs){
959 case "/linkresource":
961 Report.Error (5, arg + " requires an argument");
962 Environment.Exit (1);
964 if (resources == null)
965 resources = new ArrayList ();
967 resources.Add (value);
975 Environment.Exit (1);
977 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
979 ProcessStartInfo pi = new ProcessStartInfo ();
980 pi.FileName = "pkg-config";
981 pi.RedirectStandardOutput = true;
982 pi.UseShellExecute = false;
983 pi.Arguments = "--libs " + packages;
986 p = Process.Start (pi);
987 } catch (Exception e) {
988 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
989 Environment.Exit (1);
992 if (p.StandardOutput == null){
993 Report.Warning (-27, "Specified package did not return any information");
996 string pkgout = p.StandardOutput.ReadToEnd ();
998 if (p.ExitCode != 0) {
999 Report.Error (-27, "Error running pkg-config. Check the above output.");
1000 Environment.Exit (1);
1003 if (pkgout != null){
1004 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1005 Split (new Char [] { ' ', '\t'});
1006 args = AddArgs (args, xargs);
1016 Report.Error (5, "-resource requires an argument");
1017 Environment.Exit (1);
1019 if (embedded_resources == null)
1020 embedded_resources = new ArrayList ();
1022 if (embedded_resources.Contains (value)) {
1023 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1025 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1026 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1029 embedded_resources.Add (value);
1035 Report.Error (5, "-recurse requires an argument");
1036 Environment.Exit (1);
1038 CompileFiles (value, true);
1042 case "/reference": {
1044 Report.Error (5, "-reference requires an argument");
1045 Environment.Exit (1);
1048 string [] refs = value.Split (new char [] { ';', ',' });
1049 foreach (string r in refs){
1054 case "/addmodule": {
1056 Report.Error (5, arg + " requires an argument");
1057 Environment.Exit (1);
1060 string [] refs = value.Split (new char [] { ';', ',' });
1061 foreach (string r in refs){
1068 Report.Error (5, arg + " requires an argument");
1069 Environment.Exit (1);
1072 win32ResourceFile = value;
1075 case "/win32icon": {
1077 Report.Error (5, arg + " requires an argument");
1078 Environment.Exit (1);
1081 win32IconFile = value;
1086 Report.Error (2006, arg + " requires an argument");
1087 Environment.Exit (1);
1089 RootContext.Documentation = new Documentation (value);
1096 Report.Error (5, "/lib requires an argument");
1097 Environment.Exit (1);
1100 libdirs = value.Split (new Char [] { ',' });
1101 foreach (string dir in libdirs)
1102 link_paths.Add (dir);
1107 want_debugging_support = false;
1112 want_debugging_support = true;
1117 RootContext.Checked = true;
1121 RootContext.Checked = false;
1129 RootContext.VerifyClsCompliance = false;
1134 RootContext.Unsafe = true;
1138 RootContext.Unsafe = false;
1141 case "/warnaserror":
1142 case "/warnaserror+":
1143 Report.WarningsAreErrors = true;
1146 case "/warnaserror-":
1147 Report.WarningsAreErrors = false;
1151 SetWarningLevel (value);
1158 Report.Error (5, "/nowarn requires an argument");
1159 Environment.Exit (1);
1162 warns = value.Split (new Char [] {','});
1163 foreach (string wc in warns){
1165 int warn = Int32.Parse (wc);
1167 throw new ArgumentOutOfRangeException("warn");
1169 Report.SetIgnoreWarning (warn);
1171 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1178 load_default_config = true;
1183 load_default_config = false;
1188 Environment.Exit(0);
1194 Environment.Exit (0);
1200 Report.Error (5, arg + " requires an argument");
1201 Environment.Exit (1);
1203 RootContext.MainClass = value;
1208 RootContext.StdLib = false;
1212 RootContext.StdLib = true;
1219 if (value == String.Empty) {
1220 Report.Error (5, arg + " requires an argument");
1221 Environment.Exit (1);
1223 RootContext.StrongNameKeyFile = value;
1225 case "/keycontainer":
1226 if (value == String.Empty) {
1227 Report.Error (5, arg + " requires an argument");
1228 Environment.Exit (1);
1230 RootContext.StrongNameKeyContainer = value;
1233 RootContext.StrongNameDelaySign = true;
1236 RootContext.StrongNameDelaySign = false;
1241 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1245 case "/langversion":
1246 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1248 RootContext.Version = LanguageVersion.ISO_1;
1255 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1261 if (value == "utf8"){
1262 encoding = new UTF8Encoding();
1263 using_default_encoder = false;
1266 if (value == "reset"){
1268 // 28591 is the code page for ISO-8859-1 encoding.
1271 using_default_encoder = true;
1275 cp = Int32.Parse (value);
1276 encoding = Encoding.GetEncoding (cp);
1277 using_default_encoder = false;
1279 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1283 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1284 //Environment.Exit (1);
1288 static string [] AddArgs (string [] args, string [] extra_args)
1291 new_args = new string [extra_args.Length + args.Length];
1293 // if args contains '--' we have to take that into account
1294 // split args into first half and second half based on '--'
1295 // and add the extra_args before --
1296 int split_position = Array.IndexOf (args, "--");
1297 if (split_position != -1)
1299 Array.Copy (args, new_args, split_position);
1300 extra_args.CopyTo (new_args, split_position);
1301 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1305 args.CopyTo (new_args, 0);
1306 extra_args.CopyTo (new_args, args.Length);
1313 /// Parses the arguments, and drives the compilation
1318 /// TODO: Mostly structured to debug the compiler
1319 /// now, needs to be turned into a real driver soon.
1321 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1322 internal static bool MainDriver (string [] args)
1325 bool parsing_options = true;
1328 encoding = Encoding.GetEncoding (28591);
1330 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1331 encoding = Encoding.GetEncoding (1252);
1334 references = new ArrayList ();
1335 soft_references = new ArrayList ();
1336 modules = new ArrayList ();
1337 link_paths = new ArrayList ();
1339 SetupDefaultDefines ();
1344 // This is not required because Assembly.Load knows about this
1348 Hashtable response_file_list = null;
1350 for (i = 0; i < args.Length; i++){
1351 string arg = args [i];
1355 if (arg.StartsWith ("@")){
1356 string [] extra_args;
1357 string response_file = arg.Substring (1);
1359 if (response_file_list == null)
1360 response_file_list = new Hashtable ();
1362 if (response_file_list.Contains (response_file)){
1364 1515, "Response file `" + response_file +
1365 "' specified multiple times");
1366 Environment.Exit (1);
1369 response_file_list.Add (response_file, response_file);
1371 extra_args = LoadArgs (response_file);
1372 if (extra_args == null){
1373 Report.Error (2011, "Unable to open response file: " +
1378 args = AddArgs (args, extra_args);
1382 if (parsing_options){
1384 parsing_options = false;
1388 if (arg.StartsWith ("-")){
1389 if (UnixParseOption (arg, ref args, ref i))
1393 string csc_opt = "/" + arg.Substring (1);
1394 if (CSCParseOption (csc_opt, ref args, ref i))
1397 if (arg.StartsWith ("/")){
1398 if (CSCParseOption (arg, ref args, ref i))
1404 CompileFiles (arg, false);
1413 // This will point to the NamespaceEntry of the last file that was parsed, and may
1414 // not be meaningful when resolving classes from other files. So, reset it to prevent
1417 RootContext.Tree.Types.NamespaceEntry = null;
1420 // If we are an exe, require a source file for the entry point
1422 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1423 if (first_source == null){
1424 Report.Error (2008, "No files to compile were specified");
1431 // If there is nothing to put in the assembly, and we are not a library
1433 if (first_source == null && embedded_resources == null && resources == null){
1434 Report.Error (2008, "No files to compile were specified");
1438 if (Report.Errors > 0)
1445 // Load Core Library for default compilation
1447 if (RootContext.StdLib)
1448 references.Insert (0, "mscorlib");
1450 if (load_default_config)
1451 DefineDefaultConfig ();
1453 if (Report.Errors > 0){
1458 // Load assemblies required
1461 ShowTime ("Loading references");
1462 link_paths.Add (GetSystemDir ());
1463 link_paths.Add (Directory.GetCurrentDirectory ());
1467 ShowTime (" References loaded");
1469 if (Report.Errors > 0){
1476 if (output_file == null){
1477 int pos = first_source.LastIndexOf ('.');
1480 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1482 output_file = first_source + RootContext.TargetExt;
1485 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1488 if (RootContext.Target == Target.Module) {
1489 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1490 if (module_only == null) {
1491 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1492 Environment.Exit (1);
1495 MethodInfo set_method = module_only.GetSetMethod (true);
1496 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1499 TypeManager.AddModule (CodeGen.Module.Builder);
1501 if (modules.Count > 0) {
1502 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1503 if (adder_method == null) {
1504 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1505 Environment.Exit (1);
1508 foreach (string module in modules)
1509 LoadModule (adder_method, module);
1512 TypeManager.ComputeNamespaces ();
1515 // Before emitting, we need to get the core
1516 // types emitted from the user defined types
1517 // or from the system ones.
1520 ShowTime ("Initializing Core Types");
1521 if (!RootContext.StdLib){
1522 RootContext.ResolveCore ();
1523 if (Report.Errors > 0)
1527 TypeManager.InitCoreTypes ();
1529 ShowTime (" Core Types done");
1532 // The second pass of the compiler
1535 ShowTime ("Resolving tree");
1536 RootContext.ResolveTree ();
1538 if (Report.Errors > 0)
1541 ShowTime ("Populate tree");
1542 if (!RootContext.StdLib)
1543 RootContext.BootCorlib_PopulateCoreTypes ();
1544 RootContext.PopulateTypes ();
1545 RootContext.DefineTypes ();
1547 if (RootContext.Documentation != null &&
1548 !RootContext.Documentation.OutputDocComment (
1552 TypeManager.InitCodeHelpers ();
1555 // Verify using aliases now
1557 Namespace.VerifyUsing ();
1559 if (Report.Errors > 0){
1563 if (RootContext.VerifyClsCompliance) {
1564 CodeGen.Assembly.ResolveClsCompliance ();
1565 if (CodeGen.Assembly.IsClsCompliant) {
1566 AttributeTester.VerifyModulesClsCompliance ();
1567 TypeManager.LoadAllImportedTypes ();
1568 AttributeTester.VerifyTopLevelNameClsCompliance ();
1573 // The code generator
1576 ShowTime ("Emitting code");
1577 ShowTotalTime ("Total so far");
1578 RootContext.EmitCode ();
1582 if (Report.Errors > 0){
1587 ShowTime ("Closing types");
1589 RootContext.CloseTypes ();
1591 PEFileKinds k = PEFileKinds.ConsoleApplication;
1593 switch (RootContext.Target) {
1594 case Target.Library:
1596 k = PEFileKinds.Dll; break;
1598 k = PEFileKinds.ConsoleApplication; break;
1600 k = PEFileKinds.WindowApplication; break;
1603 if (RootContext.NeedsEntryPoint) {
1604 MethodInfo ep = RootContext.EntryPoint;
1607 if (RootContext.MainClass != null) {
1608 DeclSpace main_cont = RootContext.Tree.Decls [RootContext.MainClass] as DeclSpace;
1609 if (main_cont == null) {
1610 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1614 if (!(main_cont is ClassOrStruct)) {
1615 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1619 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1623 if (Report.Errors == 0)
1624 Report.Error (5001, "Program " + output_file +
1625 " does not have an entry point defined");
1629 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1630 } else if (RootContext.MainClass != null) {
1631 Report.Error (2017, "Can not specify -main: when building module or library");
1635 // Add the resources
1637 if (resources != null){
1638 foreach (string spec in resources){
1642 cp = spec.IndexOf (',');
1644 file = spec.Substring (0, cp);
1645 res = spec.Substring (cp + 1);
1649 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1653 if (embedded_resources != null){
1654 object[] margs = new object [2];
1655 Type[] argst = new Type [2];
1656 argst [0] = argst [1] = typeof (string);
1658 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1659 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1660 null, CallingConventions.Any, argst, null);
1662 if (embed_res == null) {
1663 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1665 foreach (string spec in embedded_resources) {
1668 cp = spec.IndexOf (',');
1670 margs [0] = spec.Substring (cp + 1);
1671 margs [1] = spec.Substring (0, cp);
1674 margs [0] = Path.GetFileName (spec);
1677 if (File.Exists ((string) margs [1]))
1678 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1680 Report.Error (1566, "Can not find the resource " + margs [1]);
1687 // Add Win32 resources
1690 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1692 if (win32ResourceFile != null) {
1694 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1696 catch (ArgumentException) {
1697 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1701 if (win32IconFile != null) {
1702 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1703 if (define_icon == null) {
1704 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1706 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1709 if (Report.Errors > 0)
1712 CodeGen.Save (output_file);
1714 ShowTime ("Saved output");
1715 ShowTotalTime ("Total");
1718 Timer.ShowTimers ();
1720 if (Report.ExpectedError != 0){
1721 if (Report.Errors == 0) {
1722 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1723 "No other errors reported.");
1725 Environment.Exit (2);
1727 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1728 "However, other errors were reported.");
1730 Environment.Exit (1);
1738 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1739 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1741 return (Report.Errors == 0);
1746 // This is the only public entry point
1748 public class CompilerCallableEntryPoint : MarshalByRefObject {
1749 static bool used = false;
1751 public static bool InvokeCompiler (string [] args)
1758 return Driver.MainDriver (args) && Report.Errors == 0;
1761 static void Reset ()
1764 RootContext.Reset ();
1766 TypeManager.Reset ();
1767 TypeHandle.Reset ();