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;
23 Library, Exe, Module, WinExe
27 /// The compiler driver.
33 // Assemblies references to be linked. Initialized with
34 // mscorlib.dll elsewhere.
35 static ArrayList references;
38 // If any of these fail, we ignore the problem. This is so
39 // that we can list all the assemblies in Windows and not fail
40 // if they are missing on Linux.
42 static ArrayList soft_references;
45 static ArrayList link_paths;
47 // Whether we want to only run the tokenizer
48 static bool tokenize = false;
50 static int error_count = 0;
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 // An array of the defines from the command line
74 static ArrayList defines;
77 // A list of resource files
79 static ArrayList resources = new ArrayList();
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);
97 static void Usage (bool is_error)
99 Console.WriteLine ( @"
100 MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
101 Usage: mbas [options] source-files
103 --about About the MonoBASIC compiler
104 --checked Set default context to checked
105 --define SYM Defines the symbol SYM
106 --fatal Makes errors fatal
107 -g, --debug Write symbolic debugging information to FILE-debug.s
108 -h, --help Prints this usage instructions
109 -L PATH Adds PATH to the assembly link path
111 --main CLASS Specifies CLASS as main (starting) class
112 --noconfig Disables implicit references to assemblies
113 --nostdlib Does not load core libraries
114 --nowarn XXX Ignores warning number XXX
116 --output FNAME Specifies output file
117 --parse Only parses the source file (for debugging the tokenizer)
118 --probe X Probes for the source to generate code X on line L
119 -r ASSEMBLY References an assembly
120 --recurse SPEC Recursively compiles the files in SPEC ([dir]/file)
121 --resource FILE Adds FILE as a resource
122 --stacktrace Shows stack trace at error location
123 --target KIND Specifies the target (KIND is one of: exe, winexe, library, module)
124 --tokenize Only tokenizes source files
125 --timestamp Displays time stamps of various compiler events
126 --unsafe Allows unsafe code
127 --werror Treat warnings as errors
128 -v Verbose parsing (for debugging the parser)
129 --wlevel LEVEL Sets warning level (the highest is 4, the default)
130 @file Read response file for more options
138 // Options.ShowAbout();
141 static void error (string msg)
143 Console.WriteLine ("Error: " + msg);
146 static void notice (string msg)
148 Console.WriteLine (msg);
151 // private static Mono.GetOptions.OptionList Options;
153 private static bool SetVerboseParsing(object nothing)
155 GenericParser.yacc_verbose_flag = true;
159 public static int Main (string[] args)
161 /* Options = new Mono.GetOptions.OptionList("The compiler source code is released under the terms of the GNU GPL\n\n" +
162 "For more information on Mono, visit the project Web site\n" +
163 " http://www.go-mono.com" , "mbas [options] source-files");
164 Options.AddAbout(' ',"about", "About the MonoBASIC compiler");
165 Options.AddBooleanSwitch ('v',"verbose", "Verbose parsing (for debugging the parser)", false, new Mono.GetOptions.OptionFound(SetVerboseParsing) );
167 return (error_count + Report.Errors) != 0 ? 1 : 0;
170 static public int LoadAssembly (string assembly, bool soft)
173 string total_log = "";
176 char[] path_chars = { '/', '\\', '.' };
178 if (assembly.IndexOfAny (path_chars) != -1)
179 a = Assembly.LoadFrom (assembly);
181 a = Assembly.Load (assembly);
182 TypeManager.AddAssembly (a);
184 } catch (FileNotFoundException){
185 foreach (string dir in link_paths){
186 string full_path = dir + "/" + assembly + ".dll";
189 a = Assembly.LoadFrom (full_path);
190 TypeManager.AddAssembly (a);
192 } catch (FileNotFoundException ff) {
193 total_log += ff.FusionLog;
199 } catch (BadImageFormatException f) {
200 error ("// Bad file format while loading assembly");
201 error ("Log: " + f.FusionLog);
203 } catch (FileLoadException f){
204 error ("File Load Exception: " + assembly);
205 error ("Log: " + f.FusionLog);
207 } catch (ArgumentNullException){
208 error ("// Argument Null exception ");
212 Report.Error (6, "Can not find assembly `" + assembly + "'" );
213 Console.WriteLine ("Log: \n" + total_log);
219 /// Loads all assemblies referenced on the command line
221 static public int LoadReferences ()
225 foreach (string r in references)
226 errors += LoadAssembly (r, false);
228 foreach (string r in soft_references)
229 errors += LoadAssembly (r, true);
234 static void SetupDefaultDefines ()
236 defines = new ArrayList ();
237 defines.Add ("__MonoBASIC__");
240 static string [] LoadArgs (string file)
243 ArrayList args = new ArrayList ();
246 f = new StreamReader (file);
251 while ((line = f.ReadLine ()) != null){
252 string [] line_args = line.Split (new char [] { ' ' });
254 foreach (string arg in line_args)
258 string [] ret_value = new string [args.Count];
259 args.CopyTo (ret_value, 0);
265 // Returns the directory where the system assemblies are installed
267 static string GetSystemDir ()
269 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
271 foreach (Assembly a in assemblies){
272 string codebase = a.CodeBase;
273 if (codebase.EndsWith ("corlib.dll")){
274 return codebase.Substring (0, codebase.LastIndexOf ("/"));
278 Report.Error (-15, "Can not compute my system path");
283 // Given a path specification, splits the path from the file/pattern
285 static void SplitPathAndPattern (string spec, out string path, out string pattern)
287 int p = spec.LastIndexOf ("/");
290 // Windows does not like /file.cs, switch that to:
295 pattern = spec.Substring (1);
297 path = spec.Substring (0, p);
298 pattern = spec.Substring (p + 1);
303 p = spec.LastIndexOf ("\\");
305 path = spec.Substring (0, p);
306 pattern = spec.Substring (p + 1);
314 static int AddFile(string f)
316 if (first_source == null)
319 if (source_files.Contains (f)){
322 "Source file `" + f + "' specified multiple times");
325 source_files.Add(f, f);
330 static int ProcessSourceFile(string filename)
333 GenericParser.Tokenize(filename);
335 return GenericParser.Parse(filename);
340 static int AddFiles (string spec, bool recurse)
342 string path, pattern;
345 SplitPathAndPattern (spec, out path, out pattern);
346 if (pattern.IndexOf ("*") == -1){
347 return AddFile (spec);
350 string [] files = null;
352 files = Directory.GetFiles (path, pattern);
353 } catch (System.IO.DirectoryNotFoundException) {
354 Report.Error (2001, "Source file `" + spec + "' could not be found");
356 } catch (System.IO.IOException){
357 Report.Error (2001, "Source file `" + spec + "' could not be found");
360 foreach (string f in files)
361 errors += AddFile (f);
366 string [] dirs = null;
369 dirs = Directory.GetDirectories (path);
373 foreach (string d in dirs) {
375 // Don't include path in this string, as each
376 // directory entry already does
377 errors += AddFiles (d + "/" + pattern, true);
384 static void DefineDefaultConfig ()
387 // For now the "default config" is harcoded into the compiler
388 // we can move this outside later
390 string [] default_config =
395 "Microsoft.VisualBasic", // just for now
398 // Is it worth pre-loading all this stuff?
401 "System.Configuration.Install",
403 "System.DirectoryServices",
404 "System.Drawing.Design",
406 "System.EnterpriseServices",
409 "System.Runtime.Remoting",
410 "System.Runtime.Serialization.Formatters.Soap",
412 "System.ServiceProcess",
414 "System.Web.RegularExpressions",
415 "System.Web.Services",
416 "System.Windows.Forms"
421 foreach (string def in default_config)
422 soft_references.Insert (p++, def);
426 /// Parses the arguments, and drives the compilation
431 /// TODO: Mostly structured to debug the compiler
432 /// now, needs to be turned into a real driver soon.
434 static void MainDriver (string [] args)
437 string output_file = null;
438 bool parsing_options = true;
440 references = new ArrayList ();
441 soft_references = new ArrayList ();
442 link_paths = new ArrayList ();
443 SetupDefaultDefines ();
448 // This is not required because Assembly.Load knows about this
451 link_paths.Add (GetSystemDir ());
453 // Options.ProcessArgs(args);
456 int argc = args.Length;
457 for (i = 0; i < argc; i++){
458 string arg = args [i];
460 if (arg.StartsWith ("@")){
461 string [] new_args, extra_args;
462 string response_file = arg.Substring (1);
464 if (response_file_list == null)
465 response_file_list = new Hashtable ();
467 if (response_file_list.Contains (response_file)){
469 1515, "Response file `" + response_file +
470 "' specified multiple times");
471 Environment.Exit (1);
474 response_file_list.Add (response_file, response_file);
476 extra_args = LoadArgs (response_file);
477 if (extra_args == null){
478 Report.Error (2011, "Unable to open response file: " +
483 new_args = new string [extra_args.Length + argc];
484 args.CopyTo (new_args, 0);
485 extra_args.CopyTo (new_args, argc);
487 argc = new_args.Length;
492 // Prepare to recurse
495 if (parsing_options && (arg.StartsWith ("-"))){
498 GenericParser.yacc_verbose_flag = true;
502 parsing_options = false;
509 case "--main": case "-m":
510 if ((i + 1) >= argc){
514 RootContext.MainClass = args [++i];
518 RootContext.Unsafe = true;
521 case "/?": case "/h": case "/help":
527 if ((i + 1) >= argc){
531 defines.Add (args [++i]);
539 args [++i], NumberStyles.AllowLeadingSign);
540 Report.SetProbe (code);
542 Report.Error (-14, "Invalid number specified");
554 if ((i + 1) >= argc){
558 output_file = args [++i];
559 string bname = CodeGen.Basename (output_file);
560 if (bname.IndexOf (".") == -1)
561 output_file += ".exe";
565 RootContext.Checked = true;
569 Report.Stacktrace = true;
573 if ((i + 1) >= argc){
578 string type = args [++i];
581 target = Target.Library;
590 target = Target.WinExe;
594 target = Target.Module;
604 if ((i + 1) >= argc){
609 references.Add(args [++i]);
616 Console.WriteLine("Missing argument to --resource");
620 resources.Add(args [++i]);
625 if ((i + 1) >= argc){
629 link_paths.Add (args [++i]);
633 RootContext.StdLib = false;
641 Report.WarningsAreErrors = true;
645 if ((i + 1) >= argc){
652 warn = Int32.Parse (args [++i]);
657 Report.SetIgnoreWarning (warn);
661 if ((i + 1) >= argc){
664 "--wlevel requires an value from 0 to 4");
671 level = Int32.Parse (args [++i]);
675 "--wlevel requires an value from 0 to 4");
678 if (level < 0 || level > 4){
679 Report.Error (1900, "Warning level must be 0 to 4");
682 RootContext.WarningLevel = level;
690 if ((i + 1) >= argc){
691 Console.WriteLine ("--recurse requires an argument");
695 errors += AddFiles (args [++i], true);
700 last_time = DateTime.Now;
701 debug_arglist.Add("timestamp");
704 case "--debug": case "-g":
705 want_debugging_support = true;
709 if ((i + 1) >= argc){
710 Console.WriteLine ("--debug-args requires an argument");
714 char[] sep = { ',' };
715 debug_arglist.AddRange (args [++i].Split (sep));
719 load_default_config = false;
723 Console.WriteLine ("Unknown option: " + arg);
729 // Rafael: Does not compile them yet!!!
730 errors += AddFiles(arg, false);
733 //Rafael: Compile all source files!!!
734 foreach(string filename in source_files.Values)
735 errors += ProcessSourceFile(filename);
737 if (first_source == null)
739 Report.Error (2008, "No files to compile were specified");
746 if (Report.Errors > 0)
753 // Load Core Library for default compilation
755 if (RootContext.StdLib)
756 references.Insert (0, "mscorlib");
758 if (load_default_config)
759 DefineDefaultConfig ();
762 error ("Parsing failed");
767 // Load assemblies required
770 ShowTime ("Loading references");
771 errors += LoadReferences ();
773 ShowTime (" References loaded");
776 error ("Could not load one or more assemblies");
780 error_count = errors;
785 if (output_file == null){
786 int pos = first_source.LastIndexOf (".");
789 output_file = first_source.Substring (0, pos) + target_ext;
791 output_file = first_source + target_ext;
794 string[] debug_args = new string [debug_arglist.Count];
795 debug_arglist.CopyTo(debug_args);
796 CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
798 TypeManager.AddModule (CodeGen.ModuleBuilder);
801 // Before emitting, we need to get the core
802 // types emitted from the user defined types
803 // or from the system ones.
806 ShowTime ("Initializing Core Types");
807 if (!RootContext.StdLib){
808 RootContext.ResolveCore ();
809 if (Report.Errors > 0)
813 TypeManager.InitCoreTypes ();
815 ShowTime (" Core Types done");
818 // The second pass of the compiler
821 ShowTime ("Resolving tree");
822 RootContext.ResolveTree ();
824 ShowTime ("Populate tree");
826 if (Report.Errors > 0){
827 error ("Compilation failed");
831 if (!RootContext.StdLib)
832 RootContext.BootCorlib_PopulateCoreTypes ();
833 RootContext.PopulateTypes ();
835 TypeManager.InitCodeHelpers ();
837 if (Report.Errors > 0){
838 error ("Compilation failed");
843 // The code generator
846 ShowTime ("Emitting code");
847 RootContext.EmitCode ();
851 if (Report.Errors > 0){
852 error ("Compilation failed");
857 ShowTime ("Closing types");
859 RootContext.CloseTypes ();
861 // PEFileKinds k = PEFileKinds.ConsoleApplication;
863 // if (target == Target.Library || target == Target.Module)
864 // k = PEFileKinds.Dll;
865 // else if (target == Target.Exe)
866 // k = PEFileKinds.ConsoleApplication;
867 // else if (target == Target.WinExe)
868 // k = PEFileKinds.WindowApplication;
870 // if (target == Target.Exe || target == Target.WinExe){
871 // MethodInfo ep = RootContext.EntryPoint;
874 // Report.Error (5001, "Program " + output_file +
875 // " does not have an entry point defined");
879 // CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
885 if (resources != null){
886 foreach (string file in resources)
887 CodeGen.AssemblyBuilder.AddResourceFile (file, file);
890 CodeGen.Save (output_file);
892 ShowTime ("Saved output");
894 if (want_debugging_support) {
895 CodeGen.SaveSymbols ();
897 ShowTime ("Saved symbols");
900 if (Report.Errors > 0){
901 error ("Compilation failed");
903 } else if (Report.ProbeCode != 0){
904 error ("Failed to report code " + Report.ProbeCode);
905 Environment.Exit (124);