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 static string[] LinkPaths = null;
49 [Option("Defines the symbol PARAM", "define")]
50 public static string[] Defines = null;
52 [Option("Only parses the source file (for debugging the tokenizer)", "parse")]
53 public static bool parse_only = false;
55 private static bool load_default_config = true;
57 [Option("Disables implicit references to assemblies", "noconfig")]
58 public bool NoConfig { set { load_default_config = !value; } }
60 [Option("Allows unsafe code", "unsafe")]
61 public bool AllowUnsafeCode { set { RootContext.Unsafe = value; } }
63 private string output_file;
65 [Option("Specifies output file", 'o', "output")]
66 public WhatToDoNext SetOutputFile(string FileName)
68 output_file = FileName;
69 string bname = CodeGen.Basename (output_file);
70 if (bname.IndexOf (".") == -1)
71 output_file += ".exe";
72 return WhatToDoNext.GoAhead;
76 [Option("Only tokenizes source files", "tokenize")]
77 public static bool tokenize = true;
79 [Option("Set default context to checked", "checked")]
80 public bool Checked { set { RootContext.Checked = value; } }
82 [Option("Shows stack trace at error location", "Stacktrace")]
83 public bool Stacktrace { set { Report.Stacktrace = value; } }
85 private static ArrayList references = new ArrayList();
87 [Option("References an assembly", 'r')]
88 public static string reference { set { references.Add(value); } }
90 [Option("Adds PARAM as a resource", "resource")]
91 public static string[] resources;
93 [Option("Set default context to checked", "nostdlib")]
94 public bool nostdlib { set { RootContext.StdLib = !value; } }
96 [Option("Makes errors fatal", "fatal")]
97 public bool Fatal { set { Report.Fatal = value; } }
99 [Option("Treat warnings as errors", "werror")]
100 public bool WarningsAreErrors { set { Report.WarningsAreErrors = value; } }
102 [Option("Ignores warning number PARAM", "nowarn")]
103 public WhatToDoNext SetIgnoreWarning(int warn)
105 Report.SetIgnoreWarning(warn);
106 return WhatToDoNext.GoAhead;
109 [Option("Recursively compiles the files in PARAM ([dir]/file)", "recurse")]
110 public WhatToDoNext recurse(string DirName)
112 AddFiles (DirName, true);
113 return WhatToDoNext.GoAhead;
117 [Option("Write symbolic debugging information to FILE-debug.s", 'g', "debug")]
118 public static bool want_debugging_support = false;
120 [Option("Debugger arguments", "debug-args")]
121 public WhatToDoNext SetDebugArgs(string args)
123 char[] sep = { ',' };
124 debug_arglist.AddRange (args.Split (sep));
125 return WhatToDoNext.GoAhead;
128 [Option("Specifies the target (PARAM is one of: exe, winexe, library, module)", "target")]
129 public WhatToDoNext SetTarget(string type)
134 target = Target.Library;
143 target = Target.WinExe;
147 target = Target.Module;
151 return WhatToDoNext.GoAhead;
154 [Option("Sets warning level (the highest is 4, the default)", "wlevel")]
155 public int wlevel { set { RootContext.WarningLevel = value; } }
157 [Option("Sets warning level (the highest is 4, the default)")]
158 public bool timestamp
163 last_time = DateTime.Now;
164 debug_arglist.Add("timestamp");
168 static void Usage (bool is_error)
170 Console.WriteLine ( @"
171 MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
172 --timestamp Displays time stamps of various compiler events
173 @file Read response file for more options
178 // If any of these fail, we ignore the problem. This is so
179 // that we can list all the assemblies in Windows and not fail
180 // if they are missing on Linux.
182 static ArrayList soft_references;
184 static int error_count = 0;
186 static string first_source;
188 static Target target = Target.Exe;
189 static string target_ext = ".exe";
191 static ArrayList debug_arglist = new ArrayList ();
193 static bool timestamps = false;
195 static Hashtable source_files = new Hashtable ();
198 // An array of the defines from the command line
200 static ArrayList defines;
204 // Last time we took the time
206 static DateTime last_time;
207 static void ShowTime (string msg)
209 DateTime now = DateTime.Now;
210 TimeSpan span = now - last_time;
214 "[{0:00}:{1:000}] {2}",
215 (int) span.TotalSeconds, span.Milliseconds, msg);
218 static void error (string msg)
220 Console.WriteLine ("Error: " + msg);
223 static void notice (string msg)
225 Console.WriteLine (msg);
228 public static int Main (string[] args)
230 Driver Exec = new Driver();
232 if (Exec.MainDriver(args) && Report.Errors == 0)
234 Console.Write("Compilation succeeded");
235 if (Report.Warnings > 0)
237 Console.Write(" - {0} warning(s)", Report.Warnings);
244 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
245 Report.Errors, Report.Warnings);
250 static public int LoadAssembly (string assembly, bool soft)
253 string total_log = "";
256 char[] path_chars = { '/', '\\', '.' };
258 if (assembly.IndexOfAny (path_chars) != -1)
259 a = Assembly.LoadFrom (assembly);
261 a = Assembly.Load (assembly);
262 TypeManager.AddAssembly (a);
264 } catch (FileNotFoundException){
265 foreach (string dir in LinkPaths){
266 string full_path = dir + "/" + assembly + ".dll";
269 a = Assembly.LoadFrom (full_path);
270 TypeManager.AddAssembly (a);
272 } catch (FileNotFoundException ff) {
273 total_log += ff.FusionLog;
279 } catch (BadImageFormatException f) {
280 error ("// Bad file format while loading assembly");
281 error ("Log: " + f.FusionLog);
283 } catch (FileLoadException f){
284 error ("File Load Exception: " + assembly);
285 error ("Log: " + f.FusionLog);
287 } catch (ArgumentNullException){
288 error ("// Argument Null exception ");
292 Report.Error (6, "Can not find assembly `" + assembly + "'" );
293 Console.WriteLine ("Log: \n" + total_log);
299 /// Loads all assemblies referenced on the command line
301 static public int LoadReferences ()
305 foreach (string r in references)
306 errors += LoadAssembly (r, false);
308 foreach (string r in soft_references)
309 errors += LoadAssembly (r, true);
314 static void SetupDefaultDefines ()
316 defines = new ArrayList ();
317 defines.Add ("__MonoBASIC__");
322 // Returns the directory where the system assemblies are installed
324 static string GetSystemDir ()
326 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
328 foreach (Assembly a in assemblies){
329 string codebase = a.CodeBase;
330 if (codebase.EndsWith ("corlib.dll")){
331 return codebase.Substring (0, codebase.LastIndexOf ("/"));
335 Report.Error (-15, "Can not compute my system path");
340 // Given a path specification, splits the path from the file/pattern
342 static void SplitPathAndPattern (string spec, out string path, out string pattern)
344 int p = spec.LastIndexOf ("/");
347 // Windows does not like /file.cs, switch that to:
352 pattern = spec.Substring (1);
354 path = spec.Substring (0, p);
355 pattern = spec.Substring (p + 1);
360 p = spec.LastIndexOf ("\\");
362 path = spec.Substring (0, p);
363 pattern = spec.Substring (p + 1);
372 static int ProcessSourceFile(string filename)
375 GenericParser.Tokenize(filename);
377 return GenericParser.Parse(filename);
382 static bool AddFiles (string spec, bool recurse)
384 string path, pattern;
386 SplitPathAndPattern (spec, out path, out pattern);
387 if (pattern.IndexOf ("*") == -1){
388 return AddFile (spec);
391 string [] files = null;
393 files = Directory.GetFiles (path, pattern);
394 } catch (System.IO.DirectoryNotFoundException) {
395 Report.Error (2001, "Source file `" + spec + "' could not be found");
397 } catch (System.IO.IOException){
398 Report.Error (2001, "Source file `" + spec + "' could not be found");
401 foreach (string f in files)
407 string [] dirs = null;
410 dirs = Directory.GetDirectories (path);
414 foreach (string d in dirs) {
416 // Don't include path in this string, as each
417 // directory entry already does
418 AddFiles (d + "/" + pattern, true);
425 static void DefineDefaultConfig ()
428 // For now the "default config" is harcoded into the compiler
429 // we can move this outside later
431 string [] default_config =
436 "Microsoft.VisualBasic", // just for now
439 // Is it worth pre-loading all this stuff?
442 "System.Configuration.Install",
444 "System.DirectoryServices",
445 "System.Drawing.Design",
447 "System.EnterpriseServices",
450 "System.Runtime.Remoting",
451 "System.Runtime.Serialization.Formatters.Soap",
453 "System.ServiceProcess",
455 "System.Web.RegularExpressions",
456 "System.Web.Services",
457 "System.Windows.Forms"
462 foreach (string def in default_config)
463 soft_references.Insert (p++, def);
466 private static bool AddFile(string fileName)
469 if (first_source == null)
472 if (source_files.Contains(f))
474 Report.Error (1516, "Source file `" + f + "' specified multiple times");
478 source_files.Add(f, f);
485 /// Parses the arguments, and drives the compilation
490 /// TODO: Mostly structured to debug the compiler
491 /// now, needs to be turned into a real driver soon.
493 bool MainDriver(string [] args)
495 int errors = 0;//, i;
496 string output_file = null;
498 soft_references = new ArrayList ();
499 SetupDefaultDefines ();
501 this.ProcessArgs(args);
503 foreach(string arg in this.RemainingArguments)
506 foreach(string filename in source_files.Values)
507 errors += ProcessSourceFile(filename);
509 if (first_source == null)
511 Report.Error (2008, "No files to compile were specified");
518 if (Report.Errors > 0)
525 // Load Core Library for default compilation
527 if (RootContext.StdLib)
528 references.Insert (0, "mscorlib");
530 if (load_default_config)
531 DefineDefaultConfig ();
535 error ("Parsing failed");
540 // Load assemblies required
543 ShowTime ("Loading references");
544 errors += LoadReferences ();
546 ShowTime (" References loaded");
550 error ("Could not load one or more assemblies");
554 error_count = errors;
559 if (output_file == null)
561 int pos = first_source.LastIndexOf (".");
564 output_file = first_source.Substring (0, pos) + target_ext;
566 output_file = first_source + target_ext;
569 string[] debug_args = new string [debug_arglist.Count];
570 debug_arglist.CopyTo(debug_args);
571 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
573 TypeManager.AddModule (CodeGen.ModuleBuilder);
576 // Before emitting, we need to get the core
577 // types emitted from the user defined types
578 // or from the system ones.
581 ShowTime ("Initializing Core Types");
582 if (!RootContext.StdLib)
584 RootContext.ResolveCore ();
585 if (Report.Errors > 0)
589 TypeManager.InitCoreTypes ();
591 ShowTime (" Core Types done");
594 // The second pass of the compiler
597 ShowTime ("Resolving tree");
598 RootContext.ResolveTree ();
600 ShowTime ("Populate tree");
602 if (Report.Errors > 0)
604 error ("Compilation failed");
608 if (!RootContext.StdLib)
609 RootContext.BootCorlib_PopulateCoreTypes ();
610 RootContext.PopulateTypes ();
612 TypeManager.InitCodeHelpers ();
614 if (Report.Errors > 0)
616 error ("Compilation failed");
621 // The code generator
624 ShowTime ("Emitting code");
625 RootContext.EmitCode ();
629 if (Report.Errors > 0)
631 error ("Compilation failed");
636 ShowTime ("Closing types");
638 RootContext.CloseTypes ();
640 // PEFileKinds k = PEFileKinds.ConsoleApplication;
642 // if (target == Target.Library || target == Target.Module)
643 // k = PEFileKinds.Dll;
644 // else if (target == Target.Exe)
645 // k = PEFileKinds.ConsoleApplication;
646 // else if (target == Target.WinExe)
647 // k = PEFileKinds.WindowApplication;
649 // if (target == Target.Exe || target == Target.WinExe){
650 // MethodInfo ep = RootContext.EntryPoint;
653 // Report.Error (5001, "Program " + output_file +
654 // " does not have an entry point defined");
658 // CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
664 if (resources != null)
666 foreach (string file in resources)
667 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
670 CodeGen.Save (output_file);
672 ShowTime ("Saved output");
674 if (want_debugging_support)
676 CodeGen.SaveSymbols ();
678 ShowTime ("Saved symbols");
681 if (Report.ExpectedError != 0)
683 Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
684 Environment.Exit (1);
687 return (Report.Errors == 0);