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'
190 protected TypeExpr[] iface_exprs;
192 protected List<FullNamedExpression> type_bases;
194 bool members_defined;
195 bool members_defined_ok;
198 TypeContainer InTransit;
200 GenericTypeParameterBuilder[] all_tp_builders;
202 public const string DefaultIndexerName = "Item";
204 private bool seen_normal_indexers = false;
205 private string indexer_name = DefaultIndexerName;
206 protected bool requires_delayed_unmanagedtype_check;
209 private CachedMethods cached_method;
211 protected TypeSpec spec;
212 TypeSpec current_type;
214 List<TypeContainer> partial_parts;
217 /// The pending methods that need to be implemented
218 // (interfaces or abstract methods)
220 PendingImplementation pending;
222 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
223 Attributes attrs, MemberKind kind)
224 : base (ns, parent, name, attrs)
226 if (parent != null && parent.NamespaceEntry != ns)
227 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
230 this.PartialContainer = this;
235 public override TypeSpec CurrentType {
237 if (current_type == null) {
240 // Switch to inflated version as it's used by all expressions
242 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
243 current_type = spec.MakeGenericType (targs);
253 public override TypeParameter[] CurrentTypeParameters {
255 return PartialContainer.type_params;
259 int CurrentTypeParametersStartIndex {
261 int total = all_tp_builders.Length;
262 if (CurrentTypeParameters != null) {
263 return total - CurrentTypeParameters.Length;
269 public TypeSpec Definition {
275 public bool HasMembersDefined {
277 return members_defined;
283 public bool AddMember (MemberCore symbol)
285 return AddToContainer (symbol, symbol.MemberName.Basename);
288 protected virtual bool AddMemberType (TypeContainer ds)
290 return AddToContainer (ds, ds.Basename);
293 protected virtual void RemoveMemberType (DeclSpace ds)
295 RemoveFromContainer (ds.Basename);
298 public void AddConstant (Const constant)
300 if (!AddMember (constant))
303 if (constants == null)
304 constants = new List<MemberCore> ();
306 constants.Add (constant);
309 public TypeContainer AddTypeContainer (TypeContainer tc)
311 if (!AddMemberType (tc))
315 types = new List<TypeContainer> ();
321 public virtual TypeContainer AddPartial (TypeContainer next_part)
323 return AddPartial (next_part, next_part.Basename);
326 protected TypeContainer AddPartial (TypeContainer next_part, string name)
328 next_part.ModFlags |= Modifiers.PARTIAL;
329 TypeContainer tc = GetDefinition (name) as TypeContainer;
331 return AddTypeContainer (next_part);
333 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
334 Report.SymbolRelatedToPreviousError (next_part);
335 Error_MissingPartialModifier (tc);
338 if (tc.Kind != next_part.Kind) {
339 Report.SymbolRelatedToPreviousError (tc);
340 Report.Error (261, next_part.Location,
341 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
342 next_part.GetSignatureForError ());
345 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
346 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
347 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
348 Report.SymbolRelatedToPreviousError (tc);
349 Report.Error (262, next_part.Location,
350 "Partial declarations of `{0}' have conflicting accessibility modifiers",
351 next_part.GetSignatureForError ());
354 if (tc.partial_parts == null)
355 tc.partial_parts = new List<TypeContainer> (1);
357 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
358 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
359 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
360 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
361 tc.ModFlags |= next_part.ModFlags;
363 tc.ModFlags |= next_part.ModFlags;
366 if (next_part.attributes != null) {
367 if (tc.attributes == null)
368 tc.attributes = next_part.attributes;
370 tc.attributes.AddAttributes (next_part.attributes.Attrs);
373 next_part.PartialContainer = tc;
374 tc.partial_parts.Add (next_part);
378 public virtual void RemoveTypeContainer (TypeContainer next_part)
381 types.Remove (next_part);
382 RemoveMemberType (next_part);
385 public void AddDelegate (Delegate d)
387 AddTypeContainer (d);
390 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
392 if (ordered_explicit_member_list == null) {
393 ordered_explicit_member_list = new List<MemberCore> ();
394 ordered_member_list = new List<MemberCore> ();
398 if (Kind == MemberKind.Interface) {
399 Report.Error (541, mc.Location,
400 "`{0}': explicit interface declaration can only be declared in a class or struct",
401 mc.GetSignatureForError ());
404 ordered_explicit_member_list.Add (mc);
405 alist.Insert (0, mc);
407 ordered_member_list.Add (mc);
413 public void AddMethod (MethodOrOperator method)
415 if (!AddToContainer (method, method.MemberName.Basename))
419 methods = new List<MemberCore> ();
421 if (method.MemberName.Left != null)
422 AddMemberToList (method, methods, true);
424 AddMemberToList (method, methods, false);
427 public void AddConstructor (Constructor c)
429 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
430 if (!AddToContainer (c, is_static ?
431 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
434 if (is_static && c.ParameterInfo.IsEmpty){
435 if (default_static_constructor != null) {
436 Report.SymbolRelatedToPreviousError (default_static_constructor);
437 Report.Error (111, c.Location,
438 "A member `{0}' is already defined. Rename this member or use different parameter types",
439 c.GetSignatureForError ());
443 default_static_constructor = c;
445 if (c.ParameterInfo.IsEmpty)
446 default_constructor = c;
448 if (instance_constructors == null)
449 instance_constructors = new List<Constructor> ();
451 instance_constructors.Add (c);
455 public bool AddField (FieldBase field)
457 if (!AddMember (field))
461 fields = new List<FieldBase> ();
465 if ((field.ModFlags & Modifiers.STATIC) != 0)
468 if (first_nonstatic_field == null) {
469 first_nonstatic_field = field;
473 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
474 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
475 Report.Warning (282, 3, field.Location,
476 "struct instance field `{0}' found in different declaration from instance field `{1}'",
477 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
482 public void AddProperty (Property prop)
484 if (!AddMember (prop) ||
485 !AddMember (prop.Get) || !AddMember (prop.Set))
488 if (properties == null)
489 properties = new List<MemberCore> ();
491 if (prop.MemberName.Left != null)
492 AddMemberToList (prop, properties, true);
494 AddMemberToList (prop, properties, false);
497 public void AddEvent (Event e)
502 if (e is EventProperty) {
503 if (!AddMember (e.Add))
506 if (!AddMember (e.Remove))
511 events = new List<MemberCore> ();
517 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
519 public void AddIndexer (Indexer i)
521 if (indexers == null)
522 indexers = new List<MemberCore> ();
524 if (i.IsExplicitImpl)
525 AddMemberToList (i, indexers, true);
527 AddMemberToList (i, indexers, false);
530 public void AddOperator (Operator op)
535 if (operators == null)
536 operators = new List<MemberCore> ();
541 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
543 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
545 if (compiler_generated == null)
546 compiler_generated = new List<CompilerGeneratedClass> ();
548 compiler_generated.Add (c);
551 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
553 if (a.Type == pa.DefaultMember) {
554 if (Indexers != null) {
555 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
560 if (a.Type == pa.Required) {
561 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
565 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
568 public override AttributeTargets AttributeTargets {
570 throw new NotSupportedException ();
574 public IList<TypeContainer> Types {
580 public IList<MemberCore> Methods {
586 public IList<MemberCore> Constants {
592 public virtual TypeSpec BaseType {
594 return spec.BaseType;
598 public IList<FieldBase> Fields {
604 public IList<Constructor> InstanceConstructors {
606 return instance_constructors;
610 public IList<MemberCore> Properties {
616 public IList<MemberCore> Events {
622 public IList<MemberCore> Indexers {
628 public IList<MemberCore> Operators {
634 public IList<CompilerGeneratedClass> CompilerGeneratedClasses {
636 return compiler_generated;
640 protected override TypeAttributes TypeAttr {
642 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
646 public int TypeParametersCount {
648 return MemberName.Arity;
652 TypeParameterSpec[] ITypeDefinition.TypeParameters {
654 // TODO MemberCache: this is going to hurt
655 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
659 public string GetAttributeDefaultMember ()
661 return indexers == null ? DefaultIndexerName : indexer_name;
664 public bool IsComImport {
666 if (OptAttributes == null)
669 return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
673 string ITypeDefinition.Namespace {
675 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
679 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
681 if ((field.ModFlags & Modifiers.STATIC) != 0){
682 if (initialized_static_fields == null) {
683 PartialContainer.HasStaticFieldInitializer = true;
684 initialized_static_fields = new List<FieldInitializer> (4);
687 initialized_static_fields.Add (expression);
689 if (initialized_fields == null)
690 initialized_fields = new List<FieldInitializer> (4);
692 initialized_fields.Add (expression);
696 public void ResolveFieldInitializers (BlockContext ec)
698 if (partial_parts != null) {
699 foreach (TypeContainer part in partial_parts) {
700 part.DoResolveFieldInitializers (ec);
703 DoResolveFieldInitializers (ec);
706 void DoResolveFieldInitializers (BlockContext ec)
709 if (initialized_static_fields == null)
712 bool has_complex_initializer = !RootContext.Optimize;
714 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
715 for (i = 0; i < initialized_static_fields.Count; ++i) {
716 FieldInitializer fi = initialized_static_fields [i];
717 ExpressionStatement s = fi.ResolveStatement (ec);
719 s = EmptyExpressionStatement.Instance;
720 } else if (fi.IsComplexInitializer) {
721 has_complex_initializer |= true;
727 for (i = 0; i < initialized_static_fields.Count; ++i) {
728 FieldInitializer fi = initialized_static_fields [i];
730 // Need special check to not optimize code like this
731 // static int a = b = 5;
734 if (!has_complex_initializer && fi.IsDefaultInitializer)
737 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
743 if (initialized_fields == null)
746 for (int i = 0; i < initialized_fields.Count; ++i) {
747 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
748 ExpressionStatement s = fi.ResolveStatement (ec);
753 // Field is re-initialized to its default value => removed
755 if (fi.IsDefaultInitializer && RootContext.Optimize)
758 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
762 public override string DocComment {
774 public PendingImplementation PendingImplementations {
775 get { return pending; }
778 public TypeSpec GetAttributeCoClass ()
780 if (OptAttributes == null)
783 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CoClass);
787 return a.GetCoClassAttributeValue ();
790 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
793 if (OptAttributes != null) {
794 a = OptAttributes.Search (pa);
798 if (BaseType != TypeManager.attribute_type)
799 return BaseType.GetAttributeUsage (pa);
804 return a.GetAttributeUsageAttribute ();
807 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
809 // FIXME: get rid of partial_parts and store lists of bases of each part here
810 // assumed, not verified: 'part' is in 'partial_parts'
811 ((TypeContainer) part).type_bases = bases;
815 /// This function computes the Base class and also the
816 /// list of interfaces that the class or struct @c implements.
818 /// The return value is an array (might be null) of
819 /// interfaces implemented (as Types).
821 /// The @base_class argument is set to the base object or null
822 /// if this is `System.Object'.
824 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
827 if (type_bases == null)
830 int count = type_bases.Count;
831 TypeExpr [] ifaces = null;
832 var base_context = new BaseContext (this);
833 for (int i = 0, j = 0; i < count; i++){
834 FullNamedExpression fne = type_bases [i];
836 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
837 if (fne_resolved == null)
840 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
841 if (fne_resolved.Type == InternalType.Dynamic)
842 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
843 GetSignatureForError ());
845 base_class = fne_resolved;
850 ifaces = new TypeExpr [count - i];
852 if (fne_resolved.Type.IsInterface) {
853 for (int ii = 0; ii < j; ++ii) {
854 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
855 Report.Error (528, Location, "`{0}' is already listed in interface list",
856 fne_resolved.GetSignatureForError ());
861 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
862 Report.Error (61, fne.Location,
863 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
864 fne_resolved.GetSignatureForError (), GetSignatureForError ());
867 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
868 if (Kind != MemberKind.Class) {
869 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
870 } else if (base_class != null)
871 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
872 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
874 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
875 GetSignatureForError (), fne_resolved.GetSignatureForError ());
879 ifaces [j++] = fne_resolved;
885 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
887 var ifaces = new List<TypeExpr> (0);
888 if (iface_exprs != null)
889 ifaces.AddRange (iface_exprs);
891 foreach (TypeContainer part in partial_parts) {
892 TypeExpr new_base_class;
893 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
894 if (new_base_class != TypeManager.system_object_expr) {
895 if (base_class == TypeManager.system_object_expr)
896 base_class = new_base_class;
898 if (new_base_class != null && !TypeManager.IsEqual (new_base_class.Type, base_class.Type)) {
899 Report.SymbolRelatedToPreviousError (base_class.Location, "");
900 Report.Error (263, part.Location,
901 "Partial declarations of `{0}' must not specify different base classes",
902 part.GetSignatureForError ());
909 if (new_ifaces == null)
912 foreach (TypeExpr iface in new_ifaces) {
913 if (ifaces.Contains (iface))
920 if (ifaces.Count == 0)
923 return ifaces.ToArray ();
927 // Checks that some operators come in pairs:
933 // They are matched based on the return type and the argument types
935 void CheckPairedOperators ()
937 bool has_equality_or_inequality = false;
938 var operators = this.operators.ToArray ();
939 bool[] has_pair = new bool[operators.Length];
941 for (int i = 0; i < operators.Length; ++i) {
942 if (operators[i] == null)
945 Operator o_a = (Operator) operators[i];
946 Operator.OpType o_type = o_a.OperatorType;
947 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
948 has_equality_or_inequality = true;
950 Operator.OpType matching_type = o_a.GetMatchingOperator ();
951 if (matching_type == Operator.OpType.TOP) {
956 for (int ii = 0; ii < operators.Length; ++ii) {
957 Operator o_b = (Operator) operators[ii];
958 if (o_b == null || o_b.OperatorType != matching_type)
961 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
964 if (!TypeSpecComparer.Default.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
970 // Used to ignore duplicate user conversions
976 for (int i = 0; i < operators.Length; ++i) {
977 if (operators[i] == null || has_pair[i])
980 Operator o = (Operator) operators [i];
981 Report.Error (216, o.Location,
982 "The operator `{0}' requires a matching operator `{1}' to also be defined",
983 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
986 if (has_equality_or_inequality) {
987 if (Methods == null || !HasEquals)
988 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
989 GetSignatureForError ());
991 if (Methods == null || !HasGetHashCode)
992 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
993 GetSignatureForError ());
997 bool CreateTypeBuilder ()
1000 // Sets .size to 1 for structs with no instance fields
1002 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1005 if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
1006 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1010 ModuleBuilder builder = Module.Compiled.Builder;
1011 TypeBuilder = builder.DefineType (Name, TypeAttr, null, type_size);
1013 TypeBuilder builder = Parent.TypeBuilder;
1015 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1018 spec.SetMetaInfo (TypeBuilder);
1019 spec.MemberCache = new MemberCache (this);
1020 spec.DeclaringType = Parent.CurrentType;
1023 Parent.MemberCache.AddMember (spec);
1026 string[] param_names = new string[TypeParameters.Length];
1027 for (int i = 0; i < TypeParameters.Length; i++)
1028 param_names [i] = TypeParameters[i].Name;
1030 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1032 int offset = CurrentTypeParametersStartIndex;
1033 for (int i = offset; i < all_tp_builders.Length; i++) {
1034 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1041 bool DefineBaseTypes ()
1043 iface_exprs = ResolveBaseTypes (out base_type);
1044 if (partial_parts != null) {
1045 iface_exprs = GetNormalPartialBases (ref base_type);
1048 var cycle = CheckRecursiveDefinition (this);
1049 if (cycle != null) {
1050 Report.SymbolRelatedToPreviousError (cycle);
1051 if (this is Interface) {
1052 Report.Error (529, Location,
1053 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1054 GetSignatureForError (), cycle.GetSignatureForError ());
1056 Report.Error (146, Location,
1057 "Circular base class dependency involving `{0}' and `{1}'",
1058 GetSignatureForError (), cycle.GetSignatureForError ());
1064 if (iface_exprs != null) {
1065 foreach (TypeExpr iface in iface_exprs) {
1066 // Prevents a crash, the interface might not have been resolved: 442144
1070 var iface_type = iface.Type;
1072 if (!spec.AddInterface (iface_type))
1075 if (iface_type.IsGeneric && spec.Interfaces != null) {
1076 foreach (var prev_iface in iface_exprs) {
1077 if (prev_iface == iface)
1080 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1083 Report.Error (695, Location,
1084 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1085 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1089 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1091 // Ensure the base is always setup
1092 var compiled_iface = iface_type.MemberDefinition as Interface;
1093 if (compiled_iface != null) {
1094 // TODO: Need DefineBaseType only
1095 compiled_iface.DefineType ();
1098 if (iface_type.Interfaces != null) {
1099 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1100 for (int i = 0; i < base_ifaces.Count; ++i) {
1101 var ii_iface_type = base_ifaces[i];
1102 if (spec.AddInterface (ii_iface_type)) {
1103 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1105 if (ii_iface_type.Interfaces != null)
1106 base_ifaces.AddRange (ii_iface_type.Interfaces);
1113 if (Kind == MemberKind.Interface) {
1114 spec.BaseType = TypeManager.object_type;
1119 if (base_type != null)
1120 base_ts = base_type.Type;
1121 else if (spec.IsStruct)
1122 base_ts = TypeManager.value_type;
1123 else if (spec.IsEnum)
1124 base_ts = TypeManager.enum_type;
1125 else if (spec.IsDelegate)
1126 base_ts = TypeManager.multicast_delegate_type;
1130 if (base_ts != null) {
1131 spec.BaseType = base_ts;
1133 // Set base type after type creation
1134 TypeBuilder.SetParent (base_ts.GetMetaInfo ());
1140 public virtual void DefineConstants ()
1142 if (constants != null) {
1143 foreach (Const c in constants) {
1148 if (instance_constructors != null) {
1149 foreach (MethodCore m in instance_constructors) {
1150 var p = m.ParameterInfo;
1151 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1152 var rc = new ResolveContext (m);
1153 p.ResolveDefaultValues (rc);
1158 if (methods != null) {
1159 foreach (MethodCore m in methods) {
1160 var p = m.ParameterInfo;
1161 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1162 var rc = new ResolveContext (m);
1163 p.ResolveDefaultValues (rc);
1168 if (indexers != null) {
1169 foreach (Indexer i in indexers) {
1170 var p = i.ParameterInfo;
1171 if (p[p.Count - 1].HasDefaultValue) {
1172 var rc = new ResolveContext (i);
1173 p.ResolveDefaultValues (rc);
1178 if (types != null) {
1179 foreach (var t in types)
1180 t.DefineConstants ();
1185 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1187 public TypeBuilder CreateType ()
1189 if (TypeBuilder != null)
1195 if (!CreateTypeBuilder ()) {
1200 if (partial_parts != null) {
1201 foreach (TypeContainer part in partial_parts) {
1203 part.current_type = current_type;
1204 part.TypeBuilder = TypeBuilder;
1208 if (Types != null) {
1209 foreach (TypeContainer tc in Types) {
1210 if (tc.CreateType () == null) {
1220 public override TypeBuilder DefineType ()
1227 type_defined = true;
1229 if (!DefineBaseTypes ()) {
1234 if (!DefineNestedTypes ()) {
1242 public override void SetParameterInfo (List<Constraints> constraints_list)
1244 base.SetParameterInfo (constraints_list);
1246 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1249 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1250 for (int i = 0; i < tc_names.Length; ++i) {
1251 if (tc_names [i].Name != type_params [i].Name) {
1252 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1253 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1254 GetSignatureForError ());
1258 if (tc_names [i].Variance != type_params [i].Variance) {
1259 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1260 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1261 GetSignatureForError ());
1268 // Replaces normal spec with predefined one when compiling corlib
1269 // and this type container defines predefined type
1271 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1276 void UpdateTypeParameterConstraints (TypeContainer part)
1278 TypeParameter[] current_params = type_params;
1279 for (int i = 0; i < current_params.Length; i++) {
1280 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1283 Report.SymbolRelatedToPreviousError (Location, "");
1284 Report.Error (265, part.Location,
1285 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1286 GetSignatureForError (), current_params [i].GetSignatureForError ());
1290 public bool ResolveTypeParameters ()
1292 if (!DoResolveTypeParameters ())
1295 if (types != null) {
1296 foreach (var type in types)
1297 if (!type.ResolveTypeParameters ())
1301 if (compiler_generated != null) {
1302 foreach (CompilerGeneratedClass c in compiler_generated)
1303 if (!c.ResolveTypeParameters ())
1310 protected virtual bool DoResolveTypeParameters ()
1312 if (CurrentTypeParameters == null)
1315 if (PartialContainer != this)
1316 throw new InternalErrorException ();
1318 var base_context = new BaseContext (this);
1319 foreach (TypeParameter type_param in CurrentTypeParameters) {
1320 if (!type_param.ResolveConstraints (base_context)) {
1326 if (partial_parts != null) {
1327 foreach (TypeContainer part in partial_parts)
1328 UpdateTypeParameterConstraints (part);
1334 protected virtual bool DefineNestedTypes ()
1336 if (Types != null) {
1337 foreach (TypeContainer tc in Types)
1338 if (tc.DefineType () == null)
1345 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1347 if (InTransit != null)
1352 if (base_type != null && base_type.Type != null) {
1353 var ptc = base_type.Type.MemberDefinition as TypeContainer;
1354 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1355 return base_type.Type;
1358 if (iface_exprs != null) {
1359 foreach (TypeExpr iface in iface_exprs) {
1360 // the interface might not have been resolved, prevents a crash, see #442144
1363 var ptc = iface.Type.MemberDefinition as Interface;
1364 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1369 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1377 /// Populates our TypeBuilder with fields and methods
1379 public sealed override bool Define ()
1381 if (members_defined)
1382 return members_defined_ok;
1384 members_defined_ok = DoDefineMembers ();
1385 members_defined = true;
1387 if (types != null) {
1388 foreach (var nested in types)
1392 return members_defined_ok;
1395 protected virtual bool DoDefineMembers ()
1397 if (iface_exprs != null) {
1398 foreach (TypeExpr iface in iface_exprs) {
1399 var iface_type = iface.Type;
1401 // Ensure the base is always setup
1402 var compiled_iface = iface_type.MemberDefinition as Interface;
1403 if (compiled_iface != null)
1404 compiled_iface.Define ();
1406 if (Kind == MemberKind.Interface)
1407 MemberCache.AddInterface (iface_type);
1409 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1410 if (oa != null && !IsObsolete)
1411 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1413 GenericTypeExpr ct = iface as GenericTypeExpr;
1415 // TODO: passing `this' is wrong, should be base type iface instead
1416 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1418 ct.CheckConstraints (this);
1420 if (ct.HasDynamicArguments ()) {
1421 Report.Error (1966, iface.Location,
1422 "`{0}': cannot implement a dynamic interface `{1}'",
1423 GetSignatureForError (), iface.GetSignatureForError ());
1430 if (base_type != null) {
1431 ObsoleteAttribute obsolete_attr = base_type.Type.GetAttributeObsolete ();
1432 if (obsolete_attr != null && !IsObsolete)
1433 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1435 var ct = base_type as GenericTypeExpr;
1437 ct.CheckConstraints (this);
1439 var baseContainer = base_type.Type.MemberDefinition as ClassOrStruct;
1440 if (baseContainer != null) {
1441 baseContainer.Define ();
1444 // It can trigger define of this type (for generic types only)
1446 if (HasMembersDefined)
1451 if (type_params != null) {
1452 foreach (var tp in type_params) {
1453 tp.CheckGenericConstraints ();
1458 MemberSpec candidate;
1459 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1460 if (conflict_symbol == null && candidate == null) {
1461 if ((ModFlags & Modifiers.NEW) != 0)
1462 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1463 GetSignatureForError ());
1465 if ((ModFlags & Modifiers.NEW) == 0) {
1466 if (candidate == null)
1467 candidate = conflict_symbol;
1469 Report.SymbolRelatedToPreviousError (candidate);
1470 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1471 GetSignatureForError (), candidate.GetSignatureForError ());
1476 DefineContainerMembers (constants);
1477 DefineContainerMembers (fields);
1479 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1480 pending = PendingImplementation.GetPendingImplementations (this);
1482 if (requires_delayed_unmanagedtype_check) {
1483 requires_delayed_unmanagedtype_check = false;
1484 foreach (FieldBase f in fields) {
1485 if (f.MemberType != null && f.MemberType.IsPointer)
1486 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1492 // Constructors are not in the defined_names array
1494 DefineContainerMembers (instance_constructors);
1496 DefineContainerMembers (events);
1497 DefineContainerMembers (ordered_explicit_member_list);
1498 DefineContainerMembers (ordered_member_list);
1500 if (operators != null) {
1501 DefineContainerMembers (operators);
1502 CheckPairedOperators ();
1505 ComputeIndexerName();
1506 CheckEqualsAndGetHashCode();
1511 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1514 foreach (MemberCore mc in mcal) {
1517 } catch (Exception e) {
1518 throw new InternalErrorException (mc, e);
1524 protected virtual void ComputeIndexerName ()
1526 if (indexers == null)
1529 string class_indexer_name = null;
1532 // If there's both an explicit and an implicit interface implementation, the
1533 // explicit one actually implements the interface while the other one is just
1534 // a normal indexer. See bug #37714.
1537 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1538 foreach (Indexer i in indexers) {
1539 if (i.InterfaceType != null) {
1540 if (seen_normal_indexers)
1541 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1545 seen_normal_indexers = true;
1547 if (class_indexer_name == null) {
1548 class_indexer_name = i.ShortName;
1552 if (i.ShortName != class_indexer_name)
1553 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");
1556 if (class_indexer_name != null)
1557 indexer_name = class_indexer_name;
1560 void EmitIndexerName ()
1562 if (!seen_normal_indexers)
1565 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1566 if (pa.Constructor == null &&
1567 !pa.ResolveConstructor (Location, TypeManager.string_type))
1570 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1571 TypeBuilder.SetCustomAttribute (cb);
1574 protected virtual void CheckEqualsAndGetHashCode ()
1576 if (methods == null)
1579 if (HasEquals && !HasGetHashCode) {
1580 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1584 // Indicated whether container has StructLayout attribute set Explicit
1585 public bool HasExplicitLayout {
1586 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1587 set { caching_flags |= Flags.HasExplicitLayout; }
1590 public bool HasStructLayout {
1591 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1592 set { caching_flags |= Flags.HasStructLayout; }
1595 public MemberCache MemberCache {
1597 return spec.MemberCache;
1601 void CheckMemberUsage (List<MemberCore> al, string member_type)
1606 foreach (MemberCore mc in al) {
1607 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1610 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1611 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1616 public virtual void VerifyMembers ()
1619 // Check for internal or private fields that were never assigned
1621 if (Report.WarningLevel >= 3) {
1622 if (RootContext.EnhancedWarnings) {
1623 CheckMemberUsage (properties, "property");
1624 CheckMemberUsage (methods, "method");
1625 CheckMemberUsage (constants, "constant");
1628 if (fields != null){
1629 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1630 foreach (FieldBase f in fields) {
1631 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1632 if (is_type_exposed)
1639 if ((f.caching_flags & Flags.IsAssigned) == 0)
1640 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1642 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1643 f.GetSignatureForError ());
1649 // Only report 649 on level 4
1651 if (Report.WarningLevel < 4)
1654 if ((f.caching_flags & Flags.IsAssigned) != 0)
1658 // Don't be pendatic over serializable attributes
1660 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1663 Constant c = New.Constantify (f.MemberType);
1664 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1665 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1671 public override void Emit ()
1673 if (all_tp_builders != null) {
1674 int current_starts_index = CurrentTypeParametersStartIndex;
1675 for (int i = 0; i < all_tp_builders.Length; i++) {
1676 if (i < current_starts_index) {
1677 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1679 CurrentTypeParameters [i - current_starts_index].Emit ();
1684 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1685 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1690 // TODO: move to ClassOrStruct
1691 void EmitConstructors ()
1693 if (instance_constructors == null)
1696 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1697 bool has_compliant_args = false;
1699 foreach (Constructor c in instance_constructors) {
1703 catch (Exception e) {
1704 throw new InternalErrorException (c, e);
1707 if (has_compliant_args)
1710 has_compliant_args = c.HasCompliantArgs;
1712 if (!has_compliant_args)
1713 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1715 foreach (Constructor c in instance_constructors) {
1719 catch (Exception e) {
1720 throw new InternalErrorException (c, e);
1727 /// Emits the code, this step is performed after all
1728 /// the types, enumerations, constructors
1730 public virtual void EmitType ()
1732 if (OptAttributes != null)
1733 OptAttributes.Emit ();
1737 EmitConstructors ();
1739 if (constants != null)
1740 foreach (Const con in constants)
1743 if (default_static_constructor != null)
1744 default_static_constructor.Emit ();
1746 if (operators != null)
1747 foreach (Operator o in operators)
1750 if (properties != null)
1751 foreach (Property p in properties)
1754 if (indexers != null) {
1755 foreach (Indexer indx in indexers)
1760 if (events != null){
1761 foreach (Event e in Events)
1765 if (methods != null) {
1766 for (int i = 0; i < methods.Count; ++i)
1767 ((MethodOrOperator) methods [i]).Emit ();
1771 foreach (FieldBase f in fields)
1774 if (types != null) {
1775 foreach (TypeContainer t in types)
1779 if (pending != null)
1780 pending.VerifyPendingMethods (Report);
1782 if (Report.Errors > 0)
1785 if (compiler_generated != null) {
1786 for (int i = 0; i < compiler_generated.Count; ++i)
1787 compiler_generated [i].EmitType ();
1791 public void CloseType ()
1793 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1796 // Close base type container first to avoid TypeLoadException
1797 if (spec.BaseType != null) {
1798 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1804 caching_flags |= Flags.CloseTypeCreated;
1805 TypeBuilder.CreateType ();
1806 } catch (TypeLoadException){
1808 // This is fine, the code still created the type
1810 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1811 // Console.WriteLine (e.Message);
1812 } catch (Exception e) {
1813 throw new InternalErrorException (this, e);
1817 foreach (TypeContainer tc in Types)
1821 if (compiler_generated != null)
1822 foreach (CompilerGeneratedClass c in compiler_generated)
1827 initialized_fields = null;
1828 initialized_static_fields = null;
1830 ordered_explicit_member_list = null;
1831 ordered_member_list = null;
1836 compiler_generated = null;
1837 default_constructor = null;
1838 default_static_constructor = null;
1840 OptAttributes = null;
1844 // Performs the validation on a Method's modifiers (properties have
1845 // the same properties).
1847 public bool MethodModifiersValid (MemberCore mc)
1849 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1850 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1851 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1853 var flags = mc.ModFlags;
1856 // At most one of static, virtual or override
1858 if ((flags & Modifiers.STATIC) != 0){
1859 if ((flags & vao) != 0){
1860 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1861 mc.GetSignatureForError ());
1866 if (Kind == MemberKind.Struct){
1867 if ((flags & va) != 0){
1868 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1873 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1874 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1875 mc.GetSignatureForError ());
1880 // If the declaration includes the abstract modifier, then the
1881 // declaration does not include static, virtual or extern
1883 if ((flags & Modifiers.ABSTRACT) != 0){
1884 if ((flags & Modifiers.EXTERN) != 0){
1886 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1890 if ((flags & Modifiers.SEALED) != 0) {
1891 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1895 if ((flags & Modifiers.VIRTUAL) != 0){
1896 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1900 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1901 Report.SymbolRelatedToPreviousError (this);
1902 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1903 mc.GetSignatureForError (), GetSignatureForError ());
1908 if ((flags & Modifiers.PRIVATE) != 0){
1909 if ((flags & vao) != 0){
1910 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1915 if ((flags & Modifiers.SEALED) != 0){
1916 if ((flags & Modifiers.OVERRIDE) == 0){
1917 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1925 public Constructor DefaultStaticConstructor {
1926 get { return default_static_constructor; }
1929 protected override bool VerifyClsCompliance ()
1931 if (!base.VerifyClsCompliance ())
1934 // Check this name against other containers
1935 NamespaceEntry.NS.VerifyClsCompliance ();
1937 // Check all container names for user classes
1938 if (Kind != MemberKind.Delegate)
1939 MemberCache.VerifyClsCompliance (Definition, Report);
1941 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1942 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1943 GetSignatureForError (), BaseType.GetSignatureForError ());
1949 /// Performs checks for an explicit interface implementation. First it
1950 /// checks whether the `interface_type' is a base inteface implementation.
1951 /// Then it checks whether `name' exists in the interface type.
1953 public bool VerifyImplements (InterfaceMemberBase mb)
1955 var ifaces = spec.Interfaces;
1956 if (ifaces != null) {
1957 foreach (TypeSpec t in ifaces){
1958 if (TypeManager.IsEqual (t, mb.InterfaceType))
1963 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1964 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1965 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1970 // Used for visiblity checks to tests whether this definition shares
1971 // base type baseType, it does member-definition search
1973 public bool IsBaseTypeDefinition (TypeSpec baseType)
1975 // RootContext check
1976 if (TypeBuilder == null)
1981 if (type.MemberDefinition == baseType.MemberDefinition)
1984 type = type.BaseType;
1985 } while (type != null);
1990 public MemberCache LoadMembers (TypeSpec declaringType)
1992 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1995 public void Mark_HasEquals ()
1997 cached_method |= CachedMethods.Equals;
2000 public void Mark_HasGetHashCode ()
2002 cached_method |= CachedMethods.GetHashCode;
2006 /// Method container contains Equals method
2008 public bool HasEquals {
2010 return (cached_method & CachedMethods.Equals) != 0;
2015 /// Method container contains GetHashCode method
2017 public bool HasGetHashCode {
2019 return (cached_method & CachedMethods.GetHashCode) != 0;
2023 public bool HasStaticFieldInitializer {
2025 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2029 cached_method |= CachedMethods.HasStaticFieldInitializer;
2031 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2036 // Generates xml doc comments (if any), and if required,
2037 // handle warning report.
2039 internal override void GenerateDocComment (DeclSpace ds)
2041 DocUtil.GenerateTypeDocComment (this, ds, Report);
2044 public override string DocCommentHeader {
2045 get { return "T:"; }
2049 public abstract class ClassOrStruct : TypeContainer
2051 Dictionary<SecurityAction, PermissionSet> declarative_security;
2053 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2054 MemberName name, Attributes attrs, MemberKind kind)
2055 : base (ns, parent, name, attrs, kind)
2059 protected override bool AddToContainer (MemberCore symbol, string name)
2061 if (name == MemberName.Name) {
2062 if (symbol is TypeParameter) {
2063 Report.Error (694, symbol.Location,
2064 "Type parameter `{0}' has same name as containing type, or method",
2065 symbol.GetSignatureForError ());
2069 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2070 if (imb == null || !imb.IsExplicitImpl) {
2071 Report.SymbolRelatedToPreviousError (this);
2072 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2073 symbol.GetSignatureForError ());
2078 return base.AddToContainer (symbol, name);
2081 public override void VerifyMembers ()
2083 base.VerifyMembers ();
2085 if ((events != null) && Report.WarningLevel >= 3) {
2086 foreach (Event e in events){
2087 // Note: The event can be assigned from same class only, so we can report
2088 // this warning for all accessibility modes
2089 if ((e.caching_flags & Flags.IsUsed) == 0)
2090 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2095 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2097 if (a.IsValidSecurityAttribute ()) {
2098 if (declarative_security == null)
2099 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2101 a.ExtractSecurityPermissionSet (declarative_security);
2105 if (a.Type == pa.StructLayout) {
2106 PartialContainer.HasStructLayout = true;
2108 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2109 PartialContainer.HasExplicitLayout = true;
2112 if (a.Type == pa.Dynamic) {
2113 a.Error_MisusedDynamicAttribute ();
2117 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2121 /// Defines the default constructors
2123 protected void DefineDefaultConstructor (bool is_static)
2125 // The default instance constructor is public
2126 // If the class is abstract, the default constructor is protected
2127 // The default static constructor is private
2131 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2133 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2136 Constructor c = new Constructor (this, MemberName.Name, mods,
2137 null, ParametersCompiled.EmptyReadOnlyParameters,
2138 new GeneratedBaseInitializer (Location),
2142 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2145 protected override bool DoDefineMembers ()
2147 CheckProtectedModifier ();
2149 base.DoDefineMembers ();
2151 if (default_static_constructor != null)
2152 default_static_constructor.Define ();
2157 public override void Emit ()
2159 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2160 DefineDefaultConstructor (true);
2161 default_static_constructor.Define ();
2166 if (declarative_security != null) {
2167 foreach (var de in declarative_security) {
2168 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2173 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2175 DeclSpace top_level = Parent;
2176 if (top_level != null) {
2177 while (top_level.Parent != null)
2178 top_level = top_level.Parent;
2180 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2181 if (candidates != null)
2182 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2185 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2188 protected override TypeAttributes TypeAttr {
2190 if (default_static_constructor == null)
2191 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2193 return base.TypeAttr;
2199 // TODO: should be sealed
2200 public class Class : ClassOrStruct {
2201 const Modifiers AllowedModifiers =
2204 Modifiers.PROTECTED |
2205 Modifiers.INTERNAL |
2207 Modifiers.ABSTRACT |
2212 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2214 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2216 : base (ns, parent, name, attrs, MemberKind.Class)
2218 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2219 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2220 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2222 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2223 Report.FeatureIsNotAvailable (Location, "static classes");
2227 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2229 if (part.Name == "System.Object")
2230 Report.Error (537, part.Location,
2231 "The class System.Object cannot have a base class or implement an interface.");
2232 base.AddBasesForPart (part, bases);
2235 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2237 if (a.Type == pa.AttributeUsage) {
2238 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2239 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2243 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2244 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2248 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2249 a.Error_MissingGuidAttribute ();
2253 if (a.Type == pa.Extension) {
2254 a.Error_MisusedExtensionAttribute ();
2258 if (a.Type.IsConditionallyExcluded (Location))
2261 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2264 public override AttributeTargets AttributeTargets {
2266 return AttributeTargets.Class;
2270 protected override void DefineContainerMembers (System.Collections.IList list)
2276 base.DefineContainerMembers (list);
2280 foreach (MemberCore m in list) {
2281 if (m is Operator) {
2282 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2286 if (m is Destructor) {
2287 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2292 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2296 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2299 if (m is Constructor) {
2300 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2304 Method method = m as Method;
2305 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2306 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2310 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2313 base.DefineContainerMembers (list);
2316 protected override bool DoDefineMembers ()
2318 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2319 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2322 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2323 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2326 if (InstanceConstructors == null && !IsStatic)
2327 DefineDefaultConstructor (false);
2329 return base.DoDefineMembers ();
2332 public override void Emit ()
2336 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2337 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2340 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2342 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2344 if (base_class == null) {
2345 if (spec != TypeManager.object_type)
2346 base_class = TypeManager.system_object_expr;
2348 var base_type = base_class.Type;
2350 if (base_type.IsGenericParameter){
2351 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2352 GetSignatureForError (), base_type.GetSignatureForError ());
2353 } else if (IsGeneric && base_type.IsAttribute) {
2354 Report.Error (698, base_class.Location,
2355 "A generic type cannot derive from `{0}' because it is an attribute class",
2356 base_class.GetSignatureForError ());
2357 } else if (base_type.IsStatic) {
2358 Report.SymbolRelatedToPreviousError (base_class.Type);
2359 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2360 GetSignatureForError (), base_type.GetSignatureForError ());
2361 } else if (base_type.IsSealed){
2362 Report.SymbolRelatedToPreviousError (base_class.Type);
2363 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2364 GetSignatureForError (), base_type.GetSignatureForError ());
2367 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2368 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2369 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2370 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2371 GetSignatureForError (), base_type.GetSignatureForError ());
2372 base_class = TypeManager.system_object_expr;
2375 if (!IsAccessibleAs (base_type)) {
2376 Report.SymbolRelatedToPreviousError (base_type);
2377 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2378 base_type.GetSignatureForError (), GetSignatureForError ());
2382 if (PartialContainer.IsStatic) {
2383 if (base_class.Type != TypeManager.object_type) {
2384 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2385 GetSignatureForError (), base_class.GetSignatureForError ());
2389 if (ifaces != null) {
2390 foreach (TypeExpr t in ifaces)
2391 Report.SymbolRelatedToPreviousError (t.Type);
2392 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2399 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2400 /// Valid only for attribute classes.
2401 public override string[] ConditionalConditions ()
2403 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2406 caching_flags &= ~Flags.Excluded_Undetected;
2408 if (OptAttributes == null)
2411 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2415 string[] conditions = new string[attrs.Length];
2416 for (int i = 0; i < conditions.Length; ++i)
2417 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2419 caching_flags |= Flags.Excluded;
2424 // FIXME: How do we deal with the user specifying a different
2427 protected override TypeAttributes TypeAttr {
2429 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2431 ta |= StaticClassAttribute;
2437 public sealed class Struct : ClassOrStruct {
2439 bool is_unmanaged, has_unmanaged_check_done;
2443 // Modifiers allowed in a struct declaration
2445 const Modifiers AllowedModifiers =
2448 Modifiers.PROTECTED |
2449 Modifiers.INTERNAL |
2453 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2454 Modifiers mod, Attributes attrs)
2455 : base (ns, parent, name, attrs, MemberKind.Struct)
2457 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2458 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2459 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2462 public override AttributeTargets AttributeTargets {
2464 return AttributeTargets.Struct;
2468 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2470 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2473 // When struct constains fixed fixed and struct layout has explicitly
2474 // set CharSet, its value has to be propagated to compiler generated
2475 // fixed field types
2477 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2478 for (int i = 0; i < Fields.Count; ++i) {
2479 FixedField ff = Fields [i] as FixedField;
2481 ff.SetCharSet (TypeBuilder.Attributes);
2486 bool CheckStructCycles (Struct s)
2488 if (s.Fields == null)
2495 foreach (FieldBase field in s.Fields) {
2496 TypeSpec ftype = field.Spec.MemberType;
2497 if (!ftype.IsStruct)
2500 if (ftype is PredefinedTypeSpec)
2503 foreach (var targ in ftype.TypeArguments) {
2504 if (!CheckFieldTypeCycle (targ)) {
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 if ((field.IsStatic && !ftype.IsGeneric))
2515 if (!CheckFieldTypeCycle (ftype)) {
2516 Report.Error (523, field.Location,
2517 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2518 field.GetSignatureForError (), ftype.GetSignatureForError ());
2523 s.InTransit = false;
2527 bool CheckFieldTypeCycle (TypeSpec ts)
2529 var fts = ts.MemberDefinition as Struct;
2533 return CheckStructCycles (fts);
2536 public override void Emit ()
2538 CheckStructCycles (this);
2543 public override bool IsUnmanagedType ()
2548 if (has_unmanaged_check_done)
2549 return is_unmanaged;
2551 if (requires_delayed_unmanagedtype_check)
2554 requires_delayed_unmanagedtype_check = true;
2556 foreach (FieldBase f in fields) {
2560 // It can happen when recursive unmanaged types are defined
2561 // struct S { S* s; }
2562 TypeSpec mt = f.MemberType;
2567 while (mt.IsPointer)
2568 mt = TypeManager.GetElementType (mt);
2570 if (mt.MemberDefinition == this) {
2571 for (var p = Parent; p != null; p = p.Parent) {
2572 if (p.Kind == MemberKind.Class) {
2573 has_unmanaged_check_done = true;
2580 if (TypeManager.IsUnmanagedType (mt))
2583 has_unmanaged_check_done = true;
2587 has_unmanaged_check_done = true;
2588 is_unmanaged = true;
2592 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2594 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2595 base_class = TypeManager.system_valuetype_expr;
2599 protected override TypeAttributes TypeAttr {
2601 const TypeAttributes DefaultTypeAttributes =
2602 TypeAttributes.SequentialLayout |
2603 TypeAttributes.Sealed;
2605 return base.TypeAttr | DefaultTypeAttributes;
2609 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2611 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2612 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2613 field.GetSignatureForError ());
2616 base.RegisterFieldForInitialization (field, expression);
2624 public sealed class Interface : TypeContainer {
2627 /// Modifiers allowed in a class declaration
2629 public const Modifiers AllowedModifiers =
2632 Modifiers.PROTECTED |
2633 Modifiers.INTERNAL |
2637 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2639 : base (ns, parent, name, attrs, MemberKind.Interface)
2641 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2643 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2644 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2647 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2649 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2650 a.Error_MissingGuidAttribute ();
2654 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2658 public override AttributeTargets AttributeTargets {
2660 return AttributeTargets.Interface;
2664 protected override TypeAttributes TypeAttr {
2666 const TypeAttributes DefaultTypeAttributes =
2667 TypeAttributes.AutoLayout |
2668 TypeAttributes.Abstract |
2669 TypeAttributes.Interface;
2671 return base.TypeAttr | DefaultTypeAttributes;
2675 protected override bool VerifyClsCompliance ()
2677 if (!base.VerifyClsCompliance ())
2680 if (iface_exprs != null) {
2681 foreach (var iface in iface_exprs) {
2682 if (iface.Type.IsCLSCompliant ())
2685 Report.SymbolRelatedToPreviousError (iface.Type);
2686 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2687 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2695 public abstract class InterfaceMemberBase : MemberBase {
2697 // Whether this is an interface member.
2699 public bool IsInterface;
2702 // If true, this is an explicit interface implementation
2704 public bool IsExplicitImpl;
2706 protected bool is_external_implementation;
2709 // The interface type we are explicitly implementing
2711 public TypeSpec InterfaceType;
2714 // The method we're overriding if this is an override method.
2716 protected MethodSpec base_method;
2718 readonly Modifiers explicit_mod_flags;
2719 public MethodAttributes flags;
2721 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2722 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2723 MemberName name, Attributes attrs)
2724 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2727 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2728 IsExplicitImpl = (MemberName.Left != null);
2729 explicit_mod_flags = mod;
2732 protected override bool CheckBase ()
2734 if (!base.CheckBase ())
2737 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2738 CheckForDuplications ();
2743 // For System.Object only
2744 if (Parent.BaseType == null)
2747 MemberSpec candidate;
2748 var base_member = FindBaseMember (out candidate);
2750 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2751 if (base_member == null) {
2752 if (candidate == null) {
2753 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2754 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2755 "object.Finalize()");
2757 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2758 GetSignatureForError (), SimpleName.GetMemberType (this));
2761 Report.SymbolRelatedToPreviousError (candidate);
2763 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2764 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2765 else if (this is PropertyBase)
2766 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2767 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2769 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2770 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2776 if (!CheckOverrideAgainstBase (base_member))
2779 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2781 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2782 Report.SymbolRelatedToPreviousError (base_member);
2783 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2784 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2787 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2788 Report.SymbolRelatedToPreviousError (base_member);
2789 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2790 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2794 base_method = base_member as MethodSpec;
2798 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2799 base_member = candidate;
2801 if (base_member == null) {
2802 if ((ModFlags & Modifiers.NEW) != 0) {
2803 if (base_member == null) {
2804 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2805 GetSignatureForError ());
2809 if ((ModFlags & Modifiers.NEW) == 0) {
2810 ModFlags |= Modifiers.NEW;
2811 Report.SymbolRelatedToPreviousError (base_member);
2812 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2813 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",
2814 GetSignatureForError (), base_member.GetSignatureForError ());
2816 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2817 GetSignatureForError (), base_member.GetSignatureForError ());
2821 if (!IsInterface && base_member.IsAbstract) {
2822 Report.SymbolRelatedToPreviousError (base_member);
2823 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2824 GetSignatureForError (), base_member.GetSignatureForError ());
2831 protected virtual bool CheckForDuplications ()
2833 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2837 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2838 // that have been defined.
2840 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2844 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2845 Report.SymbolRelatedToPreviousError (base_member);
2846 Report.Error (506, Location,
2847 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2848 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2852 // Now we check that the overriden method is not final
2853 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2854 Report.SymbolRelatedToPreviousError (base_member);
2855 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2856 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2860 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2861 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2862 Report.SymbolRelatedToPreviousError (base_member);
2863 if (this is PropertyBasedMember) {
2864 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2865 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2867 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2868 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2876 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2878 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2879 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2881 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2883 // when overriding protected internal, the method can be declared
2884 // protected internal only within the same assembly or assembly
2885 // which has InternalsVisibleTo
2887 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2888 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2890 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2892 // if it's not "protected internal", it must be "protected"
2897 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2899 // protected within the same assembly - an error
2903 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2904 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2906 // protected ok, but other attributes differ - report an error
2913 return thisp == base_classp;
2916 public override bool Define ()
2919 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2920 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2922 flags = MethodAttributes.Public |
2923 MethodAttributes.Abstract |
2924 MethodAttributes.HideBySig |
2925 MethodAttributes.NewSlot |
2926 MethodAttributes.Virtual;
2928 Parent.PartialContainer.MethodModifiersValid (this);
2930 flags = ModifiersExtensions.MethodAttr (ModFlags);
2933 if (IsExplicitImpl) {
2934 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2935 if (iface_texpr == null)
2938 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2939 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2940 GetSignatureForError ());
2943 InterfaceType = iface_texpr.Type;
2945 if (!InterfaceType.IsInterface) {
2946 Report.SymbolRelatedToPreviousError (InterfaceType);
2947 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2948 TypeManager.CSharpName (InterfaceType));
2950 Parent.PartialContainer.VerifyImplements (this);
2953 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2956 return base.Define ();
2959 protected bool DefineParameters (ParametersCompiled parameters)
2961 if (!parameters.Resolve (this))
2965 for (int i = 0; i < parameters.Count; ++i) {
2966 Parameter p = parameters [i];
2968 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2969 p.Warning_UselessOptionalParameter (Report);
2971 if (p.CheckAccessibility (this))
2974 TypeSpec t = parameters.Types [i];
2975 Report.SymbolRelatedToPreviousError (t);
2976 if (this is Indexer)
2977 Report.Error (55, Location,
2978 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2979 TypeManager.CSharpName (t), GetSignatureForError ());
2980 else if (this is Operator)
2981 Report.Error (57, Location,
2982 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2983 TypeManager.CSharpName (t), GetSignatureForError ());
2985 Report.Error (51, Location,
2986 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2987 TypeManager.CSharpName (t), GetSignatureForError ());
2993 public override void Emit()
2995 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2996 // We are more strict than csc and report this as an error because SRE does not allow emit that
2997 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2998 if (this is Constructor) {
2999 Report.Error (824, Location,
3000 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3002 Report.Error (626, Location,
3003 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3004 GetSignatureForError ());
3011 public override bool EnableOverloadChecks (MemberCore overload)
3014 // Two members can differ in their explicit interface
3015 // type parameter only
3017 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3018 if (imb != null && imb.IsExplicitImpl) {
3019 if (IsExplicitImpl) {
3020 caching_flags |= Flags.MethodOverloadsExist;
3025 return IsExplicitImpl;
3028 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3030 Report.SymbolRelatedToPreviousError (base_member);
3031 Report.Error (507, member.Location,
3032 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3033 member.GetSignatureForError (),
3034 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3035 base_member.GetSignatureForError ());
3038 protected void Error_StaticReturnType ()
3040 Report.Error (722, Location,
3041 "`{0}': static types cannot be used as return types",
3042 MemberType.GetSignatureForError ());
3046 /// Gets base method and its return type
3048 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3050 return MemberCache.FindBaseMember (this, out bestCandidate);
3054 // The "short" name of this property / indexer / event. This is the
3055 // name without the explicit interface.
3057 public string ShortName {
3058 get { return MemberName.Name; }
3059 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3063 // Returns full metadata method name
3065 public string GetFullName (MemberName name)
3067 return GetFullName (name.Name);
3070 public string GetFullName (string name)
3072 if (!IsExplicitImpl)
3076 // When dealing with explicit members a full interface type
3077 // name is added to member name to avoid possible name conflicts
3079 // We use CSharpName which gets us full name with benefit of
3080 // replacing predefined names which saves some space and name
3083 return TypeManager.CSharpName (InterfaceType) + "." + name;
3086 protected override bool VerifyClsCompliance ()
3088 if (!base.VerifyClsCompliance ()) {
3092 if (GenericMethod != null)
3093 GenericMethod.VerifyClsCompliance ();
3098 public override bool IsUsed
3100 get { return IsExplicitImpl || base.IsUsed; }
3105 public abstract class MemberBase : MemberCore
3107 protected FullNamedExpression type_expr;
3108 protected TypeSpec member_type;
3110 public readonly DeclSpace ds;
3111 public readonly GenericMethod GenericMethod;
3113 protected MemberBase (DeclSpace parent, GenericMethod generic,
3114 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3115 MemberName name, Attributes attrs)
3116 : base (parent, name, attrs)
3118 this.ds = generic != null ? generic : (DeclSpace) parent;
3119 this.type_expr = type;
3120 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3121 GenericMethod = generic;
3122 if (GenericMethod != null)
3123 GenericMethod.ModFlags = ModFlags;
3127 // Main member define entry
3129 public override bool Define ()
3131 DoMemberTypeIndependentChecks ();
3134 // Returns false only when type resolution failed
3136 if (!ResolveMemberType ())
3139 DoMemberTypeDependentChecks ();
3144 // Any type_name independent checks
3146 protected virtual void DoMemberTypeIndependentChecks ()
3148 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3149 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3150 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3151 GetSignatureForError (), Parent.GetSignatureForError ());
3156 // Any type_name dependent checks
3158 protected virtual void DoMemberTypeDependentChecks ()
3160 // verify accessibility
3161 if (!IsAccessibleAs (MemberType)) {
3162 Report.SymbolRelatedToPreviousError (MemberType);
3163 if (this is Property)
3164 Report.Error (53, Location,
3165 "Inconsistent accessibility: property type `" +
3166 TypeManager.CSharpName (MemberType) + "' is less " +
3167 "accessible than property `" + GetSignatureForError () + "'");
3168 else if (this is Indexer)
3169 Report.Error (54, Location,
3170 "Inconsistent accessibility: indexer return type `" +
3171 TypeManager.CSharpName (MemberType) + "' is less " +
3172 "accessible than indexer `" + GetSignatureForError () + "'");
3173 else if (this is MethodCore) {
3174 if (this is Operator)
3175 Report.Error (56, Location,
3176 "Inconsistent accessibility: return type `" +
3177 TypeManager.CSharpName (MemberType) + "' is less " +
3178 "accessible than operator `" + GetSignatureForError () + "'");
3180 Report.Error (50, Location,
3181 "Inconsistent accessibility: return type `" +
3182 TypeManager.CSharpName (MemberType) + "' is less " +
3183 "accessible than method `" + GetSignatureForError () + "'");
3185 Report.Error (52, Location,
3186 "Inconsistent accessibility: field type `" +
3187 TypeManager.CSharpName (MemberType) + "' is less " +
3188 "accessible than field `" + GetSignatureForError () + "'");
3192 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3193 TypeManager.CheckTypeVariance (MemberType, variance, this);
3196 protected bool IsTypePermitted ()
3198 if (TypeManager.IsSpecialType (MemberType)) {
3199 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3205 protected virtual bool CheckBase ()
3207 CheckProtectedModifier ();
3212 public TypeSpec MemberType {
3213 get { return member_type; }
3216 protected virtual bool ResolveMemberType ()
3218 if (member_type != null)
3219 throw new InternalErrorException ("Multi-resolve");
3221 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3226 // Replace original type name, error reporting can use fully resolved name
3230 member_type = te.Type;