WarningLevel = 0
};
- var cc = new Compiler.CompilerContext (reporter) {
+ var settings = new Compiler.CompilerSettings ();
+
+ var cc = new Compiler.CompilerContext (settings, reporter) {
IsRuntimeBinder = true
};
IgnorePrivateMembers = false
};
+ bool reinitialized = Compiler.RootContext.ToplevelTypes != null;
Compiler.RootContext.ToplevelTypes = module;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
importer.ImportAssembly (a, module.GlobalRootNamespace);
}
- if (!Compiler.RootContext.EvalMode) {
+ if (!reinitialized) {
cc.BuildinTypes.CheckDefinitions (module);
module.InitializePredefinedTypes ();
}
-// cs0440.cs: An alias named `global' will not be used when resolving 'global::'; the global namespace will be used instead
+// CS0440: An alias named `global' will not be used when resolving `global::'. The global namespace will be used instead
// Line: 5
// Compiler options: -warn:2 -warnaserror
--- /dev/null
+// CS2006: Missing argument for `/d:' option
+// Line: 0
+// Compiler options: -d:
var hoisted_tparams = ec.CurrentTypeParameters;
var type_params = new TypeParameter[hoisted_tparams.Length];
for (int i = 0; i < type_params.Length; ++i) {
- type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null, null);
+ type_params[i] = hoisted_tparams[i].CreateHoistedCopy (parent, null);
}
generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
readonly IList<AnonymousTypeParameter> parameters;
private AnonymousTypeClass (DeclSpace parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
- : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
+ : base (parent, name, (parent.Compiler.IsEvalutor ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
{
this.parameters = parameters;
}
wrap_non_exception_throws = true;
- delay_sign = RootContext.StrongNameDelaySign;
+ delay_sign = Compiler.Settings.StrongNameDelaySign;
//
// Load strong name key early enough for assembly importer to be able to
// use the keys for InternalsVisibleTo
// This should go somewhere close to ReferencesLoading but don't have the place yet
//
- if (RootContext.StrongNameKeyFile != null || RootContext.StrongNameKeyContainer != null) {
- LoadPublicKey (RootContext.StrongNameKeyFile, RootContext.StrongNameKeyContainer);
+ if (Compiler.Settings.HasKeyFileOrContainer) {
+ LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
}
}
if (value == null || value.Length == 0)
return;
- if (RootContext.Target == Target.Exe) {
+ if (Compiler.Settings.Target == Target.Exe) {
a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
return;
}
if (value == "neutral")
value = "";
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
SetCustomAttribute (ctor, cdata);
} else {
builder_extra.SetCulture (value, a.Location);
return;
}
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
SetCustomAttribute (ctor, cdata);
} else {
builder_extra.SetVersion (vinfo, a.Location);
alg |= ((uint) cdata [pos + 2]) << 16;
alg |= ((uint) cdata [pos + 3]) << 24;
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
SetCustomAttribute (ctor, cdata);
} else {
builder_extra.SetAlgorithmId (alg, a.Location);
if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
flags &= ~(uint) AssemblyNameFlags.PublicKey;
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
SetCustomAttribute (ctor, cdata);
} else {
builder_extra.SetFlags (flags, a.Location);
{
var an = new AssemblyName (name);
- if (public_key != null && RootContext.Target != Target.Module) {
+ if (public_key != null && Compiler.Settings.Target != Target.Module) {
if (delay_sign) {
an.SetPublicKey (public_key);
} else {
public virtual void Emit ()
{
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
module_target_attrs.CreateType ();
module_target_attrs.DefineType ();
ReadModulesAssemblyAttributes ();
}
- if (RootContext.GenerateDebugInfo) {
+ if (Compiler.Settings.GenerateDebugInfo) {
symbol_writer = new MonoSymbolWriter (file_name);
// TODO: global variables
// For attribute based KeyFile do additional lookup
// in output assembly path
//
- if (!key_file_exists && RootContext.StrongNameKeyFile == null) {
+ if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
//
// The key file can be relative to output assembly
//
public void Resolve ()
{
- if (RootContext.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
+ if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
//
// Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
// when -unsafe option was specified
is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
}
- if (added_modules != null && RootContext.VerifyClsCompliance && is_cls_compliant) {
+ if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
foreach (var m in added_modules) {
if (!m.IsCLSCompliant) {
Report.Error (3013,
case "AssemblyKeyFile":
case "AssemblyKeyFileAttribute":
case "System.Reflection.AssemblyKeyFileAttribute":
- if (RootContext.StrongNameKeyFile != null) {
+ if (Compiler.Settings.StrongNameKeyFile != null) {
Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
"keyfile", "System.Reflection.AssemblyKeyFileAttribute");
case "AssemblyKeyName":
case "AssemblyKeyNameAttribute":
case "System.Reflection.AssemblyKeyNameAttribute":
- if (RootContext.StrongNameKeyContainer != null) {
+ if (Compiler.Settings.StrongNameKeyContainer != null) {
Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
"keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
//
// Add Win32 resources
//
- if (RootContext.Win32ResourceFile != null) {
- Builder.DefineUnmanagedResource (RootContext.Win32ResourceFile);
+ if (Compiler.Settings.Win32ResourceFile != null) {
+ Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
} else {
Builder.DefineVersionInfoResource ();
}
- if (RootContext.Win32IconFile != null) {
- builder_extra.DefineWin32IconResource (RootContext.Win32IconFile);
+ if (Compiler.Settings.Win32IconFile != null) {
+ builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
}
- if (RootContext.Resources != null) {
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Resources != null) {
+ if (Compiler.Settings.Target == Target.Module) {
Report.Error (1507, "Cannot link resource file when building a module");
} else {
int counter = 0;
- foreach (var res in RootContext.Resources) {
+ foreach (var res in Compiler.Settings.Resources) {
if (!File.Exists (res.FileName)) {
Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
continue;
PortableExecutableKinds pekind;
ImageFileMachine machine;
- switch (RootContext.Platform) {
+ switch (Compiler.Settings.Platform) {
case Platform.X86:
pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
machine = ImageFileMachine.I386;
Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
try {
- if (RootContext.Target == Target.Module) {
+ if (Compiler.Settings.Target == Target.Module) {
SaveModule (pekind, machine);
} else {
Builder.Save (module.Builder.ScopeName, pekind, machine);
void SetEntryPoint ()
{
- if (!RootContext.NeedsEntryPoint) {
- if (RootContext.MainClass != null)
+ if (!Compiler.Settings.NeedsEntryPoint) {
+ if (Compiler.Settings.MainClass != null)
Report.Error (2017, "Cannot specify -main if building a module or library");
return;
PEFileKinds file_kind;
- switch (RootContext.Target) {
+ switch (Compiler.Settings.Target) {
case Target.Library:
case Target.Module:
file_kind = PEFileKinds.Dll;
}
if (entry_point == null) {
- if (RootContext.MainClass != null) {
+ if (Compiler.Settings.MainClass != null) {
// TODO: Should use MemberCache
- DeclSpace main_cont = module.GetDefinition (RootContext.MainClass) as DeclSpace;
+ DeclSpace main_cont = module.GetDefinition (Compiler.Settings.MainClass) as DeclSpace;
if (main_cont == null) {
- Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
+ Report.Error (1555, "Could not find `{0}' specified for Main method", Compiler.Settings.MainClass);
return;
}
if (!(main_cont is ClassOrStruct)) {
- Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
+ Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", Compiler.Settings.MainClass);
return;
}
{
this.compiler = compiler;
- if (RootContext.LoadDefaultReferences)
+ if (compiler.Settings.LoadDefaultReferences)
default_references = GetDefaultReferences ();
else
default_references = new string[0];
paths = new List<string> ();
- paths.AddRange (RootContext.ReferencesLookupPaths);
+ paths.AddRange (compiler.Settings.ReferencesLookupPaths);
paths.Add (Directory.GetCurrentDirectory ());
}
//
// Load mscorlib.dll as the first
//
- if (RootContext.StdLib) {
+ if (module.Compiler.Settings.StdLib) {
corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
} else {
corlib_assembly = default (T);
loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
}
- foreach (string r in RootContext.AssemblyReferences) {
+ foreach (string r in module.Compiler.Settings.AssemblyReferences) {
a = LoadAssemblyFile (r);
if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
continue;
loaded.Add (key);
}
- foreach (var entry in RootContext.AssemblyReferencesAliases) {
+ foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
a = LoadAssemblyFile (entry.Item2);
if (a == null)
continue;
var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
permissions.Add (cab);
#else
- Type orig_assembly_type = null;
-
- if (Type.MemberDefinition is TypeContainer) {
- if (!RootContext.StdLib) {
- orig_assembly_type = System.Type.GetType (Type.GetMetaInfo ().FullName);
- } else {
- string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
- if (orig_version_path == null) {
- Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
- return;
- }
-
- if (orig_sec_assembly == null) {
- string file = Path.Combine (orig_version_path, Path.GetFileName (RootContext.OutputFile));
- orig_sec_assembly = Assembly.LoadFile (file);
- }
-
- orig_assembly_type = orig_sec_assembly.GetType (Type.GetMetaInfo ().FullName, true);
- if (orig_assembly_type == null) {
- Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
- "was not found in previous version of assembly");
- return;
- }
- }
- }
-
- SecurityAttribute sa;
- object[] args;
-
- // For all non-selfreferencing security attributes we can avoid all hacks
- if (orig_assembly_type == null) {
- args = new object[PosArguments.Count];
- for (int j = 0; j < args.Length; ++j) {
- args[j] = ((Constant) PosArguments[j].Expr).GetValue ();
- }
-
- sa = (SecurityAttribute) Activator.CreateInstance (Type.GetMetaInfo (), args);
-
- if (named_values != null) {
- for (int i = 0; i < named_values.Count; ++i) {
- PropertyInfo pi = ((PropertyExpr) named_values[i].Key).PropertyInfo.MetaInfo;
- pi.SetValue (sa, ((Constant) named_values [i].Value.Expr).GetValue (), null);
- }
- }
- } else {
- // HACK: All security attributes have same ctor syntax
- args = new object[] { GetSecurityActionValue () };
- sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, args);
-
- // All types are from newly created assembly but for invocation with old one we need to convert them
- if (named_values != null) {
- for (int i = 0; i < named_values.Count; ++i) {
- PropertyInfo emited_pi = ((PropertyExpr) named_values[i].Key).PropertyInfo.MetaInfo;
- // FIXME: We are missing return type filter
- // TODO: pi can be null
- PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
-
- pi.SetValue (sa, ((Constant) named_values[i].Value.Expr).GetValue (), null);
- }
- }
- }
-
- IPermission perm;
- perm = sa.CreatePermission ();
- SecurityAction action = (SecurityAction) args [0];
-
- // IS is correct because for corlib we are using an instance from old corlib
- if (!(perm is System.Security.CodeAccessPermission)) {
- switch (action) {
- case SecurityAction.Demand:
- action = (SecurityAction)13;
- break;
- case SecurityAction.LinkDemand:
- action = (SecurityAction)14;
- break;
- case SecurityAction.InheritanceDemand:
- action = (SecurityAction)15;
- break;
- }
- }
-
- if (permissions == null)
- permissions = new SecurityType ();
-
- PermissionSet ps;
- if (!permissions.TryGetValue (action, out ps)) {
- if (sa is PermissionSetAttribute)
- ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
- else
- ps = new PermissionSet (PermissionState.None);
-
- permissions.Add (action, ps);
- } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
- ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
- permissions [action] = ps;
- }
- ps.AddPermission (perm);
+ throw new NotSupportedException ();
#endif
}
}
}
- if (!RootContext.VerifyClsCompliance)
+ if (!context.Module.Compiler.Settings.VerifyClsCompliance)
return;
// Here we are testing attribute arguments for array usage (error 3016)
if (initialized_static_fields == null)
return;
- bool has_complex_initializer = !RootContext.Optimize;
+ bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize;
int i;
ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
for (i = 0; i < initialized_static_fields.Count; ++i) {
//
// Field is re-initialized to its default value => removed
//
- if (fi.IsDefaultInitializer && RootContext.Optimize)
+ if (fi.IsDefaultInitializer && ec.Module.Compiler.Settings.Optimize)
continue;
ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
for (int i = 0; i < type_params.Length; ++i) {
var tp = hoisted_tparams[i];
targs.Add (new TypeParameterName (tp.Name, null, Location));
- type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
+ type_params[i] = new TypeParameter (tp, this, null, new MemberName (tp.Name), null);
}
member_name = new MemberName (name, targs, Location);
// Check for internal or private fields that were never assigned
//
if (Report.WarningLevel >= 3) {
- if (RootContext.EnhancedWarnings) {
+ if (Compiler.Settings.EnhancedWarnings) {
CheckMemberUsage (properties, "property");
CheckMemberUsage (methods, "method");
CheckMemberUsage (constants, "constant");
if (instance_constructors == null)
return;
- if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
+ if (spec.IsAttribute && IsExposedFromAssembly () && Compiler.Settings.VerifyClsCompliance && IsClsComplianceRequired ()) {
bool has_compliant_args = false;
foreach (Constructor c in instance_constructors) {
var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
spec = new TypeSpec (Kind, null, this, null, ModFlags);
-
- if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotAvailable (Location, "static classes");
- }
}
public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
// Use string.Empty for both literals and constants even if
// it's not allowed at language level
//
- if (Value.Length == 0 && RootContext.Optimize && ec.CurrentType != TypeManager.string_type) {
+ if (Value.Length == 0 && ec.Module.Compiler.Settings.Optimize && ec.CurrentType != TypeManager.string_type) {
if (TypeManager.string_empty == null)
TypeManager.string_empty = TypeManager.GetPredefinedField (TypeManager.string_type, "Empty", loc, TypeManager.string_type);
//
// The default setting comes from the command line option
//
- if (RootContext.Checked)
+ if (mc.Module.Compiler.Settings.Checked)
flags |= Options.CheckedScope;
//
readonly Report report;
readonly BuildinTypes buildin_types;
+ readonly CompilerSettings settings;
- public CompilerContext (Report report)
+ public CompilerContext (CompilerSettings settings, Report report)
{
+ this.settings = settings;
this.report = report;
this.buildin_types = new BuildinTypes ();
this.TimeReporter = DisabledTimeReporter;
// Used for special handling of runtime dynamic context mostly
// by error reporting but also by member accessibility checks
- public bool IsRuntimeBinder { get; set; }
+ public bool IsRuntimeBinder {
+ get; set;
+ }
+
+ //
+ // If true, it means that the compiler is executing as
+ // in eval mode so unresolved variables are resolved in
+ // static classes maintained by the eval engine.
+ //
+ public bool IsEvalutor {
+ get; set;
+ }
public Report Report {
get {
}
}
- internal TimeReporter TimeReporter { get; set; }
+ public CompilerSettings Settings {
+ get {
+ return settings;
+ }
+ }
+
+ internal TimeReporter TimeReporter {
+ get; set;
+ }
#endregion
}
}
if (expr.eclass == ExprClass.MethodGroup) {
- if (target_type.IsDelegate && RootContext.Version != LanguageVersion.ISO_1) {
+ if (target_type.IsDelegate && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
MethodGroupExpr mg = expr as MethodGroupExpr;
if (mg != null)
return DelegateCreation.ImplicitStandardConversionExists (ec, mg, target_type);
//
// Only allow anonymous method conversions on post ISO_1
//
- if (RootContext.Version != LanguageVersion.ISO_1){
+ if (ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1){
MethodGroupExpr mg = expr as MethodGroupExpr;
if (mg != null)
return ImplicitDelegateCreation.Create (
ModuleContainer module;
- CompilerContext compiler;
+ readonly CompilerContext compiler;
+ readonly LanguageVersion lang_version;
+ readonly bool doc_support;
+ readonly CompilerSettings settings;
//
// Instead of allocating carrier array everytime we
string s = lt.Value;
if (s != "alias"){
syntax_error (lt.Location, "`alias' expected");
- } else if (RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotAvailable (lt.Location, "external alias");
+ } else if (lang_version == LanguageVersion.ISO_1) {
+ FeatureIsNotAvailable (lt.Location, "external alias");
} else {
lt = (Tokenizer.LocatedToken) $3;
current_namespace.AddUsingExternalAlias (lt.Value, lt.Location, Report);
using_directive
: using_alias_directive
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
| using_namespace_directive
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
;
: USING IDENTIFIER ASSIGN namespace_or_type_name SEMICOLON
{
var lt = (Tokenizer.LocatedToken) $2;
+ if (lang_version != LanguageVersion.ISO_1 && lt.Value == "global") {
+ Report.Warning (440, 2, lt.Location,
+ "An alias named `global' will not be used when resolving `global::'. The global namespace will be used instead");
+ }
+
current_namespace.AddUsingAlias (lt.Value, (MemberName) $4, GetLocation ($1));
}
| USING error
namespace_body
: OPEN_BRACE
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_extern_alias_directives
$$ = new Attributes (sect);
}
if ($$ == null) {
- if (RootContext.Documentation != null) {
+ if (doc_support) {
Lexer.check_incorrect_doc_comment ();
Lexer.doc_state =
XmlCommentState.Allowed;
named_argument
: IDENTIFIER COLON opt_named_modifier expression
{
- if (RootContext.Version <= LanguageVersion.V_3)
- Report.FeatureIsNotAvailable (GetLocation ($1), "named argument");
+ if (lang_version <= LanguageVersion.V_3)
+ FeatureIsNotAvailable (GetLocation ($1), "named argument");
// Avoid boxing in common case (no modifier)
var arg_mod = $3 == null ? Argument.AType.None : (Argument.AType) $3;
current_class.SetParameterInfo ((List<Constraints>) $9);
- if (RootContext.Documentation != null)
+ if (doc_support)
current_container.DocComment = Lexer.consume_doc_comment ();
lbag.AddMember (current_class, mod_locations, GetLocation ($4));
struct_body
{
--lexer.parsing_declaration;
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_semicolon
struct_body
: OPEN_BRACE
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_struct_member_declarations CLOSE_BRACE
}
constant_initializer opt_constant_declarators SEMICOLON
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_field.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_field_declarators
SEMICOLON
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_field.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_modifiers
FIXED simple_type IDENTIFIER
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($3), "fixed size buffers");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($3), "fixed size buffers");
var lt = (Tokenizer.LocatedToken) $5;
current_field = new FixedField (current_class, (FullNamedExpression) $4, (Modifiers) $2,
}
fixed_field_size opt_fixed_field_declarators SEMICOLON
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_field.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
method_declaration
: method_header
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.NotAllowed;
// Add it early in the case of body being eof for full aot
current_local_parameters = null;
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
;
method.GetSignatureForError ());
}
- if (RootContext.Documentation != null)
+ if (doc_support)
method.DocComment = Lexer.consume_doc_comment ();
lbag.AddMember (method, mod_locations, GetLocation ($5), GetLocation ($8));
method = new Method (current_class, generic, new TypeExpression (TypeManager.void_type, GetLocation ($4)),
modifiers, name, current_local_parameters, (Attributes) $1);
- if (RootContext.Documentation != null)
+ if (doc_support)
method.DocComment = Lexer.consume_doc_comment ();
// TODO: lbag, push void
current_local_parameters = (ParametersCompiled) $7;
- if (RootContext.Documentation != null)
+ if (doc_support)
method.DocComment = Lexer.consume_doc_comment ();
$$ = method;
constant_expression
{
--lexer.parsing_block;
- if (RootContext.Version <= LanguageVersion.V_3) {
- Report.FeatureIsNotAvailable (GetLocation ($5), "optional parameter");
+ if (lang_version <= LanguageVersion.V_3) {
+ FeatureIsNotAvailable (GetLocation ($5), "optional parameter");
}
Parameter.Modifier mod = (Parameter.Modifier) $2;
if ((valid_param_mod & ParameterModifierType.This) == 0)
Error_ParameterModifierNotValid ("this", GetLocation ($1));
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "extension methods");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "extension methods");
$$ = Parameter.Modifier.This;
}
member_type
member_declaration_name
{
- if (RootContext.Documentation != null)
+ if (doc_support)
tmpComment = Lexer.consume_doc_comment ();
}
OPEN_BRACE
{
lexer.PropertyParsing = false;
- if (RootContext.Documentation != null)
+ if (doc_support)
current_property.DocComment = ConsumeStoredComment ();
}
CLOSE_BRACE
Report.Error (1551, GetLocation ($5), "Indexers must have at least one parameter");
}
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
}
CLOSE_BRACE
{
- if (RootContext.Documentation != null)
+ if (doc_support)
current_property.DocComment = ConsumeStoredComment ();
lbag.AppendToMember (current_property, GetLocation ($12));
get_accessor_declaration
: opt_attributes opt_modifiers GET
{
- if ($2 != ModifierNone && RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
+ if ($2 != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+ FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
}
if (current_property.Get != null) {
current_local_parameters = null;
lexer.PropertyParsing = true;
- if (RootContext.Documentation != null)
+ if (doc_support)
if (Lexer.doc_state == XmlCommentState.Error)
Lexer.doc_state = XmlCommentState.NotAllowed;
}
set_accessor_declaration
: opt_attributes opt_modifiers SET
{
- if ($2 != ModifierNone && RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
+ if ($2 != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+ FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
}
if (current_property.Set != null) {
current_local_parameters = null;
lexer.PropertyParsing = true;
- if (RootContext.Documentation != null
+ if (doc_support
&& Lexer.doc_state == XmlCommentState.Error)
Lexer.doc_state = XmlCommentState.NotAllowed;
}
current_class.SetParameterInfo ((List<Constraints>) $9);
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_container.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
OPEN_BRACE opt_interface_member_declarations CLOSE_BRACE
{
--lexer.parsing_declaration;
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_semicolon
current_local_parameters,
(ToplevelBlock) $5, (Attributes) $1, decl.location);
- if (RootContext.Documentation != null) {
+ if (doc_support) {
op.DocComment = tmpComment;
Lexer.doc_state = XmlCommentState.Allowed;
}
}
}
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.NotAllowed;
}
Location loc = GetLocation ($2);
current_local_parameters = (ParametersCompiled)$6;
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.NotAllowed;
}
Location loc = GetLocation ($2);
current_local_parameters = (ParametersCompiled)$6;
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.NotAllowed;
}
Constructor c = (Constructor) $1;
c.Block = (ToplevelBlock) $2;
- if (RootContext.Documentation != null)
+ if (doc_support)
c.DocComment = ConsumeStoredComment ();
current_container.AddConstructor (c);
current_local_parameters = null;
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
;
opt_modifiers
IDENTIFIER
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
destructor_declaration
: opt_attributes opt_modifiers TILDE
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.NotAllowed;
}
Destructor d = new Destructor (current_class, (Modifiers) $2,
ParametersCompiled.EmptyReadOnlyParameters, (Attributes) $1, lt.Location);
- if (RootContext.Documentation != null)
+ if (doc_support)
d.DocComment = ConsumeStoredComment ();
d.Block = (ToplevelBlock) $8;
opt_event_declarators
SEMICOLON
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_event_field.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
}
CLOSE_BRACE
{
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_event.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
ENUM type_declaration_name
opt_enum_base
{
- if (RootContext.Documentation != null)
+ if (doc_support)
enumTypeComment = Lexer.consume_doc_comment ();
}
OPEN_BRACE
{
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
MemberName name = (MemberName) $4;
opt_enum_member_declarations
{
// here will be evaluated after CLOSE_BLACE is consumed.
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
CLOSE_BRACE opt_semicolon
{
- if (RootContext.Documentation != null)
+ if (doc_support)
current_class.DocComment = enumTypeComment;
--lexer.parsing_declaration;
-// if (RootContext.Documentation != null)
+// if (doc_support)
// em.DocComment = ev.DocComment;
lbag.AddMember (current_class, mod_locations, GetLocation ($3), GetLocation ($7), GetLocation ($11));
var em = new EnumMember ((Enum) current_class, new MemberName (lt.Value, lt.Location), (Attributes) $1);
((Enum) current_class).AddEnumMember (em);
- if (RootContext.Documentation != null) {
+ if (doc_support) {
em.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
| opt_attributes IDENTIFIER
{
++lexer.parsing_block;
- if (RootContext.Documentation != null) {
+ if (doc_support) {
tmpComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.NotAllowed;
}
em.Initializer = new ConstInitializer (em, (Expression) $5, GetLocation ($4));
((Enum) current_class).AddEnumMember (em);
- if (RootContext.Documentation != null)
+ if (doc_support)
em.DocComment = ConsumeStoredComment ();
$$ = em;
Delegate del = new Delegate (current_namespace, current_class, (FullNamedExpression) $4,
(Modifiers) $2, name, p, (Attributes) $1);
- if (RootContext.Documentation != null) {
+ if (doc_support) {
del.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
: /* empty */
| INTERR_NULLABLE
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "nullable types");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "nullable types");
$$ = ComposedTypeSpecifier.CreateNullable (GetLocation ($1));
}
: /* empty */
| OP_GENERICS_LT type_arguments OP_GENERICS_GT
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "generics");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "generics");
$$ = $2;
}
: /* empty */
| OP_GENERICS_LT_DECL type_parameters OP_GENERICS_GT
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "generics");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "generics");
$$ = $2;
lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
: NEW new_expr_type open_parens_any opt_argument_list CLOSE_PARENS opt_object_or_collection_initializer
{
if ($6 != null) {
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "object initializers");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "object initializers");
$$ = new NewInitialize ((FullNamedExpression) $2, (Arguments) $4, (CollectionOrObjectInitializers) $6, GetLocation ($1));
} else {
}
| NEW new_expr_type object_or_collection_initializer
{
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "collection initializers");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "collection initializers");
$$ = new NewInitialize ((FullNamedExpression) $2, null, (CollectionOrObjectInitializers) $3, GetLocation ($1));
}
}
| NEW rank_specifier array_initializer
{
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "implicitly typed arrays");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "implicitly typed arrays");
$$ = new ImplicitlyTypedArrayCreation ((ComposedTypeSpecifier) $2, (ArrayInitializer) $3, GetLocation ($1));
}
anonymous_type_expression
: NEW OPEN_BRACE anonymous_type_parameters_opt_comma CLOSE_BRACE
{
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "anonymous types");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "anonymous types");
$$ = new NewAnonymousType ((List<AnonymousTypeParameter>) $3, current_container, GetLocation ($1));
generic_dimension
: GENERIC_DIMENSION
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "generics");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "generics");
$$ = $1;
}
: IDENTIFIER DOUBLE_COLON
{
var lt = (Tokenizer.LocatedToken) $1;
- if (RootContext.Version == LanguageVersion.ISO_1)
- Report.FeatureIsNotAvailable (lt.Location, "namespace alias qualifier");
+ if (lang_version == LanguageVersion.ISO_1)
+ FeatureIsNotAvailable (lt.Location, "namespace alias qualifier");
$$ = lt;
}
default_value_expression
: DEFAULT open_parens_any type CLOSE_PARENS
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "default value expression");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "default value expression");
$$ = new DefaultValueExpression ((Expression) $3, GetLocation ($1));
lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
: conditional_or_expression
| conditional_or_expression OP_COALESCING null_coalescing_expression
{
- if (RootContext.Version < LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($2), "null coalescing operator");
+ if (lang_version < LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($2), "null coalescing operator");
$$ = new Nullable.NullCoalescingOperator ((Expression) $1, (Expression) $3, GetLocation ($2));
}
}
| OPEN_PARENS_LAMBDA
{
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (GetLocation ($1), "lambda expressions");
+ if (lang_version <= LanguageVersion.ISO_2)
+ FeatureIsNotAvailable (GetLocation ($1), "lambda expressions");
valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
}
type_declaration_name
{
MemberName name = MakeName ((MemberName) $6);
- push_current_class (new Class (current_namespace, current_class, name, (Modifiers) $2, (Attributes) $1), $3);
+ Class c = new Class (current_namespace, current_class, name, (Modifiers) $2, (Attributes) $1);
+ if (((c.ModFlags & Modifiers.STATIC) != 0) && lang_version == LanguageVersion.ISO_1) {
+ FeatureIsNotAvailable (c.Location, "static classes");
+ }
+
+ push_current_class (c, $3);
}
opt_class_base
opt_type_parameter_constraints_clauses
current_class.SetParameterInfo ((List<Constraints>) $9);
lbag.AddMember (current_class, mod_locations, GetLocation ($4));
- if (RootContext.Documentation != null) {
+ if (doc_support) {
current_container.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
OPEN_BRACE opt_class_member_declarations CLOSE_BRACE
{
--lexer.parsing_declaration;
- if (RootContext.Documentation != null)
+ if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_semicolon
{
$$ = Modifiers.UNSAFE;
StoreModifierLocation ($$, GetLocation ($1));
- if (!RootContext.Unsafe)
+ if (!settings.Unsafe)
Error_UnsafeCodeNotAllowed (GetLocation ($1));
}
| ASYNC
}
| type_parameter_variance
{
- if (RootContext.Version <= LanguageVersion.V_3)
- Report.FeatureIsNotAvailable (lexer.Location, "generic type variance");
+ if (lang_version <= LanguageVersion.V_3)
+ FeatureIsNotAvailable (lexer.Location, "generic type variance");
$$ = $1;
}
Report.Error (1003, lt.Location, "; expected");
} else if ($3 == null) {
Report.Error (1627, GetLocation ($4), "Expression expected after yield return");
- } else if (RootContext.Version == LanguageVersion.ISO_1){
- Report.FeatureIsNotAvailable (lt.Location, "iterators");
+ } else if (lang_version == LanguageVersion.ISO_1){
+ FeatureIsNotAvailable (lt.Location, "iterators");
}
current_block.ParametersBlock.TopBlock.IsIterator = true;
string s = lt.Value;
if (s != "yield"){
Report.Error (1003, lt.Location, "; expected");
- } else if (RootContext.Version == LanguageVersion.ISO_1){
- Report.FeatureIsNotAvailable (lt.Location, "iterators");
+ } else if (lang_version == LanguageVersion.ISO_1){
+ FeatureIsNotAvailable (lt.Location, "iterators");
}
current_block.ParametersBlock.TopBlock.IsIterator = true;
unsafe_statement
: UNSAFE
{
- if (!RootContext.Unsafe)
+ if (!settings.Unsafe)
Error_UnsafeCodeNotAllowed (GetLocation ($1));
} block {
$$ = new Unsafe ((Block) $3, GetLocation ($1));
mpar [0] = new Parameter (new TypeExpression (TypeManager.object_type, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null);
ParametersCompiled pars = new ParametersCompiled (mpar);
+ var mods = Modifiers.PUBLIC | Modifiers.STATIC;
+ if (settings.Unsafe)
+ mods |= Modifiers.UNSAFE;
+
current_local_parameters = pars;
Method method = new Method (
current_class,
null, // generic
new TypeExpression (TypeManager.void_type, Location.Null),
- Modifiers.PUBLIC | Modifiers.STATIC,
+ mods,
new MemberName ("Host"),
pars,
null /* attributes */);
void push_current_class (TypeContainer tc, object partial_token)
{
- if (RootContext.EvalMode){
+ if (compiler.IsEvalutor){
tc.Definition.Modifiers = tc.ModFlags = (tc.ModFlags & ~Modifiers.AccessibilityMask) | Modifiers.PUBLIC;
+ if (undo == null)
+ undo = new Undo ();
undo.AddTypeContainer (current_container, tc);
}
public CSharpParser (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module, NamespaceEntry ns)
{
- if (RootContext.EvalMode)
- undo = new Undo ();
-
this.file = file;
this.module = module;
this.compiler = module.Compiler;
+ this.settings = compiler.Settings;
+ lang_version = settings.Version;
+ doc_support = settings.Documentation != null;
current_namespace = ns;
current_class = current_namespace.SlaveDeclSpace;
current_container = current_class.PartialContainer; // == RootContest.ToplevelTypes
return s;
}
+void FeatureIsNotAvailable (Location loc, string feature)
+{
+ compiler.Report.FeatureIsNotAvailable (compiler, loc, feature);
+}
+
Location GetLocation (object obj)
{
var lt = obj as Tokenizer.LocatedToken;
void start_anonymous (bool lambda, ParametersCompiled parameters, Location loc)
{
- if (RootContext.Version == LanguageVersion.ISO_1){
- Report.FeatureIsNotAvailable (loc, "anonymous methods");
+ if (lang_version == LanguageVersion.ISO_1){
+ FeatureIsNotAvailable (loc, "anonymous methods");
}
oob_stack.Push (current_anonymous_method);
res = Token.FROM_FIRST;
query_parsing = true;
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (Location, "query expressions");
+ if (context.Settings.Version <= LanguageVersion.ISO_2)
+ Report.FeatureIsNotAvailable (context, Location, "query expressions");
break;
case Token.VOID:
Expression.Error_VoidInvalidInTheContext (Location, Report);
if (ok) {
if (next_token == Token.VOID) {
- if (RootContext.Version == LanguageVersion.ISO_1 ||
- RootContext.Version == LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (Location, "partial methods");
- } else if (RootContext.Version == LanguageVersion.ISO_1)
- Report.FeatureIsNotAvailable (Location, "partial types");
+ if (context.Settings.Version <= LanguageVersion.ISO_2)
+ Report.FeatureIsNotAvailable (context, Location, "partial methods");
+ } else if (context.Settings.Version == LanguageVersion.ISO_1)
+ Report.FeatureIsNotAvailable (context, Location, "partial types");
return res;
}
break;
case Token.ASYNC:
- if (parsing_block > 0 || RootContext.Version != LanguageVersion.Future) {
+ if (parsing_block > 0 || context.Settings.Version != LanguageVersion.Future) {
res = -1;
break;
}
return true;
case PreprocessorDirective.Pragma:
- if (RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotAvailable (Location, "#pragma");
+ if (context.Settings.Version == LanguageVersion.ISO_1) {
+ Report.FeatureIsNotAvailable (context, Location, "#pragma");
}
ParsePragmaDirective (arg);
// Handle double-slash comments.
if (d == '/'){
get_char ();
- if (RootContext.Documentation != null && peek_char () == '/') {
+ if (context.Settings.Documentation != null && peek_char () == '/') {
get_char ();
// Don't allow ////.
if ((d = peek_char ()) != '/') {
} else if (d == '*'){
get_char ();
bool docAppend = false;
- if (RootContext.Documentation != null && peek_char () == '*') {
+ if (context.Settings.Documentation != null && peek_char () == '*') {
get_char ();
update_comment_location ();
// But when it is /**/, just do nothing.
}
} else {
if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
- if (RootContext.Version >= LanguageVersion.V_3) {
+ if (Compiler.Settings.Version >= LanguageVersion.V_3) {
Property.PropertyMethod pm = this as Property.PropertyMethod;
if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
pm = null;
/// </summary>
public virtual void Emit ()
{
- if (!RootContext.VerifyClsCompliance)
+ if (!Compiler.Settings.VerifyClsCompliance)
return;
VerifyClsCompliance ();
CheckProtectedModifier ();
- if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
+ if (Compiler.Settings.StdLib && TypeManager.IsSpecialType (ret_type)) {
Method.Error1599 (Location, ret_type, Report);
return false;
}
//
// 15.2 Delegate compatibility
//
- public static bool IsTypeCovariant (Expression a, TypeSpec b)
+ public static bool IsTypeCovariant (ResolveContext rc, Expression a, TypeSpec b)
{
//
// For each value parameter (a parameter with no ref or out modifier), an
if (a.Type == b)
return true;
- if (RootContext.Version == LanguageVersion.ISO_1)
+ if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
return false;
return Convert.ImplicitReferenceConversionExists (a, b);
TypeSpec rt = delegate_method.ReturnType;
Expression ret_expr = new TypeExpression (rt, loc);
- if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
+ if (!Delegate.IsTypeCovariant (ec, ret_expr, invoke_method.ReturnType)) {
Error_ConversionFailed (ec, delegate_method, ret_expr);
}
ec.Report.SymbolRelatedToPreviousError (type);
ec.Report.SymbolRelatedToPreviousError (method);
- if (RootContext.Version == LanguageVersion.ISO_1) {
+ if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
ec.Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
TypeManager.CSharpName (method.ReturnType), member_name,
TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
Expression e = a.Expr;
AnonymousMethodExpression ame = e as AnonymousMethodExpression;
- if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
+ if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
e = ame.Compatible (ec, type);
if (e == null)
return null;
// FIXME: It could be even optimizable as not
// to use XmlDocument. But anyways the nodes
// are not kept in memory.
- XmlDocument doc = RootContext.Documentation.XmlDocumentation;
+ XmlDocument doc = mc.Compiler.Settings.Documentation.XmlDocumentation;
try {
XmlElement el = doc.CreateElement ("member");
el.SetAttribute ("name", name);
HandleException (mc, ds_target, see, Report);
}
- n.WriteTo (RootContext.Documentation.XmlCommentOutput);
+ n.WriteTo (mc.Compiler.Settings.Documentation.XmlCommentOutput);
}
else if (mc.IsExposedFromAssembly ()) {
Constructor c = mc as Constructor;
}
else {
XmlDocument doc;
- if (!RootContext.Documentation.StoredDocuments.TryGetValue (file, out doc)) {
+ if (!mc.Compiler.Settings.Documentation.StoredDocuments.TryGetValue (file, out doc)) {
try {
doc = new XmlDocument ();
doc.Load (file);
- RootContext.Documentation.StoredDocuments.Add (file, doc);
+ mc.Compiler.Settings.Documentation.StoredDocuments.Add (file, doc);
} catch (Exception) {
el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file `{0}': cannot be included ", file)), el);
Report.Warning (1592, 1, mc.Location, "Badly formed XML in included comments file -- `{0}'", file);
/// </summary>
class Driver
{
- string first_source;
+ readonly CompilerContext ctx;
- internal int fatal_errors;
-
- internal readonly CompilerContext ctx;
-
- static readonly char[] argument_value_separator = new char [] { ';', ',' };
-
- private Driver (CompilerContext ctx)
+ public Driver (CompilerContext ctx)
{
this.ctx = ctx;
}
- public static Driver Create (string[] args, bool require_files, Func<string [], int, int> unknown_option_parser, ReportPrinter printer)
- {
- Driver d = new Driver (new CompilerContext (new Report (printer)));
-
- if (!d.ParseArguments (args, require_files, unknown_option_parser))
- return null;
-
- return d;
- }
-
Report Report {
- get { return ctx.Report; }
+ get {
+ return ctx.Report;
+ }
}
-
- void tokenize_file (CompilationUnit file, CompilerContext ctx)
+
+ void tokenize_file (CompilationUnit file)
{
Stream input;
}
using (input){
- SeekableStreamReader reader = new SeekableStreamReader (input, RootContext.Encoding);
+ SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
Tokenizer lexer = new Tokenizer (reader, file, ctx);
int token, tokens = 0, errors = 0;
return;
}
+ void Parse (ModuleContainer module)
+ {
+ Location.Initialize ();
+
+ bool tokenize_only = ctx.Settings.TokenizeOnly;
+ var cu = Location.SourceFiles;
+ for (int i = 0; i < cu.Count; ++i) {
+ if (tokenize_only) {
+ tokenize_file (cu[i]);
+ } else {
+ Parse (cu[i], module);
+ }
+ }
+ }
+
void Parse (CompilationUnit file, ModuleContainer module)
{
Stream input;
}
input.Position = 0;
- SeekableStreamReader reader = new SeekableStreamReader (input, RootContext.Encoding);
+ SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
Parse (reader, file, module);
reader.Dispose ();
input.Close ();
}
- void Parse (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
+ public void Parse (SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
{
CSharpParser parser = new CSharpParser (reader, file, module);
parser.parse ();
}
-
- static void OtherFlags ()
- {
- Console.WriteLine (
- "Other flags in the compiler\n" +
- " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
- " --lint Enhanced warnings\n" +
- " --parse Only parses the source file\n" +
- " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
- " --stacktrace Shows stack trace at error location\n" +
- " --timestamp Displays time stamps of various compiler events\n" +
- " -v Verbose parsing (for debugging the parser)\n" +
- " --mcs-debug X Sets MCS debugging level to X\n");
- }
-
- static void Usage ()
- {
- Console.WriteLine (
- "Mono C# compiler, Copyright 2001 - 2011 Novell, Inc.\n" +
- "mcs [options] source-files\n" +
- " --about About the Mono C# compiler\n" +
- " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
- " -checked[+|-] Sets default aritmetic overflow context\n" +
- " -clscheck[+|-] Disables CLS Compliance verifications\n" +
- " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
- " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
- " -debug[+|-], -g Generate debugging information\n" +
- " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
- " -doc:FILE Process documentation comments to XML file\n" +
- " -fullpaths Any issued error or warning uses absolute file path\n" +
- " -help Lists all compiler options (short: -?)\n" +
- " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
- " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
- " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default or Future\n" +
- " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
- " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
- " -noconfig Disables implicitly referenced assemblies\n" +
- " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
- " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
- " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
- " -out:FILE Specifies output assembly name\n" +
- " -pkg:P1[,Pn] References packages P1..Pn\n" +
- " -platform:ARCH Specifies the target platform of the output assembly\n" +
- " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
- " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
- " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
- " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
- " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
- " VERSION can be one of: 2, 4 (default) or custom value\n" +
- " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
- " KIND can be one of: exe, winexe, library, module\n" +
- " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
- " -warnaserror[+|-] Treats all warnings as errors\n" +
- " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
- " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
- " -helpinternal Shows internal and advanced compiler options\n" +
- "\n" +
- "Resources:\n" +
- " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
- " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
- " -win32res:FILE Specifies Win32 resource file (.res)\n" +
- " -win32icon:FILE Use this icon for the output\n" +
- " @file Read response file for more options\n\n" +
- "Options can be of the form -option or /option");
- }
-
- void TargetUsage ()
- {
- Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
- }
- static void About ()
- {
- Console.WriteLine (
- "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
- "The compiler source code is released under the terms of the \n"+
- "MIT X11 or GNU GPL licenses\n\n" +
-
- "For more information on Mono, visit the project Web site\n" +
- " http://www.mono-project.com\n\n" +
-
- "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
- Environment.Exit (0);
- }
-
public static int Main (string[] args)
{
Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
- var crp = new ConsoleReportPrinter ();
- Driver d = Driver.Create (args, true, null, crp);
- if (d == null)
+
+ var r = new Report (new ConsoleReportPrinter ());
+ CommandLineParser cmd = new CommandLineParser (r);
+ var settings = cmd.ParseArguments (args);
+ if (settings == null || r.Errors > 0)
return 1;
- crp.Fatal = d.fatal_errors;
+ Driver d = new Driver (new CompilerContext (settings, r));
if (d.Compile () && d.Report.Errors == 0) {
if (d.Report.Warnings > 0) {
return 1;
}
- static string [] LoadArgs (string file)
- {
- StreamReader f;
- var args = new List<string> ();
- string line;
- try {
- f = new StreamReader (file);
- } catch {
- return null;
- }
-
- StringBuilder sb = new StringBuilder ();
-
- while ((line = f.ReadLine ()) != null){
- int t = line.Length;
-
- for (int i = 0; i < t; i++){
- char c = line [i];
-
- if (c == '"' || c == '\''){
- char end = c;
-
- for (i++; i < t; i++){
- c = line [i];
-
- if (c == end)
- break;
- sb.Append (c);
- }
- } else if (c == ' '){
- if (sb.Length > 0){
- args.Add (sb.ToString ());
- sb.Length = 0;
- }
- } else
- sb.Append (c);
- }
- if (sb.Length > 0){
- args.Add (sb.ToString ());
- sb.Length = 0;
- }
- }
-
- return args.ToArray ();
- }
-
- //
- // Given a path specification, splits the path from the file/pattern
- //
- static void SplitPathAndPattern (string spec, out string path, out string pattern)
- {
- int p = spec.LastIndexOf ('/');
- if (p != -1){
- //
- // Windows does not like /file.cs, switch that to:
- // "\", "file.cs"
- //
- if (p == 0){
- path = "\\";
- pattern = spec.Substring (1);
- } else {
- path = spec.Substring (0, p);
- pattern = spec.Substring (p + 1);
- }
- return;
- }
-
- p = spec.LastIndexOf ('\\');
- if (p != -1){
- path = spec.Substring (0, p);
- pattern = spec.Substring (p + 1);
- return;
- }
-
- path = ".";
- pattern = spec;
- }
-
- void AddSourceFile (string f)
- {
- if (first_source == null)
- first_source = f;
-
- Location.AddFile (Report, f);
- }
-
- bool ParseArguments (string[] args, bool require_files, Func<string [], int, int> unknown_option_parser)
- {
- List<string> response_file_list = null;
- bool parsing_options = true;
-
- for (int i = 0; i < args.Length; i++) {
- string arg = args [i];
- if (arg.Length == 0)
- continue;
-
- if (arg [0] == '@') {
- string [] extra_args;
- string response_file = arg.Substring (1);
-
- if (response_file_list == null)
- response_file_list = new List<string> ();
-
- if (response_file_list.Contains (response_file)) {
- Report.Error (
- 1515, "Response file `" + response_file +
- "' specified multiple times");
- return false;
- }
-
- response_file_list.Add (response_file);
-
- extra_args = LoadArgs (response_file);
- if (extra_args == null) {
- Report.Error (2011, "Unable to open response file: " +
- response_file);
- return false;
- }
-
- args = AddArgs (args, extra_args);
- continue;
- }
-
- if (parsing_options) {
- if (arg == "--") {
- parsing_options = false;
- continue;
- }
-
- if (arg [0] == '-') {
- if (UnixParseOption (arg, ref args, ref i))
- continue;
-
- // Try a -CSCOPTION
- string csc_opt = "/" + arg.Substring (1);
- if (CSCParseOption (csc_opt, ref args))
- continue;
-
- if (unknown_option_parser != null){
- var ret = unknown_option_parser (args, i);
- if (ret != -1){
- i = ret;
- return true;
- }
- }
-
- Error_WrongOption (arg);
- return false;
- }
- if (arg [0] == '/') {
- if (CSCParseOption (arg, ref args))
- continue;
-
- // Need to skip `/home/test.cs' however /test.cs is considered as error
- if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
- Error_WrongOption (arg);
- return false;
- }
- }
- }
-
- ProcessSourceFiles (arg, false);
- }
-
- if (require_files == false)
- return true;
-
- //
- // If we are an exe, require a source file for the entry point
- //
- if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe || RootContext.Target == Target.Module) {
- if (first_source == null) {
- Report.Error (2008, "No files to compile were specified");
- return false;
- }
-
- }
-
- //
- // If there is nothing to put in the assembly, and we are not a library
- //
- if (first_source == null && RootContext.Resources == null) {
- Report.Error (2008, "No files to compile were specified");
- return false;
- }
-
- return true;
- }
-
- public void Parse (ModuleContainer module)
- {
- Location.Initialize ();
-
- var cu = Location.SourceFiles;
- for (int i = 0; i < cu.Count; ++i) {
- if (RootContext.TokenizeOnly) {
- tokenize_file (cu [i], ctx);
- } else {
- Parse (cu [i], module);
- }
- }
- }
-
- void ProcessSourceFiles (string spec, bool recurse)
- {
- string path, pattern;
-
- SplitPathAndPattern (spec, out path, out pattern);
- if (pattern.IndexOf ('*') == -1){
- AddSourceFile (spec);
- return;
- }
-
- string [] files = null;
- try {
- files = Directory.GetFiles (path, pattern);
- } catch (System.IO.DirectoryNotFoundException) {
- Report.Error (2001, "Source file `" + spec + "' could not be found");
- return;
- } catch (System.IO.IOException){
- Report.Error (2001, "Source file `" + spec + "' could not be found");
- return;
- }
- foreach (string f in files) {
- AddSourceFile (f);
- }
-
- if (!recurse)
- return;
-
- string [] dirs = null;
-
- try {
- dirs = Directory.GetDirectories (path);
- } catch {
- }
-
- foreach (string d in dirs) {
-
- // Don't include path in this string, as each
- // directory entry already does
- ProcessSourceFiles (d + "/" + pattern, true);
- }
- }
-
- void SetWarningLevel (string s)
- {
- int level = -1;
-
- try {
- level = Int32.Parse (s);
- } catch {
- }
- if (level < 0 || level > 4){
- Report.Error (1900, "Warning level must be in the range 0-4");
- return;
- }
- Report.WarningLevel = level;
- }
-
- static void Version ()
- {
- string version = System.Reflection.Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
- Console.WriteLine ("Mono C# compiler version {0}", version);
- Environment.Exit (0);
- }
-
- //
- // Currently handles the Unix-like command line options, but will be
- // deprecated in favor of the CSCParseOption, which will also handle the
- // options that start with a dash in the future.
- //
- bool UnixParseOption (string arg, ref string [] args, ref int i)
- {
- switch (arg){
- case "-v":
- CSharpParser.yacc_verbose_flag++;
- return true;
-
- case "--version":
- Version ();
- return true;
-
- case "--parse":
- RootContext.ParseOnly = true;
- return true;
-
- case "--main": case "-m":
- Report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
- RootContext.MainClass = args [++i];
- return true;
-
- case "--unsafe":
- Report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
- RootContext.Unsafe = true;
- return true;
-
- case "/?": case "/h": case "/help":
- case "--help":
- Usage ();
- Environment.Exit (0);
- return true;
-
- case "--define":
- Report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
- RootContext.AddConditional (args [++i]);
- return true;
-
- case "--tokenize":
- RootContext.TokenizeOnly = true;
- return true;
-
- case "-o":
- case "--output":
- Report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
- RootContext.OutputFile = args [++i];
- return true;
-
- case "--checked":
- Report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
- RootContext.Checked = true;
- return true;
-
- case "--stacktrace":
- Report.Printer.Stacktrace = true;
- return true;
-
- case "--linkresource":
- case "--linkres":
- Report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
- if ((i + 1) >= args.Length){
- Usage ();
- Report.Error (5, "Missing argument to --linkres");
- Environment.Exit (1);
- }
-
- AddResource (new AssemblyResource (args[++i], args[i]));
- return true;
-
- case "--resource":
- case "--res":
- Report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
- if ((i + 1) >= args.Length){
- Usage ();
- Report.Error (5, "Missing argument to --resource");
- Environment.Exit (1);
- }
-
- AddResource (new AssemblyResource (args[++i], args[i], true));
- return true;
-
- case "--target":
- Report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
- if ((i + 1) >= args.Length){
- Environment.Exit (1);
- return true;
- }
-
- string type = args [++i];
- switch (type){
- case "library":
- RootContext.Target = Target.Library;
- RootContext.TargetExt = ".dll";
- break;
-
- case "exe":
- RootContext.Target = Target.Exe;
- break;
-
- case "winexe":
- RootContext.Target = Target.WinExe;
- break;
-
- case "module":
- RootContext.Target = Target.Module;
- RootContext.TargetExt = ".dll";
- break;
- default:
- TargetUsage ();
- break;
- }
- return true;
-
- case "-r":
- Report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
-
- string val = args [++i];
- int idx = val.IndexOf ('=');
- if (idx > -1) {
- string alias = val.Substring (0, idx);
- string assembly = val.Substring (idx + 1);
- AddAssemblyReference (alias, assembly);
- return true;
- }
-
- AddAssemblyReference (val);
- return true;
-
- case "-L":
- Report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
- RootContext.ReferencesLookupPaths.Add (args [++i]);
- return true;
-
- case "--lint":
- RootContext.EnhancedWarnings = true;
- return true;
-
- case "--nostdlib":
- Report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
- RootContext.StdLib = false;
- return true;
-
- case "--nowarn":
- Report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
- if ((i + 1) >= args.Length){
- Usage ();
- Environment.Exit (1);
- }
- int warn = 0;
-
- try {
- warn = Int32.Parse (args [++i]);
- } catch {
- Usage ();
- Environment.Exit (1);
- }
- Report.SetIgnoreWarning (warn);
- return true;
-
- case "--wlevel":
- Report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
- if ((i + 1) >= args.Length){
- Report.Error (
- 1900,
- "--wlevel requires a value from 0 to 4");
- Environment.Exit (1);
- }
-
- SetWarningLevel (args [++i]);
- return true;
-
- case "--mcs-debug":
- if ((i + 1) >= args.Length){
- Report.Error (5, "--mcs-debug requires an argument");
- Environment.Exit (1);
- }
-
- try {
- Report.DebugFlags = Int32.Parse (args [++i]);
- } catch {
- Report.Error (5, "Invalid argument to --mcs-debug");
- Environment.Exit (1);
- }
- return true;
-
- case "--about":
- About ();
- return true;
-
- case "--recurse":
- Report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
- if ((i + 1) >= args.Length){
- Report.Error (5, "--recurse requires an argument");
- Environment.Exit (1);
- }
- ProcessSourceFiles (args [++i], true);
- return true;
-
- case "--timestamp":
- RootContext.Timestamps = true;
- return true;
-
- case "--debug": case "-g":
- Report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
- RootContext.GenerateDebugInfo = true;
- return true;
-
- case "--noconfig":
- Report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
- RootContext.LoadDefaultReferences = false;
- return true;
-
- default:
- if (arg.StartsWith ("--fatal")){
- if (arg.StartsWith ("--fatal=")){
- if (!Int32.TryParse (arg.Substring (8), out fatal_errors))
- fatal_errors = 1;
- } else
- fatal_errors = 1;
- return true;
- }
- if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
- string version = arg.Substring (10);
-
- switch (version) {
- case "v1":
- case "V1":
- RootContext.StdLibRuntimeVersion = RuntimeVersion.v1;
- break;
- case "v2":
- case "V2":
- RootContext.StdLibRuntimeVersion = RuntimeVersion.v2;
- return true;
- case "v4":
- case "V4":
- RootContext.StdLibRuntimeVersion = RuntimeVersion.v4;
- return true;
- }
- return true;
- }
-
- break;
- }
-
- return false;
- }
-
public static string GetPackageFlags (string packages, bool fatal, Report report)
{
ProcessStartInfo pi = new ProcessStartInfo ();
}
//
- // This parses the -arg and /arg options to the compiler, even if the strings
- // in the following text use "/arg" on the strings.
+ // Main compilation method
//
- bool CSCParseOption (string option, ref string [] args)
- {
- int idx = option.IndexOf (':');
- string arg, value;
-
- if (idx == -1){
- arg = option;
- value = "";
- } else {
- arg = option.Substring (0, idx);
-
- value = option.Substring (idx + 1);
- }
-
- switch (arg.ToLowerInvariant ()){
- case "/nologo":
- return true;
-
- case "/t":
- case "/target":
- switch (value){
- case "exe":
- RootContext.Target = Target.Exe;
- break;
-
- case "winexe":
- RootContext.Target = Target.WinExe;
- break;
-
- case "library":
- RootContext.Target = Target.Library;
- RootContext.TargetExt = ".dll";
- break;
-
- case "module":
- RootContext.Target = Target.Module;
- RootContext.TargetExt = ".netmodule";
- break;
-
- default:
- TargetUsage ();
- break;
- }
- return true;
-
- case "/out":
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
- RootContext.OutputFile = value;
- return true;
-
- case "/o":
- case "/o+":
- case "/optimize":
- case "/optimize+":
- RootContext.Optimize = true;
- return true;
-
- case "/o-":
- case "/optimize-":
- RootContext.Optimize = false;
- return true;
-
- // TODO: Not supported by csc 3.5+
- case "/incremental":
- case "/incremental+":
- case "/incremental-":
- // nothing.
- return true;
-
- case "/d":
- case "/define": {
- if (value.Length == 0){
- Usage ();
- Environment.Exit (1);
- }
-
- foreach (string d in value.Split (argument_value_separator)) {
- string conditional = d.Trim ();
- if (!Tokenizer.IsValidIdentifier (conditional)) {
- Report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
- continue;
- }
- RootContext.AddConditional (conditional);
- }
- return true;
- }
-
- case "/bugreport":
- //
- // We should collect data, runtime, etc and store in the file specified
- //
- Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
- return true;
-
- case "/pkg": {
- string packages;
-
- if (value.Length == 0){
- Usage ();
- Environment.Exit (1);
- }
- packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
- string pkgout = GetPackageFlags (packages, true, Report);
-
- if (pkgout != null){
- string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
- Split (new Char [] { ' ', '\t'});
- args = AddArgs (args, xargs);
- }
-
- return true;
- }
-
- case "/linkres":
- case "/linkresource":
- case "/res":
- case "/resource":
- AssemblyResource res = null;
- string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
- switch (s.Length) {
- case 1:
- if (s[0].Length == 0)
- goto default;
- res = new AssemblyResource (s [0], Path.GetFileName (s[0]));
- break;
- case 2:
- res = new AssemblyResource (s [0], s [1]);
- break;
- case 3:
- if (s [2] != "public" && s [2] != "private") {
- Report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s [2]);
- return true;
- }
- res = new AssemblyResource (s[0], s[1], s[2] == "private");
- break;
- default:
- Report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
- break;
- }
-
- if (res != null) {
- res.IsEmbeded = arg [1] == 'r' || arg [1] == 'R';
- AddResource (res);
- }
-
- return true;
-
- case "/recurse":
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
- ProcessSourceFiles (value, true);
- return true;
-
- case "/r":
- case "/reference": {
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- string[] refs = value.Split (argument_value_separator);
- foreach (string r in refs){
- if (r.Length == 0)
- continue;
-
- string val = r;
- int index = val.IndexOf ('=');
- if (index > -1) {
- string alias = r.Substring (0, index);
- string assembly = r.Substring (index + 1);
- AddAssemblyReference (alias, assembly);
- if (refs.Length != 1) {
- Report.Error (2034, "Cannot specify multiple aliases using single /reference option");
- break;
- }
- } else {
- AddAssemblyReference (val);
- }
- }
- return true;
- }
- case "/addmodule": {
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- string[] refs = value.Split (argument_value_separator);
- foreach (string r in refs){
- RootContext.Modules.Add (r);
- }
- return true;
- }
- case "/win32res": {
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- if (RootContext.Win32IconFile != null)
- Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
-
- RootContext.Win32ResourceFile = value;
- return true;
- }
- case "/win32icon": {
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- if (RootContext.Win32ResourceFile != null)
- Report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
-
- RootContext.Win32IconFile = value;
- return true;
- }
- case "/doc": {
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- RootContext.Documentation = new Documentation (value);
- return true;
- }
- case "/lib": {
- string [] libdirs;
-
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- libdirs = value.Split (argument_value_separator);
- foreach (string dir in libdirs)
- RootContext.ReferencesLookupPaths.Add (dir);
- return true;
- }
-
- case "/debug-":
- RootContext.GenerateDebugInfo = false;
- return true;
-
- case "/debug":
- if (value == "full" || value == "")
- RootContext.GenerateDebugInfo = true;
-
- return true;
-
- case "/debug+":
- RootContext.GenerateDebugInfo = true;
- return true;
-
- case "/checked":
- case "/checked+":
- RootContext.Checked = true;
- return true;
-
- case "/checked-":
- RootContext.Checked = false;
- return true;
-
- case "/clscheck":
- case "/clscheck+":
- RootContext.VerifyClsCompliance = true;
- return true;
-
- case "/clscheck-":
- RootContext.VerifyClsCompliance = false;
- return true;
-
- case "/unsafe":
- case "/unsafe+":
- RootContext.Unsafe = true;
- return true;
-
- case "/unsafe-":
- RootContext.Unsafe = false;
- return true;
-
- case "/warnaserror":
- case "/warnaserror+":
- if (value.Length == 0) {
- Report.WarningsAreErrors = true;
- } else {
- foreach (string wid in value.Split (argument_value_separator))
- Report.AddWarningAsError (wid);
- }
- return true;
-
- case "/warnaserror-":
- if (value.Length == 0) {
- Report.WarningsAreErrors = false;
- } else {
- foreach (string wid in value.Split (argument_value_separator))
- Report.RemoveWarningAsError (wid);
- }
- return true;
-
- case "/warn":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- SetWarningLevel (value);
- return true;
-
- case "/nowarn": {
- if (value.Length == 0){
- Error_RequiresArgument (option);
- break;
- }
-
- var warns = value.Split (argument_value_separator);
- foreach (string wc in warns){
- try {
- if (wc.Trim ().Length == 0)
- continue;
-
- int warn = Int32.Parse (wc);
- if (warn < 1) {
- throw new ArgumentOutOfRangeException("warn");
- }
- Report.SetIgnoreWarning (warn);
- } catch {
- Report.Error (1904, "`{0}' is not a valid warning number", wc);
- }
- }
- return true;
- }
-
- case "/noconfig":
- RootContext.LoadDefaultReferences = false;
- return true;
-
- case "/platform":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- switch (value.ToLower (CultureInfo.InvariantCulture)) {
- case "anycpu":
- RootContext.Platform = Platform.AnyCPU;
- break;
- case "x86":
- RootContext.Platform = Platform.X86;
- break;
- case "x64":
- RootContext.Platform = Platform.X64;
- break;
- case "itanium":
- RootContext.Platform = Platform.IA64;
- break;
- default:
- Report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
- break;
- }
-
- return true;
-
- case "/sdk":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- RootContext.SdkVersion = value;
- return true;
-
- // We just ignore this.
- case "/errorreport":
- case "/filealign":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- return true;
-
- case "/helpinternal":
- OtherFlags ();
- Environment.Exit(0);
- return true;
-
- case "/help":
- case "/?":
- Usage ();
- Environment.Exit (0);
- return true;
-
- case "/main":
- case "/m":
- if (value.Length == 0){
- Error_RequiresArgument (option);
- break;
- }
- RootContext.MainClass = value;
- return true;
-
- case "/nostdlib":
- case "/nostdlib+":
- RootContext.StdLib = false;
- return true;
-
- case "/nostdlib-":
- RootContext.StdLib = true;
- return true;
-
- case "/fullpaths":
- RootContext.ShowFullPaths = true;
- return true;
-
- case "/keyfile":
- if (value.Length == 0) {
- Error_RequiresFileName (option);
- break;
- }
-
- RootContext.StrongNameKeyFile = value;
- return true;
-
- case "/keycontainer":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- RootContext.StrongNameKeyContainer = value;
- return true;
- case "/delaysign+":
- case "/delaysign":
- RootContext.StrongNameDelaySign = true;
- return true;
- case "/delaysign-":
- RootContext.StrongNameDelaySign = false;
- return true;
-
- case "/langversion":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- switch (value.ToLowerInvariant ()) {
- case "iso-1":
- RootContext.Version = LanguageVersion.ISO_1;
- return true;
- case "default":
- RootContext.Version = LanguageVersion.Default;
- RootContext.AddConditional ("__V2__");
- return true;
- case "iso-2":
- RootContext.Version = LanguageVersion.ISO_2;
- return true;
- case "3":
- RootContext.Version = LanguageVersion.V_3;
- return true;
- case "future":
- RootContext.Version = LanguageVersion.Future;
- return true;
- }
-
- Report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
- return true;
-
- case "/codepage":
- if (value.Length == 0) {
- Error_RequiresArgument (option);
- break;
- }
-
- switch (value) {
- case "utf8":
- RootContext.Encoding = new UTF8Encoding();
- break;
- case "reset":
- RootContext.Encoding = Encoding.Default;
- break;
- default:
- try {
- RootContext.Encoding = Encoding.GetEncoding (Int32.Parse (value));
- } catch {
- Report.Error (2016, "Code page `{0}' is invalid or not installed", value);
- }
- break;
- }
- return true;
-
- default:
- return false;
- }
-
- return true;
- }
-
- void Error_WrongOption (string option)
- {
- Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
- }
-
- void Error_RequiresFileName (string option)
- {
- Report.Error (2005, "Missing file specification for `{0}' option", option);
- }
-
- void Error_RequiresArgument (string option)
- {
- Report.Error (2006, "Missing argument for `{0}' option", option);
- }
-
- static string [] AddArgs (string [] args, string [] extra_args)
- {
- string [] new_args;
- new_args = new string [extra_args.Length + args.Length];
-
- // if args contains '--' we have to take that into account
- // split args into first half and second half based on '--'
- // and add the extra_args before --
- int split_position = Array.IndexOf (args, "--");
- if (split_position != -1)
- {
- Array.Copy (args, new_args, split_position);
- extra_args.CopyTo (new_args, split_position);
- Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
- }
- else
- {
- args.CopyTo (new_args, 0);
- extra_args.CopyTo (new_args, args.Length);
- }
-
- return new_args;
- }
-
- void AddAssemblyReference (string assembly)
- {
- RootContext.AssemblyReferences.Add (assembly);
- }
-
- void AddAssemblyReference (string alias, string assembly)
- {
- if (assembly.Length == 0) {
- Report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
- return;
- }
-
- if (!IsExternAliasValid (alias)) {
- Report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
- return;
- }
-
- RootContext.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
- }
-
- void AddResource (AssemblyResource res)
+ public bool Compile ()
{
- if (RootContext.Resources == null) {
- RootContext.Resources = new List<AssemblyResource> ();
- RootContext.Resources.Add (res);
- return;
- }
+ var settings = ctx.Settings;
- if (RootContext.Resources.Contains (res)) {
- ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
- return;
- }
-
- RootContext.Resources.Add (res);
- }
-
- static bool IsExternAliasValid (string identifier)
- {
- if (identifier.Length == 0)
- return false;
- if (identifier [0] != '_' && !Char.IsLetter (identifier [0]))
+ //
+ // If we are an exe, require a source file for the entry point or
+ // if there is nothing to put in the assembly, and we are not a library
+ //
+ if (Location.FirstFile == null &&
+ ((settings.Target == Target.Exe || settings.Target == Target.WinExe || settings.Target == Target.Module) ||
+ settings.Resources == null)) {
+ Report.Error (2008, "No files to compile were specified");
return false;
-
- for (int i = 1; i < identifier.Length; i++) {
- char c = identifier [i];
- if (Char.IsLetter (c) || Char.IsDigit (c))
- continue;
-
- UnicodeCategory category = Char.GetUnicodeCategory (c);
- if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
- category != UnicodeCategory.SpacingCombiningMark ||
- category != UnicodeCategory.ConnectorPunctuation)
- return false;
}
-
- return true;
- }
- //
- // Main compilation method
- //
- public bool Compile ()
- {
- TimeReporter tr = new TimeReporter (RootContext.Timestamps);
+ TimeReporter tr = new TimeReporter (settings.Timestamps);
ctx.TimeReporter = tr;
tr.StartTotal ();
if (Report.Errors > 0)
return false;
- if (RootContext.TokenizeOnly || RootContext.ParseOnly)
+ if (settings.TokenizeOnly || settings.ParseOnly)
return true;
if (RootContext.ToplevelTypes.NamespaceEntry != null)
throw new InternalErrorException ("who set it?");
- //
- // Quick hack
- //
- var output_file = RootContext.OutputFile;
+ var output_file = settings.OutputFile;
string output_file_name;
if (output_file == null) {
- if (first_source == null) {
+ output_file_name = Location.FirstFile;
+
+ if (output_file_name == null) {
Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
return false;
}
- int pos = first_source.LastIndexOf ('.');
+ int pos = output_file_name.LastIndexOf ('.');
if (pos > 0)
- output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
- else
- output_file = first_source + RootContext.TargetExt;
-
- output_file_name = output_file;
+ output_file_name = output_file_name.Substring (0, pos);
+
+ output_file_name += settings.TargetExt;
+ output_file = output_file_name;
} else {
output_file_name = Path.GetFileName (output_file);
}
if (Report.Errors > 0)
return false;
- if (RootContext.Documentation != null &&
- !RootContext.Documentation.OutputDocComment (
+ if (settings.Documentation != null &&
+ !settings.Documentation.OutputDocComment (
output_file, Report))
return false;
tr.StopTotal ();
tr.ShowStats ();
- return (Report.Errors == 0);
+ return Report.Errors == 0;
}
}
public static bool InvokeCompiler (string [] args, TextWriter error)
{
try {
- StreamReportPrinter srp = new StreamReportPrinter (error);
- Driver d = Driver.Create (args, true, null, srp);
- if (d == null)
+ var r = new Report (new StreamReportPrinter (error));
+ CommandLineParser cmd = new CommandLineParser (r, error);
+ var setting = cmd.ParseArguments (args);
+ if (setting == null || r.Errors > 0)
return false;
- return d.Compile () && srp.ErrorsCount == 0;
+ var d = new Driver (new CompilerContext (setting, r));
+ return d.Compile ();
} finally {
Reset ();
}
return fne;
}
- if (Arity == 0 && Name == "dynamic" && RootContext.Version > LanguageVersion.V_3) {
+ if (Arity == 0 && Name == "dynamic" && ec.Module.Compiler.Settings.Version > LanguageVersion.V_3) {
if (!ec.Module.PredefinedAttributes.Dynamic.IsDefined) {
ec.Module.Compiler.Report.Error (1980, Location,
"Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
return null;
}
- if (RootContext.EvalMode) {
+ if (rc.Module.Compiler.IsEvalutor) {
var fi = Evaluator.LookupField (Name);
if (fi != null)
return new FieldExpr (fi.Item1, loc);
//
// If argument is an anonymous function
//
- if (argument_type == InternalType.AnonymousMethod && RootContext.Version > LanguageVersion.ISO_2) {
+ if (argument_type == InternalType.AnonymousMethod && ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2) {
//
// p and q are delegate types or expression tree types
//
if (a.Expr.Type == InternalType.Dynamic)
continue;
- if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (a.Expr, pt)) {
+ if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (ec, a.Expr, pt)) {
custom_errors.NoArgumentMatch (ec, member);
return false;
}
protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
{
- if (RootContext.Version < LanguageVersion.V_3)
+ if (ec.Module.Compiler.Settings.Version < LanguageVersion.V_3)
base.Error_TypeOrNamespaceNotFound (ec);
else
ec.Module.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
return new string [0];
CompilerCallableEntryPoint.Reset ();
- var crp = new ConsoleReportPrinter ();
- driver = Driver.Create (args, false, unknownOptionParser, crp);
- if (driver == null)
+ var r = new Report (new ConsoleReportPrinter ());
+ var cmd = new CommandLineParser (r);
+ if (unknownOptionParser != null)
+ cmd.UnknownOptionHandler += unknownOptionParser;
+
+ var settings = cmd.ParseArguments (args);
+
+ // TODO: Should use ReportPrinter with throw instead of this
+ if (settings == null || r.Errors > 0)
throw new Exception ("Failed to create compiler driver with the given arguments");
- crp.Fatal = driver.fatal_errors;
- ctx = driver.ctx;
+ ctx = new CompilerContext (settings, r) {
+ IsEvalutor = true
+ };
RootContext.ToplevelTypes = new ModuleContainer (ctx);
ctx.BuildinTypes.CheckDefinitions (RootContext.ToplevelTypes);
RootContext.ToplevelTypes.InitializePredefinedTypes ();
- RootContext.EvalMode = true;
inited = true;
return startup_files.ToArray ();
return cr.Result;
}
} finally {
- parser.undo.ExecuteUndo ();
+ if (parser.undo != null)
+ parser.undo.ExecuteUndo ();
}
}
if (kind == InputKind.StatementOrExpression){
parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
- RootContext.StatementMode = true;
+ ctx.Settings.StatementMode = true;
} else {
parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
- RootContext.StatementMode = false;
+ ctx.Settings.StatementMode = false;
}
if (mode == ParseMode.GetCompletions)
if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
partial_input = true;
- parser.undo.ExecuteUndo ();
+ if (parser.undo != null)
+ parser.undo.ExecuteUndo ();
+
parser = null;
}
RootContext.ToplevelTypes.Define ();
if (Report.Errors != 0){
- undo.ExecuteUndo ();
+ if (undo != null)
+ undo.ExecuteUndo ();
+
return null;
}
RootContext.ToplevelTypes.Emit ();
if (Report.Errors != 0){
- undo.ExecuteUndo ();
+ if (undo != null)
+ undo.ExecuteUndo ();
return null;
}
return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
}
#endif
-
+
/// <summary>
/// A sentinel value used to indicate that no value was
/// was set by the compiled function. This is used to
return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
}
- if (RootContext.Version >= LanguageVersion.ISO_2 &&
+ if (ec.Module.Compiler.Settings.Version >= LanguageVersion.ISO_2 &&
((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
(TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
(TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
{
- if (RootContext.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
+ if (ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
ec.Report.SymbolRelatedToPreviousError (type);
ec.Report.Error (1061, loc,
"Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found (are you missing a using directive or an assembly reference?)",
Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
} else {
// Sets output file metadata version when there is no mscorlib
- switch (RootContext.StdLibRuntimeVersion) {
+ switch (module.Compiler.Settings.StdLibRuntimeVersion) {
case RuntimeVersion.v4:
Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
break;
string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
string sdk_path = null;
- string sdk_version = RootContext.SdkVersion ?? "4";
+ string sdk_version = compiler.Settings.SdkVersion ?? "4";
string[] sdk_sub_dirs;
if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
default_references.Add ("System.dll");
default_references.Add ("System.Xml.dll");
- if (RootContext.Version > LanguageVersion.ISO_2)
+ if (compiler.Settings.Version > LanguageVersion.ISO_2)
default_references.Add ("System.Core.dll");
- if (RootContext.Version > LanguageVersion.V_3)
+ if (compiler.Settings.Version > LanguageVersion.V_3)
default_references.Add ("Microsoft.CSharp.dll");
return default_references.ToArray ();
public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
{
- if (RootContext.Modules.Count == 0)
- return;
-
- foreach (var moduleName in RootContext.Modules) {
+ foreach (var moduleName in compiler.Settings.Modules) {
var m = LoadModuleFile (moduleName);
if (m == null)
continue;
compile_units.Add (unit);
}
+ public static string FirstFile {
+ get {
+ return compile_units.Count == 0 ? null : compile_units[0].Name;
+ }
+ }
+
public static IList<CompilationUnit> SourceFiles {
get {
return compile_units;
if (partialMethodImplementation != null && IsPartialDefinition)
MethodBuilder = partialMethodImplementation.MethodBuilder;
- if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
+ if (Compiler.Settings.StdLib && TypeManager.IsSpecialType (ReturnType)) {
Error1599 (Location, ReturnType, Report);
return false;
}
//
// This is used to track the Entry Point,
//
- if (RootContext.NeedsEntryPoint &&
- Name == "Main" &&
- (RootContext.MainClass == null ||
- RootContext.MainClass == Parent.TypeBuilder.FullName)){
+ var settings = Compiler.Settings;
+ if (settings.NeedsEntryPoint && Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
if (IsEntryPoint ()) {
-
if (Parent.DeclaringAssembly.EntryPoint == null) {
if (Parent.IsGeneric || MemberName.IsGeneric) {
Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
}
- if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
- Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
- " the global namespace will be used instead");
-
AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
}
if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
AccessorSecond != null && Get.Block == null && Set.Block == null) {
- if (RootContext.Version <= LanguageVersion.ISO_2)
- Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
+ if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
+ Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
Get.ModFlags |= Modifiers.COMPILER_GENERATED;
Set.ModFlags |= Modifiers.COMPILER_GENERATED;
ResolveAssemblySecurityAttributes ();
var an = CreateAssemblyName ();
- try {
- Builder = file_name == null ?
- domain.DefineDynamicAssembly (an, access) :
- domain.DefineDynamicAssembly (an, access, Dirname (file_name));
- } catch (ArgumentException) {
- // specified key may not be exportable outside it's container
- if (RootContext.StrongNameKeyContainer != null) {
- Report.Error (1548, "Could not access the key inside the container `" +
- RootContext.StrongNameKeyContainer + "'.");
- }
- throw;
- }
+ Builder = file_name == null ?
+ domain.DefineDynamicAssembly (an, access) :
+ domain.DefineDynamicAssembly (an, access, Dirname (file_name));
module.Create (this, CreateModuleBuilder ());
builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
default_references.Add ("System.Windows.Browser");
#endif
- if (RootContext.Version > LanguageVersion.ISO_2)
+ if (compiler.Settings.Version > LanguageVersion.ISO_2)
default_references.Add ("System.Core");
- if (RootContext.Version > LanguageVersion.V_3)
+ if (compiler.Settings.Version > LanguageVersion.V_3)
default_references.Add ("Microsoft.CSharp");
return default_references.ToArray ();
public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
{
- if (RootContext.Modules.Count == 0)
- return;
-
- foreach (var moduleName in RootContext.Modules) {
+ foreach (var moduleName in compiler.Settings.Modules) {
var m = LoadModuleFile (assembly, moduleName);
if (m == null)
continue;
--reporting_disabled;
}
- public void FeatureIsNotAvailable (Location loc, string feature)
+ public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
{
string version;
- switch (RootContext.Version) {
+ switch (compiler.Settings.Version) {
case LanguageVersion.ISO_1:
version = "1.0";
break;
version = "3.0";
break;
default:
- throw new InternalErrorException ("Invalid feature version", RootContext.Version);
+ throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
}
Error (1644, loc,
//
// Generic base for any message writer
//
- public abstract class ReportPrinter {
- /// <summary>
- /// Whether to dump a stack trace on errors.
- /// </summary>
- public bool Stacktrace;
-
- int warnings, errors;
+ public abstract class ReportPrinter
+ {
+ #region Properties
- public int WarningsCount {
- get { return warnings; }
- }
-
- public int ErrorsCount {
- get { return errors; }
- }
+ public int FatalCounter { get; set; }
- protected virtual string FormatText (string txt)
- {
- return txt;
- }
+ public int ErrorsCount { get; protected set; }
+
+ public bool ShowFullPaths { get; set; }
+ //
+ // Whether to dump a stack trace on errors.
+ //
+ public bool Stacktrace { get; set; }
+
+ public int WarningsCount { get; private set; }
+
//
// When (symbols related to previous ...) can be used
//
get { return true; }
}
+ #endregion
+
+
+ protected virtual string FormatText (string txt)
+ {
+ return txt;
+ }
+
public virtual void Print (AbstractMessage msg)
{
- if (msg.IsWarning)
- ++warnings;
- else
- ++errors;
+ if (msg.IsWarning) {
+ ++WarningsCount;
+ } else {
+ ++ErrorsCount;
+
+ if (ErrorsCount == FatalCounter)
+ throw new Exception (msg.Text);
+ }
}
protected void Print (AbstractMessage msg, TextWriter output)
{
StringBuilder txt = new StringBuilder ();
if (!msg.Location.IsNull) {
- if (RootContext.ShowFullPaths)
+ if (ShowFullPaths)
txt.Append (msg.Location.ToStringFullName ());
else
txt.Append (msg.Location.ToString ());
public void Reset ()
{
- // Temporary hack for broken repl flow
- errors = warnings = 0;
+ // HACK: Temporary hack for broken repl flow
+ ErrorsCount = WarningsCount = 0;
}
}
{
}
- public int Fatal { get; set; }
-
static int NameToCode (string s)
{
switch (s) {
return sb.ToString ();
}
- int print_count;
public override void Print (AbstractMessage msg)
{
base.Print (msg);
if (Stacktrace)
Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
-
- if (++print_count == Fatal)
- throw new Exception (msg.Text);
}
public static string FriendlyStackTrace (Exception e)
using System.Collections.Generic;
using System.IO;
using System.Text;
+using System.Globalization;
+using System;
namespace Mono.CSharp {
public enum LanguageVersion
{
- ISO_1 = 1,
- ISO_2 = 2,
- V_3 = 3,
- V_4 = 4,
- Future = 100,
+ ISO_1 = 1,
+ ISO_2 = 2,
+ V_3 = 3,
+ V_4 = 4,
+ Future = 100,
- Default = LanguageVersion.V_4,
+ Default = LanguageVersion.V_4,
}
public enum RuntimeVersion
AnyCPU, X86, X64, IA64
}
- public class RootContext {
-
- //
- // COMPILER OPTIONS CLASS
- //
- public static Target Target;
- public static Platform Platform;
- public static string TargetExt;
- public static bool VerifyClsCompliance;
- public static bool Optimize;
- public static LanguageVersion Version;
- public static bool EnhancedWarnings;
- public static bool LoadDefaultReferences;
- public static string SdkVersion;
+ public class CompilerSettings
+ {
+ public Target Target;
+ public Platform Platform;
+ public string TargetExt;
+ public bool VerifyClsCompliance;
+ public bool Optimize;
+ public LanguageVersion Version;
+ public bool EnhancedWarnings;
+ public bool LoadDefaultReferences;
+ public string SdkVersion;
- //
- // We keep strongname related info here because
- // it's also used as complier options from CSC 8.x
- //
- public static string StrongNameKeyFile;
- public static string StrongNameKeyContainer;
- public static bool StrongNameDelaySign;
+ public string StrongNameKeyFile;
+ public string StrongNameKeyContainer;
+ public bool StrongNameDelaySign;
//
// Assemblies references to be loaded
//
- public static List<string> AssemblyReferences;
+ public List<string> AssemblyReferences;
//
// External aliases for assemblies
//
- public static List<Tuple<string, string>> AssemblyReferencesAliases;
+ public List<Tuple<string, string>> AssemblyReferencesAliases;
//
// Modules to be embedded
//
- public static List<string> Modules;
+ public List<string> Modules;
//
// Lookup paths for referenced assemblies
//
- public static List<string> ReferencesLookupPaths;
+ public List<string> ReferencesLookupPaths;
//
// Encoding.
//
- public static Encoding Encoding;
+ public Encoding Encoding;
//
// If set, enable XML documentation generation
//
- public static Documentation Documentation;
+ public Documentation Documentation;
- static public string MainClass;
+ public string MainClass;
//
// Output file
//
- static string output_file;
- public static string OutputFile {
- set {
- output_file = value;
- }
- get {
- return output_file;
- }
- }
-
+ public string OutputFile;
//
// The default compiler checked state
//
- static public bool Checked;
-
- //
- // If true, it means that the compiler is executing as
- // in eval mode so unresolved variables are resolved in
- // static classes maintained by the eval engine.
- //
- static public bool EvalMode;
+ public bool Checked;
//
// If true, the compiler is operating in statement mode,
// this currently turns local variable declaration into
// static variables of a class
//
- static public bool StatementMode;
+ public bool StatementMode; // TODO: SUPER UGLY
//
// Whether to allow Unsafe code
//
- static public bool Unsafe;
+ public bool Unsafe;
- static public string Win32ResourceFile;
- static public string Win32IconFile;
+ public string Win32ResourceFile;
+ public string Win32IconFile;
//
// A list of resource files for embedding
//
- static public List<AssemblyResource> Resources;
+ public List<AssemblyResource> Resources;
- static public bool GenerateDebugInfo;
+ public bool GenerateDebugInfo;
// Compiler debug flags only
- public static bool ParseOnly, TokenizeOnly, Timestamps;
-
- public static bool ShowFullPaths;
+ public bool ParseOnly, TokenizeOnly, Timestamps;
//
// Whether we are being linked against the standard libraries.
// This is only used to tell whether `System.Object' should
// have a base class or not.
//
- public static bool StdLib;
+ public bool StdLib;
+
+ public RuntimeVersion StdLibRuntimeVersion;
+
+ public CompilerSettings ()
+ {
+ StdLib = true;
+ Target = Target.Exe;
+ TargetExt = ".exe";
+ Platform = Platform.AnyCPU;
+ Version = LanguageVersion.Default;
+ VerifyClsCompliance = true;
+ Optimize = true;
+ Encoding = Encoding.Default;
+ LoadDefaultReferences = true;
+ StdLibRuntimeVersion = RuntimeVersion.v4;
+
+ AssemblyReferences = new List<string> ();
+ AssemblyReferencesAliases = new List<Tuple<string, string>> ();
+ Modules = new List<string> ();
+ ReferencesLookupPaths = new List<string> ();
+ }
+
+ public bool HasKeyFileOrContainer {
+ get {
+ return StrongNameKeyFile != null || StrongNameKeyContainer != null;
+ }
+ }
+
+ public bool NeedsEntryPoint {
+ get {
+ return Target == Target.Exe || Target == Target.WinExe;
+ }
+ }
+ }
+
+ class CommandLineParser
+ {
+ enum ParseResult
+ {
+ Success,
+ Error,
+ Stop,
+ UnknownOption
+ }
+
+ static readonly char[] argument_value_separator = new char[] { ';', ',' };
+
+ readonly Report report;
+ readonly TextWriter output;
+
+ public event Func<string[], int, int> UnknownOptionHandler;
+
+ public CommandLineParser (Report report)
+ : this (report, Console.Out)
+ {
+ }
+
+ public CommandLineParser (Report report, TextWriter messagesOutput)
+ {
+ this.report = report;
+ this.output = messagesOutput;
+ }
+
+ void About ()
+ {
+ output.WriteLine (
+ "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
+ "The compiler source code is released under the terms of the \n" +
+ "MIT X11 or GNU GPL licenses\n\n" +
+
+ "For more information on Mono, visit the project Web site\n" +
+ " http://www.mono-project.com\n\n" +
+
+ "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
+ }
+
+ public CompilerSettings ParseArguments (string[] args)
+ {
+ CompilerSettings settings = new CompilerSettings ();
+ List<string> response_file_list = null;
+ bool parsing_options = true;
+
+ for (int i = 0; i < args.Length; i++) {
+ string arg = args[i];
+ if (arg.Length == 0)
+ continue;
+
+ if (arg[0] == '@') {
+ string[] extra_args;
+ string response_file = arg.Substring (1);
+
+ if (response_file_list == null)
+ response_file_list = new List<string> ();
+
+ if (response_file_list.Contains (response_file)) {
+ report.Error (1515, "Response file `{0}' specified multiple times", response_file);
+ return null;
+ }
+
+ response_file_list.Add (response_file);
+
+ extra_args = LoadArgs (response_file);
+ if (extra_args == null) {
+ report.Error (2011, "Unable to open response file: " + response_file);
+ return null;
+ }
+
+ args = AddArgs (args, extra_args);
+ continue;
+ }
+
+ if (parsing_options) {
+ if (arg == "--") {
+ parsing_options = false;
+ continue;
+ }
+
+ bool dash_opt = arg[0] == '-';
+ bool slash_opt = arg[0] == '/';
+ if (dash_opt) {
+ switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
+ case ParseResult.Error:
+ case ParseResult.Success:
+ continue;
+ case ParseResult.Stop:
+ return null;
+ }
+ }
+
+ if (dash_opt || slash_opt) {
+ // Try a -CSCOPTION
+ string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
+ switch (ParseOption (csc_opt, ref args, settings)) {
+ case ParseResult.Error:
+ case ParseResult.Success:
+ continue;
+ case ParseResult.UnknownOption:
+ if (UnknownOptionHandler != null) {
+ var ret = UnknownOptionHandler (args, i);
+ if (ret != -1) {
+ i = ret;
+ continue;
+ }
+ }
+
+ Error_WrongOption (arg);
+ return null;
+
+ case ParseResult.Stop:
+ return null;
+ }
+ }
+
+ if (slash_opt) {
+ // Need to skip `/home/test.cs' however /test.cs is considered as error
+ if (arg.Length < 2 || arg.IndexOf ('/', 2) == -1) {
+ Error_WrongOption (arg);
+ return null;
+ }
+ }
+ }
+
+ ProcessSourceFiles (arg, false);
+ }
+
+ return settings;
+ }
+
+ void ProcessSourceFiles (string spec, bool recurse)
+ {
+ string path, pattern;
+
+ SplitPathAndPattern (spec, out path, out pattern);
+ if (pattern.IndexOf ('*') == -1) {
+ AddSourceFile (spec);
+ return;
+ }
+
+ string[] files = null;
+ try {
+ files = Directory.GetFiles (path, pattern);
+ } catch (System.IO.DirectoryNotFoundException) {
+ report.Error (2001, "Source file `" + spec + "' could not be found");
+ return;
+ } catch (System.IO.IOException) {
+ report.Error (2001, "Source file `" + spec + "' could not be found");
+ return;
+ }
+ foreach (string f in files) {
+ AddSourceFile (f);
+ }
+
+ if (!recurse)
+ return;
+
+ string[] dirs = null;
+
+ try {
+ dirs = Directory.GetDirectories (path);
+ } catch {
+ }
+
+ foreach (string d in dirs) {
+
+ // Don't include path in this string, as each
+ // directory entry already does
+ ProcessSourceFiles (d + "/" + pattern, true);
+ }
+ }
+
+ static string[] AddArgs (string[] args, string[] extra_args)
+ {
+ string[] new_args;
+ new_args = new string[extra_args.Length + args.Length];
+
+ // if args contains '--' we have to take that into account
+ // split args into first half and second half based on '--'
+ // and add the extra_args before --
+ int split_position = Array.IndexOf (args, "--");
+ if (split_position != -1) {
+ Array.Copy (args, new_args, split_position);
+ extra_args.CopyTo (new_args, split_position);
+ Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
+ } else {
+ args.CopyTo (new_args, 0);
+ extra_args.CopyTo (new_args, args.Length);
+ }
+
+ return new_args;
+ }
+
+ void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
+ {
+ if (assembly.Length == 0) {
+ report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
+ return;
+ }
+
+ if (!IsExternAliasValid (alias)) {
+ report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
+ return;
+ }
+
+ settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
+ }
+
+ void AddResource (AssemblyResource res, CompilerSettings settings)
+ {
+ if (settings.Resources == null) {
+ settings.Resources = new List<AssemblyResource> ();
+ settings.Resources.Add (res);
+ return;
+ }
+
+ if (settings.Resources.Contains (res)) {
+ report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
+ return;
+ }
+
+ settings.Resources.Add (res);
+ }
+
+ void AddSourceFile (string f)
+ {
+ Location.AddFile (report, f);
+ }
+
+
+ void Error_RequiresArgument (string option)
+ {
+ report.Error (2006, "Missing argument for `{0}' option", option);
+ }
+
+ void Error_RequiresFileName (string option)
+ {
+ report.Error (2005, "Missing file specification for `{0}' option", option);
+ }
+
+ void Error_WrongOption (string option)
+ {
+ report.Error (2007, "Unrecognized command-line option: `{0}'", option);
+ }
+
+ static bool IsExternAliasValid (string identifier)
+ {
+ if (identifier.Length == 0)
+ return false;
+ if (identifier[0] != '_' && !char.IsLetter (identifier[0]))
+ return false;
+
+ for (int i = 1; i < identifier.Length; i++) {
+ char c = identifier[i];
+ if (char.IsLetter (c) || char.IsDigit (c))
+ continue;
+
+ UnicodeCategory category = char.GetUnicodeCategory (c);
+ if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark ||
+ category != UnicodeCategory.SpacingCombiningMark ||
+ category != UnicodeCategory.ConnectorPunctuation)
+ return false;
+ }
+
+ return true;
+ }
+
+ static string[] LoadArgs (string file)
+ {
+ StreamReader f;
+ var args = new List<string> ();
+ string line;
+ try {
+ f = new StreamReader (file);
+ } catch {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder ();
+
+ while ((line = f.ReadLine ()) != null) {
+ int t = line.Length;
+
+ for (int i = 0; i < t; i++) {
+ char c = line[i];
+
+ if (c == '"' || c == '\'') {
+ char end = c;
+
+ for (i++; i < t; i++) {
+ c = line[i];
+
+ if (c == end)
+ break;
+ sb.Append (c);
+ }
+ } else if (c == ' ') {
+ if (sb.Length > 0) {
+ args.Add (sb.ToString ());
+ sb.Length = 0;
+ }
+ } else
+ sb.Append (c);
+ }
+ if (sb.Length > 0) {
+ args.Add (sb.ToString ());
+ sb.Length = 0;
+ }
+ }
+
+ return args.ToArray ();
+ }
+
+ void OtherFlags ()
+ {
+ output.WriteLine (
+ "Other flags in the compiler\n" +
+ " --fatal[=COUNT] Makes errors after COUNT fatal\n" +
+ " --lint Enhanced warnings\n" +
+ " --parse Only parses the source file\n" +
+ " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
+ " --stacktrace Shows stack trace at error location\n" +
+ " --timestamp Displays time stamps of various compiler events\n" +
+ " -v Verbose parsing (for debugging the parser)\n" +
+ " --mcs-debug X Sets MCS debugging level to X\n");
+ }
+
+ //
+ // This parses the -arg and /arg options to the compiler, even if the strings
+ // in the following text use "/arg" on the strings.
+ //
+ ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
+ {
+ int idx = option.IndexOf (':');
+ string arg, value;
+
+ if (idx == -1) {
+ arg = option;
+ value = "";
+ } else {
+ arg = option.Substring (0, idx);
+
+ value = option.Substring (idx + 1);
+ }
+
+ switch (arg.ToLowerInvariant ()) {
+ case "/nologo":
+ return ParseResult.Success;
+
+ case "/t":
+ case "/target":
+ switch (value) {
+ case "exe":
+ settings.Target = Target.Exe;
+ break;
+
+ case "winexe":
+ settings.Target = Target.WinExe;
+ break;
+
+ case "library":
+ settings.Target = Target.Library;
+ settings.TargetExt = ".dll";
+ break;
+
+ case "module":
+ settings.Target = Target.Module;
+ settings.TargetExt = ".netmodule";
+ break;
+
+ default:
+ report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
+ return ParseResult.Error;
+ }
+ return ParseResult.Success;
+
+ case "/out":
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+ settings.OutputFile = value;
+ return ParseResult.Success;
+
+ case "/o":
+ case "/o+":
+ case "/optimize":
+ case "/optimize+":
+ settings.Optimize = true;
+ return ParseResult.Success;
+
+ case "/o-":
+ case "/optimize-":
+ settings.Optimize = false;
+ return ParseResult.Success;
+
+ // TODO: Not supported by csc 3.5+
+ case "/incremental":
+ case "/incremental+":
+ case "/incremental-":
+ // nothing.
+ return ParseResult.Success;
+
+ case "/d":
+ case "/define": {
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ foreach (string d in value.Split (argument_value_separator)) {
+ string conditional = d.Trim ();
+ if (!Tokenizer.IsValidIdentifier (conditional)) {
+ report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
+ continue;
+ }
+ RootContext.AddConditional (conditional);
+ }
+ return ParseResult.Success;
+ }
+
+ case "/bugreport":
+ //
+ // We should collect data, runtime, etc and store in the file specified
+ //
+ output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
+ return ParseResult.Success;
+
+ case "/pkg": {
+ string packages;
+
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+ packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
+ string pkgout = Driver.GetPackageFlags (packages, true, report);
+
+ if (pkgout != null) {
+ string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).
+ Split (new Char[] { ' ', '\t' });
+ args = AddArgs (args, xargs);
+ }
+
+ return ParseResult.Success;
+ }
+
+ case "/linkres":
+ case "/linkresource":
+ case "/res":
+ case "/resource":
+ AssemblyResource res = null;
+ string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
+ switch (s.Length) {
+ case 1:
+ if (s[0].Length == 0)
+ goto default;
+ res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
+ break;
+ case 2:
+ res = new AssemblyResource (s[0], s[1]);
+ break;
+ case 3:
+ if (s[2] != "public" && s[2] != "private") {
+ report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
+ return ParseResult.Error;
+ }
+ res = new AssemblyResource (s[0], s[1], s[2] == "private");
+ break;
+ default:
+ report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
+ return ParseResult.Error;
+ }
+
+ if (res != null) {
+ res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
+ AddResource (res, settings);
+ }
+
+ return ParseResult.Success;
+
+ case "/recurse":
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+ ProcessSourceFiles (value, true);
+ return ParseResult.Success;
+
+ case "/r":
+ case "/reference": {
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ string[] refs = value.Split (argument_value_separator);
+ foreach (string r in refs) {
+ if (r.Length == 0)
+ continue;
+
+ string val = r;
+ int index = val.IndexOf ('=');
+ if (index > -1) {
+ string alias = r.Substring (0, index);
+ string assembly = r.Substring (index + 1);
+ AddAssemblyReference (alias, assembly, settings);
+ if (refs.Length != 1) {
+ report.Error (2034, "Cannot specify multiple aliases using single /reference option");
+ return ParseResult.Error;
+ }
+ } else {
+ settings.AssemblyReferences.Add (val);
+ }
+ }
+ return ParseResult.Success;
+ }
+ case "/addmodule": {
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ string[] refs = value.Split (argument_value_separator);
+ foreach (string r in refs) {
+ settings.Modules.Add (r);
+ }
+ return ParseResult.Success;
+ }
+ case "/win32res": {
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ if (settings.Win32IconFile != null)
+ report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
+
+ settings.Win32ResourceFile = value;
+ return ParseResult.Success;
+ }
+ case "/win32icon": {
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ if (settings.Win32ResourceFile != null)
+ report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
+
+ settings.Win32IconFile = value;
+ return ParseResult.Success;
+ }
+ case "/doc": {
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ settings.Documentation = new Documentation (value);
+ return ParseResult.Success;
+ }
+ case "/lib": {
+ string[] libdirs;
+
+ if (value.Length == 0) {
+ return ParseResult.Error;
+ }
+
+ libdirs = value.Split (argument_value_separator);
+ foreach (string dir in libdirs)
+ settings.ReferencesLookupPaths.Add (dir);
+ return ParseResult.Success;
+ }
+
+ case "/debug-":
+ settings.GenerateDebugInfo = false;
+ return ParseResult.Success;
+
+ case "/debug":
+ if (value == "full" || value == "")
+ settings.GenerateDebugInfo = true;
+
+ return ParseResult.Success;
+
+ case "/debug+":
+ settings.GenerateDebugInfo = true;
+ return ParseResult.Success;
+
+ case "/checked":
+ case "/checked+":
+ settings.Checked = true;
+ return ParseResult.Success;
+
+ case "/checked-":
+ settings.Checked = false;
+ return ParseResult.Success;
+
+ case "/clscheck":
+ case "/clscheck+":
+ settings.VerifyClsCompliance = true;
+ return ParseResult.Success;
+
+ case "/clscheck-":
+ settings.VerifyClsCompliance = false;
+ return ParseResult.Success;
+
+ case "/unsafe":
+ case "/unsafe+":
+ settings.Unsafe = true;
+ return ParseResult.Success;
+
+ case "/unsafe-":
+ settings.Unsafe = false;
+ return ParseResult.Success;
+
+ case "/warnaserror":
+ case "/warnaserror+":
+ if (value.Length == 0) {
+ report.WarningsAreErrors = true;
+ } else {
+ foreach (string wid in value.Split (argument_value_separator))
+ report.AddWarningAsError (wid);
+ }
+ return ParseResult.Success;
+
+ case "/warnaserror-":
+ if (value.Length == 0) {
+ report.WarningsAreErrors = false;
+ } else {
+ foreach (string wid in value.Split (argument_value_separator))
+ report.RemoveWarningAsError (wid);
+ }
+ return ParseResult.Success;
+
+ case "/warn":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ SetWarningLevel (value);
+ return ParseResult.Success;
+
+ case "/nowarn":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ var warns = value.Split (argument_value_separator);
+ foreach (string wc in warns) {
+ try {
+ if (wc.Trim ().Length == 0)
+ continue;
+
+ int warn = Int32.Parse (wc);
+ if (warn < 1) {
+ throw new ArgumentOutOfRangeException ("warn");
+ }
+ report.SetIgnoreWarning (warn);
+ } catch {
+ report.Error (1904, "`{0}' is not a valid warning number", wc);
+ return ParseResult.Error;
+ }
+ }
+ return ParseResult.Success;
+
+ case "/noconfig":
+ settings.LoadDefaultReferences = false;
+ return ParseResult.Success;
+
+ case "/platform":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ switch (value.ToLower (CultureInfo.InvariantCulture)) {
+ case "anycpu":
+ settings.Platform = Platform.AnyCPU;
+ break;
+ case "x86":
+ settings.Platform = Platform.X86;
+ break;
+ case "x64":
+ settings.Platform = Platform.X64;
+ break;
+ case "itanium":
+ settings.Platform = Platform.IA64;
+ break;
+ default:
+ report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
+ return ParseResult.Error;
+ }
+
+ return ParseResult.Success;
+
+ case "/sdk":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ settings.SdkVersion = value;
+ return ParseResult.Success;
+
+ // We just ignore this.
+ case "/errorreport":
+ case "/filealign":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ return ParseResult.Success;
+
+ case "/helpinternal":
+ OtherFlags ();
+ return ParseResult.Stop;
+
+ case "/help":
+ case "/?":
+ Usage ();
+ return ParseResult.Stop;
+
+ case "/main":
+ case "/m":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+ settings.MainClass = value;
+ return ParseResult.Success;
+
+ case "/nostdlib":
+ case "/nostdlib+":
+ settings.StdLib = false;
+ return ParseResult.Success;
- public static RuntimeVersion StdLibRuntimeVersion;
+ case "/nostdlib-":
+ settings.StdLib = true;
+ return ParseResult.Success;
- public static bool NeedsEntryPoint {
- get { return Target == Target.Exe || Target == Target.WinExe; }
+ case "/fullpaths":
+ report.Printer.ShowFullPaths = true;
+ return ParseResult.Success;
+
+ case "/keyfile":
+ if (value.Length == 0) {
+ Error_RequiresFileName (option);
+ return ParseResult.Error;
+ }
+
+ settings.StrongNameKeyFile = value;
+ return ParseResult.Success;
+
+ case "/keycontainer":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ settings.StrongNameKeyContainer = value;
+ return ParseResult.Success;
+
+ case "/delaysign+":
+ case "/delaysign":
+ settings.StrongNameDelaySign = true;
+ return ParseResult.Success;
+
+ case "/delaysign-":
+ settings.StrongNameDelaySign = false;
+ return ParseResult.Success;
+
+ case "/langversion":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ switch (value.ToLowerInvariant ()) {
+ case "iso-1":
+ settings.Version = LanguageVersion.ISO_1;
+ return ParseResult.Success;
+ case "default":
+ settings.Version = LanguageVersion.Default;
+ RootContext.AddConditional ("__V2__");
+ return ParseResult.Success;
+ case "iso-2":
+ settings.Version = LanguageVersion.ISO_2;
+ return ParseResult.Success;
+ case "3":
+ settings.Version = LanguageVersion.V_3;
+ return ParseResult.Success;
+ case "future":
+ settings.Version = LanguageVersion.Future;
+ return ParseResult.Success;
+ }
+
+ report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
+ return ParseResult.Error;
+
+ case "/codepage":
+ if (value.Length == 0) {
+ Error_RequiresArgument (option);
+ return ParseResult.Error;
+ }
+
+ switch (value) {
+ case "utf8":
+ settings.Encoding = new UTF8Encoding ();
+ break;
+ case "reset":
+ settings.Encoding = Encoding.Default;
+ break;
+ default:
+ try {
+ settings.Encoding = Encoding.GetEncoding (int.Parse (value));
+ } catch {
+ report.Error (2016, "Code page `{0}' is invalid or not installed", value);
+ }
+ return ParseResult.Error;
+ }
+ return ParseResult.Success;
+
+ default:
+ return ParseResult.UnknownOption;
+ }
+ }
+
+ //
+ // Currently handles the Unix-like command line options, but will be
+ // deprecated in favor of the CSCParseOption, which will also handle the
+ // options that start with a dash in the future.
+ //
+ ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
+ {
+ switch (arg){
+ case "-v":
+ CSharpParser.yacc_verbose_flag++;
+ return ParseResult.Success;
+
+ case "--version":
+ Version ();
+ return ParseResult.Stop;
+
+ case "--parse":
+ settings.ParseOnly = true;
+ return ParseResult.Success;
+
+ case "--main": case "-m":
+ report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ settings.MainClass = args[++i];
+ return ParseResult.Success;
+
+ case "--unsafe":
+ report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
+ settings.Unsafe = true;
+ return ParseResult.Success;
+
+ case "/?": case "/h": case "/help":
+ case "--help":
+ Usage ();
+ return ParseResult.Stop;
+
+ case "--define":
+ report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ RootContext.AddConditional (args [++i]);
+ return ParseResult.Success;
+
+ case "--tokenize":
+ settings.TokenizeOnly = true;
+ return ParseResult.Success;
+
+ case "-o":
+ case "--output":
+ report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ settings.OutputFile = args[++i];
+ return ParseResult.Success;
+
+ case "--checked":
+ report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
+ settings.Checked = true;
+ return ParseResult.Success;
+
+ case "--stacktrace":
+ report.Printer.Stacktrace = true;
+ return ParseResult.Success;
+
+ case "--linkresource":
+ case "--linkres":
+ report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ AddResource (new AssemblyResource (args[++i], args[i]), settings);
+ return ParseResult.Success;
+
+ case "--resource":
+ case "--res":
+ report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ AddResource (new AssemblyResource (args[++i], args[i], true), settings);
+ return ParseResult.Success;
+
+ case "--target":
+ report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ string type = args [++i];
+ switch (type){
+ case "library":
+ settings.Target = Target.Library;
+ settings.TargetExt = ".dll";
+ break;
+
+ case "exe":
+ settings.Target = Target.Exe;
+ break;
+
+ case "winexe":
+ settings.Target = Target.WinExe;
+ break;
+
+ case "module":
+ settings.Target = Target.Module;
+ settings.TargetExt = ".dll";
+ break;
+ default:
+ report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
+ break;
+ }
+ return ParseResult.Success;
+
+ case "-r":
+ report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ string val = args [++i];
+ int idx = val.IndexOf ('=');
+ if (idx > -1) {
+ string alias = val.Substring (0, idx);
+ string assembly = val.Substring (idx + 1);
+ AddAssemblyReference (alias, assembly, settings);
+ return ParseResult.Success;
+ }
+
+ settings.AssemblyReferences.Add (val);
+ return ParseResult.Success;
+
+ case "-L":
+ report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ settings.ReferencesLookupPaths.Add (args [++i]);
+ return ParseResult.Success;
+
+ case "--lint":
+ settings.EnhancedWarnings = true;
+ return ParseResult.Success;
+
+ case "--nostdlib":
+ report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
+ settings.StdLib = false;
+ return ParseResult.Success;
+
+ case "--nowarn":
+ report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ int warn = 0;
+
+ try {
+ warn = int.Parse (args [++i]);
+ } catch {
+ Usage ();
+ Environment.Exit (1);
+ }
+ report.SetIgnoreWarning (warn);
+ return ParseResult.Success;
+
+ case "--wlevel":
+ report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ SetWarningLevel (args [++i]);
+ return ParseResult.Success;
+
+ case "--mcs-debug":
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ try {
+ Report.DebugFlags = int.Parse (args [++i]);
+ } catch {
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+
+ return ParseResult.Success;
+
+ case "--about":
+ About ();
+ return ParseResult.Stop;
+
+ case "--recurse":
+ report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
+ if ((i + 1) >= args.Length){
+ Error_RequiresArgument (arg);
+ return ParseResult.Error;
+ }
+ ProcessSourceFiles (args [++i], true);
+ return ParseResult.Success;
+
+ case "--timestamp":
+ settings.Timestamps = true;
+ return ParseResult.Success;
+
+ case "--debug": case "-g":
+ report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
+ settings.GenerateDebugInfo = true;
+ return ParseResult.Success;
+
+ case "--noconfig":
+ report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
+ settings.LoadDefaultReferences = false;
+ return ParseResult.Success;
+
+ default:
+ if (arg.StartsWith ("--fatal")){
+ int fatal = 1;
+ if (arg.StartsWith ("--fatal="))
+ int.TryParse (arg.Substring (8), out fatal);
+
+ report.Printer.FatalCounter = fatal;
+ return ParseResult.Success;
+ }
+ if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
+ string version = arg.Substring (10);
+
+ switch (version) {
+ case "v1":
+ case "V1":
+ settings.StdLibRuntimeVersion = RuntimeVersion.v1;
+ break;
+ case "v2":
+ case "V2":
+ settings.StdLibRuntimeVersion = RuntimeVersion.v2;
+ break;
+ case "v4":
+ case "V4":
+ settings.StdLibRuntimeVersion = RuntimeVersion.v4;
+ break;
+ }
+ return ParseResult.Success;
+ }
+
+ return ParseResult.UnknownOption;
+ }
+ }
+
+ void SetWarningLevel (string s)
+ {
+ int level = -1;
+
+ try {
+ level = int.Parse (s);
+ } catch {
+ }
+ if (level < 0 || level > 4) {
+ report.Error (1900, "Warning level must be in the range 0-4");
+ return;
+ }
+ report.WarningLevel = level;
}
//
- // COMPILER OPTIONS CLASS END
+ // Given a path specification, splits the path from the file/pattern
//
+ static void SplitPathAndPattern (string spec, out string path, out string pattern)
+ {
+ int p = spec.LastIndexOf ('/');
+ if (p != -1) {
+ //
+ // Windows does not like /file.cs, switch that to:
+ // "\", "file.cs"
+ //
+ if (p == 0) {
+ path = "\\";
+ pattern = spec.Substring (1);
+ } else {
+ path = spec.Substring (0, p);
+ pattern = spec.Substring (p + 1);
+ }
+ return;
+ }
+ p = spec.LastIndexOf ('\\');
+ if (p != -1) {
+ path = spec.Substring (0, p);
+ pattern = spec.Substring (p + 1);
+ return;
+ }
+
+ path = ".";
+ pattern = spec;
+ }
+
+ void Usage ()
+ {
+ output.WriteLine (
+ "Mono C# compiler, Copyright 2001 - 2011 Novell, Inc.\n" +
+ "mcs [options] source-files\n" +
+ " --about About the Mono C# compiler\n" +
+ " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
+ " -checked[+|-] Sets default aritmetic overflow context\n" +
+ " -clscheck[+|-] Disables CLS Compliance verifications\n" +
+ " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
+ " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
+ " -debug[+|-], -g Generate debugging information\n" +
+ " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
+ " -doc:FILE Process documentation comments to XML file\n" +
+ " -fullpaths Any issued error or warning uses absolute file path\n" +
+ " -help Lists all compiler options (short: -?)\n" +
+ " -keycontainer:NAME The key pair container used to sign the output assembly\n" +
+ " -keyfile:FILE The key file used to strongname the ouput assembly\n" +
+ " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default or Future\n" +
+ " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
+ " -main:CLASS Specifies the class with the Main method (short: -m)\n" +
+ " -noconfig Disables implicitly referenced assemblies\n" +
+ " -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
+ " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
+ " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
+ " -out:FILE Specifies output assembly name\n" +
+ " -pkg:P1[,Pn] References packages P1..Pn\n" +
+ " -platform:ARCH Specifies the target platform of the output assembly\n" +
+ " ARCH can be one of: anycpu, x86, x64 or itanium\n" +
+ " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
+ " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
+ " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
+ " -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
+ " VERSION can be one of: 2, 4 (default) or custom value\n" +
+ " -target:KIND Specifies the format of the output assembly (short: -t)\n" +
+ " KIND can be one of: exe, winexe, library, module\n" +
+ " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
+ " -warnaserror[+|-] Treats all warnings as errors\n" +
+ " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
+ " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
+ " -helpinternal Shows internal and advanced compiler options\n" +
+ "\n" +
+ "Resources:\n" +
+ " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
+ " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
+ " -win32res:FILE Specifies Win32 resource file (.res)\n" +
+ " -win32icon:FILE Use this icon for the output\n" +
+ " @file Read response file for more options\n\n" +
+ "Options can be of the form -option or /option");
+ }
+
+ void Version ()
+ {
+ string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
+ output.WriteLine ("Mono C# compiler version {0}", version);
+ }
+ }
+
+ public class RootContext
+ {
//
// Contains the parsed tree
//
if (!full)
return;
- Checked = false;
- Unsafe = false;
- StdLib = true;
- StrongNameKeyFile = null;
- StrongNameKeyContainer = null;
- StrongNameDelaySign = false;
- MainClass = null;
- OutputFile = null;
- Target = Target.Exe;
- SdkVersion = null;
- TargetExt = ".exe";
- Platform = Platform.AnyCPU;
- Version = LanguageVersion.Default;
- VerifyClsCompliance = true;
- Optimize = true;
- Encoding = Encoding.Default;
- Documentation = null;
- GenerateDebugInfo = false;
- ParseOnly = false;
- TokenizeOnly = false;
- Timestamps = false;
- Win32IconFile = null;
- Win32ResourceFile = null;
- Resources = null;
- LoadDefaultReferences = true;
- AssemblyReferences = new List<string> ();
- AssemblyReferencesAliases = new List<Tuple<string, string>> ();
- Modules = new List<string> ();
- ReferencesLookupPaths = new List<string> ();
- StdLibRuntimeVersion = RuntimeVersion.v2;
- ShowFullPaths = false;
-
//
// Setup default defines
//
if (OptAttributes != null)
OptAttributes.Emit ();
- if (RootContext.Unsafe) {
+ if (Compiler.Settings.Unsafe) {
var pa = PredefinedAttributes.UnverifiableCode;
if (pa.IsDefined)
pa.EmitAttribute (builder);
//
var texpr = type_expr.ResolveAsTypeTerminal (bc, true);
if (texpr == null) {
- if (RootContext.Version < LanguageVersion.V_3)
- bc.Report.FeatureIsNotAvailable (loc, "implicitly typed local variable");
+ if (bc.Module.Compiler.Settings.Version < LanguageVersion.V_3)
+ bc.Report.FeatureIsNotAvailable (bc.Module.Compiler, loc, "implicitly typed local variable");
if (li.IsFixed) {
bc.Report.Error (821, loc, "A fixed statement cannot use an implicitly typed local variable");
if (type.IsStatic)
FieldBase.Error_VariableOfStaticClass (loc, li.Name, type, bc.Report);
- if (type.IsPointer && !bc.IsUnsafe)
- Expression.UnsafeError (bc, loc);
-
li.Type = type;
}
- bool eval_global = RootContext.StatementMode && bc.CurrentBlock is ToplevelBlock;
+ bool eval_global = bc.Module.Compiler.Settings.StatementMode && bc.CurrentBlock is ToplevelBlock;
if (eval_global) {
CreateEvaluatorVariable (bc, li);
} else {
// Validate switch.
SwitchType = new_expr.Type;
- if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
- ec.Report.FeatureIsNotAvailable (loc, "switch expression of boolean type");
+ if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
+ ec.Report.FeatureIsNotAvailable (ec.Module.Compiler, loc, "switch expression of boolean type");
return false;
}