2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004, 2005 Novell, Inc
15 using System
.Reflection
;
16 using System
.Reflection
.Emit
;
17 using System
.Collections
;
18 using System
.Collections
.Specialized
;
21 using System
.Globalization
;
22 using System
.Diagnostics
;
25 Library
, Exe
, Module
, WinExe
29 /// The compiler driver.
35 // Assemblies references to be linked. Initialized with
37 static ArrayList references
;
40 // If any of these fail, we ignore the problem. This is so
41 // that we can list all the assemblies in Windows and not fail
42 // if they are missing on Linux.
44 static ArrayList soft_references
;
47 // External aliases for assemblies.
49 static Hashtable external_aliases
;
52 // Modules to be linked
54 static ArrayList modules
;
57 static ArrayList link_paths
;
59 // Whether we want to only run the tokenizer
60 static bool tokenize
= false;
62 static string first_source
;
64 static bool want_debugging_support
= false;
66 static bool parse_only
= false;
67 static bool timestamps
= false;
68 static bool pause
= false;
69 static bool show_counters
= false;
72 // Whether to load the initial config file (what CSC.RSP has by default)
74 static bool load_default_config
= true;
77 // A list of resource files
79 static Resources embedded_resources
;
80 static string win32ResourceFile
;
81 static string win32IconFile
;
84 // An array of the defines from the command line
86 static ArrayList defines
;
91 static string output_file
= null;
94 // Last time we took the time
96 static DateTime last_time
, first_time
;
101 static Encoding encoding
;
103 static public void Reset ()
105 want_debugging_support
= false;
109 show_counters
= false;
110 load_default_config
= true;
111 embedded_resources
= null;
112 win32ResourceFile
= win32IconFile
= null;
119 public static void ShowTime (string msg
)
124 DateTime now
= DateTime
.Now
;
125 TimeSpan span
= now
- last_time
;
129 "[{0:00}:{1:000}] {2}",
130 (int) span
.TotalSeconds
, span
.Milliseconds
, msg
);
133 public static void ShowTotalTime (string msg
)
138 DateTime now
= DateTime
.Now
;
139 TimeSpan span
= now
- first_time
;
143 "[{0:00}:{1:000}] {2}",
144 (int) span
.TotalSeconds
, span
.Milliseconds
, msg
);
147 static void tokenize_file (SourceFile file
)
152 input
= File
.OpenRead (file
.Name
);
154 Report
.Error (2001, "Source file `" + file
.Name
+ "' could not be found");
159 SeekableStreamReader reader
= new SeekableStreamReader (input
, encoding
);
160 Tokenizer lexer
= new Tokenizer (reader
, file
, defines
);
161 int token
, tokens
= 0, errors
= 0;
163 while ((token
= lexer
.token ()) != Token
.EOF
){
165 if (token
== Token
.ERROR
)
168 Console
.WriteLine ("Tokenized: " + tokens
+ " found " + errors
+ " errors");
174 // MonoTODO("Change error code for aborted compilation to something reasonable")]
175 static void parse (SourceFile file
)
181 input
= File
.OpenRead (file
.Name
);
183 Report
.Error (2001, "Source file `" + file
.Name
+ "' could not be found");
187 SeekableStreamReader reader
= new SeekableStreamReader (input
, encoding
);
190 if (reader
.Read () == 77 && reader
.Read () == 90) {
191 Report
.Error (2015, "Source file `{0}' is a binary file and not a text file", file
.Name
);
197 parser
= new CSharpParser (reader
, file
, defines
);
198 parser
.ErrorOutput
= Report
.Stderr
;
201 } catch (Exception ex
) {
202 Report
.Error(666, "Compilation aborted: " + ex
);
208 static void OtherFlags ()
211 "Other flags in the compiler\n" +
212 " --fatal Makes errors fatal\n" +
213 " --parse Only parses the source file\n" +
214 " --stacktrace Shows stack trace at error location\n" +
215 " --timestamp Displays time stamps of various compiler events\n" +
216 " --expect-error X Expect that error X will be encountered\n" +
217 " -2 Enables experimental C# features\n" +
218 " -v Verbose parsing (for debugging the parser)\n" +
219 " --mcs-debug X Sets MCS debugging level to X\n");
225 "Mono C# compiler, (C) 2001 - 2005 Novell, Inc.\n" +
226 "mcs [options] source-files\n" +
227 " --about About the Mono C# compiler\n" +
228 " -addmodule:MODULE Adds the module to the generated assembly\n" +
229 " -checked[+|-] Set default context to checked\n" +
230 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
231 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment
.NewLine
+
232 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
233 " -debug[+|-], -g Generate debugging information\n" +
234 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
235 " -doc:FILE XML Documentation file to generate\n" +
236 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
237 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
238 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
239 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
240 " -main:class Specified the class that contains the entry point\n" +
241 " -noconfig[+|-] Disables implicit references to assemblies\n" +
242 " -nostdlib[+|-] Does not load core libraries\n" +
243 " -nowarn:W1[,W2] Disables one or more warnings\n" +
244 " -optimize[+|-] Enables code optimalizations\n" +
245 " -out:FNAME Specifies output file\n" +
246 " -pkg:P1[,Pn] References packages P1..Pn\n" +
247 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
248 " -reference:ASS References the specified assembly (-r:ASS)\n" +
249 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
250 " library, module), (short: /t:)\n" +
251 " -unsafe[+|-] Allows unsafe code\n" +
252 " -warnaserror[+|-] Treat warnings as errors\n" +
253 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
254 " -help2 Show other help flags\n" +
257 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
258 " -resource:FILE[,ID] Embed FILE as a resource\n" +
259 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
260 " -win32icon:FILE Use this icon for the output\n" +
261 " @file Read response file for more options\n\n" +
262 "Options can be of the form -option or /option");
265 static void TargetUsage ()
267 Report
.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
273 "The Mono C# compiler is (C) 2001-2005, Novell, Inc.\n\n" +
274 "The compiler source code is released under the terms of the GNU GPL\n\n" +
276 "For more information on Mono, visit the project Web site\n" +
277 " http://www.go-mono.com\n\n" +
279 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
280 Environment
.Exit (0);
283 public static int counter1
, counter2
;
285 public static int Main (string[] args
)
288 RootContext
.Version
= LanguageVersion
.Default
;
290 Location
.InEmacs
= Environment
.GetEnvironmentVariable ("EMACS") == "t";
292 bool ok
= MainDriver (args
);
294 if (ok
&& Report
.Errors
== 0) {
295 if (Report
.Warnings
> 0) {
296 Console
.WriteLine ("Compilation succeeded - {0} warning(s)", Report
.Warnings
);
299 Console
.WriteLine ("Counter1: " + counter1
);
300 Console
.WriteLine ("Counter2: " + counter2
);
306 Console
.WriteLine("Compilation failed: {0} error(s), {1} warnings",
307 Report
.Errors
, Report
.Warnings
);
312 static public void LoadAssembly (string assembly
, bool soft
)
314 LoadAssembly (assembly
, null, soft
);
317 static void Error6 (string name
, string log
)
319 if (log
!= null && log
.Length
> 0)
320 Report
.ExtraInformation (Location
.Null
, "Log:\n" + log
+ "\n(log related to previous ");
321 Report
.Error (6, "cannot find metadata file `{0}'", name
);
324 static void Error9 (string type
, string filename
, string log
)
326 if (log
!= null && log
.Length
> 0)
327 Report
.ExtraInformation (Location
.Null
, "Log:\n" + log
+ "\n(log related to previous ");
328 Report
.Error (9, "file `{0}' has invalid `{1}' metadata", filename
, type
);
331 static void BadAssembly (string filename
, string log
)
333 MethodInfo adder_method
= AssemblyClass
.AddModule_Method
;
335 if (adder_method
!= null) {
336 AssemblyName an
= new AssemblyName ();
338 AssemblyBuilder ab
= AppDomain
.CurrentDomain
.DefineDynamicAssembly (an
, AssemblyBuilderAccess
.Run
);
342 m
= adder_method
.Invoke (ab
, new object [] { filename }
);
343 } catch (TargetInvocationException ex
) {
344 throw ex
.InnerException
;
348 Report
.Error (1509, "referenced file `{0}' is not an assembly; try using the '-addmodule' option", filename
);
351 } catch (FileNotFoundException
) {
352 // did the file get deleted during compilation? who cares? swallow the exception
353 } catch (BadImageFormatException
) {
355 } catch (FileLoadException
) {
359 Error9 ("assembly", filename
, log
);
362 static public void LoadAssembly (string assembly
, string alias, bool soft
)
365 string total_log
= "";
369 char[] path_chars
= { '/', '\\' }
;
371 if (assembly
.IndexOfAny (path_chars
) != -1) {
372 a
= Assembly
.LoadFrom (assembly
);
374 string ass
= assembly
;
375 if (ass
.EndsWith (".dll") || ass
.EndsWith (".exe"))
376 ass
= assembly
.Substring (0, assembly
.Length
- 4);
377 a
= Assembly
.Load (ass
);
379 } catch (FileNotFoundException
) {
381 foreach (string dir
in link_paths
) {
382 string full_path
= Path
.Combine (dir
, assembly
);
383 if (!assembly
.EndsWith (".dll") && !assembly
.EndsWith (".exe"))
387 a
= Assembly
.LoadFrom (full_path
);
390 } catch (FileNotFoundException ff
) {
391 total_log
+= ff
.FusionLog
;
395 Error6 (assembly
, total_log
);
400 // Extern aliased refs require special handling
402 RootNamespace
.Global
.AddAssemblyReference (a
);
404 RootNamespace
.DefineRootNamespace (alias, a
);
406 } catch (BadImageFormatException f
) {
407 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
408 BadAssembly (f
.FileName
, f
.FusionLog
);
409 } catch (FileLoadException f
) {
410 // ... while .NET 1.1 throws this
411 BadAssembly (f
.FileName
, f
.FusionLog
);
415 static public void LoadModule (string module
)
418 string total_log
= "";
422 m
= CodeGen
.Assembly
.AddModule (module
);
423 } catch (FileNotFoundException
) {
425 foreach (string dir
in link_paths
) {
426 string full_path
= Path
.Combine (dir
, module
);
427 if (!module
.EndsWith (".netmodule"))
428 full_path
+= ".netmodule";
431 m
= CodeGen
.Assembly
.AddModule (full_path
);
434 } catch (FileNotFoundException ff
) {
435 total_log
+= ff
.FusionLog
;
439 Error6 (module
, total_log
);
444 RootNamespace
.Global
.AddModuleReference (m
);
446 } catch (BadImageFormatException f
) {
447 Error9 ("module", f
.FileName
, f
.FusionLog
);
448 } catch (FileLoadException f
) {
449 Error9 ("module", f
.FileName
, f
.FusionLog
);
454 /// Loads all assemblies referenced on the command line
456 static public void LoadReferences ()
458 foreach (string r
in references
)
459 LoadAssembly (r
, false);
461 foreach (string r
in soft_references
)
462 LoadAssembly (r
, true);
464 foreach (DictionaryEntry entry
in external_aliases
)
465 LoadAssembly ((string) entry
.Value
, (string) entry
.Key
, false);
470 static void SetupDefaultDefines ()
472 defines
= new ArrayList ();
473 defines
.Add ("__MonoCS__");
476 static string [] LoadArgs (string file
)
479 ArrayList args
= new ArrayList ();
482 f
= new StreamReader (file
);
487 StringBuilder sb
= new StringBuilder ();
489 while ((line
= f
.ReadLine ()) != null){
492 for (int i
= 0; i
< t
; i
++){
495 if (c
== '"' || c
== '\''){
498 for (i
++; i
< t
; i
++){
505 } else if (c
== ' '){
507 args
.Add (sb
.ToString ());
514 args
.Add (sb
.ToString ());
519 string [] ret_value
= new string [args
.Count
];
520 args
.CopyTo (ret_value
, 0);
526 // Returns the directory where the system assemblies are installed
528 static string GetSystemDir ()
530 return Path
.GetDirectoryName (typeof (object).Assembly
.Location
);
534 // Given a path specification, splits the path from the file/pattern
536 static void SplitPathAndPattern (string spec
, out string path
, out string pattern
)
538 int p
= spec
.LastIndexOf ('/');
541 // Windows does not like /file.cs, switch that to:
546 pattern
= spec
.Substring (1);
548 path
= spec
.Substring (0, p
);
549 pattern
= spec
.Substring (p
+ 1);
554 p
= spec
.LastIndexOf ('\\');
556 path
= spec
.Substring (0, p
);
557 pattern
= spec
.Substring (p
+ 1);
565 static void ProcessFile (string f
)
567 if (first_source
== null)
570 Location
.AddFile (f
);
573 static void ProcessFiles ()
575 Location
.Initialize ();
577 foreach (SourceFile file
in Location
.SourceFiles
) {
579 tokenize_file (file
);
586 static void CompileFiles (string spec
, bool recurse
)
588 string path
, pattern
;
590 SplitPathAndPattern (spec
, out path
, out pattern
);
591 if (pattern
.IndexOf ('*') == -1){
596 string [] files
= null;
598 files
= Directory
.GetFiles (path
, pattern
);
599 } catch (System
.IO
.DirectoryNotFoundException
) {
600 Report
.Error (2001, "Source file `" + spec
+ "' could not be found");
602 } catch (System
.IO
.IOException
){
603 Report
.Error (2001, "Source file `" + spec
+ "' could not be found");
606 foreach (string f
in files
) {
613 string [] dirs
= null;
616 dirs
= Directory
.GetDirectories (path
);
620 foreach (string d
in dirs
) {
622 // Don't include path in this string, as each
623 // directory entry already does
624 CompileFiles (d
+ "/" + pattern
, true);
628 static void DefineDefaultConfig ()
631 // For now the "default config" is harcoded into the compiler
632 // we can move this outside later
634 string [] default_config
= {
639 // Is it worth pre-loading all this stuff?
642 "System.Configuration.Install",
645 "System.DirectoryServices",
646 "System.Drawing.Design",
648 "System.EnterpriseServices",
651 "System.Runtime.Remoting",
652 "System.Runtime.Serialization.Formatters.Soap",
654 "System.ServiceProcess",
656 "System.Web.RegularExpressions",
657 "System.Web.Services",
658 "System.Windows.Forms"
663 foreach (string def
in default_config
)
664 soft_references
.Insert (p
++, def
);
667 public static string OutputFile
673 return Path
.GetFileName (output_file
);
677 static void SetWarningLevel (string s
)
682 level
= Int32
.Parse (s
);
685 if (level
< 0 || level
> 4){
686 Report
.Error (1900, "Warning level must be in the range 0-4");
689 RootContext
.WarningLevel
= level
;
692 static void SetupV2 ()
694 RootContext
.Version
= LanguageVersion
.Default
;
695 defines
.Add ("__V2__");
698 static void Version ()
700 string version
= Assembly
.GetExecutingAssembly ().GetName ().Version
.ToString ();
701 Console
.WriteLine ("Mono C# compiler version {0}", version
);
702 Environment
.Exit (0);
706 // Currently handles the Unix-like command line options, but will be
707 // deprecated in favor of the CSCParseOption, which will also handle the
708 // options that start with a dash in the future.
710 static bool UnixParseOption (string arg
, ref string [] args
, ref int i
)
714 CSharpParser
.yacc_verbose_flag
++;
725 case "--main": case "-m":
726 Report
.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
727 if ((i
+ 1) >= args
.Length
){
729 Environment
.Exit (1);
731 RootContext
.MainClass
= args
[++i
];
735 Report
.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
736 RootContext
.Unsafe
= true;
739 case "/?": case "/h": case "/help":
742 Environment
.Exit (0);
746 Report
.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
747 if ((i
+ 1) >= args
.Length
){
749 Environment
.Exit (1);
751 defines
.Add (args
[++i
]);
754 case "--show-counters":
755 show_counters
= true;
758 case "--expect-error": {
763 args
[++i
], NumberStyles
.AllowLeadingSign
);
764 Report
.ExpectedError
= code
;
766 Report
.Error (-14, "Invalid number specified");
777 Report
.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
778 if ((i
+ 1) >= args
.Length
){
780 Environment
.Exit (1);
782 OutputFile
= args
[++i
];
786 Report
.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
787 RootContext
.Checked
= true;
791 Report
.Stacktrace
= true;
794 case "--linkresource":
796 Report
.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
797 if ((i
+ 1) >= args
.Length
){
799 Report
.Error (5, "Missing argument to --linkres");
800 Environment
.Exit (1);
802 if (embedded_resources
== null)
803 embedded_resources
= new Resources ();
805 embedded_resources
.Add (false, args
[++i
], args
[i
]);
810 Report
.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
811 if ((i
+ 1) >= args
.Length
){
813 Report
.Error (5, "Missing argument to --resource");
814 Environment
.Exit (1);
816 if (embedded_resources
== null)
817 embedded_resources
= new Resources ();
819 embedded_resources
.Add (true, args
[++i
], args
[i
]);
823 Report
.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
824 if ((i
+ 1) >= args
.Length
){
825 Environment
.Exit (1);
829 string type
= args
[++i
];
832 RootContext
.Target
= Target
.Library
;
833 RootContext
.TargetExt
= ".dll";
837 RootContext
.Target
= Target
.Exe
;
841 RootContext
.Target
= Target
.WinExe
;
845 RootContext
.Target
= Target
.Module
;
846 RootContext
.TargetExt
= ".dll";
855 Report
.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
856 if ((i
+ 1) >= args
.Length
){
858 Environment
.Exit (1);
861 string val
= args
[++i
];
862 int idx
= val
.IndexOf ('=');
864 string alias = val
.Substring (0, idx
);
865 string assembly
= val
.Substring (idx
+ 1);
866 AddExternAlias (alias, assembly
);
870 references
.Add (val
);
874 Report
.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
875 if ((i
+ 1) >= args
.Length
){
877 Environment
.Exit (1);
879 link_paths
.Add (args
[++i
]);
883 Report
.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
884 RootContext
.StdLib
= false;
892 Report
.Warning (-29, 1, "Compatibility: Use -warnaserror: option instead of --werror");
893 Report
.WarningsAreErrors
= true;
897 Report
.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
898 if ((i
+ 1) >= args
.Length
){
900 Environment
.Exit (1);
905 warn
= Int32
.Parse (args
[++i
]);
908 Environment
.Exit (1);
910 Report
.SetIgnoreWarning (warn
);
914 Report
.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
915 if ((i
+ 1) >= args
.Length
){
918 "--wlevel requires a value from 0 to 4");
919 Environment
.Exit (1);
922 SetWarningLevel (args
[++i
]);
926 if ((i
+ 1) >= args
.Length
){
927 Report
.Error (5, "--mcs-debug requires an argument");
928 Environment
.Exit (1);
932 Report
.DebugFlags
= Int32
.Parse (args
[++i
]);
934 Report
.Error (5, "Invalid argument to --mcs-debug");
935 Environment
.Exit (1);
944 Report
.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
945 if ((i
+ 1) >= args
.Length
){
946 Report
.Error (5, "--recurse requires an argument");
947 Environment
.Exit (1);
949 CompileFiles (args
[++i
], true);
954 last_time
= first_time
= DateTime
.Now
;
961 case "--debug": case "-g":
962 Report
.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
963 want_debugging_support
= true;
967 Report
.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
968 load_default_config
= false;
976 // This parses the -arg and /arg options to the compiler, even if the strings
977 // in the following text use "/arg" on the strings.
979 static bool CSCParseOption (string option
, ref string [] args
, ref int i
)
981 int idx
= option
.IndexOf (':');
988 arg
= option
.Substring (0, idx
);
990 value = option
.Substring (idx
+ 1);
1001 RootContext
.Target
= Target
.Exe
;
1005 RootContext
.Target
= Target
.WinExe
;
1009 RootContext
.Target
= Target
.Library
;
1010 RootContext
.TargetExt
= ".dll";
1014 RootContext
.Target
= Target
.Module
;
1015 RootContext
.TargetExt
= ".netmodule";
1025 if (value.Length
== 0){
1027 Environment
.Exit (1);
1034 RootContext
.Optimize
= true;
1038 RootContext
.Optimize
= false;
1041 case "/incremental":
1042 case "/incremental+":
1043 case "/incremental-":
1051 if (value.Length
== 0){
1053 Environment
.Exit (1);
1056 defs
= value.Split (new Char
[] {';', ','}
);
1057 foreach (string d
in defs
){
1065 // We should collect data, runtime, etc and store in the file specified
1067 Console
.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1073 if (value.Length
== 0){
1075 Environment
.Exit (1);
1077 packages
= String
.Join (" ", value.Split (new Char
[] { ';', ',', '\n', '\r'}
));
1079 ProcessStartInfo pi
= new ProcessStartInfo ();
1080 pi
.FileName
= "pkg-config";
1081 pi
.RedirectStandardOutput
= true;
1082 pi
.UseShellExecute
= false;
1083 pi
.Arguments
= "--libs " + packages
;
1086 p
= Process
.Start (pi
);
1087 } catch (Exception e
) {
1088 Report
.Error (-27, "Couldn't run pkg-config: " + e
.Message
);
1089 Environment
.Exit (1);
1092 if (p
.StandardOutput
== null){
1093 Report
.Warning (-27, 1, "Specified package did not return any information");
1096 string pkgout
= p
.StandardOutput
.ReadToEnd ();
1098 if (p
.ExitCode
!= 0) {
1099 Report
.Error (-27, "Error running pkg-config. Check the above output.");
1100 Environment
.Exit (1);
1103 if (pkgout
!= null){
1104 string [] xargs
= pkgout
.Trim (new Char
[] {' ', '\n', '\r', '\t'}
).
1105 Split (new Char
[] { ' ', '\t'}
);
1106 args
= AddArgs (args
, xargs
);
1114 case "/linkresource":
1117 if (embedded_resources
== null)
1118 embedded_resources
= new Resources ();
1120 bool embeded
= arg
.StartsWith ("/r");
1121 string[] s
= value.Split (',');
1124 if (s
[0].Length
== 0)
1126 embedded_resources
.Add (embeded
, s
[0], Path
.GetFileName (s
[0]));
1129 embedded_resources
.Add (embeded
, s
[0], s
[1]);
1132 if (s
[2] != "public" && s
[2] != "private") {
1133 Report
.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s
[2]);
1136 embedded_resources
.Add (embeded
, s
[0], s
[1], s
[2] == "private");
1139 Report
.Error (-2005, "Wrong number of arguments for option `{0}'", option
);
1146 if (value.Length
== 0){
1147 Report
.Error (5, "-recurse requires an argument");
1148 Environment
.Exit (1);
1150 CompileFiles (value, true);
1154 case "/reference": {
1155 if (value.Length
== 0){
1156 Report
.Error (5, "-reference requires an argument");
1157 Environment
.Exit (1);
1160 string [] refs
= value.Split (new char [] { ';', ',' }
);
1161 foreach (string r
in refs
){
1163 int index
= val
.IndexOf ('=');
1165 string alias = r
.Substring (0, index
);
1166 string assembly
= r
.Substring (index
+ 1);
1167 AddExternAlias (alias, assembly
);
1171 references
.Add (val
);
1175 case "/addmodule": {
1176 if (value.Length
== 0){
1177 Report
.Error (5, arg
+ " requires an argument");
1178 Environment
.Exit (1);
1181 string [] refs
= value.Split (new char [] { ';', ',' }
);
1182 foreach (string r
in refs
){
1188 if (value.Length
== 0) {
1189 Report
.Error (5, arg
+ " requires an argument");
1190 Environment
.Exit (1);
1193 win32ResourceFile
= value;
1196 case "/win32icon": {
1197 if (value.Length
== 0) {
1198 Report
.Error (5, arg
+ " requires an argument");
1199 Environment
.Exit (1);
1202 win32IconFile
= value;
1206 if (value.Length
== 0){
1207 Report
.Error (2006, arg
+ " requires an argument");
1208 Environment
.Exit (1);
1210 RootContext
.Documentation
= new Documentation (value);
1216 if (value.Length
== 0){
1217 Report
.Error (5, "/lib requires an argument");
1218 Environment
.Exit (1);
1221 libdirs
= value.Split (new Char
[] { ',' }
);
1222 foreach (string dir
in libdirs
)
1223 link_paths
.Add (dir
);
1228 want_debugging_support
= false;
1233 want_debugging_support
= true;
1238 RootContext
.Checked
= true;
1242 RootContext
.Checked
= false;
1250 RootContext
.VerifyClsCompliance
= false;
1255 RootContext
.Unsafe
= true;
1259 RootContext
.Unsafe
= false;
1262 case "/warnaserror":
1263 case "/warnaserror+":
1264 Report
.WarningsAreErrors
= true;
1267 case "/warnaserror-":
1268 Report
.WarningsAreErrors
= false;
1272 SetWarningLevel (value);
1278 if (value.Length
== 0){
1279 Report
.Error (5, "/nowarn requires an argument");
1280 Environment
.Exit (1);
1283 warns
= value.Split (new Char
[] {','}
);
1284 foreach (string wc
in warns
){
1286 int warn
= Int32
.Parse (wc
);
1288 throw new ArgumentOutOfRangeException("warn");
1290 Report
.SetIgnoreWarning (warn
);
1292 Report
.Error (1904, String
.Format("`{0}' is not a valid warning number", wc
));
1299 load_default_config
= true;
1304 load_default_config
= false;
1309 Environment
.Exit(0);
1315 Environment
.Exit (0);
1320 if (value.Length
== 0){
1321 Report
.Error (5, arg
+ " requires an argument");
1322 Environment
.Exit (1);
1324 RootContext
.MainClass
= value;
1329 RootContext
.StdLib
= false;
1333 RootContext
.StdLib
= true;
1340 if (value == String
.Empty
) {
1341 Report
.Error (5, arg
+ " requires an argument");
1342 Environment
.Exit (1);
1344 RootContext
.StrongNameKeyFile
= value;
1346 case "/keycontainer":
1347 if (value == String
.Empty
) {
1348 Report
.Error (5, arg
+ " requires an argument");
1349 Environment
.Exit (1);
1351 RootContext
.StrongNameKeyContainer
= value;
1354 RootContext
.StrongNameDelaySign
= true;
1357 RootContext
.StrongNameDelaySign
= false;
1362 Console
.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1366 case "/langversion":
1367 switch (value.ToLower (CultureInfo
.InvariantCulture
)) {
1369 RootContext
.Version
= LanguageVersion
.ISO_1
;
1376 Report
.Error (1617, "Invalid option `{0}' for /langversion. It must be either `ISO-1' or `Default'", value);
1382 encoding
= new UTF8Encoding();
1385 encoding
= Encoding
.Default
;
1389 encoding
= Encoding
.GetEncoding (
1390 Int32
.Parse (value));
1392 Report
.Error (2016, "Code page `{0}' is invalid or not installed", value);
1402 static void Error_WrongOption (string option
)
1404 Report
.Error (2007, "Unrecognized command-line option: `{0}'", option
);
1407 static string [] AddArgs (string [] args
, string [] extra_args
)
1410 new_args
= new string [extra_args
.Length
+ args
.Length
];
1412 // if args contains '--' we have to take that into account
1413 // split args into first half and second half based on '--'
1414 // and add the extra_args before --
1415 int split_position
= Array
.IndexOf (args
, "--");
1416 if (split_position
!= -1)
1418 Array
.Copy (args
, new_args
, split_position
);
1419 extra_args
.CopyTo (new_args
, split_position
);
1420 Array
.Copy (args
, split_position
, new_args
, split_position
+ extra_args
.Length
, args
.Length
- split_position
);
1424 args
.CopyTo (new_args
, 0);
1425 extra_args
.CopyTo (new_args
, args
.Length
);
1431 static void AddExternAlias (string identifier
, string assembly
)
1433 if (assembly
.Length
== 0) {
1434 Report
.Error (1680, "Invalid reference alias '" + identifier
+ "='. Missing filename");
1438 if (!IsExternAliasValid (identifier
)) {
1439 Report
.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier
+ "' is not a valid identifier");
1443 // Could here hashtable throw an exception?
1444 external_aliases
[identifier
] = assembly
;
1447 static bool IsExternAliasValid (string identifier
)
1449 if (identifier
.Length
== 0)
1451 if (identifier
[0] != '_' && !Char
.IsLetter (identifier
[0]))
1454 for (int i
= 1; i
< identifier
.Length
; i
++) {
1455 char c
= identifier
[i
];
1456 if (Char
.IsLetter (c
) || Char
.IsDigit (c
))
1459 UnicodeCategory category
= Char
.GetUnicodeCategory (c
);
1460 if (category
!= UnicodeCategory
.Format
|| category
!= UnicodeCategory
.NonSpacingMark
||
1461 category
!= UnicodeCategory
.SpacingCombiningMark
||
1462 category
!= UnicodeCategory
.ConnectorPunctuation
)
1470 /// Parses the arguments, and drives the compilation
1475 /// TODO: Mostly structured to debug the compiler
1476 /// now, needs to be turned into a real driver soon.
1478 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1479 internal static bool MainDriver (string [] args
)
1482 bool parsing_options
= true;
1484 encoding
= Encoding
.Default
;
1486 references
= new ArrayList ();
1487 external_aliases
= new Hashtable ();
1488 soft_references
= new ArrayList ();
1489 modules
= new ArrayList ();
1490 link_paths
= new ArrayList ();
1492 SetupDefaultDefines ();
1497 // This is not required because Assembly.Load knows about this
1501 Hashtable response_file_list
= null;
1503 for (i
= 0; i
< args
.Length
; i
++){
1504 string arg
= args
[i
];
1505 if (arg
.Length
== 0)
1508 if (arg
.StartsWith ("@")){
1509 string [] extra_args
;
1510 string response_file
= arg
.Substring (1);
1512 if (response_file_list
== null)
1513 response_file_list
= new Hashtable ();
1515 if (response_file_list
.Contains (response_file
)){
1517 1515, "Response file `" + response_file
+
1518 "' specified multiple times");
1519 Environment
.Exit (1);
1522 response_file_list
.Add (response_file
, response_file
);
1524 extra_args
= LoadArgs (response_file
);
1525 if (extra_args
== null){
1526 Report
.Error (2011, "Unable to open response file: " +
1531 args
= AddArgs (args
, extra_args
);
1535 if (parsing_options
){
1537 parsing_options
= false;
1541 if (arg
.StartsWith ("-")){
1542 if (UnixParseOption (arg
, ref args
, ref i
))
1546 string csc_opt
= "/" + arg
.Substring (1);
1547 if (CSCParseOption (csc_opt
, ref args
, ref i
))
1550 Error_WrongOption (arg
);
1553 if (arg
[0] == '/'){
1554 if (CSCParseOption (arg
, ref args
, ref i
))
1557 // Need to skip `/home/test.cs' however /test.cs is considered as error
1558 if (arg
.Length
< 2 || arg
.IndexOf ('/', 2) == -1) {
1559 Error_WrongOption (arg
);
1566 CompileFiles (arg
, false);
1574 if (RootContext
.ToplevelTypes
.NamespaceEntry
!= null)
1575 throw new InternalErrorException ("who set it?");
1578 // If we are an exe, require a source file for the entry point
1580 if (RootContext
.Target
== Target
.Exe
|| RootContext
.Target
== Target
.WinExe
|| RootContext
.Target
== Target
.Module
){
1581 if (first_source
== null){
1582 Report
.Error (2008, "No files to compile were specified");
1589 // If there is nothing to put in the assembly, and we are not a library
1591 if (first_source
== null && embedded_resources
== null){
1592 Report
.Error (2008, "No files to compile were specified");
1596 if (Report
.Errors
> 0)
1603 // Load Core Library for default compilation
1605 if (RootContext
.StdLib
)
1606 references
.Insert (0, "mscorlib");
1608 if (load_default_config
)
1609 DefineDefaultConfig ();
1611 if (Report
.Errors
> 0){
1616 // Load assemblies required
1619 ShowTime ("Loading references");
1620 link_paths
.Add (GetSystemDir ());
1621 link_paths
.Add (Directory
.GetCurrentDirectory ());
1625 ShowTime (" References loaded");
1627 if (Report
.Errors
> 0){
1634 if (output_file
== null){
1635 if (first_source
== null){
1636 Report
.Error (1562, "If no source files are specified you must specify the output file with -out:");
1640 int pos
= first_source
.LastIndexOf ('.');
1643 output_file
= first_source
.Substring (0, pos
) + RootContext
.TargetExt
;
1645 output_file
= first_source
+ RootContext
.TargetExt
;
1648 if (!CodeGen
.Init (output_file
, output_file
, want_debugging_support
))
1651 if (RootContext
.Target
== Target
.Module
) {
1652 PropertyInfo module_only
= typeof (AssemblyBuilder
).GetProperty ("IsModuleOnly", BindingFlags
.Instance
|BindingFlags
.Public
|BindingFlags
.NonPublic
);
1653 if (module_only
== null) {
1654 Report
.RuntimeMissingSupport (Location
.Null
, "/target:module");
1655 Environment
.Exit (1);
1658 MethodInfo set_method
= module_only
.GetSetMethod (true);
1659 set_method
.Invoke (CodeGen
.Assembly
.Builder
, BindingFlags
.Default
, null, new object[]{true}
, null);
1662 RootNamespace
.Global
.AddModuleReference (CodeGen
.Module
.Builder
);
1664 if (modules
.Count
> 0) {
1665 foreach (string module
in modules
)
1666 LoadModule (module
);
1670 // Before emitting, we need to get the core
1671 // types emitted from the user defined types
1672 // or from the system ones.
1675 ShowTime ("Initializing Core Types");
1676 if (!RootContext
.StdLib
){
1677 RootContext
.ResolveCore ();
1678 if (Report
.Errors
> 0)
1682 TypeManager
.InitCoreTypes ();
1684 ShowTime (" Core Types done");
1686 CodeGen
.Module
.Resolve ();
1689 // The second pass of the compiler
1692 ShowTime ("Resolving tree");
1693 RootContext
.ResolveTree ();
1695 if (Report
.Errors
> 0)
1698 ShowTime ("Populate tree");
1699 if (!RootContext
.StdLib
)
1700 RootContext
.BootCorlib_PopulateCoreTypes ();
1701 RootContext
.PopulateTypes ();
1703 TypeManager
.InitCodeHelpers ();
1705 RootContext
.DefineTypes ();
1707 if (Report
.Errors
== 0 &&
1708 RootContext
.Documentation
!= null &&
1709 !RootContext
.Documentation
.OutputDocComment (
1714 // Verify using aliases now
1716 NamespaceEntry
.VerifyAllUsing ();
1718 if (Report
.Errors
> 0){
1722 CodeGen
.Assembly
.Resolve ();
1724 if (RootContext
.VerifyClsCompliance
) {
1725 if (CodeGen
.Assembly
.IsClsCompliant
) {
1726 AttributeTester
.VerifyModulesClsCompliance ();
1727 TypeManager
.LoadAllImportedTypes ();
1730 if (Report
.Errors
> 0)
1734 // The code generator
1737 ShowTime ("Emitting code");
1738 ShowTotalTime ("Total so far");
1739 RootContext
.EmitCode ();
1743 if (Report
.Errors
> 0){
1748 ShowTime ("Closing types");
1750 RootContext
.CloseTypes ();
1752 PEFileKinds k
= PEFileKinds
.ConsoleApplication
;
1754 switch (RootContext
.Target
) {
1755 case Target
.Library
:
1757 k
= PEFileKinds
.Dll
; break;
1759 k
= PEFileKinds
.ConsoleApplication
; break;
1761 k
= PEFileKinds
.WindowApplication
; break;
1764 if (RootContext
.NeedsEntryPoint
) {
1765 MethodInfo ep
= RootContext
.EntryPoint
;
1768 if (RootContext
.MainClass
!= null) {
1769 DeclSpace main_cont
= RootContext
.ToplevelTypes
.GetDefinition (RootContext
.MainClass
) as DeclSpace
;
1770 if (main_cont
== null) {
1771 Report
.Error (1555, "Could not find `{0}' specified for Main method", RootContext
.MainClass
);
1775 if (!(main_cont
is ClassOrStruct
)) {
1776 Report
.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext
.MainClass
);
1780 Report
.Error (1558, main_cont
.Location
, "`{0}' does not have a suitable static Main method", main_cont
.GetSignatureForError ());
1784 if (Report
.Errors
== 0)
1785 Report
.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1790 CodeGen
.Assembly
.Builder
.SetEntryPoint (ep
, k
);
1791 } else if (RootContext
.MainClass
!= null) {
1792 Report
.Error (2017, "Cannot specify -main if building a module or library");
1795 if (embedded_resources
!= null){
1796 if (RootContext
.Target
== Target
.Module
) {
1797 Report
.Error (1507, "Cannot link resource file when building a module");
1801 embedded_resources
.Emit ();
1805 // Add Win32 resources
1808 CodeGen
.Assembly
.Builder
.DefineVersionInfoResource ();
1810 if (win32ResourceFile
!= null) {
1812 CodeGen
.Assembly
.Builder
.DefineUnmanagedResource (win32ResourceFile
);
1814 catch (ArgumentException
) {
1815 Report
.RuntimeMissingSupport (Location
.Null
, "resource embeding");
1819 if (win32IconFile
!= null) {
1820 MethodInfo define_icon
= typeof (AssemblyBuilder
).GetMethod ("DefineIconResource", BindingFlags
.Instance
|BindingFlags
.Public
|BindingFlags
.NonPublic
);
1821 if (define_icon
== null) {
1822 Report
.RuntimeMissingSupport (Location
.Null
, "resource embeding");
1824 define_icon
.Invoke (CodeGen
.Assembly
.Builder
, new object [] { win32IconFile }
);
1827 if (Report
.Errors
> 0)
1830 CodeGen
.Save (output_file
);
1832 ShowTime ("Saved output");
1833 ShowTotalTime ("Total");
1836 Timer
.ShowTimers ();
1838 if (Report
.ExpectedError
!= 0) {
1839 if (Report
.Errors
== 0) {
1840 Console
.WriteLine ("Failed to report expected error " + Report
.ExpectedError
+ ".\n" +
1841 "No other errors reported.");
1843 Environment
.Exit (2);
1845 Console
.WriteLine ("Failed to report expected error " + Report
.ExpectedError
+ ".\n" +
1846 "However, other errors were reported.");
1848 Environment
.Exit (1);
1856 Console
.WriteLine ("Size of strings held: " + DeclSpace
.length
);
1857 Console
.WriteLine ("Size of strings short: " + DeclSpace
.small
);
1859 return (Report
.Errors
== 0);
1868 string FileName { get; }
1871 class EmbededResource
: IResource
1873 static MethodInfo embed_res
;
1875 static EmbededResource () {
1876 Type
[] argst
= new Type
[] {
1877 typeof (string), typeof (string), typeof (ResourceAttributes
)
1880 embed_res
= typeof (AssemblyBuilder
).GetMethod (
1881 "EmbedResourceFile", BindingFlags
.Instance
|BindingFlags
.Public
|BindingFlags
.NonPublic
,
1882 null, CallingConventions
.Any
, argst
, null);
1884 if (embed_res
== null) {
1885 Report
.RuntimeMissingSupport (Location
.Null
, "Resource embedding");
1889 readonly object[] args
;
1891 public EmbededResource (string name
, string file
, bool isPrivate
)
1893 args
= new object [3];
1896 args
[2] = isPrivate
? ResourceAttributes
.Private
: ResourceAttributes
.Public
;
1901 embed_res
.Invoke (CodeGen
.Assembly
.Builder
, args
);
1904 public string FileName
{
1906 return (string)args
[1];
1911 class LinkedResource
: IResource
1913 readonly string file
;
1914 readonly string name
;
1915 readonly ResourceAttributes attribute
;
1917 public LinkedResource (string name
, string file
, bool isPrivate
)
1921 this.attribute
= isPrivate
? ResourceAttributes
.Private
: ResourceAttributes
.Public
;
1926 CodeGen
.Assembly
.Builder
.AddResourceFile (name
, Path
.GetFileName(file
), attribute
);
1929 public string FileName
{
1937 IDictionary embedded_resources
= new HybridDictionary ();
1939 public void Add (bool embeded
, string file
, string name
)
1941 Add (embeded
, file
, name
, false);
1944 public void Add (bool embeded
, string file
, string name
, bool isPrivate
)
1946 if (embedded_resources
.Contains (name
)) {
1947 Report
.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name
);
1950 IResource r
= embeded
?
1951 (IResource
) new EmbededResource (name
, file
, isPrivate
) :
1952 new LinkedResource (name
, file
, isPrivate
);
1954 embedded_resources
.Add (name
, r
);
1959 foreach (IResource r
in embedded_resources
.Values
) {
1960 if (!File
.Exists (r
.FileName
)) {
1961 Report
.Error (1566, "Error reading resource file `{0}'", r
.FileName
);
1971 // This is the only public entry point
1973 public class CompilerCallableEntryPoint
: MarshalByRefObject
{
1974 public static bool InvokeCompiler (string [] args
, TextWriter error
)
1976 Report
.Stderr
= error
;
1978 return Driver
.MainDriver (args
) && Report
.Errors
== 0;
1981 Report
.Stderr
= Console
.Error
;
1986 public static int[] AllWarningNumbers
{
1988 return Report
.AllWarnings
;
1992 static void Reset ()
1996 RootContext
.Reset ();
1998 TypeManager
.Reset ();
1999 TypeHandle
.Reset ();
2000 RootNamespace
.Reset ();
2001 NamespaceEntry
.Reset ();
2004 AttributeTester
.Reset ();