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 public bool WriteMetadataOnly;
164 readonly List<string> conditional_symbols;
166 readonly List<SourceFile> source_files;
168 List<int> warnings_as_error;
169 List<int> warnings_only;
170 HashSet<int> warning_ignore_table;
172 public CompilerSettings ()
177 Platform = Platform.AnyCPU;
178 Version = LanguageVersion.Default;
179 VerifyClsCompliance = true;
180 Encoding = Encoding.UTF8;
181 LoadDefaultReferences = true;
182 StdLibRuntimeVersion = RuntimeVersion.v4;
185 // Default to 1 or mdb files would be platform speficic
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 error after COUNT fatal\n" +
674 " --lint Enhanced warnings\n" +
675 " --metadata-only Produced assembly will contain metadata only\n" +
676 " --parse Only parses the source file\n" +
677 " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
678 " --stacktrace Shows stack trace at error location\n" +
679 " --timestamp Displays time stamps of various compiler events\n" +
680 " -v Verbose parsing (for debugging the parser)\n" +
681 " --mcs-debug X Sets MCS debugging level to X\n");
685 // This parses the -arg and /arg options to the compiler, even if the strings
686 // in the following text use "/arg" on the strings.
688 ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
690 int idx = option.IndexOf (':');
697 arg = option.Substring (0, idx);
699 value = option.Substring (idx + 1);
702 switch (arg.ToLowerInvariant ()) {
704 return ParseResult.Success;
710 settings.Target = Target.Exe;
714 settings.Target = Target.WinExe;
718 settings.Target = Target.Library;
719 settings.TargetExt = ".dll";
723 settings.Target = Target.Module;
724 settings.TargetExt = ".netmodule";
728 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
729 return ParseResult.Error;
731 return ParseResult.Success;
734 if (value.Length == 0) {
735 Error_RequiresFileName (option);
736 return ParseResult.Error;
738 settings.OutputFile = value;
739 return ParseResult.Success;
745 settings.Optimize = true;
746 return ParseResult.Success;
750 settings.Optimize = false;
751 return ParseResult.Success;
753 // TODO: Not supported by csc 3.5+
755 case "/incremental+":
756 case "/incremental-":
758 return ParseResult.Success;
762 if (value.Length == 0) {
763 Error_RequiresArgument (option);
764 return ParseResult.Error;
767 foreach (string d in value.Split (argument_value_separator)) {
768 string conditional = d.Trim ();
769 if (!Tokenizer.IsValidIdentifier (conditional)) {
770 report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
774 settings.AddConditionalSymbol (conditional);
776 return ParseResult.Success;
781 // We should collect data, runtime, etc and store in the file specified
783 output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
784 return ParseResult.Success;
789 if (value.Length == 0) {
790 Error_RequiresArgument (option);
791 return ParseResult.Error;
793 packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
794 string pkgout = Driver.GetPackageFlags (packages, report);
797 return ParseResult.Error;
799 string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
800 args = AddArgs (args, xargs);
801 return ParseResult.Success;
805 case "/linkresource":
808 AssemblyResource res = null;
809 string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
812 if (s[0].Length == 0)
814 res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
817 res = new AssemblyResource (s[0], s[1]);
820 if (s[2] != "public" && s[2] != "private") {
821 report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
822 return ParseResult.Error;
824 res = new AssemblyResource (s[0], s[1], s[2] == "private");
827 report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
828 return ParseResult.Error;
832 res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
833 AddResource (res, settings);
836 return ParseResult.Success;
839 if (value.Length == 0) {
840 Error_RequiresFileName (option);
841 return ParseResult.Error;
843 ProcessSourceFiles (value, true, settings.SourceFiles);
844 return ParseResult.Success;
848 if (value.Length == 0) {
849 Error_RequiresFileName (option);
850 return ParseResult.Error;
853 string[] refs = value.Split (argument_value_separator);
854 foreach (string r in refs) {
859 int index = val.IndexOf ('=');
861 string alias = r.Substring (0, index);
862 string assembly = r.Substring (index + 1);
863 AddAssemblyReference (alias, assembly, settings);
864 if (refs.Length != 1) {
865 report.Error (2034, "Cannot specify multiple aliases using single /reference option");
866 return ParseResult.Error;
869 settings.AssemblyReferences.Add (val);
872 return ParseResult.Success;
875 if (value.Length == 0) {
876 Error_RequiresFileName (option);
877 return ParseResult.Error;
880 string[] refs = value.Split (argument_value_separator);
881 foreach (string r in refs) {
882 settings.Modules.Add (r);
884 return ParseResult.Success;
887 if (value.Length == 0) {
888 Error_RequiresFileName (option);
889 return ParseResult.Error;
892 if (settings.Win32IconFile != null)
893 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
895 settings.Win32ResourceFile = value;
896 return ParseResult.Success;
899 if (value.Length == 0) {
900 Error_RequiresFileName (option);
901 return ParseResult.Error;
904 if (settings.Win32ResourceFile != null)
905 report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
907 settings.Win32IconFile = value;
908 return ParseResult.Success;
911 if (value.Length == 0) {
912 Error_RequiresFileName (option);
913 return ParseResult.Error;
916 settings.DocumentationFile = value;
917 return ParseResult.Success;
922 if (value.Length == 0) {
923 return ParseResult.Error;
926 libdirs = value.Split (argument_value_separator);
927 foreach (string dir in libdirs)
928 settings.ReferencesLookupPaths.Add (dir);
929 return ParseResult.Success;
933 settings.GenerateDebugInfo = false;
934 return ParseResult.Success;
937 if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
938 settings.GenerateDebugInfo = true;
939 return ParseResult.Success;
942 if (value.Length > 0) {
943 report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
945 Error_RequiresArgument (option);
948 return ParseResult.Error;
951 settings.GenerateDebugInfo = true;
952 return ParseResult.Success;
956 settings.Checked = true;
957 return ParseResult.Success;
960 settings.Checked = false;
961 return ParseResult.Success;
965 settings.VerifyClsCompliance = true;
966 return ParseResult.Success;
969 settings.VerifyClsCompliance = false;
970 return ParseResult.Success;
974 settings.Unsafe = true;
975 return ParseResult.Success;
978 settings.Unsafe = false;
979 return ParseResult.Success;
982 case "/warnaserror+":
983 if (value.Length == 0) {
984 settings.WarningsAreErrors = true;
985 parser_settings.WarningsAreErrors = true;
987 if (!ProcessWarningsList (value, v => settings.AddWarningAsError (v)))
988 return ParseResult.Error;
990 return ParseResult.Success;
992 case "/warnaserror-":
993 if (value.Length == 0) {
994 settings.WarningsAreErrors = false;
996 if (!ProcessWarningsList (value, v => settings.AddWarningOnly (v)))
997 return ParseResult.Error;
999 return ParseResult.Success;
1003 if (value.Length == 0) {
1004 Error_RequiresArgument (option);
1005 return ParseResult.Error;
1008 SetWarningLevel (value, settings);
1009 return ParseResult.Success;
1012 if (value.Length == 0) {
1013 Error_RequiresArgument (option);
1014 return ParseResult.Error;
1017 if (!ProcessWarningsList (value, v => settings.SetIgnoreWarning (v)))
1018 return ParseResult.Error;
1020 return ParseResult.Success;
1023 settings.LoadDefaultReferences = false;
1024 return ParseResult.Success;
1027 if (value.Length == 0) {
1028 Error_RequiresArgument (option);
1029 return ParseResult.Error;
1032 switch (value.ToLowerInvariant ()) {
1034 settings.Platform = Platform.Arm;
1037 settings.Platform = Platform.AnyCPU;
1040 settings.Platform = Platform.X86;
1043 settings.Platform = Platform.X64;
1046 settings.Platform = Platform.IA64;
1048 case "anycpu32bitpreferred":
1049 settings.Platform = Platform.AnyCPU32Preferred;
1052 report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
1054 return ParseResult.Error;
1057 return ParseResult.Success;
1060 if (value.Length == 0) {
1061 Error_RequiresArgument (option);
1062 return ParseResult.Error;
1065 settings.SdkVersion = value;
1066 return ParseResult.Success;
1068 // We just ignore this.
1069 case "/errorreport":
1071 if (value.Length == 0) {
1072 Error_RequiresArgument (option);
1073 return ParseResult.Error;
1076 return ParseResult.Success;
1078 case "/helpinternal":
1080 return ParseResult.Stop;
1085 return ParseResult.Stop;
1089 if (value.Length == 0) {
1090 Error_RequiresArgument (option);
1091 return ParseResult.Error;
1093 settings.MainClass = value;
1094 return ParseResult.Success;
1098 settings.StdLib = false;
1099 return ParseResult.Success;
1102 settings.StdLib = true;
1103 return ParseResult.Success;
1106 settings.ShowFullPaths = true;
1107 return ParseResult.Success;
1110 if (value.Length == 0) {
1111 Error_RequiresFileName (option);
1112 return ParseResult.Error;
1115 settings.StrongNameKeyFile = value;
1116 return ParseResult.Success;
1118 case "/keycontainer":
1119 if (value.Length == 0) {
1120 Error_RequiresArgument (option);
1121 return ParseResult.Error;
1124 settings.StrongNameKeyContainer = value;
1125 return ParseResult.Success;
1129 settings.StrongNameDelaySign = true;
1130 return ParseResult.Success;
1133 settings.StrongNameDelaySign = false;
1134 return ParseResult.Success;
1136 case "/langversion":
1137 if (value.Length == 0) {
1138 Error_RequiresArgument (option);
1139 return ParseResult.Error;
1142 switch (value.ToLowerInvariant ()) {
1144 settings.Version = LanguageVersion.ISO_1;
1145 return ParseResult.Success;
1147 settings.Version = LanguageVersion.Default;
1148 return ParseResult.Success;
1150 settings.Version = LanguageVersion.ISO_2;
1151 return ParseResult.Success;
1153 settings.Version = LanguageVersion.V_3;
1154 return ParseResult.Success;
1156 settings.Version = LanguageVersion.V_4;
1157 return ParseResult.Success;
1159 settings.Version = LanguageVersion.V_5;
1160 return ParseResult.Success;
1162 settings.Version = LanguageVersion.Future;
1163 return ParseResult.Success;
1166 report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
1167 return ParseResult.Error;
1170 if (value.Length == 0) {
1171 Error_RequiresArgument (option);
1172 return ParseResult.Error;
1177 settings.Encoding = Encoding.UTF8;
1180 settings.Encoding = Encoding.Default;
1184 settings.Encoding = Encoding.GetEncoding (int.Parse (value));
1186 report.Error (2016, "Code page `{0}' is invalid or not installed", value);
1188 return ParseResult.Error;
1190 return ParseResult.Success;
1193 return ParseResult.UnknownOption;
1198 // Currently handles the Unix-like command line options, but will be
1199 // deprecated in favor of the CSCParseOption, which will also handle the
1200 // options that start with a dash in the future.
1202 ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
1206 settings.VerboseParserFlag++;
1207 return ParseResult.Success;
1211 return ParseResult.Stop;
1214 settings.ParseOnly = true;
1215 return ParseResult.Success;
1217 case "--main": case "-m":
1218 report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
1219 if ((i + 1) >= args.Length){
1220 Error_RequiresArgument (arg);
1221 return ParseResult.Error;
1223 settings.MainClass = args[++i];
1224 return ParseResult.Success;
1227 report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
1228 settings.Unsafe = true;
1229 return ParseResult.Success;
1231 case "/?": case "/h": case "/help":
1234 return ParseResult.Stop;
1237 report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
1238 if ((i + 1) >= args.Length){
1239 Error_RequiresArgument (arg);
1240 return ParseResult.Error;
1243 settings.AddConditionalSymbol (args [++i]);
1244 return ParseResult.Success;
1247 settings.TokenizeOnly = true;
1248 return ParseResult.Success;
1252 report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
1253 if ((i + 1) >= args.Length){
1254 Error_RequiresArgument (arg);
1255 return ParseResult.Error;
1257 settings.OutputFile = args[++i];
1258 return ParseResult.Success;
1261 report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
1262 settings.Checked = true;
1263 return ParseResult.Success;
1265 case "--stacktrace":
1266 settings.Stacktrace = true;
1267 return ParseResult.Success;
1269 case "--linkresource":
1271 report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
1272 if ((i + 1) >= args.Length){
1273 Error_RequiresArgument (arg);
1274 return ParseResult.Error;
1277 AddResource (new AssemblyResource (args[++i], args[i]), settings);
1278 return ParseResult.Success;
1282 report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
1283 if ((i + 1) >= args.Length){
1284 Error_RequiresArgument (arg);
1285 return ParseResult.Error;
1288 AddResource (new AssemblyResource (args[++i], args[i], true), settings);
1289 return ParseResult.Success;
1292 report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
1293 if ((i + 1) >= args.Length){
1294 Error_RequiresArgument (arg);
1295 return ParseResult.Error;
1298 string type = args [++i];
1301 settings.Target = Target.Library;
1302 settings.TargetExt = ".dll";
1306 settings.Target = Target.Exe;
1310 settings.Target = Target.WinExe;
1314 settings.Target = Target.Module;
1315 settings.TargetExt = ".dll";
1318 report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
1321 return ParseResult.Success;
1324 report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
1325 if ((i + 1) >= args.Length){
1326 Error_RequiresArgument (arg);
1327 return ParseResult.Error;
1330 string val = args [++i];
1331 int idx = val.IndexOf ('=');
1333 string alias = val.Substring (0, idx);
1334 string assembly = val.Substring (idx + 1);
1335 AddAssemblyReference (alias, assembly, settings);
1336 return ParseResult.Success;
1339 settings.AssemblyReferences.Add (val);
1340 return ParseResult.Success;
1343 report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
1344 if ((i + 1) >= args.Length){
1345 Error_RequiresArgument (arg);
1346 return ParseResult.Error;
1348 settings.ReferencesLookupPaths.Add (args [++i]);
1349 return ParseResult.Success;
1352 settings.EnhancedWarnings = true;
1353 return ParseResult.Success;
1356 report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
1357 settings.StdLib = false;
1358 return ParseResult.Success;
1361 report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
1362 if ((i + 1) >= args.Length){
1363 Error_RequiresArgument (arg);
1364 return ParseResult.Error;
1369 warn = int.Parse (args [++i]);
1372 Environment.Exit (1);
1374 settings.SetIgnoreWarning (warn);
1375 return ParseResult.Success;
1378 report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
1379 if ((i + 1) >= args.Length){
1380 Error_RequiresArgument (arg);
1381 return ParseResult.Error;
1384 SetWarningLevel (args [++i], settings);
1385 return ParseResult.Success;
1388 if ((i + 1) >= args.Length){
1389 Error_RequiresArgument (arg);
1390 return ParseResult.Error;
1394 settings.DebugFlags = int.Parse (args [++i]);
1396 Error_RequiresArgument (arg);
1397 return ParseResult.Error;
1400 return ParseResult.Success;
1404 return ParseResult.Stop;
1407 report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
1408 if ((i + 1) >= args.Length){
1409 Error_RequiresArgument (arg);
1410 return ParseResult.Error;
1412 ProcessSourceFiles (args [++i], true, settings.SourceFiles);
1413 return ParseResult.Success;
1416 settings.Timestamps = true;
1417 return ParseResult.Success;
1419 case "--debug": case "-g":
1420 report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
1421 settings.GenerateDebugInfo = true;
1422 return ParseResult.Success;
1425 report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
1426 settings.LoadDefaultReferences = false;
1427 return ParseResult.Success;
1429 case "--metadata-only":
1430 settings.WriteMetadataOnly = true;
1431 return ParseResult.Success;
1434 if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
1436 if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
1437 int.TryParse (arg.Substring (8), out fatal);
1439 settings.FatalCounter = fatal;
1440 return ParseResult.Success;
1442 if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
1443 string version = arg.Substring (10);
1448 settings.StdLibRuntimeVersion = RuntimeVersion.v1;
1452 settings.StdLibRuntimeVersion = RuntimeVersion.v2;
1456 settings.StdLibRuntimeVersion = RuntimeVersion.v4;
1459 return ParseResult.Success;
1462 return ParseResult.UnknownOption;
1466 void SetWarningLevel (string s, CompilerSettings settings)
1471 level = int.Parse (s);
1474 if (level < 0 || level > 4) {
1475 report.Error (1900, "Warning level must be in the range 0-4");
1478 settings.WarningLevel = level;
1482 // Given a path specification, splits the path from the file/pattern
1484 static void SplitPathAndPattern (string spec, out string path, out string pattern)
1486 int p = spec.LastIndexOf ('/');
1489 // Windows does not like /file.cs, switch that to:
1494 pattern = spec.Substring (1);
1496 path = spec.Substring (0, p);
1497 pattern = spec.Substring (p + 1);
1502 p = spec.LastIndexOf ('\\');
1504 path = spec.Substring (0, p);
1505 pattern = spec.Substring (p + 1);
1516 "Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
1517 "mcs [options] source-files\n" +
1518 " --about About the Mono C# compiler\n" +
1519 " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
1520 " -checked[+|-] Sets default aritmetic overflow context\n" +
1521 " -clscheck[+|-] Disables CLS Compliance verifications\n" +
1522 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
1523 " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
1524 " -debug[+|-], -g Generate debugging information\n" +
1525 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
1526 " -doc:FILE Process documentation comments to XML file\n" +
1527 " -fullpaths Any issued error or warning uses absolute file path\n" +
1528 " -help Lists all compiler options (short: -?)\n" +
1529 " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
1530 " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
1531 " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, 4, 5, Default or Future\n" +
1532 " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
1533 " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
1534 " -noconfig Disables implicitly referenced assemblies\n" +
1535 " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
1536 " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
1537 " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
1538 " -out:FILE Specifies output assembly name\n" +
1539 " -pkg:P1[,Pn] References packages P1..Pn\n" +
1540 " -platform:ARCH Specifies the target platform of the output assembly\n" +
1541 " ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
1542 " x86, x64 or itanium. The default is anycpu.\n" +
1543 " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
1544 " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
1545 " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
1546 " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
1547 " VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
1548 " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
1549 " KIND can be one of: exe, winexe, library, module\n" +
1550 " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
1551 " -warnaserror[+|-] Treats all warnings as errors\n" +
1552 " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
1553 " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
1554 " -helpinternal Shows internal and advanced compiler options\n" +
1557 " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
1558 " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
1559 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
1560 " -win32icon:FILE Use this icon for the output\n" +
1561 " @file Read response file for more options\n\n" +
1562 "Options can be of the form -option or /option");
1567 string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
1568 output.WriteLine ("Mono C# compiler version {0}", version);
1572 public class RootContext
1575 // Contains the parsed tree
1577 static ModuleContainer root;
1579 static public ModuleContainer ToplevelTypes {
1580 get { return root; }
1581 set { root = value; }