2 // driver.cs: The compiler command line driver.
4 // Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)
5 // Based on mcs by : Miguel de Icaza (miguel@gnu.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2002 Rafael Teixeira
12 namespace Mono.Languages
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
19 using System.Globalization;
21 using Mono.GetOptions;
25 Library, Exe, Module, WinExe
29 /// The compiler driver.
31 public class Driver : Options
34 [Option("Verbose parsing (for debugging the parser)",'v')]
35 public bool verbose { set { GenericParser.yacc_verbose_flag = value; } }
37 [Option("Specifies PARAM as main (starting) class", 'm')]
38 public string main { set { RootContext.MainClass = value; } }
40 [Option("About the MonoBASIC compiler", "about")]
41 public override WhatToDoNext DoAbout()
43 return base.DoAbout();
46 [Option("Adds PARAM to the assembly link path", 'L')]
47 public string[] LinkPaths = null;
49 [Option("Defines the symbol PARAM", "define")]
50 public string[] Defines = null;
52 [Option("Only parses the source file (for debugging the tokenizer)", "parse")]
53 public bool parse_only = false;
56 [Option("Disables implicit references to assemblies", "noconfig")]
57 public bool NoConfig { set { load_default_config = !value; } }
59 [Option("Allows unsafe code", "unsafe")]
60 public bool AllowUnsafeCode { set { RootContext.Unsafe = value; } }
62 [Option("Specifies output file", 'o', "output")]
63 public string output_file = null;
65 [Option("Only tokenizes source files", "tokenize")]
66 public bool tokenize = false;
68 [Option("Set default context to checked", "checked")]
69 public bool Checked { set { RootContext.Checked = value; } }
71 [Option("Shows stack trace at Error location", "Stacktrace")]
72 public bool Stacktrace { set { Report.Stacktrace = value; } }
74 [Option("References an assembly", 'r')]
75 public string reference { set { references.Add(value); } }
77 [Option("Adds PARAM as a resource", "resource")]
78 public string[] resources;
80 [Option("Set default context to checked", "nostdlib")]
81 public bool nostdlib { set { RootContext.StdLib = !value; } }
83 [Option("Makes errors fatal", "fatal")]
84 public bool Fatal { set { Report.Fatal = value; } }
86 [Option("Treat warnings as errors", "werror")]
87 public bool WarningsAreErrors { set { Report.WarningsAreErrors = value; } }
89 [Option("Ignores warning number PARAM", "nowarn")]
90 public WhatToDoNext SetIgnoreWarning(int warn)
92 Report.SetIgnoreWarning(warn);
93 return WhatToDoNext.GoAhead;
96 [Option("Recursively compiles the files in PARAM ([dir]/file)", "recurse")]
97 public WhatToDoNext recurse(string DirName)
99 AddFiles (DirName, true);
100 return WhatToDoNext.GoAhead;
104 [Option("Write symbolic debugging information to FILE-debug.s", 'g', "debug")]
105 public bool want_debugging_support = false;
107 [Option("Debugger arguments", "debug-args")]
108 public WhatToDoNext SetDebugArgs(string args)
110 char[] sep = { ',' };
111 debug_arglist.AddRange (args.Split (sep));
112 return WhatToDoNext.GoAhead;
115 [Option("Specifies the target (PARAM is one of: exe, winexe, library, module)", "target")]
116 public WhatToDoNext SetTarget(string type)
121 target = Target.Library;
130 target = Target.WinExe;
134 target = Target.Module;
138 return WhatToDoNext.GoAhead;
141 [Option("Sets warning level (the highest is 4, the default)", "wlevel")]
142 public int wlevel { set { RootContext.WarningLevel = value; } }
144 [Option("Displays time stamps of various compiler events")]
145 public bool timestamp
150 last_time = DateTime.Now;
151 debug_arglist.Add("timestamp");
155 // TODO : response file support
158 ArrayList defines = new ArrayList();
159 ArrayList references = new ArrayList();
160 ArrayList soft_references = new ArrayList();
161 string first_source = null;
162 Target target = Target.Exe;
163 string target_ext = ".exe";
164 ArrayList debug_arglist = new ArrayList ();
165 bool timestamps = false;
166 Hashtable source_files = new Hashtable ();
167 bool load_default_config = true;
170 // Last time we took the time
173 void ShowTime (string msg)
175 DateTime now = DateTime.Now;
176 TimeSpan span = now - last_time;
180 "[{0:00}:{1:000}] {2}",
181 (int) span.TotalSeconds, span.Milliseconds, msg);
184 public static int Main (string[] args)
186 Driver Exec = new Driver();
188 Exec.MainDriver(args);
190 if (Report.Errors == 0)
192 Console.Write("Compilation succeeded");
193 if (Report.Warnings > 0)
195 Console.Write(" - {0} warning(s)", Report.Warnings);
202 Console.WriteLine("Compilation failed: {0} Error(s), {1} warnings",
203 Report.Errors, Report.Warnings);
208 public int LoadAssembly (string assembly, bool soft)
211 string total_log = "";
214 char[] path_chars = { '/', '\\' };
216 if (assembly.IndexOfAny (path_chars) != -1)
217 a = Assembly.LoadFrom(assembly);
219 a = Assembly.Load(assembly);
220 TypeManager.AddAssembly (a);
222 } catch (FileNotFoundException){
223 foreach (string dir in LinkPaths){
224 string full_path = dir + "/" + assembly + ".dll";
227 a = Assembly.LoadFrom (full_path);
228 TypeManager.AddAssembly (a);
230 } catch (FileNotFoundException ff) {
231 total_log += ff.FusionLog;
237 } catch (BadImageFormatException f) {
238 Error ("// Bad file format while loading assembly");
239 Error ("Log: " + f.FusionLog);
241 } catch (FileLoadException f){
242 Error ("File Load Exception: " + assembly);
243 Error ("Log: " + f.FusionLog);
245 } catch (ArgumentNullException){
246 Error ("// Argument Null exception ");
250 Report.Error (6, "Can not find assembly `" + assembly + "'" );
251 Console.WriteLine ("Log: \n" + total_log);
256 void Error(string message)
258 Console.WriteLine(message);
262 /// Loads all assemblies referenced on the command line
264 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 void SetupDefaultDefines ()
279 defines = new ArrayList ();
280 defines.Add ("__MonoBASIC__");
285 // Returns the directory where the system assemblies are installed
287 string GetSystemDir ()
289 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
291 foreach (Assembly a in assemblies){
292 string codebase = a.CodeBase;
293 if (codebase.EndsWith ("corlib.dll")){
294 return codebase.Substring (0, codebase.LastIndexOf ("/"));
298 Report.Error (-15, "Can not compute my system path");
303 // Given a path specification, splits the path from the file/pattern
305 void SplitPathAndPattern (string spec, out string path, out string pattern)
307 int p = spec.LastIndexOf ("/");
310 // Windows does not like /file.cs, switch that to:
315 pattern = spec.Substring (1);
317 path = spec.Substring (0, p);
318 pattern = spec.Substring (p + 1);
323 p = spec.LastIndexOf ("\\");
325 path = spec.Substring (0, p);
326 pattern = spec.Substring (p + 1);
334 bool AddFiles (string spec, bool recurse)
336 string path, pattern;
338 SplitPathAndPattern(spec, out path, out pattern);
339 if (pattern.IndexOf("*") == -1)
345 string [] files = null;
347 files = Directory.GetFiles(path, pattern);
348 } catch (System.IO.DirectoryNotFoundException) {
349 Report.Error (2001, "Source file `" + spec + "' could not be found");
351 } catch (System.IO.IOException){
352 Report.Error (2001, "Source file `" + spec + "' could not be found");
355 foreach (string f in files)
361 string [] dirs = null;
364 dirs = Directory.GetDirectories(path);
368 foreach (string d in dirs) {
370 // Don't include path in this string, as each
371 // directory entry already does
372 AddFiles (d + "/" + pattern, true);
378 void DefineDefaultConfig ()
381 // For now the "default config" is harcoded into the compiler
382 // we can move this outside later
384 string [] default_config =
389 "Microsoft.VisualBasic", // just for now
392 // Is it worth pre-loading all this stuff?
395 "System.Configuration.Install",
397 "System.DirectoryServices",
398 "System.Drawing.Design",
400 "System.EnterpriseServices",
403 "System.Runtime.Remoting",
404 "System.Runtime.Serialization.Formatters.Soap",
406 "System.ServiceProcess",
408 "System.Web.RegularExpressions",
409 "System.Web.Services",
410 "System.Windows.Forms"
414 foreach (string def in default_config)
415 soft_references.Add(def);
419 public void AddFile(string fileName)
422 if (first_source == null)
425 if (source_files.Contains(f))
426 Report.Error(1516, "Source file '" + f + "' specified multiple times");
428 source_files.Add(f, f);
431 void ProcessSourceFile(string filename)
434 GenericParser.Tokenize(filename);
436 GenericParser.Parse(filename);
439 string outputFile_Name = null;
441 string outputFileName
445 if (outputFile_Name == null)
447 if (output_file == null)
449 int pos = first_source.LastIndexOf(".");
452 output_file = first_source.Substring(0, pos);
454 output_file = first_source;
456 string bname = CodeGen.Basename(output_file);
457 if (bname.IndexOf(".") == -1)
458 output_file += target_ext;
459 outputFile_Name = output_file;
461 return outputFile_Name;
466 /// Parses the arguments, and calls the compilation process.
468 void MainDriver(string [] args)
476 SetupDefaultDefines();
479 bool ParseAll() // Phase 1
481 if (first_source == null)
483 Report.Error(2008, "No files to compile were specified");
487 foreach(string filename in source_files.Values)
488 ProcessSourceFile(filename);
490 if (tokenize || parse_only || (Report.Errors > 0))
493 return true; // everything went well go ahead
496 void InitializeDebuggingSupport()
498 string[] debug_args = new string [debug_arglist.Count];
499 debug_arglist.CopyTo(debug_args);
500 CodeGen.Init(outputFileName, outputFileName, want_debugging_support, debug_args);
501 TypeManager.AddModule(CodeGen.ModuleBuilder);
504 public bool ResolveAllTypes() // Phase 2
506 // Load Core Library for default compilation
507 if (RootContext.StdLib)
508 references.Insert(0, "mscorlib");
510 if (load_default_config)
511 DefineDefaultConfig();
514 ShowTime("Loading references");
516 // Load assemblies required
517 if (LoadReferences() > 0)
519 Error ("Could not load one or more assemblies");
524 ShowTime("References loaded");
526 InitializeDebuggingSupport();
529 // Before emitting, we need to get the core
530 // types emitted from the user defined types
531 // or from the system ones.
534 ShowTime ("Initializing Core Types");
536 if (!RootContext.StdLib)
537 RootContext.ResolveCore ();
538 if (Report.Errors > 0)
541 TypeManager.InitCoreTypes();
542 if (Report.Errors > 0)
546 ShowTime (" Core Types done");
549 ShowTime ("Resolving tree");
551 // The second pass of the compiler
552 RootContext.ResolveTree ();
553 if (Report.Errors > 0)
557 ShowTime ("Populate tree");
559 if (!RootContext.StdLib)
560 RootContext.BootCorlib_PopulateCoreTypes();
561 if (Report.Errors > 0)
564 RootContext.PopulateTypes();
565 if (Report.Errors > 0)
568 TypeManager.InitCodeHelpers();
569 if (Report.Errors > 0)
575 bool GenerateAssembly()
578 // The code generator
581 ShowTime ("Emitting code");
583 RootContext.EmitCode();
584 if (Report.Errors > 0)
592 ShowTime ("Closing types");
594 RootContext.CloseTypes ();
595 if (Report.Errors > 0)
601 PEFileKinds k = PEFileKinds.ConsoleApplication;
603 if (target == Target.Library || target == Target.Module)
605 else if (target == Target.Exe)
606 k = PEFileKinds.ConsoleApplication;
607 else if (target == Target.WinExe)
608 k = PEFileKinds.WindowApplication;
610 if (target == Target.Exe || target == Target.WinExe)
612 MethodInfo ep = RootContext.EntryPoint;
616 Report.Error (5001, "Program " + outputFileName +
617 " does not have an entry point defined");
621 CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
625 if (resources != null)
626 foreach (string file in resources)
627 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
629 CodeGen.Save(outputFileName);
632 ShowTime ("Saved output");
635 if (want_debugging_support)
637 CodeGen.SaveSymbols ();
639 ShowTime ("Saved symbols");
645 public void CompileAll()
647 if (!ParseAll()) // Phase 1
650 if (!ResolveAllTypes()) // Phase 2
653 if (!GenerateAssembly()) // Phase 3
656 if (Report.ExpectedError != 0)
657 Error("Failed to report expected Error " + Report.ExpectedError);