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;
92 public static void ShowTime (string msg)
97 DateTime now = DateTime.Now;
98 TimeSpan span = now - last_time;
102 "[{0:00}:{1:000}] {2}",
103 (int) span.TotalSeconds, span.Milliseconds, msg);
106 public static void ShowTotalTime (string msg)
111 DateTime now = DateTime.Now;
112 TimeSpan span = now - first_time;
116 "[{0:00}:{1:000}] {2}",
117 (int) span.TotalSeconds, span.Milliseconds, msg);
120 static void tokenize_file (string input_file)
125 input = File.OpenRead (input_file);
127 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
132 Tokenizer lexer = new Tokenizer (input, input_file, defines);
133 int token, tokens = 0, errors = 0;
135 while ((token = lexer.token ()) != Token.EOF){
136 Location l = lexer.Location;
138 if (token == Token.ERROR)
141 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
147 // MonoTODO("Change error code for aborted compilation to something reasonable")]
148 static void parse (string input_file)
154 input = File.OpenRead (input_file);
156 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
160 parser = new CSharpParser (input_file, input, defines);
161 parser.yacc_verbose = yacc_verbose;
164 } catch (Exception ex) {
165 Report.Error(666, "Compilation aborted: " + ex);
174 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
175 "mcs [options] source-files\n" +
176 " --about About the Mono C# compiler\n" +
177 " -checked[+|-] Set default context to checked\n" +
178 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
179 " -debug[+-] Generate debugging information\n" +
180 " -g Generate debugging information\n" +
181 " --debug-args X Specify additional arguments for the\n" +
182 " symbol writer.\n" +
183 " --fatal Makes errors fatal\n" +
184 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
185 " -main:class Specified the class that contains the entry point\n" +
186 " -noconfig[+|-] Disables implicit references to assemblies\n" +
187 " -nostdlib[+|-] Does not load core libraries\n" +
188 " -nowarn:W1[,W2] Disables one or more warnings\n" +
189 " -out:FNAME Specifies output file\n" +
190 " --parse Only parses the source file\n" +
191 " --expect-error X Expect that error X will be encountered\n" +
192 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
193 " -linkresource:FILE Links FILE as a resource\n" +
194 " -resource:FILE Embed FILE as a resource\n" +
195 " -reference:ASS References the specified assembly (-r:ASS)\n" +
196 " --stacktrace Shows stack trace at error location\n" +
197 " -target:KIND Specifies the target (KIND is one of: exe, winexe, " +
198 "library, module), (short: /t:)\n" +
199 " --timestamp Displays time stamps of various compiler events\n" +
200 " -unsafe[+|-] Allows unsafe code\n" +
201 " -warnaserror[+|-] Treat warnings as errors\n" +
202 " -warn:LEVEL Sets warning level (the highest is 4, the default)\n" +
203 " -v Verbose parsing (for debugging the parser)\n" +
205 " --mcs-debug X Sets MCS debugging level to X\n" +
207 " @file Read response file for more options\n\n" +
208 "Options can be of the form -option or /option");
214 "The Mono C# compiler is (C) 2001, 2002 Ximian, Inc.\n\n" +
215 "The compiler source code is released under the terms of the GNU GPL\n\n" +
217 "For more information on Mono, visit the project Web site\n" +
218 " http://www.go-mono.com\n\n" +
220 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
221 Environment.Exit (0);
224 public static int Main (string[] args)
226 bool ok = MainDriver (args);
228 if (ok && Report.Errors == 0) {
229 Console.Write("Compilation succeeded");
230 if (Report.Warnings > 0) {
231 Console.Write(" - {0} warning(s)", Report.Warnings);
236 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
237 Report.Errors, Report.Warnings);
242 static public void LoadAssembly (string assembly, bool soft)
245 string total_log = "";
248 char[] path_chars = { '/', '\\', '.' };
250 if (assembly.IndexOfAny (path_chars) != -1) {
251 a = Assembly.LoadFrom (assembly);
253 a = Assembly.Load (assembly);
255 TypeManager.AddAssembly (a);
257 } catch (FileNotFoundException){
258 foreach (string dir in link_paths){
260 if (assembly.EndsWith (".dll"))
261 full_path = dir + "/" + assembly;
263 full_path = dir + "/" + assembly + ".dll";
266 a = Assembly.LoadFrom (full_path);
267 TypeManager.AddAssembly (a);
269 } catch (FileNotFoundException ff) {
270 total_log += ff.FusionLog;
275 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
276 Console.WriteLine ("Log: \n" + total_log);
278 } catch (BadImageFormatException f) {
279 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
280 } catch (FileLoadException f){
281 Report.Error(6, "Cannot load assembly " + f.FusionLog);
282 } catch (ArgumentNullException){
283 Report.Error(6, "Cannot load assembly (null argument)");
288 /// Loads all assemblies referenced on the command line
290 static public void LoadReferences ()
292 foreach (string r in references)
293 LoadAssembly (r, false);
295 foreach (string r in soft_references)
296 LoadAssembly (r, true);
301 static void SetupDefaultDefines ()
303 defines = new ArrayList ();
304 defines.Add ("__MonoCS__");
307 static string [] LoadArgs (string file)
310 ArrayList args = new ArrayList ();
313 f = new StreamReader (file);
318 StringBuilder sb = new StringBuilder ();
320 while ((line = f.ReadLine ()) != null){
323 for (int i = 0; i < t; i++){
326 if (c == '"' || c == '\''){
329 for (i++; i < t; i++){
336 } else if (c == ' '){
338 args.Add (sb.ToString ());
345 args.Add (sb.ToString ());
350 string [] ret_value = new string [args.Count];
351 args.CopyTo (ret_value, 0);
357 // Returns the directory where the system assemblies are installed
359 static string GetSystemDir ()
361 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
363 foreach (Assembly a in assemblies){
364 string codebase = a.CodeBase;
365 if (codebase.EndsWith ("corlib.dll")){
366 return codebase.Substring (0, codebase.LastIndexOf ("/"));
370 Report.Error (-15, "Can not compute my system path");
375 // Given a path specification, splits the path from the file/pattern
377 static void SplitPathAndPattern (string spec, out string path, out string pattern)
379 int p = spec.LastIndexOf ("/");
382 // Windows does not like /file.cs, switch that to:
387 pattern = spec.Substring (1);
389 path = spec.Substring (0, p);
390 pattern = spec.Substring (p + 1);
395 p = spec.LastIndexOf ("\\");
397 path = spec.Substring (0, p);
398 pattern = spec.Substring (p + 1);
406 static void ProcessFile (string f)
408 if (first_source == null)
411 if (source_files.Contains (f)){
414 "Source file `" + f + "' specified multiple times");
415 Environment.Exit (1);
417 source_files.Add (f, f);
426 static void CompileFiles (string spec, bool recurse)
428 string path, pattern;
430 SplitPathAndPattern (spec, out path, out pattern);
431 if (pattern.IndexOf ("*") == -1){
436 string [] files = null;
438 files = Directory.GetFiles (path, pattern);
439 } catch (System.IO.DirectoryNotFoundException) {
440 Report.Error (2001, "Source file `" + spec + "' could not be found");
442 } catch (System.IO.IOException){
443 Report.Error (2001, "Source file `" + spec + "' could not be found");
446 foreach (string f in files) {
453 string [] dirs = null;
456 dirs = Directory.GetDirectories (path);
460 foreach (string d in dirs) {
462 // Don't include path in this string, as each
463 // directory entry already does
464 CompileFiles (d + "/" + pattern, true);
468 static void DefineDefaultConfig ()
471 // For now the "default config" is harcoded into the compiler
472 // we can move this outside later
474 string [] default_config = {
479 // Is it worth pre-loading all this stuff?
482 "System.Configuration.Install",
485 "System.DirectoryServices",
486 "System.Drawing.Design",
488 "System.EnterpriseServices",
491 "System.Runtime.Remoting",
492 "System.Runtime.Serialization.Formatters.Soap",
494 "System.ServiceProcess",
496 "System.Web.RegularExpressions",
497 "System.Web.Services",
498 "System.Windows.Forms"
503 foreach (string def in default_config)
504 soft_references.Insert (p++, def);
507 static void SetOutputFile (string name)
510 string bname = CodeGen.Basename (output_file);
511 if (bname.IndexOf (".") == -1)
512 output_file += ".exe";
515 static void SetWarningLevel (string s)
520 level = Int32.Parse (s);
524 "--wlevel requires an value from 0 to 4");
525 Environment.Exit (1);
527 if (level < 0 || level > 4){
528 Report.Error (1900, "Warning level must be 0 to 4");
529 Environment.Exit (1);
531 RootContext.WarningLevel = level;
534 // Currently handles the Unix-like command line options, but will be
535 // deprecated in favor of the CSCParseOption, which will also handle the
536 // options that start with a dash in the future.
538 static bool UnixParseOption (string arg, ref string [] args, ref int i)
549 case "--main": case "-m":
550 if ((i + 1) >= args.Length){
552 Environment.Exit (1);
554 RootContext.MainClass = args [++i];
558 RootContext.Unsafe = true;
561 case "/?": case "/h": case "/help":
564 Environment.Exit (0);
568 if ((i + 1) >= args.Length){
570 Environment.Exit (1);
572 defines.Add (args [++i]);
575 case "--expect-error": {
580 args [++i], NumberStyles.AllowLeadingSign);
581 Report.ExpectedError = code;
583 Report.Error (-14, "Invalid number specified");
594 if ((i + 1) >= args.Length){
596 Environment.Exit (1);
598 SetOutputFile (args [++i]);
602 RootContext.Checked = true;
606 Report.Stacktrace = true;
609 case "--linkresource":
611 if ((i + 1) >= args.Length){
613 Console.WriteLine("Missing argument to --linkres");
614 Environment.Exit (1);
616 if (resources == null)
617 resources = new ArrayList ();
619 resources.Add (args [++i]);
624 if ((i + 1) >= args.Length){
626 Console.WriteLine("Missing argument to --resource");
627 Environment.Exit (1);
629 if (embedded_resources == null)
630 embedded_resources = new ArrayList ();
632 embedded_resources.Add (args [++i]);
636 if ((i + 1) >= args.Length){
637 Environment.Exit (1);
641 string type = args [++i];
644 target = Target.Library;
653 target = Target.WinExe;
657 target = Target.Module;
662 Environment.Exit (1);
668 if ((i + 1) >= args.Length){
670 Environment.Exit (1);
673 references.Add (args [++i]);
677 if ((i + 1) >= args.Length){
679 Environment.Exit (1);
681 link_paths.Add (args [++i]);
685 RootContext.StdLib = false;
693 Report.WarningsAreErrors = true;
697 if ((i + 1) >= args.Length){
699 Environment.Exit (1);
704 warn = Int32.Parse (args [++i]);
707 Environment.Exit (1);
709 Report.SetIgnoreWarning (warn);
713 if ((i + 1) >= args.Length){
716 "--wlevel requires an value from 0 to 4");
717 Environment.Exit (1);
720 SetWarningLevel (args [++i]);
725 if ((i + 1) >= args.Length){
726 Console.WriteLine ("--mcs-debug requires an argument");
727 Environment.Exit (1);
731 Report.DebugFlags = Int32.Parse (args [++i]);
733 Console.WriteLine ("Invalid argument to --mcs-debug");
734 Environment.Exit (1);
744 if ((i + 1) >= args.Length){
745 Console.WriteLine ("--recurse requires an argument");
746 Environment.Exit (1);
748 CompileFiles (args [++i], true);
753 last_time = first_time = DateTime.Now;
754 debug_arglist.Add ("timestamp");
757 case "--debug": case "-g":
758 want_debugging_support = true;
762 if ((i + 1) >= args.Length){
763 Console.WriteLine ("--debug-args requires an argument");
764 Environment.Exit (1);
766 char[] sep = { ',' };
767 debug_arglist.AddRange (args [++i].Split (sep));
771 load_default_config = false;
779 // Currently it is very basic option parsing, but eventually, this will
780 // be the complete option parser
782 static bool CSCParseOption (string option, ref string [] args, ref int i)
784 int idx = option.IndexOf (":");
791 arg = option.Substring (0, idx);
793 value = option.Substring (idx + 1);
808 target = Target.WinExe;
812 target = Target.Library;
817 target = Target.Module;
823 Environment.Exit (1);
831 Environment.Exit (1);
833 SetOutputFile (value);
840 case "/incremental+":
841 case "/incremental-":
851 Environment.Exit (1);
854 defs = value.Split (new Char [] {';'});
855 foreach (string d in defs){
862 case "/linkresource":
864 Console.WriteLine ("{0} requires an argument", arg);
865 Environment.Exit (1);
867 if (resources == null)
868 resources = new ArrayList ();
870 resources.Add (value);
876 Console.WriteLine ("{0} requires an argument", arg);
877 Environment.Exit (1);
879 if (embedded_resources == null)
880 embedded_resources = new ArrayList ();
882 embedded_resources.Add (value);
887 Console.WriteLine ("/recurse requires an argument");
888 Environment.Exit (1);
890 CompileFiles (value, true);
896 Console.WriteLine ("/reference requires an argument");
897 Environment.Exit (1);
899 references.Add (value);
906 Console.WriteLine ("/lib requires an argument");
907 Environment.Exit (1);
910 libdirs = value.Split (new Char [] { ',' });
911 foreach (string dir in libdirs)
912 link_paths.Add (dir);
918 want_debugging_support = true;
923 RootContext.Checked = true;
927 RootContext.Checked = false;
932 RootContext.Unsafe = true;
936 RootContext.Unsafe = false;
940 case "/warnaserror+":
941 Report.WarningsAreErrors = true;
944 case "/warnaserror-":
945 Report.WarningsAreErrors = false;
949 SetWarningLevel (value);
956 Console.WriteLine ("/nowarn requires an argument");
957 Environment.Exit (1);
960 warns = value.Split (new Char [] {','});
961 foreach (string wc in warns){
965 warn = Int32.Parse (wc);
968 Environment.Exit (1);
970 Report.SetIgnoreWarning (warn);
976 load_default_config = false;
982 Environment.Exit (0);
988 Console.WriteLine ("/main requires an argument");
989 Environment.Exit (1);
991 RootContext.MainClass = value;
996 RootContext.StdLib = false;
1000 RootContext.StdLib = true;
1008 /// Parses the arguments, and drives the compilation
1013 /// TODO: Mostly structured to debug the compiler
1014 /// now, needs to be turned into a real driver soon.
1016 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1017 static bool MainDriver (string [] args)
1020 bool parsing_options = true;
1022 references = new ArrayList ();
1023 soft_references = new ArrayList ();
1024 link_paths = new ArrayList ();
1026 SetupDefaultDefines ();
1031 // This is not required because Assembly.Load knows about this
1035 int argc = args.Length;
1036 for (i = 0; i < argc; i++){
1037 string arg = args [i];
1039 if (arg.StartsWith ("@")){
1040 string [] new_args, extra_args;
1041 string response_file = arg.Substring (1);
1043 if (response_file_list == null)
1044 response_file_list = new Hashtable ();
1046 if (response_file_list.Contains (response_file)){
1048 1515, "Response file `" + response_file +
1049 "' specified multiple times");
1050 Environment.Exit (1);
1053 response_file_list.Add (response_file, response_file);
1055 extra_args = LoadArgs (response_file);
1056 if (extra_args == null){
1057 Report.Error (2011, "Unable to open response file: " +
1062 new_args = new string [extra_args.Length + argc];
1063 args.CopyTo (new_args, 0);
1064 extra_args.CopyTo (new_args, argc);
1066 argc = new_args.Length;
1070 if (parsing_options){
1072 parsing_options = false;
1076 if (arg.StartsWith ("-")){
1077 if (UnixParseOption (arg, ref args, ref i))
1081 string csc_opt = "/" + arg.Substring (1);
1082 if (CSCParseOption (csc_opt, ref args, ref i))
1085 if (arg.StartsWith ("/")){
1086 if (CSCParseOption (arg, ref args, ref i))
1092 CompileFiles (arg, false);
1098 if (first_source == null){
1099 Report.Error (2008, "No files to compile were specified");
1103 if (Report.Errors > 0)
1110 // Load Core Library for default compilation
1112 if (RootContext.StdLib)
1113 references.Insert (0, "mscorlib");
1115 if (load_default_config)
1116 DefineDefaultConfig ();
1118 if (Report.Errors > 0){
1123 // Load assemblies required
1126 ShowTime ("Loading references");
1127 link_paths.Add (GetSystemDir ());
1131 ShowTime (" References loaded");
1133 if (Report.Errors > 0){
1140 if (output_file == null){
1141 int pos = first_source.LastIndexOf (".");
1144 output_file = first_source.Substring (0, pos) + target_ext;
1146 output_file = first_source + target_ext;
1149 string[] debug_args = new string [debug_arglist.Count];
1150 debug_arglist.CopyTo (debug_args);
1151 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
1153 TypeManager.AddModule (CodeGen.ModuleBuilder);
1156 // Before emitting, we need to get the core
1157 // types emitted from the user defined types
1158 // or from the system ones.
1161 ShowTime ("Initializing Core Types");
1162 if (!RootContext.StdLib){
1163 RootContext.ResolveCore ();
1164 if (Report.Errors > 0)
1168 TypeManager.InitCoreTypes ();
1170 ShowTime (" Core Types done");
1173 // The second pass of the compiler
1176 ShowTime ("Resolving tree");
1177 RootContext.ResolveTree ();
1179 ShowTime ("Populate tree");
1180 if (!RootContext.StdLib)
1181 RootContext.BootCorlib_PopulateCoreTypes ();
1182 RootContext.PopulateTypes ();
1184 TypeManager.InitCodeHelpers ();
1186 if (Report.Errors > 0){
1191 // The code generator
1194 ShowTime ("Emitting code");
1195 ShowTotalTime ("Total so far");
1196 RootContext.EmitCode ();
1200 if (Report.Errors > 0){
1205 ShowTime ("Closing types");
1207 RootContext.CloseTypes ();
1209 PEFileKinds k = PEFileKinds.ConsoleApplication;
1211 if (target == Target.Library || target == Target.Module)
1212 k = PEFileKinds.Dll;
1213 else if (target == Target.Exe)
1214 k = PEFileKinds.ConsoleApplication;
1215 else if (target == Target.WinExe)
1216 k = PEFileKinds.WindowApplication;
1218 if (target == Target.Exe || target == Target.WinExe){
1219 MethodInfo ep = RootContext.EntryPoint;
1222 if (Report.Errors == 0)
1223 Report.Error (5001, "Program " + output_file +
1224 " does not have an entry point defined");
1228 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1232 // Add the resources
1234 if (resources != null){
1235 foreach (string file in resources)
1236 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
1239 if (embedded_resources != null){
1240 object[] margs = new object [2];
1241 Type[] argst = new Type [2];
1242 argst [0] = argst [1] = typeof (string);
1243 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod ("EmbedResourceFile", argst);
1244 if (embed_res == null) {
1245 Report.Warning (0, new Location (-1), "Cannot embed resources on this runtime: try the Mono runtime instead.");
1247 foreach (string file in embedded_resources) {
1248 margs [0] = margs [1] = file;
1249 embed_res.Invoke (CodeGen.AssemblyBuilder, margs);
1254 CodeGen.Save (output_file);
1256 ShowTime ("Saved output");
1257 ShowTotalTime ("Total");
1260 Timer.ShowTimers ();
1262 if (want_debugging_support) {
1263 CodeGen.SaveSymbols ();
1265 ShowTime ("Saved symbols");
1268 if (Report.ExpectedError != 0){
1269 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1270 Environment.Exit (1);
1274 return (Report.Errors == 0);