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;
103 public static void ShowTime (string msg)
108 DateTime now = DateTime.Now;
109 TimeSpan span = now - last_time;
113 "[{0:00}:{1:000}] {2}",
114 (int) span.TotalSeconds, span.Milliseconds, msg);
117 public static void ShowTotalTime (string msg)
122 DateTime now = DateTime.Now;
123 TimeSpan span = now - first_time;
127 "[{0:00}:{1:000}] {2}",
128 (int) span.TotalSeconds, span.Milliseconds, msg);
131 static void tokenize_file (SourceFile file)
136 input = File.OpenRead (file.Name);
138 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
143 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
144 Tokenizer lexer = new Tokenizer (reader, file, defines);
145 int token, tokens = 0, errors = 0;
147 while ((token = lexer.token ()) != Token.EOF){
149 if (token == Token.ERROR)
152 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
158 // MonoTODO("Change error code for aborted compilation to something reasonable")]
159 static void parse (SourceFile file)
165 input = File.OpenRead (file.Name);
167 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
171 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
173 parser = new CSharpParser (reader, file, defines);
176 } catch (Exception ex) {
177 Report.Error(666, "Compilation aborted: " + ex);
183 static void OtherFlags ()
186 "Other flags in the compiler\n" +
187 " --fatal Makes errors fatal\n" +
188 " --parse Only parses the source file\n" +
189 " --stacktrace Shows stack trace at error location\n" +
190 " --timestamp Displays time stamps of various compiler events\n" +
191 " -2 Enables experimental C# features\n" +
192 " -v Verbose parsing (for debugging the parser)\n" +
193 " --mcs-debug X Sets MCS debugging level to X\n");
199 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
200 "mcs [options] source-files\n" +
201 " --about About the Mono C# compiler\n" +
202 " -addmodule:MODULE Adds the module to the generated assembly\n" +
203 " -checked[+|-] Set default context to checked\n" +
204 " -codepage:ID Sets code page to the one in ID\n" +
205 " (number, `utf8' or `reset')\n" +
206 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
207 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
208 " -debug[+|-] Generate debugging information\n" +
209 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
210 " -doc:FILE XML Documentation file to generate\n" +
211 " -g Generate debugging information\n" +
212 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
213 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
214 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
215 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
216 " -main:class Specified the class that contains the entry point\n" +
217 " -noconfig[+|-] Disables implicit references to assemblies\n" +
218 " -nostdlib[+|-] Does not load core libraries\n" +
219 " -nowarn:W1[,W2] Disables one or more warnings\n" +
220 " -optimize[+|-] Enables code optimalizations" + Environment.NewLine +
221 " -out:FNAME Specifies output file\n" +
222 " -pkg:P1[,Pn] References packages P1..Pn\n" +
223 " --expect-error X Expect that error X will be encountered\n" +
224 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
225 " -reference:ASS References the specified assembly (-r:ASS)\n" +
226 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
227 " library, module), (short: /t:)\n" +
228 " -unsafe[+|-] Allows unsafe code\n" +
229 " -warnaserror[+|-] Treat warnings as errors\n" +
230 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
231 " -help2 Show other help flags\n" +
234 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
235 " -resource:FILE[,ID] Embed FILE as a resource\n" +
236 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
237 " -win32icon:FILE Use this icon for the output\n" +
238 " @file Read response file for more options\n\n" +
239 "Options can be of the form -option or /option");
242 static void TargetUsage ()
244 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
250 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
251 "The compiler source code is released under the terms of the GNU GPL\n\n" +
253 "For more information on Mono, visit the project Web site\n" +
254 " http://www.go-mono.com\n\n" +
256 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
257 Environment.Exit (0);
260 public static int counter1, counter2;
262 public static int Main (string[] args)
264 bool ok = MainDriver (args);
266 if (ok && Report.Errors == 0) {
267 if (Report.Warnings > 0) {
268 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
271 Console.WriteLine ("Counter1: " + counter1);
272 Console.WriteLine ("Counter2: " + counter2);
278 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
279 Report.Errors, Report.Warnings);
284 static public void LoadAssembly (string assembly, bool soft)
287 string total_log = "";
290 char[] path_chars = { '/', '\\' };
292 if (assembly.IndexOfAny (path_chars) != -1) {
293 a = Assembly.LoadFrom (assembly);
295 string ass = assembly;
296 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
297 ass = assembly.Substring (0, assembly.Length - 4);
298 a = Assembly.Load (ass);
300 TypeManager.AddAssembly (a);
302 } catch (FileNotFoundException){
303 foreach (string dir in link_paths){
304 string full_path = Path.Combine (dir, assembly);
305 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
309 a = Assembly.LoadFrom (full_path);
310 TypeManager.AddAssembly (a);
312 } catch (FileNotFoundException ff) {
313 total_log += ff.FusionLog;
318 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
319 Console.WriteLine ("Log: \n" + total_log);
321 } catch (BadImageFormatException f) {
322 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
323 } catch (FileLoadException f){
324 Report.Error(6, "Cannot load assembly " + f.FusionLog);
325 } catch (ArgumentNullException){
326 Report.Error(6, "Cannot load assembly (null argument)");
330 static public void LoadModule (MethodInfo adder_method, string module)
333 string total_log = "";
337 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
339 catch (TargetInvocationException ex) {
340 throw ex.InnerException;
342 TypeManager.AddModule (m);
345 catch (FileNotFoundException){
346 foreach (string dir in link_paths){
347 string full_path = Path.Combine (dir, module);
348 if (!module.EndsWith (".netmodule"))
349 full_path += ".netmodule";
353 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
355 catch (TargetInvocationException ex) {
356 throw ex.InnerException;
358 TypeManager.AddModule (m);
360 } catch (FileNotFoundException ff) {
361 total_log += ff.FusionLog;
365 Report.Error (6, "Cannot find module `" + module + "'" );
366 Console.WriteLine ("Log: \n" + total_log);
367 } catch (BadImageFormatException f) {
368 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
369 } catch (FileLoadException f){
370 Report.Error(6, "Cannot load module " + f.FusionLog);
371 } catch (ArgumentNullException){
372 Report.Error(6, "Cannot load module (null argument)");
377 /// Loads all assemblies referenced on the command line
379 static public void LoadReferences ()
381 foreach (string r in references)
382 LoadAssembly (r, false);
384 foreach (string r in soft_references)
385 LoadAssembly (r, true);
390 static void SetupDefaultDefines ()
392 defines = new ArrayList ();
393 defines.Add ("__MonoCS__");
396 static string [] LoadArgs (string file)
399 ArrayList args = new ArrayList ();
402 f = new StreamReader (file);
407 StringBuilder sb = new StringBuilder ();
409 while ((line = f.ReadLine ()) != null){
412 for (int i = 0; i < t; i++){
415 if (c == '"' || c == '\''){
418 for (i++; i < t; i++){
425 } else if (c == ' '){
427 args.Add (sb.ToString ());
434 args.Add (sb.ToString ());
439 string [] ret_value = new string [args.Count];
440 args.CopyTo (ret_value, 0);
446 // Returns the directory where the system assemblies are installed
448 static string GetSystemDir ()
450 return Path.GetDirectoryName (typeof (object).Assembly.Location);
454 // Given a path specification, splits the path from the file/pattern
456 static void SplitPathAndPattern (string spec, out string path, out string pattern)
458 int p = spec.LastIndexOf ('/');
461 // Windows does not like /file.cs, switch that to:
466 pattern = spec.Substring (1);
468 path = spec.Substring (0, p);
469 pattern = spec.Substring (p + 1);
474 p = spec.LastIndexOf ('\\');
476 path = spec.Substring (0, p);
477 pattern = spec.Substring (p + 1);
485 static void ProcessFile (string f)
487 if (first_source == null)
490 Location.AddFile (f);
493 static void ProcessFiles ()
495 Location.Initialize ();
497 foreach (SourceFile file in Location.SourceFiles) {
499 tokenize_file (file);
506 static void CompileFiles (string spec, bool recurse)
508 string path, pattern;
510 SplitPathAndPattern (spec, out path, out pattern);
511 if (pattern.IndexOf ('*') == -1){
516 string [] files = null;
518 files = Directory.GetFiles (path, pattern);
519 } catch (System.IO.DirectoryNotFoundException) {
520 Report.Error (2001, "Source file `" + spec + "' could not be found");
522 } catch (System.IO.IOException){
523 Report.Error (2001, "Source file `" + spec + "' could not be found");
526 foreach (string f in files) {
533 string [] dirs = null;
536 dirs = Directory.GetDirectories (path);
540 foreach (string d in dirs) {
542 // Don't include path in this string, as each
543 // directory entry already does
544 CompileFiles (d + "/" + pattern, true);
548 static void DefineDefaultConfig ()
551 // For now the "default config" is harcoded into the compiler
552 // we can move this outside later
554 string [] default_config = {
559 // Is it worth pre-loading all this stuff?
562 "System.Configuration.Install",
565 "System.DirectoryServices",
566 "System.Drawing.Design",
568 "System.EnterpriseServices",
571 "System.Runtime.Remoting",
572 "System.Runtime.Serialization.Formatters.Soap",
574 "System.ServiceProcess",
576 "System.Web.RegularExpressions",
577 "System.Web.Services",
578 "System.Windows.Forms"
583 foreach (string def in default_config)
584 soft_references.Insert (p++, def);
587 static void SetOutputFile (string name)
592 static void SetWarningLevel (string s)
597 level = Int32.Parse (s);
601 "--wlevel requires a value from 0 to 4");
604 if (level < 0 || level > 4){
605 Report.Error (1900, "Warning level must be 0 to 4");
608 RootContext.WarningLevel = level;
611 static void SetupV2 ()
613 RootContext.Version = LanguageVersion.Default;
614 defines.Add ("__V2__");
617 static void Version ()
619 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
620 Console.WriteLine ("Mono C# compiler version {0}", version);
621 Environment.Exit (0);
625 // Currently handles the Unix-like command line options, but will be
626 // deprecated in favor of the CSCParseOption, which will also handle the
627 // options that start with a dash in the future.
629 static bool UnixParseOption (string arg, ref string [] args, ref int i)
633 CSharpParser.yacc_verbose_flag++;
644 case "--main": case "-m":
645 if ((i + 1) >= args.Length){
647 Environment.Exit (1);
649 RootContext.MainClass = args [++i];
653 RootContext.Unsafe = true;
656 case "/?": case "/h": case "/help":
659 Environment.Exit (0);
663 if ((i + 1) >= args.Length){
665 Environment.Exit (1);
667 defines.Add (args [++i]);
670 case "--show-counters":
671 show_counters = true;
674 case "--expect-error": {
679 args [++i], NumberStyles.AllowLeadingSign);
680 Report.ExpectedError = code;
682 Report.Error (-14, "Invalid number specified");
693 if ((i + 1) >= args.Length){
695 Environment.Exit (1);
697 SetOutputFile (args [++i]);
701 RootContext.Checked = true;
705 Report.Stacktrace = true;
708 case "--linkresource":
710 if ((i + 1) >= args.Length){
712 Report.Error (5, "Missing argument to --linkres");
713 Environment.Exit (1);
715 if (resources == null)
716 resources = new ArrayList ();
718 resources.Add (args [++i]);
723 if ((i + 1) >= args.Length){
725 Report.Error (5, "Missing argument to --resource");
726 Environment.Exit (1);
728 if (embedded_resources == null)
729 embedded_resources = new ArrayList ();
731 embedded_resources.Add (args [++i]);
735 if ((i + 1) >= args.Length){
736 Environment.Exit (1);
740 string type = args [++i];
743 RootContext.Target = Target.Library;
744 RootContext.TargetExt = ".dll";
748 RootContext.Target = Target.Exe;
752 RootContext.Target = Target.WinExe;
756 RootContext.Target = Target.Module;
757 RootContext.TargetExt = ".dll";
766 if ((i + 1) >= args.Length){
768 Environment.Exit (1);
771 references.Add (args [++i]);
775 if ((i + 1) >= args.Length){
777 Environment.Exit (1);
779 link_paths.Add (args [++i]);
783 RootContext.StdLib = false;
791 Report.WarningsAreErrors = true;
795 if ((i + 1) >= args.Length){
797 Environment.Exit (1);
802 warn = Int32.Parse (args [++i]);
805 Environment.Exit (1);
807 Report.SetIgnoreWarning (warn);
811 if ((i + 1) >= args.Length){
814 "--wlevel requires a value from 0 to 4");
815 Environment.Exit (1);
818 SetWarningLevel (args [++i]);
822 if ((i + 1) >= args.Length){
823 Report.Error (5, "--mcs-debug requires an argument");
824 Environment.Exit (1);
828 Report.DebugFlags = Int32.Parse (args [++i]);
830 Report.Error (5, "Invalid argument to --mcs-debug");
831 Environment.Exit (1);
840 if ((i + 1) >= args.Length){
841 Report.Error (5, "--recurse requires an argument");
842 Environment.Exit (1);
844 CompileFiles (args [++i], true);
849 last_time = first_time = DateTime.Now;
856 case "--debug": case "-g":
857 want_debugging_support = true;
861 load_default_config = false;
869 // Currently it is very basic option parsing, but eventually, this will
870 // be the complete option parser
872 static bool CSCParseOption (string option, ref string [] args, ref int i)
874 int idx = option.IndexOf (':');
881 arg = option.Substring (0, idx);
883 value = option.Substring (idx + 1);
894 RootContext.Target = Target.Exe;
898 RootContext.Target = Target.WinExe;
902 RootContext.Target = Target.Library;
903 RootContext.TargetExt = ".dll";
907 RootContext.Target = Target.Module;
908 RootContext.TargetExt = ".netmodule";
920 Environment.Exit (1);
922 SetOutputFile (value);
927 RootContext.Optimize = true;
931 RootContext.Optimize = false;
935 case "/incremental+":
936 case "/incremental-":
946 Environment.Exit (1);
949 defs = value.Split (new Char [] {';', ','});
950 foreach (string d in defs){
957 case "/linkresource":
959 Report.Error (5, arg + " requires an argument");
960 Environment.Exit (1);
962 if (resources == null)
963 resources = new ArrayList ();
965 resources.Add (value);
973 Environment.Exit (1);
975 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
977 ProcessStartInfo pi = new ProcessStartInfo ();
978 pi.FileName = "pkg-config";
979 pi.RedirectStandardOutput = true;
980 pi.UseShellExecute = false;
981 pi.Arguments = "--libs " + packages;
984 p = Process.Start (pi);
985 } catch (Exception e) {
986 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
987 Environment.Exit (1);
990 if (p.StandardOutput == null){
991 Report.Warning (-27, "Specified package did not return any information");
994 string pkgout = p.StandardOutput.ReadToEnd ();
996 if (p.ExitCode != 0) {
997 Report.Error (-27, "Error running pkg-config. Check the above output.");
998 Environment.Exit (1);
1001 if (pkgout != null){
1002 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1003 Split (new Char [] { ' ', '\t'});
1004 args = AddArgs (args, xargs);
1014 Report.Error (5, "-resource requires an argument");
1015 Environment.Exit (1);
1017 if (embedded_resources == null)
1018 embedded_resources = new ArrayList ();
1020 if (embedded_resources.Contains (value)) {
1021 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1023 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1024 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1027 embedded_resources.Add (value);
1033 Report.Error (5, "-recurse requires an argument");
1034 Environment.Exit (1);
1036 CompileFiles (value, true);
1040 case "/reference": {
1042 Report.Error (5, "-reference requires an argument");
1043 Environment.Exit (1);
1046 string [] refs = value.Split (new char [] { ';', ',' });
1047 foreach (string r in refs){
1052 case "/addmodule": {
1054 Report.Error (5, arg + " requires an argument");
1055 Environment.Exit (1);
1058 string [] refs = value.Split (new char [] { ';', ',' });
1059 foreach (string r in refs){
1066 Report.Error (5, arg + " requires an argument");
1067 Environment.Exit (1);
1070 win32ResourceFile = value;
1073 case "/win32icon": {
1075 Report.Error (5, arg + " requires an argument");
1076 Environment.Exit (1);
1079 win32IconFile = value;
1084 Report.Error (2006, arg + " requires an argument");
1085 Environment.Exit (1);
1087 RootContext.Documentation = new Documentation (value);
1094 Report.Error (5, "/lib requires an argument");
1095 Environment.Exit (1);
1098 libdirs = value.Split (new Char [] { ',' });
1099 foreach (string dir in libdirs)
1100 link_paths.Add (dir);
1105 want_debugging_support = false;
1110 want_debugging_support = true;
1115 RootContext.Checked = true;
1119 RootContext.Checked = false;
1127 RootContext.VerifyClsCompliance = false;
1132 RootContext.Unsafe = true;
1136 RootContext.Unsafe = false;
1139 case "/warnaserror":
1140 case "/warnaserror+":
1141 Report.WarningsAreErrors = true;
1144 case "/warnaserror-":
1145 Report.WarningsAreErrors = false;
1149 SetWarningLevel (value);
1156 Report.Error (5, "/nowarn requires an argument");
1157 Environment.Exit (1);
1160 warns = value.Split (new Char [] {','});
1161 foreach (string wc in warns){
1163 int warn = Int32.Parse (wc);
1165 throw new ArgumentOutOfRangeException("warn");
1167 Report.SetIgnoreWarning (warn);
1169 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1176 load_default_config = true;
1181 load_default_config = false;
1186 Environment.Exit(0);
1192 Environment.Exit (0);
1198 Report.Error (5, arg + " requires an argument");
1199 Environment.Exit (1);
1201 RootContext.MainClass = value;
1206 RootContext.StdLib = false;
1210 RootContext.StdLib = true;
1217 if (value == String.Empty) {
1218 Report.Error (5, arg + " requires an argument");
1219 Environment.Exit (1);
1221 RootContext.StrongNameKeyFile = value;
1223 case "/keycontainer":
1224 if (value == String.Empty) {
1225 Report.Error (5, arg + " requires an argument");
1226 Environment.Exit (1);
1228 RootContext.StrongNameKeyContainer = value;
1231 RootContext.StrongNameDelaySign = true;
1234 RootContext.StrongNameDelaySign = false;
1239 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1243 case "/langversion":
1244 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1246 RootContext.Version = LanguageVersion.ISO_1;
1253 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1259 if (value == "utf8"){
1260 encoding = new UTF8Encoding();
1261 using_default_encoder = false;
1264 if (value == "reset"){
1266 // 28591 is the code page for ISO-8859-1 encoding.
1269 using_default_encoder = true;
1273 cp = Int32.Parse (value);
1274 encoding = Encoding.GetEncoding (cp);
1275 using_default_encoder = false;
1277 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1282 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1283 //Environment.Exit (1);
1287 static string [] AddArgs (string [] args, string [] extra_args)
1290 new_args = new string [extra_args.Length + args.Length];
1292 // if args contains '--' we have to take that into account
1293 // split args into first half and second half based on '--'
1294 // and add the extra_args before --
1295 int split_position = Array.IndexOf (args, "--");
1296 if (split_position != -1)
1298 Array.Copy (args, new_args, split_position);
1299 extra_args.CopyTo (new_args, split_position);
1300 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1304 args.CopyTo (new_args, 0);
1305 extra_args.CopyTo (new_args, args.Length);
1312 /// Parses the arguments, and drives the compilation
1317 /// TODO: Mostly structured to debug the compiler
1318 /// now, needs to be turned into a real driver soon.
1320 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1321 internal static bool MainDriver (string [] args)
1324 bool parsing_options = true;
1327 encoding = Encoding.GetEncoding (28591);
1329 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1330 encoding = Encoding.GetEncoding (1252);
1333 references = new ArrayList ();
1334 soft_references = new ArrayList ();
1335 modules = new ArrayList ();
1336 link_paths = new ArrayList ();
1338 SetupDefaultDefines ();
1343 // This is not required because Assembly.Load knows about this
1347 Hashtable response_file_list = null;
1349 for (i = 0; i < args.Length; i++){
1350 string arg = args [i];
1354 if (arg.StartsWith ("@")){
1355 string [] extra_args;
1356 string response_file = arg.Substring (1);
1358 if (response_file_list == null)
1359 response_file_list = new Hashtable ();
1361 if (response_file_list.Contains (response_file)){
1363 1515, "Response file `" + response_file +
1364 "' specified multiple times");
1365 Environment.Exit (1);
1368 response_file_list.Add (response_file, response_file);
1370 extra_args = LoadArgs (response_file);
1371 if (extra_args == null){
1372 Report.Error (2011, "Unable to open response file: " +
1377 args = AddArgs (args, extra_args);
1381 if (parsing_options){
1383 parsing_options = false;
1387 if (arg.StartsWith ("-")){
1388 if (UnixParseOption (arg, ref args, ref i))
1392 string csc_opt = "/" + arg.Substring (1);
1393 if (CSCParseOption (csc_opt, ref args, ref i))
1396 if (arg.StartsWith ("/")){
1397 if (CSCParseOption (arg, ref args, ref i))
1403 CompileFiles (arg, false);
1412 // This will point to the NamespaceEntry of the last file that was parsed, and may
1413 // not be meaningful when resolving classes from other files. So, reset it to prevent
1416 RootContext.Tree.Types.NamespaceEntry = null;
1419 // If we are an exe, require a source file for the entry point
1421 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1422 if (first_source == null){
1423 Report.Error (2008, "No files to compile were specified");
1430 // If there is nothing to put in the assembly, and we are not a library
1432 if (first_source == null && embedded_resources == null && resources == null){
1433 Report.Error (2008, "No files to compile were specified");
1437 if (Report.Errors > 0)
1444 // Load Core Library for default compilation
1446 if (RootContext.StdLib)
1447 references.Insert (0, "mscorlib");
1449 if (load_default_config)
1450 DefineDefaultConfig ();
1452 if (Report.Errors > 0){
1457 // Load assemblies required
1460 ShowTime ("Loading references");
1461 link_paths.Add (GetSystemDir ());
1462 link_paths.Add (Directory.GetCurrentDirectory ());
1466 ShowTime (" References loaded");
1468 if (Report.Errors > 0){
1475 if (output_file == null){
1476 int pos = first_source.LastIndexOf ('.');
1479 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1481 output_file = first_source + RootContext.TargetExt;
1484 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1487 if (RootContext.Target == Target.Module) {
1488 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1489 if (module_only == null) {
1490 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1491 Environment.Exit (1);
1494 MethodInfo set_method = module_only.GetSetMethod (true);
1495 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1498 TypeManager.AddModule (CodeGen.Module.Builder);
1500 if (modules.Count > 0) {
1501 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1502 if (adder_method == null) {
1503 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1504 Environment.Exit (1);
1507 foreach (string module in modules)
1508 LoadModule (adder_method, module);
1511 TypeManager.ComputeNamespaces ();
1514 // Before emitting, we need to get the core
1515 // types emitted from the user defined types
1516 // or from the system ones.
1519 ShowTime ("Initializing Core Types");
1520 if (!RootContext.StdLib){
1521 RootContext.ResolveCore ();
1522 if (Report.Errors > 0)
1526 TypeManager.InitCoreTypes ();
1528 ShowTime (" Core Types done");
1531 // The second pass of the compiler
1534 ShowTime ("Resolving tree");
1535 RootContext.ResolveTree ();
1537 if (Report.Errors > 0)
1540 ShowTime ("Populate tree");
1541 if (!RootContext.StdLib)
1542 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 ();