2 // settings.cs: All compiler settings
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Ravi Pratap (ravi@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
9 // Dual licensed under the terms of the MIT X11 or GNU GPL
11 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
12 // Copyright 2004-2008 Novell, Inc
13 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
16 using System.Collections.Generic;
19 using System.Globalization;
22 namespace Mono.CSharp {
24 public enum LanguageVersion
33 Default = LanguageVersion.Future,
36 public enum RuntimeVersion
45 Library, Exe, Module, WinExe
58 public class CompilerSettings
61 public Platform Platform;
62 public string TargetExt;
63 public bool VerifyClsCompliance;
65 public LanguageVersion Version;
66 public bool EnhancedWarnings;
67 public bool LoadDefaultReferences;
68 public string SdkVersion;
70 public string StrongNameKeyFile;
71 public string StrongNameKeyContainer;
72 public bool StrongNameDelaySign;
76 public bool WarningsAreErrors;
77 public int WarningLevel;
80 // Assemblies references to be loaded
82 public List<string> AssemblyReferences;
85 // External aliases for assemblies
87 public List<Tuple<string, string>> AssemblyReferencesAliases;
90 // Modules to be embedded
92 public List<string> Modules;
95 // Lookup paths for referenced assemblies
97 public List<string> ReferencesLookupPaths;
102 public Encoding Encoding;
105 // If set, enable XML documentation generation
107 public string DocumentationFile;
109 public string MainClass;
114 public string OutputFile;
117 // The default compiler checked state
122 // If true, the compiler is operating in statement mode,
123 // this currently turns local variable declaration into
124 // static variables of a class
126 public bool StatementMode; // TODO: SUPER UGLY
129 // Whether to allow Unsafe code
133 public string Win32ResourceFile;
134 public string Win32IconFile;
137 // A list of resource files for embedding
139 public List<AssemblyResource> Resources;
141 public bool GenerateDebugInfo;
143 #region Compiler debug flags only
144 public bool ParseOnly, TokenizeOnly, Timestamps;
145 public int DebugFlags;
146 public int VerboseParserFlag;
147 public int FatalCounter;
148 public bool Stacktrace;
149 public bool BreakOnInternalError;
152 public bool ShowFullPaths;
155 // Whether we are being linked against the standard libraries.
156 // This is only used to tell whether `System.Object' should
157 // have a base class or not.
161 public RuntimeVersion StdLibRuntimeVersion;
163 public string RuntimeMetadataVersion;
165 public bool WriteMetadataOnly;
167 readonly List<string> conditional_symbols;
169 readonly List<SourceFile> source_files;
171 List<int> warnings_as_error;
172 List<int> warnings_only;
173 HashSet<int> warning_ignore_table;
175 public CompilerSettings ()
180 Platform = Platform.AnyCPU;
181 Version = LanguageVersion.Default;
182 VerifyClsCompliance = true;
183 Encoding = Encoding.UTF8;
184 LoadDefaultReferences = true;
185 StdLibRuntimeVersion = RuntimeVersion.v4;
188 // Default to 1 or mdb files would be platform speficic
191 AssemblyReferences = new List<string> ();
192 AssemblyReferencesAliases = new List<Tuple<string, string>> ();
193 Modules = new List<string> ();
194 ReferencesLookupPaths = new List<string> ();
196 conditional_symbols = new List<string> ();
198 // Add default mcs define
200 conditional_symbols.Add ("__MonoCS__");
202 source_files = new List<SourceFile> ();
207 public SourceFile FirstSourceFile {
209 return source_files.Count > 0 ? source_files [0] : null;
213 public bool HasKeyFileOrContainer {
215 return StrongNameKeyFile != null || StrongNameKeyContainer != null;
219 public bool NeedsEntryPoint {
221 return Target == Target.Exe || Target == Target.WinExe;
225 public List<SourceFile> SourceFiles {
233 public void AddConditionalSymbol (string symbol)
235 if (!conditional_symbols.Contains (symbol))
236 conditional_symbols.Add (symbol);
239 public void AddWarningAsError (int id)
241 if (warnings_as_error == null)
242 warnings_as_error = new List<int> ();
244 warnings_as_error.Add (id);
247 public void AddWarningOnly (int id)
249 if (warnings_only == null)
250 warnings_only = new List<int> ();
252 warnings_only.Add (id);
255 public bool IsConditionalSymbolDefined (string symbol)
257 return conditional_symbols.Contains (symbol);
260 public bool IsWarningAsError (int code)
262 bool is_error = WarningsAreErrors;
264 // Check specific list
265 if (warnings_as_error != null)
266 is_error |= warnings_as_error.Contains (code);
268 // Ignore excluded warnings
269 if (warnings_only != null && warnings_only.Contains (code))
275 public bool IsWarningEnabled (int code, int level)
277 if (WarningLevel < level)
280 return !IsWarningDisabledGlobally (code);
283 public bool IsWarningDisabledGlobally (int code)
285 return warning_ignore_table != null && warning_ignore_table.Contains (code);
288 public void SetIgnoreWarning (int code)
290 if (warning_ignore_table == null)
291 warning_ignore_table = new HashSet<int> ();
293 warning_ignore_table.Add (code);
297 public class CommandLineParser
307 static readonly char[] argument_value_separator = { ';', ',' };
308 static readonly char[] numeric_value_separator = { ';', ',', ' ' };
310 readonly TextWriter output;
311 readonly Report report;
314 Dictionary<string, int> source_file_index;
316 public event Func<string[], int, int> UnknownOptionHandler;
318 CompilerSettings parser_settings;
320 public CommandLineParser (TextWriter errorOutput)
321 : this (errorOutput, Console.Out)
325 public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
327 var rp = new StreamReportPrinter (errorOutput);
329 parser_settings = new CompilerSettings ();
330 report = new Report (new CompilerContext (parser_settings, rp), rp);
331 this.output = messagesOutput;
334 public bool HasBeenStopped {
336 return stop_argument;
343 "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
344 "The compiler source code is released under the terms of the \n" +
345 "MIT X11 or GNU GPL licenses\n\n" +
347 "For more information on Mono, visit the project Web site\n" +
348 " http://www.mono-project.com\n\n" +
350 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
353 public CompilerSettings ParseArguments (string[] args)
355 CompilerSettings settings = new CompilerSettings ();
356 if (!ParseArguments (settings, args))
362 public bool ParseArguments (CompilerSettings settings, string[] args)
364 if (settings == null)
365 throw new ArgumentNullException ("settings");
367 List<string> response_file_list = null;
368 bool parsing_options = true;
369 stop_argument = false;
370 source_file_index = new Dictionary<string, int> ();
372 for (int i = 0; i < args.Length; i++) {
373 string arg = args[i];
379 string response_file = arg.Substring (1);
381 if (response_file_list == null)
382 response_file_list = new List<string> ();
384 if (response_file_list.Contains (response_file)) {
385 report.Error (1515, "Response file `{0}' specified multiple times", response_file);
389 response_file_list.Add (response_file);
391 extra_args = LoadArgs (response_file);
392 if (extra_args == null) {
393 report.Error (2011, "Unable to open response file: " + response_file);
397 args = AddArgs (args, extra_args);
401 if (parsing_options) {
403 parsing_options = false;
407 bool dash_opt = arg[0] == '-';
408 bool slash_opt = arg[0] == '/';
410 switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
411 case ParseResult.Error:
412 case ParseResult.Success:
414 case ParseResult.Stop:
415 stop_argument = true;
417 case ParseResult.UnknownOption:
418 if (UnknownOptionHandler != null) {
419 var ret = UnknownOptionHandler (args, i);
429 if (dash_opt || slash_opt) {
431 string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
432 switch (ParseOption (csc_opt, ref args, settings)) {
433 case ParseResult.Error:
434 case ParseResult.Success:
436 case ParseResult.UnknownOption:
437 // Need to skip `/home/test.cs' however /test.cs is considered as error
438 if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
441 if (UnknownOptionHandler != null) {
442 var ret = UnknownOptionHandler (args, i);
449 Error_WrongOption (arg);
452 case ParseResult.Stop:
453 stop_argument = true;
459 ProcessSourceFiles (arg, false, settings.SourceFiles);
462 return report.Errors == 0;
465 void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
467 string path, pattern;
469 SplitPathAndPattern (spec, out path, out pattern);
470 if (pattern.IndexOf ('*') == -1) {
471 AddSourceFile (spec, sourceFiles);
477 files = Directory.GetFiles (path, pattern);
478 } catch (System.IO.DirectoryNotFoundException) {
479 report.Error (2001, "Source file `" + spec + "' could not be found");
481 } catch (System.IO.IOException) {
482 report.Error (2001, "Source file `" + spec + "' could not be found");
485 foreach (string f in files) {
486 AddSourceFile (f, sourceFiles);
492 string[] dirs = null;
495 dirs = Directory.GetDirectories (path);
499 foreach (string d in dirs) {
501 // Don't include path in this string, as each
502 // directory entry already does
503 ProcessSourceFiles (d + "/" + pattern, true, sourceFiles);
507 static string[] AddArgs (string[] args, string[] extra_args)
510 new_args = new string[extra_args.Length + args.Length];
512 // if args contains '--' we have to take that into account
513 // split args into first half and second half based on '--'
514 // and add the extra_args before --
515 int split_position = Array.IndexOf (args, "--");
516 if (split_position != -1) {
517 Array.Copy (args, new_args, split_position);
518 extra_args.CopyTo (new_args, split_position);
519 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
521 args.CopyTo (new_args, 0);
522 extra_args.CopyTo (new_args, args.Length);
528 void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
530 if (assembly.Length == 0) {
531 report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
535 if (!IsExternAliasValid (alias)) {
536 report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
540 settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
543 void AddResource (AssemblyResource res, CompilerSettings settings)
545 if (settings.Resources == null) {
546 settings.Resources = new List<AssemblyResource> ();
547 settings.Resources.Add (res);
551 if (settings.Resources.Contains (res)) {
552 report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
556 settings.Resources.Add (res);
559 void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
561 string path = Path.GetFullPath (fileName);
564 if (source_file_index.TryGetValue (path, out index)) {
565 string other_name = sourceFiles[index - 1].Name;
566 if (fileName.Equals (other_name))
567 report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
569 report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", fileName, other_name, path);
574 var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
575 sourceFiles.Add (unit);
576 source_file_index.Add (path, unit.Index);
579 public bool ProcessWarningsList (string text, Action<int> action)
582 foreach (string wid in text.Split (numeric_value_separator, StringSplitOptions.RemoveEmptyEntries)) {
584 if (!int.TryParse (wid, NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out id)) {
585 report.Error (1904, "`{0}' is not a valid warning number", wid);
590 if (report.CheckWarningCode (id, Location.Null))
597 void Error_RequiresArgument (string option)
599 report.Error (2006, "Missing argument for `{0}' option", option);
602 void Error_RequiresFileName (string option)
604 report.Error (2005, "Missing file specification for `{0}' option", option);
607 void Error_WrongOption (string option)
609 report.Error (2007, "Unrecognized command-line option: `{0}'", option);
612 static bool IsExternAliasValid (string identifier)
614 return Tokenizer.IsValidIdentifier (identifier);
617 static string[] LoadArgs (string file)
620 var args = new List<string> ();
623 f = new StreamReader (file);
628 StringBuilder sb = new StringBuilder ();
630 while ((line = f.ReadLine ()) != null) {
633 for (int i = 0; i < t; i++) {
636 if (c == '"' || c == '\'') {
639 for (i++; i < t; i++) {
646 } else if (c == ' ') {
648 args.Add (sb.ToString ());
655 args.Add (sb.ToString ());
660 return args.ToArray ();
666 "Other flags in the compiler\n" +
667 " --fatal[=COUNT] Makes error after COUNT fatal\n" +
668 " --lint Enhanced warnings\n" +
669 " --metadata-only Produced assembly will contain metadata only\n" +
670 " --parse Only parses the source file\n" +
671 " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
672 " --stacktrace Shows stack trace at error location\n" +
673 " --timestamp Displays time stamps of various compiler events\n" +
674 " -v Verbose parsing (for debugging the parser)\n" +
675 " --mcs-debug X Sets MCS debugging level to X\n" +
676 " --break-on-ice Breaks compilation on internal compiler error");
680 // This parses the -arg and /arg options to the compiler, even if the strings
681 // in the following text use "/arg" on the strings.
683 ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
685 int idx = option.IndexOf (':');
692 arg = option.Substring (0, idx);
694 value = option.Substring (idx + 1);
697 switch (arg.ToLowerInvariant ()) {
699 return ParseResult.Success;
705 settings.Target = Target.Exe;
709 settings.Target = Target.WinExe;
713 settings.Target = Target.Library;
714 settings.TargetExt = ".dll";
718 settings.Target = Target.Module;
719 settings.TargetExt = ".netmodule";
723 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
724 return ParseResult.Error;
726 return ParseResult.Success;
729 if (value.Length == 0) {
730 Error_RequiresFileName (option);
731 return ParseResult.Error;
733 settings.OutputFile = value;
734 return ParseResult.Success;
740 settings.Optimize = true;
741 return ParseResult.Success;
745 settings.Optimize = false;
746 return ParseResult.Success;
748 // TODO: Not supported by csc 3.5+
750 case "/incremental+":
751 case "/incremental-":
753 return ParseResult.Success;
757 if (value.Length == 0) {
758 Error_RequiresArgument (option);
759 return ParseResult.Error;
762 foreach (string d in value.Split (argument_value_separator)) {
763 string conditional = d.Trim ();
764 if (!Tokenizer.IsValidIdentifier (conditional)) {
765 report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
769 settings.AddConditionalSymbol (conditional);
771 return ParseResult.Success;
776 // We should collect data, runtime, etc and store in the file specified
778 output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
779 return ParseResult.Success;
784 if (value.Length == 0) {
785 Error_RequiresArgument (option);
786 return ParseResult.Error;
788 packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
789 string pkgout = Driver.GetPackageFlags (packages, report);
792 return ParseResult.Error;
794 string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
795 args = AddArgs (args, xargs);
796 return ParseResult.Success;
800 case "/linkresource":
803 AssemblyResource res = null;
804 string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
807 if (s[0].Length == 0)
809 res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
812 res = new AssemblyResource (s[0], s[1]);
815 if (s[2] != "public" && s[2] != "private") {
816 report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
817 return ParseResult.Error;
819 res = new AssemblyResource (s[0], s[1], s[2] == "private");
822 report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
823 return ParseResult.Error;
827 res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
828 AddResource (res, settings);
831 return ParseResult.Success;
834 if (value.Length == 0) {
835 Error_RequiresFileName (option);
836 return ParseResult.Error;
838 ProcessSourceFiles (value, true, settings.SourceFiles);
839 return ParseResult.Success;
843 if (value.Length == 0) {
844 Error_RequiresFileName (option);
845 return ParseResult.Error;
848 string[] refs = value.Split (argument_value_separator);
849 foreach (string r in refs) {
854 int index = val.IndexOf ('=');
856 string alias = r.Substring (0, index);
857 string assembly = r.Substring (index + 1);
858 AddAssemblyReference (alias, assembly, settings);
859 if (refs.Length != 1) {
860 report.Error (2034, "Cannot specify multiple aliases using single /reference option");
861 return ParseResult.Error;
864 settings.AssemblyReferences.Add (val);
867 return ParseResult.Success;
870 if (value.Length == 0) {
871 Error_RequiresFileName (option);
872 return ParseResult.Error;
875 string[] refs = value.Split (argument_value_separator);
876 foreach (string r in refs) {
877 settings.Modules.Add (r);
879 return ParseResult.Success;
882 if (value.Length == 0) {
883 Error_RequiresFileName (option);
884 return ParseResult.Error;
887 if (settings.Win32IconFile != null)
888 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
890 settings.Win32ResourceFile = value;
891 return ParseResult.Success;
894 if (value.Length == 0) {
895 Error_RequiresFileName (option);
896 return ParseResult.Error;
899 if (settings.Win32ResourceFile != null)
900 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
902 settings.Win32IconFile = value;
903 return ParseResult.Success;
906 if (value.Length == 0) {
907 Error_RequiresFileName (option);
908 return ParseResult.Error;
911 settings.DocumentationFile = value;
912 return ParseResult.Success;
917 if (value.Length == 0) {
918 return ParseResult.Error;
921 libdirs = value.Split (argument_value_separator);
922 foreach (string dir in libdirs)
923 settings.ReferencesLookupPaths.Add (dir);
924 return ParseResult.Success;
928 settings.GenerateDebugInfo = false;
929 return ParseResult.Success;
932 if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
933 settings.GenerateDebugInfo = true;
934 return ParseResult.Success;
937 if (value.Length > 0) {
938 report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
940 Error_RequiresArgument (option);
943 return ParseResult.Error;
946 settings.GenerateDebugInfo = true;
947 return ParseResult.Success;
951 settings.Checked = true;
952 return ParseResult.Success;
955 settings.Checked = false;
956 return ParseResult.Success;
960 settings.VerifyClsCompliance = true;
961 return ParseResult.Success;
964 settings.VerifyClsCompliance = false;
965 return ParseResult.Success;
969 settings.Unsafe = true;
970 return ParseResult.Success;
973 settings.Unsafe = false;
974 return ParseResult.Success;
977 case "/warnaserror+":
978 if (value.Length == 0) {
979 settings.WarningsAreErrors = true;
980 parser_settings.WarningsAreErrors = true;
982 if (!ProcessWarningsList (value, settings.AddWarningAsError))
983 return ParseResult.Error;
985 return ParseResult.Success;
987 case "/warnaserror-":
988 if (value.Length == 0) {
989 settings.WarningsAreErrors = false;
991 if (!ProcessWarningsList (value, settings.AddWarningOnly))
992 return ParseResult.Error;
994 return ParseResult.Success;
998 if (value.Length == 0) {
999 Error_RequiresArgument (option);
1000 return ParseResult.Error;
1003 SetWarningLevel (value, settings);
1004 return ParseResult.Success;
1007 if (value.Length == 0) {
1008 Error_RequiresArgument (option);
1009 return ParseResult.Error;
1012 if (!ProcessWarningsList (value, settings.SetIgnoreWarning))
1013 return ParseResult.Error;
1015 return ParseResult.Success;
1018 settings.LoadDefaultReferences = false;
1019 return ParseResult.Success;
1022 if (value.Length == 0) {
1023 Error_RequiresArgument (option);
1024 return ParseResult.Error;
1027 switch (value.ToLowerInvariant ()) {
1029 settings.Platform = Platform.Arm;
1032 settings.Platform = Platform.AnyCPU;
1035 settings.Platform = Platform.X86;
1038 settings.Platform = Platform.X64;
1041 settings.Platform = Platform.IA64;
1043 case "anycpu32bitpreferred":
1044 settings.Platform = Platform.AnyCPU32Preferred;
1047 report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
1049 return ParseResult.Error;
1052 return ParseResult.Success;
1055 if (value.Length == 0) {
1056 Error_RequiresArgument (option);
1057 return ParseResult.Error;
1060 settings.SdkVersion = value;
1061 return ParseResult.Success;
1063 // We just ignore this.
1064 case "/errorreport":
1066 if (value.Length == 0) {
1067 Error_RequiresArgument (option);
1068 return ParseResult.Error;
1071 return ParseResult.Success;
1073 case "/helpinternal":
1075 return ParseResult.Stop;
1080 return ParseResult.Stop;
1084 if (value.Length == 0) {
1085 Error_RequiresArgument (option);
1086 return ParseResult.Error;
1088 settings.MainClass = value;
1089 return ParseResult.Success;
1093 settings.StdLib = false;
1094 return ParseResult.Success;
1097 settings.StdLib = true;
1098 return ParseResult.Success;
1101 settings.ShowFullPaths = true;
1102 return ParseResult.Success;
1105 if (value.Length == 0) {
1106 Error_RequiresFileName (option);
1107 return ParseResult.Error;
1110 settings.StrongNameKeyFile = value;
1111 return ParseResult.Success;
1113 case "/keycontainer":
1114 if (value.Length == 0) {
1115 Error_RequiresArgument (option);
1116 return ParseResult.Error;
1119 settings.StrongNameKeyContainer = value;
1120 return ParseResult.Success;
1124 settings.StrongNameDelaySign = true;
1125 return ParseResult.Success;
1128 settings.StrongNameDelaySign = false;
1129 return ParseResult.Success;
1131 case "/langversion":
1132 if (value.Length == 0) {
1133 Error_RequiresArgument (option);
1134 return ParseResult.Error;
1137 switch (value.ToLowerInvariant ()) {
1139 settings.Version = LanguageVersion.ISO_1;
1140 return ParseResult.Success;
1142 settings.Version = LanguageVersion.Default;
1143 return ParseResult.Success;
1145 settings.Version = LanguageVersion.ISO_2;
1146 return ParseResult.Success;
1148 settings.Version = LanguageVersion.V_3;
1149 return ParseResult.Success;
1151 settings.Version = LanguageVersion.V_4;
1152 return ParseResult.Success;
1154 settings.Version = LanguageVersion.V_5;
1155 return ParseResult.Success;
1157 settings.Version = LanguageVersion.Future;
1158 return ParseResult.Success;
1161 report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
1162 return ParseResult.Error;
1165 if (value.Length == 0) {
1166 Error_RequiresArgument (option);
1167 return ParseResult.Error;
1172 settings.Encoding = Encoding.UTF8;
1175 settings.Encoding = Encoding.Default;
1179 settings.Encoding = Encoding.GetEncoding (int.Parse (value));
1181 report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1183 return ParseResult.Error;
1185 return ParseResult.Success;
1187 case "runtimemetadataversion":
1188 if (value.Length == 0) {
1189 Error_RequiresArgument (option);
1190 return ParseResult.Error;
1193 settings.RuntimeMetadataVersion = value;
1194 return ParseResult.Success;
1197 return ParseResult.UnknownOption;
1202 // Currently handles the Unix-like command line options, but will be
1203 // deprecated in favor of the CSCParseOption, which will also handle the
1204 // options that start with a dash in the future.
1206 ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
1210 settings.VerboseParserFlag++;
1211 return ParseResult.Success;
1215 return ParseResult.Stop;
1218 settings.ParseOnly = true;
1219 return ParseResult.Success;
1221 case "--main": case "-m":
1222 report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
1223 if ((i + 1) >= args.Length){
1224 Error_RequiresArgument (arg);
1225 return ParseResult.Error;
1227 settings.MainClass = args[++i];
1228 return ParseResult.Success;
1231 report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
1232 settings.Unsafe = true;
1233 return ParseResult.Success;
1235 case "/?": case "/h": case "/help":
1238 return ParseResult.Stop;
1241 report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
1242 if ((i + 1) >= args.Length){
1243 Error_RequiresArgument (arg);
1244 return ParseResult.Error;
1247 settings.AddConditionalSymbol (args [++i]);
1248 return ParseResult.Success;
1251 settings.TokenizeOnly = true;
1252 return ParseResult.Success;
1256 report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
1257 if ((i + 1) >= args.Length){
1258 Error_RequiresArgument (arg);
1259 return ParseResult.Error;
1261 settings.OutputFile = args[++i];
1262 return ParseResult.Success;
1265 report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
1266 settings.Checked = true;
1267 return ParseResult.Success;
1269 case "--stacktrace":
1270 settings.Stacktrace = true;
1271 return ParseResult.Success;
1273 case "--linkresource":
1275 report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
1276 if ((i + 1) >= args.Length){
1277 Error_RequiresArgument (arg);
1278 return ParseResult.Error;
1281 AddResource (new AssemblyResource (args[++i], args[i]), settings);
1282 return ParseResult.Success;
1286 report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
1287 if ((i + 1) >= args.Length){
1288 Error_RequiresArgument (arg);
1289 return ParseResult.Error;
1292 AddResource (new AssemblyResource (args[++i], args[i], true), settings);
1293 return ParseResult.Success;
1296 report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
1297 if ((i + 1) >= args.Length){
1298 Error_RequiresArgument (arg);
1299 return ParseResult.Error;
1302 string type = args [++i];
1305 settings.Target = Target.Library;
1306 settings.TargetExt = ".dll";
1310 settings.Target = Target.Exe;
1314 settings.Target = Target.WinExe;
1318 settings.Target = Target.Module;
1319 settings.TargetExt = ".dll";
1322 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
1325 return ParseResult.Success;
1328 report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
1329 if ((i + 1) >= args.Length){
1330 Error_RequiresArgument (arg);
1331 return ParseResult.Error;
1334 string val = args [++i];
1335 int idx = val.IndexOf ('=');
1337 string alias = val.Substring (0, idx);
1338 string assembly = val.Substring (idx + 1);
1339 AddAssemblyReference (alias, assembly, settings);
1340 return ParseResult.Success;
1343 settings.AssemblyReferences.Add (val);
1344 return ParseResult.Success;
1347 report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
1348 if ((i + 1) >= args.Length){
1349 Error_RequiresArgument (arg);
1350 return ParseResult.Error;
1352 settings.ReferencesLookupPaths.Add (args [++i]);
1353 return ParseResult.Success;
1356 settings.EnhancedWarnings = true;
1357 return ParseResult.Success;
1360 report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1361 settings.StdLib = false;
1362 return ParseResult.Success;
1365 report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1366 if ((i + 1) >= args.Length){
1367 Error_RequiresArgument (arg);
1368 return ParseResult.Error;
1373 warn = int.Parse (args [++i]);
1376 Environment.Exit (1);
1378 settings.SetIgnoreWarning (warn);
1379 return ParseResult.Success;
1382 report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1383 if ((i + 1) >= args.Length){
1384 Error_RequiresArgument (arg);
1385 return ParseResult.Error;
1388 SetWarningLevel (args [++i], settings);
1389 return ParseResult.Success;
1392 if ((i + 1) >= args.Length){
1393 Error_RequiresArgument (arg);
1394 return ParseResult.Error;
1398 settings.DebugFlags = int.Parse (args [++i]);
1400 Error_RequiresArgument (arg);
1401 return ParseResult.Error;
1404 return ParseResult.Success;
1408 return ParseResult.Stop;
1411 report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1412 if ((i + 1) >= args.Length){
1413 Error_RequiresArgument (arg);
1414 return ParseResult.Error;
1416 ProcessSourceFiles (args [++i], true, settings.SourceFiles);
1417 return ParseResult.Success;
1420 settings.Timestamps = true;
1421 return ParseResult.Success;
1423 case "--debug": case "-g":
1424 report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1425 settings.GenerateDebugInfo = true;
1426 return ParseResult.Success;
1429 report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1430 settings.LoadDefaultReferences = false;
1431 return ParseResult.Success;
1433 case "--metadata-only":
1434 settings.WriteMetadataOnly = true;
1435 return ParseResult.Success;
1437 case "--break-on-ice":
1438 settings.BreakOnInternalError = true;
1439 return ParseResult.Success;
1442 if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
1444 if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
1445 int.TryParse (arg.Substring (8), out fatal);
1447 settings.FatalCounter = fatal;
1448 return ParseResult.Success;
1450 if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
1451 string version = arg.Substring (10);
1456 settings.StdLibRuntimeVersion = RuntimeVersion.v1;
1460 settings.StdLibRuntimeVersion = RuntimeVersion.v2;
1464 settings.StdLibRuntimeVersion = RuntimeVersion.v4;
1467 return ParseResult.Success;
1470 return ParseResult.UnknownOption;
1474 void SetWarningLevel (string s, CompilerSettings settings)
1479 level = int.Parse (s);
1482 if (level < 0 || level > 4) {
1483 report.Error (1900, "Warning level must be in the range 0-4");
1486 settings.WarningLevel = level;
1490 // Given a path specification, splits the path from the file/pattern
1492 static void SplitPathAndPattern (string spec, out string path, out string pattern)
1494 int p = spec.LastIndexOf ('/');
1497 // Windows does not like /file.cs, switch that to:
1502 pattern = spec.Substring (1);
1504 path = spec.Substring (0, p);
1505 pattern = spec.Substring (p + 1);
1510 p = spec.LastIndexOf ('\\');
1512 path = spec.Substring (0, p);
1513 pattern = spec.Substring (p + 1);
1524 "Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
1525 "mcs [options] source-files\n" +
1526 " --about About the Mono C# compiler\n" +
1527 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
1528 " -checked[+|-] Sets default aritmetic overflow context\n" +
1529 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
1530 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
1531 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
1532 " -debug[+|-], -g Generate debugging information\n" +
1533 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
1534 " -doc:FILE Process documentation comments to XML file\n" +
1535 " -fullpaths Any issued error or warning uses absolute file path\n" +
1536 " -help Lists all compiler options (short: -?)\n" +
1537 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
1538 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
1539 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, 4, 5, Default or Future\n" +
1540 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
1541 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
1542 " -noconfig Disables implicitly referenced assemblies\n" +
1543 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
1544 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
1545 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
1546 " -out:FILE Specifies output assembly name\n" +
1547 " -pkg:P1[,Pn] References packages P1..Pn\n" +
1548 " -platform:ARCH Specifies the target platform of the output assembly\n" +
1549 " ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
1550 " x86, x64 or itanium. The default is anycpu.\n" +
1551 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
1552 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
1553 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
1554 " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
1555 " VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
1556 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
1557 " KIND can be one of: exe, winexe, library, module\n" +
1558 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
1559 " -warnaserror[+|-] Treats all warnings as errors\n" +
1560 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
1561 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
1562 " -helpinternal Shows internal and advanced compiler options\n" +
1565 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
1566 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
1567 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
1568 " -win32icon:FILE Use this icon for the output\n" +
1569 " @file Read response file for more options\n\n" +
1570 "Options can be of the form -option or /option");
1575 string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
1576 output.WriteLine ("Mono C# compiler version {0}", version);
1580 public class RootContext
1583 // Contains the parsed tree
1585 static ModuleContainer root;
1587 static public ModuleContainer ToplevelTypes {
1588 get { return root; }
1589 set { root = value; }