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 Ximian, Inc (http://www.ximian.com)
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 using System.Globalization;
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 static ArrayList link_paths;
47 // Whether we want Yacc to output its progress
48 static bool yacc_verbose = false;
50 // Whether we want to only run the tokenizer
51 static bool tokenize = false;
53 static string first_source;
55 static Target target = Target.Exe;
56 static string target_ext = ".exe";
58 static bool want_debugging_support = false;
59 static ArrayList debug_arglist = new ArrayList ();
61 static bool parse_only = false;
62 static bool timestamps = false;
65 // Whether to load the initial config file (what CSC.RSP has by default)
67 static bool load_default_config = true;
69 static Hashtable response_file_list;
70 static Hashtable source_files = new Hashtable ();
73 // A list of resource files
75 static ArrayList resources;
76 static ArrayList embedded_resources;
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 (string input_file)
136 input = File.OpenRead (input_file);
138 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
143 StreamReader reader = new StreamReader (input, encoding, using_default_encoder);
144 Tokenizer lexer = new Tokenizer (reader, input_file, defines);
145 int token, tokens = 0, errors = 0;
147 while ((token = lexer.token ()) != Token.EOF){
148 Location l = lexer.Location;
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 (string input_file)
166 input = File.OpenRead (input_file);
168 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
172 StreamReader reader = new StreamReader (input, encoding, using_default_encoder);
174 parser = new CSharpParser (reader, input_file, defines);
175 parser.yacc_verbose = yacc_verbose;
178 } catch (Exception ex) {
179 Report.Error(666, "Compilation aborted: " + ex);
188 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
189 "mcs [options] source-files\n" +
190 " --about About the Mono C# compiler\n" +
191 " -checked[+|-] Set default context to checked\n" +
192 " -codepage:ID Sets code page to the one in ID\n" +
193 " (number, `utf8' or `reset')\n" +
194 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
195 " -debug[+-] Generate debugging information\n" +
196 " -g Generate debugging information\n" +
197 " --debug-args X Specify additional arguments for the\n" +
198 " symbol writer.\n" +
199 " --fatal Makes errors fatal\n" +
200 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
201 " -main:class Specified the class that contains the entry point\n" +
202 " -noconfig[+|-] Disables implicit references to assemblies\n" +
203 " -nostdlib[+|-] Does not load core libraries\n" +
204 " -nowarn:W1[,W2] Disables one or more warnings\n" +
205 " -out:FNAME Specifies output file\n" +
206 " --parse Only parses the source file\n" +
207 " --expect-error X Expect that error X will be encountered\n" +
208 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
209 " -reference:ASS References the specified assembly (-r:ASS)\n" +
210 " --stacktrace Shows stack trace at error location\n" +
211 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
212 " library, module), (short: /t:)\n" +
213 " --timestamp Displays time stamps of various compiler events\n" +
214 " -unsafe[+|-] Allows unsafe code\n" +
215 " -warnaserror[+|-] Treat warnings as errors\n" +
216 " -warn:LEVEL Sets warning level (the highest is 4, the default)\n" +
217 " -v Verbose parsing (for debugging the parser)\n" +
220 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
221 " -resource:FILE[,ID] Embed FILE as a resource\n" +
222 " --mcs-debug X Sets MCS debugging level to X\n" +
223 " @file Read response file for more options\n\n" +
224 "Options can be of the form -option or /option");
230 "The Mono C# compiler is (C) 2001, 2002 Ximian, Inc.\n\n" +
231 "The compiler source code is released under the terms of the GNU GPL\n\n" +
233 "For more information on Mono, visit the project Web site\n" +
234 " http://www.go-mono.com\n\n" +
236 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
237 Environment.Exit (0);
240 public static int Main (string[] args)
242 bool ok = MainDriver (args);
244 if (ok && Report.Errors == 0) {
245 Console.Write("Compilation succeeded");
246 if (Report.Warnings > 0) {
247 Console.Write(" - {0} warning(s)", Report.Warnings);
252 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
253 Report.Errors, Report.Warnings);
258 static public void LoadAssembly (string assembly, bool soft)
261 string total_log = "";
264 char[] path_chars = { '/', '\\', '.' };
266 if (assembly.IndexOfAny (path_chars) != -1) {
267 a = Assembly.LoadFrom (assembly);
269 a = Assembly.Load (assembly);
271 TypeManager.AddAssembly (a);
273 } catch (FileNotFoundException){
274 foreach (string dir in link_paths){
276 if (assembly.EndsWith (".dll"))
277 full_path = dir + "/" + assembly;
279 full_path = dir + "/" + assembly + ".dll";
282 a = Assembly.LoadFrom (full_path);
283 TypeManager.AddAssembly (a);
285 } catch (FileNotFoundException ff) {
286 total_log += ff.FusionLog;
291 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
292 Console.WriteLine ("Log: \n" + total_log);
294 } catch (BadImageFormatException f) {
295 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
296 } catch (FileLoadException f){
297 Report.Error(6, "Cannot load assembly " + f.FusionLog);
298 } catch (ArgumentNullException){
299 Report.Error(6, "Cannot load assembly (null argument)");
304 /// Loads all assemblies referenced on the command line
306 static public void LoadReferences ()
308 foreach (string r in references)
309 LoadAssembly (r, false);
311 foreach (string r in soft_references)
312 LoadAssembly (r, true);
317 static void SetupDefaultDefines ()
319 defines = new ArrayList ();
320 defines.Add ("__MonoCS__");
323 static string [] LoadArgs (string file)
326 ArrayList args = new ArrayList ();
329 f = new StreamReader (file);
334 StringBuilder sb = new StringBuilder ();
336 while ((line = f.ReadLine ()) != null){
339 for (int i = 0; i < t; i++){
342 if (c == '"' || c == '\''){
345 for (i++; i < t; i++){
352 } else if (c == ' '){
354 args.Add (sb.ToString ());
361 args.Add (sb.ToString ());
366 string [] ret_value = new string [args.Count];
367 args.CopyTo (ret_value, 0);
373 // Returns the directory where the system assemblies are installed
375 static string GetSystemDir ()
377 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
379 foreach (Assembly a in assemblies){
380 string codebase = a.CodeBase;
381 if (codebase.EndsWith ("corlib.dll")){
382 return codebase.Substring (0, codebase.LastIndexOf ("/"));
386 Report.Error (-15, "Can not compute my system path");
391 // Given a path specification, splits the path from the file/pattern
393 static void SplitPathAndPattern (string spec, out string path, out string pattern)
395 int p = spec.LastIndexOf ("/");
398 // Windows does not like /file.cs, switch that to:
403 pattern = spec.Substring (1);
405 path = spec.Substring (0, p);
406 pattern = spec.Substring (p + 1);
411 p = spec.LastIndexOf ("\\");
413 path = spec.Substring (0, p);
414 pattern = spec.Substring (p + 1);
422 static void ProcessFile (string f)
424 if (first_source == null)
427 if (source_files.Contains (f)){
430 "Source file `" + f + "' specified multiple times");
431 Environment.Exit (1);
433 source_files.Add (f, f);
442 static void CompileFiles (string spec, bool recurse)
444 string path, pattern;
446 SplitPathAndPattern (spec, out path, out pattern);
447 if (pattern.IndexOf ("*") == -1){
452 string [] files = null;
454 files = Directory.GetFiles (path, pattern);
455 } catch (System.IO.DirectoryNotFoundException) {
456 Report.Error (2001, "Source file `" + spec + "' could not be found");
458 } catch (System.IO.IOException){
459 Report.Error (2001, "Source file `" + spec + "' could not be found");
462 foreach (string f in files) {
469 string [] dirs = null;
472 dirs = Directory.GetDirectories (path);
476 foreach (string d in dirs) {
478 // Don't include path in this string, as each
479 // directory entry already does
480 CompileFiles (d + "/" + pattern, true);
484 static void DefineDefaultConfig ()
487 // For now the "default config" is harcoded into the compiler
488 // we can move this outside later
490 string [] default_config = {
495 // Is it worth pre-loading all this stuff?
498 "System.Configuration.Install",
501 "System.DirectoryServices",
502 "System.Drawing.Design",
504 "System.EnterpriseServices",
507 "System.Runtime.Remoting",
508 "System.Runtime.Serialization.Formatters.Soap",
510 "System.ServiceProcess",
512 "System.Web.RegularExpressions",
513 "System.Web.Services",
514 "System.Windows.Forms"
519 foreach (string def in default_config)
520 soft_references.Insert (p++, def);
523 static void SetOutputFile (string name)
528 static void SetWarningLevel (string s)
533 level = Int32.Parse (s);
537 "--wlevel requires an value from 0 to 4");
538 Environment.Exit (1);
540 if (level < 0 || level > 4){
541 Report.Error (1900, "Warning level must be 0 to 4");
542 Environment.Exit (1);
544 RootContext.WarningLevel = level;
547 static void Version ()
549 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
550 Console.WriteLine ("Mono C# compiler version {0}", version);
551 Environment.Exit (0);
555 // Currently handles the Unix-like command line options, but will be
556 // deprecated in favor of the CSCParseOption, which will also handle the
557 // options that start with a dash in the future.
559 static bool UnixParseOption (string arg, ref string [] args, ref int i)
574 case "--main": case "-m":
575 if ((i + 1) >= args.Length){
577 Environment.Exit (1);
579 RootContext.MainClass = args [++i];
583 RootContext.Unsafe = true;
586 case "/?": case "/h": case "/help":
589 Environment.Exit (0);
593 if ((i + 1) >= args.Length){
595 Environment.Exit (1);
597 defines.Add (args [++i]);
600 case "--expect-error": {
605 args [++i], NumberStyles.AllowLeadingSign);
606 Report.ExpectedError = code;
608 Report.Error (-14, "Invalid number specified");
619 if ((i + 1) >= args.Length){
621 Environment.Exit (1);
623 SetOutputFile (args [++i]);
627 RootContext.Checked = true;
631 Report.Stacktrace = true;
634 case "--linkresource":
636 if ((i + 1) >= args.Length){
638 Report.Error (5, "Missing argument to --linkres");
639 Environment.Exit (1);
641 if (resources == null)
642 resources = new ArrayList ();
644 resources.Add (args [++i]);
649 if ((i + 1) >= args.Length){
651 Report.Error (5, "Missing argument to --resource");
652 Environment.Exit (1);
654 if (embedded_resources == null)
655 embedded_resources = new ArrayList ();
657 embedded_resources.Add (args [++i]);
661 if ((i + 1) >= args.Length){
662 Environment.Exit (1);
666 string type = args [++i];
669 target = Target.Library;
678 target = Target.WinExe;
682 target = Target.Module;
687 Environment.Exit (1);
693 if ((i + 1) >= args.Length){
695 Environment.Exit (1);
698 references.Add (args [++i]);
702 if ((i + 1) >= args.Length){
704 Environment.Exit (1);
706 link_paths.Add (args [++i]);
710 RootContext.StdLib = false;
718 Report.WarningsAreErrors = true;
722 if ((i + 1) >= args.Length){
724 Environment.Exit (1);
729 warn = Int32.Parse (args [++i]);
732 Environment.Exit (1);
734 Report.SetIgnoreWarning (warn);
738 if ((i + 1) >= args.Length){
741 "--wlevel requires an value from 0 to 4");
742 Environment.Exit (1);
745 SetWarningLevel (args [++i]);
749 if ((i + 1) >= args.Length){
750 Report.Error (5, "--mcs-debug requires an argument");
751 Environment.Exit (1);
755 Report.DebugFlags = Int32.Parse (args [++i]);
757 Report.Error (5, "Invalid argument to --mcs-debug");
758 Environment.Exit (1);
767 if ((i + 1) >= args.Length){
768 Report.Error (5, "--recurse requires an argument");
769 Environment.Exit (1);
771 CompileFiles (args [++i], true);
776 last_time = first_time = DateTime.Now;
777 debug_arglist.Add ("timestamp");
780 case "--debug": case "-g":
781 want_debugging_support = true;
785 if ((i + 1) >= args.Length){
786 Report.Error (5, "--debug-args requires an argument");
787 Environment.Exit (1);
789 char[] sep = { ',' };
790 debug_arglist.AddRange (args [++i].Split (sep));
794 load_default_config = false;
802 // Currently it is very basic option parsing, but eventually, this will
803 // be the complete option parser
805 static bool CSCParseOption (string option, ref string [] args, ref int i)
807 int idx = option.IndexOf (":");
814 arg = option.Substring (0, idx);
816 value = option.Substring (idx + 1);
831 target = Target.WinExe;
835 target = Target.Library;
840 target = Target.Module;
841 target_ext = ".netmodule";
846 Environment.Exit (1);
854 Environment.Exit (1);
856 SetOutputFile (value);
863 case "/incremental+":
864 case "/incremental-":
874 Environment.Exit (1);
877 defs = value.Split (new Char [] {';', ','});
878 foreach (string d in defs){
885 case "/linkresource":
887 Report.Error (5, arg + " requires an argument");
888 Environment.Exit (1);
890 if (resources == null)
891 resources = new ArrayList ();
893 resources.Add (value);
899 Report.Error (5, arg + " requires an argument");
900 Environment.Exit (1);
902 if (embedded_resources == null)
903 embedded_resources = new ArrayList ();
905 embedded_resources.Add (value);
910 Report.Error (5, "/recurse requires an argument");
911 Environment.Exit (1);
913 CompileFiles (value, true);
919 Report.Error (5, arg + " requires an argument");
920 Environment.Exit (1);
923 string [] refs = value.Split (new char [] { ';', ',' });
924 foreach (string r in refs){
934 Report.Error (5, "/lib requires an argument");
935 Environment.Exit (1);
938 libdirs = value.Split (new Char [] { ',' });
939 foreach (string dir in libdirs)
940 link_paths.Add (dir);
946 want_debugging_support = true;
951 RootContext.Checked = true;
955 RootContext.Checked = false;
960 RootContext.Unsafe = true;
964 RootContext.Unsafe = false;
968 case "/warnaserror+":
969 Report.WarningsAreErrors = true;
972 case "/warnaserror-":
973 Report.WarningsAreErrors = false;
977 SetWarningLevel (value);
984 Report.Error (5, "/nowarn requires an argument");
985 Environment.Exit (1);
988 warns = value.Split (new Char [] {','});
989 foreach (string wc in warns){
993 warn = Int32.Parse (wc);
996 Environment.Exit (1);
998 Report.SetIgnoreWarning (warn);
1004 load_default_config = false;
1010 Environment.Exit (0);
1016 Report.Error (5, arg + " requires an argument");
1017 Environment.Exit (1);
1019 RootContext.MainClass = value;
1024 RootContext.StdLib = false;
1028 RootContext.StdLib = true;
1037 if (value == "utf8")
1038 cp = (new UTF8Encoding()).WindowsCodePage;
1039 if (value == "reset"){
1041 using_default_encoder = true;
1045 cp = Int32.Parse (value);
1049 Console.WriteLine ("Invalid code-page requested");
1054 encoding = Encoding.GetEncoding (cp);
1055 using_default_encoder = false;
1057 Console.WriteLine ("Code page: {0} not supported", cp);
1066 /// Parses the arguments, and drives the compilation
1071 /// TODO: Mostly structured to debug the compiler
1072 /// now, needs to be turned into a real driver soon.
1074 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1075 static bool MainDriver (string [] args)
1078 bool parsing_options = true;
1081 encoding = Encoding.GetEncoding (28591);
1083 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1084 encoding = Encoding.GetEncoding (1252);
1087 references = new ArrayList ();
1088 soft_references = new ArrayList ();
1089 link_paths = new ArrayList ();
1091 SetupDefaultDefines ();
1096 // This is not required because Assembly.Load knows about this
1100 int argc = args.Length;
1101 for (i = 0; i < argc; i++){
1102 string arg = args [i];
1104 if (arg.StartsWith ("@")){
1105 string [] new_args, extra_args;
1106 string response_file = arg.Substring (1);
1108 if (response_file_list == null)
1109 response_file_list = new Hashtable ();
1111 if (response_file_list.Contains (response_file)){
1113 1515, "Response file `" + response_file +
1114 "' specified multiple times");
1115 Environment.Exit (1);
1118 response_file_list.Add (response_file, response_file);
1120 extra_args = LoadArgs (response_file);
1121 if (extra_args == null){
1122 Report.Error (2011, "Unable to open response file: " +
1127 new_args = new string [extra_args.Length + argc];
1128 args.CopyTo (new_args, 0);
1129 extra_args.CopyTo (new_args, argc);
1131 argc = new_args.Length;
1135 if (parsing_options){
1137 parsing_options = false;
1141 if (arg.StartsWith ("-")){
1142 if (UnixParseOption (arg, ref args, ref i))
1146 string csc_opt = "/" + arg.Substring (1);
1147 if (CSCParseOption (csc_opt, ref args, ref i))
1150 if (arg.StartsWith ("/")){
1151 if (CSCParseOption (arg, ref args, ref i))
1157 CompileFiles (arg, false);
1163 if (first_source == null){
1164 Report.Error (2008, "No files to compile were specified");
1168 if (Report.Errors > 0)
1175 // Load Core Library for default compilation
1177 if (RootContext.StdLib)
1178 references.Insert (0, "mscorlib");
1180 if (load_default_config)
1181 DefineDefaultConfig ();
1183 if (Report.Errors > 0){
1188 // Load assemblies required
1191 ShowTime ("Loading references");
1192 link_paths.Add (GetSystemDir ());
1196 ShowTime (" References loaded");
1198 if (Report.Errors > 0){
1205 if (output_file == null){
1206 int pos = first_source.LastIndexOf (".");
1209 output_file = first_source.Substring (0, pos) + target_ext;
1211 output_file = first_source + target_ext;
1214 string[] debug_args = new string [debug_arglist.Count];
1215 debug_arglist.CopyTo (debug_args);
1216 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
1218 TypeManager.AddModule (CodeGen.ModuleBuilder);
1221 DateTime start = DateTime.Now;
1222 TypeManager.GetAssemblyNamespaces (output_file);
1223 DateTime end = DateTime.Now;
1224 //Console.WriteLine ("Loading namespaces: " + (end - start));
1225 start = DateTime.Now;
1226 //TypeManager.GetAllTypes ();
1228 //Console.WriteLine ("Getting Types: " + (end - start));
1232 // Before emitting, we need to get the core
1233 // types emitted from the user defined types
1234 // or from the system ones.
1237 ShowTime ("Initializing Core Types");
1238 if (!RootContext.StdLib){
1239 RootContext.ResolveCore ();
1240 if (Report.Errors > 0)
1244 TypeManager.InitCoreTypes ();
1246 ShowTime (" Core Types done");
1249 // The second pass of the compiler
1252 ShowTime ("Resolving tree");
1253 RootContext.ResolveTree ();
1255 ShowTime ("Populate tree");
1256 if (!RootContext.StdLib)
1257 RootContext.BootCorlib_PopulateCoreTypes ();
1258 RootContext.PopulateTypes ();
1259 RootContext.DefineTypes ();
1261 TypeManager.InitCodeHelpers ();
1263 if (Report.Errors > 0){
1268 // The code generator
1271 ShowTime ("Emitting code");
1272 ShowTotalTime ("Total so far");
1273 RootContext.EmitCode ();
1277 if (Report.Errors > 0){
1282 ShowTime ("Closing types");
1284 if (RootContext.WarningLevel >= 4)
1285 if (!Namespace.VerifyUsing ())
1288 RootContext.CloseTypes ();
1290 PEFileKinds k = PEFileKinds.ConsoleApplication;
1292 if (target == Target.Library || target == Target.Module)
1293 k = PEFileKinds.Dll;
1294 else if (target == Target.Exe)
1295 k = PEFileKinds.ConsoleApplication;
1296 else if (target == Target.WinExe)
1297 k = PEFileKinds.WindowApplication;
1299 if (target == Target.Exe || target == Target.WinExe){
1300 MethodInfo ep = RootContext.EntryPoint;
1303 if (Report.Errors == 0)
1304 Report.Error (5001, "Program " + output_file +
1305 " does not have an entry point defined");
1309 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1313 // Add the resources
1315 if (resources != null){
1316 foreach (string spec in resources){
1320 cp = spec.IndexOf (',');
1322 file = spec.Substring (0, cp);
1323 res = spec.Substring (cp + 1);
1327 CodeGen.AssemblyBuilder.AddResourceFile (res, file);
1331 if (embedded_resources != null){
1332 object[] margs = new object [2];
1333 Type[] argst = new Type [2];
1334 argst [0] = argst [1] = typeof (string);
1335 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod ("EmbedResourceFile", argst);
1336 if (embed_res == null) {
1337 Report.Warning (0, new Location (-1), "Cannot embed resources on this runtime: try the Mono runtime instead.");
1339 foreach (string spec in embedded_resources) {
1342 cp = spec.IndexOf (',');
1344 margs [0] = spec.Substring (cp + 1);
1345 margs [1] = spec.Substring (0, cp);
1347 margs [0] = margs [1] = spec;
1349 if (File.Exists ((string) margs [1]))
1350 embed_res.Invoke (CodeGen.AssemblyBuilder, margs);
1352 Report.Error (1566, "Can not find the resource " + margs [1]);
1358 if (Report.Errors > 0)
1361 CodeGen.Save (output_file);
1363 ShowTime ("Saved output");
1364 ShowTotalTime ("Total");
1367 Timer.ShowTimers ();
1369 if (want_debugging_support) {
1370 // Avoid error if we don't support debugging for the platform
1372 CodeGen.SaveSymbols ();
1373 } catch (Exception) { }
1376 ShowTime ("Saved symbols");
1379 if (Report.ExpectedError != 0){
1380 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1381 Environment.Exit (1);
1386 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1387 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1389 return (Report.Errors == 0);