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 // An array of the defines from the command line
61 static ArrayList defines;
64 // Last time we took the time
66 static DateTime last_time;
67 static void ShowTime (string msg)
69 DateTime now = DateTime.Now;
70 TimeSpan span = now - last_time;
74 "[{0:00}:{1:000}] {2}",
75 span.Seconds, span.Milliseconds, msg);
78 static int tokenize_file (string input_file)
83 input = File.OpenRead (input_file);
86 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
91 Tokenizer lexer = new Tokenizer (input, input_file, defines);
92 int token, tokens = 0, errors = 0;
94 while ((token = lexer.token ()) != Token.EOF){
95 Location l = lexer.Location;
97 if (token == Token.ERROR)
100 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
106 static int parse (string input_file)
113 input = File.OpenRead (input_file);
115 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
119 parser = new CSharpParser (input_file, input, defines);
120 parser.yacc_verbose = yacc_verbose;
122 errors = parser.parse ();
123 } catch (Exception ex) {
124 Console.WriteLine (ex);
125 Console.WriteLine ("Compilation aborted");
134 static void Usage (bool is_error)
137 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
138 "mcs [options] source-files\n" +
139 " --about About the Mono C# compiler\n" +
140 " --checked Set default context to checked\n" +
141 " --define SYM Defines the symbol SYM\n" +
142 " --fatal Makes errors fatal\n" +
143 " --stacktrace Shows stack trace at error location\n" +
144 " -L PATH Adds PATH to the assembly link path\n" +
145 " --nostdlib Does not load core libraries\n" +
146 " --nowarn XXX Ignores warning number XXX\n" +
147 " -o FNAME Specifies output file\n" +
148 " --optimize Optimizes\n" +
149 " --parse Only parses the source file\n" +
150 " --probe X Probes for the source to generate code X on line L\n" +
151 " --target KIND Specifies the target (KIND is one of: exe, winexe, " +
152 "library, module)\n" +
153 " --timestamp Displays time stamps of various compiler events\n" +
154 " --unsafe Allows unsafe code\n" +
155 " --werror Treat warnings as errors\n" +
156 " --wlevel LEVEL Sets warning level (the highest is 4, the default)\n" +
157 " -r References an assembly\n" +
158 " -v Verbose parsing (for debugging the parser)\n" +
159 " @file Read response file for more options");
167 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
168 "The compiler source code is released under the terms of the GNU GPL\n\n" +
170 "For more information on Mono, visit the project Web site\n" +
171 " http://www.go-mono.com\n\n" +
173 "The compiler was written by Miguel de Icaza and Ravi Pratap");
176 static void error (string msg)
178 Console.WriteLine ("Error: " + msg);
181 static void notice (string msg)
183 Console.WriteLine (msg);
186 public static int Main (string[] args)
190 return (error_count + Report.Errors) != 0 ? 1 : 0;
193 static public int LoadAssembly (string assembly)
196 string total_log = "";
199 a = Assembly.Load (assembly);
200 RootContext.TypeManager.AddAssembly (a);
202 } catch (FileNotFoundException){
203 foreach (string dir in link_paths){
204 string full_path = dir + "/" + assembly + ".dll";
207 a = Assembly.LoadFrom (full_path);
208 RootContext.TypeManager.AddAssembly (a);
210 } catch (FileNotFoundException ff) {
211 total_log += ff.FusionLog;
215 } catch (BadImageFormatException f) {
216 error ("// Bad file format while loading assembly");
217 error ("Log: " + f.FusionLog);
219 } catch (FileLoadException f){
220 error ("// File Load Exception: ");
221 error ("Log: " + f.FusionLog);
223 } catch (ArgumentNullException){
224 error ("// Argument Null exception ");
228 Report.Error (6, "Can not find assembly `" + assembly + "'" );
229 Console.WriteLine ("Log: \n" + total_log);
235 /// Loads all assemblies referenced on the command line
237 static public int LoadReferences ()
241 foreach (string r in references)
242 errors += LoadAssembly (r);
247 static void SetupDefaultDefines ()
249 defines = new ArrayList ();
250 defines.Add ("__MonoCS__");
253 static string [] LoadArgs (string file)
256 ArrayList args = new ArrayList ();
259 f = new StreamReader (file);
264 while ((line = f.ReadLine ()) != null){
265 string [] line_args = line.Split (new char [] { ' ' });
267 foreach (string arg in line_args)
271 string [] ret_value = new string [args.Count];
272 args.CopyTo (ret_value, 0);
278 // Returns the directory where the system assemblies are installed
280 static string GetSystemDir ()
282 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
284 foreach (Assembly a in assemblies){
285 string codebase = a.CodeBase;
286 if (codebase.EndsWith ("corlib.dll")){
287 return codebase.Substring (0, codebase.LastIndexOf ("/"));
291 Report.Error (-15, "Can not compute my system path");
296 // Given a path specification, splits the path from the file/pattern
298 static void SplitPathAndPattern (string spec, out string path, out string pattern)
300 int p = spec.LastIndexOf ("/");
303 // Windows does not like /file.cs, switch that to:
308 pattern = spec.Substring (1);
310 path = spec.Substring (0, p);
311 pattern = spec.Substring (p + 1);
316 p = spec.LastIndexOf ("\\");
318 path = spec.Substring (0, p - 1);
319 pattern = spec.Substring (p);
327 static int ProcessFile (string f)
329 if (source_files.Contains (f)){
332 "Source file `" + f + "' specified multiple times");
333 Environment.Exit (1);
335 source_files.Add (f, f);
344 static void RecurseOn (string pattern)
350 /// Parses the arguments, and drives the compilation
355 /// TODO: Mostly structured to debug the compiler
356 /// now, needs to be turned into a real driver soon.
358 static void MainDriver (string [] args)
361 string output_file = null;
362 bool parsing_options = true;
364 references = new ArrayList ();
365 link_paths = new ArrayList ();
367 SetupDefaultDefines ();
372 // This is not required because Assembly.Load knows about this
375 link_paths.Add (GetSystemDir ());
377 int argc = args.Length;
378 for (i = 0; i < argc; i++){
379 string arg = args [i];
381 if (arg.StartsWith ("@")){
382 string [] new_args, extra_args;
383 string response_file = arg.Substring (1);
385 if (response_file_list == null)
386 response_file_list = new Hashtable ();
388 if (response_file_list.Contains (response_file)){
390 1515, "Response file `" + response_file +
391 "' specified multiple times");
392 Environment.Exit (1);
395 response_file_list.Add (response_file, response_file);
397 extra_args = LoadArgs (response_file);
398 if (extra_args == null){
399 Report.Error (2011, "Unable to open response file: " +
404 new_args = new string [extra_args.Length + argc];
405 args.CopyTo (new_args, 0);
406 extra_args.CopyTo (new_args, argc);
408 argc = new_args.Length;
413 // Prepare to recurse
416 if (parsing_options && (arg.StartsWith ("-") || arg.StartsWith ("/"))){
423 parsing_options = false;
430 case "--main": case "-m":
431 if ((i + 1) >= argc){
435 RootContext.MainClass = args [++i];
439 RootContext.Unsafe = true;
443 RootContext.Optimize = true;
446 case "/?": case "/h": case "/help":
452 if ((i + 1) >= argc){
456 defines.Add (args [++i]);
464 args [++i], NumberStyles.AllowLeadingSign);
465 Report.SetProbe (code);
467 Report.Error (-14, "Invalid number specified");
479 if ((i + 1) >= argc){
483 output_file = args [++i];
484 string bname = CodeGen.Basename (output_file);
485 if (bname.IndexOf (".") == -1)
486 output_file += ".exe";
490 RootContext.Checked = true;
494 Report.Stacktrace = true;
498 if ((i + 1) >= argc){
503 string type = args [++i];
506 target = Target.Library;
515 target = Target.WinExe;
519 target = Target.Module;
526 if ((i + 1) >= argc){
531 references.Add (args [++i]);
535 if ((i + 1) >= argc){
539 link_paths.Add (args [++i]);
543 RootContext.StdLib = false;
551 Report.WarningsAreErrors = true;
555 if ((i + 1) >= argc){
562 warn = Int32.Parse (args [++i]);
567 Report.SetIgnoreWarning (warn);
571 if ((i + 1) >= argc){
579 level = Int32.Parse (args [++i]);
584 if (level < 0 || level > 4){
585 Report.Error (1900, "Warning level must be 0 to 4");
588 RootContext.WarningLevel = level;
596 if ((i + 1) >= argc){
601 RecurseOn (args [++i]);
606 last_time = DateTime.Now;
611 if (first_source == null)
614 string path, pattern;
615 SplitPathAndPattern (arg, out path, out pattern);
616 string [] files = null;
618 files = Directory.GetFiles (path, pattern);
619 } catch (System.IO.DirectoryNotFoundException) {
620 Report.Error (2001, "Source file `" + arg + "' could not be found");
624 foreach (string f in files)
625 errors += ProcessFile (f);
631 if (first_source == null){
632 Report.Error (2008, "No files to compile were specified");
636 if (Report.Errors > 0)
643 // Load Core Library for default compilation
645 if (RootContext.StdLib){
646 references.Insert (0, "mscorlib");
647 references.Insert (1, "System");
651 error ("Parsing failed");
656 // Load assemblies required
659 ShowTime ("Loading references");
660 errors += LoadReferences ();
662 ShowTime (" References loaded");
665 error ("Could not load one or more assemblies");
669 error_count = errors;
674 if (output_file == null){
675 int pos = first_source.LastIndexOf (".");
678 output_file = first_source.Substring (0, pos) + target_ext;
680 output_file = first_source + target_ext;
683 RootContext.CodeGen = new CodeGen (output_file, output_file);
686 // Before emitting, we need to get the core
687 // types emitted from the user defined types
688 // or from the system ones.
691 ShowTime ("Initializing Core Types");
692 RootContext.TypeManager.InitCoreTypes ();
694 ShowTime (" Core Types done");
696 RootContext.TypeManager.AddModule (RootContext.CodeGen.ModuleBuilder);
699 // The second pass of the compiler
702 ShowTime ("Resolving tree");
703 RootContext.ResolveTree ();
705 ShowTime ("Populate tree");
706 RootContext.PopulateTypes ();
708 if (Report.Errors > 0){
709 error ("Compilation failed");
714 // The code generator
717 ShowTime ("Emitting code");
718 RootContext.EmitCode ();
722 if (Report.Errors > 0){
723 error ("Compilation failed");
728 ShowTime ("Closing types");
730 RootContext.CloseTypes ();
732 PEFileKinds k = PEFileKinds.ConsoleApplication;
734 if (target == Target.Library || target == Target.Module)
736 else if (target == Target.Exe)
737 k = PEFileKinds.ConsoleApplication;
738 else if (target == Target.WinExe)
739 k = PEFileKinds.WindowApplication;
741 if (target == Target.Exe || target == Target.WinExe){
742 MethodInfo ep = RootContext.EntryPoint;
745 Report.Error (5001, "Program " + output_file +
746 " does not have an entry point defined");
750 RootContext.CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
753 RootContext.CodeGen.Save (output_file);
755 ShowTime ("Saved output");
757 if (Report.Errors > 0){
758 error ("Compilation failed");
760 } else if (Report.ProbeCode != 0){
761 error ("Failed to report code " + Report.ProbeCode);
762 Environment.Exit (124);