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
34 Default = LanguageVersion.V_6,
37 public enum RuntimeVersion
46 Library, Exe, Module, WinExe
59 public class CompilerSettings
62 public Platform Platform;
63 public string TargetExt;
64 public bool VerifyClsCompliance;
66 public LanguageVersion Version;
67 public bool EnhancedWarnings;
68 public bool LoadDefaultReferences;
69 public string SdkVersion;
71 public string StrongNameKeyFile;
72 public string StrongNameKeyContainer;
73 public bool StrongNameDelaySign;
77 public bool WarningsAreErrors;
78 public int WarningLevel;
81 // Assemblies references to be loaded
83 public List<string> AssemblyReferences;
86 // External aliases for assemblies
88 public List<Tuple<string, string>> AssemblyReferencesAliases;
90 public List<KeyValuePair<string, string>> PathMap;
93 // Modules to be embedded
95 public List<string> Modules;
98 // Lookup paths for referenced assemblies
100 public List<string> ReferencesLookupPaths;
105 public Encoding Encoding;
108 // If set, enable XML documentation generation
110 public string DocumentationFile;
112 public string MainClass;
117 public string OutputFile;
120 // The default compiler checked state
125 // If true, the compiler is operating in statement mode,
126 // this currently turns local variable declaration into
127 // static variables of a class
129 public bool StatementMode; // TODO: SUPER UGLY
132 // Whether to allow Unsafe code
136 public string Win32ResourceFile;
137 public string Win32IconFile;
140 // A list of resource files for embedding
142 public List<AssemblyResource> Resources;
144 public bool GenerateDebugInfo;
146 #region Compiler debug flags only
147 public bool ParseOnly, TokenizeOnly, Timestamps;
148 public int DebugFlags;
149 public int VerboseParserFlag;
150 public int FatalCounter;
151 public bool Stacktrace;
152 public bool BreakOnInternalError;
155 public List<string> GetResourceStrings;
157 public bool ShowFullPaths;
160 // Whether we are being linked against the standard libraries.
161 // This is only used to tell whether `System.Object' should
162 // have a base class or not.
166 public RuntimeVersion StdLibRuntimeVersion;
168 public string RuntimeMetadataVersion;
170 public bool WriteMetadataOnly;
172 readonly List<string> conditional_symbols;
174 readonly List<SourceFile> source_files;
176 List<int> warnings_as_error;
177 List<int> warnings_only;
178 HashSet<int> warning_ignore_table;
180 public CompilerSettings ()
185 Platform = Platform.AnyCPU;
186 Version = LanguageVersion.Default;
187 VerifyClsCompliance = true;
188 Encoding = Encoding.UTF8;
189 LoadDefaultReferences = true;
190 StdLibRuntimeVersion = RuntimeVersion.v4;
193 // Default to 1 or mdb files would be platform speficic
196 AssemblyReferences = new List<string> ();
197 AssemblyReferencesAliases = new List<Tuple<string, string>> ();
198 Modules = new List<string> ();
199 ReferencesLookupPaths = new List<string> ();
201 conditional_symbols = new List<string> ();
203 // Add default mcs define
205 conditional_symbols.Add ("__MonoCS__");
207 source_files = new List<SourceFile> ();
212 public SourceFile FirstSourceFile {
214 return source_files.Count > 0 ? source_files [0] : null;
218 public bool HasKeyFileOrContainer {
220 return StrongNameKeyFile != null || StrongNameKeyContainer != null;
224 public bool NeedsEntryPoint {
226 return Target == Target.Exe || Target == Target.WinExe;
230 public List<SourceFile> SourceFiles {
238 public void AddConditionalSymbol (string symbol)
240 if (!conditional_symbols.Contains (symbol))
241 conditional_symbols.Add (symbol);
244 public void AddWarningAsError (int id)
246 if (warnings_as_error == null)
247 warnings_as_error = new List<int> ();
249 warnings_as_error.Add (id);
252 public void AddWarningOnly (int id)
254 if (warnings_only == null)
255 warnings_only = new List<int> ();
257 warnings_only.Add (id);
260 public bool IsConditionalSymbolDefined (string symbol)
262 return conditional_symbols.Contains (symbol);
265 public bool IsWarningAsError (int code)
267 bool is_error = WarningsAreErrors;
269 // Check specific list
270 if (warnings_as_error != null)
271 is_error |= warnings_as_error.Contains (code);
273 // Ignore excluded warnings
274 if (warnings_only != null && warnings_only.Contains (code))
280 public bool IsWarningEnabled (int code, int level)
282 if (WarningLevel < level)
285 return !IsWarningDisabledGlobally (code);
288 public bool IsWarningDisabledGlobally (int code)
290 return warning_ignore_table != null && warning_ignore_table.Contains (code);
293 public void SetIgnoreWarning (int code)
295 if (warning_ignore_table == null)
296 warning_ignore_table = new HashSet<int> ();
298 warning_ignore_table.Add (code);
302 public class CommandLineParser
312 static readonly char[] argument_value_separator = { ';', ',' };
313 static readonly char[] numeric_value_separator = { ';', ',', ' ' };
315 readonly TextWriter output;
316 readonly Report report;
319 Dictionary<string, int> source_file_index;
321 public event Func<string[], int, int> UnknownOptionHandler;
323 CompilerSettings parser_settings;
325 public CommandLineParser (TextWriter errorOutput)
326 : this (errorOutput, Console.Out)
330 public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
332 var rp = new StreamReportPrinter (errorOutput);
334 parser_settings = new CompilerSettings ();
335 report = new Report (new CompilerContext (parser_settings, rp), rp);
336 this.output = messagesOutput;
339 public bool HasBeenStopped {
341 return stop_argument;
348 "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
349 "The compiler source code is released under the terms of the \n" +
350 "MIT X11 or GNU GPL licenses\n\n" +
352 "For more information on Mono, visit the project Web site\n" +
353 " http://www.mono-project.com\n\n" +
355 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
358 public CompilerSettings ParseArguments (string[] args)
360 CompilerSettings settings = new CompilerSettings ();
361 if (!ParseArguments (settings, args))
367 public bool ParseArguments (CompilerSettings settings, string[] args)
369 if (settings == null)
370 throw new ArgumentNullException ("settings");
372 List<string> response_file_list = null;
373 bool parsing_options = true;
374 stop_argument = false;
375 source_file_index = new Dictionary<string, int> ();
377 for (int i = 0; i < args.Length; i++) {
378 string arg = args[i];
384 string response_file = arg.Substring (1);
386 if (response_file_list == null)
387 response_file_list = new List<string> ();
389 if (response_file_list.Contains (response_file)) {
390 report.Error (1515, "Response file `{0}' specified multiple times", response_file);
394 response_file_list.Add (response_file);
396 extra_args = LoadArgs (response_file);
397 if (extra_args == null) {
398 report.Error (2011, "Unable to open response file: " + response_file);
402 args = AddArgs (args, extra_args);
406 if (parsing_options) {
408 parsing_options = false;
412 bool dash_opt = arg[0] == '-';
413 bool slash_opt = arg[0] == '/';
415 switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
416 case ParseResult.Error:
417 case ParseResult.Success:
419 case ParseResult.Stop:
420 stop_argument = true;
422 case ParseResult.UnknownOption:
423 if (UnknownOptionHandler != null) {
424 var ret = UnknownOptionHandler (args, i);
434 if (dash_opt || slash_opt) {
436 string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
437 switch (ParseOption (csc_opt, ref args, settings)) {
438 case ParseResult.Error:
439 case ParseResult.Success:
441 case ParseResult.UnknownOption:
442 // Need to skip `/home/test.cs' however /test.cs is considered as error
443 if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
446 if (UnknownOptionHandler != null) {
447 var ret = UnknownOptionHandler (args, i);
454 Error_WrongOption (arg);
457 case ParseResult.Stop:
458 stop_argument = true;
464 ProcessSourceFiles (arg, false, settings.SourceFiles);
467 return report.Errors == 0;
470 void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
472 string path, pattern;
474 SplitPathAndPattern (spec, out path, out pattern);
475 if (pattern.IndexOf ('*') == -1) {
476 AddSourceFile (spec, sourceFiles);
482 files = Directory.GetFiles (path, pattern);
483 } catch (System.IO.DirectoryNotFoundException) {
484 report.Error (2001, "Source file `" + spec + "' could not be found");
486 } catch (System.IO.IOException) {
487 report.Error (2001, "Source file `" + spec + "' could not be found");
490 foreach (string f in files) {
491 AddSourceFile (f, sourceFiles);
497 string[] dirs = null;
500 dirs = Directory.GetDirectories (path);
504 foreach (string d in dirs) {
506 // Don't include path in this string, as each
507 // directory entry already does
508 ProcessSourceFiles (d + "/" + pattern, true, sourceFiles);
512 static string[] AddArgs (string[] args, string[] extra_args)
515 new_args = new string[extra_args.Length + args.Length];
517 // if args contains '--' we have to take that into account
518 // split args into first half and second half based on '--'
519 // and add the extra_args before --
520 int split_position = Array.IndexOf (args, "--");
521 if (split_position != -1) {
522 Array.Copy (args, new_args, split_position);
523 extra_args.CopyTo (new_args, split_position);
524 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
526 args.CopyTo (new_args, 0);
527 extra_args.CopyTo (new_args, args.Length);
533 void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
535 if (assembly.Length == 0) {
536 report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
540 if (!IsExternAliasValid (alias)) {
541 report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
545 settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
548 void AddResource (AssemblyResource res, CompilerSettings settings)
550 if (settings.Resources == null) {
551 settings.Resources = new List<AssemblyResource> ();
552 settings.Resources.Add (res);
556 if (settings.Resources.Contains (res)) {
557 report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
561 settings.Resources.Add (res);
564 void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
566 string path = Path.GetFullPath (fileName);
569 if (source_file_index.TryGetValue (path, out index)) {
570 string other_name = sourceFiles[index - 1].Name;
571 if (fileName.Equals (other_name))
572 report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
574 report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", fileName, other_name, path);
579 var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
580 sourceFiles.Add (unit);
581 source_file_index.Add (path, unit.Index);
584 public bool ProcessWarningsList (string text, Action<int> action)
587 foreach (string wid in text.Split (numeric_value_separator, StringSplitOptions.RemoveEmptyEntries)) {
589 if (warning.Length == 6 && warning [0] == 'C' && warning [1] == 'S')
590 warning = warning.Substring (2);
593 if (!int.TryParse (warning, NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out id)) {
597 if (report.CheckWarningCode (id, Location.Null)) {
600 report.Error (1904, "`{0}' is not a valid warning number", wid);
608 void Error_RequiresArgument (string option)
610 report.Error (2006, "Missing argument for `{0}' option", option);
613 void Error_RequiresFileName (string option)
615 report.Error (2005, "Missing file specification for `{0}' option", option);
618 void Error_WrongOption (string option)
620 report.Error (2007, "Unrecognized command-line option: `{0}'", option);
623 static bool IsExternAliasValid (string identifier)
625 return Tokenizer.IsValidIdentifier (identifier);
628 static string[] LoadArgs (string file)
631 var args = new List<string> ();
634 f = new StreamReader (file);
639 StringBuilder sb = new StringBuilder ();
641 while ((line = f.ReadLine ()) != null) {
644 for (int i = 0; i < t; i++) {
647 if (c == '"' || c == '\'') {
650 for (i++; i < t; i++) {
657 } else if (c == ' ') {
659 args.Add (sb.ToString ());
666 args.Add (sb.ToString ());
671 return args.ToArray ();
677 "Other flags in the compiler\n" +
678 " --fatal[=COUNT] Makes error after COUNT fatal\n" +
679 " --lint Enhanced warnings\n" +
680 " --metadata-only Produced assembly will contain metadata only\n" +
681 " --parse Only parses the source file\n" +
682 " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
683 " --stacktrace Shows stack trace at error location\n" +
684 " --timestamp Displays time stamps of various compiler events\n" +
685 " -v Verbose parsing (for debugging the parser)\n" +
686 " --mcs-debug X Sets MCS debugging level to X\n" +
687 " --break-on-ice Breaks compilation on internal compiler error");
691 // This parses the -arg and /arg options to the compiler, even if the strings
692 // in the following text use "/arg" on the strings.
694 ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
696 int idx = option.IndexOf (':');
703 arg = option.Substring (0, idx);
705 value = option.Substring (idx + 1);
708 switch (arg.ToLowerInvariant ()) {
710 return ParseResult.Success;
716 settings.Target = Target.Exe;
720 settings.Target = Target.WinExe;
724 settings.Target = Target.Library;
725 settings.TargetExt = ".dll";
729 settings.Target = Target.Module;
730 settings.TargetExt = ".netmodule";
734 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
735 return ParseResult.Error;
737 return ParseResult.Success;
740 if (value.Length == 0) {
741 Error_RequiresFileName (option);
742 return ParseResult.Error;
744 settings.OutputFile = value;
745 return ParseResult.Success;
751 settings.Optimize = true;
752 return ParseResult.Success;
756 settings.Optimize = false;
757 return ParseResult.Success;
759 // TODO: Not supported by csc 3.5+
761 case "/incremental+":
762 case "/incremental-":
764 return ParseResult.Success;
768 if (value.Length == 0) {
769 Error_RequiresArgument (option);
770 return ParseResult.Error;
773 foreach (string d in value.Split (argument_value_separator)) {
774 string conditional = d.Trim ();
775 if (!Tokenizer.IsValidIdentifier (conditional)) {
776 report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
780 settings.AddConditionalSymbol (conditional);
782 return ParseResult.Success;
787 // We should collect data, runtime, etc and store in the file specified
789 output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
790 return ParseResult.Success;
795 if (value.Length == 0) {
796 Error_RequiresArgument (option);
797 return ParseResult.Error;
799 packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
800 string pkgout = Driver.GetPackageFlags (packages, report);
803 return ParseResult.Error;
805 string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
806 args = AddArgs (args, xargs);
807 return ParseResult.Success;
811 case "/linkresource":
814 AssemblyResource res = null;
815 string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
818 if (s[0].Length == 0)
820 res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
823 res = new AssemblyResource (s[0], s[1]);
826 if (s[2] != "public" && s[2] != "private") {
827 report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
828 return ParseResult.Error;
830 res = new AssemblyResource (s[0], s[1], s[2] == "private");
833 report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
834 return ParseResult.Error;
838 res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
839 AddResource (res, settings);
842 return ParseResult.Success;
845 if (value.Length == 0) {
846 Error_RequiresFileName (option);
847 return ParseResult.Error;
849 ProcessSourceFiles (value, true, settings.SourceFiles);
850 return ParseResult.Success;
854 if (value.Length == 0) {
855 Error_RequiresFileName (option);
856 return ParseResult.Error;
859 string[] refs = value.Split (argument_value_separator);
860 foreach (string r in refs) {
865 int index = val.IndexOf ('=');
867 string alias = r.Substring (0, index);
868 string assembly = r.Substring (index + 1);
869 AddAssemblyReference (alias, assembly, settings);
870 if (refs.Length != 1) {
871 report.Error (2034, "Cannot specify multiple aliases using single /reference option");
872 return ParseResult.Error;
875 settings.AssemblyReferences.Add (val);
878 return ParseResult.Success;
881 if (value.Length == 0) {
882 Error_RequiresFileName (option);
883 return ParseResult.Error;
886 string[] refs = value.Split (argument_value_separator);
887 foreach (string r in refs) {
888 settings.Modules.Add (r);
890 return ParseResult.Success;
893 if (value.Length == 0) {
894 Error_RequiresFileName (option);
895 return ParseResult.Error;
898 if (settings.Win32IconFile != null)
899 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
901 settings.Win32ResourceFile = value;
902 return ParseResult.Success;
905 if (value.Length == 0) {
906 Error_RequiresFileName (option);
907 return ParseResult.Error;
910 if (settings.Win32ResourceFile != null)
911 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
913 settings.Win32IconFile = value;
914 return ParseResult.Success;
917 if (value.Length == 0) {
918 Error_RequiresFileName (option);
919 return ParseResult.Error;
922 settings.DocumentationFile = value;
923 return ParseResult.Success;
928 if (value.Length == 0) {
929 return ParseResult.Error;
932 libdirs = value.Split (argument_value_separator);
933 foreach (string dir in libdirs)
934 settings.ReferencesLookupPaths.Add (dir);
935 return ParseResult.Success;
939 settings.GenerateDebugInfo = false;
940 return ParseResult.Success;
943 if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
944 settings.GenerateDebugInfo = true;
945 return ParseResult.Success;
948 if (value.Length > 0) {
949 report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
951 Error_RequiresArgument (option);
954 return ParseResult.Error;
957 settings.GenerateDebugInfo = true;
958 return ParseResult.Success;
962 settings.Checked = true;
963 return ParseResult.Success;
966 settings.Checked = false;
967 return ParseResult.Success;
971 settings.VerifyClsCompliance = true;
972 return ParseResult.Success;
975 settings.VerifyClsCompliance = false;
976 return ParseResult.Success;
980 settings.Unsafe = true;
981 return ParseResult.Success;
984 settings.Unsafe = false;
985 return ParseResult.Success;
988 case "/warnaserror+":
989 if (value.Length == 0) {
990 settings.WarningsAreErrors = true;
991 parser_settings.WarningsAreErrors = true;
993 if (!ProcessWarningsList (value, settings.AddWarningAsError))
994 return ParseResult.Error;
996 return ParseResult.Success;
998 case "/warnaserror-":
999 if (value.Length == 0) {
1000 settings.WarningsAreErrors = false;
1002 if (!ProcessWarningsList (value, settings.AddWarningOnly))
1003 return ParseResult.Error;
1005 return ParseResult.Success;
1009 if (value.Length == 0) {
1010 Error_RequiresArgument (option);
1011 return ParseResult.Error;
1014 SetWarningLevel (value, settings);
1015 return ParseResult.Success;
1018 if (value.Length == 0) {
1019 Error_RequiresArgument (option);
1020 return ParseResult.Error;
1023 if (!ProcessWarningsList (value, settings.SetIgnoreWarning))
1024 return ParseResult.Error;
1026 return ParseResult.Success;
1029 settings.LoadDefaultReferences = false;
1030 return ParseResult.Success;
1033 if (value.Length == 0) {
1034 Error_RequiresArgument (option);
1035 return ParseResult.Error;
1038 switch (value.ToLowerInvariant ()) {
1040 settings.Platform = Platform.Arm;
1043 settings.Platform = Platform.AnyCPU;
1046 settings.Platform = Platform.X86;
1049 settings.Platform = Platform.X64;
1052 settings.Platform = Platform.IA64;
1054 case "anycpu32bitpreferred":
1055 settings.Platform = Platform.AnyCPU32Preferred;
1058 report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
1060 return ParseResult.Error;
1063 return ParseResult.Success;
1066 if (value.Length == 0) {
1067 Error_RequiresArgument (option);
1068 return ParseResult.Error;
1071 settings.SdkVersion = value;
1072 return ParseResult.Success;
1074 // We just ignore this.
1075 case "/errorreport":
1077 if (value.Length == 0) {
1078 Error_RequiresArgument (option);
1079 return ParseResult.Error;
1082 return ParseResult.Success;
1084 case "/helpinternal":
1086 return ParseResult.Stop;
1091 return ParseResult.Stop;
1095 if (value.Length == 0) {
1096 Error_RequiresArgument (option);
1097 return ParseResult.Error;
1099 settings.MainClass = value;
1100 return ParseResult.Success;
1104 settings.StdLib = false;
1105 return ParseResult.Success;
1108 settings.StdLib = true;
1109 return ParseResult.Success;
1112 settings.ShowFullPaths = true;
1113 return ParseResult.Success;
1116 if (value.Length == 0) {
1117 Error_RequiresFileName (option);
1118 return ParseResult.Error;
1121 settings.StrongNameKeyFile = value;
1122 return ParseResult.Success;
1124 case "/keycontainer":
1125 if (value.Length == 0) {
1126 Error_RequiresArgument (option);
1127 return ParseResult.Error;
1130 settings.StrongNameKeyContainer = value;
1131 return ParseResult.Success;
1135 settings.StrongNameDelaySign = true;
1136 return ParseResult.Success;
1139 settings.StrongNameDelaySign = false;
1140 return ParseResult.Success;
1142 case "/langversion":
1143 if (value.Length == 0) {
1144 Error_RequiresArgument (option);
1145 return ParseResult.Error;
1148 switch (value.ToLowerInvariant ()) {
1151 settings.Version = LanguageVersion.ISO_1;
1152 return ParseResult.Success;
1154 settings.Version = LanguageVersion.Default;
1155 return ParseResult.Success;
1158 settings.Version = LanguageVersion.ISO_2;
1159 return ParseResult.Success;
1161 settings.Version = LanguageVersion.V_3;
1162 return ParseResult.Success;
1164 settings.Version = LanguageVersion.V_4;
1165 return ParseResult.Success;
1167 settings.Version = LanguageVersion.V_5;
1168 return ParseResult.Success;
1170 settings.Version = LanguageVersion.V_6;
1171 return ParseResult.Success;
1172 case "experimental":
1173 settings.Version = LanguageVersion.Experimental;
1174 return ParseResult.Success;
1176 report.Warning (8000, 1, "Language version `future' is no longer supported");
1180 report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', Default or value in range 1 to 6", value);
1181 return ParseResult.Error;
1184 if (value.Length == 0) {
1185 Error_RequiresArgument (option);
1186 return ParseResult.Error;
1191 settings.Encoding = Encoding.UTF8;
1194 settings.Encoding = Encoding.Default;
1198 settings.Encoding = Encoding.GetEncoding (int.Parse (value));
1200 report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1202 return ParseResult.Error;
1204 return ParseResult.Success;
1206 case "runtimemetadataversion":
1207 if (value.Length == 0) {
1208 Error_RequiresArgument (option);
1209 return ParseResult.Error;
1212 settings.RuntimeMetadataVersion = value;
1213 return ParseResult.Success;
1216 if (value.Length == 0) {
1217 return ParseResult.Success;
1220 foreach (var pair in value.Split (',')) {
1221 var kv = pair.Split ('=');
1222 if (kv.Length != 2) {
1223 report.Error (8101, "The pathmap option was incorrectly formatted");
1224 return ParseResult.Error;
1227 if (settings.PathMap == null)
1228 settings.PathMap = new List<KeyValuePair<string, string>> ();
1230 var key = kv [0].TrimEnd (Path.DirectorySeparatorChar);
1231 var path = kv [1].TrimEnd (Path.DirectorySeparatorChar);
1232 if (key.Length == 0 || path.Length == 0)
1233 report.Error (8101, "The pathmap option was incorrectly formatted");
1235 settings.PathMap.Add (new KeyValuePair<string, string> (key, path));
1238 return ParseResult.Success;
1240 // csc options that we don't support
1243 case "/baseaddress":
1244 case "/deterministic":
1245 case "/errorendlocation":
1248 case "/highentropyva":
1249 case "/highentropyva+":
1250 case "/highentropyva-":
1252 case "/moduleassemblyname":
1253 case "/nowin32manifest":
1255 case "/preferreduilang":
1257 case "/publicsign+":
1258 case "/publicsign-":
1259 case "/reportanalyzer":
1261 case "/sqmsessionguid":
1262 case "/subsystemversion":
1264 case "/win32manifest":
1265 return ParseResult.Success;
1268 return ParseResult.UnknownOption;
1273 // Currently handles the Unix-like command line options, but will be
1274 // deprecated in favor of the CSCParseOption, which will also handle the
1275 // options that start with a dash in the future.
1277 ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
1281 settings.VerboseParserFlag++;
1282 return ParseResult.Success;
1286 return ParseResult.Stop;
1289 settings.ParseOnly = true;
1290 return ParseResult.Success;
1292 case "--main": case "-m":
1293 report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
1294 if ((i + 1) >= args.Length){
1295 Error_RequiresArgument (arg);
1296 return ParseResult.Error;
1298 settings.MainClass = args[++i];
1299 return ParseResult.Success;
1302 report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
1303 settings.Unsafe = true;
1304 return ParseResult.Success;
1306 case "/?": case "/h": case "/help":
1309 return ParseResult.Stop;
1312 report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
1313 if ((i + 1) >= args.Length){
1314 Error_RequiresArgument (arg);
1315 return ParseResult.Error;
1318 settings.AddConditionalSymbol (args [++i]);
1319 return ParseResult.Success;
1322 settings.TokenizeOnly = true;
1323 return ParseResult.Success;
1327 report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
1328 if ((i + 1) >= args.Length){
1329 Error_RequiresArgument (arg);
1330 return ParseResult.Error;
1332 settings.OutputFile = args[++i];
1333 return ParseResult.Success;
1336 report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
1337 settings.Checked = true;
1338 return ParseResult.Success;
1340 case "--stacktrace":
1341 settings.Stacktrace = true;
1342 return ParseResult.Success;
1344 case "--linkresource":
1346 report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
1347 if ((i + 1) >= args.Length){
1348 Error_RequiresArgument (arg);
1349 return ParseResult.Error;
1352 AddResource (new AssemblyResource (args[++i], args[i]), settings);
1353 return ParseResult.Success;
1357 report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
1358 if ((i + 1) >= args.Length){
1359 Error_RequiresArgument (arg);
1360 return ParseResult.Error;
1363 AddResource (new AssemblyResource (args[++i], args[i], true), settings);
1364 return ParseResult.Success;
1367 report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
1368 if ((i + 1) >= args.Length){
1369 Error_RequiresArgument (arg);
1370 return ParseResult.Error;
1373 string type = args [++i];
1376 settings.Target = Target.Library;
1377 settings.TargetExt = ".dll";
1381 settings.Target = Target.Exe;
1385 settings.Target = Target.WinExe;
1389 settings.Target = Target.Module;
1390 settings.TargetExt = ".dll";
1393 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
1396 return ParseResult.Success;
1399 report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
1400 if ((i + 1) >= args.Length){
1401 Error_RequiresArgument (arg);
1402 return ParseResult.Error;
1405 string val = args [++i];
1406 int idx = val.IndexOf ('=');
1408 string alias = val.Substring (0, idx);
1409 string assembly = val.Substring (idx + 1);
1410 AddAssemblyReference (alias, assembly, settings);
1411 return ParseResult.Success;
1414 settings.AssemblyReferences.Add (val);
1415 return ParseResult.Success;
1418 report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
1419 if ((i + 1) >= args.Length){
1420 Error_RequiresArgument (arg);
1421 return ParseResult.Error;
1423 settings.ReferencesLookupPaths.Add (args [++i]);
1424 return ParseResult.Success;
1427 settings.EnhancedWarnings = true;
1428 return ParseResult.Success;
1431 report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1432 settings.StdLib = false;
1433 return ParseResult.Success;
1436 report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1437 if ((i + 1) >= args.Length){
1438 Error_RequiresArgument (arg);
1439 return ParseResult.Error;
1444 warn = int.Parse (args [++i]);
1447 Environment.Exit (1);
1449 settings.SetIgnoreWarning (warn);
1450 return ParseResult.Success;
1453 report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1454 if ((i + 1) >= args.Length){
1455 Error_RequiresArgument (arg);
1456 return ParseResult.Error;
1459 SetWarningLevel (args [++i], settings);
1460 return ParseResult.Success;
1463 if ((i + 1) >= args.Length){
1464 Error_RequiresArgument (arg);
1465 return ParseResult.Error;
1469 settings.DebugFlags = int.Parse (args [++i]);
1471 Error_RequiresArgument (arg);
1472 return ParseResult.Error;
1475 return ParseResult.Success;
1479 return ParseResult.Stop;
1482 report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1483 if ((i + 1) >= args.Length){
1484 Error_RequiresArgument (arg);
1485 return ParseResult.Error;
1487 ProcessSourceFiles (args [++i], true, settings.SourceFiles);
1488 return ParseResult.Success;
1491 settings.Timestamps = true;
1492 return ParseResult.Success;
1494 case "--debug": case "-g":
1495 report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1496 settings.GenerateDebugInfo = true;
1497 return ParseResult.Success;
1500 report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1501 settings.LoadDefaultReferences = false;
1502 return ParseResult.Success;
1504 case "--metadata-only":
1505 settings.WriteMetadataOnly = true;
1506 return ParseResult.Success;
1508 case "--break-on-ice":
1509 settings.BreakOnInternalError = true;
1510 return ParseResult.Success;
1513 if (arg.StartsWith ("--fatal", StringComparison.Ordinal)) {
1515 if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
1516 int.TryParse (arg.Substring (8), out fatal);
1518 settings.FatalCounter = fatal;
1519 return ParseResult.Success;
1521 if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
1522 string version = arg.Substring (10);
1527 settings.StdLibRuntimeVersion = RuntimeVersion.v1;
1531 settings.StdLibRuntimeVersion = RuntimeVersion.v2;
1535 settings.StdLibRuntimeVersion = RuntimeVersion.v4;
1538 return ParseResult.Success;
1541 if (arg.StartsWith ("--getresourcestrings:", StringComparison.Ordinal)) {
1542 string file = arg.Substring (21).Trim ();
1543 if (file.Length < 1) {
1544 Error_RequiresArgument (arg);
1545 return ParseResult.Error;
1548 if (settings.GetResourceStrings == null)
1549 settings.GetResourceStrings = new List<string> ();
1551 settings.GetResourceStrings.Add (file);
1552 return ParseResult.Success;
1555 return ParseResult.UnknownOption;
1559 void SetWarningLevel (string s, CompilerSettings settings)
1564 level = int.Parse (s);
1567 if (level < 0 || level > 4) {
1568 report.Error (1900, "Warning level must be in the range 0-4");
1571 settings.WarningLevel = level;
1575 // Given a path specification, splits the path from the file/pattern
1577 static void SplitPathAndPattern (string spec, out string path, out string pattern)
1579 int p = spec.LastIndexOf ('/');
1582 // Windows does not like /file.cs, switch that to:
1587 pattern = spec.Substring (1);
1589 path = spec.Substring (0, p);
1590 pattern = spec.Substring (p + 1);
1595 p = spec.LastIndexOf ('\\');
1597 path = spec.Substring (0, p);
1598 pattern = spec.Substring (p + 1);
1609 "Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
1610 "mcs [options] source-files\n" +
1611 " --about About the Mono C# compiler\n" +
1612 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
1613 " -checked[+|-] Sets default aritmetic overflow context\n" +
1614 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
1615 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
1616 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
1617 " -debug[+|-], -g Generate debugging information\n" +
1618 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
1619 " -doc:FILE Process documentation comments to XML file\n" +
1620 " -fullpaths Any issued error or warning uses absolute file path\n" +
1621 " -help Lists all compiler options (short: -?)\n" +
1622 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
1623 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
1624 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, 4, 5, 6, Default or Experimental\n" +
1625 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
1626 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
1627 " -noconfig Disables implicitly referenced assemblies\n" +
1628 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
1629 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
1630 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
1631 " -out:FILE Specifies output assembly name\n" +
1632 " -pathmap:K=V[,Kn=Vn] Sets a mapping for source path names used in generated output\n" +
1633 " -pkg:P1[,Pn] References packages P1..Pn\n" +
1634 " -platform:ARCH Specifies the target platform of the output assembly\n" +
1635 " ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
1636 " x86, x64 or itanium. The default is anycpu.\n" +
1637 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
1638 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
1639 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
1640 " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
1641 " VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
1642 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
1643 " KIND can be one of: exe, winexe, library, module\n" +
1644 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
1645 " -warnaserror[+|-] Treats all warnings as errors\n" +
1646 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
1647 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
1648 " -helpinternal Shows internal and advanced compiler options\n" +
1651 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
1652 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
1653 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
1654 " -win32icon:FILE Use this icon for the output\n" +
1655 " @file Read response file for more options\n\n" +
1656 "Options can be of the form -option or /option");
1661 string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
1662 output.WriteLine ("Mono C# compiler version {0}", version);
1666 public class RootContext
1669 // Contains the parsed tree
1671 static ModuleContainer root;
1673 static public ModuleContainer ToplevelTypes {
1674 get { return root; }
1675 set { root = value; }