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)
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 using System.Globalization;
20 using System.Diagnostics;
23 Library, Exe, Module, WinExe
27 /// The compiler driver.
33 // Assemblies references to be linked. Initialized with
35 static ArrayList references;
38 // If any of these fail, we ignore the problem. This is so
39 // that we can list all the assemblies in Windows and not fail
40 // if they are missing on Linux.
42 static ArrayList soft_references;
45 // Modules to be linked
47 static ArrayList modules;
50 static ArrayList link_paths;
52 // Whether we want Yacc to output its progress
53 static bool yacc_verbose = false;
55 // Whether we want to only run the tokenizer
56 static bool tokenize = false;
58 static string first_source;
60 static bool want_debugging_support = false;
62 static bool parse_only = false;
63 static bool timestamps = false;
64 static bool pause = false;
65 static bool show_counters = false;
66 public static bool parser_verbose = false;
69 // Whether to load the initial config file (what CSC.RSP has by default)
71 static bool load_default_config = true;
73 static Hashtable response_file_list;
76 // A list of resource files
78 static ArrayList resources;
79 static ArrayList embedded_resources;
80 static string win32ResourceFile;
81 static string win32IconFile;
84 // An array of the defines from the command line
86 static ArrayList defines;
91 static string output_file = null;
94 // Last time we took the time
96 static DateTime last_time, first_time;
99 // Encoding: ISO-Latin1 is 28591
101 static Encoding encoding;
104 // Whether the user has specified a different encoder manually
106 static bool using_default_encoder = true;
108 public static void ShowTime (string msg)
113 DateTime now = DateTime.Now;
114 TimeSpan span = now - last_time;
118 "[{0:00}:{1:000}] {2}",
119 (int) span.TotalSeconds, span.Milliseconds, msg);
122 public static void ShowTotalTime (string msg)
127 DateTime now = DateTime.Now;
128 TimeSpan span = now - first_time;
132 "[{0:00}:{1:000}] {2}",
133 (int) span.TotalSeconds, span.Milliseconds, msg);
136 static void tokenize_file (SourceFile file)
141 input = File.OpenRead (file.Name);
143 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
148 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
149 Tokenizer lexer = new Tokenizer (reader, file, defines);
150 int token, tokens = 0, errors = 0;
152 while ((token = lexer.token ()) != Token.EOF){
154 if (token == Token.ERROR)
157 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
163 // MonoTODO("Change error code for aborted compilation to something reasonable")]
164 static void parse (SourceFile file)
170 input = File.OpenRead (file.Name);
172 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
176 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
178 parser = new CSharpParser (reader, file, defines);
179 parser.yacc_verbose_flag = yacc_verbose;
182 } catch (Exception ex) {
183 Report.Error(666, "Compilation aborted: " + ex);
189 static void OtherFlags ()
192 "Other flags in the compiler\n" +
193 " --fatal Makes errors fatal\n" +
194 " --parse Only parses the source file\n" +
195 " --stacktrace Shows stack trace at error location\n" +
196 " --timestamp Displays time stamps of various compiler events\n" +
197 " -2 Enables experimental C# features\n" +
198 " -v Verbose parsing (for debugging the parser)\n" +
199 " --mcs-debug X Sets MCS debugging level to X\n");
205 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
206 "mcs [options] source-files\n" +
207 " --about About the Mono C# compiler\n" +
208 " -addmodule:MODULE Adds the module to the generated assembly\n" +
209 " -checked[+|-] Set default context to checked\n" +
210 " -codepage:ID Sets code page to the one in ID\n" +
211 " (number, `utf8' or `reset')\n" +
212 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
213 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
214 " -debug[+|-] Generate debugging information\n" +
215 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
216 " -doc:FILE XML Documentation file to generate\n" +
217 " -g Generate debugging information\n" +
218 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
219 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
220 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
221 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
222 " -main:class Specified the class that contains the entry point\n" +
223 " -noconfig[+|-] Disables implicit references to assemblies\n" +
224 " -nostdlib[+|-] Does not load core libraries\n" +
225 " -nowarn:W1[,W2] Disables one or more warnings\n" +
226 " -out:FNAME Specifies output file\n" +
227 " -pkg:P1[,Pn] References packages P1..Pn\n" +
228 " --expect-error X Expect that error X will be encountered\n" +
229 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
230 " -reference:ASS References the specified assembly (-r:ASS)\n" +
231 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
232 " library, module), (short: /t:)\n" +
233 " -unsafe[+|-] Allows unsafe code\n" +
234 " -warnaserror[+|-] Treat warnings as errors\n" +
235 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
236 " -help2 Show other help flags\n" +
239 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
240 " -resource:FILE[,ID] Embed FILE as a resource\n" +
241 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
242 " -win32icon:FILE Use this icon for the output\n" +
243 " @file Read response file for more options\n\n" +
244 "Options can be of the form -option or /option");
247 static void TargetUsage ()
249 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
255 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
256 "The compiler source code is released under the terms of the GNU GPL\n\n" +
258 "For more information on Mono, visit the project Web site\n" +
259 " http://www.go-mono.com\n\n" +
261 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig and Marek Safar");
262 Environment.Exit (0);
265 public static int counter1, counter2;
267 public static int Main (string[] args)
269 bool ok = MainDriver (args);
271 if (ok && Report.Errors == 0) {
272 Console.Write("Compilation succeeded");
273 if (Report.Warnings > 0) {
274 Console.Write(" - {0} warning(s)", Report.Warnings);
278 Console.WriteLine ("Counter1: " + counter1);
279 Console.WriteLine ("Counter2: " + counter2);
285 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
286 Report.Errors, Report.Warnings);
291 static public void LoadAssembly (string assembly, bool soft)
294 string total_log = "";
297 char[] path_chars = { '/', '\\' };
299 if (assembly.IndexOfAny (path_chars) != -1) {
300 a = Assembly.LoadFrom (assembly);
302 string ass = assembly;
303 if (ass.EndsWith (".dll"))
304 ass = assembly.Substring (0, assembly.Length - 4);
305 a = Assembly.Load (ass);
307 TypeManager.AddAssembly (a);
309 } catch (FileNotFoundException){
310 foreach (string dir in link_paths){
311 string full_path = Path.Combine (dir, assembly);
312 if (!assembly.EndsWith (".dll"))
316 a = Assembly.LoadFrom (full_path);
317 TypeManager.AddAssembly (a);
319 } catch (FileNotFoundException ff) {
320 total_log += ff.FusionLog;
325 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
326 Console.WriteLine ("Log: \n" + total_log);
328 } catch (BadImageFormatException f) {
329 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
330 } catch (FileLoadException f){
331 Report.Error(6, "Cannot load assembly " + f.FusionLog);
332 } catch (ArgumentNullException){
333 Report.Error(6, "Cannot load assembly (null argument)");
337 static public void LoadModule (MethodInfo adder_method, string module)
340 string total_log = "";
344 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
346 catch (TargetInvocationException ex) {
347 throw ex.InnerException;
349 TypeManager.AddModule (m);
352 catch (FileNotFoundException){
353 foreach (string dir in link_paths){
354 string full_path = Path.Combine (dir, module);
355 if (!module.EndsWith (".netmodule"))
356 full_path += ".netmodule";
360 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
362 catch (TargetInvocationException ex) {
363 throw ex.InnerException;
365 TypeManager.AddModule (m);
367 } catch (FileNotFoundException ff) {
368 total_log += ff.FusionLog;
372 Report.Error (6, "Cannot find module `" + module + "'" );
373 Console.WriteLine ("Log: \n" + total_log);
374 } catch (BadImageFormatException f) {
375 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
376 } catch (FileLoadException f){
377 Report.Error(6, "Cannot load module " + f.FusionLog);
378 } catch (ArgumentNullException){
379 Report.Error(6, "Cannot load module (null argument)");
384 /// Loads all assemblies referenced on the command line
386 static public void LoadReferences ()
388 foreach (string r in references)
389 LoadAssembly (r, false);
391 foreach (string r in soft_references)
392 LoadAssembly (r, true);
397 static void SetupDefaultDefines ()
399 defines = new ArrayList ();
400 defines.Add ("__MonoCS__");
403 static string [] LoadArgs (string file)
406 ArrayList args = new ArrayList ();
409 f = new StreamReader (file);
414 StringBuilder sb = new StringBuilder ();
416 while ((line = f.ReadLine ()) != null){
419 for (int i = 0; i < t; i++){
422 if (c == '"' || c == '\''){
425 for (i++; i < t; i++){
432 } else if (c == ' '){
434 args.Add (sb.ToString ());
441 args.Add (sb.ToString ());
446 string [] ret_value = new string [args.Count];
447 args.CopyTo (ret_value, 0);
453 // Returns the directory where the system assemblies are installed
455 static string GetSystemDir ()
457 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
459 foreach (Assembly a in assemblies){
460 string codebase = a.Location;
461 string fn = System.IO.Path.GetFileName (codebase);
462 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
463 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
467 Report.Error (-15, "Can not compute my system path");
472 // Given a path specification, splits the path from the file/pattern
474 static void SplitPathAndPattern (string spec, out string path, out string pattern)
476 int p = spec.LastIndexOf ('/');
479 // Windows does not like /file.cs, switch that to:
484 pattern = spec.Substring (1);
486 path = spec.Substring (0, p);
487 pattern = spec.Substring (p + 1);
492 p = spec.LastIndexOf ('\\');
494 path = spec.Substring (0, p);
495 pattern = spec.Substring (p + 1);
503 static void ProcessFile (string f)
505 if (first_source == null)
508 Location.AddFile (f);
511 static void ProcessFiles ()
513 Location.Initialize ();
515 foreach (SourceFile file in Location.SourceFiles) {
517 tokenize_file (file);
524 static void CompileFiles (string spec, bool recurse)
526 string path, pattern;
528 SplitPathAndPattern (spec, out path, out pattern);
529 if (pattern.IndexOf ('*') == -1){
534 string [] files = null;
536 files = Directory.GetFiles (path, pattern);
537 } catch (System.IO.DirectoryNotFoundException) {
538 Report.Error (2001, "Source file `" + spec + "' could not be found");
540 } catch (System.IO.IOException){
541 Report.Error (2001, "Source file `" + spec + "' could not be found");
544 foreach (string f in files) {
551 string [] dirs = null;
554 dirs = Directory.GetDirectories (path);
558 foreach (string d in dirs) {
560 // Don't include path in this string, as each
561 // directory entry already does
562 CompileFiles (d + "/" + pattern, true);
566 static void DefineDefaultConfig ()
569 // For now the "default config" is harcoded into the compiler
570 // we can move this outside later
572 string [] default_config = {
577 // Is it worth pre-loading all this stuff?
580 "System.Configuration.Install",
583 "System.DirectoryServices",
584 "System.Drawing.Design",
586 "System.EnterpriseServices",
589 "System.Runtime.Remoting",
590 "System.Runtime.Serialization.Formatters.Soap",
592 "System.ServiceProcess",
594 "System.Web.RegularExpressions",
595 "System.Web.Services",
596 "System.Windows.Forms"
601 foreach (string def in default_config)
602 soft_references.Insert (p++, def);
605 static void SetOutputFile (string name)
610 static void SetWarningLevel (string s)
615 level = Int32.Parse (s);
619 "--wlevel requires a value from 0 to 4");
620 Environment.Exit (1);
622 if (level < 0 || level > 4){
623 Report.Error (1900, "Warning level must be 0 to 4");
624 Environment.Exit (1);
626 RootContext.WarningLevel = level;
627 TestWarningConflict ();
630 static void TestWarningConflict ()
632 if (RootContext.WarningLevel == 0 && Report.WarningsAreErrors) {
633 Report.Error (1901, "Conflicting options specified: Warning level 0; Treat warnings as errors");
634 Environment.Exit (1);
638 static void SetupV2 ()
640 RootContext.Version = LanguageVersion.Default;
641 defines.Add ("__V2__");
644 static void Version ()
646 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
647 Console.WriteLine ("Mono C# compiler version {0}", version);
648 Environment.Exit (0);
652 // Currently handles the Unix-like command line options, but will be
653 // deprecated in favor of the CSCParseOption, which will also handle the
654 // options that start with a dash in the future.
656 static bool UnixParseOption (string arg, ref string [] args, ref int i)
660 parser_verbose = true;
675 case "--main": case "-m":
676 if ((i + 1) >= args.Length){
678 Environment.Exit (1);
680 RootContext.MainClass = args [++i];
684 RootContext.Unsafe = true;
687 case "/?": case "/h": case "/help":
690 Environment.Exit (0);
694 if ((i + 1) >= args.Length){
696 Environment.Exit (1);
698 defines.Add (args [++i]);
701 case "--show-counters":
702 show_counters = true;
705 case "--expect-error": {
710 args [++i], NumberStyles.AllowLeadingSign);
711 Report.ExpectedError = code;
713 Report.Error (-14, "Invalid number specified");
724 if ((i + 1) >= args.Length){
726 Environment.Exit (1);
728 SetOutputFile (args [++i]);
732 RootContext.Checked = true;
736 Report.Stacktrace = true;
739 case "--linkresource":
741 if ((i + 1) >= args.Length){
743 Report.Error (5, "Missing argument to --linkres");
744 Environment.Exit (1);
746 if (resources == null)
747 resources = new ArrayList ();
749 resources.Add (args [++i]);
754 if ((i + 1) >= args.Length){
756 Report.Error (5, "Missing argument to --resource");
757 Environment.Exit (1);
759 if (embedded_resources == null)
760 embedded_resources = new ArrayList ();
762 embedded_resources.Add (args [++i]);
766 if ((i + 1) >= args.Length){
767 Environment.Exit (1);
771 string type = args [++i];
774 RootContext.Target = Target.Library;
775 RootContext.TargetExt = ".dll";
779 RootContext.Target = Target.Exe;
783 RootContext.Target = Target.WinExe;
787 RootContext.Target = Target.Module;
788 RootContext.TargetExt = ".dll";
792 Environment.Exit (1);
798 if ((i + 1) >= args.Length){
800 Environment.Exit (1);
803 references.Add (args [++i]);
807 if ((i + 1) >= args.Length){
809 Environment.Exit (1);
811 link_paths.Add (args [++i]);
815 RootContext.StdLib = false;
823 Report.WarningsAreErrors = true;
824 TestWarningConflict();
828 if ((i + 1) >= args.Length){
830 Environment.Exit (1);
835 warn = Int32.Parse (args [++i]);
838 Environment.Exit (1);
840 Report.SetIgnoreWarning (warn);
844 if ((i + 1) >= args.Length){
847 "--wlevel requires a value from 0 to 4");
848 Environment.Exit (1);
851 SetWarningLevel (args [++i]);
855 if ((i + 1) >= args.Length){
856 Report.Error (5, "--mcs-debug requires an argument");
857 Environment.Exit (1);
861 Report.DebugFlags = Int32.Parse (args [++i]);
863 Report.Error (5, "Invalid argument to --mcs-debug");
864 Environment.Exit (1);
873 if ((i + 1) >= args.Length){
874 Report.Error (5, "--recurse requires an argument");
875 Environment.Exit (1);
877 CompileFiles (args [++i], true);
882 last_time = first_time = DateTime.Now;
889 case "--debug": case "-g":
890 want_debugging_support = true;
894 load_default_config = false;
902 // Currently it is very basic option parsing, but eventually, this will
903 // be the complete option parser
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";
946 Environment.Exit (1);
954 Environment.Exit (1);
956 SetOutputFile (value);
963 case "/incremental+":
964 case "/incremental-":
974 Environment.Exit (1);
977 defs = value.Split (new Char [] {';', ','});
978 foreach (string d in defs){
985 case "/linkresource":
987 Report.Error (5, arg + " requires an argument");
988 Environment.Exit (1);
990 if (resources == null)
991 resources = new ArrayList ();
993 resources.Add (value);
1001 Environment.Exit (1);
1003 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1005 ProcessStartInfo pi = new ProcessStartInfo ();
1006 pi.FileName = "pkg-config";
1007 pi.RedirectStandardOutput = true;
1008 pi.UseShellExecute = false;
1009 pi.Arguments = "--libs " + packages;
1012 p = Process.Start (pi);
1013 } catch (Exception e) {
1014 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1015 Environment.Exit (1);
1018 if (p.StandardOutput == null){
1019 Report.Warning (-27, "Specified package did not return any information");
1022 string pkgout = p.StandardOutput.ReadToEnd ();
1024 if (p.ExitCode != 0) {
1025 Report.Error (-27, "Error running pkg-config. Check the above output.");
1026 Environment.Exit (1);
1029 if (pkgout != null){
1030 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1031 Split (new Char [] { ' ', '\t'});
1032 args = AddArgs (args, xargs);
1042 Report.Error (5, "-resource requires an argument");
1043 Environment.Exit (1);
1045 if (embedded_resources == null)
1046 embedded_resources = new ArrayList ();
1048 embedded_resources.Add (value);
1053 Report.Error (5, "-recurse requires an argument");
1054 Environment.Exit (1);
1056 CompileFiles (value, true);
1060 case "/reference": {
1062 Report.Error (5, "-reference requires an argument");
1063 Environment.Exit (1);
1066 string [] refs = value.Split (new char [] { ';', ',' });
1067 foreach (string r in refs){
1072 case "/addmodule": {
1074 Report.Error (5, arg + " requires an argument");
1075 Environment.Exit (1);
1078 string [] refs = value.Split (new char [] { ';', ',' });
1079 foreach (string r in refs){
1086 Report.Error (5, arg + " requires an argument");
1087 Environment.Exit (1);
1090 win32ResourceFile = value;
1093 case "/win32icon": {
1095 Report.Error (5, arg + " requires an argument");
1096 Environment.Exit (1);
1099 win32IconFile = value;
1104 Report.Error (5, arg + " requires an argument");
1105 Environment.Exit (1);
1107 // TODO handle the /doc argument to generate xml doc
1114 Report.Error (5, "/lib requires an argument");
1115 Environment.Exit (1);
1118 libdirs = value.Split (new Char [] { ',' });
1119 foreach (string dir in libdirs)
1120 link_paths.Add (dir);
1125 want_debugging_support = false;
1130 want_debugging_support = true;
1135 RootContext.Checked = true;
1139 RootContext.Checked = false;
1147 RootContext.VerifyClsCompliance = false;
1152 RootContext.Unsafe = true;
1156 RootContext.Unsafe = false;
1159 case "/warnaserror":
1160 case "/warnaserror+":
1161 Report.WarningsAreErrors = true;
1162 TestWarningConflict();
1165 case "/warnaserror-":
1166 Report.WarningsAreErrors = false;
1170 SetWarningLevel (value);
1177 Report.Error (5, "/nowarn requires an argument");
1178 Environment.Exit (1);
1181 warns = value.Split (new Char [] {','});
1182 foreach (string wc in warns){
1184 int warn = Int32.Parse (wc);
1186 throw new ArgumentOutOfRangeException("warn");
1188 Report.SetIgnoreWarning (warn);
1190 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1191 Environment.Exit (1);
1198 load_default_config = true;
1203 load_default_config = false;
1208 Environment.Exit(0);
1214 Environment.Exit (0);
1220 Report.Error (5, arg + " requires an argument");
1221 Environment.Exit (1);
1223 RootContext.MainClass = value;
1228 RootContext.StdLib = false;
1232 RootContext.StdLib = true;
1239 if (value == String.Empty) {
1240 Report.Error (5, arg + " requires an argument");
1241 Environment.Exit (1);
1243 RootContext.StrongNameKeyFile = value;
1245 case "/keycontainer":
1246 if (value == String.Empty) {
1247 Report.Error (5, arg + " requires an argument");
1248 Environment.Exit (1);
1250 RootContext.StrongNameKeyContainer = value;
1253 RootContext.StrongNameDelaySign = true;
1256 RootContext.StrongNameDelaySign = false;
1261 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1265 case "/langversion":
1266 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1268 RootContext.Version = LanguageVersion.ISO_1;
1275 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1276 Environment.Exit (1);
1282 if (value == "utf8"){
1283 encoding = new UTF8Encoding();
1284 using_default_encoder = false;
1287 if (value == "reset"){
1289 // 28591 is the code page for ISO-8859-1 encoding.
1292 using_default_encoder = true;
1296 cp = Int32.Parse (value);
1297 encoding = Encoding.GetEncoding (cp);
1298 using_default_encoder = false;
1300 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1301 Environment.Exit (1);
1306 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1307 //Environment.Exit (1);
1311 static string [] AddArgs (string [] args, string [] extra_args)
1315 new_args = new string [extra_args.Length + args.Length];
1316 args.CopyTo (new_args, 0);
1317 extra_args.CopyTo (new_args, args.Length);
1323 /// Parses the arguments, and drives the compilation
1328 /// TODO: Mostly structured to debug the compiler
1329 /// now, needs to be turned into a real driver soon.
1331 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1332 internal static bool MainDriver (string [] args)
1335 bool parsing_options = true;
1338 encoding = Encoding.GetEncoding (28591);
1340 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1341 encoding = Encoding.GetEncoding (1252);
1344 references = new ArrayList ();
1345 soft_references = new ArrayList ();
1346 modules = new ArrayList ();
1347 link_paths = new ArrayList ();
1349 SetupDefaultDefines ();
1354 // This is not required because Assembly.Load knows about this
1358 for (i = 0; i < args.Length; i++){
1359 string arg = args [i];
1363 if (arg.StartsWith ("@")){
1364 string [] extra_args;
1365 string response_file = arg.Substring (1);
1367 if (response_file_list == null)
1368 response_file_list = new Hashtable ();
1370 if (response_file_list.Contains (response_file)){
1372 1515, "Response file `" + response_file +
1373 "' specified multiple times");
1374 Environment.Exit (1);
1377 response_file_list.Add (response_file, response_file);
1379 extra_args = LoadArgs (response_file);
1380 if (extra_args == null){
1381 Report.Error (2011, "Unable to open response file: " +
1386 args = AddArgs (args, extra_args);
1390 if (parsing_options){
1392 parsing_options = false;
1396 if (arg.StartsWith ("-")){
1397 if (UnixParseOption (arg, ref args, ref i))
1401 string csc_opt = "/" + arg.Substring (1);
1402 if (CSCParseOption (csc_opt, ref args, ref i))
1405 if (arg.StartsWith ("/")){
1406 if (CSCParseOption (arg, ref args, ref i))
1412 CompileFiles (arg, false);
1421 // If we are an exe, require a source file for the entry point
1423 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1424 if (first_source == null){
1425 Report.Error (2008, "No files to compile were specified");
1432 // If there is nothing to put in the assembly, and we are not a library
1434 if (first_source == null && embedded_resources == null && resources == null){
1435 Report.Error (2008, "No files to compile were specified");
1439 if (Report.Errors > 0)
1445 Tokenizer.Cleanup ();
1448 // Load Core Library for default compilation
1450 if (RootContext.StdLib)
1451 references.Insert (0, "mscorlib");
1453 if (load_default_config)
1454 DefineDefaultConfig ();
1456 if (Report.Errors > 0){
1461 // Load assemblies required
1464 ShowTime ("Loading references");
1465 link_paths.Add (GetSystemDir ());
1466 link_paths.Add (Directory.GetCurrentDirectory ());
1470 ShowTime (" References loaded");
1472 if (Report.Errors > 0){
1479 if (output_file == null){
1480 int pos = first_source.LastIndexOf ('.');
1483 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1485 output_file = first_source + RootContext.TargetExt;
1488 CodeGen.Init (output_file, output_file, want_debugging_support);
1490 if (RootContext.Target == Target.Module) {
1491 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1492 if (module_only == null) {
1493 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1494 Environment.Exit (1);
1497 MethodInfo set_method = module_only.GetSetMethod (true);
1498 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1501 TypeManager.AddModule (CodeGen.Module.Builder);
1503 if (modules.Count > 0) {
1504 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1505 if (adder_method == null) {
1506 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1507 Environment.Exit (1);
1510 foreach (string module in modules)
1511 LoadModule (adder_method, module);
1514 TypeManager.ComputeNamespaces ();
1517 // Before emitting, we need to get the core
1518 // types emitted from the user defined types
1519 // or from the system ones.
1522 ShowTime ("Initializing Core Types");
1523 if (!RootContext.StdLib){
1524 RootContext.ResolveCore ();
1525 if (Report.Errors > 0)
1529 TypeManager.InitCoreTypes ();
1531 ShowTime (" Core Types done");
1534 // The second pass of the compiler
1537 ShowTime ("Resolving tree");
1538 RootContext.ResolveTree ();
1539 if (Report.Errors > 0)
1542 ShowTime ("Populate tree");
1543 if (!RootContext.StdLib)
1544 RootContext.BootCorlib_PopulateCoreTypes ();
1546 RootContext.PopulateTypes ();
1547 RootContext.DefineTypes ();
1549 TypeManager.InitCodeHelpers ();
1552 // Verify using aliases now
1554 Namespace.VerifyUsing ();
1556 if (Report.Errors > 0){
1560 if (RootContext.VerifyClsCompliance) {
1561 CodeGen.Assembly.ResolveClsCompliance ();
1562 if (CodeGen.Assembly.IsClsCompliant) {
1563 AttributeTester.VerifyModulesClsCompliance ();
1564 TypeManager.LoadAllImportedTypes ();
1565 AttributeTester.VerifyTopLevelNameClsCompliance ();
1570 // The code generator
1573 ShowTime ("Emitting code");
1574 ShowTotalTime ("Total so far");
1575 RootContext.EmitCode ();
1579 if (Report.Errors > 0){
1584 ShowTime ("Closing types");
1586 RootContext.CloseTypes ();
1588 PEFileKinds k = PEFileKinds.ConsoleApplication;
1590 switch (RootContext.Target) {
1591 case Target.Library:
1593 k = PEFileKinds.Dll; break;
1595 k = PEFileKinds.ConsoleApplication; break;
1597 k = PEFileKinds.WindowApplication; break;
1600 if (RootContext.NeedsEntryPoint) {
1601 MethodInfo ep = RootContext.EntryPoint;
1604 if (RootContext.MainClass != null) {
1605 object main_cont = RootContext.Tree.Decls [RootContext.MainClass];
1606 if (main_cont == null) {
1607 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1611 if (!(main_cont is ClassOrStruct)) {
1612 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1617 if (Report.Errors == 0)
1618 Report.Error (5001, "Program " + output_file +
1619 " does not have an entry point defined");
1623 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1624 } else if (RootContext.MainClass != null) {
1625 Report.Error (2017, "Can not specify -main: when building module or library");
1629 // Add the resources
1631 if (resources != null){
1632 foreach (string spec in resources){
1636 cp = spec.IndexOf (',');
1638 file = spec.Substring (0, cp);
1639 res = spec.Substring (cp + 1);
1643 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1647 if (embedded_resources != null){
1648 object[] margs = new object [2];
1649 Type[] argst = new Type [2];
1650 argst [0] = argst [1] = typeof (string);
1652 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1653 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1654 null, CallingConventions.Any, argst, null);
1656 if (embed_res == null) {
1657 Report.Warning (0, new Location (-1),
1658 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1660 foreach (string spec in embedded_resources) {
1663 cp = spec.IndexOf (',');
1665 margs [0] = spec.Substring (cp + 1);
1666 margs [1] = spec.Substring (0, cp);
1669 margs [0] = spec.Replace ('/','.').Replace ('\\', '.');
1672 if (File.Exists ((string) margs [1]))
1673 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1675 Report.Error (1566, "Can not find the resource " + margs [1]);
1682 // Add Win32 resources
1685 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1687 if (win32ResourceFile != null) {
1689 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1691 catch (ArgumentException) {
1692 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1696 if (win32IconFile != null) {
1697 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1698 if (define_icon == null) {
1699 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1701 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1704 if (Report.Errors > 0)
1707 CodeGen.Save (output_file);
1709 ShowTime ("Saved output");
1710 ShowTotalTime ("Total");
1713 Timer.ShowTimers ();
1715 if (Report.ExpectedError != 0) {
1716 if (Report.Errors == 0) {
1717 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1718 "No other errors reported.");
1720 Environment.Exit (2);
1722 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1723 "However, other errors were reported.");
1725 Environment.Exit (1);
1733 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1734 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1736 return (Report.Errors == 0);
1742 // This is the only public entry point
1744 public class CompilerCallableEntryPoint : MarshalByRefObject {
1745 static bool used = false;
1747 public bool InvokeCompiler (string [] args)
1751 bool ok = Driver.MainDriver (args);
1752 return ok && Report.Errors == 0;
1755 public void Reset ()