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 span.Seconds, 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 a = Assembly.Load (assembly);
225 TypeManager.AddAssembly (a);
227 } catch (FileNotFoundException){
228 foreach (string dir in link_paths){
229 string full_path = dir + "/" + assembly + ".dll";
232 a = Assembly.LoadFrom (full_path);
233 TypeManager.AddAssembly (a);
235 } catch (FileNotFoundException ff) {
236 total_log += ff.FusionLog;
242 } catch (BadImageFormatException f) {
243 error ("// Bad file format while loading assembly");
244 error ("Log: " + f.FusionLog);
246 } catch (FileLoadException f){
247 error ("// File Load Exception: ");
248 error ("Log: " + f.FusionLog);
250 } catch (ArgumentNullException){
251 error ("// Argument Null exception ");
255 Report.Error (6, "Can not find assembly `" + assembly + "'" );
256 Console.WriteLine ("Log: \n" + total_log);
262 /// Loads all assemblies referenced on the command line
264 static public int LoadReferences ()
268 foreach (string r in references)
269 errors += LoadAssembly (r, false);
271 foreach (string r in soft_references)
272 errors += LoadAssembly (r, true);
277 static void SetupDefaultDefines ()
279 defines = new ArrayList ();
280 defines.Add ("__MonoCS__");
283 static string [] LoadArgs (string file)
286 ArrayList args = new ArrayList ();
289 f = new StreamReader (file);
294 while ((line = f.ReadLine ()) != null){
295 string [] line_args = line.Split (new char [] { ' ' });
297 foreach (string arg in line_args)
301 string [] ret_value = new string [args.Count];
302 args.CopyTo (ret_value, 0);
308 // Returns the directory where the system assemblies are installed
310 static string GetSystemDir ()
312 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
314 foreach (Assembly a in assemblies){
315 string codebase = a.CodeBase;
316 if (codebase.EndsWith ("corlib.dll")){
317 return codebase.Substring (0, codebase.LastIndexOf ("/"));
321 Report.Error (-15, "Can not compute my system path");
326 // Given a path specification, splits the path from the file/pattern
328 static void SplitPathAndPattern (string spec, out string path, out string pattern)
330 int p = spec.LastIndexOf ("/");
333 // Windows does not like /file.cs, switch that to:
338 pattern = spec.Substring (1);
340 path = spec.Substring (0, p);
341 pattern = spec.Substring (p + 1);
346 p = spec.LastIndexOf ("\\");
348 path = spec.Substring (0, p);
349 pattern = spec.Substring (p + 1);
357 static int ProcessFile (string f)
359 if (first_source == null)
362 if (source_files.Contains (f)){
365 "Source file `" + f + "' specified multiple times");
366 Environment.Exit (1);
368 source_files.Add (f, f);
377 static int CompileFiles (string spec, bool recurse)
379 string path, pattern;
382 SplitPathAndPattern (spec, out path, out pattern);
383 string [] files = null;
385 files = Directory.GetFiles (path, pattern);
386 } catch (System.IO.DirectoryNotFoundException) {
387 Report.Error (2001, "Source file `" + spec + "' could not be found");
389 } catch (System.IO.IOException){
390 Report.Error (2001, "Source file `" + spec + "' could not be found");
394 foreach (string f in files)
395 errors += ProcessFile (f);
400 string [] dirs = null;
403 dirs = Directory.GetDirectories (path);
407 foreach (string d in dirs)
408 errors += CompileFiles (path + "\\" + d + "\\" + pattern, true);
413 static void DefineDefaultConfig ()
416 // For now the "default config" is harcoded into the compiler
417 // we can move this outside later
419 string [] default_config = {
424 // Is it worth pre-loading all this stuff?
427 "System.Configuration.Install",
430 "System.DirectoryServices",
431 "System.Drawing.Design",
433 "System.EnterpriseServices",
436 "System.Runtime.Remoting",
437 "System.Runtime.Serialization.Formatters.Soap",
439 "System.ServiceProcess",
441 "System.Web.RegularExpressions",
442 "System.Web.Services",
443 "System.Windows.Forms"
448 foreach (string def in default_config)
449 soft_references.Insert (p++, def);
453 /// Parses the arguments, and drives the compilation
458 /// TODO: Mostly structured to debug the compiler
459 /// now, needs to be turned into a real driver soon.
461 static void MainDriver (string [] args)
464 string output_file = null;
465 bool parsing_options = true;
467 references = new ArrayList ();
468 soft_references = new ArrayList ();
469 link_paths = new ArrayList ();
471 SetupDefaultDefines ();
476 // This is not required because Assembly.Load knows about this
479 link_paths.Add (GetSystemDir ());
481 int argc = args.Length;
482 for (i = 0; i < argc; i++){
483 string arg = args [i];
485 if (arg.StartsWith ("@")){
486 string [] new_args, extra_args;
487 string response_file = arg.Substring (1);
489 if (response_file_list == null)
490 response_file_list = new Hashtable ();
492 if (response_file_list.Contains (response_file)){
494 1515, "Response file `" + response_file +
495 "' specified multiple times");
496 Environment.Exit (1);
499 response_file_list.Add (response_file, response_file);
501 extra_args = LoadArgs (response_file);
502 if (extra_args == null){
503 Report.Error (2011, "Unable to open response file: " +
508 new_args = new string [extra_args.Length + argc];
509 args.CopyTo (new_args, 0);
510 extra_args.CopyTo (new_args, argc);
512 argc = new_args.Length;
517 // Prepare to recurse
520 if (parsing_options && (arg.StartsWith ("-"))){
527 parsing_options = false;
534 case "--main": case "-m":
535 if ((i + 1) >= argc){
539 RootContext.MainClass = args [++i];
543 RootContext.Unsafe = true;
547 RootContext.Optimize = true;
550 case "/?": case "/h": case "/help":
556 if ((i + 1) >= argc){
560 defines.Add (args [++i]);
568 args [++i], NumberStyles.AllowLeadingSign);
569 Report.SetProbe (code);
571 Report.Error (-14, "Invalid number specified");
583 if ((i + 1) >= argc){
587 output_file = args [++i];
588 string bname = CodeGen.Basename (output_file);
589 if (bname.IndexOf (".") == -1)
590 output_file += ".exe";
594 RootContext.Checked = true;
598 Report.Stacktrace = true;
602 if ((i + 1) >= argc){
604 Console.WriteLine("Missing argument to --resource");
607 if (resources == null)
608 resources = new ArrayList ();
610 resources.Add (args [++i]);
614 if ((i + 1) >= argc){
619 string type = args [++i];
622 target = Target.Library;
631 target = Target.WinExe;
635 target = Target.Module;
645 if ((i + 1) >= argc){
650 references.Add (args [++i]);
654 if ((i + 1) >= argc){
658 link_paths.Add (args [++i]);
662 RootContext.StdLib = false;
670 Report.WarningsAreErrors = true;
674 if ((i + 1) >= argc){
681 warn = Int32.Parse (args [++i]);
686 Report.SetIgnoreWarning (warn);
690 if ((i + 1) >= argc){
693 "--wlevel requires an value from 0 to 4");
700 level = Int32.Parse (args [++i]);
704 "--wlevel requires an value from 0 to 4");
707 if (level < 0 || level > 4){
708 Report.Error (1900, "Warning level must be 0 to 4");
711 RootContext.WarningLevel = level;
719 if ((i + 1) >= argc){
720 Console.WriteLine ("--recurse requires an argument");
724 errors += CompileFiles (args [++i], true);
729 last_time = DateTime.Now;
732 case "--debug": case "-g":
733 want_debugging_support = true;
737 load_default_config = false;
741 Console.WriteLine ("Unknown option: " + arg);
747 CompileFiles (arg, false);
753 if (first_source == null){
754 Report.Error (2008, "No files to compile were specified");
758 if (Report.Errors > 0)
765 // Load Core Library for default compilation
767 if (RootContext.StdLib)
768 references.Insert (0, "mscorlib");
770 if (load_default_config)
771 DefineDefaultConfig ();
774 error ("Parsing failed");
779 // Load assemblies required
782 ShowTime ("Loading references");
783 errors += LoadReferences ();
785 ShowTime (" References loaded");
788 error ("Could not load one or more assemblies");
792 error_count = errors;
797 if (output_file == null){
798 int pos = first_source.LastIndexOf (".");
801 output_file = first_source.Substring (0, pos) + target_ext;
803 output_file = first_source + target_ext;
806 RootContext.CodeGen = new CodeGen (output_file, output_file,
807 want_debugging_support);
809 TypeManager.AddModule (RootContext.CodeGen.ModuleBuilder);
812 // Before emitting, we need to get the core
813 // types emitted from the user defined types
814 // or from the system ones.
817 ShowTime ("Initializing Core Types");
818 if (!RootContext.StdLib){
819 RootContext.ResolveCore ();
820 if (Report.Errors > 0)
824 TypeManager.InitCoreTypes ();
826 ShowTime (" Core Types done");
829 // The second pass of the compiler
832 ShowTime ("Resolving tree");
833 RootContext.ResolveTree ();
835 ShowTime ("Populate tree");
836 RootContext.PopulateTypes ();
838 if (RootContext.StdLib)
839 TypeManager.InitCodeHelpers ();
841 if (Report.Errors > 0){
842 error ("Compilation failed");
847 // The code generator
850 ShowTime ("Emitting code");
851 RootContext.EmitCode ();
855 if (Report.Errors > 0){
856 error ("Compilation failed");
861 ShowTime ("Closing types");
863 RootContext.CloseTypes ();
865 PEFileKinds k = PEFileKinds.ConsoleApplication;
867 if (target == Target.Library || target == Target.Module)
869 else if (target == Target.Exe)
870 k = PEFileKinds.ConsoleApplication;
871 else if (target == Target.WinExe)
872 k = PEFileKinds.WindowApplication;
874 if (target == Target.Exe || target == Target.WinExe){
875 MethodInfo ep = RootContext.EntryPoint;
878 Report.Error (5001, "Program " + output_file +
879 " does not have an entry point defined");
883 RootContext.CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
889 if (resources != null){
890 foreach (string file in resources)
891 RootContext.CodeGen.AssemblyBuilder.AddResourceFile (file, file);
894 RootContext.CodeGen.Save (output_file);
896 ShowTime ("Saved output");
898 if (Report.Errors > 0){
899 error ("Compilation failed");
901 } else if (Report.ProbeCode != 0){
902 error ("Failed to report code " + Report.ProbeCode);
903 Environment.Exit (124);