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 ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
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 List<CompilerGeneratedClass> compiler_generated;
172 // Pointers to the default constructor and the default static constructor
174 protected Constructor default_constructor;
175 protected Constructor default_static_constructor;
178 // Points to the first non-static field added to the container.
180 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
181 // and the first one's as good as any.
183 FieldBase first_nonstatic_field = null;
186 // This one is computed after we can distinguish interfaces
187 // from classes from the arraylist `type_bases'
189 protected TypeSpec base_type;
190 protected TypeExpr base_type_expr;
191 protected TypeExpr[] iface_exprs;
193 protected List<FullNamedExpression> type_bases;
195 bool members_defined;
196 bool members_defined_ok;
199 TypeContainer InTransit;
201 GenericTypeParameterBuilder[] all_tp_builders;
203 public const string DefaultIndexerName = "Item";
205 private bool seen_normal_indexers = false;
206 private string indexer_name = DefaultIndexerName;
207 protected bool requires_delayed_unmanagedtype_check;
210 private CachedMethods cached_method;
212 protected TypeSpec spec;
213 TypeSpec current_type;
215 List<TypeContainer> partial_parts;
218 /// The pending methods that need to be implemented
219 // (interfaces or abstract methods)
221 PendingImplementation pending;
223 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
224 Attributes attrs, MemberKind kind)
225 : base (ns, parent, name, attrs)
227 if (parent != null && parent.NamespaceEntry != ns)
228 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
231 this.PartialContainer = this;
236 public override TypeSpec CurrentType {
238 if (current_type == null) {
241 // Switch to inflated version as it's used by all expressions
243 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
244 current_type = spec.MakeGenericType (targs);
254 public override TypeParameter[] CurrentTypeParameters {
256 return PartialContainer.type_params;
260 int CurrentTypeParametersStartIndex {
262 int total = all_tp_builders.Length;
263 if (CurrentTypeParameters != null) {
264 return total - CurrentTypeParameters.Length;
270 public TypeSpec Definition {
276 public bool HasMembersDefined {
278 return members_defined;
284 public bool AddMember (MemberCore symbol)
286 return AddToContainer (symbol, symbol.MemberName.Basename);
289 public bool AddMember (MemberCore symbol, string name)
291 return AddToContainer (symbol, name);
294 protected virtual bool AddMemberType (TypeContainer ds)
296 return AddToContainer (ds, ds.Basename);
299 protected virtual void RemoveMemberType (DeclSpace ds)
301 RemoveFromContainer (ds.Basename);
304 public void AddConstant (Const constant)
306 if (!AddMember (constant))
309 if (constants == null)
310 constants = new List<MemberCore> ();
312 constants.Add (constant);
315 public TypeContainer AddTypeContainer (TypeContainer tc)
317 if (!AddMemberType (tc))
321 types = new List<TypeContainer> ();
327 public virtual TypeContainer AddPartial (TypeContainer next_part)
329 return AddPartial (next_part, next_part.Basename);
332 protected TypeContainer AddPartial (TypeContainer next_part, string name)
334 next_part.ModFlags |= Modifiers.PARTIAL;
335 TypeContainer tc = GetDefinition (name) as TypeContainer;
337 return AddTypeContainer (next_part);
339 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
340 Report.SymbolRelatedToPreviousError (next_part);
341 Error_MissingPartialModifier (tc);
344 if (tc.Kind != next_part.Kind) {
345 Report.SymbolRelatedToPreviousError (tc);
346 Report.Error (261, next_part.Location,
347 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
348 next_part.GetSignatureForError ());
351 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
352 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
353 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
354 Report.SymbolRelatedToPreviousError (tc);
355 Report.Error (262, next_part.Location,
356 "Partial declarations of `{0}' have conflicting accessibility modifiers",
357 next_part.GetSignatureForError ());
360 if (tc.partial_parts == null)
361 tc.partial_parts = new List<TypeContainer> (1);
363 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
364 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
365 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
366 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
367 tc.ModFlags |= next_part.ModFlags;
369 tc.ModFlags |= next_part.ModFlags;
372 tc.spec.Modifiers = tc.ModFlags;
374 if (next_part.attributes != null) {
375 if (tc.attributes == null)
376 tc.attributes = next_part.attributes;
378 tc.attributes.AddAttributes (next_part.attributes.Attrs);
381 next_part.PartialContainer = tc;
382 tc.partial_parts.Add (next_part);
386 public virtual void RemoveTypeContainer (TypeContainer next_part)
389 types.Remove (next_part);
390 RemoveMemberType (next_part);
393 public void AddDelegate (Delegate d)
395 AddTypeContainer (d);
398 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
400 if (ordered_explicit_member_list == null) {
401 ordered_explicit_member_list = new List<MemberCore> ();
402 ordered_member_list = new List<MemberCore> ();
406 if (Kind == MemberKind.Interface) {
407 Report.Error (541, mc.Location,
408 "`{0}': explicit interface declaration can only be declared in a class or struct",
409 mc.GetSignatureForError ());
412 ordered_explicit_member_list.Add (mc);
413 alist.Insert (0, mc);
415 ordered_member_list.Add (mc);
421 public void AddMethod (MethodOrOperator method)
423 if (!AddToContainer (method, method.MemberName.Basename))
427 methods = new List<MemberCore> ();
429 if (method.MemberName.Left != null)
430 AddMemberToList (method, methods, true);
432 AddMemberToList (method, methods, false);
435 public void AddConstructor (Constructor c)
437 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
438 if (!AddToContainer (c, is_static ?
439 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
442 if (is_static && c.ParameterInfo.IsEmpty){
443 if (default_static_constructor != null) {
444 Report.SymbolRelatedToPreviousError (default_static_constructor);
445 Report.Error (111, c.Location,
446 "A member `{0}' is already defined. Rename this member or use different parameter types",
447 c.GetSignatureForError ());
451 default_static_constructor = c;
453 if (c.ParameterInfo.IsEmpty)
454 default_constructor = c;
456 if (instance_constructors == null)
457 instance_constructors = new List<Constructor> ();
459 instance_constructors.Add (c);
463 public bool AddField (FieldBase field)
465 if (!AddMember (field))
469 fields = new List<FieldBase> ();
473 if ((field.ModFlags & Modifiers.STATIC) != 0)
476 if (first_nonstatic_field == null) {
477 first_nonstatic_field = field;
481 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
482 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
483 Report.Warning (282, 3, field.Location,
484 "struct instance field `{0}' found in different declaration from instance field `{1}'",
485 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
490 public void AddProperty (Property prop)
492 if (!AddMember (prop))
495 if (properties == null)
496 properties = new List<MemberCore> ();
498 if (prop.MemberName.Left != null)
499 AddMemberToList (prop, properties, true);
501 AddMemberToList (prop, properties, false);
504 public void AddEvent (Event e)
510 events = new List<MemberCore> ();
516 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
518 public void AddIndexer (Indexer i)
520 if (indexers == null)
521 indexers = new List<MemberCore> ();
523 if (i.IsExplicitImpl)
524 AddMemberToList (i, indexers, true);
526 AddMemberToList (i, indexers, false);
529 public void AddOperator (Operator op)
534 if (operators == null)
535 operators = new List<MemberCore> ();
540 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
542 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
544 if (compiler_generated == null)
545 compiler_generated = new List<CompilerGeneratedClass> ();
547 compiler_generated.Add (c);
550 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
552 if (a.Type == pa.DefaultMember) {
553 if (Indexers != null) {
554 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
559 if (a.Type == pa.Required) {
560 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
564 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
567 public override AttributeTargets AttributeTargets {
569 throw new NotSupportedException ();
573 public IList<TypeContainer> Types {
579 public IList<MemberCore> Methods {
585 public IList<MemberCore> Constants {
591 public TypeSpec BaseType {
593 return spec.BaseType;
597 public IList<FieldBase> Fields {
603 public IList<Constructor> InstanceConstructors {
605 return instance_constructors;
609 public IList<MemberCore> Properties {
615 public IList<MemberCore> Events {
621 public IList<MemberCore> Indexers {
627 public IList<MemberCore> Operators {
633 public IList<CompilerGeneratedClass> CompilerGeneratedClasses {
635 return compiler_generated;
639 protected override TypeAttributes TypeAttr {
641 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
645 public int TypeParametersCount {
647 return MemberName.Arity;
651 TypeParameterSpec[] ITypeDefinition.TypeParameters {
653 // TODO MemberCache: this is going to hurt
654 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
658 public string GetAttributeDefaultMember ()
660 return indexers == null ? DefaultIndexerName : indexer_name;
663 public bool IsComImport {
665 if (OptAttributes == null)
668 return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
672 string ITypeDefinition.Namespace {
674 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
678 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
680 if ((field.ModFlags & Modifiers.STATIC) != 0){
681 if (initialized_static_fields == null) {
682 PartialContainer.HasStaticFieldInitializer = true;
683 initialized_static_fields = new List<FieldInitializer> (4);
686 initialized_static_fields.Add (expression);
688 if (initialized_fields == null)
689 initialized_fields = new List<FieldInitializer> (4);
691 initialized_fields.Add (expression);
695 public void ResolveFieldInitializers (BlockContext ec)
697 if (partial_parts != null) {
698 foreach (TypeContainer part in partial_parts) {
699 part.DoResolveFieldInitializers (ec);
702 DoResolveFieldInitializers (ec);
705 void DoResolveFieldInitializers (BlockContext ec)
708 if (initialized_static_fields == null)
711 bool has_complex_initializer = !RootContext.Optimize;
713 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
714 for (i = 0; i < initialized_static_fields.Count; ++i) {
715 FieldInitializer fi = initialized_static_fields [i];
716 ExpressionStatement s = fi.ResolveStatement (ec);
718 s = EmptyExpressionStatement.Instance;
719 } else if (fi.IsComplexInitializer) {
720 has_complex_initializer |= true;
726 for (i = 0; i < initialized_static_fields.Count; ++i) {
727 FieldInitializer fi = initialized_static_fields [i];
729 // Need special check to not optimize code like this
730 // static int a = b = 5;
733 if (!has_complex_initializer && fi.IsDefaultInitializer)
736 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
742 if (initialized_fields == null)
745 for (int i = 0; i < initialized_fields.Count; ++i) {
746 FieldInitializer fi = initialized_fields [i];
747 ExpressionStatement s = fi.ResolveStatement (ec);
752 // Field is re-initialized to its default value => removed
754 if (fi.IsDefaultInitializer && RootContext.Optimize)
757 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
761 public override string DocComment {
773 public PendingImplementation PendingImplementations {
774 get { return pending; }
777 public TypeSpec GetAttributeCoClass ()
779 if (OptAttributes == null)
782 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CoClass);
786 return a.GetCoClassAttributeValue ();
789 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
792 if (OptAttributes != null) {
793 a = OptAttributes.Search (pa);
799 return a.GetAttributeUsageAttribute ();
802 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
804 // FIXME: get rid of partial_parts and store lists of bases of each part here
805 // assumed, not verified: 'part' is in 'partial_parts'
806 ((TypeContainer) part).type_bases = bases;
810 /// This function computes the Base class and also the
811 /// list of interfaces that the class or struct @c implements.
813 /// The return value is an array (might be null) of
814 /// interfaces implemented (as Types).
816 /// The @base_class argument is set to the base object or null
817 /// if this is `System.Object'.
819 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
822 if (type_bases == null)
825 int count = type_bases.Count;
826 TypeExpr [] ifaces = null;
827 var base_context = new BaseContext (this);
828 for (int i = 0, j = 0; i < count; i++){
829 FullNamedExpression fne = type_bases [i];
831 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
832 if (fne_resolved == null)
835 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
836 if (fne_resolved.Type == InternalType.Dynamic)
837 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
838 GetSignatureForError ());
840 base_type = fne_resolved.Type;
842 base_class = fne_resolved;
847 ifaces = new TypeExpr [count - i];
849 if (fne_resolved.Type.IsInterface) {
850 for (int ii = 0; ii < j; ++ii) {
851 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
852 Report.Error (528, Location, "`{0}' is already listed in interface list",
853 fne_resolved.GetSignatureForError ());
858 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
859 Report.Error (61, fne.Location,
860 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
861 fne_resolved.GetSignatureForError (), GetSignatureForError ());
864 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
865 if (Kind != MemberKind.Class) {
866 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
867 } else if (base_class != null)
868 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
869 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
871 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
872 GetSignatureForError (), fne_resolved.GetSignatureForError ());
876 ifaces [j++] = fne_resolved;
882 TypeExpr[] GetNormalPartialBases ()
884 var ifaces = new List<TypeExpr> (0);
885 if (iface_exprs != null)
886 ifaces.AddRange (iface_exprs);
888 foreach (TypeContainer part in partial_parts) {
889 TypeExpr new_base_class;
890 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
891 if (new_base_class != null) {
892 if (base_type_expr != null && new_base_class.Type != base_type) {
893 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
894 Report.Error (263, part.Location,
895 "Partial declarations of `{0}' must not specify different base classes",
896 part.GetSignatureForError ());
898 base_type_expr = new_base_class;
899 base_type = base_type_expr.Type;
903 if (new_ifaces == null)
906 foreach (TypeExpr iface in new_ifaces) {
907 if (ifaces.Contains (iface))
914 if (ifaces.Count == 0)
917 return ifaces.ToArray ();
921 // Checks that some operators come in pairs:
927 // They are matched based on the return type and the argument types
929 void CheckPairedOperators ()
931 bool has_equality_or_inequality = false;
932 var operators = this.operators.ToArray ();
933 bool[] has_pair = new bool[operators.Length];
935 for (int i = 0; i < operators.Length; ++i) {
936 if (operators[i] == null)
939 Operator o_a = (Operator) operators[i];
940 Operator.OpType o_type = o_a.OperatorType;
941 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
942 has_equality_or_inequality = true;
944 Operator.OpType matching_type = o_a.GetMatchingOperator ();
945 if (matching_type == Operator.OpType.TOP) {
950 for (int ii = 0; ii < operators.Length; ++ii) {
951 Operator o_b = (Operator) operators[ii];
952 if (o_b == null || o_b.OperatorType != matching_type)
955 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
958 if (!TypeSpecComparer.Default.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
964 // Used to ignore duplicate user conversions
970 for (int i = 0; i < operators.Length; ++i) {
971 if (operators[i] == null || has_pair[i])
974 Operator o = (Operator) operators [i];
975 Report.Error (216, o.Location,
976 "The operator `{0}' requires a matching operator `{1}' to also be defined",
977 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
980 if (has_equality_or_inequality) {
981 if (Methods == null || !HasEquals)
982 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
983 GetSignatureForError ());
985 if (Methods == null || !HasGetHashCode)
986 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
987 GetSignatureForError ());
991 bool CreateTypeBuilder ()
994 // Sets .size to 1 for structs with no instance fields
996 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
999 if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
1000 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1004 ModuleBuilder builder = Module.Compiled.Builder;
1005 TypeBuilder = builder.DefineType (Name, TypeAttr, null, type_size);
1007 TypeBuilder builder = Parent.TypeBuilder;
1009 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1012 spec.SetMetaInfo (TypeBuilder);
1013 spec.MemberCache = new MemberCache (this);
1014 spec.DeclaringType = Parent.CurrentType;
1017 Parent.MemberCache.AddMember (spec);
1020 string[] param_names = new string[TypeParameters.Length];
1021 for (int i = 0; i < TypeParameters.Length; i++)
1022 param_names [i] = TypeParameters[i].Name;
1024 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1026 int offset = CurrentTypeParametersStartIndex;
1027 for (int i = offset; i < all_tp_builders.Length; i++) {
1028 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1035 bool DefineBaseTypes ()
1037 iface_exprs = ResolveBaseTypes (out base_type_expr);
1038 if (partial_parts != null) {
1039 iface_exprs = GetNormalPartialBases ();
1042 var cycle = CheckRecursiveDefinition (this);
1043 if (cycle != null) {
1044 Report.SymbolRelatedToPreviousError (cycle);
1045 if (this is Interface) {
1046 Report.Error (529, Location,
1047 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1048 GetSignatureForError (), cycle.GetSignatureForError ());
1050 Report.Error (146, Location,
1051 "Circular base class dependency involving `{0}' and `{1}'",
1052 GetSignatureForError (), cycle.GetSignatureForError ());
1058 if (iface_exprs != null) {
1059 foreach (TypeExpr iface in iface_exprs) {
1060 // Prevents a crash, the interface might not have been resolved: 442144
1064 var iface_type = iface.Type;
1066 if (!spec.AddInterface (iface_type))
1069 if (iface_type.IsGeneric && spec.Interfaces != null) {
1070 foreach (var prev_iface in iface_exprs) {
1071 if (prev_iface == iface)
1074 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1077 Report.Error (695, Location,
1078 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1079 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1083 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1085 // Ensure the base is always setup
1086 var compiled_iface = iface_type.MemberDefinition as Interface;
1087 if (compiled_iface != null) {
1088 // TODO: Need DefineBaseType only
1089 compiled_iface.DefineType ();
1092 if (iface_type.Interfaces != null) {
1093 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1094 for (int i = 0; i < base_ifaces.Count; ++i) {
1095 var ii_iface_type = base_ifaces[i];
1096 if (spec.AddInterface (ii_iface_type)) {
1097 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1099 if (ii_iface_type.Interfaces != null)
1100 base_ifaces.AddRange (ii_iface_type.Interfaces);
1107 if (Kind == MemberKind.Interface) {
1108 spec.BaseType = TypeManager.object_type;
1112 if (base_type != null) {
1113 spec.BaseType = base_type;
1115 // Set base type after type creation
1116 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1122 public virtual void DefineConstants ()
1124 if (constants != null) {
1125 foreach (Const c in constants) {
1130 if (instance_constructors != null) {
1131 foreach (MethodCore m in instance_constructors) {
1132 var p = m.ParameterInfo;
1133 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1134 var rc = new ResolveContext (m);
1135 p.ResolveDefaultValues (rc);
1140 if (methods != null) {
1141 foreach (MethodCore m in methods) {
1142 var p = m.ParameterInfo;
1143 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1144 var rc = new ResolveContext (m);
1145 p.ResolveDefaultValues (rc);
1150 if (indexers != null) {
1151 foreach (Indexer i in indexers) {
1152 var p = i.ParameterInfo;
1153 if (p[p.Count - 1].HasDefaultValue) {
1154 var rc = new ResolveContext (i);
1155 p.ResolveDefaultValues (rc);
1160 if (types != null) {
1161 foreach (var t in types)
1162 t.DefineConstants ();
1167 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1169 public TypeBuilder CreateType ()
1171 if (TypeBuilder != null)
1177 if (!CreateTypeBuilder ()) {
1182 if (partial_parts != null) {
1183 foreach (TypeContainer part in partial_parts) {
1185 part.current_type = current_type;
1186 part.TypeBuilder = TypeBuilder;
1190 if (Types != null) {
1191 foreach (TypeContainer tc in Types) {
1192 if (tc.CreateType () == null) {
1202 public override TypeBuilder DefineType ()
1209 type_defined = true;
1211 if (!DefineBaseTypes ()) {
1216 if (!DefineNestedTypes ()) {
1224 public override void SetParameterInfo (List<Constraints> constraints_list)
1226 base.SetParameterInfo (constraints_list);
1228 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1231 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1232 for (int i = 0; i < tc_names.Length; ++i) {
1233 if (tc_names [i].Name != type_params [i].Name) {
1234 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1235 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1236 GetSignatureForError ());
1240 if (tc_names [i].Variance != type_params [i].Variance) {
1241 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1242 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1243 GetSignatureForError ());
1250 // Replaces normal spec with predefined one when compiling corlib
1251 // and this type container defines predefined type
1253 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1258 void UpdateTypeParameterConstraints (TypeContainer part)
1260 TypeParameter[] current_params = type_params;
1261 for (int i = 0; i < current_params.Length; i++) {
1262 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1265 Report.SymbolRelatedToPreviousError (Location, "");
1266 Report.Error (265, part.Location,
1267 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1268 GetSignatureForError (), current_params [i].GetSignatureForError ());
1272 public bool ResolveTypeParameters ()
1274 if (!DoResolveTypeParameters ())
1277 if (types != null) {
1278 foreach (var type in types)
1279 if (!type.ResolveTypeParameters ())
1283 if (compiler_generated != null) {
1284 foreach (CompilerGeneratedClass c in compiler_generated)
1285 if (!c.ResolveTypeParameters ())
1292 protected virtual bool DoResolveTypeParameters ()
1294 if (CurrentTypeParameters == null)
1297 if (PartialContainer != this)
1298 throw new InternalErrorException ();
1300 var base_context = new BaseContext (this);
1301 foreach (TypeParameter type_param in CurrentTypeParameters) {
1302 if (!type_param.ResolveConstraints (base_context)) {
1308 if (partial_parts != null) {
1309 foreach (TypeContainer part in partial_parts)
1310 UpdateTypeParameterConstraints (part);
1316 protected virtual bool DefineNestedTypes ()
1318 if (Types != null) {
1319 foreach (TypeContainer tc in Types)
1320 if (tc.DefineType () == null)
1327 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1329 if (InTransit != null)
1334 if (base_type_expr != null) {
1335 var ptc = base_type.MemberDefinition as TypeContainer;
1336 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1340 if (iface_exprs != null) {
1341 foreach (TypeExpr iface in iface_exprs) {
1342 // the interface might not have been resolved, prevents a crash, see #442144
1345 var ptc = iface.Type.MemberDefinition as Interface;
1346 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1351 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1359 /// Populates our TypeBuilder with fields and methods
1361 public sealed override bool Define ()
1363 if (members_defined)
1364 return members_defined_ok;
1366 members_defined_ok = DoDefineMembers ();
1367 members_defined = true;
1369 if (types != null) {
1370 foreach (var nested in types)
1374 return members_defined_ok;
1377 protected virtual bool DoDefineMembers ()
1379 if (iface_exprs != null) {
1380 foreach (TypeExpr iface in iface_exprs) {
1381 var iface_type = iface.Type;
1383 // Ensure the base is always setup
1384 var compiled_iface = iface_type.MemberDefinition as Interface;
1385 if (compiled_iface != null)
1386 compiled_iface.Define ();
1388 if (Kind == MemberKind.Interface)
1389 MemberCache.AddInterface (iface_type);
1391 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1392 if (oa != null && !IsObsolete)
1393 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1395 GenericTypeExpr ct = iface as GenericTypeExpr;
1397 // TODO: passing `this' is wrong, should be base type iface instead
1398 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1400 ct.CheckConstraints (this);
1402 if (ct.HasDynamicArguments ()) {
1403 Report.Error (1966, iface.Location,
1404 "`{0}': cannot implement a dynamic interface `{1}'",
1405 GetSignatureForError (), iface.GetSignatureForError ());
1412 if (base_type_expr != null) {
1413 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1414 if (obsolete_attr != null && !IsObsolete)
1415 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1417 var ct = base_type_expr as GenericTypeExpr;
1419 ct.CheckConstraints (this);
1422 if (base_type != null) {
1423 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1424 if (baseContainer != null) {
1425 baseContainer.Define ();
1428 // It can trigger define of this type (for generic types only)
1430 if (HasMembersDefined)
1435 if (type_params != null) {
1436 foreach (var tp in type_params) {
1437 tp.CheckGenericConstraints ();
1442 MemberSpec candidate;
1443 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1444 if (conflict_symbol == null && candidate == null) {
1445 if ((ModFlags & Modifiers.NEW) != 0)
1446 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1447 GetSignatureForError ());
1449 if ((ModFlags & Modifiers.NEW) == 0) {
1450 if (candidate == null)
1451 candidate = conflict_symbol;
1453 Report.SymbolRelatedToPreviousError (candidate);
1454 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1455 GetSignatureForError (), candidate.GetSignatureForError ());
1460 DefineContainerMembers (constants);
1461 DefineContainerMembers (fields);
1463 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1464 pending = PendingImplementation.GetPendingImplementations (this);
1466 if (requires_delayed_unmanagedtype_check) {
1467 requires_delayed_unmanagedtype_check = false;
1468 foreach (FieldBase f in fields) {
1469 if (f.MemberType != null && f.MemberType.IsPointer)
1470 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1476 // Constructors are not in the defined_names array
1478 DefineContainerMembers (instance_constructors);
1480 DefineContainerMembers (events);
1481 DefineContainerMembers (ordered_explicit_member_list);
1482 DefineContainerMembers (ordered_member_list);
1484 if (operators != null) {
1485 DefineContainerMembers (operators);
1486 CheckPairedOperators ();
1489 ComputeIndexerName();
1490 CheckEqualsAndGetHashCode();
1495 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1498 for (int i = 0; i < mcal.Count; ++i) {
1499 MemberCore mc = (MemberCore) mcal[i];
1502 } catch (Exception e) {
1503 throw new InternalErrorException (mc, e);
1509 protected virtual void ComputeIndexerName ()
1511 if (indexers == null)
1514 string class_indexer_name = null;
1517 // If there's both an explicit and an implicit interface implementation, the
1518 // explicit one actually implements the interface while the other one is just
1519 // a normal indexer. See bug #37714.
1522 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1523 foreach (Indexer i in indexers) {
1524 if (i.InterfaceType != null) {
1525 if (seen_normal_indexers)
1526 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1530 seen_normal_indexers = true;
1532 if (class_indexer_name == null) {
1533 class_indexer_name = i.ShortName;
1537 if (i.ShortName != class_indexer_name)
1538 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");
1541 if (class_indexer_name != null)
1542 indexer_name = class_indexer_name;
1545 void EmitIndexerName ()
1547 if (!seen_normal_indexers)
1550 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1551 if (pa.Constructor == null &&
1552 !pa.ResolveConstructor (Location, TypeManager.string_type))
1555 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1556 TypeBuilder.SetCustomAttribute (cb);
1559 protected virtual void CheckEqualsAndGetHashCode ()
1561 if (methods == null)
1564 if (HasEquals && !HasGetHashCode) {
1565 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1569 // Indicated whether container has StructLayout attribute set Explicit
1570 public bool HasExplicitLayout {
1571 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1572 set { caching_flags |= Flags.HasExplicitLayout; }
1575 public bool HasStructLayout {
1576 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1577 set { caching_flags |= Flags.HasStructLayout; }
1580 public MemberCache MemberCache {
1582 return spec.MemberCache;
1586 void CheckMemberUsage (List<MemberCore> al, string member_type)
1591 foreach (MemberCore mc in al) {
1592 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1595 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1596 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1601 public virtual void VerifyMembers ()
1604 // Check for internal or private fields that were never assigned
1606 if (Report.WarningLevel >= 3) {
1607 if (RootContext.EnhancedWarnings) {
1608 CheckMemberUsage (properties, "property");
1609 CheckMemberUsage (methods, "method");
1610 CheckMemberUsage (constants, "constant");
1613 if (fields != null){
1614 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1615 foreach (FieldBase f in fields) {
1616 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1617 if (is_type_exposed)
1624 if ((f.caching_flags & Flags.IsAssigned) == 0)
1625 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1627 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1628 f.GetSignatureForError ());
1634 // Only report 649 on level 4
1636 if (Report.WarningLevel < 4)
1639 if ((f.caching_flags & Flags.IsAssigned) != 0)
1643 // Don't be pendatic over serializable attributes
1645 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1648 Constant c = New.Constantify (f.MemberType);
1649 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1650 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1656 public override void Emit ()
1658 if (all_tp_builders != null) {
1659 int current_starts_index = CurrentTypeParametersStartIndex;
1660 for (int i = 0; i < all_tp_builders.Length; i++) {
1661 if (i < current_starts_index) {
1662 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1664 CurrentTypeParameters [i - current_starts_index].Emit ();
1669 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1670 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1675 // TODO: move to ClassOrStruct
1676 void EmitConstructors ()
1678 if (instance_constructors == null)
1681 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1682 bool has_compliant_args = false;
1684 foreach (Constructor c in instance_constructors) {
1688 catch (Exception e) {
1689 throw new InternalErrorException (c, e);
1692 if (has_compliant_args)
1695 has_compliant_args = c.HasCompliantArgs;
1697 if (!has_compliant_args)
1698 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1700 foreach (Constructor c in instance_constructors) {
1704 catch (Exception e) {
1705 throw new InternalErrorException (c, e);
1712 /// Emits the code, this step is performed after all
1713 /// the types, enumerations, constructors
1715 public virtual void EmitType ()
1717 if (OptAttributes != null)
1718 OptAttributes.Emit ();
1722 EmitConstructors ();
1724 if (constants != null)
1725 foreach (Const con in constants)
1728 if (default_static_constructor != null)
1729 default_static_constructor.Emit ();
1731 if (operators != null)
1732 foreach (Operator o in operators)
1735 if (properties != null)
1736 foreach (Property p in properties)
1739 if (indexers != null) {
1740 foreach (Indexer indx in indexers)
1745 if (events != null){
1746 foreach (Event e in Events)
1750 if (methods != null) {
1751 for (int i = 0; i < methods.Count; ++i)
1752 ((MethodOrOperator) methods [i]).Emit ();
1756 foreach (FieldBase f in fields)
1759 if (types != null) {
1760 foreach (TypeContainer t in types)
1764 if (pending != null)
1765 pending.VerifyPendingMethods (Report);
1767 if (Report.Errors > 0)
1770 if (compiler_generated != null) {
1771 for (int i = 0; i < compiler_generated.Count; ++i)
1772 compiler_generated [i].EmitType ();
1776 public void CloseType ()
1778 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1781 // Close base type container first to avoid TypeLoadException
1782 if (spec.BaseType != null) {
1783 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1789 caching_flags |= Flags.CloseTypeCreated;
1790 TypeBuilder.CreateType ();
1791 } catch (TypeLoadException){
1793 // This is fine, the code still created the type
1795 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1796 // Console.WriteLine (e.Message);
1797 } catch (Exception e) {
1798 throw new InternalErrorException (this, e);
1802 foreach (TypeContainer tc in Types)
1806 if (compiler_generated != null)
1807 foreach (CompilerGeneratedClass c in compiler_generated)
1812 initialized_fields = null;
1813 initialized_static_fields = null;
1815 ordered_explicit_member_list = null;
1816 ordered_member_list = null;
1821 compiler_generated = null;
1822 default_constructor = null;
1823 default_static_constructor = null;
1825 OptAttributes = null;
1829 // Performs the validation on a Method's modifiers (properties have
1830 // the same properties).
1832 // TODO: Why is it not done at parse stage ?
1834 public bool MethodModifiersValid (MemberCore mc)
1836 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1837 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1838 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1840 var flags = mc.ModFlags;
1843 // At most one of static, virtual or override
1845 if ((flags & Modifiers.STATIC) != 0){
1846 if ((flags & vao) != 0){
1847 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1848 mc.GetSignatureForError ());
1853 if (Kind == MemberKind.Struct){
1854 if ((flags & va) != 0){
1855 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1860 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1861 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1862 mc.GetSignatureForError ());
1867 // If the declaration includes the abstract modifier, then the
1868 // declaration does not include static, virtual or extern
1870 if ((flags & Modifiers.ABSTRACT) != 0){
1871 if ((flags & Modifiers.EXTERN) != 0){
1873 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1877 if ((flags & Modifiers.SEALED) != 0) {
1878 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1882 if ((flags & Modifiers.VIRTUAL) != 0){
1883 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1887 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1888 Report.SymbolRelatedToPreviousError (this);
1889 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1890 mc.GetSignatureForError (), GetSignatureForError ());
1895 if ((flags & Modifiers.PRIVATE) != 0){
1896 if ((flags & vao) != 0){
1897 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1902 if ((flags & Modifiers.SEALED) != 0){
1903 if ((flags & Modifiers.OVERRIDE) == 0){
1904 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1912 public Constructor DefaultStaticConstructor {
1913 get { return default_static_constructor; }
1916 protected override bool VerifyClsCompliance ()
1918 if (!base.VerifyClsCompliance ())
1921 // Check this name against other containers
1922 NamespaceEntry.NS.VerifyClsCompliance ();
1924 // Check all container names for user classes
1925 if (Kind != MemberKind.Delegate)
1926 MemberCache.VerifyClsCompliance (Definition, Report);
1928 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1929 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1930 GetSignatureForError (), BaseType.GetSignatureForError ());
1936 /// Performs checks for an explicit interface implementation. First it
1937 /// checks whether the `interface_type' is a base inteface implementation.
1938 /// Then it checks whether `name' exists in the interface type.
1940 public bool VerifyImplements (InterfaceMemberBase mb)
1942 var ifaces = spec.Interfaces;
1943 if (ifaces != null) {
1944 foreach (TypeSpec t in ifaces){
1945 if (TypeManager.IsEqual (t, mb.InterfaceType))
1950 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1951 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1952 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1957 // Used for visiblity checks to tests whether this definition shares
1958 // base type baseType, it does member-definition search
1960 public bool IsBaseTypeDefinition (TypeSpec baseType)
1962 // RootContext check
1963 if (TypeBuilder == null)
1968 if (type.MemberDefinition == baseType.MemberDefinition)
1971 type = type.BaseType;
1972 } while (type != null);
1977 public MemberCache LoadMembers (TypeSpec declaringType)
1979 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1982 public void Mark_HasEquals ()
1984 cached_method |= CachedMethods.Equals;
1987 public void Mark_HasGetHashCode ()
1989 cached_method |= CachedMethods.GetHashCode;
1993 /// Method container contains Equals method
1995 public bool HasEquals {
1997 return (cached_method & CachedMethods.Equals) != 0;
2002 /// Method container contains GetHashCode method
2004 public bool HasGetHashCode {
2006 return (cached_method & CachedMethods.GetHashCode) != 0;
2010 public bool HasStaticFieldInitializer {
2012 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2016 cached_method |= CachedMethods.HasStaticFieldInitializer;
2018 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2023 // Generates xml doc comments (if any), and if required,
2024 // handle warning report.
2026 internal override void GenerateDocComment (DeclSpace ds)
2028 DocUtil.GenerateTypeDocComment (this, ds, Report);
2031 public override string DocCommentHeader {
2032 get { return "T:"; }
2036 public abstract class ClassOrStruct : TypeContainer
2038 Dictionary<SecurityAction, PermissionSet> declarative_security;
2040 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2041 MemberName name, Attributes attrs, MemberKind kind)
2042 : base (ns, parent, name, attrs, kind)
2046 protected override bool AddToContainer (MemberCore symbol, string name)
2048 if (name == MemberName.Name) {
2049 if (symbol is TypeParameter) {
2050 Report.Error (694, symbol.Location,
2051 "Type parameter `{0}' has same name as containing type, or method",
2052 symbol.GetSignatureForError ());
2056 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2057 if (imb == null || !imb.IsExplicitImpl) {
2058 Report.SymbolRelatedToPreviousError (this);
2059 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2060 symbol.GetSignatureForError ());
2065 return base.AddToContainer (symbol, name);
2068 public override void VerifyMembers ()
2070 base.VerifyMembers ();
2072 if ((events != null) && Report.WarningLevel >= 3) {
2073 foreach (Event e in events){
2074 // Note: The event can be assigned from same class only, so we can report
2075 // this warning for all accessibility modes
2076 if ((e.caching_flags & Flags.IsUsed) == 0)
2077 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2082 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2084 if (a.IsValidSecurityAttribute ()) {
2085 if (declarative_security == null)
2086 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2088 a.ExtractSecurityPermissionSet (declarative_security);
2092 if (a.Type == pa.StructLayout) {
2093 PartialContainer.HasStructLayout = true;
2095 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2096 PartialContainer.HasExplicitLayout = true;
2099 if (a.Type == pa.Dynamic) {
2100 a.Error_MisusedDynamicAttribute ();
2104 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2108 /// Defines the default constructors
2110 protected void DefineDefaultConstructor (bool is_static)
2112 // The default instance constructor is public
2113 // If the class is abstract, the default constructor is protected
2114 // The default static constructor is private
2118 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2120 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2123 Constructor c = new Constructor (this, MemberName.Name, mods,
2124 null, ParametersCompiled.EmptyReadOnlyParameters,
2125 new GeneratedBaseInitializer (Location),
2129 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2132 protected override bool DoDefineMembers ()
2134 CheckProtectedModifier ();
2136 base.DoDefineMembers ();
2138 if (default_static_constructor != null)
2139 default_static_constructor.Define ();
2144 public override void Emit ()
2146 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2147 DefineDefaultConstructor (true);
2148 default_static_constructor.Define ();
2153 if (declarative_security != null) {
2154 foreach (var de in declarative_security) {
2155 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2160 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2162 DeclSpace top_level = Parent;
2163 if (top_level != null) {
2164 while (top_level.Parent != null)
2165 top_level = top_level.Parent;
2167 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2168 if (candidates != null)
2169 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2172 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2175 protected override TypeAttributes TypeAttr {
2177 if (default_static_constructor == null)
2178 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2180 return base.TypeAttr;
2186 // TODO: should be sealed
2187 public class Class : ClassOrStruct {
2188 const Modifiers AllowedModifiers =
2191 Modifiers.PROTECTED |
2192 Modifiers.INTERNAL |
2194 Modifiers.ABSTRACT |
2199 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2201 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2203 : base (ns, parent, name, attrs, MemberKind.Class)
2205 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2206 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2207 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2209 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2210 Report.FeatureIsNotAvailable (Location, "static classes");
2214 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2216 if (part.Name == "System.Object")
2217 Report.Error (537, part.Location,
2218 "The class System.Object cannot have a base class or implement an interface.");
2219 base.AddBasesForPart (part, bases);
2222 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2224 if (a.Type == pa.AttributeUsage) {
2225 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2226 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2230 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2231 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2235 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2236 a.Error_MissingGuidAttribute ();
2240 if (a.Type == pa.Extension) {
2241 a.Error_MisusedExtensionAttribute ();
2245 if (a.Type.IsConditionallyExcluded (Location))
2248 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2251 public override AttributeTargets AttributeTargets {
2253 return AttributeTargets.Class;
2257 protected override void DefineContainerMembers (System.Collections.IList list)
2263 base.DefineContainerMembers (list);
2267 foreach (MemberCore m in list) {
2268 if (m is Operator) {
2269 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2273 if (m is Destructor) {
2274 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2279 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2283 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2286 if (m is Constructor) {
2287 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2291 Method method = m as Method;
2292 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2293 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2297 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2300 base.DefineContainerMembers (list);
2303 protected override bool DoDefineMembers ()
2305 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2306 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2309 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2310 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2313 if (InstanceConstructors == null && !IsStatic)
2314 DefineDefaultConstructor (false);
2316 return base.DoDefineMembers ();
2319 public override void Emit ()
2323 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2324 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2326 var trans_flags = TypeManager.HasDynamicTypeUsed (base_type);
2327 if (trans_flags != null) {
2328 var pa = PredefinedAttributes.Get.DynamicTransform;
2329 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
2330 TypeBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
2335 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2337 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2339 if (base_class == null) {
2340 if (spec != TypeManager.object_type)
2341 base_type = TypeManager.object_type;
2343 if (base_type.IsGenericParameter){
2344 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2345 GetSignatureForError (), base_type.GetSignatureForError ());
2346 } else if (IsGeneric && base_type.IsAttribute) {
2347 Report.Error (698, base_class.Location,
2348 "A generic type cannot derive from `{0}' because it is an attribute class",
2349 base_class.GetSignatureForError ());
2350 } else if (base_type.IsStatic) {
2351 Report.SymbolRelatedToPreviousError (base_class.Type);
2352 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2353 GetSignatureForError (), base_type.GetSignatureForError ());
2354 } else if (base_type.IsSealed) {
2355 Report.SymbolRelatedToPreviousError (base_class.Type);
2356 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2357 GetSignatureForError (), base_type.GetSignatureForError ());
2358 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2359 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2360 GetSignatureForError (), base_class.GetSignatureForError ());
2363 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2364 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2365 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2366 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2367 GetSignatureForError (), base_type.GetSignatureForError ());
2369 base_type = TypeManager.object_type;
2372 if (!IsAccessibleAs (base_type)) {
2373 Report.SymbolRelatedToPreviousError (base_type);
2374 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2375 base_type.GetSignatureForError (), GetSignatureForError ());
2379 if (PartialContainer.IsStatic && ifaces != null) {
2380 foreach (TypeExpr t in ifaces)
2381 Report.SymbolRelatedToPreviousError (t.Type);
2382 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2388 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2389 /// Valid only for attribute classes.
2390 public override string[] ConditionalConditions ()
2392 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2395 caching_flags &= ~Flags.Excluded_Undetected;
2397 if (OptAttributes == null)
2400 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2404 string[] conditions = new string[attrs.Length];
2405 for (int i = 0; i < conditions.Length; ++i)
2406 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2408 caching_flags |= Flags.Excluded;
2413 // FIXME: How do we deal with the user specifying a different
2416 protected override TypeAttributes TypeAttr {
2418 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2420 ta |= StaticClassAttribute;
2426 public sealed class Struct : ClassOrStruct {
2428 bool is_unmanaged, has_unmanaged_check_done;
2432 // Modifiers allowed in a struct declaration
2434 const Modifiers AllowedModifiers =
2437 Modifiers.PROTECTED |
2438 Modifiers.INTERNAL |
2442 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2443 Modifiers mod, Attributes attrs)
2444 : base (ns, parent, name, attrs, MemberKind.Struct)
2446 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2447 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2448 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2451 public override AttributeTargets AttributeTargets {
2453 return AttributeTargets.Struct;
2457 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2459 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2462 // When struct constains fixed fixed and struct layout has explicitly
2463 // set CharSet, its value has to be propagated to compiler generated
2464 // fixed field types
2466 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2467 for (int i = 0; i < Fields.Count; ++i) {
2468 FixedField ff = Fields [i] as FixedField;
2470 ff.SetCharSet (TypeBuilder.Attributes);
2475 bool CheckStructCycles (Struct s)
2477 if (s.Fields == null)
2484 foreach (FieldBase field in s.Fields) {
2485 TypeSpec ftype = field.Spec.MemberType;
2486 if (!ftype.IsStruct)
2489 if (ftype is PredefinedTypeSpec)
2492 foreach (var targ in ftype.TypeArguments) {
2493 if (!CheckFieldTypeCycle (targ)) {
2494 Report.Error (523, field.Location,
2495 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2496 field.GetSignatureForError (), ftype.GetSignatureForError ());
2501 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2504 if (!CheckFieldTypeCycle (ftype)) {
2505 Report.Error (523, field.Location,
2506 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2507 field.GetSignatureForError (), ftype.GetSignatureForError ());
2512 s.InTransit = false;
2516 bool CheckFieldTypeCycle (TypeSpec ts)
2518 var fts = ts.MemberDefinition as Struct;
2522 return CheckStructCycles (fts);
2525 public override void Emit ()
2527 CheckStructCycles (this);
2532 public override bool IsUnmanagedType ()
2537 if (has_unmanaged_check_done)
2538 return is_unmanaged;
2540 if (requires_delayed_unmanagedtype_check)
2543 requires_delayed_unmanagedtype_check = true;
2545 foreach (FieldBase f in fields) {
2549 // It can happen when recursive unmanaged types are defined
2550 // struct S { S* s; }
2551 TypeSpec mt = f.MemberType;
2556 while (mt.IsPointer)
2557 mt = TypeManager.GetElementType (mt);
2559 if (mt.MemberDefinition == this) {
2560 for (var p = Parent; p != null; p = p.Parent) {
2561 if (p.Kind == MemberKind.Class) {
2562 has_unmanaged_check_done = true;
2569 if (TypeManager.IsUnmanagedType (mt))
2572 has_unmanaged_check_done = true;
2576 has_unmanaged_check_done = true;
2577 is_unmanaged = true;
2581 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2583 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2584 base_type = TypeManager.value_type;
2588 protected override TypeAttributes TypeAttr {
2590 const TypeAttributes DefaultTypeAttributes =
2591 TypeAttributes.SequentialLayout |
2592 TypeAttributes.Sealed;
2594 return base.TypeAttr | DefaultTypeAttributes;
2598 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2600 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2601 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2602 field.GetSignatureForError ());
2605 base.RegisterFieldForInitialization (field, expression);
2613 public sealed class Interface : TypeContainer {
2616 /// Modifiers allowed in a class declaration
2618 public const Modifiers AllowedModifiers =
2621 Modifiers.PROTECTED |
2622 Modifiers.INTERNAL |
2626 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2628 : base (ns, parent, name, attrs, MemberKind.Interface)
2630 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2632 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2633 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2636 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2638 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2639 a.Error_MissingGuidAttribute ();
2643 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2647 public override AttributeTargets AttributeTargets {
2649 return AttributeTargets.Interface;
2653 protected override TypeAttributes TypeAttr {
2655 const TypeAttributes DefaultTypeAttributes =
2656 TypeAttributes.AutoLayout |
2657 TypeAttributes.Abstract |
2658 TypeAttributes.Interface;
2660 return base.TypeAttr | DefaultTypeAttributes;
2664 protected override bool VerifyClsCompliance ()
2666 if (!base.VerifyClsCompliance ())
2669 if (iface_exprs != null) {
2670 foreach (var iface in iface_exprs) {
2671 if (iface.Type.IsCLSCompliant ())
2674 Report.SymbolRelatedToPreviousError (iface.Type);
2675 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2676 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2684 public abstract class InterfaceMemberBase : MemberBase {
2686 // Whether this is an interface member.
2688 public bool IsInterface;
2691 // If true, this is an explicit interface implementation
2693 public bool IsExplicitImpl;
2695 protected bool is_external_implementation;
2698 // The interface type we are explicitly implementing
2700 public TypeSpec InterfaceType;
2703 // The method we're overriding if this is an override method.
2705 protected MethodSpec base_method;
2707 readonly Modifiers explicit_mod_flags;
2708 public MethodAttributes flags;
2710 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2711 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2712 MemberName name, Attributes attrs)
2713 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2716 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2717 IsExplicitImpl = (MemberName.Left != null);
2718 explicit_mod_flags = mod;
2721 protected override bool CheckBase ()
2723 if (!base.CheckBase ())
2726 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2727 CheckForDuplications ();
2732 // For System.Object only
2733 if (Parent.BaseType == null)
2736 MemberSpec candidate;
2737 var base_member = FindBaseMember (out candidate);
2739 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2740 if (base_member == null) {
2741 if (candidate == null) {
2742 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2743 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2744 "object.Finalize()");
2746 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2747 GetSignatureForError (), SimpleName.GetMemberType (this));
2750 Report.SymbolRelatedToPreviousError (candidate);
2752 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2753 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2754 else if (this is PropertyBase)
2755 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2756 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2758 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2759 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2765 if (!CheckOverrideAgainstBase (base_member))
2768 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2770 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2771 Report.SymbolRelatedToPreviousError (base_member);
2772 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2773 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2776 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2777 Report.SymbolRelatedToPreviousError (base_member);
2778 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2779 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2783 base_method = base_member as MethodSpec;
2787 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2788 base_member = candidate;
2790 if (base_member == null) {
2791 if ((ModFlags & Modifiers.NEW) != 0) {
2792 if (base_member == null) {
2793 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2794 GetSignatureForError ());
2798 if ((ModFlags & Modifiers.NEW) == 0) {
2799 ModFlags |= Modifiers.NEW;
2800 Report.SymbolRelatedToPreviousError (base_member);
2801 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2802 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",
2803 GetSignatureForError (), base_member.GetSignatureForError ());
2805 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2806 GetSignatureForError (), base_member.GetSignatureForError ());
2810 if (!IsInterface && base_member.IsAbstract) {
2811 Report.SymbolRelatedToPreviousError (base_member);
2812 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2813 GetSignatureForError (), base_member.GetSignatureForError ());
2820 protected virtual bool CheckForDuplications ()
2822 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2826 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2827 // that have been defined.
2829 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2833 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2834 Report.SymbolRelatedToPreviousError (base_member);
2835 Report.Error (506, Location,
2836 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2837 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2841 // Now we check that the overriden method is not final
2842 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2843 Report.SymbolRelatedToPreviousError (base_member);
2844 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2845 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2849 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2850 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2851 Report.SymbolRelatedToPreviousError (base_member);
2852 if (this is PropertyBasedMember) {
2853 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2854 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2856 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2857 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2865 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2867 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2868 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2870 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2872 // when overriding protected internal, the method can be declared
2873 // protected internal only within the same assembly or assembly
2874 // which has InternalsVisibleTo
2876 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2877 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2879 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2881 // if it's not "protected internal", it must be "protected"
2886 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2888 // protected within the same assembly - an error
2892 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2893 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2895 // protected ok, but other attributes differ - report an error
2902 return thisp == base_classp;
2905 public override bool Define ()
2908 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2909 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2911 flags = MethodAttributes.Public |
2912 MethodAttributes.Abstract |
2913 MethodAttributes.HideBySig |
2914 MethodAttributes.NewSlot |
2915 MethodAttributes.Virtual;
2917 Parent.PartialContainer.MethodModifiersValid (this);
2919 flags = ModifiersExtensions.MethodAttr (ModFlags);
2922 if (IsExplicitImpl) {
2923 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2924 if (iface_texpr == null)
2927 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2928 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2929 GetSignatureForError ());
2932 InterfaceType = iface_texpr.Type;
2934 if (!InterfaceType.IsInterface) {
2935 Report.SymbolRelatedToPreviousError (InterfaceType);
2936 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2937 TypeManager.CSharpName (InterfaceType));
2939 Parent.PartialContainer.VerifyImplements (this);
2942 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2945 return base.Define ();
2948 protected bool DefineParameters (ParametersCompiled parameters)
2950 if (!parameters.Resolve (this))
2954 for (int i = 0; i < parameters.Count; ++i) {
2955 Parameter p = parameters [i];
2957 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2958 p.Warning_UselessOptionalParameter (Report);
2960 if (p.CheckAccessibility (this))
2963 TypeSpec t = parameters.Types [i];
2964 Report.SymbolRelatedToPreviousError (t);
2965 if (this is Indexer)
2966 Report.Error (55, Location,
2967 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2968 TypeManager.CSharpName (t), GetSignatureForError ());
2969 else if (this is Operator)
2970 Report.Error (57, Location,
2971 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2972 TypeManager.CSharpName (t), GetSignatureForError ());
2974 Report.Error (51, Location,
2975 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2976 TypeManager.CSharpName (t), GetSignatureForError ());
2982 public override void Emit()
2984 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2985 // We are more strict than csc and report this as an error because SRE does not allow emit that
2986 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2987 if (this is Constructor) {
2988 Report.Error (824, Location,
2989 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
2991 Report.Error (626, Location,
2992 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
2993 GetSignatureForError ());
3000 public override bool EnableOverloadChecks (MemberCore overload)
3003 // Two members can differ in their explicit interface
3004 // type parameter only
3006 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3007 if (imb != null && imb.IsExplicitImpl) {
3008 if (IsExplicitImpl) {
3009 caching_flags |= Flags.MethodOverloadsExist;
3014 return IsExplicitImpl;
3017 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3019 Report.SymbolRelatedToPreviousError (base_member);
3020 Report.Error (507, member.Location,
3021 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3022 member.GetSignatureForError (),
3023 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3024 base_member.GetSignatureForError ());
3027 protected void Error_StaticReturnType ()
3029 Report.Error (722, Location,
3030 "`{0}': static types cannot be used as return types",
3031 MemberType.GetSignatureForError ());
3035 /// Gets base method and its return type
3037 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3039 return MemberCache.FindBaseMember (this, out bestCandidate);
3043 // The "short" name of this property / indexer / event. This is the
3044 // name without the explicit interface.
3046 public string ShortName {
3047 get { return MemberName.Name; }
3048 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3052 // Returns full metadata method name
3054 public string GetFullName (MemberName name)
3056 return GetFullName (name.Name);
3059 public string GetFullName (string name)
3061 if (!IsExplicitImpl)
3065 // When dealing with explicit members a full interface type
3066 // name is added to member name to avoid possible name conflicts
3068 // We use CSharpName which gets us full name with benefit of
3069 // replacing predefined names which saves some space and name
3072 return TypeManager.CSharpName (InterfaceType) + "." + name;
3075 protected override bool VerifyClsCompliance ()
3077 if (!base.VerifyClsCompliance ()) {
3081 if (GenericMethod != null)
3082 GenericMethod.VerifyClsCompliance ();
3087 public override bool IsUsed
3089 get { return IsExplicitImpl || base.IsUsed; }
3094 public abstract class MemberBase : MemberCore
3096 protected FullNamedExpression type_expr;
3097 protected TypeSpec member_type;
3099 public readonly DeclSpace ds;
3100 public readonly GenericMethod GenericMethod;
3102 protected MemberBase (DeclSpace parent, GenericMethod generic,
3103 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3104 MemberName name, Attributes attrs)
3105 : base (parent, name, attrs)
3107 this.ds = generic != null ? generic : (DeclSpace) parent;
3108 this.type_expr = type;
3109 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3110 GenericMethod = generic;
3111 if (GenericMethod != null)
3112 GenericMethod.ModFlags = ModFlags;
3117 public TypeSpec MemberType {
3123 public FullNamedExpression TypeExpression {
3132 // Main member define entry
3134 public override bool Define ()
3136 DoMemberTypeIndependentChecks ();
3139 // Returns false only when type resolution failed
3141 if (!ResolveMemberType ())
3144 DoMemberTypeDependentChecks ();
3149 // Any type_name independent checks
3151 protected virtual void DoMemberTypeIndependentChecks ()
3153 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3154 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3155 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3156 GetSignatureForError (), Parent.GetSignatureForError ());
3161 // Any type_name dependent checks
3163 protected virtual void DoMemberTypeDependentChecks ()
3165 // verify accessibility
3166 if (!IsAccessibleAs (MemberType)) {
3167 Report.SymbolRelatedToPreviousError (MemberType);
3168 if (this is Property)
3169 Report.Error (53, Location,
3170 "Inconsistent accessibility: property type `" +
3171 TypeManager.CSharpName (MemberType) + "' is less " +
3172 "accessible than property `" + GetSignatureForError () + "'");
3173 else if (this is Indexer)
3174 Report.Error (54, Location,
3175 "Inconsistent accessibility: indexer return type `" +
3176 TypeManager.CSharpName (MemberType) + "' is less " +
3177 "accessible than indexer `" + GetSignatureForError () + "'");
3178 else if (this is MethodCore) {
3179 if (this is Operator)
3180 Report.Error (56, Location,
3181 "Inconsistent accessibility: return type `" +
3182 TypeManager.CSharpName (MemberType) + "' is less " +
3183 "accessible than operator `" + GetSignatureForError () + "'");
3185 Report.Error (50, Location,
3186 "Inconsistent accessibility: return type `" +
3187 TypeManager.CSharpName (MemberType) + "' is less " +
3188 "accessible than method `" + GetSignatureForError () + "'");
3190 Report.Error (52, Location,
3191 "Inconsistent accessibility: field type `" +
3192 TypeManager.CSharpName (MemberType) + "' is less " +
3193 "accessible than field `" + GetSignatureForError () + "'");
3197 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3198 TypeManager.CheckTypeVariance (MemberType, variance, this);
3201 protected bool IsTypePermitted ()
3203 if (TypeManager.IsSpecialType (MemberType)) {
3204 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3210 protected virtual bool CheckBase ()
3212 CheckProtectedModifier ();
3217 protected virtual bool ResolveMemberType ()
3219 if (member_type != null)
3220 throw new InternalErrorException ("Multi-resolve");
3222 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3227 // Replace original type name, error reporting can use fully resolved name
3231 member_type = te.Type;