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 var iface_type = iface.Type;
1068 if (!spec.AddInterface (iface_type))
1071 if (iface_type.IsGeneric && spec.Interfaces != null) {
1072 foreach (var prev_iface in iface_exprs) {
1073 if (prev_iface == iface)
1076 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1079 Report.Error (695, Location,
1080 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1081 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1085 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1087 // Ensure the base is always setup
1088 var compiled_iface = iface_type.MemberDefinition as Interface;
1089 if (compiled_iface != null) {
1090 // TODO: Need DefineBaseType only
1091 compiled_iface.DefineType ();
1094 if (iface_type.Interfaces != null) {
1095 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1096 for (int i = 0; i < base_ifaces.Count; ++i) {
1097 var ii_iface_type = base_ifaces[i];
1098 if (spec.AddInterface (ii_iface_type)) {
1099 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1101 if (ii_iface_type.Interfaces != null)
1102 base_ifaces.AddRange (ii_iface_type.Interfaces);
1109 if (Kind == MemberKind.Interface) {
1110 spec.BaseType = TypeManager.object_type;
1115 if (base_type != null)
1116 base_ts = base_type.Type;
1117 else if (spec.IsStruct)
1118 base_ts = TypeManager.value_type;
1119 else if (spec.IsEnum)
1120 base_ts = TypeManager.enum_type;
1121 else if (spec.IsDelegate)
1122 base_ts = TypeManager.multicast_delegate_type;
1126 if (base_ts != null) {
1127 spec.BaseType = base_ts;
1129 // Set base type after type creation
1130 TypeBuilder.SetParent (base_ts.GetMetaInfo ());
1136 public virtual void DefineConstants ()
1138 if (constants != null) {
1139 foreach (Const c in constants) {
1144 if (instance_constructors != null) {
1145 foreach (MethodCore m in instance_constructors) {
1146 var p = m.ParameterInfo;
1147 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1148 var rc = new ResolveContext (m);
1149 p.ResolveDefaultValues (rc);
1154 if (methods != null) {
1155 foreach (MethodCore m in methods) {
1156 var p = m.ParameterInfo;
1157 if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1158 var rc = new ResolveContext (m);
1159 p.ResolveDefaultValues (rc);
1164 if (indexers != null) {
1165 foreach (Indexer i in indexers) {
1166 var p = i.ParameterInfo;
1167 if (p[p.Count - 1].HasDefaultValue) {
1168 var rc = new ResolveContext (i);
1169 p.ResolveDefaultValues (rc);
1174 if (types != null) {
1175 foreach (var t in types)
1176 t.DefineConstants ();
1181 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1183 public TypeBuilder CreateType ()
1185 if (TypeBuilder != null)
1191 if (!CreateTypeBuilder ()) {
1196 if (partial_parts != null) {
1197 foreach (TypeContainer part in partial_parts) {
1199 part.current_type = current_type;
1200 part.TypeBuilder = TypeBuilder;
1204 if (Types != null) {
1205 foreach (TypeContainer tc in Types) {
1206 if (tc.CreateType () == null) {
1216 public override TypeBuilder DefineType ()
1223 type_defined = true;
1225 if (!DefineBaseTypes ()) {
1230 if (!DefineNestedTypes ()) {
1238 public override void SetParameterInfo (List<Constraints> constraints_list)
1240 base.SetParameterInfo (constraints_list);
1242 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1245 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1246 for (int i = 0; i < tc_names.Length; ++i) {
1247 if (tc_names [i].Name != type_params [i].Name) {
1248 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1249 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1250 GetSignatureForError ());
1254 if (tc_names [i].Variance != type_params [i].Variance) {
1255 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1256 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1257 GetSignatureForError ());
1264 // Replaces normal spec with predefined one when compiling corlib
1265 // and this type container defines predefined type
1267 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1272 void UpdateTypeParameterConstraints (TypeContainer part)
1274 TypeParameter[] current_params = type_params;
1275 for (int i = 0; i < current_params.Length; i++) {
1276 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1279 Report.SymbolRelatedToPreviousError (Location, "");
1280 Report.Error (265, part.Location,
1281 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1282 GetSignatureForError (), current_params [i].GetSignatureForError ());
1286 public bool ResolveTypeParameters ()
1288 if (!DoResolveTypeParameters ())
1291 if (types != null) {
1292 foreach (var type in types)
1293 if (!type.ResolveTypeParameters ())
1297 if (compiler_generated != null) {
1298 foreach (CompilerGeneratedClass c in compiler_generated)
1299 if (!c.ResolveTypeParameters ())
1306 protected virtual bool DoResolveTypeParameters ()
1308 if (CurrentTypeParameters == null)
1311 if (PartialContainer != this)
1312 throw new InternalErrorException ();
1314 var base_context = new BaseContext (this);
1315 foreach (TypeParameter type_param in CurrentTypeParameters) {
1316 if (!type_param.ResolveConstraints (base_context)) {
1322 if (partial_parts != null) {
1323 foreach (TypeContainer part in partial_parts)
1324 UpdateTypeParameterConstraints (part);
1330 protected virtual bool DefineNestedTypes ()
1332 if (Types != null) {
1333 foreach (TypeContainer tc in Types)
1334 if (tc.DefineType () == null)
1341 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1343 if (InTransit != null)
1348 if (base_type != null && base_type.Type != null) {
1349 var ptc = base_type.Type.MemberDefinition as TypeContainer;
1350 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1351 return base_type.Type;
1354 if (iface_exprs != null) {
1355 foreach (TypeExpr iface in iface_exprs) {
1356 var ptc = iface.Type.MemberDefinition as Interface;
1357 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1362 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1370 /// Populates our TypeBuilder with fields and methods
1372 public sealed override bool Define ()
1374 if (members_defined)
1375 return members_defined_ok;
1377 members_defined_ok = DoDefineMembers ();
1378 members_defined = true;
1380 if (types != null) {
1381 foreach (var nested in types)
1385 return members_defined_ok;
1388 protected virtual bool DoDefineMembers ()
1390 if (iface_exprs != null) {
1391 foreach (TypeExpr iface in iface_exprs) {
1392 var iface_type = iface.Type;
1394 // Ensure the base is always setup
1395 var compiled_iface = iface_type.MemberDefinition as Interface;
1396 if (compiled_iface != null)
1397 compiled_iface.Define ();
1399 if (Kind == MemberKind.Interface)
1400 MemberCache.AddInterface (iface_type);
1402 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1403 if (oa != null && !IsObsolete)
1404 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1406 GenericTypeExpr ct = iface as GenericTypeExpr;
1408 // TODO: passing `this' is wrong, should be base type iface instead
1409 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1411 ct.CheckConstraints (this);
1413 if (ct.HasDynamicArguments ()) {
1414 Report.Error (1966, iface.Location,
1415 "`{0}': cannot implement a dynamic interface `{1}'",
1416 GetSignatureForError (), iface.GetSignatureForError ());
1423 if (base_type != null) {
1424 ObsoleteAttribute obsolete_attr = base_type.Type.GetAttributeObsolete ();
1425 if (obsolete_attr != null && !IsObsolete)
1426 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1428 var ct = base_type as GenericTypeExpr;
1430 ct.CheckConstraints (this);
1432 var baseContainer = base_type.Type.MemberDefinition as ClassOrStruct;
1433 if (baseContainer != null)
1434 baseContainer.Define ();
1437 if (type_params != null) {
1438 foreach (var tp in type_params) {
1439 tp.CheckGenericConstraints ();
1444 MemberSpec candidate;
1445 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1446 if (conflict_symbol == null && candidate == null) {
1447 if ((ModFlags & Modifiers.NEW) != 0)
1448 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1449 GetSignatureForError ());
1451 if ((ModFlags & Modifiers.NEW) == 0) {
1452 if (candidate == null)
1453 candidate = conflict_symbol;
1455 Report.SymbolRelatedToPreviousError (candidate);
1456 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1457 GetSignatureForError (), candidate.GetSignatureForError ());
1462 DefineContainerMembers (constants);
1463 DefineContainerMembers (fields);
1465 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1466 pending = PendingImplementation.GetPendingImplementations (this);
1468 if (requires_delayed_unmanagedtype_check) {
1469 requires_delayed_unmanagedtype_check = false;
1470 foreach (FieldBase f in fields) {
1471 if (f.MemberType != null && f.MemberType.IsPointer)
1472 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1478 // Constructors are not in the defined_names array
1480 DefineContainerMembers (instance_constructors);
1482 DefineContainerMembers (events);
1483 DefineContainerMembers (ordered_explicit_member_list);
1484 DefineContainerMembers (ordered_member_list);
1486 if (operators != null) {
1487 DefineContainerMembers (operators);
1488 CheckPairedOperators ();
1491 ComputeIndexerName();
1492 CheckEqualsAndGetHashCode();
1497 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1500 foreach (MemberCore mc in mcal) {
1503 } catch (Exception e) {
1504 throw new InternalErrorException (mc, e);
1510 protected virtual void ComputeIndexerName ()
1512 if (indexers == null)
1515 string class_indexer_name = null;
1518 // If there's both an explicit and an implicit interface implementation, the
1519 // explicit one actually implements the interface while the other one is just
1520 // a normal indexer. See bug #37714.
1523 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1524 foreach (Indexer i in indexers) {
1525 if (i.InterfaceType != null) {
1526 if (seen_normal_indexers)
1527 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1531 seen_normal_indexers = true;
1533 if (class_indexer_name == null) {
1534 class_indexer_name = i.ShortName;
1538 if (i.ShortName != class_indexer_name)
1539 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");
1542 if (class_indexer_name != null)
1543 indexer_name = class_indexer_name;
1546 void EmitIndexerName ()
1548 if (!seen_normal_indexers)
1551 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1552 if (pa.Constructor == null &&
1553 !pa.ResolveConstructor (Location, TypeManager.string_type))
1556 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1557 TypeBuilder.SetCustomAttribute (cb);
1560 protected virtual void CheckEqualsAndGetHashCode ()
1562 if (methods == null)
1565 if (HasEquals && !HasGetHashCode) {
1566 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1570 // Indicated whether container has StructLayout attribute set Explicit
1571 public bool HasExplicitLayout {
1572 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1573 set { caching_flags |= Flags.HasExplicitLayout; }
1576 public bool HasStructLayout {
1577 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1578 set { caching_flags |= Flags.HasStructLayout; }
1581 public MemberCache MemberCache {
1583 return spec.MemberCache;
1587 void CheckMemberUsage (List<MemberCore> al, string member_type)
1592 foreach (MemberCore mc in al) {
1593 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1596 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1597 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1602 public virtual void VerifyMembers ()
1605 // Check for internal or private fields that were never assigned
1607 if (Report.WarningLevel >= 3) {
1608 if (RootContext.EnhancedWarnings) {
1609 CheckMemberUsage (properties, "property");
1610 CheckMemberUsage (methods, "method");
1611 CheckMemberUsage (constants, "constant");
1614 if (fields != null){
1615 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1616 foreach (FieldBase f in fields) {
1617 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1618 if (is_type_exposed)
1625 if ((f.caching_flags & Flags.IsAssigned) == 0)
1626 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1628 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1629 f.GetSignatureForError ());
1635 // Only report 649 on level 4
1637 if (Report.WarningLevel < 4)
1640 if ((f.caching_flags & Flags.IsAssigned) != 0)
1644 // Don't be pendatic over serializable attributes
1646 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1649 Constant c = New.Constantify (f.MemberType);
1650 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1651 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1657 public override void Emit ()
1659 if (all_tp_builders != null) {
1660 int current_starts_index = CurrentTypeParametersStartIndex;
1661 for (int i = 0; i < all_tp_builders.Length; i++) {
1662 if (i < current_starts_index) {
1663 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1665 CurrentTypeParameters [i - current_starts_index].Emit ();
1670 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1671 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1676 // TODO: move to ClassOrStruct
1677 void EmitConstructors ()
1679 if (instance_constructors == null)
1682 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1683 bool has_compliant_args = false;
1685 foreach (Constructor c in instance_constructors) {
1689 catch (Exception e) {
1690 throw new InternalErrorException (c, e);
1693 if (has_compliant_args)
1696 has_compliant_args = c.HasCompliantArgs;
1698 if (!has_compliant_args)
1699 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1701 foreach (Constructor c in instance_constructors) {
1705 catch (Exception e) {
1706 throw new InternalErrorException (c, e);
1713 /// Emits the code, this step is performed after all
1714 /// the types, enumerations, constructors
1716 public virtual void EmitType ()
1718 if (OptAttributes != null)
1719 OptAttributes.Emit ();
1723 EmitConstructors ();
1725 if (constants != null)
1726 foreach (Const con in constants)
1729 if (default_static_constructor != null)
1730 default_static_constructor.Emit ();
1732 if (operators != null)
1733 foreach (Operator o in operators)
1736 if (properties != null)
1737 foreach (Property p in properties)
1740 if (indexers != null) {
1741 foreach (Indexer indx in indexers)
1746 if (events != null){
1747 foreach (Event e in Events)
1751 if (methods != null) {
1752 for (int i = 0; i < methods.Count; ++i)
1753 ((MethodOrOperator) methods [i]).Emit ();
1757 foreach (FieldBase f in fields)
1760 if (types != null) {
1761 foreach (TypeContainer t in types)
1765 if (pending != null)
1766 pending.VerifyPendingMethods (Report);
1768 if (Report.Errors > 0)
1771 if (compiler_generated != null) {
1772 for (int i = 0; i < compiler_generated.Count; ++i)
1773 compiler_generated [i].EmitType ();
1777 public void CloseType ()
1779 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1782 // Close base type container first to avoid TypeLoadException
1783 if (spec.BaseType != null) {
1784 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1790 caching_flags |= Flags.CloseTypeCreated;
1791 TypeBuilder.CreateType ();
1792 } catch (TypeLoadException){
1794 // This is fine, the code still created the type
1796 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1797 // Console.WriteLine (e.Message);
1798 } catch (Exception e) {
1799 throw new InternalErrorException (this, e);
1803 foreach (TypeContainer tc in Types)
1807 if (compiler_generated != null)
1808 foreach (CompilerGeneratedClass c in compiler_generated)
1813 initialized_fields = null;
1814 initialized_static_fields = null;
1816 ordered_explicit_member_list = null;
1817 ordered_member_list = null;
1822 compiler_generated = null;
1823 default_constructor = null;
1824 default_static_constructor = null;
1826 OptAttributes = null;
1830 // Performs the validation on a Method's modifiers (properties have
1831 // the same properties).
1833 public bool MethodModifiersValid (MemberCore mc)
1835 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1836 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1837 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1839 var flags = mc.ModFlags;
1842 // At most one of static, virtual or override
1844 if ((flags & Modifiers.STATIC) != 0){
1845 if ((flags & vao) != 0){
1846 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1847 mc.GetSignatureForError ());
1852 if (Kind == MemberKind.Struct){
1853 if ((flags & va) != 0){
1854 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1859 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1860 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1861 mc.GetSignatureForError ());
1866 // If the declaration includes the abstract modifier, then the
1867 // declaration does not include static, virtual or extern
1869 if ((flags & Modifiers.ABSTRACT) != 0){
1870 if ((flags & Modifiers.EXTERN) != 0){
1872 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1876 if ((flags & Modifiers.SEALED) != 0) {
1877 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1881 if ((flags & Modifiers.VIRTUAL) != 0){
1882 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1886 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1887 Report.SymbolRelatedToPreviousError (this);
1888 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1889 mc.GetSignatureForError (), GetSignatureForError ());
1894 if ((flags & Modifiers.PRIVATE) != 0){
1895 if ((flags & vao) != 0){
1896 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1901 if ((flags & Modifiers.SEALED) != 0){
1902 if ((flags & Modifiers.OVERRIDE) == 0){
1903 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1911 public Constructor DefaultStaticConstructor {
1912 get { return default_static_constructor; }
1915 protected override bool VerifyClsCompliance ()
1917 if (!base.VerifyClsCompliance ())
1920 // Check this name against other containers
1921 NamespaceEntry.NS.VerifyClsCompliance ();
1923 // Check all container names for user classes
1924 if (Kind != MemberKind.Delegate)
1925 MemberCache.VerifyClsCompliance (Definition, Report);
1927 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1928 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1929 GetSignatureForError (), BaseType.GetSignatureForError ());
1935 /// Performs checks for an explicit interface implementation. First it
1936 /// checks whether the `interface_type' is a base inteface implementation.
1937 /// Then it checks whether `name' exists in the interface type.
1939 public bool VerifyImplements (InterfaceMemberBase mb)
1941 var ifaces = spec.Interfaces;
1942 if (ifaces != null) {
1943 foreach (TypeSpec t in ifaces){
1944 if (TypeManager.IsEqual (t, mb.InterfaceType))
1949 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1950 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1951 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1956 // Used for visiblity checks to tests whether this definition shares
1957 // base type baseType, it does member-definition search
1959 public bool IsBaseTypeDefinition (TypeSpec baseType)
1961 // RootContext check
1962 if (TypeBuilder == null)
1967 if (type.MemberDefinition == baseType.MemberDefinition)
1970 type = type.BaseType;
1971 } while (type != null);
1976 public MemberCache LoadMembers (TypeSpec declaringType)
1978 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1981 public void Mark_HasEquals ()
1983 cached_method |= CachedMethods.Equals;
1986 public void Mark_HasGetHashCode ()
1988 cached_method |= CachedMethods.GetHashCode;
1992 /// Method container contains Equals method
1994 public bool HasEquals {
1996 return (cached_method & CachedMethods.Equals) != 0;
2001 /// Method container contains GetHashCode method
2003 public bool HasGetHashCode {
2005 return (cached_method & CachedMethods.GetHashCode) != 0;
2009 public bool HasStaticFieldInitializer {
2011 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2015 cached_method |= CachedMethods.HasStaticFieldInitializer;
2017 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2022 // Generates xml doc comments (if any), and if required,
2023 // handle warning report.
2025 internal override void GenerateDocComment (DeclSpace ds)
2027 DocUtil.GenerateTypeDocComment (this, ds, Report);
2030 public override string DocCommentHeader {
2031 get { return "T:"; }
2035 public abstract class ClassOrStruct : TypeContainer
2037 Dictionary<SecurityAction, PermissionSet> declarative_security;
2039 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2040 MemberName name, Attributes attrs, MemberKind kind)
2041 : base (ns, parent, name, attrs, kind)
2045 protected override bool AddToContainer (MemberCore symbol, string name)
2047 if (name == MemberName.Name) {
2048 if (symbol is TypeParameter) {
2049 Report.Error (694, symbol.Location,
2050 "Type parameter `{0}' has same name as containing type, or method",
2051 symbol.GetSignatureForError ());
2055 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2056 if (imb == null || !imb.IsExplicitImpl) {
2057 Report.SymbolRelatedToPreviousError (this);
2058 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2059 symbol.GetSignatureForError ());
2064 return base.AddToContainer (symbol, name);
2067 public override void VerifyMembers ()
2069 base.VerifyMembers ();
2071 if ((events != null) && Report.WarningLevel >= 3) {
2072 foreach (Event e in events){
2073 // Note: The event can be assigned from same class only, so we can report
2074 // this warning for all accessibility modes
2075 if ((e.caching_flags & Flags.IsUsed) == 0)
2076 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2081 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2083 if (a.IsValidSecurityAttribute ()) {
2084 if (declarative_security == null)
2085 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2087 a.ExtractSecurityPermissionSet (declarative_security);
2091 if (a.Type == pa.StructLayout) {
2092 PartialContainer.HasStructLayout = true;
2094 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2095 PartialContainer.HasExplicitLayout = true;
2098 if (a.Type == pa.Dynamic) {
2099 a.Error_MisusedDynamicAttribute ();
2103 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2107 /// Defines the default constructors
2109 protected void DefineDefaultConstructor (bool is_static)
2111 // The default instance constructor is public
2112 // If the class is abstract, the default constructor is protected
2113 // The default static constructor is private
2117 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2119 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2122 Constructor c = new Constructor (this, MemberName.Name, mods,
2123 null, ParametersCompiled.EmptyReadOnlyParameters,
2124 new GeneratedBaseInitializer (Location),
2128 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2131 protected override bool DoDefineMembers ()
2133 CheckProtectedModifier ();
2135 base.DoDefineMembers ();
2137 if (default_static_constructor != null)
2138 default_static_constructor.Define ();
2143 public override void Emit ()
2145 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2146 DefineDefaultConstructor (true);
2147 default_static_constructor.Define ();
2152 if (declarative_security != null) {
2153 foreach (var de in declarative_security) {
2154 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2159 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2161 DeclSpace top_level = Parent;
2162 if (top_level != null) {
2163 while (top_level.Parent != null)
2164 top_level = top_level.Parent;
2166 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2167 if (candidates != null)
2168 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2171 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2174 protected override TypeAttributes TypeAttr {
2176 if (default_static_constructor == null)
2177 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2179 return base.TypeAttr;
2185 // TODO: should be sealed
2186 public class Class : ClassOrStruct {
2187 const Modifiers AllowedModifiers =
2190 Modifiers.PROTECTED |
2191 Modifiers.INTERNAL |
2193 Modifiers.ABSTRACT |
2198 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2200 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2202 : base (ns, parent, name, attrs, MemberKind.Class)
2204 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2205 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2206 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2208 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2209 Report.FeatureIsNotAvailable (Location, "static classes");
2213 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2215 if (part.Name == "System.Object")
2216 Report.Error (537, part.Location,
2217 "The class System.Object cannot have a base class or implement an interface.");
2218 base.AddBasesForPart (part, bases);
2221 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2223 if (a.Type == pa.AttributeUsage) {
2224 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2225 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2229 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2230 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2234 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2235 a.Error_MissingGuidAttribute ();
2239 if (a.Type == pa.Extension) {
2240 a.Error_MisusedExtensionAttribute ();
2244 if (a.Type.IsConditionallyExcluded (Location))
2247 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2250 public override AttributeTargets AttributeTargets {
2252 return AttributeTargets.Class;
2256 protected override void DefineContainerMembers (System.Collections.IList list)
2262 base.DefineContainerMembers (list);
2266 foreach (MemberCore m in list) {
2267 if (m is Operator) {
2268 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2272 if (m is Destructor) {
2273 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2278 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2282 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2285 if (m is Constructor) {
2286 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2290 Method method = m as Method;
2291 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2292 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2296 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2299 base.DefineContainerMembers (list);
2302 protected override bool DoDefineMembers ()
2304 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2305 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2308 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2309 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2312 if (InstanceConstructors == null && !IsStatic)
2313 DefineDefaultConstructor (false);
2315 return base.DoDefineMembers ();
2318 public override void Emit ()
2322 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2323 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2326 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2328 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2330 if (base_class == null) {
2331 if (spec != TypeManager.object_type)
2332 base_class = TypeManager.system_object_expr;
2334 var base_type = base_class.Type;
2336 if (base_type.IsGenericParameter){
2337 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2338 GetSignatureForError (), base_type.GetSignatureForError ());
2339 } else if (IsGeneric && base_type.IsAttribute) {
2340 Report.Error (698, base_class.Location,
2341 "A generic type cannot derive from `{0}' because it is an attribute class",
2342 base_class.GetSignatureForError ());
2343 } else if (base_type.IsStatic) {
2344 Report.SymbolRelatedToPreviousError (base_class.Type);
2345 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2346 GetSignatureForError (), base_type.GetSignatureForError ());
2347 } else if (base_type.IsSealed){
2348 Report.SymbolRelatedToPreviousError (base_class.Type);
2349 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2350 GetSignatureForError (), base_type.GetSignatureForError ());
2353 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2354 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2355 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2356 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2357 GetSignatureForError (), base_type.GetSignatureForError ());
2358 base_class = TypeManager.system_object_expr;
2361 if (!IsAccessibleAs (base_type)) {
2362 Report.SymbolRelatedToPreviousError (base_type);
2363 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2364 base_type.GetSignatureForError (), GetSignatureForError ());
2368 if (PartialContainer.IsStatic) {
2369 if (base_class.Type != TypeManager.object_type) {
2370 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2371 GetSignatureForError (), base_class.GetSignatureForError ());
2375 if (ifaces != null) {
2376 foreach (TypeExpr t in ifaces)
2377 Report.SymbolRelatedToPreviousError (t.Type);
2378 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2385 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2386 /// Valid only for attribute classes.
2387 public override string[] ConditionalConditions ()
2389 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2392 caching_flags &= ~Flags.Excluded_Undetected;
2394 if (OptAttributes == null)
2397 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2401 string[] conditions = new string[attrs.Length];
2402 for (int i = 0; i < conditions.Length; ++i)
2403 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2405 caching_flags |= Flags.Excluded;
2410 // FIXME: How do we deal with the user specifying a different
2413 protected override TypeAttributes TypeAttr {
2415 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2417 ta |= StaticClassAttribute;
2423 public sealed class Struct : ClassOrStruct {
2425 bool is_unmanaged, has_unmanaged_check_done;
2429 // Modifiers allowed in a struct declaration
2431 const Modifiers AllowedModifiers =
2434 Modifiers.PROTECTED |
2435 Modifiers.INTERNAL |
2439 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2440 Modifiers mod, Attributes attrs)
2441 : base (ns, parent, name, attrs, MemberKind.Struct)
2443 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2444 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2445 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2448 public override AttributeTargets AttributeTargets {
2450 return AttributeTargets.Struct;
2454 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2456 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2459 // When struct constains fixed fixed and struct layout has explicitly
2460 // set CharSet, its value has to be propagated to compiler generated
2461 // fixed field types
2463 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2464 for (int i = 0; i < Fields.Count; ++i) {
2465 FixedField ff = Fields [i] as FixedField;
2467 ff.SetCharSet (TypeBuilder.Attributes);
2472 bool CheckStructCycles (Struct s)
2474 if (s.Fields == null)
2481 foreach (FieldBase field in s.Fields) {
2482 TypeSpec ftype = field.Spec.MemberType;
2483 if (!ftype.IsStruct)
2486 if (ftype is PredefinedTypeSpec)
2489 foreach (var targ in ftype.TypeArguments) {
2490 if (!CheckFieldTypeCycle (targ)) {
2491 Report.Error (523, field.Location,
2492 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2493 field.GetSignatureForError (), ftype.GetSignatureForError ());
2498 if ((field.IsStatic && !ftype.IsGeneric))
2501 if (!CheckFieldTypeCycle (ftype)) {
2502 Report.Error (523, field.Location,
2503 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2504 field.GetSignatureForError (), ftype.GetSignatureForError ());
2509 s.InTransit = false;
2513 bool CheckFieldTypeCycle (TypeSpec ts)
2515 var fts = ts.MemberDefinition as Struct;
2519 return CheckStructCycles (fts);
2522 public override void Emit ()
2524 CheckStructCycles (this);
2529 public override bool IsUnmanagedType ()
2534 if (requires_delayed_unmanagedtype_check)
2537 if (has_unmanaged_check_done)
2538 return is_unmanaged;
2540 has_unmanaged_check_done = true;
2542 foreach (FieldBase f in fields) {
2546 // It can happen when recursive unmanaged types are defined
2547 // struct S { S* s; }
2548 TypeSpec mt = f.MemberType;
2550 has_unmanaged_check_done = false;
2551 requires_delayed_unmanagedtype_check = true;
2555 // TODO: Remove when pointer types are under mcs control
2556 while (mt.IsPointer)
2557 mt = TypeManager.GetElementType (mt);
2559 if (mt.MemberDefinition == this) {
2560 for (var p = Parent; p != null; p = p.Parent) {
2561 if (p.Kind == MemberKind.Class)
2567 if (TypeManager.IsUnmanagedType (mt))
2573 is_unmanaged = true;
2577 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2579 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2580 base_class = TypeManager.system_valuetype_expr;
2584 protected override TypeAttributes TypeAttr {
2586 const TypeAttributes DefaultTypeAttributes =
2587 TypeAttributes.SequentialLayout |
2588 TypeAttributes.Sealed;
2590 return base.TypeAttr | DefaultTypeAttributes;
2594 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2596 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2597 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2598 field.GetSignatureForError ());
2601 base.RegisterFieldForInitialization (field, expression);
2609 public sealed class Interface : TypeContainer {
2612 /// Modifiers allowed in a class declaration
2614 public const Modifiers AllowedModifiers =
2617 Modifiers.PROTECTED |
2618 Modifiers.INTERNAL |
2622 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2624 : base (ns, parent, name, attrs, MemberKind.Interface)
2626 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2628 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2629 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2632 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2634 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2635 a.Error_MissingGuidAttribute ();
2639 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2643 public override AttributeTargets AttributeTargets {
2645 return AttributeTargets.Interface;
2649 protected override TypeAttributes TypeAttr {
2651 const TypeAttributes DefaultTypeAttributes =
2652 TypeAttributes.AutoLayout |
2653 TypeAttributes.Abstract |
2654 TypeAttributes.Interface;
2656 return base.TypeAttr | DefaultTypeAttributes;
2660 protected override bool VerifyClsCompliance ()
2662 if (!base.VerifyClsCompliance ())
2665 if (iface_exprs != null) {
2666 foreach (var iface in iface_exprs) {
2667 if (iface.Type.IsCLSCompliant ())
2670 Report.SymbolRelatedToPreviousError (iface.Type);
2671 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2672 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2680 public abstract class InterfaceMemberBase : MemberBase {
2682 // Whether this is an interface member.
2684 public bool IsInterface;
2687 // If true, this is an explicit interface implementation
2689 public bool IsExplicitImpl;
2691 protected bool is_external_implementation;
2694 // The interface type we are explicitly implementing
2696 public TypeSpec InterfaceType;
2699 // The method we're overriding if this is an override method.
2701 protected MethodSpec base_method;
2703 readonly Modifiers explicit_mod_flags;
2704 public MethodAttributes flags;
2706 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2707 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2708 MemberName name, Attributes attrs)
2709 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2712 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2713 IsExplicitImpl = (MemberName.Left != null);
2714 explicit_mod_flags = mod;
2717 protected override bool CheckBase ()
2719 if (!base.CheckBase ())
2722 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2723 CheckForDuplications ();
2728 // For System.Object only
2729 if (Parent.BaseType == null)
2732 MemberSpec candidate;
2733 var base_member = FindBaseMember (out candidate);
2735 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2736 if (base_member == null) {
2737 if (candidate == null) {
2738 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2739 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2740 "object.Finalize()");
2742 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2743 GetSignatureForError (), SimpleName.GetMemberType (this));
2746 Report.SymbolRelatedToPreviousError (candidate);
2748 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2749 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2750 else if (this is PropertyBase)
2751 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2752 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2754 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2755 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2761 if (!CheckOverrideAgainstBase (base_member))
2764 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2766 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2767 Report.SymbolRelatedToPreviousError (base_member);
2768 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2769 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2772 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2773 Report.SymbolRelatedToPreviousError (base_member);
2774 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2775 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2779 base_method = base_member as MethodSpec;
2783 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2784 base_member = candidate;
2786 if (base_member == null) {
2787 if ((ModFlags & Modifiers.NEW) != 0) {
2788 if (base_member == null) {
2789 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2790 GetSignatureForError ());
2794 if ((ModFlags & Modifiers.NEW) == 0) {
2795 ModFlags |= Modifiers.NEW;
2796 Report.SymbolRelatedToPreviousError (base_member);
2797 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2798 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",
2799 GetSignatureForError (), base_member.GetSignatureForError ());
2801 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2802 GetSignatureForError (), base_member.GetSignatureForError ());
2806 if (!IsInterface && base_member.IsAbstract) {
2807 Report.SymbolRelatedToPreviousError (base_member);
2808 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2809 GetSignatureForError (), base_member.GetSignatureForError ());
2816 protected virtual bool CheckForDuplications ()
2818 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2822 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2823 // that have been defined.
2825 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2829 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2830 Report.SymbolRelatedToPreviousError (base_member);
2831 Report.Error (506, Location,
2832 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2833 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2837 // Now we check that the overriden method is not final
2838 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2839 Report.SymbolRelatedToPreviousError (base_member);
2840 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2841 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2845 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2846 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2847 Report.SymbolRelatedToPreviousError (base_member);
2848 if (this is PropertyBasedMember) {
2849 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2850 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2852 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2853 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2861 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2863 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2864 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2866 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2868 // when overriding protected internal, the method can be declared
2869 // protected internal only within the same assembly or assembly
2870 // which has InternalsVisibleTo
2872 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2873 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2875 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2877 // if it's not "protected internal", it must be "protected"
2882 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2884 // protected within the same assembly - an error
2888 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2889 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2891 // protected ok, but other attributes differ - report an error
2898 return thisp == base_classp;
2901 public override bool Define ()
2904 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2905 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2907 flags = MethodAttributes.Public |
2908 MethodAttributes.Abstract |
2909 MethodAttributes.HideBySig |
2910 MethodAttributes.NewSlot |
2911 MethodAttributes.Virtual;
2913 Parent.PartialContainer.MethodModifiersValid (this);
2915 flags = ModifiersExtensions.MethodAttr (ModFlags);
2918 if (IsExplicitImpl) {
2919 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2920 if (iface_texpr == null)
2923 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2924 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2925 GetSignatureForError ());
2928 InterfaceType = iface_texpr.Type;
2930 if (!InterfaceType.IsInterface) {
2931 Report.SymbolRelatedToPreviousError (InterfaceType);
2932 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2933 TypeManager.CSharpName (InterfaceType));
2935 Parent.PartialContainer.VerifyImplements (this);
2938 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2941 return base.Define ();
2944 protected bool DefineParameters (ParametersCompiled parameters)
2946 if (!parameters.Resolve (this))
2950 for (int i = 0; i < parameters.Count; ++i) {
2951 Parameter p = parameters [i];
2953 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2954 p.Warning_UselessOptionalParameter (Report);
2956 if (p.CheckAccessibility (this))
2959 TypeSpec t = parameters.Types [i];
2960 Report.SymbolRelatedToPreviousError (t);
2961 if (this is Indexer)
2962 Report.Error (55, Location,
2963 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2964 TypeManager.CSharpName (t), GetSignatureForError ());
2965 else if (this is Operator)
2966 Report.Error (57, Location,
2967 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2968 TypeManager.CSharpName (t), GetSignatureForError ());
2970 Report.Error (51, Location,
2971 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2972 TypeManager.CSharpName (t), GetSignatureForError ());
2978 public override void Emit()
2980 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2981 // We are more strict than csc and report this as an error because SRE does not allow emit that
2982 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2983 if (this is Constructor) {
2984 Report.Error (824, Location,
2985 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
2987 Report.Error (626, Location,
2988 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
2989 GetSignatureForError ());
2996 public override bool EnableOverloadChecks (MemberCore overload)
2999 // Two members can differ in their explicit interface
3000 // type parameter only
3002 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3003 if (imb != null && imb.IsExplicitImpl) {
3004 if (IsExplicitImpl) {
3005 caching_flags |= Flags.MethodOverloadsExist;
3010 return IsExplicitImpl;
3013 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3015 Report.SymbolRelatedToPreviousError (base_member);
3016 Report.Error (507, member.Location,
3017 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3018 member.GetSignatureForError (),
3019 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3020 base_member.GetSignatureForError ());
3023 protected void Error_StaticReturnType ()
3025 Report.Error (722, Location,
3026 "`{0}': static types cannot be used as return types",
3027 MemberType.GetSignatureForError ());
3031 /// Gets base method and its return type
3033 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3035 return MemberCache.FindBaseMember (this, out bestCandidate);
3039 // The "short" name of this property / indexer / event. This is the
3040 // name without the explicit interface.
3042 public string ShortName {
3043 get { return MemberName.Name; }
3044 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3048 // Returns full metadata method name
3050 public string GetFullName (MemberName name)
3052 return GetFullName (name.Name);
3055 public string GetFullName (string name)
3057 if (!IsExplicitImpl)
3061 // When dealing with explicit members a full interface type
3062 // name is added to member name to avoid possible name conflicts
3064 // We use CSharpName which gets us full name with benefit of
3065 // replacing predefined names which saves some space and name
3068 return TypeManager.CSharpName (InterfaceType) + "." + name;
3071 protected override bool VerifyClsCompliance ()
3073 if (!base.VerifyClsCompliance ()) {
3077 if (GenericMethod != null)
3078 GenericMethod.VerifyClsCompliance ();
3083 public override bool IsUsed
3085 get { return IsExplicitImpl || base.IsUsed; }
3090 public abstract class MemberBase : MemberCore
3092 protected FullNamedExpression type_expr;
3093 protected TypeSpec member_type;
3095 public readonly DeclSpace ds;
3096 public readonly GenericMethod GenericMethod;
3098 protected MemberBase (DeclSpace parent, GenericMethod generic,
3099 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3100 MemberName name, Attributes attrs)
3101 : base (parent, name, attrs)
3103 this.ds = generic != null ? generic : (DeclSpace) parent;
3104 this.type_expr = type;
3105 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3106 GenericMethod = generic;
3107 if (GenericMethod != null)
3108 GenericMethod.ModFlags = ModFlags;
3112 // Main member define entry
3114 public override bool Define ()
3116 DoMemberTypeIndependentChecks ();
3119 // Returns false only when type resolution failed
3121 if (!ResolveMemberType ())
3124 DoMemberTypeDependentChecks ();
3129 // Any type_name independent checks
3131 protected virtual void DoMemberTypeIndependentChecks ()
3133 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3134 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3135 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3136 GetSignatureForError (), Parent.GetSignatureForError ());
3141 // Any type_name dependent checks
3143 protected virtual void DoMemberTypeDependentChecks ()
3145 // verify accessibility
3146 if (!IsAccessibleAs (MemberType)) {
3147 Report.SymbolRelatedToPreviousError (MemberType);
3148 if (this is Property)
3149 Report.Error (53, Location,
3150 "Inconsistent accessibility: property type `" +
3151 TypeManager.CSharpName (MemberType) + "' is less " +
3152 "accessible than property `" + GetSignatureForError () + "'");
3153 else if (this is Indexer)
3154 Report.Error (54, Location,
3155 "Inconsistent accessibility: indexer return type `" +
3156 TypeManager.CSharpName (MemberType) + "' is less " +
3157 "accessible than indexer `" + GetSignatureForError () + "'");
3158 else if (this is MethodCore) {
3159 if (this is Operator)
3160 Report.Error (56, Location,
3161 "Inconsistent accessibility: return type `" +
3162 TypeManager.CSharpName (MemberType) + "' is less " +
3163 "accessible than operator `" + GetSignatureForError () + "'");
3165 Report.Error (50, Location,
3166 "Inconsistent accessibility: return type `" +
3167 TypeManager.CSharpName (MemberType) + "' is less " +
3168 "accessible than method `" + GetSignatureForError () + "'");
3170 Report.Error (52, Location,
3171 "Inconsistent accessibility: field type `" +
3172 TypeManager.CSharpName (MemberType) + "' is less " +
3173 "accessible than field `" + GetSignatureForError () + "'");
3177 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3178 TypeManager.CheckTypeVariance (MemberType, variance, this);
3181 protected bool IsTypePermitted ()
3183 if (TypeManager.IsSpecialType (MemberType)) {
3184 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3190 protected virtual bool CheckBase ()
3192 CheckProtectedModifier ();
3197 public TypeSpec MemberType {
3198 get { return member_type; }
3201 protected virtual bool ResolveMemberType ()
3203 if (member_type != null)
3204 throw new InternalErrorException ("Multi-resolve");
3206 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3211 // Replace original type name, error reporting can use fully resolved name
3215 member_type = te.Type;