-//\r
-// driver.cs: The compiler command line driver.\r
-//\r
-// Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)\r
-// Based on mcs by : Miguel de Icaza (miguel@gnu.org)\r
-//\r
-// Licensed under the terms of the GNU GPL\r
-//\r
-// (C) 2002 Rafael Teixeira\r
-//\r
-\r
-namespace Mono.Languages\r
-{\r
- using System;\r
- using System.Reflection;\r
- using System.Reflection.Emit;\r
- using System.Collections;\r
- using System.IO;\r
- using System.Globalization;\r
- using Mono.CSharp;\r
- using Mono.GetOptions;\r
-\r
- enum Target \r
- {\r
- Library, Exe, Module, WinExe\r
- };\r
- \r
- enum OptionCompare\r
- {\r
- Binary, Text\r
- };\r
- \r
- /// <summary>\r
- /// The compiler driver.\r
- /// </summary>\r
- public class Driver : Options\r
- {\r
- // Temporary options\r
- //------------------------------------------------------------------\r
- [Option("[Mono] Only parses the source file (for debugging the tokenizer)", "parse")]\r
- public bool parse_only = false;\r
-\r
- [Option("[Mono] Only tokenizes source files")]\r
- public bool tokenize = false;\r
-\r
- [Option("[Mono] Shows stack trace at Error location")]\r
- public bool stacktrace { set { Report.Stacktrace = value; } }\r
-\r
- [Option("[Mono] Displays time stamps of various compiler events")]\r
- public bool timestamp\r
- {\r
- set\r
- {\r
- timestamps = true;\r
- last_time = DateTime.Now;\r
- debug_arglist.Add("timestamp");\r
- }\r
- }\r
-\r
- // Mono-specific options\r
- //------------------------------------------------------------------\r
- [Option("About the MonoBASIC compiler", "about")]\r
- public override WhatToDoNext DoAbout()\r
- {\r
- return base.DoAbout();\r
- }\r
-\r
- [Option("[Mono] Don\'t assume the standard library", "nostdlib")]\r
- public bool nostdlib { set { RootContext.StdLib = !value; } }\r
-\r
- [Option("[Mono] Disables implicit references to assemblies", "noconfig")]\r
- public bool NoConfig { set { load_default_config = !value; } }\r
-\r
- [Option("[Mono] Allows unsafe code", "unsafe")]\r
- public bool AllowUnsafeCode { set { RootContext.Unsafe = value; } }\r
-\r
- [Option("[Mono] Set default context to checked", "checked")]\r
- public bool Checked { set { RootContext.Checked = value; } }\r
-\r
- [Option("[Mono] Debugger arguments", "debug-args")]\r
- public WhatToDoNext SetDebugArgs(string args)\r
- {\r
- char[] sep = { ',' };\r
- debug_arglist.AddRange (args.Split (sep));\r
- return WhatToDoNext.GoAhead;\r
- }\r
-\r
- [Option("[Mono] Ignores warning number PARAM", "ignorewarn")]\r
- public WhatToDoNext SetIgnoreWarning(int warn)\r
- {\r
- Report.SetIgnoreWarning(warn);\r
- return WhatToDoNext.GoAhead;\r
- } \r
-\r
- [Option("[Mono] Sets warning level (the highest is 4, the default)", "wlevel")]\r
- public int wlevel { set { RootContext.WarningLevel = value; } }\r
-\r
- [Option("[Mono] Makes errors fatal", "fatal")]\r
- public bool Fatal { set { Report.Fatal = value; } }\r
-\r
- [Option("[Mono] Adds path to the assembly link path")]\r
- public string[] linkpaths = null;\r
-\r
- // Output file options\r
- //------------------------------------------------------------------\r
- [Option("Specifies the output file name", 'o', "out")]\r
- public string output_file = null;\r
-\r
- [Option("Specifies the target type for the output file (exe [default], winexe, library, module)", "target")]\r
- public WhatToDoNext SetTarget(string type)\r
- {\r
- switch (type.ToLower())\r
- {\r
- case "library":\r
- target = Target.Library;\r
- target_ext = ".dll";\r
- break;\r
- \r
- case "exe":\r
- target = Target.Exe;\r
- break;\r
- \r
- case "winexe":\r
- target = Target.WinExe;\r
- break;\r
- \r
- case "module":\r
- target = Target.Module;\r
- target_ext = ".dll";\r
- break;\r
- }\r
- return WhatToDoNext.GoAhead;\r
- }\r
-\r
- // input file options\r
- //------------------------------------------------------------------\r
- [Option("[NOT IMPLEMENTED YET]Reference metadata from specified module", "addmodule")]\r
- public string[] addedModules = null;\r
-\r
- [Option("[NOT IMPLEMENTED YET]Include all files in the current directory and subdirectories according to the wildcard", "recurse")]\r
- public WhatToDoNext recurse(string wildcard)\r
- {\r
- //AddFiles (DirName, true); // TODO wrong semantics\r
- return WhatToDoNext.GoAhead;\r
- }\r
-\r
- [Option(-1, "References metadata from the specified assembly", 'r', "reference")]\r
- public string reference { set { references.Add(value); } }\r
-\r
- // resource options\r
- //------------------------------------------------------------------\r
- public ArrayList EmbeddedResources = new ArrayList();\r
- \r
- // TODO : accept a multi-letter short form: 'res'\r
- [Option(-1, "Adds the specified file as an embedded assembly resource", "resource")]\r
- public string resource { set { EmbeddedResources.Add(value); } }\r
-\r
- public ArrayList LinkedResources = new ArrayList();\r
- \r
- // TODO : accept a multi-letter short form: 'linkres'\r
- [Option(-1, "[NOT IMPLEMENTED YET]Adds the specified file as an embedded assembly resource", "linkresource")]\r
- public string linkresource { set { LinkedResources.Add(value); } }\r
-\r
- public ArrayList Win32Resources = new ArrayList();\r
- \r
- [Option(-1, "[NOT IMPLEMENTED YET]Specifies a Win32 resource file (.res)", "win32resource")]\r
- public string win32resource { set { Win32Resources.Add(value); } }\r
-\r
- public ArrayList Win32Icons = new ArrayList();\r
- \r
- // TODO : accept a multi-letter short form: 'res'\r
- [Option(-1, "[NOT IMPLEMENTED YET]Specifies a Win32 icon file (.ico) for the default Win32 resources", "win32icon")]\r
- public string win32icon { set { Win32Icons.Add(value); } }\r
-\r
-\r
- // code generation options\r
- //------------------------------------------------------------------\r
- [Option("[NOT IMPLEMENTED YET]Enable optimizations")]\r
- public bool optimize = false;\r
-\r
- [Option("[NOT IMPLEMENTED YET]Remove integer checks. Default off.")]\r
- public bool removeintchecks = false;\r
-\r
- // TODO: handle VB.NET [+|-] boolean syntax\r
- [Option("Emit debugging information", "debug")]\r
- public bool want_debugging_support = false;\r
-\r
- [Option("Emit full debugging information (default)", "debug:full")]\r
- public bool fullDebugging = false;\r
-\r
- [Option("[IGNORED]Emit PDB file only", "debug:pdbonly")]\r
- public bool pdbOnly = false;\r
-\r
- // errors and warnings options\r
- //------------------------------------------------------------------\r
- [Option("Treat warnings as errors", "warnaserror")]\r
- public bool WarningsAreErrors { set { Report.WarningsAreErrors = value; } }\r
-\r
- [Option("Disable warnings")]\r
- public bool nowarn { set { if (value) RootContext.WarningLevel = 0; } }\r
-\r
-\r
- // language options\r
- //------------------------------------------------------------------\r
- public Hashtable Defines = new Hashtable();\r
- \r
- // TODO: Symbol-List parsing\r
- [Option(-1, "[NOT IMPLEMENTED YET]Declares global conditional compilation symbol(s). symbol list:name=value,...", 'd', "define")]\r
- public string define { \r
- set {\r
- foreach(string item in value.Split(',')) { \r
- string[] dados = item.Split('=');\r
- if (dados.Length > 1)\r
- Defines.Add(dados[0], dados[1]); \r
- else\r
- Defines.Add(dados[0], string.Empty);\r
- }\r
- } \r
- }\r
- \r
- private string[] importsList = null;\r
- \r
- [Option("[NOT IMPLEMENTED YET]Declare global Imports for namespaces in referenced metadata files. import list:namespace,...", "imports")]\r
- public WhatToDoNext imports(string importslist)\r
- {\r
- importsList = importslist.Split(';');\r
- return WhatToDoNext.GoAhead;\r
- }\r
-\r
- // TODO: handle VB.NET [+|-] boolean syntax\r
- [Option("[NOT IMPLEMENTED YET]Require explicit declaration of variables")]\r
- public bool optionexplicit { set { Mono.MonoBASIC.Parser.InitialOptionExplicit = value; } }\r
-\r
- // TODO: handle VB.NET [+|-] boolean syntax\r
- [Option("[NOT IMPLEMENTED YET]Enforce strict language semantics")]\r
- public bool optionstrict { set { Mono.MonoBASIC.Parser.InitialOptionStrict = value; } }\r
- \r
- [Option("[NOT IMPLEMENTED YET]Specifies binary-style string comparisons. This is the default", "optioncompare:binary")]\r
- public bool optioncomparebinary { set { Mono.MonoBASIC.Parser.InitialOptionCompareBinary = true; } }\r
-\r
- [Option("[NOT IMPLEMENTED YET]Specifies text-style string comparisons.", "optioncompare:text")]\r
- public bool optioncomparetext { set { Mono.MonoBASIC.Parser.InitialOptionCompareBinary = false; } }\r
-\r
- [Option("Specifies de root namespace for all type declarations")]\r
- public string rootnamespace { set { RootContext.RootNamespace = value; } }\r
- \r
- // Miscellaneous options \r
- //------------------------------------------------------------------\r
- \r
- [Option("[NOT IMPLEMENTED YET]Do not display compiler copyright banner")]\r
- public bool nologo = false;\r
- \r
- [Option("[NOT IMPLEMENTED YET]Quiet output mode")]\r
- public bool quiet = false;\r
- \r
- // TODO: semantics are different and should be adjusted\r
- [Option("Display verbose messages", 'v')] \r
- public bool verbose { set { GenericParser.yacc_verbose_flag = value; } }\r
-\r
- // Advanced options \r
- //------------------------------------------------------------------\r
- // TODO: force option to accept number in hex format\r
- [Option("[NOT IMPLEMENTED YET]The base address for a library or module (hex)")]\r
- public int baseaddress;\r
- \r
- [Option("[NOT IMPLEMENTED YET]Create bug report file")]\r
- public string bugreport;\r
- \r
- // TODO: handle VB.NET [+|-] boolean syntax\r
- [Option("[NOT IMPLEMENTED YET]Delay-sign the assembly using only the public portion of the strong name key")]\r
- public bool delaysign;\r
- \r
- [Option("[NOT IMPLEMENTED YET]Specifies a strong name key container")]\r
- public string keycontainer;\r
- \r
- [Option("[NOT IMPLEMENTED YET]Specifies a strong name key file")]\r
- public string keyfile;\r
-\r
- public string[] libpath = null;\r
- \r
- [Option("[NOT IMPLEMENTED YET]List of directories to search for metada references (semi-colon delimited)", "libpath")]\r
- public WhatToDoNext setlibpath(string pathlist)\r
- {\r
- libpath = pathlist.Split(';');\r
- return WhatToDoNext.GoAhead;\r
- }\r
-\r
- [Option(@"Specifies the Class or Module that contains Sub Main.\r
- It can also be a Class that inherits from System.Windows.Forms.Form.",\r
- 'm', "main")]\r
- public string main { set { RootContext.MainClass = value; } }\r
-\r
- // TODO: handle VB.NET [+|-] boolean syntax\r
- [Option("[NOT IMPLEMENTED YET]Emit compiler output in UTF8 character encoding")]\r
- public bool utf8output;\r
-\r
- // TODO : response file support\r
- \r
- ArrayList defines = new ArrayList();\r
- ArrayList references = new ArrayList();\r
- ArrayList soft_references = new ArrayList();\r
- string first_source = null;\r
- Target target = Target.Exe;\r
- string target_ext = ".exe";\r
- ArrayList debug_arglist = new ArrayList ();\r
- bool timestamps = false;\r
- Hashtable source_files = new Hashtable ();\r
- bool load_default_config = true;\r
-\r
- //\r
- // Last time we took the time\r
- //\r
- DateTime last_time;\r
- void ShowTime (string msg)\r
- {\r
- DateTime now = DateTime.Now;\r
- TimeSpan span = now - last_time;\r
- last_time = now;\r
-\r
- Console.WriteLine (\r
- "[{0:00}:{1:000}] {2}",\r
- (int) span.TotalSeconds, span.Milliseconds, msg);\r
- }\r
- \r
- public static int Main (string[] args)\r
- {\r
- Driver Exec = new Driver();\r
-\r
- return Exec.MainDriver(args);\r
- }\r
-\r
- public int LoadAssembly (string assembly, bool soft)\r
- {\r
- Assembly a;\r
- string total_log = "";\r
-\r
- try {\r
- char[] path_chars = { '/', '\\' };\r
-\r
- if (assembly.IndexOfAny (path_chars) != -1)\r
- a = Assembly.LoadFrom(assembly);\r
- else\r
- a = Assembly.Load(assembly);\r
- TypeManager.AddAssembly (a);\r
- return 0;\r
- } catch (FileNotFoundException){\r
- foreach (string dir in linkpaths){\r
- string full_path = dir + "/" + assembly + ".dll";\r
-\r
- try {\r
- a = Assembly.LoadFrom (full_path);\r
- TypeManager.AddAssembly (a);\r
- return 0;\r
- } catch (FileNotFoundException ff) {\r
- total_log += ff.FusionLog;\r
- continue;\r
- }\r
- }\r
- if (soft)\r
- return 0;\r
- } catch (BadImageFormatException f) {\r
- Error ("// Bad file format while loading assembly");\r
- Error ("Log: " + f.FusionLog);\r
- return 1;\r
- } catch (FileLoadException f){\r
- Error ("File Load Exception: " + assembly);\r
- Error ("Log: " + f.FusionLog);\r
- return 1;\r
- } catch (ArgumentNullException){\r
- Error ("// Argument Null exception ");\r
- return 1;\r
- }\r
- \r
- Report.Error (6, "Can not find assembly `" + assembly + "'" );\r
- Console.WriteLine ("Log: \n" + total_log);\r
-\r
- return 0;\r
- }\r
-\r
- void Error(string message)\r
- {\r
- Console.WriteLine(message);\r
- }\r
-\r
- /// <summary>\r
- /// Loads all assemblies referenced on the command line\r
- /// </summary>\r
- public int LoadReferences ()\r
- {\r
- int errors = 0;\r
-\r
- foreach (string r in references)\r
- errors += LoadAssembly (r, false);\r
-\r
- foreach (string r in soft_references)\r
- errors += LoadAssembly (r, true);\r
- \r
- return errors;\r
- }\r
-\r
- void SetupDefaultDefines ()\r
- {\r
- defines = new ArrayList ();\r
- defines.Add ("__MonoBASIC__");\r
- }\r
-\r
-\r
- //\r
- // Returns the directory where the system assemblies are installed\r
- //\r
- string GetSystemDir ()\r
- {\r
- Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();\r
-\r
- foreach (Assembly a in assemblies){\r
- string codebase = a.CodeBase;\r
- if (codebase.EndsWith ("corlib.dll")){\r
- return codebase.Substring (0, codebase.LastIndexOf ("/"));\r
- }\r
- }\r
-\r
- Report.Error (-15, "Can not compute my system path");\r
- return "";\r
- }\r
-\r
- //\r
- // Given a path specification, splits the path from the file/pattern\r
- //\r
- void SplitPathAndPattern (string spec, out string path, out string pattern)\r
- {\r
- int p = spec.LastIndexOf ("/");\r
- if (p != -1){\r
- //\r
- // Windows does not like /file.cs, switch that to:\r
- // "\", "file.cs"\r
- //\r
- if (p == 0){\r
- path = "\\";\r
- pattern = spec.Substring (1);\r
- } else {\r
- path = spec.Substring (0, p);\r
- pattern = spec.Substring (p + 1);\r
- }\r
- return;\r
- }\r
-\r
- p = spec.LastIndexOf ("\\");\r
- if (p != -1){\r
- path = spec.Substring (0, p);\r
- pattern = spec.Substring (p + 1);\r
- return;\r
- }\r
-\r
- path = ".";\r
- pattern = spec;\r
- }\r
-\r
- bool AddFiles (string spec, bool recurse)\r
- {\r
- string path, pattern;\r
-\r
- SplitPathAndPattern(spec, out path, out pattern);\r
- if (pattern.IndexOf("*") == -1)\r
- {\r
- AddFile(spec);\r
- return true;\r
- }\r
-\r
- string [] files = null;\r
- try {\r
- files = Directory.GetFiles(path, pattern);\r
- } catch (System.IO.DirectoryNotFoundException) {\r
- Report.Error (2001, "Source file `" + spec + "' could not be found");\r
- return false;\r
- } catch (System.IO.IOException){\r
- Report.Error (2001, "Source file `" + spec + "' could not be found");\r
- return false;\r
- }\r
- foreach (string f in files)\r
- AddFile (f);\r
-\r
- if (!recurse)\r
- return true;\r
- \r
- string [] dirs = null;\r
-\r
- try {\r
- dirs = Directory.GetDirectories(path);\r
- } catch {\r
- }\r
- \r
- foreach (string d in dirs) {\r
- \r
- // Don't include path in this string, as each\r
- // directory entry already does\r
- AddFiles (d + "/" + pattern, true);\r
- }\r
-\r
- return true;\r
- }\r
-\r
- void DefineDefaultConfig ()\r
- {\r
- //\r
- // For now the "default config" is harcoded into the compiler\r
- // we can move this outside later\r
- //\r
- string [] default_config = \r
- {\r
- "System",\r
- "System.Data",\r
- "System.Xml",\r
- "Microsoft.VisualBasic" , \r
-#if EXTRA_DEFAULT_REFS\r
- //\r
- // Is it worth pre-loading all this stuff?\r
- //\r
- "Accessibility",\r
- "System.Configuration.Install",\r
- "System.Design",\r
- "System.DirectoryServices",\r
- "System.Drawing.Design",\r
- "System.Drawing",\r
- "System.EnterpriseServices",\r
- "System.Management",\r
- "System.Messaging",\r
- "System.Runtime.Remoting",\r
- "System.Runtime.Serialization.Formatters.Soap",\r
- "System.Security",\r
- "System.ServiceProcess",\r
- "System.Web",\r
- "System.Web.RegularExpressions",\r
- "System.Web.Services" ,\r
- "System.Windows.Forms"\r
-#endif\r
- };\r
- \r
- foreach (string def in default_config)\r
- soft_references.Add(def);\r
- }\r
-\r
- [ArgumentProcessor]\r
- public void AddFile(string fileName)\r
- {\r
- string f = fileName;\r
- if (first_source == null)\r
- first_source = f;\r
-\r
- if (source_files.Contains(f))\r
- Report.Error(1516, "Source file '" + f + "' specified multiple times");\r
- else\r
- source_files.Add(f, f);\r
- }\r
-\r
- void ProcessSourceFile(string filename)\r
- {\r
- if (tokenize)\r
- GenericParser.Tokenize(filename);\r
- else\r
- GenericParser.Parse(filename);\r
- }\r
-\r
- string outputFile_Name = null;\r
-\r
- string outputFileName\r
- {\r
- get \r
- {\r
- if (outputFile_Name == null)\r
- {\r
- if (output_file == null)\r
- {\r
- int pos = first_source.LastIndexOf(".");\r
-\r
- if (pos > 0)\r
- output_file = first_source.Substring(0, pos);\r
- else\r
- output_file = first_source;\r
- }\r
- string bname = CodeGen.Basename(output_file);\r
- if (bname.IndexOf(".") == -1)\r
- output_file += target_ext;\r
- outputFile_Name = output_file;\r
- }\r
- return outputFile_Name;\r
- }\r
- }\r
-\r
- /// <summary>\r
- /// Parses the arguments, and calls the compilation process.\r
- /// </summary>\r
- int MainDriver(string [] args)\r
- {\r
- ProcessArgs(args);\r
- if (first_source == null)\r
- {\r
- DoHelp();\r
- return 2;\r
- }\r
-\r
- CompileAll();\r
-\r
- if (Report.Errors == 0) \r
- {\r
- Console.Write("Compilation succeeded");\r
- if (Report.Warnings > 0) \r
- {\r
- Console.Write(" - {0} warning(s)", Report.Warnings);\r
- } \r
- Console.WriteLine();\r
- return 0;\r
- } \r
- Console.WriteLine("Compilation failed: {0} Error(s), {1} warnings",\r
- Report.Errors, Report.Warnings);\r
- return 1;\r
- }\r
-\r
- public Driver()\r
- {\r
- SetupDefaultDefines(); \r
- }\r
-\r
- bool ParseAll() // Phase 1\r
- {\r
- if (first_source == null)\r
- {\r
- Report.Error(2008, "No files to compile were specified");\r
- return false;\r
- }\r
-\r
- foreach(string filename in source_files.Values)\r
- ProcessSourceFile(filename);\r
-\r
- if (tokenize || parse_only || (Report.Errors > 0))\r
- return false; \r
-\r
- return true; // everything went well go ahead\r
- }\r
-\r
- void InitializeDebuggingSupport()\r
- {\r
- string[] debug_args = new string [debug_arglist.Count];\r
- debug_arglist.CopyTo(debug_args);\r
- CodeGen.Init(outputFileName, outputFileName, want_debugging_support, debug_args);\r
- TypeManager.AddModule(CodeGen.ModuleBuilder);\r
- }\r
-\r
- public bool ResolveAllTypes() // Phase 2\r
- {\r
- // Load Core Library for default compilation\r
- if (RootContext.StdLib)\r
- references.Insert(0, "mscorlib");\r
-\r
- if (load_default_config)\r
- DefineDefaultConfig();\r
-\r
- if (timestamps)\r
- ShowTime("Loading references");\r
-\r
- // Load assemblies required\r
- if (LoadReferences() > 0)\r
- {\r
- Error ("Could not load one or more assemblies");\r
- return false;\r
- }\r
-\r
- if (timestamps)\r
- ShowTime("References loaded");\r
-\r
- InitializeDebuggingSupport();\r
-\r
- //\r
- // Before emitting, we need to get the core\r
- // types emitted from the user defined types\r
- // or from the system ones.\r
- //\r
- if (timestamps)\r
- ShowTime ("Initializing Core Types");\r
-\r
- if (!RootContext.StdLib)\r
- RootContext.ResolveCore ();\r
- if (Report.Errors > 0)\r
- return false;\r
- \r
- TypeManager.InitCoreTypes();\r
- if (Report.Errors > 0)\r
- return false;\r
-\r
- if (timestamps)\r
- ShowTime (" Core Types done");\r
-\r
- if (timestamps)\r
- ShowTime ("Resolving tree");\r
-\r
- // The second pass of the compiler\r
- RootContext.ResolveTree ();\r
- if (Report.Errors > 0)\r
- return false;\r
- \r
- if (timestamps)\r
- ShowTime ("Populate tree");\r
-\r
- if (!RootContext.StdLib)\r
- RootContext.BootCorlib_PopulateCoreTypes();\r
- if (Report.Errors > 0)\r
- return false;\r
-\r
- RootContext.PopulateTypes();\r
- if (Report.Errors > 0)\r
- return false;\r
- \r
- TypeManager.InitCodeHelpers();\r
- if (Report.Errors > 0)\r
- return false;\r
-\r
- return true;\r
- }\r
- \r
- bool IsSWFApp()\r
- {\r
- bool hasSWF = false, isForm = false;\r
- \r
- foreach (string r in references) {\r
- if (r.IndexOf ("System.Windows.Forms") >= 0) {\r
- hasSWF = true;\r
- break; \r
- } \r
- } \r
- \r
- Type t = TypeManager.LookupType(RootContext.RootNamespace + "." + RootContext.MainClass);\r
- if (t != null) \r
- isForm = t.IsSubclassOf (TypeManager.LookupType("System.Windows.Forms.Form"));\r
- \r
- return (hasSWF && isForm);\r
- }\r
- \r
- void FixEntryPoint()\r
- {\r
- if (target == Target.Exe || target == Target.WinExe)\r
- {\r
- MethodInfo ep = RootContext.EntryPoint;\r
- \r
- if (ep == null)\r
- {\r
- // If we don't have a valid entry point yet\r
- // AND if System.Windows.Forms is included\r
- // among the dependencies, we have to build\r
- // a new entry point on-the-fly. Otherwise we\r
- // won't be able to compile SWF code out of the box.\r
-\r
- if (IsSWFApp()) \r
- { \r
- Type t = TypeManager.LookupType(RootContext.RootNamespace + "." + RootContext.MainClass);\r
- if (t != null) \r
- {\r
- TypeBuilder tb = t as TypeBuilder;\r
- MethodBuilder mb = tb.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, \r
- typeof(void), new Type[0]);\r
-\r
- Type SWFA = TypeManager.LookupType("System.Windows.Forms.Application");\r
- Type SWFF = TypeManager.LookupType("System.Windows.Forms.Form");\r
- Type[] args = new Type[1];\r
- args[0] = SWFF;\r
- MethodInfo mi = SWFA.GetMethod("Run", args);\r
- ILGenerator ig = mb.GetILGenerator();\r
- ConstructorInfo ci = TypeManager.GetConstructor (TypeManager.LookupType(t.FullName), new Type[0]);\r
- \r
- ig.Emit (OpCodes.Newobj, ci);\r
- ig.Emit (OpCodes.Call, mi);\r
- ig.Emit (OpCodes.Ret);\r
-\r
- RootContext.EntryPoint = mb as MethodInfo;\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- bool GenerateAssembly()\r
- {\r
- //\r
- // The code generator\r
- //\r
- if (timestamps)\r
- ShowTime ("Emitting code");\r
- \r
- \r
-\r
- RootContext.EmitCode();\r
- FixEntryPoint();\r
- if (Report.Errors > 0)\r
- return false;\r
-\r
- if (timestamps)\r
- ShowTime (" done");\r
-\r
-\r
- if (timestamps)\r
- ShowTime ("Closing types");\r
-\r
- RootContext.CloseTypes ();\r
- if (Report.Errors > 0)\r
- return false;\r
-\r
- if (timestamps)\r
- ShowTime (" done");\r
-\r
- PEFileKinds k = PEFileKinds.ConsoleApplication;\r
- \r
- if (target == Target.Library || target == Target.Module)\r
- k = PEFileKinds.Dll;\r
- else if (target == Target.Exe)\r
- k = PEFileKinds.ConsoleApplication;\r
- else if (target == Target.WinExe)\r
- k = PEFileKinds.WindowApplication;\r
- \r
- if (target == Target.Exe || target == Target.WinExe)\r
- {\r
- MethodInfo ep = RootContext.EntryPoint;\r
- \r
- if (ep == null)\r
- {\r
- Report.Error (5001, "Program " + outputFileName +\r
- " does not have an entry point defined");\r
- return false;\r
- }\r
- \r
- CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);\r
- }\r
-\r
- // Add the resources\r
- if (EmbeddedResources != null)\r
- foreach (string file in EmbeddedResources)\r
- CodeGen.AssemblyBuilder.AddResourceFile (file, file);\r
- \r
- CodeGen.Save(outputFileName);\r
-\r
- if (timestamps)\r
- ShowTime ("Saved output");\r
-\r
- \r
- if (want_debugging_support) \r
- {\r
- CodeGen.SaveSymbols ();\r
- if (timestamps)\r
- ShowTime ("Saved symbols");\r
- }\r
-\r
- return true;\r
- }\r
-\r
- public void CompileAll()\r
- {\r
-/* \r
- VB.NET expects the default namespace to be "" (empty string) \r
- \r
- if (RootContext.RootNamespace == "")\r
- {\r
- RootContext.RootNamespace = System.IO.Path.GetFileNameWithoutExtension(outputFileName);\r
- }\r
-*/\r
- if (!ParseAll()) // Phase 1\r
- return;\r
-\r
- if (!ResolveAllTypes()) // Phase 2\r
- return;\r
-\r
- if (!GenerateAssembly()) // Phase 3 \r
- return;\r
-\r
- if (Report.ExpectedError != 0)\r
- Error("Failed to report expected Error " + Report.ExpectedError);\r
- }\r
-\r
- }\r
-}\r
+//
+// driver.cs: The compiler command line driver.
+//
+// Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)
+// Based on mcs by : Miguel de Icaza (miguel@gnu.org)
+//
+// Licensed under the terms of the GNU GPL
+//
+// (C) 2002, 2003, 2004 Rafael Teixeira
+//
+
+namespace Mono.Languages {
+
+ using System;
+ using System.Collections;
+ using System.IO;
+ using System.Text;
+ using System.Globalization;
+ using System.Reflection;
+ using System.Reflection.Emit;
+
+ using Mono.GetOptions;
+ using Mono.GetOptions.Useful;
+
+ using Mono.MonoBASIC;
+
+ public class Driver {
+ CompilerOptions options;
+
+ private void InitializeRootContextAndOthersFromOptions()
+ {
+ Report.Stacktrace = options.Stacktrace;
+ Report.WarningsAreErrors = options.WarningsAreErrors;
+ // TODO: change Report to receive the whole array
+ for(int i = 0; i < options.WarningsToIgnore.Length; i++)
+ Report.SetIgnoreWarning(options.WarningsToIgnore[i]);
+ Report.Fatal = options.MakeErrorsFatal;
+
+ RootContext.WarningLevel = options.WarningLevel;
+ RootContext.Checked = options.CheckedContext;
+ RootContext.MainClass = options.MainClassName;
+ RootContext.StdLib = !options.NoStandardLibraries;
+ RootContext.Unsafe = options.AllowUnsafeCode;
+ if (options.RootNamespace != null)
+ RootContext.RootNamespace = options.RootNamespace;
+
+ // TODO: semantics are different and should be adjusted
+ GenericParser.yacc_verbose_flag = options.Verbose ? 1 : 0;
+
+ Mono.MonoBASIC.Parser.InitialOptionExplicit = options.OptionExplicit;
+ Mono.MonoBASIC.Parser.InitialOptionStrict = options.OptionStrict;
+ Mono.MonoBASIC.Parser.InitialOptionCompareBinary = options.OptionCompareBinary;
+ Mono.MonoBASIC.Parser.ImportsList = options.Imports;
+ }
+
+ bool ParseAllSourceFiles()
+ {
+ options.StartTime("Parsing Source Files");
+ foreach(FileToCompile file in options.SourceFilesToCompile)
+ GenericParser.Parse(file.Filename, file.Encoding);
+ options.ShowTime(" Done");
+ return (Report.Errors == 0);
+ }
+
+ private bool InitializeDebuggingSupport()
+ {
+ string[] debug_args = new string [options.DebugListOfArguments.Count];
+ options.DebugListOfArguments.CopyTo(debug_args);
+ CodeGen.Init(options.OutputFileName, options.OutputFileName, options.WantDebuggingSupport, debug_args);
+ TypeManager.AddModule(CodeGen.ModuleBuilder);
+ return true;
+ }
+
+ private bool LoadReferencedAssemblies()
+ {
+ return
+ options.LoadReferencedAssemblies(
+ new Mono.GetOptions.Useful.AssemblyAdder(TypeManager.AddAssembly));
+ }
+
+ private bool AdjustCodegenWhenTargetIsNetModule()
+ {
+ options.AdjustCodegenWhenTargetIsNetModule(CodeGen.AssemblyBuilder);
+ return true;
+ }
+
+ private bool LoadAddedNetModules()
+ {
+ return
+ options.LoadAddedNetModules(
+ CodeGen.AssemblyBuilder,
+ new Mono.GetOptions.Useful.ModuleAdder(TypeManager.AddModule));
+ }
+
+ private bool InitializeCoreTypes()
+ {
+ //
+ // Before emitting, we need to get the core
+ // types emitted from the user defined types
+ // or from the system ones.
+ //
+ options.StartTime("Initializing Core Types");
+
+ if (!RootContext.StdLib)
+ RootContext.ResolveCore ();
+ if (Report.Errors > 0)
+ return false;
+
+ TypeManager.InitCoreTypes();
+
+ options.ShowTime("Core Types Done");
+ return Report.Errors == 0;
+ }
+
+ private bool ResolveTree()
+ {
+ options.StartTime("Resolving tree");
+ RootContext.ResolveTree (); // The second pass of the compiler
+ options.ShowTime("Tree resolved");
+ return Report.Errors == 0;
+ }
+
+ private bool PopulateCoreTypes()
+ {
+ if (!RootContext.StdLib) {
+ options.StartTime("Populate core types");
+ RootContext.BootCorlib_PopulateCoreTypes();
+ options.ShowTime(" Done");
+ }
+ return Report.Errors == 0;
+ }
+
+ private bool PopulateTypes()
+ {
+ options.StartTime("Populate types");
+ RootContext.PopulateTypes();
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+
+ private bool InitCodeHelpers()
+ {
+ options.StartTime("Initialize code helpers");
+ TypeManager.InitCodeHelpers();
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+
+ void CookUpEntryPointForWinFormsApplication(Type t)
+ {
+ Type SystemWindowsFormsFormType = TypeManager.LookupType ("System.Windows.Forms.Form");
+ if (SystemWindowsFormsFormType == null || !t.IsSubclassOf (SystemWindowsFormsFormType))
+ return;
+
+ TypeBuilder tb = t as TypeBuilder;
+ MethodBuilder mb = tb.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard,
+ typeof(void), new Type[0]);
+
+ Type SystemWindowsFormsApplicationType = TypeManager.LookupType ("System.Windows.Forms.Application");
+ MethodInfo mi = SystemWindowsFormsApplicationType.GetMethod ("Run", new Type[] { SystemWindowsFormsFormType } );
+ ILGenerator ig = mb.GetILGenerator();
+ ConstructorInfo ci = TypeManager.GetConstructor (TypeManager.LookupType(t.FullName), new Type[0]);
+
+ ig.Emit (OpCodes.Newobj, ci);
+ ig.Emit (OpCodes.Call, mi);
+ ig.Emit (OpCodes.Ret);
+
+ RootContext.EntryPoint = mb as MethodInfo;
+ }
+
+ void FixEntryPoint()
+ {
+ if (options.TargetFileType == TargetType.Exe || options.TargetFileType == TargetType.WinExe) {
+ if (RootContext.EntryPoint == null && RootContext.MainClass != null) {
+ // If we don't have a valid entry point yet AND if System.Windows.Forms is included
+ // among the dependencies, we have to build a new entry point on-the-fly for the specified
+ // main class.
+ // Otherwise we won't be able to compile SWF code out of the box.
+ Type t = TypeManager.LookupType(RootContext.MainClass);
+ if (t == null)
+ Report.Error(-1, string.Format("Specified main class {0} doesn't exist", RootContext.MainClass));
+ else
+ CookUpEntryPointForWinFormsApplication (t);
+ }
+ }
+ }
+
+ private bool EmitCode()
+ {
+ options.StartTime("Emitting code");
+ RootContext.EmitCode();
+ FixEntryPoint();
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+
+ private bool CloseTypes()
+ {
+ options.StartTime("Closing types");
+ RootContext.CloseTypes ();
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+
+ private bool SetEntryPoint()
+ {
+ if (options.TargetFileType == TargetType.Exe || options.TargetFileType == TargetType.WinExe) {
+ options.StartTime("Setting entry point");
+ MethodInfo ep = RootContext.EntryPoint;
+
+ if (ep == null) {
+ Report.Error (30737, "Program " + options.OutputFileName + " does not have an entry point defined");
+ return false;
+ }
+
+ CodeGen.AssemblyBuilder.SetEntryPoint (ep,
+ (options.TargetFileType == TargetType.Exe)?PEFileKinds.ConsoleApplication:PEFileKinds.WindowApplication);
+ options.ShowTime(" Done");
+ }
+ return Report.Errors == 0;
+ }
+
+/*
+ private bool EmbedResources()
+ {
+ options.StartTime("Embedding resources");
+ options.EmbedResources(CodeGen.AssemblyBuilder);
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+*/
+
+ private bool SaveOutput()
+ {
+ options.StartTime("Saving Output");
+ CodeGen.Save(options.OutputFileName);
+ options.ShowTime(" Done");
+ return Report.Errors == 0;
+ }
+
+
+ private bool SaveDebugSymbols()
+ {
+ if (options.WantDebuggingSupport) {
+ options.StartTime("Saving Debug Symbols");
+ CodeGen.SaveSymbols ();
+ options.ShowTime (" Done");
+ }
+ return true;
+ }
+
+ delegate bool CompilerStep();
+
+ private CompilerStep[] Steps {
+ get {
+ return new CompilerStep[] {
+ new CompilerStep(ParseAllSourceFiles),
+ new CompilerStep(InitializeDebuggingSupport),
+ new CompilerStep(LoadReferencedAssemblies),
+ new CompilerStep(AdjustCodegenWhenTargetIsNetModule),
+ new CompilerStep(LoadAddedNetModules),
+ new CompilerStep(InitializeCoreTypes),
+ new CompilerStep(ResolveTree),
+ new CompilerStep(PopulateCoreTypes),
+ new CompilerStep(PopulateTypes),
+ new CompilerStep(InitCodeHelpers),
+ new CompilerStep(EmitCode),
+ new CompilerStep(CloseTypes),
+ new CompilerStep(SetEntryPoint),
+ new CompilerStep(SaveOutput),
+ new CompilerStep(SaveDebugSymbols) } ;
+ }
+ }
+
+ /// <summary>
+ /// Parses the arguments, and calls the compilation process.
+ /// </summary>
+ int Execute(string [] args)
+ {
+ options = new CompilerOptions(args, new ErrorReporter(Report.Error));
+ if (options.NothingToCompile)
+ return 2;
+ try {
+ InitializeRootContextAndOthersFromOptions();
+
+ foreach(CompilerStep step in Steps)
+ if (!step())
+ break;
+
+ } catch (Exception ex) {
+ Report.Error(0, "Exception: " + ex.ToString());
+ }
+ return Report.ProcessResults(options.BeQuiet);
+ }
+
+ public static int Main (string[] args)
+ {
+ Driver driver = new Driver();
+
+ return driver.Execute(args);
+ }
+
+ }
+}