📄 driver.cs
字号:
//// driver.cs: The compiler command line driver.//// Author: Miguel de Icaza (miguel@gnu.org)//// Licensed under the terms of the GNU GPL//// (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)// (C) 2004, 2005 Novell, Inc//namespace Mono.CSharp{ using System; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Text; using System.Globalization; using System.Diagnostics; public enum Target { Library, Exe, Module, WinExe }; /// <summary> /// The compiler driver. /// </summary> public class Driver { // // Assemblies references to be linked. Initialized with // mscorlib.dll here. static ArrayList references; // // 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; // // External aliases for assemblies. // static Hashtable external_aliases; // // Modules to be linked // static ArrayList modules; // Lookup paths static ArrayList link_paths; // Whether we want to only run the tokenizer static bool tokenize = false; static string first_source; static bool want_debugging_support = false; static bool parse_only = false; static bool timestamps = false; static bool pause = false; static bool show_counters = false; // // Whether to load the initial config file (what CSC.RSP has by default) // static bool load_default_config = true; // // A list of resource files // static Resources embedded_resources; static string win32ResourceFile; static string win32IconFile; // // An array of the defines from the command line // static ArrayList defines; // // Output file // static string output_file = null; // // Last time we took the time // static DateTime last_time, first_time; // // Encoding. // static Encoding encoding; static public void Reset () { want_debugging_support = false; parse_only = false; timestamps = false; pause = false; show_counters = false; load_default_config = true; embedded_resources = null; win32ResourceFile = win32IconFile = null; defines = null; output_file = null; encoding = null; first_source = null; } public static void ShowTime (string msg) { if (!timestamps) return; DateTime now = DateTime.Now; TimeSpan span = now - last_time; last_time = now; Console.WriteLine ( "[{0:00}:{1:000}] {2}", (int) span.TotalSeconds, span.Milliseconds, msg); } public static void ShowTotalTime (string msg) { if (!timestamps) return; DateTime now = DateTime.Now; TimeSpan span = now - first_time; last_time = now; Console.WriteLine ( "[{0:00}:{1:000}] {2}", (int) span.TotalSeconds, span.Milliseconds, msg); } static void tokenize_file (SourceFile file) { Stream input; try { input = File.OpenRead (file.Name); } catch { Report.Error (2001, "Source file `" + file.Name + "' could not be found"); return; } using (input){ SeekableStreamReader reader = new SeekableStreamReader (input, encoding); Tokenizer lexer = new Tokenizer (reader, file, defines); int token, tokens = 0, errors = 0; while ((token = lexer.token ()) != Token.EOF){ tokens++; if (token == Token.ERROR) errors++; } Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors"); } return; } // MonoTODO("Change error code for aborted compilation to something reasonable")] static void parse (SourceFile file) { CSharpParser parser; Stream input; try { input = File.OpenRead (file.Name); } catch { Report.Error (2001, "Source file `" + file.Name + "' could not be found"); return; } SeekableStreamReader reader = new SeekableStreamReader (input, encoding); // Check 'MZ' header if (reader.Read () == 77 && reader.Read () == 90) { Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name); input.Close (); return; } reader.Position = 0; parser = new CSharpParser (reader, file, defines); parser.ErrorOutput = Report.Stderr; try { parser.parse (); } catch (Exception ex) { Report.Error(666, "Compilation aborted: " + ex); } finally { input.Close (); } } static void OtherFlags () { Console.WriteLine ( "Other flags in the compiler\n" + " --fatal Makes errors fatal\n" + " --parse Only parses the source file\n" + " --stacktrace Shows stack trace at error location\n" + " --timestamp Displays time stamps of various compiler events\n" + " --expect-error X Expect that error X will be encountered\n" + " -2 Enables experimental C# features\n" + " -v Verbose parsing (for debugging the parser)\n" + " --mcs-debug X Sets MCS debugging level to X\n"); } static void Usage () { Console.WriteLine ( "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" + "mcs [options] source-files\n" + " --about About the Mono C# compiler\n" + " -addmodule:MODULE Adds the module to the generated assembly\n" + " -checked[+|-] Set default context to checked\n" + " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" + " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine + " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" + " -debug[+|-], -g Generate debugging information\n" + " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" + " -doc:FILE XML Documentation file to generate\n" + " -keycontainer:NAME The key pair container used to strongname the assembly\n" + " -keyfile:FILE The strongname key file used to strongname the assembly\n" + " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" + " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" + " -main:class Specified the class that contains the entry point\n" + " -noconfig[+|-] Disables implicit references to assemblies\n" + " -nostdlib[+|-] Does not load core libraries\n" + " -nowarn:W1[,W2] Disables one or more warnings\n" + " -optimize[+|-] Enables code optimalizations\n" + " -out:FNAME Specifies output file\n" + " -pkg:P1[,Pn] References packages P1..Pn\n" + " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" + " -reference:ASS References the specified assembly (-r:ASS)\n" + " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" + " library, module), (short: /t:)\n" + " -unsafe[+|-] Allows unsafe code\n" + " -warnaserror[+|-] Treat warnings as errors\n" + " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" + " -help2 Show other help flags\n" + "\n" + "Resources:\n" + " -linkresource:FILE[,ID] Links FILE as a resource\n" + " -resource:FILE[,ID] Embed FILE as a resource\n" + " -win32res:FILE Specifies Win32 resource file (.res)\n" + " -win32icon:FILE Use this icon for the output\n" + " @file Read response file for more options\n\n" + "Options can be of the form -option or /option"); } static void TargetUsage () { Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'"); } static void About () { Console.WriteLine ( "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" + "The compiler source code is released under the terms of the GNU GPL\n\n" + "For more information on Mono, visit the project Web site\n" + " http://www.go-mono.com\n\n" + "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath"); Environment.Exit (0); } public static int counter1, counter2; public static int Main (string[] args) { Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t"; bool ok = MainDriver (args); if (ok && Report.Errors == 0) { if (Report.Warnings > 0) { Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings); } if (show_counters){ Console.WriteLine ("Counter1: " + counter1); Console.WriteLine ("Counter2: " + counter2); } if (pause) Console.ReadLine (); return 0; } else { Console.WriteLine("Compilation failed: {0} error(s), {1} warnings", Report.Errors, Report.Warnings); return 1; } } static public void LoadAssembly (string assembly, bool soft) { LoadAssembly (assembly, null, soft); } static public void LoadAssembly (string assembly, string alias, bool soft) { Assembly a; string total_log = ""; try { char[] path_chars = { '/', '\\' }; if (assembly.IndexOfAny (path_chars) != -1) { a = Assembly.LoadFrom (assembly); } else { string ass = assembly; if (ass.EndsWith (".dll") || ass.EndsWith (".exe")) ass = assembly.Substring (0, assembly.Length - 4); a = Assembly.Load (ass); } // Extern aliased refs require special handling if (alias == null) RootNamespace.Global.AddAssemblyReference (a); else RootNamespace.DefineRootNamespace (alias, a); } catch (FileNotFoundException){ foreach (string dir in link_paths){ string full_path = Path.Combine (dir, assembly); if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe")) full_path += ".dll"; try { a = Assembly.LoadFrom (full_path); if (alias == null) RootNamespace.Global.AddAssemblyReference (a); else RootNamespace.DefineRootNamespace (alias, a); return; } catch (FileNotFoundException ff) { total_log += ff.FusionLog; continue; } } if (!soft) { Report.Error (6, "Cannot find assembly `" + assembly + "'" ); Console.WriteLine ("Log: \n" + total_log); } } catch (BadImageFormatException f) { Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog); } catch (FileLoadException f){ Report.Error(6, "Cannot load assembly " + f.FusionLog); } catch (ArgumentNullException){ Report.Error(6, "Cannot load assembly (null argument)"); } } static public void LoadModule (MethodInfo adder_method, string module) { Module m; string total_log = ""; try { try { m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module }); } catch (TargetInvocationException ex) { throw ex.InnerException; } RootNamespace.Global.AddModuleReference (m); } catch (FileNotFoundException){ foreach (string dir in link_paths){ string full_path = Path.Combine (dir, module); if (!module.EndsWith (".netmodule")) full_path += ".netmodule"; try { try { m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path }); } catch (TargetInvocationException ex) { throw ex.InnerException; } RootNamespace.Global.AddModuleReference (m); return; } catch (FileNotFoundException ff) { total_log += ff.FusionLog; continue; } } Report.Error (6, "Cannot find module `" + module + "'" ); Console.WriteLine ("Log: \n" + total_log); } catch (BadImageFormatException f) { Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog); } catch (FileLoadException f){ Report.Error(6, "Cannot load module " + f.FusionLog); } catch (ArgumentNullException){ Report.Error(6, "Cannot load module (null argument)"); } } /// <summary> /// Loads all assemblies referenced on the command line /// </summary> static public void LoadReferences () { foreach (string r in references) LoadAssembly (r, false); foreach (string r in soft_references) LoadAssembly (r, true); foreach (DictionaryEntry entry in external_aliases) LoadAssembly ((string) entry.Value, (string) entry.Key, false); return; } static void SetupDefaultDefines () { defines = new ArrayList (); defines.Add ("__MonoCS__"); } static string [] LoadArgs (string file) { StreamReader f; ArrayList args = new ArrayList (); string line; try { f = new StreamReader (file); } catch { return null; } StringBuilder sb = new StringBuilder (); while ((line = f.ReadLine ()) != null){ int t = line.Length; for (int i = 0; i < t; i++){ char c = line [i]; if (c == '"' || c == '\''){ char end = c; for (i++; i < t; i++){ c = line [i]; if (c == end) break; sb.Append (c); } } else if (c == ' '){ if (sb.Length > 0){ args.Add (sb.ToString ()); sb.Length = 0; } } else sb.Append (c); } if (sb.Length > 0){ args.Add (sb.ToString ()); sb.Length = 0; } } string [] ret_value = new string [args.Count]; args.CopyTo (ret_value, 0); return ret_value; } // // Returns the directory where the system assemblies are installed // static string GetSystemDir () { return Path.GetDirectoryName (typeof (object).Assembly.Location); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -