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 int error_count = 0;
54 static string first_source;
56 static Target target = Target.Exe;
57 static string target_ext = ".exe";
59 static bool want_debugging_support = false;
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;
78 // An array of the defines from the command line
80 static ArrayList defines;
83 // Last time we took the time
85 static DateTime last_time;
86 static void ShowTime (string msg)
88 DateTime now = DateTime.Now;
89 TimeSpan span = now - last_time;
93 "[{0:00}:{1:000}] {2}",
94 (int) span.TotalSeconds, span.Milliseconds, msg);
97 static int tokenize_file (string input_file)
102 input = File.OpenRead (input_file);
105 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
110 Tokenizer lexer = new Tokenizer (input, input_file, defines);
111 int token, tokens = 0, errors = 0;
113 while ((token = lexer.token ()) != Token.EOF){
114 Location l = lexer.Location;
116 if (token == Token.ERROR)
119 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
125 static int parse (string input_file)
132 input = File.OpenRead (input_file);
134 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
138 parser = new CSharpParser (input_file, input, defines);
139 parser.yacc_verbose = yacc_verbose;
141 errors = parser.parse ();
142 } catch (Exception ex) {
143 Console.WriteLine (ex);
144 Console.WriteLine ("Compilation aborted");
153 static void Usage (bool is_error)
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 " --fatal Makes errors fatal\n" +
164 " -L PATH Adds PATH to the assembly link path\n" +
165 " --noconfig Disables implicit references to assemblies\n" +
166 " --nostdlib Does not load core libraries\n" +
167 " --nowarn XXX Ignores warning number XXX\n" +
168 " -o FNAME Specifies output file\n" +
169 " --optimize Optimizes\n" +
170 " -g, --debug Write symbolic debugging information to FILE-debug.s\n" +
171 " --parse Only parses the source file\n" +
172 " --probe X Probes for the source to generate code X on line L\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");
192 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
193 "The compiler source code is released under the terms of the GNU GPL\n\n" +
195 "For more information on Mono, visit the project Web site\n" +
196 " http://www.go-mono.com\n\n" +
198 "The compiler was written by Miguel de Icaza and Ravi Pratap");
201 static void error (string msg)
203 Console.WriteLine ("Error: " + msg);
206 static void notice (string msg)
208 Console.WriteLine (msg);
211 public static int Main (string[] args)
215 return (error_count + Report.Errors) != 0 ? 1 : 0;
218 static public int LoadAssembly (string assembly, bool soft)
221 string total_log = "";
224 char[] path_chars = { '/', '\\', '.' };
226 if (assembly.IndexOfAny (path_chars) != -1)
227 a = Assembly.LoadFrom (assembly);
229 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;
247 } catch (BadImageFormatException f) {
248 error ("// Bad file format while loading assembly");
249 error ("Log: " + f.FusionLog);
251 } catch (FileLoadException f){
252 error ("// File Load Exception: ");
253 error ("Log: " + f.FusionLog);
255 } catch (ArgumentNullException){
256 error ("// Argument Null exception ");
260 Report.Error (6, "Can not find assembly `" + assembly + "'" );
261 Console.WriteLine ("Log: \n" + total_log);
267 /// Loads all assemblies referenced on the command line
269 static public int LoadReferences ()
273 foreach (string r in references)
274 errors += LoadAssembly (r, false);
276 foreach (string r in soft_references)
277 errors += LoadAssembly (r, true);
282 static void SetupDefaultDefines ()
284 defines = new ArrayList ();
285 defines.Add ("__MonoCS__");
288 static string [] LoadArgs (string file)
291 ArrayList args = new ArrayList ();
294 f = new StreamReader (file);
299 while ((line = f.ReadLine ()) != null){
300 string [] line_args = line.Split (new char [] { ' ' });
302 foreach (string arg in line_args)
306 string [] ret_value = new string [args.Count];
307 args.CopyTo (ret_value, 0);
313 // Returns the directory where the system assemblies are installed
315 static string GetSystemDir ()
317 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
319 foreach (Assembly a in assemblies){
320 string codebase = a.CodeBase;
321 if (codebase.EndsWith ("corlib.dll")){
322 return codebase.Substring (0, codebase.LastIndexOf ("/"));
326 Report.Error (-15, "Can not compute my system path");
331 // Given a path specification, splits the path from the file/pattern
333 static void SplitPathAndPattern (string spec, out string path, out string pattern)
335 int p = spec.LastIndexOf ("/");
338 // Windows does not like /file.cs, switch that to:
343 pattern = spec.Substring (1);
345 path = spec.Substring (0, p);
346 pattern = spec.Substring (p + 1);
351 p = spec.LastIndexOf ("\\");
353 path = spec.Substring (0, p);
354 pattern = spec.Substring (p + 1);
362 static int ProcessFile (string f)
364 if (first_source == null)
367 if (source_files.Contains (f)){
370 "Source file `" + f + "' specified multiple times");
371 Environment.Exit (1);
373 source_files.Add (f, f);
382 static int CompileFiles (string spec, bool recurse)
384 string path, pattern;
387 SplitPathAndPattern (spec, out path, out pattern);
388 string [] files = null;
390 files = Directory.GetFiles (path, pattern);
391 } catch (System.IO.DirectoryNotFoundException) {
392 Report.Error (2001, "Source file `" + spec + "' could not be found");
394 } catch (System.IO.IOException){
395 Report.Error (2001, "Source file `" + spec + "' could not be found");
399 foreach (string f in files)
400 errors += ProcessFile (f);
405 string [] dirs = null;
408 dirs = Directory.GetDirectories (path);
412 foreach (string d in dirs) {
414 // Don't include path in this string, as each
415 // directory entry already does
416 errors += 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);
463 /// Parses the arguments, and drives the compilation
468 /// TODO: Mostly structured to debug the compiler
469 /// now, needs to be turned into a real driver soon.
471 static void MainDriver (string [] args)
474 string output_file = null;
475 bool parsing_options = true;
477 references = new ArrayList ();
478 soft_references = new ArrayList ();
479 link_paths = new ArrayList ();
481 SetupDefaultDefines ();
486 // This is not required because Assembly.Load knows about this
489 link_paths.Add (GetSystemDir ());
491 int argc = args.Length;
492 for (i = 0; i < argc; i++){
493 string arg = args [i];
495 if (arg.StartsWith ("@")){
496 string [] new_args, extra_args;
497 string response_file = arg.Substring (1);
499 if (response_file_list == null)
500 response_file_list = new Hashtable ();
502 if (response_file_list.Contains (response_file)){
504 1515, "Response file `" + response_file +
505 "' specified multiple times");
506 Environment.Exit (1);
509 response_file_list.Add (response_file, response_file);
511 extra_args = LoadArgs (response_file);
512 if (extra_args == null){
513 Report.Error (2011, "Unable to open response file: " +
518 new_args = new string [extra_args.Length + argc];
519 args.CopyTo (new_args, 0);
520 extra_args.CopyTo (new_args, argc);
522 argc = new_args.Length;
527 // Prepare to recurse
530 if (parsing_options && (arg.StartsWith ("-"))){
537 parsing_options = false;
544 case "--main": case "-m":
545 if ((i + 1) >= argc){
549 RootContext.MainClass = args [++i];
553 RootContext.Unsafe = true;
557 RootContext.Optimize = true;
560 case "/?": case "/h": case "/help":
566 if ((i + 1) >= argc){
570 defines.Add (args [++i]);
578 args [++i], NumberStyles.AllowLeadingSign);
579 Report.SetProbe (code);
581 Report.Error (-14, "Invalid number specified");
593 if ((i + 1) >= argc){
597 output_file = args [++i];
598 string bname = CodeGen.Basename (output_file);
599 if (bname.IndexOf (".") == -1)
600 output_file += ".exe";
604 RootContext.Checked = true;
608 Report.Stacktrace = true;
612 if ((i + 1) >= argc){
614 Console.WriteLine("Missing argument to --resource");
617 if (resources == null)
618 resources = new ArrayList ();
620 resources.Add (args [++i]);
624 if ((i + 1) >= argc){
629 string type = args [++i];
632 target = Target.Library;
641 target = Target.WinExe;
645 target = Target.Module;
655 if ((i + 1) >= argc){
660 references.Add (args [++i]);
664 if ((i + 1) >= argc){
668 link_paths.Add (args [++i]);
672 RootContext.StdLib = false;
680 Report.WarningsAreErrors = true;
684 if ((i + 1) >= argc){
691 warn = Int32.Parse (args [++i]);
696 Report.SetIgnoreWarning (warn);
700 if ((i + 1) >= argc){
703 "--wlevel requires an value from 0 to 4");
710 level = Int32.Parse (args [++i]);
714 "--wlevel requires an value from 0 to 4");
717 if (level < 0 || level > 4){
718 Report.Error (1900, "Warning level must be 0 to 4");
721 RootContext.WarningLevel = level;
729 if ((i + 1) >= argc){
730 Console.WriteLine ("--recurse requires an argument");
734 errors += CompileFiles (args [++i], true);
739 last_time = DateTime.Now;
742 case "--debug": case "-g":
743 want_debugging_support = true;
747 load_default_config = false;
751 Console.WriteLine ("Unknown option: " + arg);
757 CompileFiles (arg, false);
763 if (first_source == null){
764 Report.Error (2008, "No files to compile were specified");
768 if (Report.Errors > 0)
775 // Load Core Library for default compilation
777 if (RootContext.StdLib)
778 references.Insert (0, "mscorlib");
780 if (load_default_config)
781 DefineDefaultConfig ();
784 error ("Parsing failed");
789 // Load assemblies required
792 ShowTime ("Loading references");
793 errors += LoadReferences ();
795 ShowTime (" References loaded");
798 error ("Could not load one or more assemblies");
802 error_count = errors;
807 if (output_file == null){
808 int pos = first_source.LastIndexOf (".");
811 output_file = first_source.Substring (0, pos) + target_ext;
813 output_file = first_source + target_ext;
816 CodeGen.Init (output_file, output_file, want_debugging_support);
818 TypeManager.AddModule (CodeGen.ModuleBuilder);
821 // Before emitting, we need to get the core
822 // types emitted from the user defined types
823 // or from the system ones.
826 ShowTime ("Initializing Core Types");
827 if (!RootContext.StdLib){
828 RootContext.ResolveCore ();
829 if (Report.Errors > 0)
833 TypeManager.InitCoreTypes ();
835 ShowTime (" Core Types done");
838 // The second pass of the compiler
841 ShowTime ("Resolving tree");
842 RootContext.ResolveTree ();
844 ShowTime ("Populate tree");
845 if (!RootContext.StdLib)
846 RootContext.BootCorlib_PopulateCoreTypes ();
847 RootContext.PopulateTypes ();
849 TypeManager.InitCodeHelpers ();
851 if (Report.Errors > 0){
852 error ("Compilation failed");
857 // The code generator
860 ShowTime ("Emitting code");
861 RootContext.EmitCode ();
865 if (Report.Errors > 0){
866 error ("Compilation failed");
871 ShowTime ("Closing types");
873 RootContext.CloseTypes ();
875 PEFileKinds k = PEFileKinds.ConsoleApplication;
877 if (target == Target.Library || target == Target.Module)
879 else if (target == Target.Exe)
880 k = PEFileKinds.ConsoleApplication;
881 else if (target == Target.WinExe)
882 k = PEFileKinds.WindowApplication;
884 if (target == Target.Exe || target == Target.WinExe){
885 MethodInfo ep = RootContext.EntryPoint;
888 Report.Error (5001, "Program " + output_file +
889 " does not have an entry point defined");
893 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
899 if (resources != null){
900 foreach (string file in resources)
901 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
904 CodeGen.Save (output_file);
906 ShowTime ("Saved output");
908 if (want_debugging_support) {
909 CodeGen.SaveSymbols ();
911 ShowTime ("Saved symbols");
914 if (Report.Errors > 0){
915 error ("Compilation failed");
917 } else if (Report.ProbeCode != 0){
918 error ("Failed to report code " + Report.ProbeCode);
919 Environment.Exit (124);