2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
26 using XmlElement = System.Object;
31 using Mono.CompilerServices.SymbolWriter;
33 namespace Mono.CSharp {
36 /// This is the base class for structs and classes.
38 public abstract class TypeContainer : DeclSpace, ITypeDefinition
41 // Different context is needed when resolving type container base
42 // types. Type names come from the parent scope but type parameter
43 // names from the container scope.
45 public struct BaseContext : IMemberContext
49 public BaseContext (TypeContainer tc)
54 #region IMemberContext Members
56 public CompilerContext Compiler {
57 get { return tc.Compiler; }
60 public TypeSpec CurrentType {
61 get { return tc.Parent.CurrentType; }
64 public TypeParameter[] CurrentTypeParameters {
65 get { return tc.PartialContainer.CurrentTypeParameters; }
68 public MemberCore CurrentMemberDefinition {
72 public bool HasUnresolvedConstraints {
76 public bool IsObsolete {
77 get { return tc.IsObsolete; }
80 public bool IsUnsafe {
81 get { return tc.IsUnsafe; }
84 public bool IsStatic {
85 get { return tc.IsStatic; }
88 public string GetSignatureForError ()
90 return tc.GetSignatureForError ();
93 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
98 public FullNamedExpression LookupNamespaceAlias (string name)
100 return tc.Parent.LookupNamespaceAlias (name);
103 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
106 TypeParameter[] tp = CurrentTypeParameters;
108 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
110 return new TypeParameterExpr (t, loc);
114 return tc.Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
124 GetHashCode = 1 << 1,
125 HasStaticFieldInitializer = 1 << 2
129 // Whether this is a struct, class or interface
130 public readonly MemberKind Kind;
132 // Holds a list of classes and structures
133 protected List<TypeContainer> types;
135 List<MemberCore> ordered_explicit_member_list;
136 List<MemberCore> ordered_member_list;
138 // Holds the list of properties
139 List<MemberCore> properties;
141 // Holds the list of constructors
142 protected List<Constructor> instance_constructors;
144 // Holds the list of fields
145 protected List<FieldBase> fields;
147 // Holds a list of fields that have initializers
148 protected List<FieldInitializer> initialized_fields;
150 // Holds a list of static fields that have initializers
151 protected List<FieldInitializer> initialized_static_fields;
153 // Holds the list of constants
154 protected List<MemberCore> constants;
156 // Holds the methods.
157 List<MemberCore> methods;
160 protected List<MemberCore> events;
162 // Holds the indexers
163 List<MemberCore> indexers;
165 // Holds the operators
166 List<MemberCore> operators;
168 // Holds the compiler generated classes
169 protected List<CompilerGeneratedClass> compiler_generated;
171 Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
173 Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
176 // Pointers to the default constructor and the default static constructor
178 protected Constructor default_constructor;
179 protected Constructor default_static_constructor;
182 // Points to the first non-static field added to the container.
184 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
185 // and the first one's as good as any.
187 FieldBase first_nonstatic_field;
190 // This one is computed after we can distinguish interfaces
191 // from classes from the arraylist `type_bases'
193 protected TypeSpec base_type;
194 protected TypeExpr base_type_expr;
195 protected TypeExpr[] iface_exprs;
197 protected List<FullNamedExpression> type_bases;
199 bool members_defined;
200 bool members_defined_ok;
203 TypeContainer InTransit;
205 GenericTypeParameterBuilder[] all_tp_builders;
207 public const string DefaultIndexerName = "Item";
209 private bool seen_normal_indexers = false;
210 private string indexer_name = DefaultIndexerName;
211 protected bool requires_delayed_unmanagedtype_check;
214 private CachedMethods cached_method;
216 protected TypeSpec spec;
217 TypeSpec current_type;
219 List<TypeContainer> partial_parts;
221 public int DynamicSitesCounter;
224 /// The pending methods that need to be implemented
225 // (interfaces or abstract methods)
227 PendingImplementation pending;
229 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
230 Attributes attrs, MemberKind kind)
231 : base (ns, parent, name, attrs)
233 if (parent != null && parent.NamespaceEntry != ns)
234 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
237 this.PartialContainer = this;
242 public override TypeSpec CurrentType {
244 if (current_type == null) {
247 // Switch to inflated version as it's used by all expressions
249 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
250 current_type = spec.MakeGenericType (targs);
260 public override TypeParameter[] CurrentTypeParameters {
262 return PartialContainer.type_params;
266 int CurrentTypeParametersStartIndex {
268 int total = all_tp_builders.Length;
269 if (CurrentTypeParameters != null) {
270 return total - CurrentTypeParameters.Length;
276 public virtual AssemblyDefinition DeclaringAssembly {
278 return Module.DeclaringAssembly;
282 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
284 return Module.DeclaringAssembly;
288 public TypeSpec Definition {
294 public bool HasMembersDefined {
296 return members_defined;
302 public bool AddMember (MemberCore symbol)
304 return AddToContainer (symbol, symbol.MemberName.Basename);
307 public bool AddMember (MemberCore symbol, string name)
309 return AddToContainer (symbol, name);
312 protected virtual bool AddMemberType (TypeContainer ds)
314 return AddToContainer (ds, ds.Basename);
317 protected virtual void RemoveMemberType (DeclSpace ds)
319 RemoveFromContainer (ds.Basename);
322 public void AddConstant (Const constant)
324 if (!AddMember (constant))
327 if (constants == null)
328 constants = new List<MemberCore> ();
330 constants.Add (constant);
333 public TypeContainer AddTypeContainer (TypeContainer tc)
335 if (!AddMemberType (tc))
339 types = new List<TypeContainer> ();
345 public virtual TypeContainer AddPartial (TypeContainer next_part)
347 return AddPartial (next_part, next_part.Basename);
350 protected TypeContainer AddPartial (TypeContainer next_part, string name)
352 next_part.ModFlags |= Modifiers.PARTIAL;
353 TypeContainer tc = GetDefinition (name) as TypeContainer;
355 return AddTypeContainer (next_part);
357 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
358 Report.SymbolRelatedToPreviousError (next_part);
359 Error_MissingPartialModifier (tc);
362 if (tc.Kind != next_part.Kind) {
363 Report.SymbolRelatedToPreviousError (tc);
364 Report.Error (261, next_part.Location,
365 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
366 next_part.GetSignatureForError ());
369 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
370 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
371 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
372 Report.SymbolRelatedToPreviousError (tc);
373 Report.Error (262, next_part.Location,
374 "Partial declarations of `{0}' have conflicting accessibility modifiers",
375 next_part.GetSignatureForError ());
378 if (tc.partial_parts == null)
379 tc.partial_parts = new List<TypeContainer> (1);
381 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
382 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
383 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
384 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
385 tc.ModFlags |= next_part.ModFlags;
387 tc.ModFlags |= next_part.ModFlags;
390 tc.spec.Modifiers = tc.ModFlags;
392 if (next_part.attributes != null) {
393 if (tc.attributes == null)
394 tc.attributes = next_part.attributes;
396 tc.attributes.AddAttributes (next_part.attributes.Attrs);
399 next_part.PartialContainer = tc;
400 tc.partial_parts.Add (next_part);
404 public virtual void RemoveTypeContainer (TypeContainer next_part)
407 types.Remove (next_part);
408 RemoveMemberType (next_part);
411 public virtual TypeSpec AddDelegate (Delegate d)
413 AddTypeContainer (d);
417 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
419 if (ordered_explicit_member_list == null) {
420 ordered_explicit_member_list = new List<MemberCore> ();
421 ordered_member_list = new List<MemberCore> ();
425 if (Kind == MemberKind.Interface) {
426 Report.Error (541, mc.Location,
427 "`{0}': explicit interface declaration can only be declared in a class or struct",
428 mc.GetSignatureForError ());
431 ordered_explicit_member_list.Add (mc);
432 alist.Insert (0, mc);
434 ordered_member_list.Add (mc);
440 public void AddMethod (MethodOrOperator method)
442 if (!AddToContainer (method, method.MemberName.Basename))
446 methods = new List<MemberCore> ();
448 if (method.MemberName.Left != null)
449 AddMemberToList (method, methods, true);
451 AddMemberToList (method, methods, false);
454 public void AddConstructor (Constructor c)
456 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
457 if (!AddToContainer (c, is_static ?
458 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
461 if (is_static && c.ParameterInfo.IsEmpty){
462 if (default_static_constructor != null) {
463 Report.SymbolRelatedToPreviousError (default_static_constructor);
464 Report.Error (111, c.Location,
465 "A member `{0}' is already defined. Rename this member or use different parameter types",
466 c.GetSignatureForError ());
470 default_static_constructor = c;
472 if (c.ParameterInfo.IsEmpty)
473 default_constructor = c;
475 if (instance_constructors == null)
476 instance_constructors = new List<Constructor> ();
478 instance_constructors.Add (c);
482 public bool AddField (FieldBase field)
484 if (!AddMember (field))
488 fields = new List<FieldBase> ();
492 if ((field.ModFlags & Modifiers.STATIC) != 0)
495 if (first_nonstatic_field == null) {
496 first_nonstatic_field = field;
500 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
501 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
502 Report.Warning (282, 3, field.Location,
503 "struct instance field `{0}' found in different declaration from instance field `{1}'",
504 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
509 public void AddProperty (Property prop)
511 if (!AddMember (prop))
514 if (properties == null)
515 properties = new List<MemberCore> ();
517 if (prop.MemberName.Left != null)
518 AddMemberToList (prop, properties, true);
520 AddMemberToList (prop, properties, false);
523 public void AddEvent (Event e)
529 events = new List<MemberCore> ();
535 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
537 public void AddIndexer (Indexer i)
539 if (indexers == null)
540 indexers = new List<MemberCore> ();
542 if (i.IsExplicitImpl)
543 AddMemberToList (i, indexers, true);
545 AddMemberToList (i, indexers, false);
548 public void AddOperator (Operator op)
553 if (operators == null)
554 operators = new List<MemberCore> ();
559 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
561 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
563 if (compiler_generated == null)
564 compiler_generated = new List<CompilerGeneratedClass> ();
566 compiler_generated.Add (c);
569 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
571 if (a.Type == pa.DefaultMember) {
572 if (Indexers != null) {
573 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
578 if (a.Type == pa.Required) {
579 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
583 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
586 public override AttributeTargets AttributeTargets {
588 throw new NotSupportedException ();
592 public IList<TypeContainer> Types {
598 public IList<MemberCore> Methods {
604 public IList<MemberCore> Constants {
610 public TypeSpec BaseType {
612 return spec.BaseType;
616 public IList<FieldBase> Fields {
622 public IList<Constructor> InstanceConstructors {
624 return instance_constructors;
628 public IList<MemberCore> Properties {
634 public IList<MemberCore> Events {
640 public IList<MemberCore> Indexers {
646 public IList<MemberCore> Operators {
652 protected override TypeAttributes TypeAttr {
654 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
658 public int TypeParametersCount {
660 return MemberName.Arity;
664 TypeParameterSpec[] ITypeDefinition.TypeParameters {
666 // TODO MemberCache: this is going to hurt
667 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
671 public string GetAttributeDefaultMember ()
673 return indexers == null ? DefaultIndexerName : indexer_name;
676 public bool IsComImport {
678 if (OptAttributes == null)
681 return OptAttributes.Contains (Compiler.PredefinedAttributes.ComImport);
685 string ITypeDefinition.Namespace {
687 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
691 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
693 if ((field.ModFlags & Modifiers.STATIC) != 0){
694 if (initialized_static_fields == null) {
695 PartialContainer.HasStaticFieldInitializer = true;
696 initialized_static_fields = new List<FieldInitializer> (4);
699 initialized_static_fields.Add (expression);
701 if (initialized_fields == null)
702 initialized_fields = new List<FieldInitializer> (4);
704 initialized_fields.Add (expression);
708 public void ResolveFieldInitializers (BlockContext ec)
710 if (partial_parts != null) {
711 foreach (TypeContainer part in partial_parts) {
712 part.DoResolveFieldInitializers (ec);
715 DoResolveFieldInitializers (ec);
718 void DoResolveFieldInitializers (BlockContext ec)
721 if (initialized_static_fields == null)
724 bool has_complex_initializer = !RootContext.Optimize;
726 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
727 for (i = 0; i < initialized_static_fields.Count; ++i) {
728 FieldInitializer fi = initialized_static_fields [i];
729 ExpressionStatement s = fi.ResolveStatement (ec);
731 s = EmptyExpressionStatement.Instance;
732 } else if (fi.IsComplexInitializer) {
733 has_complex_initializer |= true;
739 for (i = 0; i < initialized_static_fields.Count; ++i) {
740 FieldInitializer fi = initialized_static_fields [i];
742 // Need special check to not optimize code like this
743 // static int a = b = 5;
746 if (!has_complex_initializer && fi.IsDefaultInitializer)
749 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
755 if (initialized_fields == null)
758 for (int i = 0; i < initialized_fields.Count; ++i) {
759 FieldInitializer fi = initialized_fields [i];
760 ExpressionStatement s = fi.ResolveStatement (ec);
765 // Field is re-initialized to its default value => removed
767 if (fi.IsDefaultInitializer && RootContext.Optimize)
770 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
774 public override string DocComment {
786 public PendingImplementation PendingImplementations {
787 get { return pending; }
790 public TypeSpec GetAttributeCoClass ()
792 if (OptAttributes == null)
795 Attribute a = OptAttributes.Search (Compiler.PredefinedAttributes.CoClass);
799 return a.GetCoClassAttributeValue ();
802 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
805 if (OptAttributes != null) {
806 a = OptAttributes.Search (pa);
812 return a.GetAttributeUsageAttribute ();
815 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
817 // FIXME: get rid of partial_parts and store lists of bases of each part here
818 // assumed, not verified: 'part' is in 'partial_parts'
819 ((TypeContainer) part).type_bases = bases;
823 /// This function computes the Base class and also the
824 /// list of interfaces that the class or struct @c implements.
826 /// The return value is an array (might be null) of
827 /// interfaces implemented (as Types).
829 /// The @base_class argument is set to the base object or null
830 /// if this is `System.Object'.
832 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
835 if (type_bases == null)
838 int count = type_bases.Count;
839 TypeExpr [] ifaces = null;
840 var base_context = new BaseContext (this);
841 for (int i = 0, j = 0; i < count; i++){
842 FullNamedExpression fne = type_bases [i];
844 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
845 if (fne_resolved == null)
848 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
849 if (fne_resolved.Type == InternalType.Dynamic) {
850 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
851 GetSignatureForError ());
856 base_type = fne_resolved.Type;
857 base_class = fne_resolved;
862 ifaces = new TypeExpr [count - i];
864 if (fne_resolved.Type.IsInterface) {
865 for (int ii = 0; ii < j; ++ii) {
866 if (fne_resolved.Type == ifaces [ii].Type) {
867 Report.Error (528, Location, "`{0}' is already listed in interface list",
868 fne_resolved.GetSignatureForError ());
873 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
874 Report.Error (61, fne.Location,
875 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
876 fne_resolved.GetSignatureForError (), GetSignatureForError ());
879 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
880 if (Kind != MemberKind.Class) {
881 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
882 } else if (base_class != null)
883 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
884 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
886 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
887 GetSignatureForError (), fne_resolved.GetSignatureForError ());
891 ifaces [j++] = fne_resolved;
897 TypeExpr[] GetNormalPartialBases ()
899 var ifaces = new List<TypeExpr> (0);
900 if (iface_exprs != null)
901 ifaces.AddRange (iface_exprs);
903 foreach (TypeContainer part in partial_parts) {
904 TypeExpr new_base_class;
905 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
906 if (new_base_class != null) {
907 if (base_type_expr != null && new_base_class.Type != base_type) {
908 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
909 Report.Error (263, part.Location,
910 "Partial declarations of `{0}' must not specify different base classes",
911 part.GetSignatureForError ());
913 base_type_expr = new_base_class;
914 base_type = base_type_expr.Type;
918 if (new_ifaces == null)
921 foreach (TypeExpr iface in new_ifaces) {
922 if (ifaces.Contains (iface))
929 if (ifaces.Count == 0)
932 return ifaces.ToArray ();
936 // Checks that some operators come in pairs:
942 // They are matched based on the return type and the argument types
944 void CheckPairedOperators ()
946 bool has_equality_or_inequality = false;
947 var operators = this.operators.ToArray ();
948 bool[] has_pair = new bool[operators.Length];
950 for (int i = 0; i < operators.Length; ++i) {
951 if (operators[i] == null)
954 Operator o_a = (Operator) operators[i];
955 Operator.OpType o_type = o_a.OperatorType;
956 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
957 has_equality_or_inequality = true;
959 Operator.OpType matching_type = o_a.GetMatchingOperator ();
960 if (matching_type == Operator.OpType.TOP) {
965 for (int ii = 0; ii < operators.Length; ++ii) {
966 Operator o_b = (Operator) operators[ii];
967 if (o_b == null || o_b.OperatorType != matching_type)
970 if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
973 if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
979 // Used to ignore duplicate user conversions
985 for (int i = 0; i < operators.Length; ++i) {
986 if (operators[i] == null || has_pair[i])
989 Operator o = (Operator) operators [i];
990 Report.Error (216, o.Location,
991 "The operator `{0}' requires a matching operator `{1}' to also be defined",
992 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
995 if (has_equality_or_inequality) {
996 if (Methods == null || !HasEquals)
997 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
998 GetSignatureForError ());
1000 if (Methods == null || !HasGetHashCode)
1001 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
1002 GetSignatureForError ());
1006 bool CreateTypeBuilder ()
1009 // Sets .size to 1 for structs with no instance fields
1011 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1014 // TODO: Completely wrong
1015 if (Module.GlobalRootNamespace.IsNamespace (Name)) {
1016 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1019 TypeBuilder = Module.CreateBuilder (Name, TypeAttr, type_size);
1021 TypeBuilder builder = Parent.TypeBuilder;
1023 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1026 spec.SetMetaInfo (TypeBuilder);
1027 spec.MemberCache = new MemberCache (this);
1028 spec.DeclaringType = Parent.CurrentType;
1031 Parent.MemberCache.AddMember (spec);
1034 string[] param_names = new string[TypeParameters.Length];
1035 for (int i = 0; i < TypeParameters.Length; i++)
1036 param_names [i] = TypeParameters[i].Name;
1038 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1040 int offset = CurrentTypeParametersStartIndex;
1041 for (int i = offset; i < all_tp_builders.Length; i++) {
1042 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1050 // Creates a proxy base method call inside this container for hoisted base member calls
1052 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1054 Method proxy_method;
1057 // One proxy per base method is enough
1059 if (hoisted_base_call_proxies == null) {
1060 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1061 proxy_method = null;
1063 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1066 if (proxy_method == null) {
1067 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1068 var base_parameters = new Parameter[method.Parameters.Count];
1069 for (int i = 0; i < base_parameters.Length; ++i) {
1070 var base_param = method.Parameters.FixedParameters[i];
1071 base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1072 base_param.Name, base_param.ModFlags, null, Location);
1073 base_parameters[i].Resolve (this, i);
1076 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1077 if (method.Parameters.HasArglist) {
1078 cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1079 cloned_params.Types[0] = TypeManager.runtime_argument_handle_type;
1082 GenericMethod generic_method;
1083 MemberName member_name;
1084 if (method.IsGeneric) {
1086 // Copy all base generic method type parameters info
1088 var hoisted_tparams = method.GenericDefinition.TypeParameters;
1089 var targs = new TypeArguments ();
1090 var type_params = new TypeParameter[hoisted_tparams.Length];
1091 for (int i = 0; i < type_params.Length; ++i) {
1092 var tp = hoisted_tparams[i];
1093 targs.Add (new TypeParameterName (tp.Name, null, Location));
1094 type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
1097 member_name = new MemberName (name, targs, Location);
1098 generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1099 new TypeExpression (method.ReturnType, Location), cloned_params);
1101 member_name = new MemberName (name);
1102 generic_method = null;
1105 // Compiler generated proxy
1106 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1107 Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1108 member_name, cloned_params, null);
1110 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1112 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1113 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1115 // Get all the method parameters and pass them as arguments
1116 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1117 Statement statement;
1118 if (method.ReturnType == TypeManager.void_type)
1119 statement = new StatementExpression (real_base_call);
1121 statement = new Return (real_base_call, Location);
1123 block.AddStatement (statement);
1124 proxy_method.Block = block;
1126 methods.Add (proxy_method);
1127 proxy_method.Define ();
1129 hoisted_base_call_proxies.Add (method, proxy_method);
1132 return proxy_method.Spec;
1135 bool DefineBaseTypes ()
1137 iface_exprs = ResolveBaseTypes (out base_type_expr);
1138 if (partial_parts != null) {
1139 iface_exprs = GetNormalPartialBases ();
1142 var cycle = CheckRecursiveDefinition (this);
1143 if (cycle != null) {
1144 Report.SymbolRelatedToPreviousError (cycle);
1145 if (this is Interface) {
1146 Report.Error (529, Location,
1147 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1148 GetSignatureForError (), cycle.GetSignatureForError ());
1152 Report.Error (146, Location,
1153 "Circular base class dependency involving `{0}' and `{1}'",
1154 GetSignatureForError (), cycle.GetSignatureForError ());
1160 if (iface_exprs != null) {
1161 foreach (TypeExpr iface in iface_exprs) {
1162 // Prevents a crash, the interface might not have been resolved: 442144
1166 var iface_type = iface.Type;
1168 if (!spec.AddInterface (iface_type))
1171 if (iface_type.IsGeneric && spec.Interfaces != null) {
1172 foreach (var prev_iface in iface_exprs) {
1173 if (prev_iface == iface)
1176 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1179 Report.Error (695, Location,
1180 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1181 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1185 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1187 // Ensure the base is always setup
1188 var compiled_iface = iface_type.MemberDefinition as Interface;
1189 if (compiled_iface != null) {
1190 // TODO: Need DefineBaseType only
1191 compiled_iface.DefineType ();
1194 if (iface_type.Interfaces != null) {
1195 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1196 for (int i = 0; i < base_ifaces.Count; ++i) {
1197 var ii_iface_type = base_ifaces[i];
1198 if (spec.AddInterface (ii_iface_type)) {
1199 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1201 if (ii_iface_type.Interfaces != null)
1202 base_ifaces.AddRange (ii_iface_type.Interfaces);
1209 if (Kind == MemberKind.Interface) {
1210 spec.BaseType = TypeManager.object_type;
1214 if (base_type != null) {
1215 spec.BaseType = base_type;
1217 // Set base type after type creation
1218 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1224 public virtual void DefineConstants ()
1226 if (constants != null) {
1227 foreach (Const c in constants) {
1232 if (instance_constructors != null) {
1233 foreach (MethodCore m in instance_constructors) {
1234 var p = m.ParameterInfo;
1236 p.ResolveDefaultValues (m);
1241 if (methods != null) {
1242 foreach (MethodCore m in methods) {
1243 var p = m.ParameterInfo;
1245 p.ResolveDefaultValues (m);
1250 if (indexers != null) {
1251 foreach (Indexer i in indexers) {
1252 i.ParameterInfo.ResolveDefaultValues (i);
1256 if (types != null) {
1257 foreach (var t in types)
1258 t.DefineConstants ();
1263 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1265 public TypeBuilder CreateType ()
1267 if (TypeBuilder != null)
1273 if (!CreateTypeBuilder ()) {
1278 if (partial_parts != null) {
1279 foreach (TypeContainer part in partial_parts) {
1281 part.current_type = current_type;
1282 part.TypeBuilder = TypeBuilder;
1286 if (Types != null) {
1287 foreach (TypeContainer tc in Types) {
1288 if (tc.CreateType () == null) {
1298 public override TypeBuilder DefineType ()
1305 type_defined = true;
1307 if (!DefineBaseTypes ()) {
1312 if (!DefineNestedTypes ()) {
1320 public override void SetParameterInfo (List<Constraints> constraints_list)
1322 base.SetParameterInfo (constraints_list);
1324 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1327 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1328 for (int i = 0; i < tc_names.Length; ++i) {
1329 if (tc_names [i].Name != type_params [i].Name) {
1330 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1331 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1332 GetSignatureForError ());
1336 if (tc_names [i].Variance != type_params [i].Variance) {
1337 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1338 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1339 GetSignatureForError ());
1346 // Replaces normal spec with predefined one when compiling corlib
1347 // and this type container defines predefined type
1349 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1354 void UpdateTypeParameterConstraints (TypeContainer part)
1356 TypeParameter[] current_params = type_params;
1357 for (int i = 0; i < current_params.Length; i++) {
1358 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1361 Report.SymbolRelatedToPreviousError (Location, "");
1362 Report.Error (265, part.Location,
1363 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1364 GetSignatureForError (), current_params [i].GetSignatureForError ());
1368 public bool ResolveTypeParameters ()
1370 if (!DoResolveTypeParameters ())
1373 if (types != null) {
1374 foreach (var type in types)
1375 if (!type.ResolveTypeParameters ())
1379 if (compiler_generated != null) {
1380 foreach (CompilerGeneratedClass c in compiler_generated)
1381 if (!c.ResolveTypeParameters ())
1388 protected virtual bool DoResolveTypeParameters ()
1390 if (CurrentTypeParameters == null)
1393 if (PartialContainer != this)
1394 throw new InternalErrorException ();
1396 var base_context = new BaseContext (this);
1397 foreach (TypeParameter type_param in CurrentTypeParameters) {
1398 if (!type_param.ResolveConstraints (base_context)) {
1404 if (partial_parts != null) {
1405 foreach (TypeContainer part in partial_parts)
1406 UpdateTypeParameterConstraints (part);
1412 protected virtual bool DefineNestedTypes ()
1414 if (Types != null) {
1415 foreach (TypeContainer tc in Types)
1416 if (tc.DefineType () == null)
1423 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1425 if (InTransit != null)
1430 if (base_type_expr != null) {
1431 var ptc = base_type.MemberDefinition as TypeContainer;
1432 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1436 if (iface_exprs != null) {
1437 foreach (TypeExpr iface in iface_exprs) {
1438 // the interface might not have been resolved, prevents a crash, see #442144
1441 var ptc = iface.Type.MemberDefinition as Interface;
1442 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1447 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1455 /// Populates our TypeBuilder with fields and methods
1457 public sealed override bool Define ()
1459 if (members_defined)
1460 return members_defined_ok;
1462 members_defined_ok = DoDefineMembers ();
1463 members_defined = true;
1465 if (types != null) {
1466 foreach (var nested in types)
1470 return members_defined_ok;
1473 protected virtual bool DoDefineMembers ()
1475 if (iface_exprs != null) {
1476 foreach (TypeExpr iface in iface_exprs) {
1480 var iface_type = iface.Type;
1482 // Ensure the base is always setup
1483 var compiled_iface = iface_type.MemberDefinition as Interface;
1484 if (compiled_iface != null)
1485 compiled_iface.Define ();
1487 if (Kind == MemberKind.Interface)
1488 MemberCache.AddInterface (iface_type);
1490 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1491 if (oa != null && !IsObsolete)
1492 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1494 GenericTypeExpr ct = iface as GenericTypeExpr;
1496 // TODO: passing `this' is wrong, should be base type iface instead
1497 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1499 ct.CheckConstraints (this);
1501 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1502 Report.Error (1966, iface.Location,
1503 "`{0}': cannot implement a dynamic interface `{1}'",
1504 GetSignatureForError (), iface.GetSignatureForError ());
1511 if (base_type != null) {
1512 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1513 if (obsolete_attr != null && !IsObsolete)
1514 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1516 var ct = base_type_expr as GenericTypeExpr;
1518 ct.CheckConstraints (this);
1520 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1521 if (baseContainer != null) {
1522 baseContainer.Define ();
1525 // It can trigger define of this type (for generic types only)
1527 if (HasMembersDefined)
1532 if (type_params != null) {
1533 foreach (var tp in type_params) {
1534 tp.CheckGenericConstraints ();
1538 DefineContainerMembers (constants);
1539 DefineContainerMembers (fields);
1541 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1542 pending = PendingImplementation.GetPendingImplementations (this);
1544 if (requires_delayed_unmanagedtype_check) {
1545 requires_delayed_unmanagedtype_check = false;
1546 foreach (FieldBase f in fields) {
1547 if (f.MemberType != null && f.MemberType.IsPointer)
1548 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1554 // Constructors are not in the defined_names array
1556 DefineContainerMembers (instance_constructors);
1558 DefineContainerMembers (events);
1559 DefineContainerMembers (ordered_explicit_member_list);
1560 DefineContainerMembers (ordered_member_list);
1562 if (operators != null) {
1563 DefineContainerMembers (operators);
1564 CheckPairedOperators ();
1567 ComputeIndexerName();
1568 CheckEqualsAndGetHashCode();
1573 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1576 for (int i = 0; i < mcal.Count; ++i) {
1577 MemberCore mc = (MemberCore) mcal[i];
1580 } catch (Exception e) {
1581 throw new InternalErrorException (mc, e);
1587 protected virtual void ComputeIndexerName ()
1589 if (indexers == null)
1592 string class_indexer_name = null;
1595 // If there's both an explicit and an implicit interface implementation, the
1596 // explicit one actually implements the interface while the other one is just
1597 // a normal indexer. See bug #37714.
1600 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1601 foreach (Indexer i in indexers) {
1602 if (i.InterfaceType != null) {
1603 if (seen_normal_indexers)
1604 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1608 seen_normal_indexers = true;
1610 if (class_indexer_name == null) {
1611 class_indexer_name = i.ShortName;
1615 if (i.ShortName != class_indexer_name)
1616 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
1619 if (class_indexer_name != null)
1620 indexer_name = class_indexer_name;
1623 void EmitIndexerName ()
1625 if (!seen_normal_indexers)
1628 PredefinedAttribute pa = Compiler.PredefinedAttributes.DefaultMember;
1629 if (pa.Constructor == null &&
1630 !pa.ResolveConstructor (Location, TypeManager.string_type))
1633 var encoder = new AttributeEncoder (false);
1634 encoder.Encode (GetAttributeDefaultMember ());
1635 encoder.EncodeEmptyNamedArguments ();
1637 pa.EmitAttribute (TypeBuilder, encoder);
1640 protected virtual void CheckEqualsAndGetHashCode ()
1642 if (methods == null)
1645 if (HasEquals && !HasGetHashCode) {
1646 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1650 // Indicated whether container has StructLayout attribute set Explicit
1651 public bool HasExplicitLayout {
1652 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1653 set { caching_flags |= Flags.HasExplicitLayout; }
1656 public bool HasStructLayout {
1657 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1658 set { caching_flags |= Flags.HasStructLayout; }
1661 public MemberCache MemberCache {
1663 return spec.MemberCache;
1667 void CheckMemberUsage (List<MemberCore> al, string member_type)
1672 foreach (MemberCore mc in al) {
1673 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1676 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1677 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1682 public virtual void VerifyMembers ()
1685 // Check for internal or private fields that were never assigned
1687 if (Report.WarningLevel >= 3) {
1688 if (RootContext.EnhancedWarnings) {
1689 CheckMemberUsage (properties, "property");
1690 CheckMemberUsage (methods, "method");
1691 CheckMemberUsage (constants, "constant");
1694 if (fields != null){
1695 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1696 foreach (FieldBase f in fields) {
1697 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1698 if (is_type_exposed)
1705 if ((f.caching_flags & Flags.IsAssigned) == 0)
1706 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1708 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1709 f.GetSignatureForError ());
1715 // Only report 649 on level 4
1717 if (Report.WarningLevel < 4)
1720 if ((f.caching_flags & Flags.IsAssigned) != 0)
1724 // Don't be pendatic over serializable attributes
1726 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1729 Constant c = New.Constantify (f.MemberType, f.Location);
1730 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1731 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1737 public override void Emit ()
1740 MemberSpec candidate;
1741 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1742 if (conflict_symbol == null && candidate == null) {
1743 if ((ModFlags & Modifiers.NEW) != 0)
1744 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1745 GetSignatureForError ());
1747 if ((ModFlags & Modifiers.NEW) == 0) {
1748 if (candidate == null)
1749 candidate = conflict_symbol;
1751 Report.SymbolRelatedToPreviousError (candidate);
1752 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1753 GetSignatureForError (), candidate.GetSignatureForError ());
1758 if (all_tp_builders != null) {
1759 int current_starts_index = CurrentTypeParametersStartIndex;
1760 for (int i = 0; i < all_tp_builders.Length; i++) {
1761 if (i < current_starts_index) {
1762 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1764 CurrentTypeParameters [i - current_starts_index].Emit ();
1769 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1770 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1775 // TODO: move to ClassOrStruct
1776 void EmitConstructors ()
1778 if (instance_constructors == null)
1781 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1782 bool has_compliant_args = false;
1784 foreach (Constructor c in instance_constructors) {
1788 catch (Exception e) {
1789 throw new InternalErrorException (c, e);
1792 if (has_compliant_args)
1795 has_compliant_args = c.HasCompliantArgs;
1797 if (!has_compliant_args)
1798 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1800 foreach (Constructor c in instance_constructors) {
1804 catch (Exception e) {
1805 throw new InternalErrorException (c, e);
1812 /// Emits the code, this step is performed after all
1813 /// the types, enumerations, constructors
1815 public virtual void EmitType ()
1817 if (OptAttributes != null)
1818 OptAttributes.Emit ();
1822 EmitConstructors ();
1824 if (constants != null)
1825 foreach (Const con in constants)
1828 if (default_static_constructor != null)
1829 default_static_constructor.Emit ();
1831 if (operators != null)
1832 foreach (Operator o in operators)
1835 if (properties != null)
1836 foreach (Property p in properties)
1839 if (indexers != null) {
1840 foreach (Indexer indx in indexers)
1845 if (events != null){
1846 foreach (Event e in Events)
1850 if (methods != null) {
1851 for (int i = 0; i < methods.Count; ++i)
1852 ((MethodOrOperator) methods [i]).Emit ();
1856 foreach (FieldBase f in fields)
1859 if (types != null) {
1860 foreach (TypeContainer t in types)
1864 if (pending != null)
1865 pending.VerifyPendingMethods (Report);
1867 if (Report.Errors > 0)
1870 if (compiler_generated != null) {
1871 for (int i = 0; i < compiler_generated.Count; ++i)
1872 compiler_generated [i].EmitType ();
1876 public void CloseType ()
1878 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1881 // Close base type container first to avoid TypeLoadException
1882 if (spec.BaseType != null) {
1883 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1889 caching_flags |= Flags.CloseTypeCreated;
1890 TypeBuilder.CreateType ();
1891 } catch (TypeLoadException){
1893 // This is fine, the code still created the type
1895 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1896 // Console.WriteLine (e.Message);
1897 } catch (Exception e) {
1898 throw new InternalErrorException (this, e);
1902 foreach (TypeContainer tc in Types)
1906 if (compiler_generated != null)
1907 foreach (CompilerGeneratedClass c in compiler_generated)
1912 initialized_fields = null;
1913 initialized_static_fields = null;
1915 ordered_explicit_member_list = null;
1916 ordered_member_list = null;
1921 compiler_generated = null;
1922 default_constructor = null;
1923 default_static_constructor = null;
1925 OptAttributes = null;
1929 // Performs the validation on a Method's modifiers (properties have
1930 // the same properties).
1932 // TODO: Why is it not done at parse stage ?
1934 public bool MethodModifiersValid (MemberCore mc)
1936 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1937 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1939 var flags = mc.ModFlags;
1942 // At most one of static, virtual or override
1944 if ((flags & Modifiers.STATIC) != 0){
1945 if ((flags & vao) != 0){
1946 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1947 mc.GetSignatureForError ());
1952 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1953 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1954 mc.GetSignatureForError ());
1959 // If the declaration includes the abstract modifier, then the
1960 // declaration does not include static, virtual or extern
1962 if ((flags & Modifiers.ABSTRACT) != 0){
1963 if ((flags & Modifiers.EXTERN) != 0){
1965 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1969 if ((flags & Modifiers.SEALED) != 0) {
1970 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1974 if ((flags & Modifiers.VIRTUAL) != 0){
1975 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1979 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1980 Report.SymbolRelatedToPreviousError (this);
1981 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1982 mc.GetSignatureForError (), GetSignatureForError ());
1987 if ((flags & Modifiers.PRIVATE) != 0){
1988 if ((flags & vao) != 0){
1989 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1994 if ((flags & Modifiers.SEALED) != 0){
1995 if ((flags & Modifiers.OVERRIDE) == 0){
1996 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2004 public Constructor DefaultStaticConstructor {
2005 get { return default_static_constructor; }
2008 protected override bool VerifyClsCompliance ()
2010 if (!base.VerifyClsCompliance ())
2013 // Check this name against other containers
2014 NamespaceEntry.NS.VerifyClsCompliance ();
2016 // Check all container names for user classes
2017 if (Kind != MemberKind.Delegate)
2018 MemberCache.VerifyClsCompliance (Definition, Report);
2020 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2021 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2022 GetSignatureForError (), BaseType.GetSignatureForError ());
2028 /// Performs checks for an explicit interface implementation. First it
2029 /// checks whether the `interface_type' is a base inteface implementation.
2030 /// Then it checks whether `name' exists in the interface type.
2032 public bool VerifyImplements (InterfaceMemberBase mb)
2034 var ifaces = spec.Interfaces;
2035 if (ifaces != null) {
2036 foreach (TypeSpec t in ifaces){
2037 if (t == mb.InterfaceType)
2042 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2043 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2044 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2049 // Used for visiblity checks to tests whether this definition shares
2050 // base type baseType, it does member-definition search
2052 public bool IsBaseTypeDefinition (TypeSpec baseType)
2054 // RootContext check
2055 if (TypeBuilder == null)
2060 if (type.MemberDefinition == baseType.MemberDefinition)
2063 type = type.BaseType;
2064 } while (type != null);
2069 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2071 return Module.DeclaringAssembly == assembly;
2074 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2076 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2080 // Public function used to locate types.
2082 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2084 // Returns: Type or null if they type can not be found.
2086 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2088 FullNamedExpression e;
2089 if (arity == 0 && Cache.TryGetValue (name, out e))
2093 int errors = Report.Errors;
2096 TypeParameter[] tp = CurrentTypeParameters;
2098 TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2100 e = new TypeParameterExpr (tparam, Location.Null);
2105 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2108 e = new TypeExpression (t, Location.Null);
2109 else if (Parent != null) {
2110 e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2112 e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2115 // TODO MemberCache: How to cache arity stuff ?
2116 if (errors == Report.Errors && arity == 0)
2122 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2124 // TODO: GenericMethod only
2125 if (PartialContainer == null)
2128 // Has any nested type
2129 // Does not work, because base type can have
2130 //if (PartialContainer.Types == null)
2133 var container = PartialContainer.CurrentType;
2135 // Is not Root container
2136 if (container == null)
2139 var t = MemberCache.FindNestedType (container, name, arity);
2143 // FIXME: Breaks error reporting
2144 if (!t.IsAccessible (CurrentType))
2150 public void Mark_HasEquals ()
2152 cached_method |= CachedMethods.Equals;
2155 public void Mark_HasGetHashCode ()
2157 cached_method |= CachedMethods.GetHashCode;
2161 /// Method container contains Equals method
2163 public bool HasEquals {
2165 return (cached_method & CachedMethods.Equals) != 0;
2170 /// Method container contains GetHashCode method
2172 public bool HasGetHashCode {
2174 return (cached_method & CachedMethods.GetHashCode) != 0;
2178 public bool HasStaticFieldInitializer {
2180 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2184 cached_method |= CachedMethods.HasStaticFieldInitializer;
2186 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2191 // Generates xml doc comments (if any), and if required,
2192 // handle warning report.
2194 internal override void GenerateDocComment (DeclSpace ds)
2196 DocUtil.GenerateTypeDocComment (this, ds, Report);
2199 public override string DocCommentHeader {
2200 get { return "T:"; }
2204 public abstract class ClassOrStruct : TypeContainer
2206 Dictionary<SecurityAction, PermissionSet> declarative_security;
2208 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2209 MemberName name, Attributes attrs, MemberKind kind)
2210 : base (ns, parent, name, attrs, kind)
2214 protected override bool AddToContainer (MemberCore symbol, string name)
2216 if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2217 if (symbol is TypeParameter) {
2218 Report.Error (694, symbol.Location,
2219 "Type parameter `{0}' has same name as containing type, or method",
2220 symbol.GetSignatureForError ());
2224 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2225 if (imb == null || !imb.IsExplicitImpl) {
2226 Report.SymbolRelatedToPreviousError (this);
2227 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2228 symbol.GetSignatureForError ());
2233 return base.AddToContainer (symbol, name);
2236 public override void VerifyMembers ()
2238 base.VerifyMembers ();
2240 if ((events != null) && Report.WarningLevel >= 3) {
2241 foreach (Event e in events){
2242 // Note: The event can be assigned from same class only, so we can report
2243 // this warning for all accessibility modes
2244 if ((e.caching_flags & Flags.IsUsed) == 0)
2245 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2250 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2252 if (a.IsValidSecurityAttribute ()) {
2253 if (declarative_security == null)
2254 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2256 a.ExtractSecurityPermissionSet (declarative_security);
2260 if (a.Type == pa.StructLayout) {
2261 PartialContainer.HasStructLayout = true;
2263 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2264 PartialContainer.HasExplicitLayout = true;
2267 if (a.Type == pa.Dynamic) {
2268 a.Error_MisusedDynamicAttribute ();
2272 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2276 /// Defines the default constructors
2278 protected void DefineDefaultConstructor (bool is_static)
2280 // The default instance constructor is public
2281 // If the class is abstract, the default constructor is protected
2282 // The default static constructor is private
2286 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2288 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2291 Constructor c = new Constructor (this, MemberName.Name, mods,
2292 null, ParametersCompiled.EmptyReadOnlyParameters,
2293 new GeneratedBaseInitializer (Location),
2297 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2300 protected override bool DoDefineMembers ()
2302 CheckProtectedModifier ();
2304 base.DoDefineMembers ();
2306 if (default_static_constructor != null)
2307 default_static_constructor.Define ();
2312 public override void Emit ()
2314 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2315 DefineDefaultConstructor (true);
2316 default_static_constructor.Define ();
2321 if (declarative_security != null) {
2322 foreach (var de in declarative_security) {
2323 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2328 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2330 DeclSpace top_level = Parent;
2331 if (top_level != null) {
2332 while (top_level.Parent != null)
2333 top_level = top_level.Parent;
2335 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2336 if (candidates != null) {
2337 scope = NamespaceEntry;
2342 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2345 protected override TypeAttributes TypeAttr {
2347 if (default_static_constructor == null)
2348 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2350 return base.TypeAttr;
2356 // TODO: should be sealed
2357 public class Class : ClassOrStruct {
2358 const Modifiers AllowedModifiers =
2361 Modifiers.PROTECTED |
2362 Modifiers.INTERNAL |
2364 Modifiers.ABSTRACT |
2369 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2371 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2373 : base (ns, parent, name, attrs, MemberKind.Class)
2375 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2376 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2377 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2379 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2380 Report.FeatureIsNotAvailable (Location, "static classes");
2384 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2386 if (part.Name == "System.Object")
2387 Report.Error (537, part.Location,
2388 "The class System.Object cannot have a base class or implement an interface.");
2389 base.AddBasesForPart (part, bases);
2392 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2394 if (a.Type == pa.AttributeUsage) {
2395 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2396 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2400 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2401 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2405 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2406 a.Error_MissingGuidAttribute ();
2410 if (a.Type == pa.Extension) {
2411 a.Error_MisusedExtensionAttribute ();
2415 if (a.Type.IsConditionallyExcluded (Location))
2418 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2421 public override AttributeTargets AttributeTargets {
2423 return AttributeTargets.Class;
2427 protected override void DefineContainerMembers (System.Collections.IList list)
2433 base.DefineContainerMembers (list);
2437 foreach (MemberCore m in list) {
2438 if (m is Operator) {
2439 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2443 if (m is Destructor) {
2444 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2449 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2453 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2456 if (m is Constructor) {
2457 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2461 Method method = m as Method;
2462 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2463 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2467 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2470 base.DefineContainerMembers (list);
2473 protected override bool DoDefineMembers ()
2475 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2476 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2479 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2480 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2483 if (InstanceConstructors == null && !IsStatic)
2484 DefineDefaultConstructor (false);
2486 return base.DoDefineMembers ();
2489 public override void Emit ()
2493 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2494 Compiler.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2496 if (base_type != null && base_type.HasDynamicElement) {
2497 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type);
2501 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2503 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2505 if (base_class == null) {
2506 if (spec != TypeManager.object_type)
2507 base_type = TypeManager.object_type;
2509 if (base_type.IsGenericParameter){
2510 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2511 GetSignatureForError (), base_type.GetSignatureForError ());
2512 } else if (IsGeneric && base_type.IsAttribute) {
2513 Report.Error (698, base_class.Location,
2514 "A generic type cannot derive from `{0}' because it is an attribute class",
2515 base_class.GetSignatureForError ());
2516 } else if (base_type.IsStatic) {
2517 Report.SymbolRelatedToPreviousError (base_class.Type);
2518 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2519 GetSignatureForError (), base_type.GetSignatureForError ());
2520 } else if (base_type.IsSealed) {
2521 Report.SymbolRelatedToPreviousError (base_class.Type);
2522 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2523 GetSignatureForError (), base_type.GetSignatureForError ());
2524 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2525 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2526 GetSignatureForError (), base_class.GetSignatureForError ());
2529 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2530 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2531 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2532 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2533 GetSignatureForError (), base_type.GetSignatureForError ());
2535 base_type = TypeManager.object_type;
2538 if (!IsAccessibleAs (base_type)) {
2539 Report.SymbolRelatedToPreviousError (base_type);
2540 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2541 base_type.GetSignatureForError (), GetSignatureForError ());
2545 if (PartialContainer.IsStatic && ifaces != null) {
2546 foreach (TypeExpr t in ifaces)
2547 Report.SymbolRelatedToPreviousError (t.Type);
2548 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2554 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2555 /// Valid only for attribute classes.
2556 public override string[] ConditionalConditions ()
2558 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2561 caching_flags &= ~Flags.Excluded_Undetected;
2563 if (OptAttributes == null)
2566 Attribute[] attrs = OptAttributes.SearchMulti (Compiler.PredefinedAttributes.Conditional);
2570 string[] conditions = new string[attrs.Length];
2571 for (int i = 0; i < conditions.Length; ++i)
2572 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2574 caching_flags |= Flags.Excluded;
2579 // FIXME: How do we deal with the user specifying a different
2582 protected override TypeAttributes TypeAttr {
2584 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2586 ta |= StaticClassAttribute;
2592 public sealed class Struct : ClassOrStruct {
2594 bool is_unmanaged, has_unmanaged_check_done;
2598 // Modifiers allowed in a struct declaration
2600 const Modifiers AllowedModifiers =
2603 Modifiers.PROTECTED |
2604 Modifiers.INTERNAL |
2608 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2609 Modifiers mod, Attributes attrs)
2610 : base (ns, parent, name, attrs, MemberKind.Struct)
2612 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2613 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2614 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2617 public override AttributeTargets AttributeTargets {
2619 return AttributeTargets.Struct;
2623 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2625 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2628 // When struct constains fixed fixed and struct layout has explicitly
2629 // set CharSet, its value has to be propagated to compiler generated
2632 if (a.Type == pa.StructLayout && Fields != null) {
2633 var value = a.GetNamedValue ("CharSet");
2637 for (int i = 0; i < Fields.Count; ++i) {
2638 FixedField ff = Fields [i] as FixedField;
2642 ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2647 bool CheckStructCycles (Struct s)
2649 if (s.Fields == null)
2656 foreach (FieldBase field in s.Fields) {
2657 TypeSpec ftype = field.Spec.MemberType;
2658 if (!ftype.IsStruct)
2661 if (ftype is PredefinedTypeSpec)
2664 foreach (var targ in ftype.TypeArguments) {
2665 if (!CheckFieldTypeCycle (targ)) {
2666 Report.Error (523, field.Location,
2667 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2668 field.GetSignatureForError (), ftype.GetSignatureForError ());
2673 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2676 if (!CheckFieldTypeCycle (ftype)) {
2677 Report.Error (523, field.Location,
2678 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2679 field.GetSignatureForError (), ftype.GetSignatureForError ());
2684 s.InTransit = false;
2688 bool CheckFieldTypeCycle (TypeSpec ts)
2690 var fts = ts.MemberDefinition as Struct;
2694 return CheckStructCycles (fts);
2697 public override void Emit ()
2699 CheckStructCycles (this);
2704 public override bool IsUnmanagedType ()
2709 if (has_unmanaged_check_done)
2710 return is_unmanaged;
2712 if (requires_delayed_unmanagedtype_check)
2715 requires_delayed_unmanagedtype_check = true;
2717 foreach (FieldBase f in fields) {
2721 // It can happen when recursive unmanaged types are defined
2722 // struct S { S* s; }
2723 TypeSpec mt = f.MemberType;
2728 while (mt.IsPointer)
2729 mt = TypeManager.GetElementType (mt);
2731 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2732 has_unmanaged_check_done = true;
2736 if (TypeManager.IsUnmanagedType (mt))
2739 has_unmanaged_check_done = true;
2743 has_unmanaged_check_done = true;
2744 is_unmanaged = true;
2748 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2750 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2751 base_type = TypeManager.value_type;
2755 protected override TypeAttributes TypeAttr {
2757 const TypeAttributes DefaultTypeAttributes =
2758 TypeAttributes.SequentialLayout |
2759 TypeAttributes.Sealed;
2761 return base.TypeAttr | DefaultTypeAttributes;
2765 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2767 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2768 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2769 field.GetSignatureForError ());
2772 base.RegisterFieldForInitialization (field, expression);
2780 public sealed class Interface : TypeContainer {
2783 /// Modifiers allowed in a class declaration
2785 public const Modifiers AllowedModifiers =
2788 Modifiers.PROTECTED |
2789 Modifiers.INTERNAL |
2793 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2795 : base (ns, parent, name, attrs, MemberKind.Interface)
2797 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2799 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2800 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2803 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2805 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2806 a.Error_MissingGuidAttribute ();
2810 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2814 public override AttributeTargets AttributeTargets {
2816 return AttributeTargets.Interface;
2820 protected override TypeAttributes TypeAttr {
2822 const TypeAttributes DefaultTypeAttributes =
2823 TypeAttributes.AutoLayout |
2824 TypeAttributes.Abstract |
2825 TypeAttributes.Interface;
2827 return base.TypeAttr | DefaultTypeAttributes;
2831 protected override bool VerifyClsCompliance ()
2833 if (!base.VerifyClsCompliance ())
2836 if (iface_exprs != null) {
2837 foreach (var iface in iface_exprs) {
2838 if (iface.Type.IsCLSCompliant ())
2841 Report.SymbolRelatedToPreviousError (iface.Type);
2842 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2843 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2851 public abstract class InterfaceMemberBase : MemberBase
2854 // Common modifiers allowed in a class declaration
2856 protected const Modifiers AllowedModifiersClass =
2859 Modifiers.PROTECTED |
2860 Modifiers.INTERNAL |
2865 Modifiers.OVERRIDE |
2866 Modifiers.ABSTRACT |
2871 // Common modifiers allowed in a struct declaration
2873 protected const Modifiers AllowedModifiersStruct =
2876 Modifiers.PROTECTED |
2877 Modifiers.INTERNAL |
2880 Modifiers.OVERRIDE |
2885 // Common modifiers allowed in a interface declaration
2887 protected const Modifiers AllowedModifiersInterface =
2892 // Whether this is an interface member.
2894 public bool IsInterface;
2897 // If true, this is an explicit interface implementation
2899 public bool IsExplicitImpl;
2901 protected bool is_external_implementation;
2904 // The interface type we are explicitly implementing
2906 public TypeSpec InterfaceType;
2909 // The method we're overriding if this is an override method.
2911 protected MethodSpec base_method;
2913 readonly Modifiers explicit_mod_flags;
2914 public MethodAttributes flags;
2916 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2917 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2918 MemberName name, Attributes attrs)
2919 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2922 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2923 IsExplicitImpl = (MemberName.Left != null);
2924 explicit_mod_flags = mod;
2927 protected override bool CheckBase ()
2929 if (!base.CheckBase ())
2932 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2933 CheckForDuplications ();
2938 // For System.Object only
2939 if (Parent.BaseType == null)
2942 MemberSpec candidate;
2943 var base_member = FindBaseMember (out candidate);
2945 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2946 if (base_member == null) {
2947 if (candidate == null) {
2948 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2949 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2950 "object.Finalize()");
2952 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2953 GetSignatureForError (), SimpleName.GetMemberType (this));
2956 Report.SymbolRelatedToPreviousError (candidate);
2958 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2959 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2960 else if (this is PropertyBase)
2961 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2962 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2964 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2965 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2971 if (!CheckOverrideAgainstBase (base_member))
2974 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2976 if (OptAttributes == null || !OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2977 Report.SymbolRelatedToPreviousError (base_member);
2978 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2979 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2982 if (OptAttributes != null && OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2983 Report.SymbolRelatedToPreviousError (base_member);
2984 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2985 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2989 base_method = base_member as MethodSpec;
2993 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2994 base_member = candidate;
2996 if (base_member == null) {
2997 if ((ModFlags & Modifiers.NEW) != 0) {
2998 if (base_member == null) {
2999 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3000 GetSignatureForError ());
3004 if ((ModFlags & Modifiers.NEW) == 0) {
3005 ModFlags |= Modifiers.NEW;
3006 if (!IsCompilerGenerated) {
3007 Report.SymbolRelatedToPreviousError (base_member);
3008 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3009 Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
3010 GetSignatureForError (), base_member.GetSignatureForError ());
3012 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3013 GetSignatureForError (), base_member.GetSignatureForError ());
3018 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3019 Report.SymbolRelatedToPreviousError (base_member);
3020 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3021 GetSignatureForError (), base_member.GetSignatureForError ());
3028 protected virtual bool CheckForDuplications ()
3030 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3034 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3035 // that have been defined.
3037 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3041 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3042 Report.SymbolRelatedToPreviousError (base_member);
3043 Report.Error (506, Location,
3044 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3045 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3049 // Now we check that the overriden method is not final
3050 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3051 Report.SymbolRelatedToPreviousError (base_member);
3052 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3053 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3057 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3058 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3059 Report.SymbolRelatedToPreviousError (base_member);
3060 if (this is PropertyBasedMember) {
3061 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3062 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3064 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3065 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3073 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3075 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3076 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3078 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3080 // when overriding protected internal, the method can be declared
3081 // protected internal only within the same assembly or assembly
3082 // which has InternalsVisibleTo
3084 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3085 return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3087 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
3089 // if it's not "protected internal", it must be "protected"
3094 if (this_member.Parent.PartialContainer.DeclaringAssembly == base_member.DeclaringType.MemberDefinition.DeclaringAssembly) {
3096 // protected within the same assembly - an error
3100 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
3101 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
3103 // protected ok, but other attributes differ - report an error
3110 return thisp == base_classp;
3113 public override bool Define ()
3116 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3117 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3119 flags = MethodAttributes.Public |
3120 MethodAttributes.Abstract |
3121 MethodAttributes.HideBySig |
3122 MethodAttributes.NewSlot |
3123 MethodAttributes.Virtual;
3125 Parent.PartialContainer.MethodModifiersValid (this);
3127 flags = ModifiersExtensions.MethodAttr (ModFlags);
3130 if (IsExplicitImpl) {
3131 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3132 if (iface_texpr == null)
3135 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3136 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3137 GetSignatureForError ());
3140 InterfaceType = iface_texpr.Type;
3142 if (!InterfaceType.IsInterface) {
3143 Report.SymbolRelatedToPreviousError (InterfaceType);
3144 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3145 TypeManager.CSharpName (InterfaceType));
3147 Parent.PartialContainer.VerifyImplements (this);
3150 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3153 return base.Define ();
3156 protected bool DefineParameters (ParametersCompiled parameters)
3158 if (!parameters.Resolve (this))
3162 for (int i = 0; i < parameters.Count; ++i) {
3163 Parameter p = parameters [i];
3165 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3166 p.Warning_UselessOptionalParameter (Report);
3168 if (p.CheckAccessibility (this))
3171 TypeSpec t = parameters.Types [i];
3172 Report.SymbolRelatedToPreviousError (t);
3173 if (this is Indexer)
3174 Report.Error (55, Location,
3175 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3176 TypeManager.CSharpName (t), GetSignatureForError ());
3177 else if (this is Operator)
3178 Report.Error (57, Location,
3179 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3180 TypeManager.CSharpName (t), GetSignatureForError ());
3182 Report.Error (51, Location,
3183 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3184 TypeManager.CSharpName (t), GetSignatureForError ());
3190 public override void Emit()
3192 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3193 // We are more strict than csc and report this as an error because SRE does not allow emit that
3194 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3195 if (this is Constructor) {
3196 Report.Error (824, Location,
3197 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3199 Report.Error (626, Location,
3200 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3201 GetSignatureForError ());
3208 public override bool EnableOverloadChecks (MemberCore overload)
3211 // Two members can differ in their explicit interface
3212 // type parameter only
3214 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3215 if (imb != null && imb.IsExplicitImpl) {
3216 if (IsExplicitImpl) {
3217 caching_flags |= Flags.MethodOverloadsExist;
3222 return IsExplicitImpl;
3225 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3227 Report.SymbolRelatedToPreviousError (base_member);
3228 Report.Error (507, member.Location,
3229 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3230 member.GetSignatureForError (),
3231 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3232 base_member.GetSignatureForError ());
3235 protected void Error_StaticReturnType ()
3237 Report.Error (722, Location,
3238 "`{0}': static types cannot be used as return types",
3239 MemberType.GetSignatureForError ());
3243 /// Gets base method and its return type
3245 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3247 return MemberCache.FindBaseMember (this, out bestCandidate);
3251 // The "short" name of this property / indexer / event. This is the
3252 // name without the explicit interface.
3254 public string ShortName {
3255 get { return MemberName.Name; }
3256 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3260 // Returns full metadata method name
3262 public string GetFullName (MemberName name)
3264 return GetFullName (name.Name);
3267 public string GetFullName (string name)
3269 if (!IsExplicitImpl)
3273 // When dealing with explicit members a full interface type
3274 // name is added to member name to avoid possible name conflicts
3276 // We use CSharpName which gets us full name with benefit of
3277 // replacing predefined names which saves some space and name
3280 return TypeManager.CSharpName (InterfaceType) + "." + name;
3283 protected override bool VerifyClsCompliance ()
3285 if (!base.VerifyClsCompliance ()) {
3289 if (GenericMethod != null)
3290 GenericMethod.VerifyClsCompliance ();
3295 public override bool IsUsed
3297 get { return IsExplicitImpl || base.IsUsed; }
3302 public abstract class MemberBase : MemberCore
3304 protected FullNamedExpression type_expr;
3305 protected TypeSpec member_type;
3307 public readonly DeclSpace ds;
3308 public readonly GenericMethod GenericMethod;
3310 protected MemberBase (DeclSpace parent, GenericMethod generic,
3311 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3312 MemberName name, Attributes attrs)
3313 : base (parent, name, attrs)
3315 this.ds = generic != null ? generic : (DeclSpace) parent;
3316 this.type_expr = type;
3317 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3318 GenericMethod = generic;
3319 if (GenericMethod != null)
3320 GenericMethod.ModFlags = ModFlags;
3325 public TypeSpec MemberType {
3331 public FullNamedExpression TypeExpression {
3340 // Main member define entry
3342 public override bool Define ()
3344 DoMemberTypeIndependentChecks ();
3347 // Returns false only when type resolution failed
3349 if (!ResolveMemberType ())
3352 DoMemberTypeDependentChecks ();
3357 // Any type_name independent checks
3359 protected virtual void DoMemberTypeIndependentChecks ()
3361 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3362 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3363 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3364 GetSignatureForError (), Parent.GetSignatureForError ());
3369 // Any type_name dependent checks
3371 protected virtual void DoMemberTypeDependentChecks ()
3373 // verify accessibility
3374 if (!IsAccessibleAs (MemberType)) {
3375 Report.SymbolRelatedToPreviousError (MemberType);
3376 if (this is Property)
3377 Report.Error (53, Location,
3378 "Inconsistent accessibility: property type `" +
3379 TypeManager.CSharpName (MemberType) + "' is less " +
3380 "accessible than property `" + GetSignatureForError () + "'");
3381 else if (this is Indexer)
3382 Report.Error (54, Location,
3383 "Inconsistent accessibility: indexer return type `" +
3384 TypeManager.CSharpName (MemberType) + "' is less " +
3385 "accessible than indexer `" + GetSignatureForError () + "'");
3386 else if (this is MethodCore) {
3387 if (this is Operator)
3388 Report.Error (56, Location,
3389 "Inconsistent accessibility: return type `" +
3390 TypeManager.CSharpName (MemberType) + "' is less " +
3391 "accessible than operator `" + GetSignatureForError () + "'");
3393 Report.Error (50, Location,
3394 "Inconsistent accessibility: return type `" +
3395 TypeManager.CSharpName (MemberType) + "' is less " +
3396 "accessible than method `" + GetSignatureForError () + "'");
3398 Report.Error (52, Location,
3399 "Inconsistent accessibility: field type `" +
3400 TypeManager.CSharpName (MemberType) + "' is less " +
3401 "accessible than field `" + GetSignatureForError () + "'");
3405 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3406 TypeManager.CheckTypeVariance (MemberType, variance, this);
3409 protected bool IsTypePermitted ()
3411 if (TypeManager.IsSpecialType (MemberType)) {
3412 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3418 protected virtual bool CheckBase ()
3420 CheckProtectedModifier ();
3425 protected virtual bool ResolveMemberType ()
3427 if (member_type != null)
3428 throw new InternalErrorException ("Multi-resolve");
3430 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3435 // Replace original type name, error reporting can use fully resolved name
3439 member_type = te.Type;