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 protected virtual bool AddMemberType (TypeContainer ds)
291 return AddToContainer (ds, ds.Basename);
294 protected virtual void RemoveMemberType (DeclSpace ds)
296 RemoveFromContainer (ds.Basename);
299 public void AddConstant (Const constant)
301 if (!AddMember (constant))
304 if (constants == null)
305 constants = new List<MemberCore> ();
307 constants.Add (constant);
310 public TypeContainer AddTypeContainer (TypeContainer tc)
312 if (!AddMemberType (tc))
316 types = new List<TypeContainer> ();
322 public virtual TypeContainer AddPartial (TypeContainer next_part)
324 return AddPartial (next_part, next_part.Basename);
327 protected TypeContainer AddPartial (TypeContainer next_part, string name)
329 next_part.ModFlags |= Modifiers.PARTIAL;
330 TypeContainer tc = GetDefinition (name) as TypeContainer;
332 return AddTypeContainer (next_part);
334 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
335 Report.SymbolRelatedToPreviousError (next_part);
336 Error_MissingPartialModifier (tc);
339 if (tc.Kind != next_part.Kind) {
340 Report.SymbolRelatedToPreviousError (tc);
341 Report.Error (261, next_part.Location,
342 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
343 next_part.GetSignatureForError ());
346 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
347 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
348 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
349 Report.SymbolRelatedToPreviousError (tc);
350 Report.Error (262, next_part.Location,
351 "Partial declarations of `{0}' have conflicting accessibility modifiers",
352 next_part.GetSignatureForError ());
355 if (tc.partial_parts == null)
356 tc.partial_parts = new List<TypeContainer> (1);
358 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
359 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
360 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
361 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
362 tc.ModFlags |= next_part.ModFlags;
364 tc.ModFlags |= next_part.ModFlags;
367 tc.spec.Modifiers = tc.ModFlags;
369 if (next_part.attributes != null) {
370 if (tc.attributes == null)
371 tc.attributes = next_part.attributes;
373 tc.attributes.AddAttributes (next_part.attributes.Attrs);
376 next_part.PartialContainer = tc;
377 tc.partial_parts.Add (next_part);
381 public virtual void RemoveTypeContainer (TypeContainer next_part)
384 types.Remove (next_part);
385 RemoveMemberType (next_part);
388 public void AddDelegate (Delegate d)
390 AddTypeContainer (d);
393 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
395 if (ordered_explicit_member_list == null) {
396 ordered_explicit_member_list = new List<MemberCore> ();
397 ordered_member_list = new List<MemberCore> ();
401 if (Kind == MemberKind.Interface) {
402 Report.Error (541, mc.Location,
403 "`{0}': explicit interface declaration can only be declared in a class or struct",
404 mc.GetSignatureForError ());
407 ordered_explicit_member_list.Add (mc);
408 alist.Insert (0, mc);
410 ordered_member_list.Add (mc);
416 public void AddMethod (MethodOrOperator method)
418 if (!AddToContainer (method, method.MemberName.Basename))
422 methods = new List<MemberCore> ();
424 if (method.MemberName.Left != null)
425 AddMemberToList (method, methods, true);
427 AddMemberToList (method, methods, false);
430 public void AddConstructor (Constructor c)
432 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
433 if (!AddToContainer (c, is_static ?
434 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
437 if (is_static && c.ParameterInfo.IsEmpty){
438 if (default_static_constructor != null) {
439 Report.SymbolRelatedToPreviousError (default_static_constructor);
440 Report.Error (111, c.Location,
441 "A member `{0}' is already defined. Rename this member or use different parameter types",
442 c.GetSignatureForError ());
446 default_static_constructor = c;
448 if (c.ParameterInfo.IsEmpty)
449 default_constructor = c;
451 if (instance_constructors == null)
452 instance_constructors = new List<Constructor> ();
454 instance_constructors.Add (c);
458 public bool AddField (FieldBase field)
460 if (!AddMember (field))
464 fields = new List<FieldBase> ();
468 if ((field.ModFlags & Modifiers.STATIC) != 0)
471 if (first_nonstatic_field == null) {
472 first_nonstatic_field = field;
476 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
477 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
478 Report.Warning (282, 3, field.Location,
479 "struct instance field `{0}' found in different declaration from instance field `{1}'",
480 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
485 public void AddProperty (Property prop)
487 if (!AddMember (prop))
490 if (properties == null)
491 properties = new List<MemberCore> ();
493 if (prop.MemberName.Left != null)
494 AddMemberToList (prop, properties, true);
496 AddMemberToList (prop, properties, false);
499 public void AddEvent (Event e)
505 events = new List<MemberCore> ();
511 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
513 public void AddIndexer (Indexer i)
515 if (indexers == null)
516 indexers = new List<MemberCore> ();
518 if (i.IsExplicitImpl)
519 AddMemberToList (i, indexers, true);
521 AddMemberToList (i, indexers, false);
524 public void AddOperator (Operator op)
529 if (operators == null)
530 operators = new List<MemberCore> ();
535 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
537 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
539 if (compiler_generated == null)
540 compiler_generated = new List<CompilerGeneratedClass> ();
542 compiler_generated.Add (c);
545 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
547 if (a.Type == pa.DefaultMember) {
548 if (Indexers != null) {
549 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
554 if (a.Type == pa.Required) {
555 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
559 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
562 public override AttributeTargets AttributeTargets {
564 throw new NotSupportedException ();
568 public IList<TypeContainer> Types {
574 public IList<MemberCore> Methods {
580 public IList<MemberCore> Constants {
586 public TypeSpec BaseType {
588 return spec.BaseType;
592 public IList<FieldBase> Fields {
598 public IList<Constructor> InstanceConstructors {
600 return instance_constructors;
604 public IList<MemberCore> Properties {
610 public IList<MemberCore> Events {
616 public IList<MemberCore> Indexers {
622 public IList<MemberCore> Operators {
628 public IList<CompilerGeneratedClass> CompilerGeneratedClasses {
630 return compiler_generated;
634 protected override TypeAttributes TypeAttr {
636 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
640 public int TypeParametersCount {
642 return MemberName.Arity;
646 TypeParameterSpec[] ITypeDefinition.TypeParameters {
648 // TODO MemberCache: this is going to hurt
649 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
653 public string GetAttributeDefaultMember ()
655 return indexers == null ? DefaultIndexerName : indexer_name;
658 public bool IsComImport {
660 if (OptAttributes == null)
663 return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
667 string ITypeDefinition.Namespace {
669 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
673 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
675 if ((field.ModFlags & Modifiers.STATIC) != 0){
676 if (initialized_static_fields == null) {
677 PartialContainer.HasStaticFieldInitializer = true;
678 initialized_static_fields = new List<FieldInitializer> (4);
681 initialized_static_fields.Add (expression);
683 if (initialized_fields == null)
684 initialized_fields = new List<FieldInitializer> (4);
686 initialized_fields.Add (expression);
690 public void ResolveFieldInitializers (BlockContext ec)
692 if (partial_parts != null) {
693 foreach (TypeContainer part in partial_parts) {
694 part.DoResolveFieldInitializers (ec);
697 DoResolveFieldInitializers (ec);
700 void DoResolveFieldInitializers (BlockContext ec)
703 if (initialized_static_fields == null)
706 bool has_complex_initializer = !RootContext.Optimize;
708 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
709 for (i = 0; i < initialized_static_fields.Count; ++i) {
710 FieldInitializer fi = initialized_static_fields [i];
711 ExpressionStatement s = fi.ResolveStatement (ec);
713 s = EmptyExpressionStatement.Instance;
714 } else if (fi.IsComplexInitializer) {
715 has_complex_initializer |= true;
721 for (i = 0; i < initialized_static_fields.Count; ++i) {
722 FieldInitializer fi = initialized_static_fields [i];
724 // Need special check to not optimize code like this
725 // static int a = b = 5;
728 if (!has_complex_initializer && fi.IsDefaultInitializer)
731 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
737 if (initialized_fields == null)
740 for (int i = 0; i < initialized_fields.Count; ++i) {
741 FieldInitializer fi = initialized_fields [i];
742 ExpressionStatement s = fi.ResolveStatement (ec);
747 // Field is re-initialized to its default value => removed
749 if (fi.IsDefaultInitializer && RootContext.Optimize)
752 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
756 public override string DocComment {
768 public PendingImplementation PendingImplementations {
769 get { return pending; }
772 public TypeSpec GetAttributeCoClass ()
774 if (OptAttributes == null)
777 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CoClass);
781 return a.GetCoClassAttributeValue ();
784 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
787 if (OptAttributes != null) {
788 a = OptAttributes.Search (pa);
794 return a.GetAttributeUsageAttribute ();
797 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
799 // FIXME: get rid of partial_parts and store lists of bases of each part here
800 // assumed, not verified: 'part' is in 'partial_parts'
801 ((TypeContainer) part).type_bases = bases;
805 /// This function computes the Base class and also the
806 /// list of interfaces that the class or struct @c implements.
808 /// The return value is an array (might be null) of
809 /// interfaces implemented (as Types).
811 /// The @base_class argument is set to the base object or null
812 /// if this is `System.Object'.
814 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
817 if (type_bases == null)
820 int count = type_bases.Count;
821 TypeExpr [] ifaces = null;
822 var base_context = new BaseContext (this);
823 for (int i = 0, j = 0; i < count; i++){
824 FullNamedExpression fne = type_bases [i];
826 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
827 if (fne_resolved == null)
830 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
831 if (fne_resolved.Type == InternalType.Dynamic)
832 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
833 GetSignatureForError ());
835 base_type = fne_resolved.Type;
837 base_class = fne_resolved;
842 ifaces = new TypeExpr [count - i];
844 if (fne_resolved.Type.IsInterface) {
845 for (int ii = 0; ii < j; ++ii) {
846 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
847 Report.Error (528, Location, "`{0}' is already listed in interface list",
848 fne_resolved.GetSignatureForError ());
853 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
854 Report.Error (61, fne.Location,
855 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
856 fne_resolved.GetSignatureForError (), GetSignatureForError ());
859 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
860 if (Kind != MemberKind.Class) {
861 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
862 } else if (base_class != null)
863 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
864 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
866 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
867 GetSignatureForError (), fne_resolved.GetSignatureForError ());
871 ifaces [j++] = fne_resolved;
877 TypeExpr[] GetNormalPartialBases ()
879 var ifaces = new List<TypeExpr> (0);
880 if (iface_exprs != null)
881 ifaces.AddRange (iface_exprs);
883 foreach (TypeContainer part in partial_parts) {
884 TypeExpr new_base_class;
885 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
886 if (new_base_class != null) {
887 if (base_type_expr != null && new_base_class.Type != base_type) {
888 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
889 Report.Error (263, part.Location,
890 "Partial declarations of `{0}' must not specify different base classes",
891 part.GetSignatureForError ());
893 base_type_expr = new_base_class;
894 base_type = base_type_expr.Type;
898 if (new_ifaces == null)
901 foreach (TypeExpr iface in new_ifaces) {
902 if (ifaces.Contains (iface))
909 if (ifaces.Count == 0)
912 return ifaces.ToArray ();
916 // Checks that some operators come in pairs:
922 // They are matched based on the return type and the argument types
924 void CheckPairedOperators ()
926 bool has_equality_or_inequality = false;
927 var operators = this.operators.ToArray ();
928 bool[] has_pair = new bool[operators.Length];
930 for (int i = 0; i < operators.Length; ++i) {
931 if (operators[i] == null)
934 Operator o_a = (Operator) operators[i];
935 Operator.OpType o_type = o_a.OperatorType;
936 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
937 has_equality_or_inequality = true;
939 Operator.OpType matching_type = o_a.GetMatchingOperator ();
940 if (matching_type == Operator.OpType.TOP) {
945 for (int ii = 0; ii < operators.Length; ++ii) {
946 Operator o_b = (Operator) operators[ii];
947 if (o_b == null || o_b.OperatorType != matching_type)
950 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
953 if (!TypeSpecComparer.Default.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
959 // Used to ignore duplicate user conversions
965 for (int i = 0; i < operators.Length; ++i) {
966 if (operators[i] == null || has_pair[i])
969 Operator o = (Operator) operators [i];
970 Report.Error (216, o.Location,
971 "The operator `{0}' requires a matching operator `{1}' to also be defined",
972 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
975 if (has_equality_or_inequality) {
976 if (Methods == null || !HasEquals)
977 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
978 GetSignatureForError ());
980 if (Methods == null || !HasGetHashCode)
981 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
982 GetSignatureForError ());
986 bool CreateTypeBuilder ()
989 // Sets .size to 1 for structs with no instance fields
991 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
994 if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
995 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
999 ModuleBuilder builder = Module.Compiled.Builder;
1000 TypeBuilder = builder.DefineType (Name, TypeAttr, null, type_size);
1002 TypeBuilder builder = Parent.TypeBuilder;
1004 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1007 spec.SetMetaInfo (TypeBuilder);
1008 spec.MemberCache = new MemberCache (this);
1009 spec.DeclaringType = Parent.CurrentType;
1012 Parent.MemberCache.AddMember (spec);
1015 string[] param_names = new string[TypeParameters.Length];
1016 for (int i = 0; i < TypeParameters.Length; i++)
1017 param_names [i] = TypeParameters[i].Name;
1019 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1021 int offset = CurrentTypeParametersStartIndex;
1022 for (int i = offset; i < all_tp_builders.Length; i++) {
1023 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1030 bool DefineBaseTypes ()
1032 iface_exprs = ResolveBaseTypes (out base_type_expr);
1033 if (partial_parts != null) {
1034 iface_exprs = GetNormalPartialBases ();
1037 var cycle = CheckRecursiveDefinition (this);
1038 if (cycle != null) {
1039 Report.SymbolRelatedToPreviousError (cycle);
1040 if (this is Interface) {
1041 Report.Error (529, Location,
1042 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1043 GetSignatureForError (), cycle.GetSignatureForError ());
1045 Report.Error (146, Location,
1046 "Circular base class dependency involving `{0}' and `{1}'",
1047 GetSignatureForError (), cycle.GetSignatureForError ());
1053 if (iface_exprs != null) {
1054 foreach (TypeExpr iface in iface_exprs) {
1055 // Prevents a crash, the interface might not have been resolved: 442144
1059 var iface_type = iface.Type;
1061 if (!spec.AddInterface (iface_type))
1064 if (iface_type.IsGeneric && spec.Interfaces != null) {
1065 foreach (var prev_iface in iface_exprs) {
1066 if (prev_iface == iface)
1069 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1072 Report.Error (695, Location,
1073 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1074 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1078 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1080 // Ensure the base is always setup
1081 var compiled_iface = iface_type.MemberDefinition as Interface;
1082 if (compiled_iface != null) {
1083 // TODO: Need DefineBaseType only
1084 compiled_iface.DefineType ();
1087 if (iface_type.Interfaces != null) {
1088 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1089 for (int i = 0; i < base_ifaces.Count; ++i) {
1090 var ii_iface_type = base_ifaces[i];
1091 if (spec.AddInterface (ii_iface_type)) {
1092 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1094 if (ii_iface_type.Interfaces != null)
1095 base_ifaces.AddRange (ii_iface_type.Interfaces);
1102 if (Kind == MemberKind.Interface) {
1103 spec.BaseType = TypeManager.object_type;
1107 if (base_type != null) {
1108 spec.BaseType = base_type;
1110 // Set base type after type creation
1111 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1117 public virtual void DefineConstants ()
1119 if (constants != null) {
1120 foreach (Const c in constants) {
1125 if (instance_constructors != null) {
1126 foreach (MethodCore m in instance_constructors) {
1127 var p = m.ParameterInfo;
1128 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1129 var rc = new ResolveContext (m);
1130 p.ResolveDefaultValues (rc);
1135 if (methods != null) {
1136 foreach (MethodCore m in methods) {
1137 var p = m.ParameterInfo;
1138 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1139 var rc = new ResolveContext (m);
1140 p.ResolveDefaultValues (rc);
1145 if (indexers != null) {
1146 foreach (Indexer i in indexers) {
1147 var p = i.ParameterInfo;
1148 if (p[p.Count - 1].HasDefaultValue) {
1149 var rc = new ResolveContext (i);
1150 p.ResolveDefaultValues (rc);
1155 if (types != null) {
1156 foreach (var t in types)
1157 t.DefineConstants ();
1162 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1164 public TypeBuilder CreateType ()
1166 if (TypeBuilder != null)
1172 if (!CreateTypeBuilder ()) {
1177 if (partial_parts != null) {
1178 foreach (TypeContainer part in partial_parts) {
1180 part.current_type = current_type;
1181 part.TypeBuilder = TypeBuilder;
1185 if (Types != null) {
1186 foreach (TypeContainer tc in Types) {
1187 if (tc.CreateType () == null) {
1197 public override TypeBuilder DefineType ()
1204 type_defined = true;
1206 if (!DefineBaseTypes ()) {
1211 if (!DefineNestedTypes ()) {
1219 public override void SetParameterInfo (List<Constraints> constraints_list)
1221 base.SetParameterInfo (constraints_list);
1223 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1226 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1227 for (int i = 0; i < tc_names.Length; ++i) {
1228 if (tc_names [i].Name != type_params [i].Name) {
1229 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1230 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1231 GetSignatureForError ());
1235 if (tc_names [i].Variance != type_params [i].Variance) {
1236 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1237 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1238 GetSignatureForError ());
1245 // Replaces normal spec with predefined one when compiling corlib
1246 // and this type container defines predefined type
1248 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1253 void UpdateTypeParameterConstraints (TypeContainer part)
1255 TypeParameter[] current_params = type_params;
1256 for (int i = 0; i < current_params.Length; i++) {
1257 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1260 Report.SymbolRelatedToPreviousError (Location, "");
1261 Report.Error (265, part.Location,
1262 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1263 GetSignatureForError (), current_params [i].GetSignatureForError ());
1267 public bool ResolveTypeParameters ()
1269 if (!DoResolveTypeParameters ())
1272 if (types != null) {
1273 foreach (var type in types)
1274 if (!type.ResolveTypeParameters ())
1278 if (compiler_generated != null) {
1279 foreach (CompilerGeneratedClass c in compiler_generated)
1280 if (!c.ResolveTypeParameters ())
1287 protected virtual bool DoResolveTypeParameters ()
1289 if (CurrentTypeParameters == null)
1292 if (PartialContainer != this)
1293 throw new InternalErrorException ();
1295 var base_context = new BaseContext (this);
1296 foreach (TypeParameter type_param in CurrentTypeParameters) {
1297 if (!type_param.ResolveConstraints (base_context)) {
1303 if (partial_parts != null) {
1304 foreach (TypeContainer part in partial_parts)
1305 UpdateTypeParameterConstraints (part);
1311 protected virtual bool DefineNestedTypes ()
1313 if (Types != null) {
1314 foreach (TypeContainer tc in Types)
1315 if (tc.DefineType () == null)
1322 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1324 if (InTransit != null)
1329 if (base_type_expr != null) {
1330 var ptc = base_type.MemberDefinition as TypeContainer;
1331 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1335 if (iface_exprs != null) {
1336 foreach (TypeExpr iface in iface_exprs) {
1337 // the interface might not have been resolved, prevents a crash, see #442144
1340 var ptc = iface.Type.MemberDefinition as Interface;
1341 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1346 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1354 /// Populates our TypeBuilder with fields and methods
1356 public sealed override bool Define ()
1358 if (members_defined)
1359 return members_defined_ok;
1361 members_defined_ok = DoDefineMembers ();
1362 members_defined = true;
1364 if (types != null) {
1365 foreach (var nested in types)
1369 return members_defined_ok;
1372 protected virtual bool DoDefineMembers ()
1374 if (iface_exprs != null) {
1375 foreach (TypeExpr iface in iface_exprs) {
1376 var iface_type = iface.Type;
1378 // Ensure the base is always setup
1379 var compiled_iface = iface_type.MemberDefinition as Interface;
1380 if (compiled_iface != null)
1381 compiled_iface.Define ();
1383 if (Kind == MemberKind.Interface)
1384 MemberCache.AddInterface (iface_type);
1386 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1387 if (oa != null && !IsObsolete)
1388 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1390 GenericTypeExpr ct = iface as GenericTypeExpr;
1392 // TODO: passing `this' is wrong, should be base type iface instead
1393 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1395 ct.CheckConstraints (this);
1397 if (ct.HasDynamicArguments ()) {
1398 Report.Error (1966, iface.Location,
1399 "`{0}': cannot implement a dynamic interface `{1}'",
1400 GetSignatureForError (), iface.GetSignatureForError ());
1407 if (base_type_expr != null) {
1408 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1409 if (obsolete_attr != null && !IsObsolete)
1410 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1412 var ct = base_type_expr as GenericTypeExpr;
1414 ct.CheckConstraints (this);
1417 if (base_type != null) {
1418 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1419 if (baseContainer != null) {
1420 baseContainer.Define ();
1423 // It can trigger define of this type (for generic types only)
1425 if (HasMembersDefined)
1430 if (type_params != null) {
1431 foreach (var tp in type_params) {
1432 tp.CheckGenericConstraints ();
1437 MemberSpec candidate;
1438 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1439 if (conflict_symbol == null && candidate == null) {
1440 if ((ModFlags & Modifiers.NEW) != 0)
1441 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1442 GetSignatureForError ());
1444 if ((ModFlags & Modifiers.NEW) == 0) {
1445 if (candidate == null)
1446 candidate = conflict_symbol;
1448 Report.SymbolRelatedToPreviousError (candidate);
1449 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1450 GetSignatureForError (), candidate.GetSignatureForError ());
1455 DefineContainerMembers (constants);
1456 DefineContainerMembers (fields);
1458 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1459 pending = PendingImplementation.GetPendingImplementations (this);
1461 if (requires_delayed_unmanagedtype_check) {
1462 requires_delayed_unmanagedtype_check = false;
1463 foreach (FieldBase f in fields) {
1464 if (f.MemberType != null && f.MemberType.IsPointer)
1465 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1471 // Constructors are not in the defined_names array
1473 DefineContainerMembers (instance_constructors);
1475 DefineContainerMembers (events);
1476 DefineContainerMembers (ordered_explicit_member_list);
1477 DefineContainerMembers (ordered_member_list);
1479 if (operators != null) {
1480 DefineContainerMembers (operators);
1481 CheckPairedOperators ();
1484 ComputeIndexerName();
1485 CheckEqualsAndGetHashCode();
1490 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1493 foreach (MemberCore mc in mcal) {
1496 } catch (Exception e) {
1497 throw new InternalErrorException (mc, e);
1503 protected virtual void ComputeIndexerName ()
1505 if (indexers == null)
1508 string class_indexer_name = null;
1511 // If there's both an explicit and an implicit interface implementation, the
1512 // explicit one actually implements the interface while the other one is just
1513 // a normal indexer. See bug #37714.
1516 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1517 foreach (Indexer i in indexers) {
1518 if (i.InterfaceType != null) {
1519 if (seen_normal_indexers)
1520 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1524 seen_normal_indexers = true;
1526 if (class_indexer_name == null) {
1527 class_indexer_name = i.ShortName;
1531 if (i.ShortName != class_indexer_name)
1532 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");
1535 if (class_indexer_name != null)
1536 indexer_name = class_indexer_name;
1539 void EmitIndexerName ()
1541 if (!seen_normal_indexers)
1544 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1545 if (pa.Constructor == null &&
1546 !pa.ResolveConstructor (Location, TypeManager.string_type))
1549 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1550 TypeBuilder.SetCustomAttribute (cb);
1553 protected virtual void CheckEqualsAndGetHashCode ()
1555 if (methods == null)
1558 if (HasEquals && !HasGetHashCode) {
1559 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1563 // Indicated whether container has StructLayout attribute set Explicit
1564 public bool HasExplicitLayout {
1565 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1566 set { caching_flags |= Flags.HasExplicitLayout; }
1569 public bool HasStructLayout {
1570 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1571 set { caching_flags |= Flags.HasStructLayout; }
1574 public MemberCache MemberCache {
1576 return spec.MemberCache;
1580 void CheckMemberUsage (List<MemberCore> al, string member_type)
1585 foreach (MemberCore mc in al) {
1586 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1589 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1590 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1595 public virtual void VerifyMembers ()
1598 // Check for internal or private fields that were never assigned
1600 if (Report.WarningLevel >= 3) {
1601 if (RootContext.EnhancedWarnings) {
1602 CheckMemberUsage (properties, "property");
1603 CheckMemberUsage (methods, "method");
1604 CheckMemberUsage (constants, "constant");
1607 if (fields != null){
1608 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1609 foreach (FieldBase f in fields) {
1610 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1611 if (is_type_exposed)
1618 if ((f.caching_flags & Flags.IsAssigned) == 0)
1619 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1621 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1622 f.GetSignatureForError ());
1628 // Only report 649 on level 4
1630 if (Report.WarningLevel < 4)
1633 if ((f.caching_flags & Flags.IsAssigned) != 0)
1637 // Don't be pendatic over serializable attributes
1639 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1642 Constant c = New.Constantify (f.MemberType);
1643 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1644 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1650 public override void Emit ()
1652 if (all_tp_builders != null) {
1653 int current_starts_index = CurrentTypeParametersStartIndex;
1654 for (int i = 0; i < all_tp_builders.Length; i++) {
1655 if (i < current_starts_index) {
1656 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1658 CurrentTypeParameters [i - current_starts_index].Emit ();
1663 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1664 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1669 // TODO: move to ClassOrStruct
1670 void EmitConstructors ()
1672 if (instance_constructors == null)
1675 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1676 bool has_compliant_args = false;
1678 foreach (Constructor c in instance_constructors) {
1682 catch (Exception e) {
1683 throw new InternalErrorException (c, e);
1686 if (has_compliant_args)
1689 has_compliant_args = c.HasCompliantArgs;
1691 if (!has_compliant_args)
1692 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1694 foreach (Constructor c in instance_constructors) {
1698 catch (Exception e) {
1699 throw new InternalErrorException (c, e);
1706 /// Emits the code, this step is performed after all
1707 /// the types, enumerations, constructors
1709 public virtual void EmitType ()
1711 if (OptAttributes != null)
1712 OptAttributes.Emit ();
1716 EmitConstructors ();
1718 if (constants != null)
1719 foreach (Const con in constants)
1722 if (default_static_constructor != null)
1723 default_static_constructor.Emit ();
1725 if (operators != null)
1726 foreach (Operator o in operators)
1729 if (properties != null)
1730 foreach (Property p in properties)
1733 if (indexers != null) {
1734 foreach (Indexer indx in indexers)
1739 if (events != null){
1740 foreach (Event e in Events)
1744 if (methods != null) {
1745 for (int i = 0; i < methods.Count; ++i)
1746 ((MethodOrOperator) methods [i]).Emit ();
1750 foreach (FieldBase f in fields)
1753 if (types != null) {
1754 foreach (TypeContainer t in types)
1758 if (pending != null)
1759 pending.VerifyPendingMethods (Report);
1761 if (Report.Errors > 0)
1764 if (compiler_generated != null) {
1765 for (int i = 0; i < compiler_generated.Count; ++i)
1766 compiler_generated [i].EmitType ();
1770 public void CloseType ()
1772 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1775 // Close base type container first to avoid TypeLoadException
1776 if (spec.BaseType != null) {
1777 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1783 caching_flags |= Flags.CloseTypeCreated;
1784 TypeBuilder.CreateType ();
1785 } catch (TypeLoadException){
1787 // This is fine, the code still created the type
1789 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1790 // Console.WriteLine (e.Message);
1791 } catch (Exception e) {
1792 throw new InternalErrorException (this, e);
1796 foreach (TypeContainer tc in Types)
1800 if (compiler_generated != null)
1801 foreach (CompilerGeneratedClass c in compiler_generated)
1806 initialized_fields = null;
1807 initialized_static_fields = null;
1809 ordered_explicit_member_list = null;
1810 ordered_member_list = null;
1815 compiler_generated = null;
1816 default_constructor = null;
1817 default_static_constructor = null;
1819 OptAttributes = null;
1823 // Performs the validation on a Method's modifiers (properties have
1824 // the same properties).
1826 public bool MethodModifiersValid (MemberCore mc)
1828 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1829 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1830 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1832 var flags = mc.ModFlags;
1835 // At most one of static, virtual or override
1837 if ((flags & Modifiers.STATIC) != 0){
1838 if ((flags & vao) != 0){
1839 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1840 mc.GetSignatureForError ());
1845 if (Kind == MemberKind.Struct){
1846 if ((flags & va) != 0){
1847 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1852 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1853 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1854 mc.GetSignatureForError ());
1859 // If the declaration includes the abstract modifier, then the
1860 // declaration does not include static, virtual or extern
1862 if ((flags & Modifiers.ABSTRACT) != 0){
1863 if ((flags & Modifiers.EXTERN) != 0){
1865 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1869 if ((flags & Modifiers.SEALED) != 0) {
1870 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1874 if ((flags & Modifiers.VIRTUAL) != 0){
1875 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1879 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1880 Report.SymbolRelatedToPreviousError (this);
1881 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1882 mc.GetSignatureForError (), GetSignatureForError ());
1887 if ((flags & Modifiers.PRIVATE) != 0){
1888 if ((flags & vao) != 0){
1889 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1894 if ((flags & Modifiers.SEALED) != 0){
1895 if ((flags & Modifiers.OVERRIDE) == 0){
1896 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1904 public Constructor DefaultStaticConstructor {
1905 get { return default_static_constructor; }
1908 protected override bool VerifyClsCompliance ()
1910 if (!base.VerifyClsCompliance ())
1913 // Check this name against other containers
1914 NamespaceEntry.NS.VerifyClsCompliance ();
1916 // Check all container names for user classes
1917 if (Kind != MemberKind.Delegate)
1918 MemberCache.VerifyClsCompliance (Definition, Report);
1920 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1921 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1922 GetSignatureForError (), BaseType.GetSignatureForError ());
1928 /// Performs checks for an explicit interface implementation. First it
1929 /// checks whether the `interface_type' is a base inteface implementation.
1930 /// Then it checks whether `name' exists in the interface type.
1932 public bool VerifyImplements (InterfaceMemberBase mb)
1934 var ifaces = spec.Interfaces;
1935 if (ifaces != null) {
1936 foreach (TypeSpec t in ifaces){
1937 if (TypeManager.IsEqual (t, mb.InterfaceType))
1942 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1943 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1944 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1949 // Used for visiblity checks to tests whether this definition shares
1950 // base type baseType, it does member-definition search
1952 public bool IsBaseTypeDefinition (TypeSpec baseType)
1954 // RootContext check
1955 if (TypeBuilder == null)
1960 if (type.MemberDefinition == baseType.MemberDefinition)
1963 type = type.BaseType;
1964 } while (type != null);
1969 public MemberCache LoadMembers (TypeSpec declaringType)
1971 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1974 public void Mark_HasEquals ()
1976 cached_method |= CachedMethods.Equals;
1979 public void Mark_HasGetHashCode ()
1981 cached_method |= CachedMethods.GetHashCode;
1985 /// Method container contains Equals method
1987 public bool HasEquals {
1989 return (cached_method & CachedMethods.Equals) != 0;
1994 /// Method container contains GetHashCode method
1996 public bool HasGetHashCode {
1998 return (cached_method & CachedMethods.GetHashCode) != 0;
2002 public bool HasStaticFieldInitializer {
2004 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2008 cached_method |= CachedMethods.HasStaticFieldInitializer;
2010 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2015 // Generates xml doc comments (if any), and if required,
2016 // handle warning report.
2018 internal override void GenerateDocComment (DeclSpace ds)
2020 DocUtil.GenerateTypeDocComment (this, ds, Report);
2023 public override string DocCommentHeader {
2024 get { return "T:"; }
2028 public abstract class ClassOrStruct : TypeContainer
2030 Dictionary<SecurityAction, PermissionSet> declarative_security;
2032 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2033 MemberName name, Attributes attrs, MemberKind kind)
2034 : base (ns, parent, name, attrs, kind)
2038 protected override bool AddToContainer (MemberCore symbol, string name)
2040 if (name == MemberName.Name) {
2041 if (symbol is TypeParameter) {
2042 Report.Error (694, symbol.Location,
2043 "Type parameter `{0}' has same name as containing type, or method",
2044 symbol.GetSignatureForError ());
2048 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2049 if (imb == null || !imb.IsExplicitImpl) {
2050 Report.SymbolRelatedToPreviousError (this);
2051 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2052 symbol.GetSignatureForError ());
2057 return base.AddToContainer (symbol, name);
2060 public override void VerifyMembers ()
2062 base.VerifyMembers ();
2064 if ((events != null) && Report.WarningLevel >= 3) {
2065 foreach (Event e in events){
2066 // Note: The event can be assigned from same class only, so we can report
2067 // this warning for all accessibility modes
2068 if ((e.caching_flags & Flags.IsUsed) == 0)
2069 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2074 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2076 if (a.IsValidSecurityAttribute ()) {
2077 if (declarative_security == null)
2078 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2080 a.ExtractSecurityPermissionSet (declarative_security);
2084 if (a.Type == pa.StructLayout) {
2085 PartialContainer.HasStructLayout = true;
2087 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2088 PartialContainer.HasExplicitLayout = true;
2091 if (a.Type == pa.Dynamic) {
2092 a.Error_MisusedDynamicAttribute ();
2096 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2100 /// Defines the default constructors
2102 protected void DefineDefaultConstructor (bool is_static)
2104 // The default instance constructor is public
2105 // If the class is abstract, the default constructor is protected
2106 // The default static constructor is private
2110 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2112 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2115 Constructor c = new Constructor (this, MemberName.Name, mods,
2116 null, ParametersCompiled.EmptyReadOnlyParameters,
2117 new GeneratedBaseInitializer (Location),
2121 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2124 protected override bool DoDefineMembers ()
2126 CheckProtectedModifier ();
2128 base.DoDefineMembers ();
2130 if (default_static_constructor != null)
2131 default_static_constructor.Define ();
2136 public override void Emit ()
2138 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2139 DefineDefaultConstructor (true);
2140 default_static_constructor.Define ();
2145 if (declarative_security != null) {
2146 foreach (var de in declarative_security) {
2147 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2152 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2154 DeclSpace top_level = Parent;
2155 if (top_level != null) {
2156 while (top_level.Parent != null)
2157 top_level = top_level.Parent;
2159 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2160 if (candidates != null)
2161 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2164 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2167 protected override TypeAttributes TypeAttr {
2169 if (default_static_constructor == null)
2170 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2172 return base.TypeAttr;
2178 // TODO: should be sealed
2179 public class Class : ClassOrStruct {
2180 const Modifiers AllowedModifiers =
2183 Modifiers.PROTECTED |
2184 Modifiers.INTERNAL |
2186 Modifiers.ABSTRACT |
2191 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2193 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2195 : base (ns, parent, name, attrs, MemberKind.Class)
2197 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2198 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2199 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2201 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2202 Report.FeatureIsNotAvailable (Location, "static classes");
2206 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2208 if (part.Name == "System.Object")
2209 Report.Error (537, part.Location,
2210 "The class System.Object cannot have a base class or implement an interface.");
2211 base.AddBasesForPart (part, bases);
2214 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2216 if (a.Type == pa.AttributeUsage) {
2217 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2218 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2222 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2223 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2227 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2228 a.Error_MissingGuidAttribute ();
2232 if (a.Type == pa.Extension) {
2233 a.Error_MisusedExtensionAttribute ();
2237 if (a.Type.IsConditionallyExcluded (Location))
2240 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2243 public override AttributeTargets AttributeTargets {
2245 return AttributeTargets.Class;
2249 protected override void DefineContainerMembers (System.Collections.IList list)
2255 base.DefineContainerMembers (list);
2259 foreach (MemberCore m in list) {
2260 if (m is Operator) {
2261 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2265 if (m is Destructor) {
2266 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2271 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2275 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2278 if (m is Constructor) {
2279 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2283 Method method = m as Method;
2284 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2285 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2289 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2292 base.DefineContainerMembers (list);
2295 protected override bool DoDefineMembers ()
2297 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2298 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2301 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2302 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2305 if (InstanceConstructors == null && !IsStatic)
2306 DefineDefaultConstructor (false);
2308 return base.DoDefineMembers ();
2311 public override void Emit ()
2315 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2316 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2318 var trans_flags = TypeManager.HasDynamicTypeUsed (base_type);
2319 if (trans_flags != null) {
2320 var pa = PredefinedAttributes.Get.DynamicTransform;
2321 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
2322 TypeBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
2327 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2329 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2331 if (base_class == null) {
2332 if (spec != TypeManager.object_type)
2333 base_type = TypeManager.object_type;
2335 if (base_type.IsGenericParameter){
2336 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2337 GetSignatureForError (), base_type.GetSignatureForError ());
2338 } else if (IsGeneric && base_type.IsAttribute) {
2339 Report.Error (698, base_class.Location,
2340 "A generic type cannot derive from `{0}' because it is an attribute class",
2341 base_class.GetSignatureForError ());
2342 } else if (base_type.IsStatic) {
2343 Report.SymbolRelatedToPreviousError (base_class.Type);
2344 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2345 GetSignatureForError (), base_type.GetSignatureForError ());
2346 } else if (base_type.IsSealed) {
2347 Report.SymbolRelatedToPreviousError (base_class.Type);
2348 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2349 GetSignatureForError (), base_type.GetSignatureForError ());
2350 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2351 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2352 GetSignatureForError (), base_class.GetSignatureForError ());
2355 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2356 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2357 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2358 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2359 GetSignatureForError (), base_type.GetSignatureForError ());
2361 base_type = TypeManager.object_type;
2364 if (!IsAccessibleAs (base_type)) {
2365 Report.SymbolRelatedToPreviousError (base_type);
2366 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2367 base_type.GetSignatureForError (), GetSignatureForError ());
2371 if (PartialContainer.IsStatic && ifaces != null) {
2372 foreach (TypeExpr t in ifaces)
2373 Report.SymbolRelatedToPreviousError (t.Type);
2374 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2380 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2381 /// Valid only for attribute classes.
2382 public override string[] ConditionalConditions ()
2384 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2387 caching_flags &= ~Flags.Excluded_Undetected;
2389 if (OptAttributes == null)
2392 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2396 string[] conditions = new string[attrs.Length];
2397 for (int i = 0; i < conditions.Length; ++i)
2398 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2400 caching_flags |= Flags.Excluded;
2405 // FIXME: How do we deal with the user specifying a different
2408 protected override TypeAttributes TypeAttr {
2410 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2412 ta |= StaticClassAttribute;
2418 public sealed class Struct : ClassOrStruct {
2420 bool is_unmanaged, has_unmanaged_check_done;
2424 // Modifiers allowed in a struct declaration
2426 const Modifiers AllowedModifiers =
2429 Modifiers.PROTECTED |
2430 Modifiers.INTERNAL |
2434 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2435 Modifiers mod, Attributes attrs)
2436 : base (ns, parent, name, attrs, MemberKind.Struct)
2438 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2439 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2440 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2443 public override AttributeTargets AttributeTargets {
2445 return AttributeTargets.Struct;
2449 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2451 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2454 // When struct constains fixed fixed and struct layout has explicitly
2455 // set CharSet, its value has to be propagated to compiler generated
2456 // fixed field types
2458 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2459 for (int i = 0; i < Fields.Count; ++i) {
2460 FixedField ff = Fields [i] as FixedField;
2462 ff.SetCharSet (TypeBuilder.Attributes);
2467 bool CheckStructCycles (Struct s)
2469 if (s.Fields == null)
2476 foreach (FieldBase field in s.Fields) {
2477 TypeSpec ftype = field.Spec.MemberType;
2478 if (!ftype.IsStruct)
2481 if (ftype is PredefinedTypeSpec)
2484 foreach (var targ in ftype.TypeArguments) {
2485 if (!CheckFieldTypeCycle (targ)) {
2486 Report.Error (523, field.Location,
2487 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2488 field.GetSignatureForError (), ftype.GetSignatureForError ());
2493 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2496 if (!CheckFieldTypeCycle (ftype)) {
2497 Report.Error (523, field.Location,
2498 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2499 field.GetSignatureForError (), ftype.GetSignatureForError ());
2504 s.InTransit = false;
2508 bool CheckFieldTypeCycle (TypeSpec ts)
2510 var fts = ts.MemberDefinition as Struct;
2514 return CheckStructCycles (fts);
2517 public override void Emit ()
2519 CheckStructCycles (this);
2524 public override bool IsUnmanagedType ()
2529 if (has_unmanaged_check_done)
2530 return is_unmanaged;
2532 if (requires_delayed_unmanagedtype_check)
2535 requires_delayed_unmanagedtype_check = true;
2537 foreach (FieldBase f in fields) {
2541 // It can happen when recursive unmanaged types are defined
2542 // struct S { S* s; }
2543 TypeSpec mt = f.MemberType;
2548 while (mt.IsPointer)
2549 mt = TypeManager.GetElementType (mt);
2551 if (mt.MemberDefinition == this) {
2552 for (var p = Parent; p != null; p = p.Parent) {
2553 if (p.Kind == MemberKind.Class) {
2554 has_unmanaged_check_done = true;
2561 if (TypeManager.IsUnmanagedType (mt))
2564 has_unmanaged_check_done = true;
2568 has_unmanaged_check_done = true;
2569 is_unmanaged = true;
2573 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2575 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2576 base_type = TypeManager.value_type;
2580 protected override TypeAttributes TypeAttr {
2582 const TypeAttributes DefaultTypeAttributes =
2583 TypeAttributes.SequentialLayout |
2584 TypeAttributes.Sealed;
2586 return base.TypeAttr | DefaultTypeAttributes;
2590 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2592 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2593 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2594 field.GetSignatureForError ());
2597 base.RegisterFieldForInitialization (field, expression);
2605 public sealed class Interface : TypeContainer {
2608 /// Modifiers allowed in a class declaration
2610 public const Modifiers AllowedModifiers =
2613 Modifiers.PROTECTED |
2614 Modifiers.INTERNAL |
2618 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2620 : base (ns, parent, name, attrs, MemberKind.Interface)
2622 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2624 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2625 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2628 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2630 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2631 a.Error_MissingGuidAttribute ();
2635 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2639 public override AttributeTargets AttributeTargets {
2641 return AttributeTargets.Interface;
2645 protected override TypeAttributes TypeAttr {
2647 const TypeAttributes DefaultTypeAttributes =
2648 TypeAttributes.AutoLayout |
2649 TypeAttributes.Abstract |
2650 TypeAttributes.Interface;
2652 return base.TypeAttr | DefaultTypeAttributes;
2656 protected override bool VerifyClsCompliance ()
2658 if (!base.VerifyClsCompliance ())
2661 if (iface_exprs != null) {
2662 foreach (var iface in iface_exprs) {
2663 if (iface.Type.IsCLSCompliant ())
2666 Report.SymbolRelatedToPreviousError (iface.Type);
2667 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2668 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2676 public abstract class InterfaceMemberBase : MemberBase {
2678 // Whether this is an interface member.
2680 public bool IsInterface;
2683 // If true, this is an explicit interface implementation
2685 public bool IsExplicitImpl;
2687 protected bool is_external_implementation;
2690 // The interface type we are explicitly implementing
2692 public TypeSpec InterfaceType;
2695 // The method we're overriding if this is an override method.
2697 protected MethodSpec base_method;
2699 readonly Modifiers explicit_mod_flags;
2700 public MethodAttributes flags;
2702 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2703 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2704 MemberName name, Attributes attrs)
2705 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2708 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2709 IsExplicitImpl = (MemberName.Left != null);
2710 explicit_mod_flags = mod;
2713 protected override bool CheckBase ()
2715 if (!base.CheckBase ())
2718 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2719 CheckForDuplications ();
2724 // For System.Object only
2725 if (Parent.BaseType == null)
2728 MemberSpec candidate;
2729 var base_member = FindBaseMember (out candidate);
2731 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2732 if (base_member == null) {
2733 if (candidate == null) {
2734 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2735 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2736 "object.Finalize()");
2738 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2739 GetSignatureForError (), SimpleName.GetMemberType (this));
2742 Report.SymbolRelatedToPreviousError (candidate);
2744 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2745 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2746 else if (this is PropertyBase)
2747 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2748 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2750 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2751 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2757 if (!CheckOverrideAgainstBase (base_member))
2760 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2762 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2763 Report.SymbolRelatedToPreviousError (base_member);
2764 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2765 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2768 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2769 Report.SymbolRelatedToPreviousError (base_member);
2770 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2771 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2775 base_method = base_member as MethodSpec;
2779 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2780 base_member = candidate;
2782 if (base_member == null) {
2783 if ((ModFlags & Modifiers.NEW) != 0) {
2784 if (base_member == null) {
2785 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2786 GetSignatureForError ());
2790 if ((ModFlags & Modifiers.NEW) == 0) {
2791 ModFlags |= Modifiers.NEW;
2792 Report.SymbolRelatedToPreviousError (base_member);
2793 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2794 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",
2795 GetSignatureForError (), base_member.GetSignatureForError ());
2797 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2798 GetSignatureForError (), base_member.GetSignatureForError ());
2802 if (!IsInterface && base_member.IsAbstract) {
2803 Report.SymbolRelatedToPreviousError (base_member);
2804 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2805 GetSignatureForError (), base_member.GetSignatureForError ());
2812 protected virtual bool CheckForDuplications ()
2814 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2818 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2819 // that have been defined.
2821 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2825 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2826 Report.SymbolRelatedToPreviousError (base_member);
2827 Report.Error (506, Location,
2828 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2829 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2833 // Now we check that the overriden method is not final
2834 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2835 Report.SymbolRelatedToPreviousError (base_member);
2836 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2837 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2841 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2842 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2843 Report.SymbolRelatedToPreviousError (base_member);
2844 if (this is PropertyBasedMember) {
2845 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2846 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2848 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2849 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2857 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2859 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2860 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2862 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2864 // when overriding protected internal, the method can be declared
2865 // protected internal only within the same assembly or assembly
2866 // which has InternalsVisibleTo
2868 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2869 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2871 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2873 // if it's not "protected internal", it must be "protected"
2878 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2880 // protected within the same assembly - an error
2884 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2885 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2887 // protected ok, but other attributes differ - report an error
2894 return thisp == base_classp;
2897 public override bool Define ()
2900 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2901 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2903 flags = MethodAttributes.Public |
2904 MethodAttributes.Abstract |
2905 MethodAttributes.HideBySig |
2906 MethodAttributes.NewSlot |
2907 MethodAttributes.Virtual;
2909 Parent.PartialContainer.MethodModifiersValid (this);
2911 flags = ModifiersExtensions.MethodAttr (ModFlags);
2914 if (IsExplicitImpl) {
2915 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2916 if (iface_texpr == null)
2919 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2920 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2921 GetSignatureForError ());
2924 InterfaceType = iface_texpr.Type;
2926 if (!InterfaceType.IsInterface) {
2927 Report.SymbolRelatedToPreviousError (InterfaceType);
2928 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2929 TypeManager.CSharpName (InterfaceType));
2931 Parent.PartialContainer.VerifyImplements (this);
2934 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2937 return base.Define ();
2940 protected bool DefineParameters (ParametersCompiled parameters)
2942 if (!parameters.Resolve (this))
2946 for (int i = 0; i < parameters.Count; ++i) {
2947 Parameter p = parameters [i];
2949 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2950 p.Warning_UselessOptionalParameter (Report);
2952 if (p.CheckAccessibility (this))
2955 TypeSpec t = parameters.Types [i];
2956 Report.SymbolRelatedToPreviousError (t);
2957 if (this is Indexer)
2958 Report.Error (55, Location,
2959 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2960 TypeManager.CSharpName (t), GetSignatureForError ());
2961 else if (this is Operator)
2962 Report.Error (57, Location,
2963 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2964 TypeManager.CSharpName (t), GetSignatureForError ());
2966 Report.Error (51, Location,
2967 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2968 TypeManager.CSharpName (t), GetSignatureForError ());
2974 public override void Emit()
2976 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2977 // We are more strict than csc and report this as an error because SRE does not allow emit that
2978 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2979 if (this is Constructor) {
2980 Report.Error (824, Location,
2981 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
2983 Report.Error (626, Location,
2984 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
2985 GetSignatureForError ());
2992 public override bool EnableOverloadChecks (MemberCore overload)
2995 // Two members can differ in their explicit interface
2996 // type parameter only
2998 InterfaceMemberBase imb = overload as InterfaceMemberBase;
2999 if (imb != null && imb.IsExplicitImpl) {
3000 if (IsExplicitImpl) {
3001 caching_flags |= Flags.MethodOverloadsExist;
3006 return IsExplicitImpl;
3009 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3011 Report.SymbolRelatedToPreviousError (base_member);
3012 Report.Error (507, member.Location,
3013 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3014 member.GetSignatureForError (),
3015 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3016 base_member.GetSignatureForError ());
3019 protected void Error_StaticReturnType ()
3021 Report.Error (722, Location,
3022 "`{0}': static types cannot be used as return types",
3023 MemberType.GetSignatureForError ());
3027 /// Gets base method and its return type
3029 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3031 return MemberCache.FindBaseMember (this, out bestCandidate);
3035 // The "short" name of this property / indexer / event. This is the
3036 // name without the explicit interface.
3038 public string ShortName {
3039 get { return MemberName.Name; }
3040 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3044 // Returns full metadata method name
3046 public string GetFullName (MemberName name)
3048 return GetFullName (name.Name);
3051 public string GetFullName (string name)
3053 if (!IsExplicitImpl)
3057 // When dealing with explicit members a full interface type
3058 // name is added to member name to avoid possible name conflicts
3060 // We use CSharpName which gets us full name with benefit of
3061 // replacing predefined names which saves some space and name
3064 return TypeManager.CSharpName (InterfaceType) + "." + name;
3067 protected override bool VerifyClsCompliance ()
3069 if (!base.VerifyClsCompliance ()) {
3073 if (GenericMethod != null)
3074 GenericMethod.VerifyClsCompliance ();
3079 public override bool IsUsed
3081 get { return IsExplicitImpl || base.IsUsed; }
3086 public abstract class MemberBase : MemberCore
3088 protected FullNamedExpression type_expr;
3089 protected TypeSpec member_type;
3091 public readonly DeclSpace ds;
3092 public readonly GenericMethod GenericMethod;
3094 protected MemberBase (DeclSpace parent, GenericMethod generic,
3095 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3096 MemberName name, Attributes attrs)
3097 : base (parent, name, attrs)
3099 this.ds = generic != null ? generic : (DeclSpace) parent;
3100 this.type_expr = type;
3101 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3102 GenericMethod = generic;
3103 if (GenericMethod != null)
3104 GenericMethod.ModFlags = ModFlags;
3109 public TypeSpec MemberType {
3115 public FullNamedExpression TypeExpression {
3124 // Main member define entry
3126 public override bool Define ()
3128 DoMemberTypeIndependentChecks ();
3131 // Returns false only when type resolution failed
3133 if (!ResolveMemberType ())
3136 DoMemberTypeDependentChecks ();
3141 // Any type_name independent checks
3143 protected virtual void DoMemberTypeIndependentChecks ()
3145 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3146 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3147 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3148 GetSignatureForError (), Parent.GetSignatureForError ());
3153 // Any type_name dependent checks
3155 protected virtual void DoMemberTypeDependentChecks ()
3157 // verify accessibility
3158 if (!IsAccessibleAs (MemberType)) {
3159 Report.SymbolRelatedToPreviousError (MemberType);
3160 if (this is Property)
3161 Report.Error (53, Location,
3162 "Inconsistent accessibility: property type `" +
3163 TypeManager.CSharpName (MemberType) + "' is less " +
3164 "accessible than property `" + GetSignatureForError () + "'");
3165 else if (this is Indexer)
3166 Report.Error (54, Location,
3167 "Inconsistent accessibility: indexer return type `" +
3168 TypeManager.CSharpName (MemberType) + "' is less " +
3169 "accessible than indexer `" + GetSignatureForError () + "'");
3170 else if (this is MethodCore) {
3171 if (this is Operator)
3172 Report.Error (56, Location,
3173 "Inconsistent accessibility: return type `" +
3174 TypeManager.CSharpName (MemberType) + "' is less " +
3175 "accessible than operator `" + GetSignatureForError () + "'");
3177 Report.Error (50, Location,
3178 "Inconsistent accessibility: return type `" +
3179 TypeManager.CSharpName (MemberType) + "' is less " +
3180 "accessible than method `" + GetSignatureForError () + "'");
3182 Report.Error (52, Location,
3183 "Inconsistent accessibility: field type `" +
3184 TypeManager.CSharpName (MemberType) + "' is less " +
3185 "accessible than field `" + GetSignatureForError () + "'");
3189 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3190 TypeManager.CheckTypeVariance (MemberType, variance, this);
3193 protected bool IsTypePermitted ()
3195 if (TypeManager.IsSpecialType (MemberType)) {
3196 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3202 protected virtual bool CheckBase ()
3204 CheckProtectedModifier ();
3209 protected virtual bool ResolveMemberType ()
3211 if (member_type != null)
3212 throw new InternalErrorException ("Multi-resolve");
3214 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3219 // Replace original type name, error reporting can use fully resolved name
3223 member_type = te.Type;