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;
77 // An array of the defines from the command line
79 static ArrayList defines;
84 static string output_file = null;
87 // Last time we took the time
89 static DateTime last_time;
90 static void ShowTime (string msg)
92 DateTime now = DateTime.Now;
93 TimeSpan span = now - last_time;
97 "[{0:00}:{1:000}] {2}",
98 (int) span.TotalSeconds, span.Milliseconds, msg);
101 static void tokenize_file (string input_file)
106 input = File.OpenRead (input_file);
108 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
113 Tokenizer lexer = new Tokenizer (input, input_file, defines);
114 int token, tokens = 0, errors = 0;
116 while ((token = lexer.token ()) != Token.EOF){
117 Location l = lexer.Location;
119 if (token == Token.ERROR)
122 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
128 // MonoTODO("Change error code for aborted compilation to something reasonable")]
129 static void parse (string input_file)
135 input = File.OpenRead (input_file);
137 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
141 parser = new CSharpParser (input_file, input, defines);
142 parser.yacc_verbose = yacc_verbose;
145 } catch (Exception ex) {
146 Report.Error(666, "Compilation aborted: " + ex);
155 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
156 "mcs [options] source-files\n" +
157 " --about About the Mono C# compiler\n" +
158 " --checked Set default context to checked\n" +
159 " --define SYM Defines the symbol SYM\n" +
160 " --debug Generate debugging information\n" +
161 " -g Generate debugging information\n" +
162 " --debug-args X Specify additional arguments for the\n" +
163 " symbol writer.\n" +
164 " --fatal Makes errors fatal\n" +
165 " -L PATH Adds PATH to the assembly link path\n" +
166 " --noconfig Disables implicit references to assemblies\n" +
167 " --nostdlib Does not load core libraries\n" +
168 " --nowarn XXX Ignores warning number XXX\n" +
169 " -o FNAME Specifies output file\n" +
170 " -g, --debug Write symbolic debugging information to FILE-debug.s\n" +
171 " --parse Only parses the source file\n" +
172 " --expect-error X Expect that error X will be encountered\n" +
173 " --recurse SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
174 " --resource FILE Addds FILE as a resource\n" +
175 " --stacktrace Shows stack trace at error location\n" +
176 " --target KIND Specifies the target (KIND is one of: exe, winexe, " +
177 "library, module)\n" +
178 " --timestamp Displays time stamps of various compiler events\n" +
179 " --unsafe Allows unsafe code\n" +
180 " --werror Treat warnings as errors\n" +
181 " --wlevel LEVEL Sets warning level (the highest is 4, the default)\n" +
182 " -r References an assembly\n" +
183 " -v Verbose parsing (for debugging the parser)\n" +
184 " @file Read response file for more options");
190 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
191 "The compiler source code is released under the terms of the GNU GPL\n\n" +
193 "For more information on Mono, visit the project Web site\n" +
194 " http://www.go-mono.com\n\n" +
196 "The compiler was written by Miguel de Icaza and Ravi Pratap");
199 public static int Main (string[] args)
201 bool ok = MainDriver (args);
203 if (ok && Report.Errors == 0) {
204 Console.Write("Compilation succeeded");
205 if (Report.Warnings > 0) {
206 Console.Write(" - {0} warning(s)", Report.Warnings);
211 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
212 Report.Errors, Report.Warnings);
217 static public void LoadAssembly (string assembly, bool soft)
220 string total_log = "";
223 char[] path_chars = { '/', '\\', '.' };
225 if (assembly.IndexOfAny (path_chars) != -1) {
226 a = Assembly.LoadFrom (assembly);
228 a = Assembly.Load (assembly);
230 TypeManager.AddAssembly (a);
232 } catch (FileNotFoundException){
233 foreach (string dir in link_paths){
234 string full_path = dir + "/" + assembly + ".dll";
237 a = Assembly.LoadFrom (full_path);
238 TypeManager.AddAssembly (a);
240 } catch (FileNotFoundException ff) {
241 total_log += ff.FusionLog;
246 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
247 Console.WriteLine ("Log: \n" + total_log);
249 } catch (BadImageFormatException f) {
250 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
251 } catch (FileLoadException f){
252 Report.Error(6, "Cannot load assembly " + f.FusionLog);
253 } catch (ArgumentNullException){
254 Report.Error(6, "Cannot load assembly (null argument)");
259 /// Loads all assemblies referenced on the command line
261 static public void LoadReferences ()
263 foreach (string r in references)
264 LoadAssembly (r, false);
266 foreach (string r in soft_references)
267 LoadAssembly (r, true);
272 static void SetupDefaultDefines ()
274 defines = new ArrayList ();
275 defines.Add ("__MonoCS__");
278 static string [] LoadArgs (string file)
281 ArrayList args = new ArrayList ();
284 f = new StreamReader (file);
289 while ((line = f.ReadLine ()) != null){
290 string [] line_args = line.Split (new char [] { ' ' });
292 foreach (string arg in line_args)
296 string [] ret_value = new string [args.Count];
297 args.CopyTo (ret_value, 0);
303 // Returns the directory where the system assemblies are installed
305 static string GetSystemDir ()
307 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
309 foreach (Assembly a in assemblies){
310 string codebase = a.CodeBase;
311 if (codebase.EndsWith ("corlib.dll")){
312 return codebase.Substring (0, codebase.LastIndexOf ("/"));
316 Report.Error (-15, "Can not compute my system path");
321 // Given a path specification, splits the path from the file/pattern
323 static void SplitPathAndPattern (string spec, out string path, out string pattern)
325 int p = spec.LastIndexOf ("/");
328 // Windows does not like /file.cs, switch that to:
333 pattern = spec.Substring (1);
335 path = spec.Substring (0, p);
336 pattern = spec.Substring (p + 1);
341 p = spec.LastIndexOf ("\\");
343 path = spec.Substring (0, p);
344 pattern = spec.Substring (p + 1);
352 static void ProcessFile (string f)
354 if (first_source == null)
357 if (source_files.Contains (f)){
360 "Source file `" + f + "' specified multiple times");
361 Environment.Exit (1);
363 source_files.Add (f, f);
372 static void CompileFiles (string spec, bool recurse)
374 string path, pattern;
376 SplitPathAndPattern (spec, out path, out pattern);
377 if (pattern.IndexOf ("*") == -1){
382 string [] files = null;
384 files = Directory.GetFiles (path, pattern);
385 } catch (System.IO.DirectoryNotFoundException) {
386 Report.Error (2001, "Source file `" + spec + "' could not be found");
388 } catch (System.IO.IOException){
389 Report.Error (2001, "Source file `" + spec + "' could not be found");
392 foreach (string f in files) {
399 string [] dirs = null;
402 dirs = Directory.GetDirectories (path);
406 foreach (string d in dirs) {
408 // Don't include path in this string, as each
409 // directory entry already does
410 CompileFiles (d + "/" + pattern, true);
414 static void DefineDefaultConfig ()
417 // For now the "default config" is harcoded into the compiler
418 // we can move this outside later
420 string [] default_config = {
425 // Is it worth pre-loading all this stuff?
428 "System.Configuration.Install",
431 "System.DirectoryServices",
432 "System.Drawing.Design",
434 "System.EnterpriseServices",
437 "System.Runtime.Remoting",
438 "System.Runtime.Serialization.Formatters.Soap",
440 "System.ServiceProcess",
442 "System.Web.RegularExpressions",
443 "System.Web.Services",
444 "System.Windows.Forms"
449 foreach (string def in default_config)
450 soft_references.Insert (p++, def);
453 static void SetOutputFile (string name)
456 string bname = CodeGen.Basename (output_file);
457 if (bname.IndexOf (".") == -1)
458 output_file += ".exe";
461 static void SetWarningLevel (string s)
466 level = Int32.Parse (s);
470 "--wlevel requires an value from 0 to 4");
471 Environment.Exit (1);
473 if (level < 0 || level > 4){
474 Report.Error (1900, "Warning level must be 0 to 4");
475 Environment.Exit (1);
477 RootContext.WarningLevel = level;
480 // Currently handles the Unix-like command line options, but will be
481 // deprecated in favor of the CSCParseOption, which will also handle the
482 // options that start with a dash in the future.
484 static bool UnixParseOption (string arg, ref string [] args, ref int i)
495 case "--main": case "-m":
496 if ((i + 1) >= args.Length){
498 Environment.Exit (1);
500 RootContext.MainClass = args [++i];
504 RootContext.Unsafe = true;
507 case "/?": case "/h": case "/help":
510 Environment.Exit (0);
514 if ((i + 1) >= args.Length){
516 Environment.Exit (1);
518 defines.Add (args [++i]);
521 case "--expect-error": {
526 args [++i], NumberStyles.AllowLeadingSign);
527 Report.ExpectedError = code;
529 Report.Error (-14, "Invalid number specified");
540 if ((i + 1) >= args.Length){
542 Environment.Exit (1);
544 SetOutputFile (args [++i]);
548 RootContext.Checked = true;
552 Report.Stacktrace = true;
556 if ((i + 1) >= args.Length){
558 Console.WriteLine("Missing argument to --resource");
559 Environment.Exit (1);
561 if (resources == null)
562 resources = new ArrayList ();
564 resources.Add (args [++i]);
568 if ((i + 1) >= args.Length){
569 Environment.Exit (1);
573 string type = args [++i];
576 target = Target.Library;
585 target = Target.WinExe;
589 target = Target.Module;
594 Environment.Exit (1);
600 if ((i + 1) >= args.Length){
602 Environment.Exit (1);
605 references.Add (args [++i]);
609 if ((i + 1) >= args.Length){
611 Environment.Exit (1);
613 link_paths.Add (args [++i]);
617 RootContext.StdLib = false;
625 Report.WarningsAreErrors = true;
629 if ((i + 1) >= args.Length){
631 Environment.Exit (1);
636 warn = Int32.Parse (args [++i]);
639 Environment.Exit (1);
641 Report.SetIgnoreWarning (warn);
645 if ((i + 1) >= args.Length){
648 "--wlevel requires an value from 0 to 4");
649 Environment.Exit (1);
652 SetWarningLevel (args [++i]);
660 if ((i + 1) >= args.Length){
661 Console.WriteLine ("--recurse requires an argument");
662 Environment.Exit (1);
664 CompileFiles (args [++i], true);
669 last_time = DateTime.Now;
670 debug_arglist.Add ("timestamp");
673 case "--debug": case "-g":
674 want_debugging_support = true;
678 if ((i + 1) >= args.Length){
679 Console.WriteLine ("--debug-args requires an argument");
680 Environment.Exit (1);
682 char[] sep = { ',' };
683 debug_arglist.AddRange (args [++i].Split (sep));
687 load_default_config = false;
691 Report.Warning(666, "Unknown option: " + arg);
697 // Currently it is very basic option parsing, but eventually, this will
698 // be the complete option parser
700 static bool CSCParseOption (string option, ref string [] args, ref int i)
702 int idx = option.IndexOf (":");
709 arg = option.Substring (0, idx);
711 value = option.Substring (idx + 1);
726 target = Target.WinExe;
730 target = Target.Library;
735 target = Target.Module;
741 Environment.Exit (1);
749 Environment.Exit (1);
751 SetOutputFile (value);
758 case "/incremental+":
759 case "/incremental-":
769 Environment.Exit (1);
772 defs = value.Split (new Char [] {';'});
773 foreach (string d in defs)
780 Console.WriteLine ("/recurse requires an argument");
781 Environment.Exit (1);
783 CompileFiles (args [++i], true);
788 Console.WriteLine ("/r and /reference not supported, use -r which will give you MCS semantics");
789 Console.WriteLine ("this will be fixed shortly");
790 Environment.Exit (1);
794 Console.WriteLine ("/lib is not supported, use -L which will give you MCS semantics");
795 Console.WriteLine ("this will be fixed shortly");
796 Environment.Exit (1);
801 want_debugging_support = true;
806 RootContext.Checked = true;
810 RootContext.Checked = false;
815 RootContext.Unsafe = true;
819 RootContext.Unsafe = false;
823 case "/warnaserror+":
824 Report.WarningsAreErrors = true;
827 case "/warnaserror-":
828 Report.WarningsAreErrors = false;
832 SetWarningLevel (value);
840 Environment.Exit (1);
843 warns = value.Split (new Char [] {','});
844 foreach (string wc in warns){
848 warn = Int32.Parse (wc);
851 Environment.Exit (1);
853 Report.SetIgnoreWarning (warn);
859 load_default_config = false;
865 Environment.Exit (0);
872 Environment.Exit (1);
874 RootContext.MainClass = value;
879 RootContext.StdLib = false;
883 RootContext.StdLib = true;
891 /// Parses the arguments, and drives the compilation
896 /// TODO: Mostly structured to debug the compiler
897 /// now, needs to be turned into a real driver soon.
899 // [MonoTODO("Change error code for unknown argument to something reasonable")]
900 static bool MainDriver (string [] args)
903 bool parsing_options = true;
905 references = new ArrayList ();
906 soft_references = new ArrayList ();
907 link_paths = new ArrayList ();
909 SetupDefaultDefines ();
914 // This is not required because Assembly.Load knows about this
917 link_paths.Add (GetSystemDir ());
919 int argc = args.Length;
920 for (i = 0; i < argc; i++){
921 string arg = args [i];
923 if (arg.StartsWith ("@")){
924 string [] new_args, extra_args;
925 string response_file = arg.Substring (1);
927 if (response_file_list == null)
928 response_file_list = new Hashtable ();
930 if (response_file_list.Contains (response_file)){
932 1515, "Response file `" + response_file +
933 "' specified multiple times");
934 Environment.Exit (1);
937 response_file_list.Add (response_file, response_file);
939 extra_args = LoadArgs (response_file);
940 if (extra_args == null){
941 Report.Error (2011, "Unable to open response file: " +
946 new_args = new string [extra_args.Length + argc];
947 args.CopyTo (new_args, 0);
948 extra_args.CopyTo (new_args, argc);
950 argc = new_args.Length;
954 if (parsing_options){
956 parsing_options = false;
960 if (arg.StartsWith ("-")){
961 if (UnixParseOption (arg, ref args, ref i))
964 if (arg.StartsWith ("/"))
965 if (CSCParseOption (arg, ref args, ref i))
970 CompileFiles (arg, false);
976 if (first_source == null){
977 Report.Error (2008, "No files to compile were specified");
981 if (Report.Errors > 0)
988 // Load Core Library for default compilation
990 if (RootContext.StdLib)
991 references.Insert (0, "mscorlib");
993 if (load_default_config)
994 DefineDefaultConfig ();
996 if (Report.Errors > 0){
1001 // Load assemblies required
1004 ShowTime ("Loading references");
1008 ShowTime (" References loaded");
1010 if (Report.Errors > 0){
1017 if (output_file == null){
1018 int pos = first_source.LastIndexOf (".");
1021 output_file = first_source.Substring (0, pos) + target_ext;
1023 output_file = first_source + target_ext;
1026 string[] debug_args = new string [debug_arglist.Count];
1027 debug_arglist.CopyTo (debug_args);
1028 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
1030 TypeManager.AddModule (CodeGen.ModuleBuilder);
1033 // Before emitting, we need to get the core
1034 // types emitted from the user defined types
1035 // or from the system ones.
1038 ShowTime ("Initializing Core Types");
1039 if (!RootContext.StdLib){
1040 RootContext.ResolveCore ();
1041 if (Report.Errors > 0)
1045 TypeManager.InitCoreTypes ();
1047 ShowTime (" Core Types done");
1050 // The second pass of the compiler
1053 ShowTime ("Resolving tree");
1054 RootContext.ResolveTree ();
1056 ShowTime ("Populate tree");
1057 if (!RootContext.StdLib)
1058 RootContext.BootCorlib_PopulateCoreTypes ();
1059 RootContext.PopulateTypes ();
1061 TypeManager.InitCodeHelpers ();
1063 if (Report.Errors > 0){
1068 // The code generator
1071 ShowTime ("Emitting code");
1072 RootContext.EmitCode ();
1076 if (Report.Errors > 0){
1081 ShowTime ("Closing types");
1083 RootContext.CloseTypes ();
1085 PEFileKinds k = PEFileKinds.ConsoleApplication;
1087 if (target == Target.Library || target == Target.Module)
1088 k = PEFileKinds.Dll;
1089 else if (target == Target.Exe)
1090 k = PEFileKinds.ConsoleApplication;
1091 else if (target == Target.WinExe)
1092 k = PEFileKinds.WindowApplication;
1094 if (target == Target.Exe || target == Target.WinExe){
1095 MethodInfo ep = RootContext.EntryPoint;
1098 Report.Error (5001, "Program " + output_file +
1099 " does not have an entry point defined");
1103 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1107 // Add the resources
1109 if (resources != null){
1110 foreach (string file in resources)
1111 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
1114 CodeGen.Save (output_file);
1116 ShowTime ("Saved output");
1118 if (want_debugging_support) {
1119 CodeGen.SaveSymbols ();
1121 ShowTime ("Saved symbols");
1124 if (Report.ExpectedError != 0){
1125 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1126 Environment.Exit (1);
1130 return (Report.Errors == 0);