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){
235 if (assembly.EndsWith (".dll"))
236 full_path = dir + "/" + assembly;
238 full_path = dir + "/" + assembly + ".dll";
241 a = Assembly.LoadFrom (full_path);
242 TypeManager.AddAssembly (a);
244 } catch (FileNotFoundException ff) {
245 total_log += ff.FusionLog;
250 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
251 Console.WriteLine ("Log: \n" + total_log);
253 } catch (BadImageFormatException f) {
254 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
255 } catch (FileLoadException f){
256 Report.Error(6, "Cannot load assembly " + f.FusionLog);
257 } catch (ArgumentNullException){
258 Report.Error(6, "Cannot load assembly (null argument)");
263 /// Loads all assemblies referenced on the command line
265 static public void LoadReferences ()
267 foreach (string r in references)
268 LoadAssembly (r, false);
270 foreach (string r in soft_references)
271 LoadAssembly (r, true);
276 static void SetupDefaultDefines ()
278 defines = new ArrayList ();
279 defines.Add ("__MonoCS__");
282 static string [] LoadArgs (string file)
285 ArrayList args = new ArrayList ();
288 f = new StreamReader (file);
293 while ((line = f.ReadLine ()) != null){
294 string [] line_args = line.Split (new char [] { ' ' });
296 foreach (string arg in line_args)
300 string [] ret_value = new string [args.Count];
301 args.CopyTo (ret_value, 0);
307 // Returns the directory where the system assemblies are installed
309 static string GetSystemDir ()
311 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
313 foreach (Assembly a in assemblies){
314 string codebase = a.CodeBase;
315 if (codebase.EndsWith ("corlib.dll")){
316 return codebase.Substring (0, codebase.LastIndexOf ("/"));
320 Report.Error (-15, "Can not compute my system path");
325 // Given a path specification, splits the path from the file/pattern
327 static void SplitPathAndPattern (string spec, out string path, out string pattern)
329 int p = spec.LastIndexOf ("/");
332 // Windows does not like /file.cs, switch that to:
337 pattern = spec.Substring (1);
339 path = spec.Substring (0, p);
340 pattern = spec.Substring (p + 1);
345 p = spec.LastIndexOf ("\\");
347 path = spec.Substring (0, p);
348 pattern = spec.Substring (p + 1);
356 static void ProcessFile (string f)
358 if (first_source == null)
361 if (source_files.Contains (f)){
364 "Source file `" + f + "' specified multiple times");
365 Environment.Exit (1);
367 source_files.Add (f, f);
376 static void CompileFiles (string spec, bool recurse)
378 string path, pattern;
380 SplitPathAndPattern (spec, out path, out pattern);
381 if (pattern.IndexOf ("*") == -1){
386 string [] files = null;
388 files = Directory.GetFiles (path, pattern);
389 } catch (System.IO.DirectoryNotFoundException) {
390 Report.Error (2001, "Source file `" + spec + "' could not be found");
392 } catch (System.IO.IOException){
393 Report.Error (2001, "Source file `" + spec + "' could not be found");
396 foreach (string f in files) {
403 string [] dirs = null;
406 dirs = Directory.GetDirectories (path);
410 foreach (string d in dirs) {
412 // Don't include path in this string, as each
413 // directory entry already does
414 CompileFiles (d + "/" + pattern, true);
418 static void DefineDefaultConfig ()
421 // For now the "default config" is harcoded into the compiler
422 // we can move this outside later
424 string [] default_config = {
429 // Is it worth pre-loading all this stuff?
432 "System.Configuration.Install",
435 "System.DirectoryServices",
436 "System.Drawing.Design",
438 "System.EnterpriseServices",
441 "System.Runtime.Remoting",
442 "System.Runtime.Serialization.Formatters.Soap",
444 "System.ServiceProcess",
446 "System.Web.RegularExpressions",
447 "System.Web.Services",
448 "System.Windows.Forms"
453 foreach (string def in default_config)
454 soft_references.Insert (p++, def);
457 static void SetOutputFile (string name)
460 string bname = CodeGen.Basename (output_file);
461 if (bname.IndexOf (".") == -1)
462 output_file += ".exe";
465 static void SetWarningLevel (string s)
470 level = Int32.Parse (s);
474 "--wlevel requires an value from 0 to 4");
475 Environment.Exit (1);
477 if (level < 0 || level > 4){
478 Report.Error (1900, "Warning level must be 0 to 4");
479 Environment.Exit (1);
481 RootContext.WarningLevel = level;
484 // Currently handles the Unix-like command line options, but will be
485 // deprecated in favor of the CSCParseOption, which will also handle the
486 // options that start with a dash in the future.
488 static bool UnixParseOption (string arg, ref string [] args, ref int i)
499 case "--main": case "-m":
500 if ((i + 1) >= args.Length){
502 Environment.Exit (1);
504 RootContext.MainClass = args [++i];
508 RootContext.Unsafe = true;
511 case "/?": case "/h": case "/help":
514 Environment.Exit (0);
518 if ((i + 1) >= args.Length){
520 Environment.Exit (1);
522 defines.Add (args [++i]);
525 case "--expect-error": {
530 args [++i], NumberStyles.AllowLeadingSign);
531 Report.ExpectedError = code;
533 Report.Error (-14, "Invalid number specified");
544 if ((i + 1) >= args.Length){
546 Environment.Exit (1);
548 SetOutputFile (args [++i]);
552 RootContext.Checked = true;
556 Report.Stacktrace = true;
560 if ((i + 1) >= args.Length){
562 Console.WriteLine("Missing argument to --resource");
563 Environment.Exit (1);
565 if (resources == null)
566 resources = new ArrayList ();
568 resources.Add (args [++i]);
572 if ((i + 1) >= args.Length){
573 Environment.Exit (1);
577 string type = args [++i];
580 target = Target.Library;
589 target = Target.WinExe;
593 target = Target.Module;
598 Environment.Exit (1);
604 if ((i + 1) >= args.Length){
606 Environment.Exit (1);
609 references.Add (args [++i]);
613 if ((i + 1) >= args.Length){
615 Environment.Exit (1);
617 link_paths.Add (args [++i]);
621 RootContext.StdLib = false;
629 Report.WarningsAreErrors = true;
633 if ((i + 1) >= args.Length){
635 Environment.Exit (1);
640 warn = Int32.Parse (args [++i]);
643 Environment.Exit (1);
645 Report.SetIgnoreWarning (warn);
649 if ((i + 1) >= args.Length){
652 "--wlevel requires an value from 0 to 4");
653 Environment.Exit (1);
656 SetWarningLevel (args [++i]);
664 if ((i + 1) >= args.Length){
665 Console.WriteLine ("--recurse requires an argument");
666 Environment.Exit (1);
668 CompileFiles (args [++i], true);
673 last_time = DateTime.Now;
674 debug_arglist.Add ("timestamp");
677 case "--debug": case "-g":
678 want_debugging_support = true;
682 if ((i + 1) >= args.Length){
683 Console.WriteLine ("--debug-args requires an argument");
684 Environment.Exit (1);
686 char[] sep = { ',' };
687 debug_arglist.AddRange (args [++i].Split (sep));
691 load_default_config = false;
699 // Currently it is very basic option parsing, but eventually, this will
700 // be the complete option parser
702 static bool CSCParseOption (string option, ref string [] args, ref int i)
704 int idx = option.IndexOf (":");
711 arg = option.Substring (0, idx);
713 value = option.Substring (idx + 1);
728 target = Target.WinExe;
732 target = Target.Library;
737 target = Target.Module;
743 Environment.Exit (1);
751 Environment.Exit (1);
753 SetOutputFile (value);
760 case "/incremental+":
761 case "/incremental-":
771 Environment.Exit (1);
774 defs = value.Split (new Char [] {';'});
775 foreach (string d in defs){
783 Console.WriteLine ("/recurse requires an argument");
784 Environment.Exit (1);
786 CompileFiles (value, true);
792 Console.WriteLine ("/recurse requires an argument");
793 Environment.Exit (1);
795 references.Add (value);
803 Environment.Exit (1);
806 libdirs = value.Split (new Char [] { ',' });
807 foreach (string dir in libdirs)
808 link_paths.Add (dir);
814 want_debugging_support = true;
819 RootContext.Checked = true;
823 RootContext.Checked = false;
828 RootContext.Unsafe = true;
832 RootContext.Unsafe = false;
836 case "/warnaserror+":
837 Report.WarningsAreErrors = true;
840 case "/warnaserror-":
841 Report.WarningsAreErrors = false;
845 SetWarningLevel (value);
853 Environment.Exit (1);
856 warns = value.Split (new Char [] {','});
857 foreach (string wc in warns){
861 warn = Int32.Parse (wc);
864 Environment.Exit (1);
866 Report.SetIgnoreWarning (warn);
872 load_default_config = false;
878 Environment.Exit (0);
885 Environment.Exit (1);
887 RootContext.MainClass = value;
892 RootContext.StdLib = false;
896 RootContext.StdLib = true;
904 /// Parses the arguments, and drives the compilation
909 /// TODO: Mostly structured to debug the compiler
910 /// now, needs to be turned into a real driver soon.
912 // [MonoTODO("Change error code for unknown argument to something reasonable")]
913 static bool MainDriver (string [] args)
916 bool parsing_options = true;
918 references = new ArrayList ();
919 soft_references = new ArrayList ();
920 link_paths = new ArrayList ();
922 SetupDefaultDefines ();
927 // This is not required because Assembly.Load knows about this
931 int argc = args.Length;
932 for (i = 0; i < argc; i++){
933 string arg = args [i];
935 if (arg.StartsWith ("@")){
936 string [] new_args, extra_args;
937 string response_file = arg.Substring (1);
939 if (response_file_list == null)
940 response_file_list = new Hashtable ();
942 if (response_file_list.Contains (response_file)){
944 1515, "Response file `" + response_file +
945 "' specified multiple times");
946 Environment.Exit (1);
949 response_file_list.Add (response_file, response_file);
951 extra_args = LoadArgs (response_file);
952 if (extra_args == null){
953 Report.Error (2011, "Unable to open response file: " +
958 new_args = new string [extra_args.Length + argc];
959 args.CopyTo (new_args, 0);
960 extra_args.CopyTo (new_args, argc);
962 argc = new_args.Length;
966 if (parsing_options){
968 parsing_options = false;
972 if (arg.StartsWith ("-")){
973 if (UnixParseOption (arg, ref args, ref i))
977 string csc_opt = "/" + arg.Substring (1);
978 if (CSCParseOption (csc_opt, ref args, ref i))
981 if (arg.StartsWith ("/")){
982 if (CSCParseOption (arg, ref args, ref i))
988 CompileFiles (arg, false);
994 if (first_source == null){
995 Report.Error (2008, "No files to compile were specified");
999 if (Report.Errors > 0)
1006 // Load Core Library for default compilation
1008 if (RootContext.StdLib)
1009 references.Insert (0, "mscorlib");
1011 if (load_default_config)
1012 DefineDefaultConfig ();
1014 if (Report.Errors > 0){
1019 // Load assemblies required
1022 ShowTime ("Loading references");
1023 link_paths.Add (GetSystemDir ());
1027 ShowTime (" References loaded");
1029 if (Report.Errors > 0){
1036 if (output_file == null){
1037 int pos = first_source.LastIndexOf (".");
1040 output_file = first_source.Substring (0, pos) + target_ext;
1042 output_file = first_source + target_ext;
1045 string[] debug_args = new string [debug_arglist.Count];
1046 debug_arglist.CopyTo (debug_args);
1047 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
1049 TypeManager.AddModule (CodeGen.ModuleBuilder);
1052 // Before emitting, we need to get the core
1053 // types emitted from the user defined types
1054 // or from the system ones.
1057 ShowTime ("Initializing Core Types");
1058 if (!RootContext.StdLib){
1059 RootContext.ResolveCore ();
1060 if (Report.Errors > 0)
1064 TypeManager.InitCoreTypes ();
1066 ShowTime (" Core Types done");
1069 // The second pass of the compiler
1072 ShowTime ("Resolving tree");
1073 RootContext.ResolveTree ();
1075 ShowTime ("Populate tree");
1076 if (!RootContext.StdLib)
1077 RootContext.BootCorlib_PopulateCoreTypes ();
1078 RootContext.PopulateTypes ();
1080 TypeManager.InitCodeHelpers ();
1082 if (Report.Errors > 0){
1087 // The code generator
1090 ShowTime ("Emitting code");
1091 RootContext.EmitCode ();
1095 if (Report.Errors > 0){
1100 ShowTime ("Closing types");
1102 RootContext.CloseTypes ();
1104 PEFileKinds k = PEFileKinds.ConsoleApplication;
1106 if (target == Target.Library || target == Target.Module)
1107 k = PEFileKinds.Dll;
1108 else if (target == Target.Exe)
1109 k = PEFileKinds.ConsoleApplication;
1110 else if (target == Target.WinExe)
1111 k = PEFileKinds.WindowApplication;
1113 if (target == Target.Exe || target == Target.WinExe){
1114 MethodInfo ep = RootContext.EntryPoint;
1117 Report.Error (5001, "Program " + output_file +
1118 " does not have an entry point defined");
1122 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
1126 // Add the resources
1128 if (resources != null){
1129 foreach (string file in resources)
1130 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
1133 CodeGen.Save (output_file);
1135 ShowTime ("Saved output");
1137 if (want_debugging_support) {
1138 CodeGen.SaveSymbols ();
1140 ShowTime ("Saved symbols");
1143 if (Report.ExpectedError != 0){
1144 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
1145 Environment.Exit (1);
1149 return (Report.Errors == 0);