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 static ArrayList link_paths;
39 // Whether we want Yacc to output its progress
40 static bool yacc_verbose = false;
42 // Whether we want to only run the tokenizer
43 static bool tokenize = false;
45 static int error_count = 0;
47 static string first_source;
49 static Target target = Target.Exe;
50 static string target_ext = ".exe";
52 static bool parse_only = false;
53 static bool timestamps = false;
55 static Hashtable response_file_list;
56 static Hashtable source_files = new Hashtable ();
59 // A list of resource files
61 static ArrayList resources;
64 // An array of the defines from the command line
66 static ArrayList defines;
69 // Last time we took the time
71 static DateTime last_time;
72 static void ShowTime (string msg)
74 DateTime now = DateTime.Now;
75 TimeSpan span = now - last_time;
79 "[{0:00}:{1:000}] {2}",
80 span.Seconds, span.Milliseconds, msg);
83 static int tokenize_file (string input_file)
88 input = File.OpenRead (input_file);
91 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
96 Tokenizer lexer = new Tokenizer (input, input_file, defines);
97 int token, tokens = 0, errors = 0;
99 while ((token = lexer.token ()) != Token.EOF){
100 Location l = lexer.Location;
102 if (token == Token.ERROR)
105 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
111 static int parse (string input_file)
118 input = File.OpenRead (input_file);
120 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
124 parser = new CSharpParser (input_file, input, defines);
125 parser.yacc_verbose = yacc_verbose;
127 errors = parser.parse ();
128 } catch (Exception ex) {
129 Console.WriteLine (ex);
130 Console.WriteLine ("Compilation aborted");
139 static void Usage (bool is_error)
142 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
143 "mcs [options] source-files\n" +
144 " --about About the Mono C# compiler\n" +
145 " --checked Set default context to checked\n" +
146 " --define SYM Defines the symbol SYM\n" +
147 " --fatal Makes errors fatal\n" +
148 " -L PATH Adds PATH to the assembly link path\n" +
149 " --nostdlib Does not load core libraries\n" +
150 " --nowarn XXX Ignores warning number XXX\n" +
151 " -o FNAME Specifies output file\n" +
152 " --optimize Optimizes\n" +
153 " --parse Only parses the source file\n" +
154 " --probe X Probes for the source to generate code X on line L\n" +
155 " --resource FILE Addds FILE as a resource\n" +
156 " --stacktrace Shows stack trace at error location\n" +
157 " --target KIND Specifies the target (KIND is one of: exe, winexe, " +
158 "library, module)\n" +
159 " --timestamp Displays time stamps of various compiler events\n" +
160 " --unsafe Allows unsafe code\n" +
161 " --werror Treat warnings as errors\n" +
162 " --wlevel LEVEL Sets warning level (the highest is 4, the default)\n" +
163 " -r References an assembly\n" +
164 " -v Verbose parsing (for debugging the parser)\n" +
165 " @file Read response file for more options");
173 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
174 "The compiler source code is released under the terms of the GNU GPL\n\n" +
176 "For more information on Mono, visit the project Web site\n" +
177 " http://www.go-mono.com\n\n" +
179 "The compiler was written by Miguel de Icaza and Ravi Pratap");
182 static void error (string msg)
184 Console.WriteLine ("Error: " + msg);
187 static void notice (string msg)
189 Console.WriteLine (msg);
192 public static int Main (string[] args)
196 return (error_count + Report.Errors) != 0 ? 1 : 0;
199 static public int LoadAssembly (string assembly)
202 string total_log = "";
205 a = Assembly.Load (assembly);
206 RootContext.TypeManager.AddAssembly (a);
208 } catch (FileNotFoundException){
209 foreach (string dir in link_paths){
210 string full_path = dir + "/" + assembly + ".dll";
213 a = Assembly.LoadFrom (full_path);
214 RootContext.TypeManager.AddAssembly (a);
216 } catch (FileNotFoundException ff) {
217 total_log += ff.FusionLog;
221 } catch (BadImageFormatException f) {
222 error ("// Bad file format while loading assembly");
223 error ("Log: " + f.FusionLog);
225 } catch (FileLoadException f){
226 error ("// File Load Exception: ");
227 error ("Log: " + f.FusionLog);
229 } catch (ArgumentNullException){
230 error ("// Argument Null exception ");
234 Report.Error (6, "Can not find assembly `" + assembly + "'" );
235 Console.WriteLine ("Log: \n" + total_log);
241 /// Loads all assemblies referenced on the command line
243 static public int LoadReferences ()
247 foreach (string r in references)
248 errors += LoadAssembly (r);
253 static void SetupDefaultDefines ()
255 defines = new ArrayList ();
256 defines.Add ("__MonoCS__");
259 static string [] LoadArgs (string file)
262 ArrayList args = new ArrayList ();
265 f = new StreamReader (file);
270 while ((line = f.ReadLine ()) != null){
271 string [] line_args = line.Split (new char [] { ' ' });
273 foreach (string arg in line_args)
277 string [] ret_value = new string [args.Count];
278 args.CopyTo (ret_value, 0);
284 // Returns the directory where the system assemblies are installed
286 static string GetSystemDir ()
288 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
290 foreach (Assembly a in assemblies){
291 string codebase = a.CodeBase;
292 if (codebase.EndsWith ("corlib.dll")){
293 return codebase.Substring (0, codebase.LastIndexOf ("/"));
297 Report.Error (-15, "Can not compute my system path");
302 // Given a path specification, splits the path from the file/pattern
304 static void SplitPathAndPattern (string spec, out string path, out string pattern)
306 int p = spec.LastIndexOf ("/");
309 // Windows does not like /file.cs, switch that to:
314 pattern = spec.Substring (1);
316 path = spec.Substring (0, p);
317 pattern = spec.Substring (p + 1);
322 p = spec.LastIndexOf ("\\");
324 path = spec.Substring (0, p - 1);
325 pattern = spec.Substring (p);
333 static int ProcessFile (string f)
335 if (source_files.Contains (f)){
338 "Source file `" + f + "' specified multiple times");
339 Environment.Exit (1);
341 source_files.Add (f, f);
350 static void RecurseOn (string pattern)
356 /// Parses the arguments, and drives the compilation
361 /// TODO: Mostly structured to debug the compiler
362 /// now, needs to be turned into a real driver soon.
364 static void MainDriver (string [] args)
367 string output_file = null;
368 bool parsing_options = true;
370 references = new ArrayList ();
371 link_paths = new ArrayList ();
373 SetupDefaultDefines ();
378 // This is not required because Assembly.Load knows about this
381 link_paths.Add (GetSystemDir ());
383 int argc = args.Length;
384 for (i = 0; i < argc; i++){
385 string arg = args [i];
387 if (arg.StartsWith ("@")){
388 string [] new_args, extra_args;
389 string response_file = arg.Substring (1);
391 if (response_file_list == null)
392 response_file_list = new Hashtable ();
394 if (response_file_list.Contains (response_file)){
396 1515, "Response file `" + response_file +
397 "' specified multiple times");
398 Environment.Exit (1);
401 response_file_list.Add (response_file, response_file);
403 extra_args = LoadArgs (response_file);
404 if (extra_args == null){
405 Report.Error (2011, "Unable to open response file: " +
410 new_args = new string [extra_args.Length + argc];
411 args.CopyTo (new_args, 0);
412 extra_args.CopyTo (new_args, argc);
414 argc = new_args.Length;
419 // Prepare to recurse
422 if (parsing_options && (arg.StartsWith ("-") || arg.StartsWith ("/"))){
429 parsing_options = false;
436 case "--main": case "-m":
437 if ((i + 1) >= argc){
441 RootContext.MainClass = args [++i];
445 RootContext.Unsafe = true;
449 RootContext.Optimize = true;
452 case "/?": case "/h": case "/help":
458 if ((i + 1) >= argc){
462 defines.Add (args [++i]);
470 args [++i], NumberStyles.AllowLeadingSign);
471 Report.SetProbe (code);
473 Report.Error (-14, "Invalid number specified");
485 if ((i + 1) >= argc){
489 output_file = args [++i];
490 string bname = CodeGen.Basename (output_file);
491 if (bname.IndexOf (".") == -1)
492 output_file += ".exe";
496 RootContext.Checked = true;
500 Report.Stacktrace = true;
504 if ((i + 1) >= argc){
506 Console.WriteLine("Missing argument to --resource");
509 if (resources == null)
510 resources = new ArrayList ();
512 resources.Add (args [++i]);
516 if ((i + 1) >= argc){
521 string type = args [++i];
524 target = Target.Library;
533 target = Target.WinExe;
537 target = Target.Module;
544 if ((i + 1) >= argc){
549 references.Add (args [++i]);
553 if ((i + 1) >= argc){
557 link_paths.Add (args [++i]);
561 RootContext.StdLib = false;
569 Report.WarningsAreErrors = true;
573 if ((i + 1) >= argc){
580 warn = Int32.Parse (args [++i]);
585 Report.SetIgnoreWarning (warn);
589 if ((i + 1) >= argc){
597 level = Int32.Parse (args [++i]);
602 if (level < 0 || level > 4){
603 Report.Error (1900, "Warning level must be 0 to 4");
606 RootContext.WarningLevel = level;
614 if ((i + 1) >= argc){
619 RecurseOn (args [++i]);
624 last_time = DateTime.Now;
629 if (first_source == null)
632 string path, pattern;
633 SplitPathAndPattern (arg, out path, out pattern);
634 string [] files = null;
636 files = Directory.GetFiles (path, pattern);
637 } catch (System.IO.DirectoryNotFoundException) {
638 Report.Error (2001, "Source file `" + arg + "' could not be found");
642 foreach (string f in files)
643 errors += ProcessFile (f);
649 if (first_source == null){
650 Report.Error (2008, "No files to compile were specified");
654 if (Report.Errors > 0)
661 // Load Core Library for default compilation
663 if (RootContext.StdLib){
664 references.Insert (0, "mscorlib");
665 references.Insert (1, "System");
669 error ("Parsing failed");
674 // Load assemblies required
677 ShowTime ("Loading references");
678 errors += LoadReferences ();
680 ShowTime (" References loaded");
683 error ("Could not load one or more assemblies");
687 error_count = errors;
692 if (output_file == null){
693 int pos = first_source.LastIndexOf (".");
696 output_file = first_source.Substring (0, pos) + target_ext;
698 output_file = first_source + target_ext;
701 RootContext.CodeGen = new CodeGen (output_file, output_file);
704 // Before emitting, we need to get the core
705 // types emitted from the user defined types
706 // or from the system ones.
709 ShowTime ("Initializing Core Types");
710 RootContext.TypeManager.InitCoreTypes ();
712 ShowTime (" Core Types done");
714 RootContext.TypeManager.AddModule (RootContext.CodeGen.ModuleBuilder);
717 // The second pass of the compiler
720 ShowTime ("Resolving tree");
721 RootContext.ResolveTree ();
723 ShowTime ("Populate tree");
724 RootContext.PopulateTypes ();
726 if (Report.Errors > 0){
727 error ("Compilation failed");
732 // The code generator
735 ShowTime ("Emitting code");
736 RootContext.EmitCode ();
740 if (Report.Errors > 0){
741 error ("Compilation failed");
746 ShowTime ("Closing types");
748 RootContext.CloseTypes ();
750 PEFileKinds k = PEFileKinds.ConsoleApplication;
752 if (target == Target.Library || target == Target.Module)
754 else if (target == Target.Exe)
755 k = PEFileKinds.ConsoleApplication;
756 else if (target == Target.WinExe)
757 k = PEFileKinds.WindowApplication;
759 if (target == Target.Exe || target == Target.WinExe){
760 MethodInfo ep = RootContext.EntryPoint;
763 Report.Error (5001, "Program " + output_file +
764 " does not have an entry point defined");
768 RootContext.CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
774 if (resources != null){
775 foreach (string file in resources)
776 RootContext.CodeGen.AssemblyBuilder.AddResourceFile (file, file);
779 RootContext.CodeGen.Save (output_file);
781 ShowTime ("Saved output");
783 if (Report.Errors > 0){
784 error ("Compilation failed");
786 } else if (Report.ProbeCode != 0){
787 error ("Failed to report code " + Report.ProbeCode);
788 Environment.Exit (124);