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;
82 // Last time we took the time
84 static DateTime last_time;
85 static void ShowTime (string msg)
87 DateTime now = DateTime.Now;
88 TimeSpan span = now - last_time;
92 "[{0:00}:{1:000}] {2}",
93 (int) span.TotalSeconds, span.Milliseconds, msg);
96 static void tokenize_file (string input_file)
101 input = File.OpenRead (input_file);
103 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
108 Tokenizer lexer = new Tokenizer (input, input_file, defines);
109 int token, tokens = 0, errors = 0;
111 while ((token = lexer.token ()) != Token.EOF){
112 Location l = lexer.Location;
114 if (token == Token.ERROR)
117 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
123 // MonoTODO("Change error code for aborted compilation to something reasonable")]
124 static void parse (string input_file)
130 input = File.OpenRead (input_file);
132 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
136 parser = new CSharpParser (input_file, input, defines);
137 parser.yacc_verbose = yacc_verbose;
140 } catch (Exception ex) {
141 Report.Error(666, "Compilation aborted: " + ex);
150 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
151 "mcs [options] source-files\n" +
152 " --about About the Mono C# compiler\n" +
153 " --checked Set default context to checked\n" +
154 " --define SYM Defines the symbol SYM\n" +
155 " --debug Generate debugging information\n" +
156 " -g Generate debugging information\n" +
157 " --debug-args X Specify additional arguments for the\n" +
158 " symbol writer.\n" +
159 " --fatal Makes errors fatal\n" +
160 " -L PATH Adds PATH to the assembly link path\n" +
161 " --noconfig Disables implicit references to assemblies\n" +
162 " --nostdlib Does not load core libraries\n" +
163 " --nowarn XXX Ignores warning number XXX\n" +
164 " -o FNAME Specifies output file\n" +
165 " -g, --debug Write symbolic debugging information to FILE-debug.s\n" +
166 " --parse Only parses the source file\n" +
167 " --expect-error X Expect that error X will be encountered\n" +
168 " --recurse SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
169 " --resource FILE Addds FILE as a resource\n" +
170 " --stacktrace Shows stack trace at error location\n" +
171 " --target KIND Specifies the target (KIND is one of: exe, winexe, " +
172 "library, module)\n" +
173 " --timestamp Displays time stamps of various compiler events\n" +
174 " --unsafe Allows unsafe code\n" +
175 " --werror Treat warnings as errors\n" +
176 " --wlevel LEVEL Sets warning level (the highest is 4, the default)\n" +
177 " -r References an assembly\n" +
178 " -v Verbose parsing (for debugging the parser)\n" +
179 " @file Read response file for more options");
185 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
186 "The compiler source code is released under the terms of the GNU GPL\n\n" +
188 "For more information on Mono, visit the project Web site\n" +
189 " http://www.go-mono.com\n\n" +
191 "The compiler was written by Miguel de Icaza and Ravi Pratap");
194 public static int Main (string[] args)
196 bool ok = MainDriver (args);
198 if (ok && Report.Errors == 0) {
199 Console.Write("Compilation succeeded");
200 if (Report.Warnings > 0) {
201 Console.Write(" - {0} warning(s)", Report.Warnings);
206 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
207 Report.Errors, Report.Warnings);
212 static public void LoadAssembly (string assembly, bool soft)
215 string total_log = "";
218 char[] path_chars = { '/', '\\', '.' };
220 if (assembly.IndexOfAny (path_chars) != -1) {
221 a = Assembly.LoadFrom (assembly);
223 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;
241 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
242 Console.WriteLine ("Log: \n" + total_log);
244 } catch (BadImageFormatException f) {
245 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
246 } catch (FileLoadException f){
247 Report.Error(6, "Cannot load assembly " + f.FusionLog);
248 } catch (ArgumentNullException){
249 Report.Error(6, "Cannot load assembly (null argument)");
254 /// Loads all assemblies referenced on the command line
256 static public void LoadReferences ()
258 foreach (string r in references)
259 LoadAssembly (r, false);
261 foreach (string r in soft_references)
262 LoadAssembly (r, true);
267 static void SetupDefaultDefines ()
269 defines = new ArrayList ();
270 defines.Add ("__MonoCS__");
273 static string [] LoadArgs (string file)
276 ArrayList args = new ArrayList ();
279 f = new StreamReader (file);
284 while ((line = f.ReadLine ()) != null){
285 string [] line_args = line.Split (new char [] { ' ' });
287 foreach (string arg in line_args)
291 string [] ret_value = new string [args.Count];
292 args.CopyTo (ret_value, 0);
298 // Returns the directory where the system assemblies are installed
300 static string GetSystemDir ()
302 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
304 foreach (Assembly a in assemblies){
305 string codebase = a.CodeBase;
306 if (codebase.EndsWith ("corlib.dll")){
307 return codebase.Substring (0, codebase.LastIndexOf ("/"));
311 Report.Error (-15, "Can not compute my system path");
316 // Given a path specification, splits the path from the file/pattern
318 static void SplitPathAndPattern (string spec, out string path, out string pattern)
320 int p = spec.LastIndexOf ("/");
323 // Windows does not like /file.cs, switch that to:
328 pattern = spec.Substring (1);
330 path = spec.Substring (0, p);
331 pattern = spec.Substring (p + 1);
336 p = spec.LastIndexOf ("\\");
338 path = spec.Substring (0, p);
339 pattern = spec.Substring (p + 1);
347 static void ProcessFile (string f)
349 if (first_source == null)
352 if (source_files.Contains (f)){
355 "Source file `" + f + "' specified multiple times");
356 Environment.Exit (1);
358 source_files.Add (f, f);
367 static void CompileFiles (string spec, bool recurse)
369 string path, pattern;
371 SplitPathAndPattern (spec, out path, out pattern);
372 if (pattern.IndexOf ("*") == -1){
377 string [] files = null;
379 files = Directory.GetFiles (path, pattern);
380 } catch (System.IO.DirectoryNotFoundException) {
381 Report.Error (2001, "Source file `" + spec + "' could not be found");
383 } catch (System.IO.IOException){
384 Report.Error (2001, "Source file `" + spec + "' could not be found");
387 foreach (string f in files) {
394 string [] dirs = null;
397 dirs = Directory.GetDirectories (path);
401 foreach (string d in dirs) {
403 // Don't include path in this string, as each
404 // directory entry already does
405 CompileFiles (d + "/" + pattern, true);
409 static void DefineDefaultConfig ()
412 // For now the "default config" is harcoded into the compiler
413 // we can move this outside later
415 string [] default_config = {
420 // Is it worth pre-loading all this stuff?
423 "System.Configuration.Install",
426 "System.DirectoryServices",
427 "System.Drawing.Design",
429 "System.EnterpriseServices",
432 "System.Runtime.Remoting",
433 "System.Runtime.Serialization.Formatters.Soap",
435 "System.ServiceProcess",
437 "System.Web.RegularExpressions",
438 "System.Web.Services",
439 "System.Windows.Forms"
444 foreach (string def in default_config)
445 soft_references.Insert (p++, def);
449 /// Parses the arguments, and drives the compilation
454 /// TODO: Mostly structured to debug the compiler
455 /// now, needs to be turned into a real driver soon.
457 // [MonoTODO("Change error code for unknown argument to something reasonable")]
458 static bool MainDriver (string [] args)
461 string output_file = null;
462 bool parsing_options = true;
464 references = new ArrayList ();
465 soft_references = new ArrayList ();
466 link_paths = new ArrayList ();
468 SetupDefaultDefines ();
473 // This is not required because Assembly.Load knows about this
476 link_paths.Add (GetSystemDir ());
478 int argc = args.Length;
479 for (i = 0; i < argc; i++){
480 string arg = args [i];
482 if (arg.StartsWith ("@")){
483 string [] new_args, extra_args;
484 string response_file = arg.Substring (1);
486 if (response_file_list == null)
487 response_file_list = new Hashtable ();
489 if (response_file_list.Contains (response_file)){
491 1515, "Response file `" + response_file +
492 "' specified multiple times");
493 Environment.Exit (1);
496 response_file_list.Add (response_file, response_file);
498 extra_args = LoadArgs (response_file);
499 if (extra_args == null){
500 Report.Error (2011, "Unable to open response file: " +
505 new_args = new string [extra_args.Length + argc];
506 args.CopyTo (new_args, 0);
507 extra_args.CopyTo (new_args, argc);
509 argc = new_args.Length;
514 // Prepare to recurse
517 if (parsing_options && (arg.StartsWith ("-"))){
524 parsing_options = false;
531 case "--main": case "-m":
532 if ((i + 1) >= argc){
536 RootContext.MainClass = args [++i];
540 RootContext.Unsafe = true;
543 case "/?": case "/h": case "/help":
549 if ((i + 1) >= argc){
553 defines.Add (args [++i]);
556 case "--expect-error": {
561 args [++i], NumberStyles.AllowLeadingSign);
562 Report.ExpectedError = code;
564 Report.Error (-14, "Invalid number specified");
576 if ((i + 1) >= argc){
580 output_file = args [++i];
581 string bname = CodeGen.Basename (output_file);
582 if (bname.IndexOf (".") == -1)
583 output_file += ".exe";
587 RootContext.Checked = true;
591 Report.Stacktrace = true;
595 if ((i + 1) >= argc){
597 Console.WriteLine("Missing argument to --resource");
600 if (resources == null)
601 resources = new ArrayList ();
603 resources.Add (args [++i]);
607 if ((i + 1) >= argc){
612 string type = args [++i];
615 target = Target.Library;
624 target = Target.WinExe;
628 target = Target.Module;
638 if ((i + 1) >= argc){
643 references.Add (args [++i]);
647 if ((i + 1) >= argc){
651 link_paths.Add (args [++i]);
655 RootContext.StdLib = false;
663 Report.WarningsAreErrors = true;
667 if ((i + 1) >= argc){
674 warn = Int32.Parse (args [++i]);
679 Report.SetIgnoreWarning (warn);
683 if ((i + 1) >= argc){
686 "--wlevel requires an value from 0 to 4");
692 level = Int32.Parse (args [++i]);
696 "--wlevel requires an value from 0 to 4");
699 if (level < 0 || level > 4){
700 Report.Error (1900, "Warning level must be 0 to 4");
703 RootContext.WarningLevel = level;
711 if ((i + 1) >= argc){
712 Console.WriteLine ("--recurse requires an argument");
715 CompileFiles (args [++i], true);
720 last_time = DateTime.Now;
721 debug_arglist.Add ("timestamp");
724 case "--debug": case "-g":
725 want_debugging_support = true;
729 if ((i + 1) >= argc){
730 Console.WriteLine ("--debug-args requires an argument");
733 char[] sep = { ',' };
734 debug_arglist.AddRange (args [++i].Split (sep));
738 load_default_config = false;
742 Report.Warning(666, "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 ();
773 if (Report.Errors > 0){
778 // Load assemblies required
781 ShowTime ("Loading references");
785 ShowTime (" References loaded");
787 if (Report.Errors > 0){
794 if (output_file == null){
795 int pos = first_source.LastIndexOf (".");
798 output_file = first_source.Substring (0, pos) + target_ext;
800 output_file = first_source + target_ext;
803 string[] debug_args = new string [debug_arglist.Count];
804 debug_arglist.CopyTo (debug_args);
805 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
807 TypeManager.AddModule (CodeGen.ModuleBuilder);
810 // Before emitting, we need to get the core
811 // types emitted from the user defined types
812 // or from the system ones.
815 ShowTime ("Initializing Core Types");
816 if (!RootContext.StdLib){
817 RootContext.ResolveCore ();
818 if (Report.Errors > 0)
822 TypeManager.InitCoreTypes ();
824 ShowTime (" Core Types done");
827 // The second pass of the compiler
830 ShowTime ("Resolving tree");
831 RootContext.ResolveTree ();
833 ShowTime ("Populate tree");
834 if (!RootContext.StdLib)
835 RootContext.BootCorlib_PopulateCoreTypes ();
836 RootContext.PopulateTypes ();
838 TypeManager.InitCodeHelpers ();
840 if (Report.Errors > 0){
845 // The code generator
848 ShowTime ("Emitting code");
849 RootContext.EmitCode ();
853 if (Report.Errors > 0){
858 ShowTime ("Closing types");
860 RootContext.CloseTypes ();
862 PEFileKinds k = PEFileKinds.ConsoleApplication;
864 if (target == Target.Library || target == Target.Module)
866 else if (target == Target.Exe)
867 k = PEFileKinds.ConsoleApplication;
868 else if (target == Target.WinExe)
869 k = PEFileKinds.WindowApplication;
871 if (target == Target.Exe || target == Target.WinExe){
872 MethodInfo ep = RootContext.EntryPoint;
875 Report.Error (5001, "Program " + output_file +
876 " does not have an entry point defined");
880 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
886 if (resources != null){
887 foreach (string file in resources)
888 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
891 CodeGen.Save (output_file);
893 ShowTime ("Saved output");
895 if (want_debugging_support) {
896 CodeGen.SaveSymbols ();
898 ShowTime ("Saved symbols");
901 if (Report.ExpectedError != 0){
902 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
903 Environment.Exit (1);
907 return (Report.Errors == 0);