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;
18 using System.Globalization;
22 Library, Exe, Module, WinExe
26 /// The compiler driver.
32 // Assemblies references to be linked. Initialized with
34 static ArrayList references;
37 // If any of these fail, we ignore the problem. This is so
38 // that we can list all the assemblies in Windows and not fail
39 // if they are missing on Linux.
41 static ArrayList soft_references;
44 static ArrayList link_paths;
46 // Whether we want Yacc to output its progress
47 static bool yacc_verbose = false;
49 // Whether we want to only run the tokenizer
50 static bool tokenize = false;
52 static string first_source;
54 static Target target = Target.Exe;
55 static string target_ext = ".exe";
57 static bool want_debugging_support = false;
58 static ArrayList debug_arglist = new ArrayList ();
60 static bool parse_only = false;
61 static bool timestamps = false;
64 // Whether to load the initial config file (what CSC.RSP has by default)
66 static bool load_default_config = true;
68 static Hashtable response_file_list;
69 static Hashtable source_files = new Hashtable ();
72 // A list of resource files
74 static ArrayList resources;
75 static ArrayList embedded_resources;
78 // An array of the defines from the command line
80 static ArrayList defines;
85 static string output_file = null;
88 // Last time we took the time
90 static DateTime last_time;
91 static void ShowTime (string msg)
93 DateTime now = DateTime.Now;
94 TimeSpan span = now - last_time;
98 "[{0:00}:{1:000}] {2}",
99 (int) span.TotalSeconds, span.Milliseconds, msg);
102 static void tokenize_file (string input_file)
107 input = File.OpenRead (input_file);
109 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
114 Tokenizer lexer = new Tokenizer (input, input_file, defines);
115 int token, tokens = 0, errors = 0;
117 while ((token = lexer.token ()) != Token.EOF){
118 Location l = lexer.Location;
120 if (token == Token.ERROR)
123 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
129 // MonoTODO("Change error code for aborted compilation to something reasonable")]
130 static void parse (string input_file)
136 input = File.OpenRead (input_file);
138 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
142 parser = new CSharpParser (input_file, input, defines);
143 parser.yacc_verbose = yacc_verbose;
146 } catch (Exception ex) {
147 Report.Error(666, "Compilation aborted: " + ex);
156 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
157 "mcs [options] source-files\n" +
158 " --about About the Mono C# compiler\n" +
159 " --checked Set default context to checked\n" +
160 " --define SYM Defines the symbol SYM\n" +
161 " --debug Generate debugging information\n" +
162 " -g Generate debugging information\n" +
163 " --debug-args X Specify additional arguments for the\n" +
164 " symbol writer.\n" +
165 " --fatal Makes errors fatal\n" +
166 " -L PATH Adds PATH to the assembly link path\n" +
167 " --noconfig Disables implicit references to assemblies\n" +
168 " --nostdlib Does not load core libraries\n" +
169 " --nowarn XXX Ignores warning number XXX\n" +
170 " -o FNAME Specifies output file\n" +
171 " -g, --debug Write symbolic debugging information to FILE-debug.s\n" +
172 " --parse Only parses the source file\n" +
173 " --expect-error X Expect that error X will be encountered\n" +
174 " --recurse SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
175 " --linkres FILE Links FILE as a resource\n" +
176 " --resource FILE Embed FILE as a resource\n" +
177 " --stacktrace Shows stack trace at error location\n" +
178 " --target KIND Specifies the target (KIND is one of: exe, winexe, " +
179 "library, module)\n" +
180 " --timestamp Displays time stamps of various compiler events\n" +
181 " --unsafe Allows unsafe code\n" +
182 " --werror Treat warnings as errors\n" +
183 " --wlevel LEVEL Sets warning level (the highest is 4, the default)\n" +
184 " -r References an assembly\n" +
185 " -v Verbose parsing (for debugging the parser)\n" +
187 " --mcs-debug X Sets MCS debugging level to X" +
189 " @file Read response file for more options");
195 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
196 "The compiler source code is released under the terms of the GNU GPL\n\n" +
198 "For more information on Mono, visit the project Web site\n" +
199 " http://www.go-mono.com\n\n" +
201 "The compiler was written by Miguel de Icaza, Ravi Pratap and Martin Baulig");
204 public static int Main (string[] args)
206 bool ok = MainDriver (args);
208 if (ok && Report.Errors == 0) {
209 Console.Write("Compilation succeeded");
210 if (Report.Warnings > 0) {
211 Console.Write(" - {0} warning(s)", Report.Warnings);
216 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
217 Report.Errors, Report.Warnings);
222 static public void LoadAssembly (string assembly, bool soft)
225 string total_log = "";
228 char[] path_chars = { '/', '\\', '.' };
230 if (assembly.IndexOfAny (path_chars) != -1) {
231 a = Assembly.LoadFrom (assembly);
233 a = Assembly.Load (assembly);
235 TypeManager.AddAssembly (a);
237 } catch (FileNotFoundException){
238 foreach (string dir in link_paths){
240 if (assembly.EndsWith (".dll"))
241 full_path = dir + "/" + assembly;
243 full_path = dir + "/" + assembly + ".dll";
246 a = Assembly.LoadFrom (full_path);
247 TypeManager.AddAssembly (a);
249 } catch (FileNotFoundException ff) {
250 total_log += ff.FusionLog;
255 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
256 Console.WriteLine ("Log: \n" + total_log);
258 } catch (BadImageFormatException f) {
259 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
260 } catch (FileLoadException f){
261 Report.Error(6, "Cannot load assembly " + f.FusionLog);
262 } catch (ArgumentNullException){
263 Report.Error(6, "Cannot load assembly (null argument)");
268 /// Loads all assemblies referenced on the command line
270 static public void LoadReferences ()
272 foreach (string r in references)
273 LoadAssembly (r, false);
275 foreach (string r in soft_references)
276 LoadAssembly (r, true);
281 static void SetupDefaultDefines ()
283 defines = new ArrayList ();
284 defines.Add ("__MonoCS__");
287 static string [] LoadArgs (string file)
290 ArrayList args = new ArrayList ();
293 f = new StreamReader (file);
298 while ((line = f.ReadLine ()) != null){
299 string [] line_args = line.Split (new char [] { ' ' });
301 foreach (string arg in line_args)
305 string [] ret_value = new string [args.Count];
306 args.CopyTo (ret_value, 0);
312 // Returns the directory where the system assemblies are installed
314 static string GetSystemDir ()
316 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
318 foreach (Assembly a in assemblies){
319 string codebase = a.CodeBase;
320 if (codebase.EndsWith ("corlib.dll")){
321 return codebase.Substring (0, codebase.LastIndexOf ("/"));
325 Report.Error (-15, "Can not compute my system path");
330 // Given a path specification, splits the path from the file/pattern
332 static void SplitPathAndPattern (string spec, out string path, out string pattern)
334 int p = spec.LastIndexOf ("/");
337 // Windows does not like /file.cs, switch that to:
342 pattern = spec.Substring (1);
344 path = spec.Substring (0, p);
345 pattern = spec.Substring (p + 1);
350 p = spec.LastIndexOf ("\\");
352 path = spec.Substring (0, p);
353 pattern = spec.Substring (p + 1);
361 static void ProcessFile (string f)
363 if (first_source == null)
366 if (source_files.Contains (f)){
369 "Source file `" + f + "' specified multiple times");
370 Environment.Exit (1);
372 source_files.Add (f, f);
381 static void CompileFiles (string spec, bool recurse)
383 string path, pattern;
385 SplitPathAndPattern (spec, out path, out pattern);
386 if (pattern.IndexOf ("*") == -1){
391 string [] files = null;
393 files = Directory.GetFiles (path, pattern);
394 } catch (System.IO.DirectoryNotFoundException) {
395 Report.Error (2001, "Source file `" + spec + "' could not be found");
397 } catch (System.IO.IOException){
398 Report.Error (2001, "Source file `" + spec + "' could not be found");
401 foreach (string f in files) {
408 string [] dirs = null;
411 dirs = Directory.GetDirectories (path);
415 foreach (string d in dirs) {
417 // Don't include path in this string, as each
418 // directory entry already does
419 CompileFiles (d + "/" + pattern, true);
423 static void DefineDefaultConfig ()
426 // For now the "default config" is harcoded into the compiler
427 // we can move this outside later
429 string [] default_config = {
434 // Is it worth pre-loading all this stuff?
437 "System.Configuration.Install",
440 "System.DirectoryServices",
441 "System.Drawing.Design",
443 "System.EnterpriseServices",
446 "System.Runtime.Remoting",
447 "System.Runtime.Serialization.Formatters.Soap",
449 "System.ServiceProcess",
451 "System.Web.RegularExpressions",
452 "System.Web.Services",
453 "System.Windows.Forms"
458 foreach (string def in default_config)
459 soft_references.Insert (p++, def);
462 static void SetOutputFile (string name)
465 string bname = CodeGen.Basename (output_file);
466 if (bname.IndexOf (".") == -1)
467 output_file += ".exe";
470 static void SetWarningLevel (string s)
475 level = Int32.Parse (s);
479 "--wlevel requires an value from 0 to 4");
480 Environment.Exit (1);
482 if (level < 0 || level > 4){
483 Report.Error (1900, "Warning level must be 0 to 4");
484 Environment.Exit (1);
486 RootContext.WarningLevel = level;
489 // Currently handles the Unix-like command line options, but will be
490 // deprecated in favor of the CSCParseOption, which will also handle the
491 // options that start with a dash in the future.
493 static bool UnixParseOption (string arg, ref string [] args, ref int i)
504 case "--main": case "-m":
505 if ((i + 1) >= args.Length){
507 Environment.Exit (1);
509 RootContext.MainClass = args [++i];
513 RootContext.Unsafe = true;
516 case "/?": case "/h": case "/help":
519 Environment.Exit (0);
523 if ((i + 1) >= args.Length){
525 Environment.Exit (1);
527 defines.Add (args [++i]);
530 case "--expect-error": {
535 args [++i], NumberStyles.AllowLeadingSign);
536 Report.ExpectedError = code;
538 Report.Error (-14, "Invalid number specified");
549 if ((i + 1) >= args.Length){
551 Environment.Exit (1);
553 SetOutputFile (args [++i]);
557 RootContext.Checked = true;
561 Report.Stacktrace = true;
564 case "--linkresource":
566 if ((i + 1) >= args.Length){
568 Console.WriteLine("Missing argument to --linkres");
569 Environment.Exit (1);
571 if (resources == null)
572 resources = new ArrayList ();
574 resources.Add (args [++i]);
579 if ((i + 1) >= args.Length){
581 Console.WriteLine("Missing argument to --resource");
582 Environment.Exit (1);
584 if (embedded_resources == null)
585 embedded_resources = new ArrayList ();
587 embedded_resources.Add (args [++i]);
591 if ((i + 1) >= args.Length){
592 Environment.Exit (1);
596 string type = args [++i];
599 target = Target.Library;
608 target = Target.WinExe;
612 target = Target.Module;
617 Environment.Exit (1);
623 if ((i + 1) >= args.Length){
625 Environment.Exit (1);
628 references.Add (args [++i]);
632 if ((i + 1) >= args.Length){
634 Environment.Exit (1);
636 link_paths.Add (args [++i]);
640 RootContext.StdLib = false;
648 Report.WarningsAreErrors = true;
652 if ((i + 1) >= args.Length){
654 Environment.Exit (1);
659 warn = Int32.Parse (args [++i]);
662 Environment.Exit (1);
664 Report.SetIgnoreWarning (warn);
668 if ((i + 1) >= args.Length){
671 "--wlevel requires an value from 0 to 4");
672 Environment.Exit (1);
675 SetWarningLevel (args [++i]);
680 if ((i + 1) >= args.Length){
681 Console.WriteLine ("--mcs-debug requires an argument");
682 Environment.Exit (1);
686 Report.DebugFlags = Int32.Parse (args [++i]);
688 Console.WriteLine ("Invalid argument to --mcs-debug");
689 Environment.Exit (1);
699 if ((i + 1) >= args.Length){
700 Console.WriteLine ("--recurse requires an argument");
701 Environment.Exit (1);
703 CompileFiles (args [++i], true);
708 last_time = DateTime.Now;
709 debug_arglist.Add ("timestamp");
712 case "--debug": case "-g":
713 want_debugging_support = true;
717 if ((i + 1) >= args.Length){
718 Console.WriteLine ("--debug-args requires an argument");
719 Environment.Exit (1);
721 char[] sep = { ',' };
722 debug_arglist.AddRange (args [++i].Split (sep));
726 load_default_config = false;
734 // Currently it is very basic option parsing, but eventually, this will
735 // be the complete option parser
737 static bool CSCParseOption (string option, ref string [] args, ref int i)
739 int idx = option.IndexOf (":");
746 arg = option.Substring (0, idx);
748 value = option.Substring (idx + 1);
763 target = Target.WinExe;
767 target = Target.Library;
772 target = Target.Module;
778 Environment.Exit (1);
786 Environment.Exit (1);
788 SetOutputFile (value);
795 case "/incremental+":
796 case "/incremental-":
806 Environment.Exit (1);
809 defs = value.Split (new Char [] {';'});
810 foreach (string d in defs){
817 case "/linkresource":
819 Console.WriteLine ("{0} requires an argument", arg);
820 Environment.Exit (1);
822 if (resources == null)
823 resources = new ArrayList ();
825 resources.Add (value);
831 Console.WriteLine ("{0} requires an argument", arg);
832 Environment.Exit (1);
834 if (embedded_resources == null)
835 embedded_resources = new ArrayList ();
837 embedded_resources.Add (value);
842 Console.WriteLine ("/recurse requires an argument");
843 Environment.Exit (1);
845 CompileFiles (value, true);
851 Console.WriteLine ("/recurse requires an argument");
852 Environment.Exit (1);
854 references.Add (value);
862 Environment.Exit (1);
865 libdirs = value.Split (new Char [] { ',' });
866 foreach (string dir in libdirs)
867 link_paths.Add (dir);
873 want_debugging_support = true;
878 RootContext.Checked = true;
882 RootContext.Checked = false;
887 RootContext.Unsafe = true;
891 RootContext.Unsafe = false;
895 case "/warnaserror+":
896 Report.WarningsAreErrors = true;
899 case "/warnaserror-":
900 Report.WarningsAreErrors = false;
904 SetWarningLevel (value);
912 Environment.Exit (1);
915 warns = value.Split (new Char [] {','});
916 foreach (string wc in warns){
920 warn = Int32.Parse (wc);
923 Environment.Exit (1);
925 Report.SetIgnoreWarning (warn);
931 load_default_config = false;
937 Environment.Exit (0);
944 Environment.Exit (1);
946 RootContext.MainClass = value;
951 RootContext.StdLib = false;
955 RootContext.StdLib = true;
963 /// Parses the arguments, and drives the compilation
968 /// TODO: Mostly structured to debug the compiler
969 /// now, needs to be turned into a real driver soon.
971 // [MonoTODO("Change error code for unknown argument to something reasonable")]
972 static bool MainDriver (string [] args)
975 bool parsing_options = true;
977 references = new ArrayList ();
978 soft_references = new ArrayList ();
979 link_paths = new ArrayList ();
981 SetupDefaultDefines ();
986 // This is not required because Assembly.Load knows about this
990 int argc = args.Length;
991 for (i = 0; i < argc; i++){
992 string arg = args [i];
994 if (arg.StartsWith ("@")){
995 string [] new_args, extra_args;
996 string response_file = arg.Substring (1);
998 if (response_file_list == null)
999 response_file_list = new Hashtable ();
1001 if (response_file_list.Contains (response_file)){
1003 1515, "Response file `" + response_file +
1004 "' specified multiple times");
1005 Environment.Exit (1);
1008 response_file_list.Add (response_file, response_file);
1010 extra_args = LoadArgs (response_file);
1011 if (extra_args == null){
1012 Report.Error (2011, "Unable to open response file: " +
1017 new_args = new string [extra_args.Length + argc];
1018 args.CopyTo (new_args, 0);
1019 extra_args.CopyTo (new_args, argc);
1021 argc = new_args.Length;
1025 if (parsing_options){
1027 parsing_options = false;
1031 if (arg.StartsWith ("-")){
1032 if (UnixParseOption (arg, ref args, ref i))
1036 string csc_opt = "/" + arg.Substring (1);
1037 if (CSCParseOption (csc_opt, ref args, ref i))
1040 if (arg.StartsWith ("/")){
1041 if (CSCParseOption (arg, ref args, ref i))
1047 CompileFiles (arg, false);
1053 if (first_source == null){
1054 Report.Error (2008, "No files to compile were specified");
1058 if (Report.Errors > 0)
1065 // Load Core Library for default compilation
1067 if (RootContext.StdLib)
1068 references.Insert (0, "mscorlib");
1070 if (load_default_config)
1071 DefineDefaultConfig ();
1073 if (Report.Errors > 0){
1078 // Load assemblies required
1081 ShowTime ("Loading references");
1082 link_paths.Add (GetSystemDir ());
1086 ShowTime (" References loaded");
1088 if (Report.Errors > 0){
1095 if (output_file == null){
1096 int pos = first_source.LastIndexOf (".");
1099 output_file = first_source.Substring (0, pos) + target_ext;
1101 output_file = first_source + target_ext;
1104 string[] debug_args = new string [debug_arglist.Count];
1105 debug_arglist.CopyTo (debug_args);
1106 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
1108 TypeManager.AddModule (CodeGen.ModuleBuilder);
1111 // Before emitting, we need to get the core
1112 // types emitted from the user defined types
1113 // or from the system ones.
1116 ShowTime ("Initializing Core Types");
1117 if (!RootContext.StdLib){
1118 RootContext.ResolveCore ();
1119 if (Report.Errors > 0)
1123 TypeManager.InitCoreTypes ();
1125 ShowTime (" Core Types done");
1128 // The second pass of the compiler
1131 ShowTime ("Resolving tree");
1132 RootContext.ResolveTree ();
1134 ShowTime ("Populate tree");
1135 if (!RootContext.StdLib)
1136 RootContext.BootCorlib_PopulateCoreTypes ();
1137 RootContext.PopulateTypes ();
1139 TypeManager.InitCodeHelpers ();
1141 if (Report.Errors > 0){
1146 // The code generator
1149 ShowTime ("Emitting code");
1150 RootContext.EmitCode ();
1154 if (Report.Errors > 0){
1159 ShowTime ("Closing types");
1161 RootContext.CloseTypes ();
1163 PEFileKinds k = PEFileKinds.ConsoleApplication;
1165 if (target == Target.Library || target == Target.Module)
1166 k = PEFileKinds.Dll;
1167 else if (target == Target.Exe)
1168 k = PEFileKinds.ConsoleApplication;
1169 else if (target == Target.WinExe)
1170 k = PEFileKinds.WindowApplication;
1172 if (target == Target.Exe || target == Target.WinExe){
1173 MethodInfo ep = RootContext.EntryPoint;
1176 Report.Error (5001, "Program " + output_file +
1177 " does not have an entry point defined");
1181 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1185 // Add the resources
1187 if (resources != null){
1188 foreach (string file in resources)
1189 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
1192 if (embedded_resources != null){
1193 object[] margs = new object [2];
1194 Type[] argst = new Type [2];
1195 argst [0] = argst [1] = typeof (string);
1196 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod ("EmbedResourceFile", argst);
1197 if (embed_res == null) {
1198 Report.Warning (0, new Location (-1), "Cannot embed resources on this runtime: try the Mono runtime instead.");
1200 foreach (string file in embedded_resources) {
1201 margs [0] = margs [1] = file;
1202 embed_res.Invoke (CodeGen.AssemblyBuilder, margs);
1207 CodeGen.Save (output_file);
1209 ShowTime ("Saved output");
1211 if (want_debugging_support) {
1212 CodeGen.SaveSymbols ();
1214 ShowTime ("Saved symbols");
1217 if (Report.ExpectedError != 0){
1218 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1219 Environment.Exit (1);
1223 return (Report.Errors == 0);