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 // It can trigger define of this type (for generic types only)
1439 if (HasMembersDefined)
1444 if (type_params != null) {
1445 foreach (var tp in type_params) {
1446 tp.CheckGenericConstraints ();
1451 MemberSpec candidate;
1452 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1453 if (conflict_symbol == null && candidate == null) {
1454 if ((ModFlags & Modifiers.NEW) != 0)
1455 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1456 GetSignatureForError ());
1458 if ((ModFlags & Modifiers.NEW) == 0) {
1459 if (candidate == null)
1460 candidate = conflict_symbol;
1462 Report.SymbolRelatedToPreviousError (candidate);
1463 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1464 GetSignatureForError (), candidate.GetSignatureForError ());
1469 DefineContainerMembers (constants);
1470 DefineContainerMembers (fields);
1472 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1473 pending = PendingImplementation.GetPendingImplementations (this);
1475 if (requires_delayed_unmanagedtype_check) {
1476 requires_delayed_unmanagedtype_check = false;
1477 foreach (FieldBase f in fields) {
1478 if (f.MemberType != null && f.MemberType.IsPointer)
1479 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1485 // Constructors are not in the defined_names array
1487 DefineContainerMembers (instance_constructors);
1489 DefineContainerMembers (events);
1490 DefineContainerMembers (ordered_explicit_member_list);
1491 DefineContainerMembers (ordered_member_list);
1493 if (operators != null) {
1494 DefineContainerMembers (operators);
1495 CheckPairedOperators ();
1498 ComputeIndexerName();
1499 CheckEqualsAndGetHashCode();
1504 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1507 foreach (MemberCore mc in mcal) {
1510 } catch (Exception e) {
1511 throw new InternalErrorException (mc, e);
1517 protected virtual void ComputeIndexerName ()
1519 if (indexers == null)
1522 string class_indexer_name = null;
1525 // If there's both an explicit and an implicit interface implementation, the
1526 // explicit one actually implements the interface while the other one is just
1527 // a normal indexer. See bug #37714.
1530 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1531 foreach (Indexer i in indexers) {
1532 if (i.InterfaceType != null) {
1533 if (seen_normal_indexers)
1534 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1538 seen_normal_indexers = true;
1540 if (class_indexer_name == null) {
1541 class_indexer_name = i.ShortName;
1545 if (i.ShortName != class_indexer_name)
1546 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");
1549 if (class_indexer_name != null)
1550 indexer_name = class_indexer_name;
1553 void EmitIndexerName ()
1555 if (!seen_normal_indexers)
1558 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1559 if (pa.Constructor == null &&
1560 !pa.ResolveConstructor (Location, TypeManager.string_type))
1563 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1564 TypeBuilder.SetCustomAttribute (cb);
1567 protected virtual void CheckEqualsAndGetHashCode ()
1569 if (methods == null)
1572 if (HasEquals && !HasGetHashCode) {
1573 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1577 // Indicated whether container has StructLayout attribute set Explicit
1578 public bool HasExplicitLayout {
1579 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1580 set { caching_flags |= Flags.HasExplicitLayout; }
1583 public bool HasStructLayout {
1584 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1585 set { caching_flags |= Flags.HasStructLayout; }
1588 public MemberCache MemberCache {
1590 return spec.MemberCache;
1594 void CheckMemberUsage (List<MemberCore> al, string member_type)
1599 foreach (MemberCore mc in al) {
1600 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1603 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1604 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1609 public virtual void VerifyMembers ()
1612 // Check for internal or private fields that were never assigned
1614 if (Report.WarningLevel >= 3) {
1615 if (RootContext.EnhancedWarnings) {
1616 CheckMemberUsage (properties, "property");
1617 CheckMemberUsage (methods, "method");
1618 CheckMemberUsage (constants, "constant");
1621 if (fields != null){
1622 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1623 foreach (FieldBase f in fields) {
1624 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1625 if (is_type_exposed)
1632 if ((f.caching_flags & Flags.IsAssigned) == 0)
1633 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1635 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1636 f.GetSignatureForError ());
1642 // Only report 649 on level 4
1644 if (Report.WarningLevel < 4)
1647 if ((f.caching_flags & Flags.IsAssigned) != 0)
1651 // Don't be pendatic over serializable attributes
1653 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1656 Constant c = New.Constantify (f.MemberType);
1657 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1658 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1664 public override void Emit ()
1666 if (all_tp_builders != null) {
1667 int current_starts_index = CurrentTypeParametersStartIndex;
1668 for (int i = 0; i < all_tp_builders.Length; i++) {
1669 if (i < current_starts_index) {
1670 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1672 CurrentTypeParameters [i - current_starts_index].Emit ();
1677 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1678 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1683 // TODO: move to ClassOrStruct
1684 void EmitConstructors ()
1686 if (instance_constructors == null)
1689 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1690 bool has_compliant_args = false;
1692 foreach (Constructor c in instance_constructors) {
1696 catch (Exception e) {
1697 throw new InternalErrorException (c, e);
1700 if (has_compliant_args)
1703 has_compliant_args = c.HasCompliantArgs;
1705 if (!has_compliant_args)
1706 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1708 foreach (Constructor c in instance_constructors) {
1712 catch (Exception e) {
1713 throw new InternalErrorException (c, e);
1720 /// Emits the code, this step is performed after all
1721 /// the types, enumerations, constructors
1723 public virtual void EmitType ()
1725 if (OptAttributes != null)
1726 OptAttributes.Emit ();
1730 EmitConstructors ();
1732 if (constants != null)
1733 foreach (Const con in constants)
1736 if (default_static_constructor != null)
1737 default_static_constructor.Emit ();
1739 if (operators != null)
1740 foreach (Operator o in operators)
1743 if (properties != null)
1744 foreach (Property p in properties)
1747 if (indexers != null) {
1748 foreach (Indexer indx in indexers)
1753 if (events != null){
1754 foreach (Event e in Events)
1758 if (methods != null) {
1759 for (int i = 0; i < methods.Count; ++i)
1760 ((MethodOrOperator) methods [i]).Emit ();
1764 foreach (FieldBase f in fields)
1767 if (types != null) {
1768 foreach (TypeContainer t in types)
1772 if (pending != null)
1773 pending.VerifyPendingMethods (Report);
1775 if (Report.Errors > 0)
1778 if (compiler_generated != null) {
1779 for (int i = 0; i < compiler_generated.Count; ++i)
1780 compiler_generated [i].EmitType ();
1784 public void CloseType ()
1786 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1789 // Close base type container first to avoid TypeLoadException
1790 if (spec.BaseType != null) {
1791 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1797 caching_flags |= Flags.CloseTypeCreated;
1798 TypeBuilder.CreateType ();
1799 } catch (TypeLoadException){
1801 // This is fine, the code still created the type
1803 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1804 // Console.WriteLine (e.Message);
1805 } catch (Exception e) {
1806 throw new InternalErrorException (this, e);
1810 foreach (TypeContainer tc in Types)
1814 if (compiler_generated != null)
1815 foreach (CompilerGeneratedClass c in compiler_generated)
1820 initialized_fields = null;
1821 initialized_static_fields = null;
1823 ordered_explicit_member_list = null;
1824 ordered_member_list = null;
1829 compiler_generated = null;
1830 default_constructor = null;
1831 default_static_constructor = null;
1833 OptAttributes = null;
1837 // Performs the validation on a Method's modifiers (properties have
1838 // the same properties).
1840 public bool MethodModifiersValid (MemberCore mc)
1842 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1843 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1844 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1846 var flags = mc.ModFlags;
1849 // At most one of static, virtual or override
1851 if ((flags & Modifiers.STATIC) != 0){
1852 if ((flags & vao) != 0){
1853 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1854 mc.GetSignatureForError ());
1859 if (Kind == MemberKind.Struct){
1860 if ((flags & va) != 0){
1861 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1866 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1867 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1868 mc.GetSignatureForError ());
1873 // If the declaration includes the abstract modifier, then the
1874 // declaration does not include static, virtual or extern
1876 if ((flags & Modifiers.ABSTRACT) != 0){
1877 if ((flags & Modifiers.EXTERN) != 0){
1879 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1883 if ((flags & Modifiers.SEALED) != 0) {
1884 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1888 if ((flags & Modifiers.VIRTUAL) != 0){
1889 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1893 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1894 Report.SymbolRelatedToPreviousError (this);
1895 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1896 mc.GetSignatureForError (), GetSignatureForError ());
1901 if ((flags & Modifiers.PRIVATE) != 0){
1902 if ((flags & vao) != 0){
1903 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1908 if ((flags & Modifiers.SEALED) != 0){
1909 if ((flags & Modifiers.OVERRIDE) == 0){
1910 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1918 public Constructor DefaultStaticConstructor {
1919 get { return default_static_constructor; }
1922 protected override bool VerifyClsCompliance ()
1924 if (!base.VerifyClsCompliance ())
1927 // Check this name against other containers
1928 NamespaceEntry.NS.VerifyClsCompliance ();
1930 // Check all container names for user classes
1931 if (Kind != MemberKind.Delegate)
1932 MemberCache.VerifyClsCompliance (Definition, Report);
1934 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1935 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1936 GetSignatureForError (), BaseType.GetSignatureForError ());
1942 /// Performs checks for an explicit interface implementation. First it
1943 /// checks whether the `interface_type' is a base inteface implementation.
1944 /// Then it checks whether `name' exists in the interface type.
1946 public bool VerifyImplements (InterfaceMemberBase mb)
1948 var ifaces = spec.Interfaces;
1949 if (ifaces != null) {
1950 foreach (TypeSpec t in ifaces){
1951 if (TypeManager.IsEqual (t, mb.InterfaceType))
1956 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1957 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1958 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1963 // Used for visiblity checks to tests whether this definition shares
1964 // base type baseType, it does member-definition search
1966 public bool IsBaseTypeDefinition (TypeSpec baseType)
1968 // RootContext check
1969 if (TypeBuilder == null)
1974 if (type.MemberDefinition == baseType.MemberDefinition)
1977 type = type.BaseType;
1978 } while (type != null);
1983 public MemberCache LoadMembers (TypeSpec declaringType)
1985 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1988 public void Mark_HasEquals ()
1990 cached_method |= CachedMethods.Equals;
1993 public void Mark_HasGetHashCode ()
1995 cached_method |= CachedMethods.GetHashCode;
1999 /// Method container contains Equals method
2001 public bool HasEquals {
2003 return (cached_method & CachedMethods.Equals) != 0;
2008 /// Method container contains GetHashCode method
2010 public bool HasGetHashCode {
2012 return (cached_method & CachedMethods.GetHashCode) != 0;
2016 public bool HasStaticFieldInitializer {
2018 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2022 cached_method |= CachedMethods.HasStaticFieldInitializer;
2024 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2029 // Generates xml doc comments (if any), and if required,
2030 // handle warning report.
2032 internal override void GenerateDocComment (DeclSpace ds)
2034 DocUtil.GenerateTypeDocComment (this, ds, Report);
2037 public override string DocCommentHeader {
2038 get { return "T:"; }
2042 public abstract class ClassOrStruct : TypeContainer
2044 Dictionary<SecurityAction, PermissionSet> declarative_security;
2046 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2047 MemberName name, Attributes attrs, MemberKind kind)
2048 : base (ns, parent, name, attrs, kind)
2052 protected override bool AddToContainer (MemberCore symbol, string name)
2054 if (name == MemberName.Name) {
2055 if (symbol is TypeParameter) {
2056 Report.Error (694, symbol.Location,
2057 "Type parameter `{0}' has same name as containing type, or method",
2058 symbol.GetSignatureForError ());
2062 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2063 if (imb == null || !imb.IsExplicitImpl) {
2064 Report.SymbolRelatedToPreviousError (this);
2065 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2066 symbol.GetSignatureForError ());
2071 return base.AddToContainer (symbol, name);
2074 public override void VerifyMembers ()
2076 base.VerifyMembers ();
2078 if ((events != null) && Report.WarningLevel >= 3) {
2079 foreach (Event e in events){
2080 // Note: The event can be assigned from same class only, so we can report
2081 // this warning for all accessibility modes
2082 if ((e.caching_flags & Flags.IsUsed) == 0)
2083 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2088 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2090 if (a.IsValidSecurityAttribute ()) {
2091 if (declarative_security == null)
2092 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2094 a.ExtractSecurityPermissionSet (declarative_security);
2098 if (a.Type == pa.StructLayout) {
2099 PartialContainer.HasStructLayout = true;
2101 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2102 PartialContainer.HasExplicitLayout = true;
2105 if (a.Type == pa.Dynamic) {
2106 a.Error_MisusedDynamicAttribute ();
2110 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2114 /// Defines the default constructors
2116 protected void DefineDefaultConstructor (bool is_static)
2118 // The default instance constructor is public
2119 // If the class is abstract, the default constructor is protected
2120 // The default static constructor is private
2124 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2126 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2129 Constructor c = new Constructor (this, MemberName.Name, mods,
2130 null, ParametersCompiled.EmptyReadOnlyParameters,
2131 new GeneratedBaseInitializer (Location),
2135 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2138 protected override bool DoDefineMembers ()
2140 CheckProtectedModifier ();
2142 base.DoDefineMembers ();
2144 if (default_static_constructor != null)
2145 default_static_constructor.Define ();
2150 public override void Emit ()
2152 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2153 DefineDefaultConstructor (true);
2154 default_static_constructor.Define ();
2159 if (declarative_security != null) {
2160 foreach (var de in declarative_security) {
2161 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2166 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2168 DeclSpace top_level = Parent;
2169 if (top_level != null) {
2170 while (top_level.Parent != null)
2171 top_level = top_level.Parent;
2173 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2174 if (candidates != null)
2175 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2178 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2181 protected override TypeAttributes TypeAttr {
2183 if (default_static_constructor == null)
2184 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2186 return base.TypeAttr;
2192 // TODO: should be sealed
2193 public class Class : ClassOrStruct {
2194 const Modifiers AllowedModifiers =
2197 Modifiers.PROTECTED |
2198 Modifiers.INTERNAL |
2200 Modifiers.ABSTRACT |
2205 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2207 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2209 : base (ns, parent, name, attrs, MemberKind.Class)
2211 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2212 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2213 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2215 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2216 Report.FeatureIsNotAvailable (Location, "static classes");
2220 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2222 if (part.Name == "System.Object")
2223 Report.Error (537, part.Location,
2224 "The class System.Object cannot have a base class or implement an interface.");
2225 base.AddBasesForPart (part, bases);
2228 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2230 if (a.Type == pa.AttributeUsage) {
2231 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2232 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2236 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2237 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2241 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2242 a.Error_MissingGuidAttribute ();
2246 if (a.Type == pa.Extension) {
2247 a.Error_MisusedExtensionAttribute ();
2251 if (a.Type.IsConditionallyExcluded (Location))
2254 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2257 public override AttributeTargets AttributeTargets {
2259 return AttributeTargets.Class;
2263 protected override void DefineContainerMembers (System.Collections.IList list)
2269 base.DefineContainerMembers (list);
2273 foreach (MemberCore m in list) {
2274 if (m is Operator) {
2275 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2279 if (m is Destructor) {
2280 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2285 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2289 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2292 if (m is Constructor) {
2293 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2297 Method method = m as Method;
2298 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2299 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2303 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2306 base.DefineContainerMembers (list);
2309 protected override bool DoDefineMembers ()
2311 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2312 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2315 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2316 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2319 if (InstanceConstructors == null && !IsStatic)
2320 DefineDefaultConstructor (false);
2322 return base.DoDefineMembers ();
2325 public override void Emit ()
2329 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2330 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2333 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2335 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2337 if (base_class == null) {
2338 if (spec != TypeManager.object_type)
2339 base_class = TypeManager.system_object_expr;
2341 var base_type = base_class.Type;
2343 if (base_type.IsGenericParameter){
2344 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2345 GetSignatureForError (), base_type.GetSignatureForError ());
2346 } else if (IsGeneric && base_type.IsAttribute) {
2347 Report.Error (698, base_class.Location,
2348 "A generic type cannot derive from `{0}' because it is an attribute class",
2349 base_class.GetSignatureForError ());
2350 } else if (base_type.IsStatic) {
2351 Report.SymbolRelatedToPreviousError (base_class.Type);
2352 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2353 GetSignatureForError (), base_type.GetSignatureForError ());
2354 } else if (base_type.IsSealed){
2355 Report.SymbolRelatedToPreviousError (base_class.Type);
2356 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2357 GetSignatureForError (), base_type.GetSignatureForError ());
2360 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2361 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2362 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2363 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2364 GetSignatureForError (), base_type.GetSignatureForError ());
2365 base_class = TypeManager.system_object_expr;
2368 if (!IsAccessibleAs (base_type)) {
2369 Report.SymbolRelatedToPreviousError (base_type);
2370 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2371 base_type.GetSignatureForError (), GetSignatureForError ());
2375 if (PartialContainer.IsStatic) {
2376 if (base_class.Type != TypeManager.object_type) {
2377 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2378 GetSignatureForError (), base_class.GetSignatureForError ());
2382 if (ifaces != null) {
2383 foreach (TypeExpr t in ifaces)
2384 Report.SymbolRelatedToPreviousError (t.Type);
2385 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2392 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2393 /// Valid only for attribute classes.
2394 public override string[] ConditionalConditions ()
2396 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2399 caching_flags &= ~Flags.Excluded_Undetected;
2401 if (OptAttributes == null)
2404 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2408 string[] conditions = new string[attrs.Length];
2409 for (int i = 0; i < conditions.Length; ++i)
2410 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2412 caching_flags |= Flags.Excluded;
2417 // FIXME: How do we deal with the user specifying a different
2420 protected override TypeAttributes TypeAttr {
2422 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2424 ta |= StaticClassAttribute;
2430 public sealed class Struct : ClassOrStruct {
2432 bool is_unmanaged, has_unmanaged_check_done;
2436 // Modifiers allowed in a struct declaration
2438 const Modifiers AllowedModifiers =
2441 Modifiers.PROTECTED |
2442 Modifiers.INTERNAL |
2446 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2447 Modifiers mod, Attributes attrs)
2448 : base (ns, parent, name, attrs, MemberKind.Struct)
2450 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2451 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2452 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2455 public override AttributeTargets AttributeTargets {
2457 return AttributeTargets.Struct;
2461 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2463 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2466 // When struct constains fixed fixed and struct layout has explicitly
2467 // set CharSet, its value has to be propagated to compiler generated
2468 // fixed field types
2470 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2471 for (int i = 0; i < Fields.Count; ++i) {
2472 FixedField ff = Fields [i] as FixedField;
2474 ff.SetCharSet (TypeBuilder.Attributes);
2479 bool CheckStructCycles (Struct s)
2481 if (s.Fields == null)
2488 foreach (FieldBase field in s.Fields) {
2489 TypeSpec ftype = field.Spec.MemberType;
2490 if (!ftype.IsStruct)
2493 if (ftype is PredefinedTypeSpec)
2496 foreach (var targ in ftype.TypeArguments) {
2497 if (!CheckFieldTypeCycle (targ)) {
2498 Report.Error (523, field.Location,
2499 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2500 field.GetSignatureForError (), ftype.GetSignatureForError ());
2505 if ((field.IsStatic && !ftype.IsGeneric))
2508 if (!CheckFieldTypeCycle (ftype)) {
2509 Report.Error (523, field.Location,
2510 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2511 field.GetSignatureForError (), ftype.GetSignatureForError ());
2516 s.InTransit = false;
2520 bool CheckFieldTypeCycle (TypeSpec ts)
2522 var fts = ts.MemberDefinition as Struct;
2526 return CheckStructCycles (fts);
2529 public override void Emit ()
2531 CheckStructCycles (this);
2536 public override bool IsUnmanagedType ()
2541 if (has_unmanaged_check_done)
2542 return is_unmanaged;
2544 if (requires_delayed_unmanagedtype_check)
2547 requires_delayed_unmanagedtype_check = true;
2549 foreach (FieldBase f in fields) {
2553 // It can happen when recursive unmanaged types are defined
2554 // struct S { S* s; }
2555 TypeSpec mt = f.MemberType;
2560 while (mt.IsPointer)
2561 mt = TypeManager.GetElementType (mt);
2563 if (mt.MemberDefinition == this) {
2564 for (var p = Parent; p != null; p = p.Parent) {
2565 if (p.Kind == MemberKind.Class) {
2566 has_unmanaged_check_done = true;
2573 if (TypeManager.IsUnmanagedType (mt))
2576 has_unmanaged_check_done = true;
2580 has_unmanaged_check_done = true;
2581 is_unmanaged = true;
2585 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2587 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2588 base_class = TypeManager.system_valuetype_expr;
2592 protected override TypeAttributes TypeAttr {
2594 const TypeAttributes DefaultTypeAttributes =
2595 TypeAttributes.SequentialLayout |
2596 TypeAttributes.Sealed;
2598 return base.TypeAttr | DefaultTypeAttributes;
2602 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2604 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2605 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2606 field.GetSignatureForError ());
2609 base.RegisterFieldForInitialization (field, expression);
2617 public sealed class Interface : TypeContainer {
2620 /// Modifiers allowed in a class declaration
2622 public const Modifiers AllowedModifiers =
2625 Modifiers.PROTECTED |
2626 Modifiers.INTERNAL |
2630 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2632 : base (ns, parent, name, attrs, MemberKind.Interface)
2634 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2636 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2637 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2640 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2642 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2643 a.Error_MissingGuidAttribute ();
2647 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2651 public override AttributeTargets AttributeTargets {
2653 return AttributeTargets.Interface;
2657 protected override TypeAttributes TypeAttr {
2659 const TypeAttributes DefaultTypeAttributes =
2660 TypeAttributes.AutoLayout |
2661 TypeAttributes.Abstract |
2662 TypeAttributes.Interface;
2664 return base.TypeAttr | DefaultTypeAttributes;
2668 protected override bool VerifyClsCompliance ()
2670 if (!base.VerifyClsCompliance ())
2673 if (iface_exprs != null) {
2674 foreach (var iface in iface_exprs) {
2675 if (iface.Type.IsCLSCompliant ())
2678 Report.SymbolRelatedToPreviousError (iface.Type);
2679 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2680 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2688 public abstract class InterfaceMemberBase : MemberBase {
2690 // Whether this is an interface member.
2692 public bool IsInterface;
2695 // If true, this is an explicit interface implementation
2697 public bool IsExplicitImpl;
2699 protected bool is_external_implementation;
2702 // The interface type we are explicitly implementing
2704 public TypeSpec InterfaceType;
2707 // The method we're overriding if this is an override method.
2709 protected MethodSpec base_method;
2711 readonly Modifiers explicit_mod_flags;
2712 public MethodAttributes flags;
2714 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2715 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2716 MemberName name, Attributes attrs)
2717 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2720 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2721 IsExplicitImpl = (MemberName.Left != null);
2722 explicit_mod_flags = mod;
2725 protected override bool CheckBase ()
2727 if (!base.CheckBase ())
2730 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2731 CheckForDuplications ();
2736 // For System.Object only
2737 if (Parent.BaseType == null)
2740 MemberSpec candidate;
2741 var base_member = FindBaseMember (out candidate);
2743 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2744 if (base_member == null) {
2745 if (candidate == null) {
2746 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2747 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2748 "object.Finalize()");
2750 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2751 GetSignatureForError (), SimpleName.GetMemberType (this));
2754 Report.SymbolRelatedToPreviousError (candidate);
2756 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2757 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2758 else if (this is PropertyBase)
2759 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2760 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2762 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2763 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2769 if (!CheckOverrideAgainstBase (base_member))
2772 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2774 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2775 Report.SymbolRelatedToPreviousError (base_member);
2776 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2777 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2780 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2781 Report.SymbolRelatedToPreviousError (base_member);
2782 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2783 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2787 base_method = base_member as MethodSpec;
2791 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2792 base_member = candidate;
2794 if (base_member == null) {
2795 if ((ModFlags & Modifiers.NEW) != 0) {
2796 if (base_member == null) {
2797 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2798 GetSignatureForError ());
2802 if ((ModFlags & Modifiers.NEW) == 0) {
2803 ModFlags |= Modifiers.NEW;
2804 Report.SymbolRelatedToPreviousError (base_member);
2805 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2806 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",
2807 GetSignatureForError (), base_member.GetSignatureForError ());
2809 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2810 GetSignatureForError (), base_member.GetSignatureForError ());
2814 if (!IsInterface && base_member.IsAbstract) {
2815 Report.SymbolRelatedToPreviousError (base_member);
2816 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2817 GetSignatureForError (), base_member.GetSignatureForError ());
2824 protected virtual bool CheckForDuplications ()
2826 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2830 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2831 // that have been defined.
2833 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2837 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2838 Report.SymbolRelatedToPreviousError (base_member);
2839 Report.Error (506, Location,
2840 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2841 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2845 // Now we check that the overriden method is not final
2846 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2847 Report.SymbolRelatedToPreviousError (base_member);
2848 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2849 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2853 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2854 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2855 Report.SymbolRelatedToPreviousError (base_member);
2856 if (this is PropertyBasedMember) {
2857 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2858 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2860 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2861 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2869 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2871 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2872 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2874 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2876 // when overriding protected internal, the method can be declared
2877 // protected internal only within the same assembly or assembly
2878 // which has InternalsVisibleTo
2880 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2881 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2883 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2885 // if it's not "protected internal", it must be "protected"
2890 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2892 // protected within the same assembly - an error
2896 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2897 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2899 // protected ok, but other attributes differ - report an error
2906 return thisp == base_classp;
2909 public override bool Define ()
2912 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2913 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2915 flags = MethodAttributes.Public |
2916 MethodAttributes.Abstract |
2917 MethodAttributes.HideBySig |
2918 MethodAttributes.NewSlot |
2919 MethodAttributes.Virtual;
2921 Parent.PartialContainer.MethodModifiersValid (this);
2923 flags = ModifiersExtensions.MethodAttr (ModFlags);
2926 if (IsExplicitImpl) {
2927 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2928 if (iface_texpr == null)
2931 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2932 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2933 GetSignatureForError ());
2936 InterfaceType = iface_texpr.Type;
2938 if (!InterfaceType.IsInterface) {
2939 Report.SymbolRelatedToPreviousError (InterfaceType);
2940 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2941 TypeManager.CSharpName (InterfaceType));
2943 Parent.PartialContainer.VerifyImplements (this);
2946 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2949 return base.Define ();
2952 protected bool DefineParameters (ParametersCompiled parameters)
2954 if (!parameters.Resolve (this))
2958 for (int i = 0; i < parameters.Count; ++i) {
2959 Parameter p = parameters [i];
2961 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2962 p.Warning_UselessOptionalParameter (Report);
2964 if (p.CheckAccessibility (this))
2967 TypeSpec t = parameters.Types [i];
2968 Report.SymbolRelatedToPreviousError (t);
2969 if (this is Indexer)
2970 Report.Error (55, Location,
2971 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2972 TypeManager.CSharpName (t), GetSignatureForError ());
2973 else if (this is Operator)
2974 Report.Error (57, Location,
2975 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2976 TypeManager.CSharpName (t), GetSignatureForError ());
2978 Report.Error (51, Location,
2979 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2980 TypeManager.CSharpName (t), GetSignatureForError ());
2986 public override void Emit()
2988 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2989 // We are more strict than csc and report this as an error because SRE does not allow emit that
2990 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2991 if (this is Constructor) {
2992 Report.Error (824, Location,
2993 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
2995 Report.Error (626, Location,
2996 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
2997 GetSignatureForError ());
3004 public override bool EnableOverloadChecks (MemberCore overload)
3007 // Two members can differ in their explicit interface
3008 // type parameter only
3010 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3011 if (imb != null && imb.IsExplicitImpl) {
3012 if (IsExplicitImpl) {
3013 caching_flags |= Flags.MethodOverloadsExist;
3018 return IsExplicitImpl;
3021 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3023 Report.SymbolRelatedToPreviousError (base_member);
3024 Report.Error (507, member.Location,
3025 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3026 member.GetSignatureForError (),
3027 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3028 base_member.GetSignatureForError ());
3031 protected void Error_StaticReturnType ()
3033 Report.Error (722, Location,
3034 "`{0}': static types cannot be used as return types",
3035 MemberType.GetSignatureForError ());
3039 /// Gets base method and its return type
3041 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3043 return MemberCache.FindBaseMember (this, out bestCandidate);
3047 // The "short" name of this property / indexer / event. This is the
3048 // name without the explicit interface.
3050 public string ShortName {
3051 get { return MemberName.Name; }
3052 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3056 // Returns full metadata method name
3058 public string GetFullName (MemberName name)
3060 return GetFullName (name.Name);
3063 public string GetFullName (string name)
3065 if (!IsExplicitImpl)
3069 // When dealing with explicit members a full interface type
3070 // name is added to member name to avoid possible name conflicts
3072 // We use CSharpName which gets us full name with benefit of
3073 // replacing predefined names which saves some space and name
3076 return TypeManager.CSharpName (InterfaceType) + "." + name;
3079 protected override bool VerifyClsCompliance ()
3081 if (!base.VerifyClsCompliance ()) {
3085 if (GenericMethod != null)
3086 GenericMethod.VerifyClsCompliance ();
3091 public override bool IsUsed
3093 get { return IsExplicitImpl || base.IsUsed; }
3098 public abstract class MemberBase : MemberCore
3100 protected FullNamedExpression type_expr;
3101 protected TypeSpec member_type;
3103 public readonly DeclSpace ds;
3104 public readonly GenericMethod GenericMethod;
3106 protected MemberBase (DeclSpace parent, GenericMethod generic,
3107 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3108 MemberName name, Attributes attrs)
3109 : base (parent, name, attrs)
3111 this.ds = generic != null ? generic : (DeclSpace) parent;
3112 this.type_expr = type;
3113 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3114 GenericMethod = generic;
3115 if (GenericMethod != null)
3116 GenericMethod.ModFlags = ModFlags;
3120 // Main member define entry
3122 public override bool Define ()
3124 DoMemberTypeIndependentChecks ();
3127 // Returns false only when type resolution failed
3129 if (!ResolveMemberType ())
3132 DoMemberTypeDependentChecks ();
3137 // Any type_name independent checks
3139 protected virtual void DoMemberTypeIndependentChecks ()
3141 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3142 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3143 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3144 GetSignatureForError (), Parent.GetSignatureForError ());
3149 // Any type_name dependent checks
3151 protected virtual void DoMemberTypeDependentChecks ()
3153 // verify accessibility
3154 if (!IsAccessibleAs (MemberType)) {
3155 Report.SymbolRelatedToPreviousError (MemberType);
3156 if (this is Property)
3157 Report.Error (53, Location,
3158 "Inconsistent accessibility: property type `" +
3159 TypeManager.CSharpName (MemberType) + "' is less " +
3160 "accessible than property `" + GetSignatureForError () + "'");
3161 else if (this is Indexer)
3162 Report.Error (54, Location,
3163 "Inconsistent accessibility: indexer return type `" +
3164 TypeManager.CSharpName (MemberType) + "' is less " +
3165 "accessible than indexer `" + GetSignatureForError () + "'");
3166 else if (this is MethodCore) {
3167 if (this is Operator)
3168 Report.Error (56, Location,
3169 "Inconsistent accessibility: return type `" +
3170 TypeManager.CSharpName (MemberType) + "' is less " +
3171 "accessible than operator `" + GetSignatureForError () + "'");
3173 Report.Error (50, Location,
3174 "Inconsistent accessibility: return type `" +
3175 TypeManager.CSharpName (MemberType) + "' is less " +
3176 "accessible than method `" + GetSignatureForError () + "'");
3178 Report.Error (52, Location,
3179 "Inconsistent accessibility: field type `" +
3180 TypeManager.CSharpName (MemberType) + "' is less " +
3181 "accessible than field `" + GetSignatureForError () + "'");
3185 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3186 TypeManager.CheckTypeVariance (MemberType, variance, this);
3189 protected bool IsTypePermitted ()
3191 if (TypeManager.IsSpecialType (MemberType)) {
3192 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3198 protected virtual bool CheckBase ()
3200 CheckProtectedModifier ();
3205 public TypeSpec MemberType {
3206 get { return member_type; }
3209 protected virtual bool ResolveMemberType ()
3211 if (member_type != null)
3212 throw new InternalErrorException ("Multi-resolve");
3214 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3219 // Replace original type name, error reporting can use fully resolved name
3223 member_type = te.Type;