2 // driver.cs: The compiler command line driver.
5 // Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
17 using System
.Reflection
;
18 using System
.Reflection
.Emit
;
19 using System
.Collections
.Generic
;
22 using System
.Globalization
;
23 using System
.Diagnostics
;
26 Library
, Exe
, Module
, WinExe
29 public enum Platform
{
30 AnyCPU
, X86
, X64
, IA64
34 /// The compiler driver.
39 // Assemblies references to be linked. Initialized with
41 List
<string> references
;
44 // If any of these fail, we ignore the problem. This is so
45 // that we can list all the assemblies in Windows and not fail
46 // if they are missing on Linux.
48 List
<string> soft_references
;
51 // External aliases for assemblies.
53 Dictionary
<string, string> external_aliases
;
56 // Modules to be linked
61 List
<string> link_paths
;
63 // Whether we want to only run the tokenizer
68 bool want_debugging_support
;
71 internal int fatal_errors
;
74 // Whether to load the initial config file (what CSC.RSP has by default)
76 bool load_default_config
= true;
79 // A list of resource files
81 Resources embedded_resources
;
82 string win32ResourceFile
;
88 static string output_file
;
91 // Last time we took the time
93 DateTime last_time
, first_time
;
100 readonly CompilerContext ctx
;
102 static readonly char[] argument_value_separator
= new char [] { ';', ',' }
;
104 static public void Reset ()
109 private Driver (CompilerContext ctx
)
112 encoding
= Encoding
.Default
;
115 public static Driver
Create (string[] args
, bool require_files
, ReportPrinter printer
)
117 Driver d
= new Driver (new CompilerContext (new Report (printer
)));
119 if (!d
.ParseArguments (args
, require_files
))
126 get { return ctx.Report; }
129 void ShowTime (string msg
)
134 DateTime now
= DateTime
.Now
;
135 TimeSpan span
= now
- last_time
;
139 "[{0:00}:{1:000}] {2}",
140 (int) span
.TotalSeconds
, span
.Milliseconds
, msg
);
143 void ShowTotalTime (string msg
)
148 DateTime now
= DateTime
.Now
;
149 TimeSpan span
= now
- first_time
;
153 "[{0:00}:{1:000}] {2}",
154 (int) span
.TotalSeconds
, span
.Milliseconds
, msg
);
157 void tokenize_file (CompilationUnit file
, CompilerContext ctx
)
162 input
= File
.OpenRead (file
.Name
);
164 Report
.Error (2001, "Source file `" + file
.Name
+ "' could not be found");
169 SeekableStreamReader reader
= new SeekableStreamReader (input
, encoding
);
170 Tokenizer lexer
= new Tokenizer (reader
, file
, ctx
);
171 int token
, tokens
= 0, errors
= 0;
173 while ((token
= lexer
.token ()) != Token
.EOF
){
175 if (token
== Token
.ERROR
)
178 Console
.WriteLine ("Tokenized: " + tokens
+ " found " + errors
+ " errors");
184 void Parse (CompilationUnit file
)
189 input
= File
.OpenRead (file
.Name
);
191 Report
.Error (2001, "Source file `{0}' could not be found", file
.Name
);
195 SeekableStreamReader reader
= new SeekableStreamReader (input
, encoding
);
198 if (reader
.Read () == 77 && reader
.Read () == 90) {
199 Report
.Error (2015, "Source file `{0}' is a binary file and not a text file", file
.Name
);
205 Parse (reader
, file
);
210 void Parse (SeekableStreamReader reader
, CompilationUnit file
)
212 CSharpParser parser
= new CSharpParser (reader
, file
, ctx
);
216 static void OtherFlags ()
219 "Other flags in the compiler\n" +
220 " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
221 " --lint Enhanced warnings\n" +
222 " --parse Only parses the source file\n" +
223 " --stacktrace Shows stack trace at error location\n" +
224 " --timestamp Displays time stamps of various compiler events\n" +
225 " -v Verbose parsing (for debugging the parser)\n" +
226 " --mcs-debug X Sets MCS debugging level to X\n");
232 "Mono C# compiler, Copyright 2001 - 2008 Novell, Inc.\n" +
233 "mcs [options] source-files\n" +
234 " --about About the Mono C# compiler\n" +
235 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
236 " -checked[+|-] Sets default aritmetic overflow context\n" +
237 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
238 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
239 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
240 " -debug[+|-], -g Generate debugging information\n" +
241 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
242 " -doc:FILE Process documentation comments to XML file\n" +
243 " -help Lists all compiler options (short: -?)\n" +
244 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
245 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
246 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, Default, or Future\n" +
247 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
248 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
249 " -noconfig Disables implicitly referenced assemblies\n" +
250 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
251 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
252 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
253 " -out:FILE Specifies output assembly name\n" +
255 " -pkg:P1[,Pn] References packages P1..Pn\n" +
257 " -platform:ARCH Specifies the target platform of the output assembly\n" +
258 " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
259 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
260 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
261 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
262 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
263 " KIND can be one of: exe, winexe, library, module\n" +
264 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
265 " -warnaserror[+|-] Treats all warnings as errors\n" +
266 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
267 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
268 " -help2 Shows internal compiler options\n" +
271 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
272 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
273 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
274 " -win32icon:FILE Use this icon for the output\n" +
275 " @file Read response file for more options\n\n" +
276 "Options can be of the form -option or /option");
281 Report
.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
287 "The Mono C# compiler is Copyright 2001-2008, Novell, Inc.\n\n" +
288 "The compiler source code is released under the terms of the \n"+
289 "MIT X11 or GNU GPL licenses\n\n" +
291 "For more information on Mono, visit the project Web site\n" +
292 " http://www.mono-project.com\n\n" +
294 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
295 Environment
.Exit (0);
298 public static int Main (string[] args
)
300 Location
.InEmacs
= Environment
.GetEnvironmentVariable ("EMACS") == "t";
301 var crp
= new ConsoleReportPrinter ();
302 Driver d
= Driver
.Create (args
, true, crp
);
306 crp
.Fatal
= d
.fatal_errors
;
308 if (d
.Compile () && d
.Report
.Errors
== 0) {
309 if (d
.Report
.Warnings
> 0) {
310 Console
.WriteLine ("Compilation succeeded - {0} warning(s)", d
.Report
.Warnings
);
312 Environment
.Exit (0);
317 Console
.WriteLine("Compilation failed: {0} error(s), {1} warnings",
318 d
.Report
.Errors
, d
.Report
.Warnings
);
319 Environment
.Exit (1);
323 public void LoadAssembly (string assembly
, bool soft
)
325 LoadAssembly (assembly
, null, soft
);
328 void Error6 (string name
, string log
)
330 if (log
!= null && log
.Length
> 0)
331 Report
.ExtraInformation (Location
.Null
, "Log:\n" + log
+ "\n(log related to previous ");
332 Report
.Error (6, "cannot find metadata file `{0}'", name
);
335 void Error9 (string type
, string filename
, string log
)
337 if (log
!= null && log
.Length
> 0)
338 Report
.ExtraInformation (Location
.Null
, "Log:\n" + log
+ "\n(log related to previous ");
339 Report
.Error (9, "file `{0}' has invalid `{1}' metadata", filename
, type
);
342 void BadAssembly (string filename
, string log
)
344 MethodInfo adder_method
= AssemblyClass
.AddModule_Method
;
346 if (adder_method
!= null) {
347 AssemblyName an
= new AssemblyName ();
349 AssemblyBuilder ab
= AppDomain
.CurrentDomain
.DefineDynamicAssembly (an
, AssemblyBuilderAccess
.Run
);
353 m
= adder_method
.Invoke (ab
, new object [] { filename }
);
354 } catch (TargetInvocationException ex
) {
355 throw ex
.InnerException
;
359 Report
.Error (1509, "Referenced file `{0}' is not an assembly. Consider using `-addmodule' option instead",
360 Path
.GetFileName (filename
));
363 } catch (FileNotFoundException
) {
364 // did the file get deleted during compilation? who cares? swallow the exception
365 } catch (BadImageFormatException
) {
367 } catch (FileLoadException
) {
371 Error9 ("assembly", filename
, log
);
374 public void LoadAssembly (string assembly
, string alias, bool soft
)
377 string total_log
= "";
381 char[] path_chars
= { '/', '\\' }
;
383 if (assembly
.IndexOfAny (path_chars
) != -1) {
384 a
= Assembly
.LoadFrom (assembly
);
386 string ass
= assembly
;
387 if (ass
.EndsWith (".dll") || ass
.EndsWith (".exe"))
388 ass
= assembly
.Substring (0, assembly
.Length
- 4);
389 a
= Assembly
.Load (ass
);
391 } catch (FileNotFoundException
) {
393 foreach (string dir
in link_paths
) {
394 string full_path
= Path
.Combine (dir
, assembly
);
395 if (!assembly
.EndsWith (".dll") && !assembly
.EndsWith (".exe"))
399 a
= Assembly
.LoadFrom (full_path
);
402 } catch (FileNotFoundException ff
) {
405 total_log
+= ff
.FusionLog
;
409 Error6 (assembly
, total_log
);
414 // Extern aliased refs require special handling
416 GlobalRootNamespace
.Instance
.AddAssemblyReference (a
);
418 GlobalRootNamespace
.Instance
.DefineRootNamespace (alias, a
, ctx
);
420 } catch (BadImageFormatException f
) {
421 // .NET 2.0 throws this if we try to load a module without an assembly manifest ...
422 BadAssembly (f
.FileName
, f
.FusionLog
);
423 } catch (FileLoadException f
) {
424 // ... while .NET 1.1 throws this
425 BadAssembly (f
.FileName
, f
.FusionLog
);
429 public void LoadModule (string module
)
432 string total_log
= "";
436 m
= CodeGen
.Assembly
.AddModule (module
);
437 } catch (FileNotFoundException
) {
439 foreach (string dir
in link_paths
) {
440 string full_path
= Path
.Combine (dir
, module
);
441 if (!module
.EndsWith (".netmodule"))
442 full_path
+= ".netmodule";
445 m
= CodeGen
.Assembly
.AddModule (full_path
);
448 } catch (FileNotFoundException ff
) {
449 total_log
+= ff
.FusionLog
;
453 Error6 (module
, total_log
);
458 GlobalRootNamespace
.Instance
.AddModuleReference (m
);
460 } catch (BadImageFormatException f
) {
461 Error9 ("module", f
.FileName
, f
.FusionLog
);
462 } catch (FileLoadException f
) {
463 Error9 ("module", f
.FileName
, f
.FusionLog
);
468 /// Loads all assemblies referenced on the command line
470 public void LoadReferences ()
472 link_paths
.Add (GetSystemDir ());
473 link_paths
.Add (Directory
.GetCurrentDirectory ());
476 // Load Core Library for default compilation
478 if (RootContext
.StdLib
)
479 LoadAssembly ("mscorlib", false);
481 foreach (string r
in soft_references
)
482 LoadAssembly (r
, true);
484 foreach (string r
in references
)
485 LoadAssembly (r
, false);
487 foreach (var entry
in external_aliases
)
488 LoadAssembly (entry
.Value
, entry
.Key
, false);
490 GlobalRootNamespace
.Instance
.ComputeNamespaces (ctx
);
493 static string [] LoadArgs (string file
)
496 var args
= new List
<string> ();
499 f
= new StreamReader (file
);
504 StringBuilder sb
= new StringBuilder ();
506 while ((line
= f
.ReadLine ()) != null){
509 for (int i
= 0; i
< t
; i
++){
512 if (c
== '"' || c
== '\''){
515 for (i
++; i
< t
; i
++){
522 } else if (c
== ' '){
524 args
.Add (sb
.ToString ());
531 args
.Add (sb
.ToString ());
536 return args
.ToArray ();
540 // Returns the directory where the system assemblies are installed
542 static string GetSystemDir ()
544 return Path
.GetDirectoryName (typeof (object).Assembly
.Location
);
548 // Given a path specification, splits the path from the file/pattern
550 static void SplitPathAndPattern (string spec
, out string path
, out string pattern
)
552 int p
= spec
.LastIndexOf ('/');
555 // Windows does not like /file.cs, switch that to:
560 pattern
= spec
.Substring (1);
562 path
= spec
.Substring (0, p
);
563 pattern
= spec
.Substring (p
+ 1);
568 p
= spec
.LastIndexOf ('\\');
570 path
= spec
.Substring (0, p
);
571 pattern
= spec
.Substring (p
+ 1);
579 void AddSourceFile (string f
)
581 if (first_source
== null)
584 Location
.AddFile (Report
, f
);
587 bool ParseArguments (string[] args
, bool require_files
)
589 references
= new List
<string> ();
590 external_aliases
= new Dictionary
<string, string> ();
591 soft_references
= new List
<string> ();
592 modules
= new List
<string> (2);
593 link_paths
= new List
<string> ();
595 List
<string> response_file_list
= null;
596 bool parsing_options
= true;
598 for (int i
= 0; i
< args
.Length
; i
++) {
599 string arg
= args
[i
];
603 if (arg
[0] == '@') {
604 string [] extra_args
;
605 string response_file
= arg
.Substring (1);
607 if (response_file_list
== null)
608 response_file_list
= new List
<string> ();
610 if (response_file_list
.Contains (response_file
)) {
612 1515, "Response file `" + response_file
+
613 "' specified multiple times");
617 response_file_list
.Add (response_file
);
619 extra_args
= LoadArgs (response_file
);
620 if (extra_args
== null) {
621 Report
.Error (2011, "Unable to open response file: " +
626 args
= AddArgs (args
, extra_args
);
630 if (parsing_options
) {
632 parsing_options
= false;
636 if (arg
[0] == '-') {
637 if (UnixParseOption (arg
, ref args
, ref i
))
641 string csc_opt
= "/" + arg
.Substring (1);
642 if (CSCParseOption (csc_opt
, ref args
))
645 Error_WrongOption (arg
);
648 if (arg
[0] == '/') {
649 if (CSCParseOption (arg
, ref args
))
652 // Need to skip `/home/test.cs' however /test.cs is considered as error
653 if (arg
.Length
< 2 || arg
.IndexOf ('/', 2) == -1) {
654 Error_WrongOption (arg
);
660 ProcessSourceFiles (arg
, false);
663 if (require_files
== false)
667 // If we are an exe, require a source file for the entry point
669 if (RootContext
.Target
== Target
.Exe
|| RootContext
.Target
== Target
.WinExe
|| RootContext
.Target
== Target
.Module
) {
670 if (first_source
== null) {
671 Report
.Error (2008, "No files to compile were specified");
678 // If there is nothing to put in the assembly, and we are not a library
680 if (first_source
== null && embedded_resources
== null) {
681 Report
.Error (2008, "No files to compile were specified");
690 Location
.Initialize ();
692 var cu
= Location
.SourceFiles
;
693 for (int i
= 0; i
< cu
.Count
; ++i
) {
695 tokenize_file (cu
[i
], ctx
);
702 void ProcessSourceFiles (string spec
, bool recurse
)
704 string path
, pattern
;
706 SplitPathAndPattern (spec
, out path
, out pattern
);
707 if (pattern
.IndexOf ('*') == -1){
708 AddSourceFile (spec
);
712 string [] files
= null;
714 files
= Directory
.GetFiles (path
, pattern
);
715 } catch (System
.IO
.DirectoryNotFoundException
) {
716 Report
.Error (2001, "Source file `" + spec
+ "' could not be found");
718 } catch (System
.IO
.IOException
){
719 Report
.Error (2001, "Source file `" + spec
+ "' could not be found");
722 foreach (string f
in files
) {
729 string [] dirs
= null;
732 dirs
= Directory
.GetDirectories (path
);
736 foreach (string d
in dirs
) {
738 // Don't include path in this string, as each
739 // directory entry already does
740 ProcessSourceFiles (d
+ "/" + pattern
, true);
744 public void ProcessDefaultConfig ()
746 if (!load_default_config
)
750 // For now the "default config" is harcoded into the compiler
751 // we can move this outside later
753 string [] default_config
= {
759 "System.Windows.Browser",
763 // Is it worth pre-loading all this stuff?
766 "System.Configuration.Install",
769 "System.DirectoryServices",
770 "System.Drawing.Design",
772 "System.EnterpriseServices",
775 "System.Runtime.Remoting",
776 "System.Runtime.Serialization.Formatters.Soap",
778 "System.ServiceProcess",
780 "System.Web.RegularExpressions",
781 "System.Web.Services",
782 "System.Windows.Forms"
786 soft_references
.AddRange (default_config
);
788 if (RootContext
.Version
> LanguageVersion
.ISO_2
)
789 soft_references
.Add ("System.Core");
790 if (RootContext
.Version
> LanguageVersion
.V_3
)
791 soft_references
.Add ("Microsoft.CSharp");
794 public static string OutputFile
800 return Path
.GetFileName (output_file
);
804 void SetWarningLevel (string s
)
809 level
= Int32
.Parse (s
);
812 if (level
< 0 || level
> 4){
813 Report
.Error (1900, "Warning level must be in the range 0-4");
816 Report
.WarningLevel
= level
;
819 static void Version ()
821 string version
= Assembly
.GetExecutingAssembly ().GetName ().Version
.ToString ();
822 Console
.WriteLine ("Mono C# compiler version {0}", version
);
823 Environment
.Exit (0);
827 // Currently handles the Unix-like command line options, but will be
828 // deprecated in favor of the CSCParseOption, which will also handle the
829 // options that start with a dash in the future.
831 bool UnixParseOption (string arg
, ref string [] args
, ref int i
)
835 CSharpParser
.yacc_verbose_flag
++;
846 case "--main": case "-m":
847 Report
.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
848 if ((i
+ 1) >= args
.Length
){
850 Environment
.Exit (1);
852 RootContext
.MainClass
= args
[++i
];
856 Report
.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
857 RootContext
.Unsafe
= true;
860 case "/?": case "/h": case "/help":
863 Environment
.Exit (0);
867 Report
.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
868 if ((i
+ 1) >= args
.Length
){
870 Environment
.Exit (1);
872 RootContext
.AddConditional (args
[++i
]);
881 Report
.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
882 if ((i
+ 1) >= args
.Length
){
884 Environment
.Exit (1);
886 OutputFile
= args
[++i
];
890 Report
.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
891 RootContext
.Checked
= true;
895 Report
.Printer
.Stacktrace
= true;
898 case "--linkresource":
900 Report
.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
901 if ((i
+ 1) >= args
.Length
){
903 Report
.Error (5, "Missing argument to --linkres");
904 Environment
.Exit (1);
906 if (embedded_resources
== null)
907 embedded_resources
= new Resources (ctx
);
909 embedded_resources
.Add (false, args
[++i
], args
[i
]);
914 Report
.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
915 if ((i
+ 1) >= args
.Length
){
917 Report
.Error (5, "Missing argument to --resource");
918 Environment
.Exit (1);
920 if (embedded_resources
== null)
921 embedded_resources
= new Resources (ctx
);
923 embedded_resources
.Add (true, args
[++i
], args
[i
]);
927 Report
.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
928 if ((i
+ 1) >= args
.Length
){
929 Environment
.Exit (1);
933 string type
= args
[++i
];
936 RootContext
.Target
= Target
.Library
;
937 RootContext
.TargetExt
= ".dll";
941 RootContext
.Target
= Target
.Exe
;
945 RootContext
.Target
= Target
.WinExe
;
949 RootContext
.Target
= Target
.Module
;
950 RootContext
.TargetExt
= ".dll";
959 Report
.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
960 if ((i
+ 1) >= args
.Length
){
962 Environment
.Exit (1);
965 string val
= args
[++i
];
966 int idx
= val
.IndexOf ('=');
968 string alias = val
.Substring (0, idx
);
969 string assembly
= val
.Substring (idx
+ 1);
970 AddExternAlias (alias, assembly
);
974 references
.Add (val
);
978 Report
.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
979 if ((i
+ 1) >= args
.Length
){
981 Environment
.Exit (1);
983 link_paths
.Add (args
[++i
]);
987 RootContext
.EnhancedWarnings
= true;
991 Report
.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
992 RootContext
.StdLib
= false;
996 Report
.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
997 if ((i
+ 1) >= args
.Length
){
999 Environment
.Exit (1);
1004 warn
= Int32
.Parse (args
[++i
]);
1007 Environment
.Exit (1);
1009 Report
.SetIgnoreWarning (warn
);
1013 Report
.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1014 if ((i
+ 1) >= args
.Length
){
1017 "--wlevel requires a value from 0 to 4");
1018 Environment
.Exit (1);
1021 SetWarningLevel (args
[++i
]);
1025 if ((i
+ 1) >= args
.Length
){
1026 Report
.Error (5, "--mcs-debug requires an argument");
1027 Environment
.Exit (1);
1031 Report
.DebugFlags
= Int32
.Parse (args
[++i
]);
1033 Report
.Error (5, "Invalid argument to --mcs-debug");
1034 Environment
.Exit (1);
1043 Report
.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1044 if ((i
+ 1) >= args
.Length
){
1045 Report
.Error (5, "--recurse requires an argument");
1046 Environment
.Exit (1);
1048 ProcessSourceFiles (args
[++i
], true);
1053 last_time
= first_time
= DateTime
.Now
;
1056 case "--debug": case "-g":
1057 Report
.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1058 want_debugging_support
= true;
1062 Report
.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1063 load_default_config
= false;
1067 if (arg
.StartsWith ("--fatal")){
1068 if (arg
.StartsWith ("--fatal=")){
1069 if (!Int32
.TryParse (arg
.Substring (8), out fatal_errors
))
1082 public static string GetPackageFlags (string packages
, bool fatal
, Report report
)
1084 ProcessStartInfo pi
= new ProcessStartInfo ();
1085 pi
.FileName
= "pkg-config";
1086 pi
.RedirectStandardOutput
= true;
1087 pi
.UseShellExecute
= false;
1088 pi
.Arguments
= "--libs " + packages
;
1091 p
= Process
.Start (pi
);
1092 } catch (Exception e
) {
1093 report
.Error (-27, "Couldn't run pkg-config: " + e
.Message
);
1095 Environment
.Exit (1);
1100 if (p
.StandardOutput
== null){
1101 report
.Warning (-27, 1, "Specified package did not return any information");
1105 string pkgout
= p
.StandardOutput
.ReadToEnd ();
1107 if (p
.ExitCode
!= 0) {
1108 report
.Error (-27, "Error running pkg-config. Check the above output.");
1110 Environment
.Exit (1);
1121 // This parses the -arg and /arg options to the compiler, even if the strings
1122 // in the following text use "/arg" on the strings.
1124 bool CSCParseOption (string option
, ref string [] args
)
1126 int idx
= option
.IndexOf (':');
1133 arg
= option
.Substring (0, idx
);
1135 value = option
.Substring (idx
+ 1);
1138 switch (arg
.ToLower (CultureInfo
.InvariantCulture
)){
1146 RootContext
.Target
= Target
.Exe
;
1150 RootContext
.Target
= Target
.WinExe
;
1154 RootContext
.Target
= Target
.Library
;
1155 RootContext
.TargetExt
= ".dll";
1159 RootContext
.Target
= Target
.Module
;
1160 RootContext
.TargetExt
= ".netmodule";
1170 if (value.Length
== 0){
1172 Environment
.Exit (1);
1181 RootContext
.Optimize
= true;
1186 RootContext
.Optimize
= false;
1189 // TODO: Not supported by csc 3.5+
1190 case "/incremental":
1191 case "/incremental+":
1192 case "/incremental-":
1198 if (value.Length
== 0){
1200 Environment
.Exit (1);
1203 foreach (string d
in value.Split (argument_value_separator
)) {
1204 string conditional
= d
.Trim ();
1205 if (!Tokenizer
.IsValidIdentifier (conditional
)) {
1206 Report
.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional
);
1209 RootContext
.AddConditional (conditional
);
1216 // We should collect data, runtime, etc and store in the file specified
1218 Console
.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
1224 if (value.Length
== 0){
1226 Environment
.Exit (1);
1228 packages
= String
.Join (" ", value.Split (new Char
[] { ';', ',', '\n', '\r'}
));
1229 string pkgout
= GetPackageFlags (packages
, true, Report
);
1231 if (pkgout
!= null){
1232 string [] xargs
= pkgout
.Trim (new Char
[] {' ', '\n', '\r', '\t'}
).
1233 Split (new Char
[] { ' ', '\t'}
);
1234 args
= AddArgs (args
, xargs
);
1241 case "/linkresource":
1244 if (embedded_resources
== null)
1245 embedded_resources
= new Resources (ctx
);
1247 bool embeded
= arg
[1] == 'r' || arg
[1] == 'R';
1248 string[] s
= value.Split (argument_value_separator
);
1251 if (s
[0].Length
== 0)
1253 embedded_resources
.Add (embeded
, s
[0], Path
.GetFileName (s
[0]));
1256 embedded_resources
.Add (embeded
, s
[0], s
[1]);
1259 if (s
[2] != "public" && s
[2] != "private") {
1260 Report
.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s
[2]);
1263 embedded_resources
.Add (embeded
, s
[0], s
[1], s
[2] == "private");
1266 Report
.Error (-2005, "Wrong number of arguments for option `{0}'", option
);
1273 if (value.Length
== 0){
1274 Report
.Error (5, "-recurse requires an argument");
1275 Environment
.Exit (1);
1277 ProcessSourceFiles (value, true);
1281 case "/reference": {
1282 if (value.Length
== 0){
1283 Report
.Error (5, "-reference requires an argument");
1284 Environment
.Exit (1);
1287 string[] refs
= value.Split (argument_value_separator
);
1288 foreach (string r
in refs
){
1290 int index
= val
.IndexOf ('=');
1292 string alias = r
.Substring (0, index
);
1293 string assembly
= r
.Substring (index
+ 1);
1294 AddExternAlias (alias, assembly
);
1298 if (val
.Length
!= 0)
1299 references
.Add (val
);
1303 case "/addmodule": {
1304 if (value.Length
== 0){
1305 Report
.Error (5, arg
+ " requires an argument");
1306 Environment
.Exit (1);
1309 string[] refs
= value.Split (argument_value_separator
);
1310 foreach (string r
in refs
){
1316 if (value.Length
== 0) {
1317 Report
.Error (5, arg
+ " requires an argument");
1318 Environment
.Exit (1);
1321 if (win32IconFile
!= null)
1322 Report
.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1324 win32ResourceFile
= value;
1327 case "/win32icon": {
1328 if (value.Length
== 0) {
1329 Report
.Error (5, arg
+ " requires an argument");
1330 Environment
.Exit (1);
1333 if (win32ResourceFile
!= null)
1334 Report
.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
1336 win32IconFile
= value;
1340 if (value.Length
== 0){
1341 Report
.Error (2006, arg
+ " requires an argument");
1342 Environment
.Exit (1);
1344 RootContext
.Documentation
= new Documentation (value);
1350 if (value.Length
== 0){
1351 Report
.Error (5, "/lib requires an argument");
1352 Environment
.Exit (1);
1355 libdirs
= value.Split (argument_value_separator
);
1356 foreach (string dir
in libdirs
)
1357 link_paths
.Add (dir
);
1362 want_debugging_support
= false;
1366 if (value == "full" || value == "")
1367 want_debugging_support
= true;
1372 want_debugging_support
= true;
1377 RootContext
.Checked
= true;
1381 RootContext
.Checked
= false;
1389 RootContext
.VerifyClsCompliance
= false;
1394 RootContext
.Unsafe
= true;
1398 RootContext
.Unsafe
= false;
1401 case "/warnaserror":
1402 case "/warnaserror+":
1403 if (value.Length
== 0) {
1404 Report
.WarningsAreErrors
= true;
1406 foreach (string wid
in value.Split (argument_value_separator
))
1407 Report
.AddWarningAsError (wid
);
1411 case "/warnaserror-":
1412 if (value.Length
== 0) {
1413 Report
.WarningsAreErrors
= false;
1415 foreach (string wid
in value.Split (argument_value_separator
))
1416 Report
.RemoveWarningAsError (wid
);
1421 SetWarningLevel (value);
1427 if (value.Length
== 0){
1428 Report
.Error (5, "/nowarn requires an argument");
1429 Environment
.Exit (1);
1432 warns
= value.Split (argument_value_separator
);
1433 foreach (string wc
in warns
){
1435 if (wc
.Trim ().Length
== 0)
1438 int warn
= Int32
.Parse (wc
);
1440 throw new ArgumentOutOfRangeException("warn");
1442 Report
.SetIgnoreWarning (warn
);
1444 Report
.Error (1904, String
.Format("`{0}' is not a valid warning number", wc
));
1451 load_default_config
= false;
1455 switch (value.ToLower (CultureInfo
.InvariantCulture
)) {
1457 RootContext
.Platform
= Platform
.AnyCPU
;
1460 RootContext
.Platform
= Platform
.X86
;
1463 RootContext
.Platform
= Platform
.X64
;
1466 RootContext
.Platform
= Platform
.IA64
;
1469 Report
.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
1475 // We just ignore this.
1476 case "/errorreport":
1482 Environment
.Exit(0);
1488 Environment
.Exit (0);
1493 if (value.Length
== 0){
1494 Report
.Error (5, arg
+ " requires an argument");
1495 Environment
.Exit (1);
1497 RootContext
.MainClass
= value;
1502 RootContext
.StdLib
= false;
1506 RootContext
.StdLib
= true;
1513 if (value == String
.Empty
) {
1514 Report
.Error (5, arg
+ " requires an argument");
1515 Environment
.Exit (1);
1517 RootContext
.StrongNameKeyFile
= value;
1519 case "/keycontainer":
1520 if (value == String
.Empty
) {
1521 Report
.Error (5, arg
+ " requires an argument");
1522 Environment
.Exit (1);
1524 RootContext
.StrongNameKeyContainer
= value;
1527 RootContext
.StrongNameDelaySign
= true;
1530 RootContext
.StrongNameDelaySign
= false;
1533 case "/langversion":
1534 switch (value.ToLower (CultureInfo
.InvariantCulture
)) {
1536 RootContext
.Version
= LanguageVersion
.ISO_1
;
1539 RootContext
.Version
= LanguageVersion
.Default
;
1540 RootContext
.AddConditional ("__V2__");
1543 RootContext
.Version
= LanguageVersion
.ISO_2
;
1546 RootContext
.Version
= LanguageVersion
.V_3
;
1549 RootContext
.Version
= LanguageVersion
.Future
;
1553 Report
.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
1559 encoding
= new UTF8Encoding();
1562 encoding
= Encoding
.Default
;
1566 encoding
= Encoding
.GetEncoding (
1567 Int32
.Parse (value));
1569 Report
.Error (2016, "Code page `{0}' is invalid or not installed", value);
1579 void Error_WrongOption (string option
)
1581 Report
.Error (2007, "Unrecognized command-line option: `{0}'", option
);
1584 static string [] AddArgs (string [] args
, string [] extra_args
)
1587 new_args
= new string [extra_args
.Length
+ args
.Length
];
1589 // if args contains '--' we have to take that into account
1590 // split args into first half and second half based on '--'
1591 // and add the extra_args before --
1592 int split_position
= Array
.IndexOf (args
, "--");
1593 if (split_position
!= -1)
1595 Array
.Copy (args
, new_args
, split_position
);
1596 extra_args
.CopyTo (new_args
, split_position
);
1597 Array
.Copy (args
, split_position
, new_args
, split_position
+ extra_args
.Length
, args
.Length
- split_position
);
1601 args
.CopyTo (new_args
, 0);
1602 extra_args
.CopyTo (new_args
, args
.Length
);
1608 void AddExternAlias (string identifier
, string assembly
)
1610 if (assembly
.Length
== 0) {
1611 Report
.Error (1680, "Invalid reference alias '" + identifier
+ "='. Missing filename");
1615 if (!IsExternAliasValid (identifier
)) {
1616 Report
.Error (1679, "Invalid extern alias for /reference. Alias '" + identifier
+ "' is not a valid identifier");
1620 // Could here hashtable throw an exception?
1621 external_aliases
[identifier
] = assembly
;
1624 static bool IsExternAliasValid (string identifier
)
1626 if (identifier
.Length
== 0)
1628 if (identifier
[0] != '_' && !Char
.IsLetter (identifier
[0]))
1631 for (int i
= 1; i
< identifier
.Length
; i
++) {
1632 char c
= identifier
[i
];
1633 if (Char
.IsLetter (c
) || Char
.IsDigit (c
))
1636 UnicodeCategory category
= Char
.GetUnicodeCategory (c
);
1637 if (category
!= UnicodeCategory
.Format
|| category
!= UnicodeCategory
.NonSpacingMark
||
1638 category
!= UnicodeCategory
.SpacingCombiningMark
||
1639 category
!= UnicodeCategory
.ConnectorPunctuation
)
1647 // Main compilation method
1649 public bool Compile ()
1651 // TODO: Should be passed to parser as an argument
1652 RootContext
.ToplevelTypes
= new ModuleCompiled (ctx
, RootContext
.Unsafe
);
1655 if (Report
.Errors
> 0)
1658 if (tokenize
|| parse_only
)
1661 if (RootContext
.ToplevelTypes
.NamespaceEntry
!= null)
1662 throw new InternalErrorException ("who set it?");
1664 ProcessDefaultConfig ();
1669 if (output_file
== null){
1670 if (first_source
== null){
1671 Report
.Error (1562, "If no source files are specified you must specify the output file with -out:");
1675 int pos
= first_source
.LastIndexOf ('.');
1678 output_file
= first_source
.Substring (0, pos
) + RootContext
.TargetExt
;
1680 output_file
= first_source
+ RootContext
.TargetExt
;
1683 if (!CodeGen
.Init (output_file
, output_file
, want_debugging_support
, ctx
))
1686 if (RootContext
.Target
== Target
.Module
) {
1687 PropertyInfo module_only
= typeof (AssemblyBuilder
).GetProperty ("IsModuleOnly", BindingFlags
.Instance
|BindingFlags
.Public
|BindingFlags
.NonPublic
);
1688 if (module_only
== null) {
1689 Report
.RuntimeMissingSupport (Location
.Null
, "/target:module");
1690 Environment
.Exit (1);
1693 MethodInfo set_method
= module_only
.GetSetMethod (true);
1694 set_method
.Invoke (CodeGen
.Assembly
.Builder
, BindingFlags
.Default
, null, new object[]{true}
, null);
1697 GlobalRootNamespace
.Instance
.AddModuleReference (RootContext
.ToplevelTypes
.Builder
);
1700 // Load assemblies required
1703 ShowTime ("Loading references");
1707 if (modules
.Count
> 0) {
1708 foreach (string module
in modules
)
1709 LoadModule (module
);
1713 ShowTime ("References loaded");
1715 if (!TypeManager
.InitCoreTypes (ctx
) || Report
.Errors
> 0)
1718 TypeManager
.InitOptionalCoreTypes (ctx
);
1721 ShowTime (" Core Types done");
1724 // The second pass of the compiler
1727 ShowTime ("Resolving tree");
1728 RootContext
.ResolveTree ();
1730 if (Report
.Errors
> 0)
1733 ShowTime ("Populate tree");
1734 if (!RootContext
.StdLib
)
1735 RootContext
.BootCorlib_PopulateCoreTypes ();
1736 RootContext
.PopulateTypes ();
1738 if (Report
.Errors
== 0 &&
1739 RootContext
.Documentation
!= null &&
1740 !RootContext
.Documentation
.OutputDocComment (
1741 output_file
, Report
))
1745 // Verify using aliases now
1747 NamespaceEntry
.VerifyAllUsing ();
1749 if (Report
.Errors
> 0){
1753 CodeGen
.Assembly
.Resolve ();
1755 if (RootContext
.VerifyClsCompliance
) {
1756 if (CodeGen
.Assembly
.IsClsCompliant
) {
1757 AttributeTester
.VerifyModulesClsCompliance (ctx
);
1758 TypeManager
.LoadAllImportedTypes ();
1761 if (Report
.Errors
> 0)
1765 // The code generator
1768 ShowTime ("Emitting code");
1769 ShowTotalTime ("Total so far");
1770 RootContext
.EmitCode ();
1774 if (Report
.Errors
> 0){
1779 ShowTime ("Closing types");
1781 RootContext
.CloseTypes ();
1783 PEFileKinds k
= PEFileKinds
.ConsoleApplication
;
1785 switch (RootContext
.Target
) {
1786 case Target
.Library
:
1788 k
= PEFileKinds
.Dll
; break;
1790 k
= PEFileKinds
.ConsoleApplication
; break;
1792 k
= PEFileKinds
.WindowApplication
; break;
1795 if (RootContext
.NeedsEntryPoint
) {
1796 Method ep
= RootContext
.EntryPoint
;
1799 if (RootContext
.MainClass
!= null) {
1800 DeclSpace main_cont
= RootContext
.ToplevelTypes
.GetDefinition (RootContext
.MainClass
) as DeclSpace
;
1801 if (main_cont
== null) {
1802 Report
.Error (1555, "Could not find `{0}' specified for Main method", RootContext
.MainClass
);
1806 if (!(main_cont
is ClassOrStruct
)) {
1807 Report
.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext
.MainClass
);
1811 Report
.Error (1558, main_cont
.Location
, "`{0}' does not have a suitable static Main method", main_cont
.GetSignatureForError ());
1815 if (Report
.Errors
== 0)
1816 Report
.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1821 CodeGen
.Assembly
.Builder
.SetEntryPoint (ep
.MethodBuilder
, k
);
1822 } else if (RootContext
.MainClass
!= null) {
1823 Report
.Error (2017, "Cannot specify -main if building a module or library");
1826 if (embedded_resources
!= null){
1827 if (RootContext
.Target
== Target
.Module
) {
1828 Report
.Error (1507, "Cannot link resource file when building a module");
1832 embedded_resources
.Emit ();
1836 // Add Win32 resources
1839 if (win32ResourceFile
!= null) {
1841 CodeGen
.Assembly
.Builder
.DefineUnmanagedResource (win32ResourceFile
);
1842 } catch (ArgumentException
) {
1843 Report
.RuntimeMissingSupport (Location
.Null
, "resource embedding ");
1846 CodeGen
.Assembly
.Builder
.DefineVersionInfoResource ();
1849 if (win32IconFile
!= null) {
1850 MethodInfo define_icon
= typeof (AssemblyBuilder
).GetMethod ("DefineIconResource", BindingFlags
.Instance
| BindingFlags
.Public
| BindingFlags
.NonPublic
);
1851 if (define_icon
== null) {
1852 Report
.RuntimeMissingSupport (Location
.Null
, "resource embedding");
1854 define_icon
.Invoke (CodeGen
.Assembly
.Builder
, new object [] { win32IconFile }
);
1858 if (Report
.Errors
> 0)
1861 CodeGen
.Save (output_file
, want_debugging_support
, Report
);
1863 ShowTime ("Saved output");
1864 ShowTotalTime ("Total");
1867 Timer
.ShowTimers ();
1870 Console
.WriteLine ("Size of strings held: " + DeclSpace
.length
);
1871 Console
.WriteLine ("Size of strings short: " + DeclSpace
.small
);
1873 return (Report
.Errors
== 0);
1881 void Emit (CompilerContext cc
);
1882 string FileName { get; }
1885 class EmbededResource
: IResource
1887 static MethodInfo embed_res
;
1888 readonly object[] args
;
1890 public EmbededResource (string name
, string file
, bool isPrivate
)
1892 args
= new object [3];
1895 args
[2] = isPrivate
? ResourceAttributes
.Private
: ResourceAttributes
.Public
;
1898 public void Emit (CompilerContext cc
)
1900 if (embed_res
== null) {
1901 var argst
= new [] {
1902 typeof (string), typeof (string), typeof (ResourceAttributes
)
1905 embed_res
= typeof (AssemblyBuilder
).GetMethod (
1906 "EmbedResourceFile", BindingFlags
.Instance
| BindingFlags
.Public
| BindingFlags
.NonPublic
,
1907 null, CallingConventions
.Any
, argst
, null);
1909 if (embed_res
== null) {
1910 cc
.Report
.RuntimeMissingSupport (Location
.Null
, "Resource embedding");
1914 embed_res
.Invoke (CodeGen
.Assembly
.Builder
, args
);
1917 public string FileName
{
1919 return (string)args
[1];
1924 class LinkedResource
: IResource
1926 readonly string file
;
1927 readonly string name
;
1928 readonly ResourceAttributes attribute
;
1930 public LinkedResource (string name
, string file
, bool isPrivate
)
1934 this.attribute
= isPrivate
? ResourceAttributes
.Private
: ResourceAttributes
.Public
;
1937 public void Emit (CompilerContext cc
)
1939 CodeGen
.Assembly
.Builder
.AddResourceFile (name
, Path
.GetFileName(file
), attribute
);
1942 public string FileName
{
1950 Dictionary
<string, IResource
> embedded_resources
= new Dictionary
<string, IResource
> ();
1951 readonly CompilerContext ctx
;
1953 public Resources (CompilerContext ctx
)
1958 public void Add (bool embeded
, string file
, string name
)
1960 Add (embeded
, file
, name
, false);
1963 public void Add (bool embeded
, string file
, string name
, bool isPrivate
)
1965 if (embedded_resources
.ContainsKey (name
)) {
1966 ctx
.Report
.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name
);
1969 IResource r
= embeded
?
1970 (IResource
) new EmbededResource (name
, file
, isPrivate
) :
1971 new LinkedResource (name
, file
, isPrivate
);
1973 embedded_resources
.Add (name
, r
);
1978 foreach (IResource r
in embedded_resources
.Values
) {
1979 if (!File
.Exists (r
.FileName
)) {
1980 ctx
.Report
.Error (1566, "Error reading resource file `{0}'", r
.FileName
);
1990 // This is the only public entry point
1992 public class CompilerCallableEntryPoint
: MarshalByRefObject
{
1993 public static bool InvokeCompiler (string [] args
, TextWriter error
)
1996 StreamReportPrinter srp
= new StreamReportPrinter (error
);
1997 Driver d
= Driver
.Create (args
, true, srp
);
2001 return d
.Compile () && srp
.ErrorsCount
== 0;
2007 public static int[] AllWarningNumbers
{
2009 return Report
.AllWarnings
;
2013 public static void Reset ()
2018 public static void PartialReset ()
2023 public static void Reset (bool full_flag
)
2026 CSharpParser
.yacc_verbose_flag
= 0;
2027 RootContext
.Reset (full_flag
);
2029 TypeManager
.Reset ();
2030 PredefinedAttributes
.Reset ();
2031 TypeHandle
.Reset ();
2034 GlobalRootNamespace
.Reset ();
2036 NamespaceEntry
.Reset ();
2039 AttributeTester
.Reset ();
2040 AnonymousTypeClass
.Reset ();
2041 AnonymousMethodBody
.Reset ();
2042 AnonymousMethodStorey
.Reset ();
2043 SymbolWriter
.Reset ();
2045 Linq
.QueryBlock
.TransparentParameter
.Reset ();
2048 DynamicExpressionStatement
.Reset ();