Start
[mono.git] / mcs / mbas / driver.cs
index e9acff0ad5f9a1ed7aac68177f373942bd8d903e..dd4c27c76ff859421ebed9296a166406d1635b4b 100644 (file)
@@ -1,4 +1,4 @@
-//
+//
 // driver.cs: The compiler command line driver.
 //
 // Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)
@@ -17,7 +17,7 @@ namespace Mono.Languages
        using System.Collections;
        using System.IO;
        using System.Globalization;
-       using Mono.CSharp;
+       using Mono.MonoBASIC;
        using Mono.GetOptions;
 
        enum Target 
@@ -25,110 +25,88 @@ namespace Mono.Languages
                Library, Exe, Module, WinExe
        };
        
+       enum OptionCompare
+       {
+               Binary, Text
+       };
+       
        /// <summary>
        ///    The compiler driver.
        /// </summary>
        public class Driver : Options
        {
-               
-               [Option("Verbose parsing (for debugging the parser)",'v')] 
-               public bool verbose     { set { GenericParser.yacc_verbose_flag = value; } }
+               // Temporary options
+               //------------------------------------------------------------------
+               [Option("[Mono] Only parses the source file (for debugging the tokenizer)", "parse")]
+               public bool parse_only = false;
 
-               [Option("Specifies PARAM as main (starting) class", 'm')]
-               public string main { set { RootContext.MainClass = value; } }
+               [Option("[Mono] Only tokenizes source files")]
+               public bool tokenize = false;
+
+               [Option("[Mono] Shows stack trace at Error location")]
+               public bool stacktrace { set { Report.Stacktrace = value; } }
 
+               [Option("[Mono] Displays time stamps of various compiler events")]
+               public bool timestamp
+               {
+                       set
+                       {
+                               timestamps = true;
+                               last_time = DateTime.Now;
+                               debug_arglist.Add("timestamp");
+                       }
+               }
+
+               // Mono-specific options
+               //------------------------------------------------------------------
                [Option("About the MonoBASIC compiler", "about")]
                public override WhatToDoNext DoAbout()
                {
                        return base.DoAbout();
                }
 
-               [Option("Adds PARAM to the assembly link path", 'L')]
-               public static string[] LinkPaths = null;
-
-               [Option("Defines the symbol PARAM", "define")]
-               public static string[] Defines = null;
-
-               [Option("Only parses the source file (for debugging the tokenizer)", "parse")]
-               public static bool parse_only = false;
-
-               private static bool load_default_config = true;
+               [Option("[Mono] Don\'t assume the standard library", "nostdlib")]
+               public bool NoStandardLibraries { set { RootContext.StdLib = !value; } }
 
-               [Option("Disables implicit references to assemblies", "noconfig")]
+               [Option("[Mono] Disables implicit references to assemblies", "noconfig")]
                public bool NoConfig { set { load_default_config = !value; } }
 
-               [Option("Allows unsafe code", "unsafe")]
+               [Option("[Mono] Allows unsafe code", "unsafe")]
                public bool AllowUnsafeCode { set { RootContext.Unsafe = value; } }
 
-               private string output_file;
+               [Option("[Mono] Set default context to checked", "checked")]
+               public bool Checked { set { RootContext.Checked = value; } }
 
-               [Option("Specifies output file", 'o', "output")]
-               public WhatToDoNext SetOutputFile(string FileName)
+               [Option("[Mono] Debugger {arguments}", "debug-args")]
+               public WhatToDoNext SetDebugArgs(string args)
                {
-                       output_file = FileName;
-                       string bname = CodeGen.Basename (output_file);
-                       if (bname.IndexOf (".") == -1)
-                               output_file += ".exe";
+                       char[] sep = { ',' };
+                       debug_arglist.AddRange (args.Split (sep));
                        return WhatToDoNext.GoAhead;
                }
 
-
-               [Option("Only tokenizes source files", "tokenize")]
-               public static bool tokenize = true;
-
-               [Option("Set default context to checked", "checked")]
-               public bool Checked { set { RootContext.Checked = value; } }
-
-               [Option("Shows stack trace at error location", "Stacktrace")]
-               public bool Stacktrace { set { Report.Stacktrace = value; } }
-
-               private static ArrayList references;
-
-               [Option("References an assembly", 'r')]
-               public static string reference { set { references.Add(value); } }
-
-               [Option("Adds PARAM as a resource", "resource")]
-               public static string[] resources;
-
-               [Option("Set default context to checked", "nostdlib")]
-               public bool nostdlib { set { RootContext.StdLib = !value; } }
-
-               [Option("Makes errors fatal", "fatal")]
-               public bool Fatal { set { Report.Fatal = value; } }
-
-               [Option("Treat warnings as errors", "werror")]
-               public bool WarningsAreErrors { set { Report.WarningsAreErrors = value; } }
-
-               [Option("Ignores warning number PARAM", "nowarn")]
+               [Option("[Mono] Ignores warning number {XXXX}", "ignorewarn")]
                public WhatToDoNext SetIgnoreWarning(int warn)
                {
                        Report.SetIgnoreWarning(warn);
                        return WhatToDoNext.GoAhead;
-               }
+               }       
 
-               [Option("Recursively compiles the files in PARAM ([dir]/file)", "recurse")]
-               public WhatToDoNext recurse(string DirName)
-               {
-                       AddFiles (DirName, true);
-                       return WhatToDoNext.GoAhead;
-               }
-       
+               [Option("[Mono] Sets warning {level} (the highest is 4, the default)", "wlevel")]
+               public int WarningLevel { set { RootContext.WarningLevel = value; } }
 
-               [Option("Write symbolic debugging information to FILE-debug.s", 'g', "debug")]
-               public static bool want_debugging_support = false;
+               [Option("[Mono] Makes errors fatal", "fatal")]
+               public bool Fatal { set { Report.Fatal = value; } }
 
-               [Option("Debugger arguments", "debug-args")]
-               public WhatToDoNext SetDebugArgs(string args)
-               {
-                       char[] sep = { ',' };
-                       debug_arglist.AddRange (args.Split (sep));
-                       return WhatToDoNext.GoAhead;
-               }
+               // Output file options
+               //------------------------------------------------------------------
+               [Option("Specifies the output {file} name", 'o', "out")]
+               public string OutputFileName = null;
 
-               [Option("Specifies the target (PARAM is one of: exe, winexe, library, module)", "target")]
+               [Option("Specifies the target {type} for the output file (exe [default], winexe, library, module)", "target")]
                public WhatToDoNext SetTarget(string type)
                {
-                       switch (type)
+                       switch (type.ToLower())
                        {
                                case "library":
                                        target = Target.Library;
@@ -151,60 +129,199 @@ namespace Mono.Languages
                        return WhatToDoNext.GoAhead;
                }
 
-               [Option("Sets warning level (the highest is 4, the default)", "wlevel")]
-               public int wlevel { set { RootContext.WarningLevel = value; } }
+               // input file options
+               //------------------------------------------------------------------
+               public ArrayList AddedModules = new ArrayList();
 
-               [Option("Sets warning level (the highest is 4, the default)")]
-               public bool timestamp
+               [Option("[NOT IMPLEMENTED YET]References metadata from specified {module}", "addmodule")]
+               public string AddedModule { set { AddedModules.Add(value); } }
+
+               [Option("[NOT IMPLEMENTED YET]Include all files in the current directory and subdirectories according to the {wildcard}", "recurse")]
+               public WhatToDoNext Recurse(string wildcard)
                {
-                       set
-                       {
-                               timestamps = true;
-                               last_time = DateTime.Now;
-                               debug_arglist.Add("timestamp");
-                       }
+                       //AddFiles (DirName, true); // TODO wrong semantics
+                       return WhatToDoNext.GoAhead;
                }
 
-       static void Usage (bool is_error)
-               {
-                       Console.WriteLine (     @"
-MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
-  --timestamp     Displays time stamps of various compiler events
-  @file           Read response file for more options
-");
+               [Option(-1, "References metadata from the specified {assembly}", 'r', "reference")]
+               public string AddedReference { set { references.Add(value); } }
+               
+               // support for the Compact Framework
+               //------------------------------------------------------------------
+               [Option("[NOT IMPLEMENTED YET]Sets the compiler to target the Compact Framework","netcf")]
+               public bool CompileForCompactFramework = false;
+               
+               [Option("[NOT IMPLEMENTED YET]Specifies the {path} to the location of mscorlib.dll and microsoft.visualbasic.dll", "sdkpath")]
+               public string SDKPath = null;
+
+               // resource options
+               //------------------------------------------------------------------
+               public ArrayList EmbeddedResources = new ArrayList();
+               
+               [Option(-1, "Adds the specified {file} as an embedded assembly resource", "resource", "res")]
+               public string AddedResource { set { EmbeddedResources.Add(value); } }
+
+               public ArrayList LinkedResources = new ArrayList();
+               
+               [Option(-1, "[NOT IMPLEMENTED YET]Adds the specified {file} as a linked assembly resource", "linkresource", "linkres")]
+               public string AddedLinkresource { set { LinkedResources.Add(value); } }
+
+               public ArrayList Win32Resources = new ArrayList();
+               
+               [Option(-1, "[NOT IMPLEMENTED YET]Specifies a Win32 resource {file} (.res)", "win32resource")]
+               public string AddedWin32resource { set { Win32Resources.Add(value); } }
+
+               public ArrayList Win32Icons = new ArrayList();
+               
+               [Option(-1, "[NOT IMPLEMENTED YET]Specifies a Win32 icon {file} (.ico) for the default Win32 resources", "win32icon")]
+               public string AddedWin32icon { set { Win32Icons.Add(value); } }
+
+               // code generation options
+               //------------------------------------------------------------------
+               [Option("[NOT IMPLEMENTED YET]Enable optimizations", "optimize")]
+               public bool optimize = false;
+
+               [Option("[NOT IMPLEMENTED YET]Remove integer checks. Default off.")]
+               public bool removeintchecks = false;
+
+               // TODO: handle VB.NET [+|-] boolean syntax
+               [Option("Emit debugging information", 'g', "debug")]
+               public bool want_debugging_support = false;
+
+               [Option("Emit full debugging information (default)", "debug:full")]
+               public bool fullDebugging = false;
+
+               [Option("[IGNORED]Emit PDB file only", "debug:pdbonly")]
+               public bool pdbOnly = false;
+
+               // errors and warnings options
+               //------------------------------------------------------------------
+               [Option("Treat warnings as errors", "warnaserror")]
+               public bool WarningsAreErrors { set { Report.WarningsAreErrors = value; } }
+
+               [Option("Disable warnings", "nowarn")]
+               public bool NoWarnings { set { if (value) RootContext.WarningLevel = 0; } }
+
+
+               // language options
+               //------------------------------------------------------------------
+               public Hashtable Defines = new Hashtable();
+               
+               [Option(-1, "Declares global conditional compilation symbol(s). {symbol-list}:name=value,...", 'd', "define")]
+               public string define { 
+                       set 
+                       {
+                               foreach(string item in value.Split(',')) 
+                               {       
+                                       string[] dados = item.Split('=');
+                                       try
+                                       {
+                                               if (dados.Length > 1)
+                                                       Defines.Add(dados[0], dados[1]); 
+                                               else
+                                                       Defines.Add(dados[0], string.Empty);
+                                       }
+                                       catch 
+                                       {
+                                               Error ("Could not define symbol" + dados[0]);
+                                       }
+                               }
+                       } 
                }
                
-               //
-               // If any of these fail, we ignore the problem.  This is so
-               // that we can list all the assemblies in Windows and not fail
-               // if they are missing on Linux.
-               //
-               static ArrayList soft_references;
+               [Option("Declare global Imports for namespaces in referenced metadata files. {import-list}:namespace,...", "imports")]
+               public WhatToDoNext imports(string importslist)
+               {
+                       Mono.MonoBASIC.Parser.ImportsList.AddRange(importslist.Split(','));
+                       return WhatToDoNext.GoAhead;
+               }
 
-               static int error_count = 0;
+               // TODO: handle VB.NET [+|-] boolean syntax
+               [Option("[NOT IMPLEMENTED YET]Require explicit declaration of variables")]
+               public bool optionexplicit { set { Mono.MonoBASIC.Parser.InitialOptionExplicit = value; } }
 
-               static string first_source;
+               // TODO: handle VB.NET [+|-] boolean syntax
+               [Option("[NOT IMPLEMENTED YET]Enforce strict language semantics")]
+               public bool optionstrict { set { Mono.MonoBASIC.Parser.InitialOptionStrict = value; } }
+               
+               [Option("[NOT IMPLEMENTED YET]Specifies binary-style string comparisons. This is the default", "optioncompare:binary")]
+               public bool optioncomparebinary { set { Mono.MonoBASIC.Parser.InitialOptionCompareBinary = true; } }
 
-               static Target target = Target.Exe;
-               static string target_ext = ".exe";
+               [Option("[NOT IMPLEMENTED YET]Specifies text-style string comparisons.", "optioncompare:text")]
+               public bool optioncomparetext { set { Mono.MonoBASIC.Parser.InitialOptionCompareBinary = false; } }
 
-               static ArrayList debug_arglist = new ArrayList ();
+               [Option("Specifies de root {namespace} for all type declarations")]
+               public string rootnamespace { set { RootContext.RootNamespace = value; } }
+               
+               // Miscellaneous options        
+               //------------------------------------------------------------------
+               
+               [Option("[IGNORED]Do not display compiler copyright banner")]
+               public bool nologo = false;
+               
+               [Option("[NOT IMPLEMENTED YET]Quiet output mode")]
+               public bool quiet = false;
+               
+               // TODO: semantics are different and should be adjusted
+               [Option("Display verbose messages", 'v')] 
+               public bool verbose     { set { GenericParser.yacc_verbose_flag = value; } }
 
-               static bool timestamps = false;
+               // Advanced options     
+               //------------------------------------------------------------------
+               // TODO: force option to accept number in hex format
+               [Option("[NOT IMPLEMENTED YET]The base {address} for a library or module (hex)")]
+               public int baseaddress;
+               
+               [Option("[NOT IMPLEMENTED YET]Create bug report {file}")]
+               public string bugreport;
+               
+               // TODO: handle VB.NET [+|-] boolean syntax
+               [Option("[NOT IMPLEMENTED YET]Delay-sign the assembly using only the public portion of the strong name key")]
+               public bool delaysign;
+               
+               [Option("[NOT IMPLEMENTED YET]Specifies a strong name key {container}")]
+               public string keycontainer;
+               
+               [Option("[NOT IMPLEMENTED YET]Specifies a strong name key {file}")]
+               public string keyfile;
 
-               static Hashtable source_files = new Hashtable ();
+               public string[] libpath = null;
+               
+               [Option("List of directories to search for metadata references {path-list}:path;...", "libpath")]
+               public WhatToDoNext setlibpath(string pathlist)
+               {
+                       libpath = pathlist.Split(';');
+                       return WhatToDoNext.GoAhead;
+               }
 
-               //
-               // An array of the defines from the command line
-               //
-               static ArrayList defines;
+               [Option(@"Specifies the Class or Module that contains Sub Main.
+                       It can also be a {class} that inherits from System.Windows.Forms.Form.",
+                       'm', "main")]
+               public string main { set { RootContext.MainClass = value; } }
+
+               // TODO: handle VB.NET [+|-] boolean syntax
+               [Option("[IGNORED]Emit compiler output in UTF8 character encoding")]
+               public bool utf8output;
 
+               // TODO : response file support
                
+               ArrayList defines = new ArrayList();
+               ArrayList references = new ArrayList();
+               ArrayList soft_references = new ArrayList();
+               
+               string first_source = null;
+               Target target = Target.Exe;
+               string target_ext = ".exe";
+               ArrayList debug_arglist = new ArrayList ();
+               bool timestamps = false;
+               Hashtable source_files = new Hashtable ();
+               bool load_default_config = true;
+
                //
                // Last time we took the time
                //
-               static DateTime last_time;
-               static void ShowTime (string msg)
+               DateTime last_time;
+               void ShowTime (string msg)
                {
                        DateTime now = DateTime.Now;
                        TimeSpan span = now - last_time;
@@ -215,77 +332,57 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                                (int) span.TotalSeconds, span.Milliseconds, msg);
                }
                        
-               static void error (string msg)
-               {
-                       Console.WriteLine ("Error: " + msg);
-               }
-
-               static void notice (string msg)
-               {
-                       Console.WriteLine (msg);
-               }
-               
-               public static int Main (string[] args)
-               {
-                       Driver Exec = new Driver();
-                       
-                       if (Exec.MainDriver(args) && Report.Errors == 0) 
-                       {
-                               Console.Write("Compilation succeeded");
-                               if (Report.Warnings > 0) 
-                               {
-                                       Console.Write(" - {0} warning(s)", Report.Warnings);
-                               } 
-                               Console.WriteLine();
-                               return 0;
-                       } 
-                       else 
-                       {
-                               Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
-                                       Report.Errors, Report.Warnings);
-                               return 1;
-                       }
-               }
-
-               static public int LoadAssembly (string assembly, bool soft)
+               public int LoadAssembly (string assembly, bool soft)
                {
                        Assembly a;
                        string total_log = "";
 
-                       try {
-                               char[] path_chars = { '/', '\\', '.' };
+                       try 
+                       {
+                               char[] path_chars = { '/', '\\' };
 
                                if (assembly.IndexOfAny (path_chars) != -1)
-                                       a = Assembly.LoadFrom (assembly);
+                                       a = Assembly.LoadFrom(assembly);
                                else
-                                       a = Assembly.Load (assembly);
+                                       a = Assembly.Load(assembly);
                                TypeManager.AddAssembly (a);
                                return 0;
-                       } catch (FileNotFoundException){
-                               foreach (string dir in LinkPaths){
-                                       string full_path = dir + "/" + assembly + ".dll";
-
-                                       try {
-                                               a = Assembly.LoadFrom (full_path);
-                                               TypeManager.AddAssembly (a);
-                                               return 0;
-                                       } catch (FileNotFoundException ff) {
-                                               total_log += ff.FusionLog;
-                                               continue;
+                       }
+                       catch (FileNotFoundException)
+                       {
+                               if (libpath != null)
+                               {
+                                       foreach (string dir in libpath)
+                                       {
+                                               string full_path = dir + "/" + assembly + ".dll";
+
+                                               try 
+                                               {
+                                                       a = Assembly.LoadFrom (full_path);
+                                                       TypeManager.AddAssembly (a);
+                                                       return 0;
+                                               } 
+                                               catch (FileNotFoundException ff) 
+                                               {
+                                                       total_log += ff.FusionLog;
+                                                       continue;
+                                               }
                                        }
                                }
                                if (soft)
                                        return 0;
-                       } catch (BadImageFormatException f) {
-                               error ("// Bad file format while loading assembly");
-                               error ("Log: " + f.FusionLog);
+                       }
+                       catch (BadImageFormatException f) 
+                       {
+                               Error ("// Bad file format while loading assembly");
+                               Error ("Log: " + f.FusionLog);
                                return 1;
                        } catch (FileLoadException f){
-                               error ("File Load Exception: " + assembly);
-                               error ("Log: " + f.FusionLog);
+                               Error ("File Load Exception: " + assembly);
+                               Error ("Log: " + f.FusionLog);
                                return 1;
                        } catch (ArgumentNullException){
-                               error ("// Argument Null exception ");
+                               Error ("// Argument Null exception ");
                                return 1;
                        }
                        
@@ -295,10 +392,15 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                        return 0;
                }
 
+               void Error(string message)
+               {
+                       Console.WriteLine(message);
+               }
+
                /// <summary>
                ///   Loads all assemblies referenced on the command line
                /// </summary>
-               static public int LoadReferences ()
+               public int LoadReferences ()
                {
                        int errors = 0;
 
@@ -311,17 +413,23 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                        return errors;
                }
 
-               static void SetupDefaultDefines ()
+               void SetupDefaultDefines ()
                {
                        defines = new ArrayList ();
                        defines.Add ("__MonoBASIC__");
                }
+               
+               void SetupDefaultImports()
+               {
+                       Mono.MonoBASIC.Parser.ImportsList = new ArrayList();
+                       Mono.MonoBASIC.Parser.ImportsList.Add("Microsoft.VisualBasic");
+               }
 
 
                //
                // Returns the directory where the system assemblies are installed
                //
-               static string GetSystemDir ()
+               string GetSystemDir ()
                {
                        Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
 
@@ -339,7 +447,7 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                //
                // Given a path specification, splits the path from the file/pattern
                //
-               static void SplitPathAndPattern (string spec, out string path, out string pattern)
+               void SplitPathAndPattern (string spec, out string path, out string pattern)
                {
                        int p = spec.LastIndexOf ("/");
                        if (p != -1){
@@ -368,29 +476,20 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                        pattern = spec;
                }
 
-
-               static int ProcessSourceFile(string filename)
-               {
-                       if (tokenize)
-                               GenericParser.Tokenize(filename);
-                       else
-                               return GenericParser.Parse(filename);
-
-                       return 0;
-               }
-
-               static bool AddFiles (string spec, bool recurse)
+               bool AddFiles (string spec, bool recurse)
                {
                        string path, pattern;
 
-                       SplitPathAndPattern (spec, out path, out pattern);
-                       if (pattern.IndexOf ("*") == -1){
-                               return AddFile (spec);
+                       SplitPathAndPattern(spec, out path, out pattern);
+                       if (pattern.IndexOf("*") == -1)
+                       {
+                               AddFile(spec);
+                               return true;
                        }
 
                        string [] files = null;
                        try {
-                               files = Directory.GetFiles (path, pattern);
+                               files = Directory.GetFiles(path, pattern);
                        } catch (System.IO.DirectoryNotFoundException) {
                                Report.Error (2001, "Source file `" + spec + "' could not be found");
                                return false;
@@ -407,7 +506,7 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                        string [] dirs = null;
 
                        try {
-                               dirs = Directory.GetDirectories (path);
+                               dirs = Directory.GetDirectories(path);
                        } catch {
                        }
                        
@@ -417,12 +516,11 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                                // directory entry already does
                                AddFiles (d + "/" + pattern, true);
                        }
-                       
 
                        return true;
                }
 
-               static void DefineDefaultConfig ()
+               void DefineDefaultConfig ()
                {
                        //
                        // For now the "default config" is harcoded into the compiler
@@ -433,8 +531,8 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                                "System",
                                "System.Data",
                                "System.Xml",
-                               "Microsoft.VisualBasic", // just for now
-#if false
+                               "Microsoft.VisualBasic" , 
+#if EXTRA_DEFAULT_REFS
                                //
                                // Is it worth pre-loading all this stuff?
                                //
@@ -453,124 +551,110 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                                "System.ServiceProcess",
                                "System.Web",
                                "System.Web.RegularExpressions",
-                               "System.Web.Services",
+                               "System.Web.Services" ,
                                "System.Windows.Forms"
 #endif
                        };
                        
-                       int p = 0;
                        foreach (string def in default_config)
-                               soft_references.Insert (p++, def);
+                               soft_references.Add(def);
                }
 
-               private static bool AddFile(string fileName)
+               [ArgumentProcessor]
+               public void AddFile(string fileName)
                {
                        string f = fileName;
                        if (first_source == null)
                                first_source = f;
 
                        if (source_files.Contains(f))
-                       {
-                               Report.Error (1516, "Source file `" + f + "' specified multiple times");
-                               return false;
-                       } 
+                               Report.Error(1516, "Source file '" + f + "' specified multiple times");
                        else
                                source_files.Add(f, f);
-
-                       return true;
                }
 
-               
-               /// <summary>
-               ///    Parses the arguments, and drives the compilation
-               ///    process.
-               /// </summary>
-               ///
-               /// <remarks>
-               ///    TODO: Mostly structured to debug the compiler
-               ///    now, needs to be turned into a real driver soon.
-               /// </remarks>
-               bool MainDriver(string [] args)
+               void ProcessSourceFile(string filename)
                {
-                       int errors = 0;//, i;
-                       string output_file = null;
-                       
-                       soft_references = new ArrayList ();
-                       SetupDefaultDefines ();
-                       
-                       this.ProcessArgs(args);
+                       if (tokenize)
+                               GenericParser.Tokenize(filename);
+                       else
+                               GenericParser.Parse(filename);
+               }
 
-                       foreach(string arg in this.RemainingArguments)
-                               AddFile(arg); 
+               string outputFile_Name = null;
 
-                       foreach(string filename in source_files.Values)
-                               errors += ProcessSourceFile(filename);
+               string outputFileName
+               {
+                       get 
+                       {
+                               if (outputFile_Name == null)
+                               {
+                                       if (OutputFileName == null)
+                                       {
+                                               int pos = first_source.LastIndexOf(".");
+
+                                               if (pos > 0)
+                                                       OutputFileName = first_source.Substring(0, pos);
+                                               else
+                                                       OutputFileName = first_source;
+                                       }
+                                       string bname = CodeGen.Basename(OutputFileName);
+                                       if (bname.IndexOf(".") == -1)
+                                               OutputFileName +=  target_ext;
+                                       outputFile_Name = OutputFileName;
+                               }
+                               return outputFile_Name;
+                       }
+               }
 
+               bool ParseAll() // Phase 1
+               {
                        if (first_source == null)
                        {
-                               Report.Error (2008, "No files to compile were specified");
+                               Report.Error(2008, "No files to compile were specified");
                                return false;
                        }
 
-                       if (tokenize)
-                               return true;
-                       
-                       if (Report.Errors > 0)
-                               return false;
-                       
-                       if (parse_only)
-                               return true;
-                       
-                       //
+                       foreach(string filename in source_files.Values)
+                               ProcessSourceFile(filename);
+
+                       if (tokenize || parse_only || (Report.Errors > 0))
+                               return false;           
+
+                       return true; // everything went well go ahead
+               }
+
+               void InitializeDebuggingSupport()
+               {
+                       string[] debug_args = new string [debug_arglist.Count];
+                       debug_arglist.CopyTo(debug_args);
+                       CodeGen.Init(outputFileName, outputFileName, want_debugging_support, debug_args);
+                       TypeManager.AddModule(CodeGen.ModuleBuilder);
+               }
+
+               public bool ResolveAllTypes() // Phase 2
+               {
                        // Load Core Library for default compilation
-                       //
                        if (RootContext.StdLib)
-                               references.Insert (0, "mscorlib");
+                               references.Insert(0, "mscorlib");
 
                        if (load_default_config)
-                               DefineDefaultConfig ();
+                               DefineDefaultConfig();
 
-                       if (errors > 0)
-                       {
-                               error ("Parsing failed");
-                               return false;
-                       }
+                       if (timestamps)
+                               ShowTime("Loading references");
 
-                       //
                        // Load assemblies required
-                       //
-                       if (timestamps)
-                               ShowTime ("Loading references");
-                       errors += LoadReferences ();
-                       if (timestamps)
-                               ShowTime ("   References loaded");
-                       
-                       if (errors > 0)
+                       if (LoadReferences() > 0)
                        {
-                               error ("Could not load one or more assemblies");
+                               Error ("Could not load one or more assemblies");
                                return false;
                        }
 
-                       error_count = errors;
-
-                       //
-                       // Quick hack
-                       //
-                       if (output_file == null)
-                       {
-                               int pos = first_source.LastIndexOf (".");
-
-                               if (pos > 0)
-                                       output_file = first_source.Substring (0, pos) + target_ext;
-                               else
-                                       output_file = first_source + target_ext;
-                       }
-
-                       string[] debug_args = new string [debug_arglist.Count];
-                       debug_arglist.CopyTo(debug_args);
-                       CodeGen.Init (output_file, output_file, want_debugging_support, debug_args);
+                       if (timestamps)
+                               ShowTime("References loaded");
 
-                       TypeManager.AddModule (CodeGen.ModuleBuilder);
+                       InitializeDebuggingSupport();
 
                        //
                        // Before emitting, we need to get the core
@@ -579,98 +663,176 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                        //
                        if (timestamps)
                                ShowTime ("Initializing Core Types");
+
                        if (!RootContext.StdLib)
-                       {
                                RootContext.ResolveCore ();
-                               if (Report.Errors > 0)
-                                       return false;
-                       }
+                       if (Report.Errors > 0)
+                               return false;
                        
-                       TypeManager.InitCoreTypes ();
+                       TypeManager.InitCoreTypes();
+                       if (Report.Errors > 0)
+                               return false;
+
                        if (timestamps)
                                ShowTime ("   Core Types done");
-               
-                       //
-                       // The second pass of the compiler
-                       //
+
                        if (timestamps)
                                ShowTime ("Resolving tree");
+
+                       // The second pass of the compiler
                        RootContext.ResolveTree ();
+                       if (Report.Errors > 0)
+                               return false;
+                       
                        if (timestamps)
                                ShowTime ("Populate tree");
 
+                       if (!RootContext.StdLib)
+                               RootContext.BootCorlib_PopulateCoreTypes();
                        if (Report.Errors > 0)
-                       {
-                               error ("Compilation failed");
                                return false;
-                       }
 
-                       if (!RootContext.StdLib)
-                               RootContext.BootCorlib_PopulateCoreTypes ();
-                       RootContext.PopulateTypes ();
+                       RootContext.PopulateTypes();
+                       if (Report.Errors > 0)
+                               return false;
                        
-                       TypeManager.InitCodeHelpers ();
-                               
+                       TypeManager.InitCodeHelpers();
                        if (Report.Errors > 0)
-                       {
-                               error ("Compilation failed");
                                return false;
+
+                       return true;
+               }
+               
+               bool IsSWFApp()
+               {
+                       string mainclass = GetFQMainClass();
+                       
+                       if (mainclass != null) {
+                               foreach (string r in references) {
+                                       if (r.IndexOf ("System.Windows.Forms") >= 0) {
+                                               Type t = TypeManager.LookupType(mainclass);
+                                               if (t != null) 
+                                                       return t.IsSubclassOf (TypeManager.LookupType("System.Windows.Forms.Form"));
+                                               break;  
+                                       }       
+                               }
                        }
+                       return false;
+               }
+               
+               string GetFQMainClass()
+               {       
+                       if (RootContext.RootNamespace != "")
+                               return RootContext.RootNamespace + "." + RootContext.MainClass;
+                       else
+                               return RootContext.MainClass;                   
+               }
+               
+               void FixEntryPoint()
+               {
+                       if (target == Target.Exe || target == Target.WinExe)
+                       {
+                               MethodInfo ep = RootContext.EntryPoint;
                        
+                               if (ep == 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. Otherwise we
+                                       // won't be able to compile SWF code out of the box.
+
+                                       if (IsSWFApp()) 
+                                       {                                                                                               
+                                               Type t = TypeManager.LookupType(GetFQMainClass());
+                                               if (t != null) 
+                                               {                                                       
+                                                       TypeBuilder tb = t as TypeBuilder;
+                                                       MethodBuilder mb = tb.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, 
+                                                               typeof(void), new Type[0]);
+
+                                                       Type SWFA = TypeManager.LookupType("System.Windows.Forms.Application");
+                                                       Type SWFF = TypeManager.LookupType("System.Windows.Forms.Form");
+                                                       Type[] args = new Type[1];
+                                                       args[0] = SWFF;
+                                                       MethodInfo mi = SWFA.GetMethod("Run", args);
+                                                       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;
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               bool GenerateAssembly()
+               {
                        //
                        // The code generator
                        //
                        if (timestamps)
                                ShowTime ("Emitting code");
-                       RootContext.EmitCode ();
-                       if (timestamps)
-                               ShowTime ("   done");
+                       
+                       
 
+                       RootContext.EmitCode();
+                       FixEntryPoint();
                        if (Report.Errors > 0)
-                       {
-                               error ("Compilation failed");
                                return false;
-                       }
+
+                       if (timestamps)
+                               ShowTime ("   done");
+
 
                        if (timestamps)
                                ShowTime ("Closing types");
-                       
+
                        RootContext.CloseTypes ();
+                       if (Report.Errors > 0)
+                               return false;
 
-                       //                      PEFileKinds k = PEFileKinds.ConsoleApplication;
-                       //                              
-                       //                      if (target == Target.Library || target == Target.Module)
-                       //                              k = PEFileKinds.Dll;
-                       //                      else if (target == Target.Exe)
-                       //                              k = PEFileKinds.ConsoleApplication;
-                       //                      else if (target == Target.WinExe)
-                       //                              k = PEFileKinds.WindowApplication;
-                       //
-                       //                      if (target == Target.Exe || target == Target.WinExe){
-                       //                              MethodInfo ep = RootContext.EntryPoint;
-                       //
-                       //                              if (ep == null){
-                       //                                      Report.Error (5001, "Program " + output_file +
-                       //                                                            " does not have an entry point defined");
-                       //                                      return;
-                       //                              }
-                       //                              
-                       //                              CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
-                       //                      }
+                       if (timestamps)
+                               ShowTime ("   done");
 
-                       //
-                       // Add the resources
-                       //
-                       if (resources != null)
+                       PEFileKinds k = PEFileKinds.ConsoleApplication;
+                                                       
+                       if (target == Target.Library || target == Target.Module)
+                               k = PEFileKinds.Dll;
+                       else if (target == Target.Exe)
+                               k = PEFileKinds.ConsoleApplication;
+                       else if (target == Target.WinExe)
+                               k = PEFileKinds.WindowApplication;
+                       
+                       if (target == Target.Exe || target == Target.WinExe)
                        {
-                               foreach (string file in resources)
-                                       CodeGen.AssemblyBuilder.AddResourceFile (file, file);
+                               MethodInfo ep = RootContext.EntryPoint;
+                       
+                               if (ep == null)
+                               {
+                                       Report.Error (30737, "Program " + outputFileName +
+                                               " does not have an entry point defined");
+                                       return false;
+                               }
+                                                       
+                               CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
                        }
+
+                       // Add the resources
+                       if (EmbeddedResources != null)
+                               foreach (string file in EmbeddedResources)
+                                       CodeGen.AssemblyBuilder.AddResourceFile (file, file);
                        
-                       CodeGen.Save (output_file);
+                       CodeGen.Save(outputFileName);
+
                        if (timestamps)
                                ShowTime ("Saved output");
 
+                       
                        if (want_debugging_support) 
                        {
                                CodeGen.SaveSymbols ();
@@ -678,13 +840,59 @@ MonoBASIC Compiler, Copyright (C)2002 Rafael Teixeira.
                                        ShowTime ("Saved symbols");
                        }
 
-                       if (Report.ExpectedError != 0)
+                       return true;
+               }
+
+               public void CompileAll()
+               {
+/* 
+                   VB.NET expects the default namespace to be "" (empty string)                
+                   
+                   if (RootContext.RootNamespace == "")
+                   {
+                     RootContext.RootNamespace = System.IO.Path.GetFileNameWithoutExtension(outputFileName);
+                   }
+*/
+                       if (!ParseAll()) // Phase 1
+                               return;
+
+                       if (!ResolveAllTypes()) // Phase 2
+                               return;
+
+                       GenerateAssembly(); // Phase 3 
+               }
+
+               /// <summary>
+               ///    Parses the arguments, and calls the compilation process.
+               /// </summary>
+               int MainDriver(string [] args)
+               {
+                       Console.WriteLine ("THIS IS ALPHA AND UNSUPPORTED SOFTWARE, USE AT YOUR OWN RISK.");
+                       SetupDefaultDefines();  
+                       
+                       SetupDefaultImports();
+
+                       ProcessArgs(args);
+                       
+                       if (first_source == null)
                        {
-                               Console.WriteLine("Failed to report expected error " + Report.ExpectedError);
-                               Environment.Exit (1);
-                               return false;
+                               if (!quiet) 
+                                       DoHelp();
+                               return 2;
                        }
-                       return (Report.Errors == 0);
+
+                       CompileAll();
+
+                       return Report.ProcessResults(quiet);
+               }
+
+               public static int Main (string[] args)
+               {
+                       Driver Exec = new Driver();
+                       
+                       Report.Stacktrace = false;
+
+                       return Exec.MainDriver(args);
                }
 
        }