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.V_5,
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;
151 public bool ShowFullPaths;
154 // Whether we are being linked against the standard libraries.
155 // This is only used to tell whether `System.Object' should
156 // have a base class or not.
160 public RuntimeVersion StdLibRuntimeVersion;
162 readonly List<string> conditional_symbols;
164 readonly List<SourceFile> source_files;
166 List<int> warnings_as_error;
167 List<int> warnings_only;
168 HashSet<int> warning_ignore_table;
170 public CompilerSettings ()
175 Platform = Platform.AnyCPU;
176 Version = LanguageVersion.Default;
177 VerifyClsCompliance = true;
178 Encoding = Encoding.UTF8;
179 LoadDefaultReferences = true;
180 StdLibRuntimeVersion = RuntimeVersion.v4;
183 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
188 AssemblyReferences = new List<string> ();
189 AssemblyReferencesAliases = new List<Tuple<string, string>> ();
190 Modules = new List<string> ();
191 ReferencesLookupPaths = new List<string> ();
193 conditional_symbols = new List<string> ();
195 // Add default mcs define
197 conditional_symbols.Add ("__MonoCS__");
199 source_files = new List<SourceFile> ();
204 public SourceFile FirstSourceFile {
206 return source_files.Count > 0 ? source_files [0] : null;
210 public bool HasKeyFileOrContainer {
212 return StrongNameKeyFile != null || StrongNameKeyContainer != null;
216 public bool NeedsEntryPoint {
218 return Target == Target.Exe || Target == Target.WinExe;
222 public List<SourceFile> SourceFiles {
230 public void AddConditionalSymbol (string symbol)
232 if (!conditional_symbols.Contains (symbol))
233 conditional_symbols.Add (symbol);
236 public void AddWarningAsError (int id)
238 if (warnings_as_error == null)
239 warnings_as_error = new List<int> ();
241 warnings_as_error.Add (id);
244 public void AddWarningOnly (int id)
246 if (warnings_only == null)
247 warnings_only = new List<int> ();
249 warnings_only.Add (id);
252 public bool IsConditionalSymbolDefined (string symbol)
254 return conditional_symbols.Contains (symbol);
257 public bool IsWarningAsError (int code)
259 bool is_error = WarningsAreErrors;
261 // Check specific list
262 if (warnings_as_error != null)
263 is_error |= warnings_as_error.Contains (code);
265 // Ignore excluded warnings
266 if (warnings_only != null && warnings_only.Contains (code))
272 public bool IsWarningEnabled (int code, int level)
274 if (WarningLevel < level)
277 return !IsWarningDisabledGlobally (code);
280 public bool IsWarningDisabledGlobally (int code)
282 return warning_ignore_table != null && warning_ignore_table.Contains (code);
285 public void SetIgnoreWarning (int code)
287 if (warning_ignore_table == null)
288 warning_ignore_table = new HashSet<int> ();
290 warning_ignore_table.Add (code);
294 public class CommandLineParser
304 static readonly char[] argument_value_separator = new char[] { ';', ',' };
305 static readonly char[] numeric_value_separator = new char[] { ';', ',', ' ' };
307 readonly TextWriter output;
308 readonly Report report;
311 Dictionary<string, int> source_file_index;
313 public event Func<string[], int, int> UnknownOptionHandler;
315 CompilerSettings parser_settings;
317 public CommandLineParser (TextWriter errorOutput)
318 : this (errorOutput, Console.Out)
322 public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
324 var rp = new StreamReportPrinter (errorOutput);
326 parser_settings = new CompilerSettings ();
327 report = new Report (new CompilerContext (parser_settings, rp), rp);
328 this.output = messagesOutput;
331 public bool HasBeenStopped {
333 return stop_argument;
340 "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
341 "The compiler source code is released under the terms of the \n" +
342 "MIT X11 or GNU GPL licenses\n\n" +
344 "For more information on Mono, visit the project Web site\n" +
345 " http://www.mono-project.com\n\n" +
347 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
350 public CompilerSettings ParseArguments (string[] args)
352 CompilerSettings settings = new CompilerSettings ();
353 List<string> response_file_list = null;
354 bool parsing_options = true;
355 stop_argument = false;
356 source_file_index = new Dictionary<string, int> ();
358 for (int i = 0; i < args.Length; i++) {
359 string arg = args[i];
365 string response_file = arg.Substring (1);
367 if (response_file_list == null)
368 response_file_list = new List<string> ();
370 if (response_file_list.Contains (response_file)) {
371 report.Error (1515, "Response file `{0}' specified multiple times", response_file);
375 response_file_list.Add (response_file);
377 extra_args = LoadArgs (response_file);
378 if (extra_args == null) {
379 report.Error (2011, "Unable to open response file: " + response_file);
383 args = AddArgs (args, extra_args);
387 if (parsing_options) {
389 parsing_options = false;
393 bool dash_opt = arg[0] == '-';
394 bool slash_opt = arg[0] == '/';
396 switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
397 case ParseResult.Error:
398 case ParseResult.Success:
400 case ParseResult.Stop:
401 stop_argument = true;
403 case ParseResult.UnknownOption:
404 if (UnknownOptionHandler != null) {
405 var ret = UnknownOptionHandler (args, i);
415 if (dash_opt || slash_opt) {
417 string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
418 switch (ParseOption (csc_opt, ref args, settings)) {
419 case ParseResult.Error:
420 case ParseResult.Success:
422 case ParseResult.UnknownOption:
423 // Need to skip `/home/test.cs' however /test.cs is considered as error
424 if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
427 if (UnknownOptionHandler != null) {
428 var ret = UnknownOptionHandler (args, i);
435 Error_WrongOption (arg);
438 case ParseResult.Stop:
439 stop_argument = true;
445 ProcessSourceFiles (arg, false, settings.SourceFiles);
448 if (report.Errors > 0)
454 void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
456 string path, pattern;
458 SplitPathAndPattern (spec, out path, out pattern);
459 if (pattern.IndexOf ('*') == -1) {
460 AddSourceFile (spec, sourceFiles);
464 string[] files = null;
466 files = Directory.GetFiles (path, pattern);
467 } catch (System.IO.DirectoryNotFoundException) {
468 report.Error (2001, "Source file `" + spec + "' could not be found");
470 } catch (System.IO.IOException) {
471 report.Error (2001, "Source file `" + spec + "' could not be found");
474 foreach (string f in files) {
475 AddSourceFile (f, sourceFiles);
481 string[] dirs = null;
484 dirs = Directory.GetDirectories (path);
488 foreach (string d in dirs) {
490 // Don't include path in this string, as each
491 // directory entry already does
492 ProcessSourceFiles (d + "/" + pattern, true, sourceFiles);
496 static string[] AddArgs (string[] args, string[] extra_args)
499 new_args = new string[extra_args.Length + args.Length];
501 // if args contains '--' we have to take that into account
502 // split args into first half and second half based on '--'
503 // and add the extra_args before --
504 int split_position = Array.IndexOf (args, "--");
505 if (split_position != -1) {
506 Array.Copy (args, new_args, split_position);
507 extra_args.CopyTo (new_args, split_position);
508 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
510 args.CopyTo (new_args, 0);
511 extra_args.CopyTo (new_args, args.Length);
517 void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
519 if (assembly.Length == 0) {
520 report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
524 if (!IsExternAliasValid (alias)) {
525 report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
529 settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
532 void AddResource (AssemblyResource res, CompilerSettings settings)
534 if (settings.Resources == null) {
535 settings.Resources = new List<AssemblyResource> ();
536 settings.Resources.Add (res);
540 if (settings.Resources.Contains (res)) {
541 report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
545 settings.Resources.Add (res);
548 void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
550 string path = Path.GetFullPath (fileName);
553 if (source_file_index.TryGetValue (path, out index)) {
554 string other_name = sourceFiles[index - 1].Name;
555 if (fileName.Equals (other_name))
556 report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
558 report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", fileName, other_name, path);
563 var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
564 sourceFiles.Add (unit);
565 source_file_index.Add (path, unit.Index);
568 public bool ProcessWarningsList (string text, Action<int> action)
571 foreach (string wid in text.Split (numeric_value_separator)) {
573 if (!int.TryParse (wid, NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out id)) {
574 report.Error (1904, "`{0}' is not a valid warning number", wid);
579 if (report.CheckWarningCode (id, Location.Null))
586 void Error_RequiresArgument (string option)
588 report.Error (2006, "Missing argument for `{0}' option", option);
591 void Error_RequiresFileName (string option)
593 report.Error (2005, "Missing file specification for `{0}' option", option);
596 void Error_WrongOption (string option)
598 report.Error (2007, "Unrecognized command-line option: `{0}'", option);
601 static bool IsExternAliasValid (string identifier)
603 if (identifier.Length == 0)
605 if (identifier[0] != '_' && !char.IsLetter (identifier[0]))
608 for (int i = 1; i < identifier.Length; i++) {
609 char c = identifier[i];
610 if (char.IsLetter (c) || char.IsDigit (c))
613 UnicodeCategory category = char.GetUnicodeCategory (c);
614 if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
615 category != UnicodeCategory.SpacingCombiningMark ||
616 category != UnicodeCategory.ConnectorPunctuation)
623 static string[] LoadArgs (string file)
626 var args = new List<string> ();
629 f = new StreamReader (file);
634 StringBuilder sb = new StringBuilder ();
636 while ((line = f.ReadLine ()) != null) {
639 for (int i = 0; i < t; i++) {
642 if (c == '"' || c == '\'') {
645 for (i++; i < t; i++) {
652 } else if (c == ' ') {
654 args.Add (sb.ToString ());
661 args.Add (sb.ToString ());
666 return args.ToArray ();
672 "Other flags in the compiler\n" +
673 " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
674 " --lint Enhanced warnings\n" +
675 " --parse Only parses the source file\n" +
676 " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
677 " --stacktrace Shows stack trace at error location\n" +
678 " --timestamp Displays time stamps of various compiler events\n" +
679 " -v Verbose parsing (for debugging the parser)\n" +
680 " --mcs-debug X Sets MCS debugging level to X\n");
684 // This parses the -arg and /arg options to the compiler, even if the strings
685 // in the following text use "/arg" on the strings.
687 ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
689 int idx = option.IndexOf (':');
696 arg = option.Substring (0, idx);
698 value = option.Substring (idx + 1);
701 switch (arg.ToLowerInvariant ()) {
703 return ParseResult.Success;
709 settings.Target = Target.Exe;
713 settings.Target = Target.WinExe;
717 settings.Target = Target.Library;
718 settings.TargetExt = ".dll";
722 settings.Target = Target.Module;
723 settings.TargetExt = ".netmodule";
727 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
728 return ParseResult.Error;
730 return ParseResult.Success;
733 if (value.Length == 0) {
734 Error_RequiresFileName (option);
735 return ParseResult.Error;
737 settings.OutputFile = value;
738 return ParseResult.Success;
744 settings.Optimize = true;
745 return ParseResult.Success;
749 settings.Optimize = false;
750 return ParseResult.Success;
752 // TODO: Not supported by csc 3.5+
754 case "/incremental+":
755 case "/incremental-":
757 return ParseResult.Success;
761 if (value.Length == 0) {
762 Error_RequiresArgument (option);
763 return ParseResult.Error;
766 foreach (string d in value.Split (argument_value_separator)) {
767 string conditional = d.Trim ();
768 if (!Tokenizer.IsValidIdentifier (conditional)) {
769 report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
773 settings.AddConditionalSymbol (conditional);
775 return ParseResult.Success;
780 // We should collect data, runtime, etc and store in the file specified
782 output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
783 return ParseResult.Success;
788 if (value.Length == 0) {
789 Error_RequiresArgument (option);
790 return ParseResult.Error;
792 packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
793 string pkgout = Driver.GetPackageFlags (packages, report);
796 return ParseResult.Error;
798 string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
799 args = AddArgs (args, xargs);
800 return ParseResult.Success;
804 case "/linkresource":
807 AssemblyResource res = null;
808 string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
811 if (s[0].Length == 0)
813 res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
816 res = new AssemblyResource (s[0], s[1]);
819 if (s[2] != "public" && s[2] != "private") {
820 report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
821 return ParseResult.Error;
823 res = new AssemblyResource (s[0], s[1], s[2] == "private");
826 report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
827 return ParseResult.Error;
831 res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
832 AddResource (res, settings);
835 return ParseResult.Success;
838 if (value.Length == 0) {
839 Error_RequiresFileName (option);
840 return ParseResult.Error;
842 ProcessSourceFiles (value, true, settings.SourceFiles);
843 return ParseResult.Success;
847 if (value.Length == 0) {
848 Error_RequiresFileName (option);
849 return ParseResult.Error;
852 string[] refs = value.Split (argument_value_separator);
853 foreach (string r in refs) {
858 int index = val.IndexOf ('=');
860 string alias = r.Substring (0, index);
861 string assembly = r.Substring (index + 1);
862 AddAssemblyReference (alias, assembly, settings);
863 if (refs.Length != 1) {
864 report.Error (2034, "Cannot specify multiple aliases using single /reference option");
865 return ParseResult.Error;
868 settings.AssemblyReferences.Add (val);
871 return ParseResult.Success;
874 if (value.Length == 0) {
875 Error_RequiresFileName (option);
876 return ParseResult.Error;
879 string[] refs = value.Split (argument_value_separator);
880 foreach (string r in refs) {
881 settings.Modules.Add (r);
883 return ParseResult.Success;
886 if (value.Length == 0) {
887 Error_RequiresFileName (option);
888 return ParseResult.Error;
891 if (settings.Win32IconFile != null)
892 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
894 settings.Win32ResourceFile = value;
895 return ParseResult.Success;
898 if (value.Length == 0) {
899 Error_RequiresFileName (option);
900 return ParseResult.Error;
903 if (settings.Win32ResourceFile != null)
904 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
906 settings.Win32IconFile = value;
907 return ParseResult.Success;
910 if (value.Length == 0) {
911 Error_RequiresFileName (option);
912 return ParseResult.Error;
915 settings.DocumentationFile = value;
916 return ParseResult.Success;
921 if (value.Length == 0) {
922 return ParseResult.Error;
925 libdirs = value.Split (argument_value_separator);
926 foreach (string dir in libdirs)
927 settings.ReferencesLookupPaths.Add (dir);
928 return ParseResult.Success;
932 settings.GenerateDebugInfo = false;
933 return ParseResult.Success;
936 if (value == "full" || value == "pdbonly" || idx < 0) {
937 settings.GenerateDebugInfo = true;
938 return ParseResult.Success;
941 if (value.Length > 0) {
942 report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
944 Error_RequiresArgument (option);
947 return ParseResult.Error;
950 settings.GenerateDebugInfo = true;
951 return ParseResult.Success;
955 settings.Checked = true;
956 return ParseResult.Success;
959 settings.Checked = false;
960 return ParseResult.Success;
964 settings.VerifyClsCompliance = true;
965 return ParseResult.Success;
968 settings.VerifyClsCompliance = false;
969 return ParseResult.Success;
973 settings.Unsafe = true;
974 return ParseResult.Success;
977 settings.Unsafe = false;
978 return ParseResult.Success;
981 case "/warnaserror+":
982 if (value.Length == 0) {
983 settings.WarningsAreErrors = true;
984 parser_settings.WarningsAreErrors = true;
986 if (!ProcessWarningsList (value, v => settings.AddWarningAsError (v)))
987 return ParseResult.Error;
989 return ParseResult.Success;
991 case "/warnaserror-":
992 if (value.Length == 0) {
993 settings.WarningsAreErrors = false;
995 if (!ProcessWarningsList (value, v => settings.AddWarningOnly (v)))
996 return ParseResult.Error;
998 return ParseResult.Success;
1002 if (value.Length == 0) {
1003 Error_RequiresArgument (option);
1004 return ParseResult.Error;
1007 SetWarningLevel (value, settings);
1008 return ParseResult.Success;
1011 if (value.Length == 0) {
1012 Error_RequiresArgument (option);
1013 return ParseResult.Error;
1016 if (!ProcessWarningsList (value, v => settings.SetIgnoreWarning (v)))
1017 return ParseResult.Error;
1019 return ParseResult.Success;
1022 settings.LoadDefaultReferences = false;
1023 return ParseResult.Success;
1026 if (value.Length == 0) {
1027 Error_RequiresArgument (option);
1028 return ParseResult.Error;
1031 switch (value.ToLowerInvariant ()) {
1033 settings.Platform = Platform.Arm;
1036 settings.Platform = Platform.AnyCPU;
1039 settings.Platform = Platform.X86;
1042 settings.Platform = Platform.X64;
1045 settings.Platform = Platform.IA64;
1047 case "anycpu32bitpreferred":
1048 settings.Platform = Platform.AnyCPU32Preferred;
1051 report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
1053 return ParseResult.Error;
1056 return ParseResult.Success;
1059 if (value.Length == 0) {
1060 Error_RequiresArgument (option);
1061 return ParseResult.Error;
1064 settings.SdkVersion = value;
1065 return ParseResult.Success;
1067 // We just ignore this.
1068 case "/errorreport":
1070 if (value.Length == 0) {
1071 Error_RequiresArgument (option);
1072 return ParseResult.Error;
1075 return ParseResult.Success;
1077 case "/helpinternal":
1079 return ParseResult.Stop;
1084 return ParseResult.Stop;
1088 if (value.Length == 0) {
1089 Error_RequiresArgument (option);
1090 return ParseResult.Error;
1092 settings.MainClass = value;
1093 return ParseResult.Success;
1097 settings.StdLib = false;
1098 return ParseResult.Success;
1101 settings.StdLib = true;
1102 return ParseResult.Success;
1105 settings.ShowFullPaths = true;
1106 return ParseResult.Success;
1109 if (value.Length == 0) {
1110 Error_RequiresFileName (option);
1111 return ParseResult.Error;
1114 settings.StrongNameKeyFile = value;
1115 return ParseResult.Success;
1117 case "/keycontainer":
1118 if (value.Length == 0) {
1119 Error_RequiresArgument (option);
1120 return ParseResult.Error;
1123 settings.StrongNameKeyContainer = value;
1124 return ParseResult.Success;
1128 settings.StrongNameDelaySign = true;
1129 return ParseResult.Success;
1132 settings.StrongNameDelaySign = false;
1133 return ParseResult.Success;
1135 case "/langversion":
1136 if (value.Length == 0) {
1137 Error_RequiresArgument (option);
1138 return ParseResult.Error;
1141 switch (value.ToLowerInvariant ()) {
1143 settings.Version = LanguageVersion.ISO_1;
1144 return ParseResult.Success;
1146 settings.Version = LanguageVersion.Default;
1147 return ParseResult.Success;
1149 settings.Version = LanguageVersion.ISO_2;
1150 return ParseResult.Success;
1152 settings.Version = LanguageVersion.V_3;
1153 return ParseResult.Success;
1155 settings.Version = LanguageVersion.V_4;
1156 return ParseResult.Success;
1158 settings.Version = LanguageVersion.V_5;
1159 return ParseResult.Success;
1161 settings.Version = LanguageVersion.Future;
1162 return ParseResult.Success;
1165 report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
1166 return ParseResult.Error;
1169 if (value.Length == 0) {
1170 Error_RequiresArgument (option);
1171 return ParseResult.Error;
1176 settings.Encoding = Encoding.UTF8;
1179 settings.Encoding = Encoding.Default;
1183 settings.Encoding = Encoding.GetEncoding (int.Parse (value));
1185 report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1187 return ParseResult.Error;
1189 return ParseResult.Success;
1192 return ParseResult.UnknownOption;
1197 // Currently handles the Unix-like command line options, but will be
1198 // deprecated in favor of the CSCParseOption, which will also handle the
1199 // options that start with a dash in the future.
1201 ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
1205 settings.VerboseParserFlag++;
1206 return ParseResult.Success;
1210 return ParseResult.Stop;
1213 settings.ParseOnly = true;
1214 return ParseResult.Success;
1216 case "--main": case "-m":
1217 report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
1218 if ((i + 1) >= args.Length){
1219 Error_RequiresArgument (arg);
1220 return ParseResult.Error;
1222 settings.MainClass = args[++i];
1223 return ParseResult.Success;
1226 report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
1227 settings.Unsafe = true;
1228 return ParseResult.Success;
1230 case "/?": case "/h": case "/help":
1233 return ParseResult.Stop;
1236 report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
1237 if ((i + 1) >= args.Length){
1238 Error_RequiresArgument (arg);
1239 return ParseResult.Error;
1242 settings.AddConditionalSymbol (args [++i]);
1243 return ParseResult.Success;
1246 settings.TokenizeOnly = true;
1247 return ParseResult.Success;
1251 report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
1252 if ((i + 1) >= args.Length){
1253 Error_RequiresArgument (arg);
1254 return ParseResult.Error;
1256 settings.OutputFile = args[++i];
1257 return ParseResult.Success;
1260 report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
1261 settings.Checked = true;
1262 return ParseResult.Success;
1264 case "--stacktrace":
1265 settings.Stacktrace = true;
1266 return ParseResult.Success;
1268 case "--linkresource":
1270 report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
1271 if ((i + 1) >= args.Length){
1272 Error_RequiresArgument (arg);
1273 return ParseResult.Error;
1276 AddResource (new AssemblyResource (args[++i], args[i]), settings);
1277 return ParseResult.Success;
1281 report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
1282 if ((i + 1) >= args.Length){
1283 Error_RequiresArgument (arg);
1284 return ParseResult.Error;
1287 AddResource (new AssemblyResource (args[++i], args[i], true), settings);
1288 return ParseResult.Success;
1291 report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
1292 if ((i + 1) >= args.Length){
1293 Error_RequiresArgument (arg);
1294 return ParseResult.Error;
1297 string type = args [++i];
1300 settings.Target = Target.Library;
1301 settings.TargetExt = ".dll";
1305 settings.Target = Target.Exe;
1309 settings.Target = Target.WinExe;
1313 settings.Target = Target.Module;
1314 settings.TargetExt = ".dll";
1317 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
1320 return ParseResult.Success;
1323 report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
1324 if ((i + 1) >= args.Length){
1325 Error_RequiresArgument (arg);
1326 return ParseResult.Error;
1329 string val = args [++i];
1330 int idx = val.IndexOf ('=');
1332 string alias = val.Substring (0, idx);
1333 string assembly = val.Substring (idx + 1);
1334 AddAssemblyReference (alias, assembly, settings);
1335 return ParseResult.Success;
1338 settings.AssemblyReferences.Add (val);
1339 return ParseResult.Success;
1342 report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
1343 if ((i + 1) >= args.Length){
1344 Error_RequiresArgument (arg);
1345 return ParseResult.Error;
1347 settings.ReferencesLookupPaths.Add (args [++i]);
1348 return ParseResult.Success;
1351 settings.EnhancedWarnings = true;
1352 return ParseResult.Success;
1355 report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1356 settings.StdLib = false;
1357 return ParseResult.Success;
1360 report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1361 if ((i + 1) >= args.Length){
1362 Error_RequiresArgument (arg);
1363 return ParseResult.Error;
1368 warn = int.Parse (args [++i]);
1371 Environment.Exit (1);
1373 settings.SetIgnoreWarning (warn);
1374 return ParseResult.Success;
1377 report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1378 if ((i + 1) >= args.Length){
1379 Error_RequiresArgument (arg);
1380 return ParseResult.Error;
1383 SetWarningLevel (args [++i], settings);
1384 return ParseResult.Success;
1387 if ((i + 1) >= args.Length){
1388 Error_RequiresArgument (arg);
1389 return ParseResult.Error;
1393 settings.DebugFlags = int.Parse (args [++i]);
1395 Error_RequiresArgument (arg);
1396 return ParseResult.Error;
1399 return ParseResult.Success;
1403 return ParseResult.Stop;
1406 report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1407 if ((i + 1) >= args.Length){
1408 Error_RequiresArgument (arg);
1409 return ParseResult.Error;
1411 ProcessSourceFiles (args [++i], true, settings.SourceFiles);
1412 return ParseResult.Success;
1415 settings.Timestamps = true;
1416 return ParseResult.Success;
1418 case "--debug": case "-g":
1419 report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1420 settings.GenerateDebugInfo = true;
1421 return ParseResult.Success;
1424 report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1425 settings.LoadDefaultReferences = false;
1426 return ParseResult.Success;
1429 if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
1431 if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
1432 int.TryParse (arg.Substring (8), out fatal);
1434 settings.FatalCounter = fatal;
1435 return ParseResult.Success;
1437 if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
1438 string version = arg.Substring (10);
1443 settings.StdLibRuntimeVersion = RuntimeVersion.v1;
1447 settings.StdLibRuntimeVersion = RuntimeVersion.v2;
1451 settings.StdLibRuntimeVersion = RuntimeVersion.v4;
1454 return ParseResult.Success;
1457 return ParseResult.UnknownOption;
1461 void SetWarningLevel (string s, CompilerSettings settings)
1466 level = int.Parse (s);
1469 if (level < 0 || level > 4) {
1470 report.Error (1900, "Warning level must be in the range 0-4");
1473 settings.WarningLevel = level;
1477 // Given a path specification, splits the path from the file/pattern
1479 static void SplitPathAndPattern (string spec, out string path, out string pattern)
1481 int p = spec.LastIndexOf ('/');
1484 // Windows does not like /file.cs, switch that to:
1489 pattern = spec.Substring (1);
1491 path = spec.Substring (0, p);
1492 pattern = spec.Substring (p + 1);
1497 p = spec.LastIndexOf ('\\');
1499 path = spec.Substring (0, p);
1500 pattern = spec.Substring (p + 1);
1511 "Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
1512 "mcs [options] source-files\n" +
1513 " --about About the Mono C# compiler\n" +
1514 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
1515 " -checked[+|-] Sets default aritmetic overflow context\n" +
1516 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
1517 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
1518 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
1519 " -debug[+|-], -g Generate debugging information\n" +
1520 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
1521 " -doc:FILE Process documentation comments to XML file\n" +
1522 " -fullpaths Any issued error or warning uses absolute file path\n" +
1523 " -help Lists all compiler options (short: -?)\n" +
1524 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
1525 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
1526 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, 4, 5, Default or Future\n" +
1527 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
1528 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
1529 " -noconfig Disables implicitly referenced assemblies\n" +
1530 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
1531 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
1532 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
1533 " -out:FILE Specifies output assembly name\n" +
1534 " -pkg:P1[,Pn] References packages P1..Pn\n" +
1535 " -platform:ARCH Specifies the target platform of the output assembly\n" +
1536 " ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
1537 " x86, x64 or itanium. The default is anycpu.\n" +
1538 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
1539 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
1540 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
1541 " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
1542 " VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
1543 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
1544 " KIND can be one of: exe, winexe, library, module\n" +
1545 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
1546 " -warnaserror[+|-] Treats all warnings as errors\n" +
1547 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
1548 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
1549 " -helpinternal Shows internal and advanced compiler options\n" +
1552 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
1553 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
1554 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
1555 " -win32icon:FILE Use this icon for the output\n" +
1556 " @file Read response file for more options\n\n" +
1557 "Options can be of the form -option or /option");
1562 string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
1563 output.WriteLine ("Mono C# compiler version {0}", version);
1567 public class RootContext
1570 // Contains the parsed tree
1572 static ModuleContainer root;
1574 static public ModuleContainer ToplevelTypes {
1575 get { return root; }
1576 set { root = value; }