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.Runtime.InteropServices;
17 using System.Security;
18 using System.Security.Permissions;
22 using XmlElement = System.Object;
26 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
27 using IKVM.Reflection;
28 using IKVM.Reflection.Emit;
30 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
31 using System.Reflection;
32 using System.Reflection.Emit;
35 namespace Mono.CSharp {
38 /// This is the base class for structs and classes.
40 public abstract class TypeContainer : DeclSpace, ITypeDefinition
43 // Different context is needed when resolving type container base
44 // types. Type names come from the parent scope but type parameter
45 // names from the container scope.
47 public struct BaseContext : IMemberContext
51 public BaseContext (TypeContainer tc)
56 #region IMemberContext Members
58 public CompilerContext Compiler {
59 get { return tc.Compiler; }
62 public TypeSpec CurrentType {
63 get { return tc.Parent.CurrentType; }
66 public TypeParameter[] CurrentTypeParameters {
67 get { return tc.PartialContainer.CurrentTypeParameters; }
70 public MemberCore CurrentMemberDefinition {
74 public bool HasUnresolvedConstraints {
78 public bool IsObsolete {
79 get { return tc.IsObsolete; }
82 public bool IsUnsafe {
83 get { return tc.IsUnsafe; }
86 public bool IsStatic {
87 get { return tc.IsStatic; }
90 public ModuleContainer Module {
91 get { return tc.Module; }
94 public string GetSignatureForError ()
96 return tc.GetSignatureForError ();
99 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
104 public FullNamedExpression LookupNamespaceAlias (string name)
106 return tc.Parent.LookupNamespaceAlias (name);
109 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
112 TypeParameter[] tp = CurrentTypeParameters;
114 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
116 return new TypeParameterExpr (t, loc);
120 return tc.Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
130 GetHashCode = 1 << 1,
131 HasStaticFieldInitializer = 1 << 2
135 // Whether this is a struct, class or interface
136 public readonly MemberKind Kind;
138 // Holds a list of classes and structures
139 protected List<TypeContainer> types;
141 List<MemberCore> ordered_explicit_member_list;
142 List<MemberCore> ordered_member_list;
144 // Holds the list of properties
145 List<MemberCore> properties;
147 // Holds the list of constructors
148 protected List<Constructor> instance_constructors;
150 // Holds the list of fields
151 protected List<FieldBase> fields;
153 // Holds a list of fields that have initializers
154 protected List<FieldInitializer> initialized_fields;
156 // Holds a list of static fields that have initializers
157 protected List<FieldInitializer> initialized_static_fields;
159 // Holds the list of constants
160 protected List<MemberCore> constants;
162 // Holds the methods.
163 List<MemberCore> methods;
166 protected List<MemberCore> events;
168 // Holds the indexers
169 List<MemberCore> indexers;
171 // Holds the operators
172 List<MemberCore> operators;
174 // Holds the compiler generated classes
175 protected List<CompilerGeneratedClass> compiler_generated;
177 Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
179 Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
182 // Pointers to the default constructor and the default static constructor
184 protected Constructor default_constructor;
185 protected Constructor default_static_constructor;
188 // Points to the first non-static field added to the container.
190 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
191 // and the first one's as good as any.
193 FieldBase first_nonstatic_field;
196 // This one is computed after we can distinguish interfaces
197 // from classes from the arraylist `type_bases'
199 protected TypeSpec base_type;
200 protected TypeExpr base_type_expr;
201 protected TypeExpr[] iface_exprs;
203 protected List<FullNamedExpression> type_bases;
205 bool members_defined;
206 bool members_defined_ok;
209 TypeContainer InTransit;
211 GenericTypeParameterBuilder[] all_tp_builders;
213 public const string DefaultIndexerName = "Item";
215 private bool seen_normal_indexers = false;
216 private string indexer_name = DefaultIndexerName;
217 protected bool requires_delayed_unmanagedtype_check;
220 private CachedMethods cached_method;
222 protected TypeSpec spec;
223 TypeSpec current_type;
225 List<TypeContainer> partial_parts;
227 public int DynamicSitesCounter;
230 /// The pending methods that need to be implemented
231 // (interfaces or abstract methods)
233 PendingImplementation pending;
235 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
236 Attributes attrs, MemberKind kind)
237 : base (ns, parent, name, attrs)
239 if (parent != null && parent.NamespaceEntry != ns)
240 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
243 this.PartialContainer = this;
248 public override TypeSpec CurrentType {
250 if (current_type == null) {
253 // Switch to inflated version as it's used by all expressions
255 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
256 current_type = spec.MakeGenericType (this, targs);
266 public override TypeParameter[] CurrentTypeParameters {
268 return PartialContainer.type_params;
272 int CurrentTypeParametersStartIndex {
274 int total = all_tp_builders.Length;
275 if (CurrentTypeParameters != null) {
276 return total - CurrentTypeParameters.Length;
282 public virtual AssemblyDefinition DeclaringAssembly {
284 return Module.DeclaringAssembly;
288 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
290 return Module.DeclaringAssembly;
294 public TypeSpec Definition {
300 public bool HasMembersDefined {
302 return members_defined;
308 public abstract void Accept (StructuralVisitor visitor);
310 public bool AddMember (MemberCore symbol)
312 return AddToContainer (symbol, symbol.MemberName.Basename);
315 public bool AddMember (MemberCore symbol, string name)
317 return AddToContainer (symbol, name);
320 protected virtual bool AddMemberType (TypeContainer ds)
322 return AddToContainer (ds, ds.Basename);
325 protected virtual void RemoveMemberType (DeclSpace ds)
327 RemoveFromContainer (ds.Basename);
330 public void AddConstant (Const constant)
332 if (!AddMember (constant))
335 if (constants == null)
336 constants = new List<MemberCore> ();
338 constants.Add (constant);
341 public TypeContainer AddTypeContainer (TypeContainer tc)
343 if (!AddMemberType (tc))
347 types = new List<TypeContainer> ();
353 public virtual TypeContainer AddPartial (TypeContainer next_part)
355 return AddPartial (next_part, next_part.Basename);
358 protected TypeContainer AddPartial (TypeContainer next_part, string name)
360 next_part.ModFlags |= Modifiers.PARTIAL;
361 TypeContainer tc = GetDefinition (name) as TypeContainer;
363 return AddTypeContainer (next_part);
365 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
366 Report.SymbolRelatedToPreviousError (next_part);
367 Error_MissingPartialModifier (tc);
370 if (tc.Kind != next_part.Kind) {
371 Report.SymbolRelatedToPreviousError (tc);
372 Report.Error (261, next_part.Location,
373 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
374 next_part.GetSignatureForError ());
377 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
378 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
379 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
380 Report.SymbolRelatedToPreviousError (tc);
381 Report.Error (262, next_part.Location,
382 "Partial declarations of `{0}' have conflicting accessibility modifiers",
383 next_part.GetSignatureForError ());
386 if (tc.partial_parts == null)
387 tc.partial_parts = new List<TypeContainer> (1);
389 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
390 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
391 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
392 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
393 tc.ModFlags |= next_part.ModFlags;
395 tc.ModFlags |= next_part.ModFlags;
398 tc.spec.Modifiers = tc.ModFlags;
400 if (next_part.attributes != null) {
401 if (tc.attributes == null)
402 tc.attributes = next_part.attributes;
404 tc.attributes.AddAttributes (next_part.attributes.Attrs);
407 next_part.PartialContainer = tc;
408 tc.partial_parts.Add (next_part);
412 public virtual void RemoveTypeContainer (TypeContainer next_part)
415 types.Remove (next_part);
417 Cache.Remove (next_part.Basename);
418 RemoveMemberType (next_part);
421 public virtual TypeSpec AddDelegate (Delegate d)
423 AddTypeContainer (d);
427 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
429 if (ordered_explicit_member_list == null) {
430 ordered_explicit_member_list = new List<MemberCore> ();
431 ordered_member_list = new List<MemberCore> ();
435 if (Kind == MemberKind.Interface) {
436 Report.Error (541, mc.Location,
437 "`{0}': explicit interface declaration can only be declared in a class or struct",
438 mc.GetSignatureForError ());
441 ordered_explicit_member_list.Add (mc);
442 alist.Insert (0, mc);
444 ordered_member_list.Add (mc);
450 public void AddMethod (MethodOrOperator method)
452 if (!AddToContainer (method, method.MemberName.Basename))
456 methods = new List<MemberCore> ();
458 if (method.MemberName.Left != null)
459 AddMemberToList (method, methods, true);
461 AddMemberToList (method, methods, false);
464 public void AddConstructor (Constructor c)
466 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
467 if (!AddToContainer (c, is_static ? Constructor.ConstructorName : Constructor.TypeConstructorName))
470 if (is_static && c.ParameterInfo.IsEmpty){
471 if (default_static_constructor != null) {
472 Report.SymbolRelatedToPreviousError (default_static_constructor);
473 Report.Error (111, c.Location,
474 "A member `{0}' is already defined. Rename this member or use different parameter types",
475 c.GetSignatureForError ());
479 default_static_constructor = c;
481 if (c.ParameterInfo.IsEmpty)
482 default_constructor = c;
484 if (instance_constructors == null)
485 instance_constructors = new List<Constructor> ();
487 instance_constructors.Add (c);
491 public bool AddField (FieldBase field)
493 if (!AddMember (field))
497 fields = new List<FieldBase> ();
501 if ((field.ModFlags & Modifiers.STATIC) != 0)
504 if (first_nonstatic_field == null) {
505 first_nonstatic_field = field;
509 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
510 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
511 Report.Warning (282, 3, field.Location,
512 "struct instance field `{0}' found in different declaration from instance field `{1}'",
513 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
518 public void AddProperty (Property prop)
520 if (!AddMember (prop))
523 if (properties == null)
524 properties = new List<MemberCore> ();
526 if (prop.MemberName.Left != null)
527 AddMemberToList (prop, properties, true);
529 AddMemberToList (prop, properties, false);
532 public void AddEvent (Event e)
538 events = new List<MemberCore> ();
544 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
546 public void AddIndexer (Indexer i)
548 if (indexers == null)
549 indexers = new List<MemberCore> ();
551 if (i.IsExplicitImpl)
552 AddMemberToList (i, indexers, true);
554 AddMemberToList (i, indexers, false);
557 public void AddOperator (Operator op)
562 if (operators == null)
563 operators = new List<MemberCore> ();
568 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
570 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
572 if (compiler_generated == null)
573 compiler_generated = new List<CompilerGeneratedClass> ();
575 compiler_generated.Add (c);
578 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
580 if (a.Type == pa.DefaultMember) {
581 if (Indexers != null) {
582 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
587 if (a.Type == pa.Required) {
588 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
592 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
595 public override AttributeTargets AttributeTargets {
597 throw new NotSupportedException ();
601 public IList<TypeContainer> Types {
607 public IList<MemberCore> Methods {
613 public IList<MemberCore> Constants {
619 public TypeSpec BaseType {
621 return spec.BaseType;
625 public IList<FieldBase> Fields {
631 public IList<Constructor> InstanceConstructors {
633 return instance_constructors;
637 public IList<MemberCore> Properties {
643 public IList<MemberCore> Events {
649 public IList<MemberCore> Indexers {
655 public IList<MemberCore> Operators {
661 protected override TypeAttributes TypeAttr {
663 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel);
667 public int TypeParametersCount {
669 return MemberName.Arity;
673 TypeParameterSpec[] ITypeDefinition.TypeParameters {
675 // TODO MemberCache: this is going to hurt
676 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
680 public string GetAttributeDefaultMember ()
682 return indexers == null ? DefaultIndexerName : indexer_name;
685 public bool IsComImport {
687 if (OptAttributes == null)
690 return OptAttributes.Contains (Module.PredefinedAttributes.ComImport);
694 string ITypeDefinition.Namespace {
696 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
700 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
702 if ((field.ModFlags & Modifiers.STATIC) != 0){
703 if (initialized_static_fields == null) {
704 PartialContainer.HasStaticFieldInitializer = true;
705 initialized_static_fields = new List<FieldInitializer> (4);
708 initialized_static_fields.Add (expression);
710 if (initialized_fields == null)
711 initialized_fields = new List<FieldInitializer> (4);
713 initialized_fields.Add (expression);
717 public void ResolveFieldInitializers (BlockContext ec)
719 if (partial_parts != null) {
720 foreach (TypeContainer part in partial_parts) {
721 part.DoResolveFieldInitializers (ec);
724 DoResolveFieldInitializers (ec);
727 void DoResolveFieldInitializers (BlockContext ec)
730 if (initialized_static_fields == null)
733 bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize;
735 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
736 for (i = 0; i < initialized_static_fields.Count; ++i) {
737 FieldInitializer fi = initialized_static_fields [i];
738 ExpressionStatement s = fi.ResolveStatement (ec);
740 s = EmptyExpressionStatement.Instance;
741 } else if (fi.IsComplexInitializer) {
742 has_complex_initializer |= true;
748 for (i = 0; i < initialized_static_fields.Count; ++i) {
749 FieldInitializer fi = initialized_static_fields [i];
751 // Need special check to not optimize code like this
752 // static int a = b = 5;
755 if (!has_complex_initializer && fi.IsDefaultInitializer)
758 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
764 if (initialized_fields == null)
767 for (int i = 0; i < initialized_fields.Count; ++i) {
768 FieldInitializer fi = initialized_fields [i];
769 ExpressionStatement s = fi.ResolveStatement (ec);
774 // Field is re-initialized to its default value => removed
776 if (fi.IsDefaultInitializer && ec.Module.Compiler.Settings.Optimize)
779 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
783 public override string DocComment {
795 public PendingImplementation PendingImplementations {
796 get { return pending; }
799 public TypeSpec GetAttributeCoClass ()
801 if (OptAttributes == null)
804 Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass);
808 return a.GetCoClassAttributeValue ();
811 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
814 if (OptAttributes != null) {
815 a = OptAttributes.Search (pa);
821 return a.GetAttributeUsageAttribute ();
824 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
826 // FIXME: get rid of partial_parts and store lists of bases of each part here
827 // assumed, not verified: 'part' is in 'partial_parts'
828 ((TypeContainer) part).type_bases = bases;
832 /// This function computes the Base class and also the
833 /// list of interfaces that the class or struct @c implements.
835 /// The return value is an array (might be null) of
836 /// interfaces implemented (as Types).
838 /// The @base_class argument is set to the base object or null
839 /// if this is `System.Object'.
841 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
844 if (type_bases == null)
847 int count = type_bases.Count;
848 TypeExpr [] ifaces = null;
849 var base_context = new BaseContext (this);
850 for (int i = 0, j = 0; i < count; i++){
851 FullNamedExpression fne = type_bases [i];
853 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
854 if (fne_resolved == null)
857 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
858 if (fne_resolved.Type == InternalType.Dynamic) {
859 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
860 GetSignatureForError ());
865 base_type = fne_resolved.Type;
866 base_class = fne_resolved;
871 ifaces = new TypeExpr [count - i];
873 if (fne_resolved.Type.IsInterface) {
874 for (int ii = 0; ii < j; ++ii) {
875 if (fne_resolved.Type == ifaces [ii].Type) {
876 Report.Error (528, Location, "`{0}' is already listed in interface list",
877 fne_resolved.GetSignatureForError ());
882 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
883 Report.Error (61, fne.Location,
884 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
885 fne_resolved.GetSignatureForError (), GetSignatureForError ());
888 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
889 if (Kind != MemberKind.Class) {
890 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
891 } else if (base_class != null)
892 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
893 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
895 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
896 GetSignatureForError (), fne_resolved.GetSignatureForError ());
900 ifaces [j++] = fne_resolved;
906 TypeExpr[] GetNormalPartialBases ()
908 var ifaces = new List<TypeExpr> (0);
909 if (iface_exprs != null)
910 ifaces.AddRange (iface_exprs);
912 foreach (TypeContainer part in partial_parts) {
913 TypeExpr new_base_class;
914 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
915 if (new_base_class != null) {
916 if (base_type_expr != null && new_base_class.Type != base_type) {
917 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
918 Report.Error (263, part.Location,
919 "Partial declarations of `{0}' must not specify different base classes",
920 part.GetSignatureForError ());
922 base_type_expr = new_base_class;
923 base_type = base_type_expr.Type;
927 if (new_ifaces == null)
930 foreach (TypeExpr iface in new_ifaces) {
931 if (ifaces.Contains (iface))
938 if (ifaces.Count == 0)
941 return ifaces.ToArray ();
945 // Checks that some operators come in pairs:
951 // They are matched based on the return type and the argument types
953 void CheckPairedOperators ()
955 bool has_equality_or_inequality = false;
956 var operators = this.operators.ToArray ();
957 bool[] has_pair = new bool[operators.Length];
959 for (int i = 0; i < operators.Length; ++i) {
960 if (operators[i] == null)
963 Operator o_a = (Operator) operators[i];
964 Operator.OpType o_type = o_a.OperatorType;
965 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
966 has_equality_or_inequality = true;
968 Operator.OpType matching_type = o_a.GetMatchingOperator ();
969 if (matching_type == Operator.OpType.TOP) {
974 for (int ii = 0; ii < operators.Length; ++ii) {
975 Operator o_b = (Operator) operators[ii];
976 if (o_b == null || o_b.OperatorType != matching_type)
979 if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
982 if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
988 // Used to ignore duplicate user conversions
994 for (int i = 0; i < operators.Length; ++i) {
995 if (operators[i] == null || has_pair[i])
998 Operator o = (Operator) operators [i];
999 Report.Error (216, o.Location,
1000 "The operator `{0}' requires a matching operator `{1}' to also be defined",
1001 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
1004 if (has_equality_or_inequality) {
1005 if (Methods == null || !HasEquals)
1006 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
1007 GetSignatureForError ());
1009 if (Methods == null || !HasGetHashCode)
1010 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
1011 GetSignatureForError ());
1015 bool CreateTypeBuilder ()
1018 // Sets .size to 1 for structs with no instance fields
1020 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1023 // TODO: Completely wrong
1024 if (Module.GlobalRootNamespace.IsNamespace (Name)) {
1025 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1028 TypeBuilder = Module.CreateBuilder (Name, TypeAttr, type_size);
1030 TypeBuilder = Parent.TypeBuilder.DefineNestedType (Basename, TypeAttr, null, type_size);
1033 if (DeclaringAssembly.Importer != null)
1034 DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec);
1036 spec.SetMetaInfo (TypeBuilder);
1037 spec.MemberCache = new MemberCache (this);
1038 spec.DeclaringType = Parent.CurrentType;
1041 Parent.MemberCache.AddMember (spec);
1044 string[] param_names = new string[TypeParameters.Length];
1045 for (int i = 0; i < TypeParameters.Length; i++)
1046 param_names [i] = TypeParameters[i].Name;
1048 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1050 int offset = CurrentTypeParametersStartIndex;
1051 for (int i = offset; i < all_tp_builders.Length; i++) {
1052 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1060 // Creates a proxy base method call inside this container for hoisted base member calls
1062 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1064 Method proxy_method;
1067 // One proxy per base method is enough
1069 if (hoisted_base_call_proxies == null) {
1070 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1071 proxy_method = null;
1073 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1076 if (proxy_method == null) {
1077 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1078 var base_parameters = new Parameter[method.Parameters.Count];
1079 for (int i = 0; i < base_parameters.Length; ++i) {
1080 var base_param = method.Parameters.FixedParameters[i];
1081 base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1082 base_param.Name, base_param.ModFlags, null, Location);
1083 base_parameters[i].Resolve (this, i);
1086 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1087 if (method.Parameters.HasArglist) {
1088 cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1089 cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve (Location);
1092 GenericMethod generic_method;
1093 MemberName member_name;
1094 if (method.IsGeneric) {
1096 // Copy all base generic method type parameters info
1098 var hoisted_tparams = method.GenericDefinition.TypeParameters;
1099 var targs = new TypeArguments ();
1100 var type_params = new TypeParameter[hoisted_tparams.Length];
1101 for (int i = 0; i < type_params.Length; ++i) {
1102 var tp = hoisted_tparams[i];
1103 targs.Add (new TypeParameterName (tp.Name, null, Location));
1104 type_params[i] = new TypeParameter (tp, this, null, new MemberName (tp.Name), null);
1107 member_name = new MemberName (name, targs, Location);
1108 generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1109 new TypeExpression (method.ReturnType, Location), cloned_params);
1111 member_name = new MemberName (name);
1112 generic_method = null;
1115 // Compiler generated proxy
1116 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1117 Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1118 member_name, cloned_params, null);
1120 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1122 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1123 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1125 // Get all the method parameters and pass them as arguments
1126 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1127 Statement statement;
1128 if (method.ReturnType == TypeManager.void_type)
1129 statement = new StatementExpression (real_base_call);
1131 statement = new Return (real_base_call, Location);
1133 block.AddStatement (statement);
1134 proxy_method.Block = block;
1136 methods.Add (proxy_method);
1137 proxy_method.Define ();
1139 hoisted_base_call_proxies.Add (method, proxy_method);
1142 return proxy_method.Spec;
1145 bool DefineBaseTypes ()
1147 iface_exprs = ResolveBaseTypes (out base_type_expr);
1148 if (partial_parts != null) {
1149 iface_exprs = GetNormalPartialBases ();
1152 var cycle = CheckRecursiveDefinition (this);
1153 if (cycle != null) {
1154 Report.SymbolRelatedToPreviousError (cycle);
1155 if (this is Interface) {
1156 Report.Error (529, Location,
1157 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1158 GetSignatureForError (), cycle.GetSignatureForError ());
1162 Report.Error (146, Location,
1163 "Circular base class dependency involving `{0}' and `{1}'",
1164 GetSignatureForError (), cycle.GetSignatureForError ());
1170 if (iface_exprs != null) {
1171 foreach (TypeExpr iface in iface_exprs) {
1172 // Prevents a crash, the interface might not have been resolved: 442144
1176 var iface_type = iface.Type;
1178 if (!spec.AddInterface (iface_type))
1181 if (iface_type.IsGeneric && spec.Interfaces != null) {
1182 foreach (var prev_iface in iface_exprs) {
1183 if (prev_iface == iface)
1186 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1189 Report.Error (695, Location,
1190 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1191 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1195 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1197 // Ensure the base is always setup
1198 var compiled_iface = iface_type.MemberDefinition as Interface;
1199 if (compiled_iface != null) {
1200 // TODO: Need DefineBaseType only
1201 compiled_iface.DefineType ();
1204 if (iface_type.Interfaces != null) {
1205 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1206 for (int i = 0; i < base_ifaces.Count; ++i) {
1207 var ii_iface_type = base_ifaces[i];
1208 if (spec.AddInterface (ii_iface_type)) {
1209 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1211 if (ii_iface_type.Interfaces != null)
1212 base_ifaces.AddRange (ii_iface_type.Interfaces);
1219 if (Kind == MemberKind.Interface) {
1220 spec.BaseType = TypeManager.object_type;
1224 if (base_type != null) {
1225 spec.BaseType = base_type;
1227 // Set base type after type creation
1228 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1230 TypeBuilder.SetParent (null);
1236 public virtual void DefineConstants ()
1238 if (constants != null) {
1239 foreach (Const c in constants) {
1244 if (instance_constructors != null) {
1245 foreach (MethodCore m in instance_constructors) {
1246 var p = m.ParameterInfo;
1248 p.ResolveDefaultValues (m);
1253 if (methods != null) {
1254 foreach (MethodCore m in methods) {
1255 var p = m.ParameterInfo;
1257 p.ResolveDefaultValues (m);
1262 if (indexers != null) {
1263 foreach (Indexer i in indexers) {
1264 i.ParameterInfo.ResolveDefaultValues (i);
1268 if (types != null) {
1269 foreach (var t in types)
1270 t.DefineConstants ();
1275 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1277 public bool CreateType ()
1279 if (TypeBuilder != null)
1285 if (!CreateTypeBuilder ()) {
1290 if (partial_parts != null) {
1291 foreach (TypeContainer part in partial_parts) {
1293 part.current_type = current_type;
1294 part.TypeBuilder = TypeBuilder;
1298 if (Types != null) {
1299 foreach (TypeContainer tc in Types) {
1307 public override void DefineType ()
1314 type_defined = true;
1316 if (!DefineBaseTypes ()) {
1321 if (!DefineNestedTypes ()) {
1327 public override void SetParameterInfo (List<Constraints> constraints_list)
1329 base.SetParameterInfo (constraints_list);
1331 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1334 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1335 for (int i = 0; i < tc_names.Length; ++i) {
1336 if (tc_names [i].Name != type_params [i].Name) {
1337 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1338 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1339 GetSignatureForError ());
1343 if (tc_names [i].Variance != type_params [i].Variance) {
1344 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1345 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1346 GetSignatureForError ());
1353 // Replaces normal spec with predefined one when compiling corlib
1354 // and this type container defines predefined type
1356 public void SetPredefinedSpec (BuildinTypeSpec spec)
1358 // When compiling build-in types we start with two
1359 // version of same type. One is of BuildinTypeSpec and
1360 // second one is ordinary TypeSpec. The unification
1361 // happens at later stage when we know which type
1362 // really matches the buildin type signature. However
1363 // that means TypeSpec create during CreateType of this
1364 // type has to be replaced with buildin one
1366 spec.SetMetaInfo (TypeBuilder);
1367 spec.MemberCache = this.spec.MemberCache;
1368 spec.DeclaringType = this.spec.DeclaringType;
1371 current_type = null;
1374 void UpdateTypeParameterConstraints (TypeContainer part)
1376 TypeParameter[] current_params = type_params;
1377 for (int i = 0; i < current_params.Length; i++) {
1378 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1381 Report.SymbolRelatedToPreviousError (Location, "");
1382 Report.Error (265, part.Location,
1383 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1384 GetSignatureForError (), current_params [i].GetSignatureForError ());
1388 public bool ResolveTypeParameters ()
1390 if (!DoResolveTypeParameters ())
1393 if (types != null) {
1394 foreach (var type in types)
1395 if (!type.ResolveTypeParameters ())
1399 if (compiler_generated != null) {
1400 foreach (CompilerGeneratedClass c in compiler_generated)
1401 if (!c.ResolveTypeParameters ())
1408 protected virtual bool DoResolveTypeParameters ()
1410 if (CurrentTypeParameters == null)
1413 if (PartialContainer != this)
1414 throw new InternalErrorException ();
1416 var base_context = new BaseContext (this);
1417 foreach (TypeParameter type_param in CurrentTypeParameters) {
1418 if (!type_param.ResolveConstraints (base_context)) {
1424 if (partial_parts != null) {
1425 foreach (TypeContainer part in partial_parts)
1426 UpdateTypeParameterConstraints (part);
1432 protected virtual bool DefineNestedTypes ()
1434 if (Types != null) {
1435 foreach (TypeContainer tc in Types)
1442 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1444 if (InTransit != null)
1449 if (base_type_expr != null) {
1450 var ptc = base_type.MemberDefinition as TypeContainer;
1451 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1455 if (iface_exprs != null) {
1456 foreach (TypeExpr iface in iface_exprs) {
1457 // the interface might not have been resolved, prevents a crash, see #442144
1460 var ptc = iface.Type.MemberDefinition as Interface;
1461 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1466 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1474 /// Populates our TypeBuilder with fields and methods
1476 public sealed override bool Define ()
1478 if (members_defined)
1479 return members_defined_ok;
1481 members_defined_ok = DoDefineMembers ();
1482 members_defined = true;
1484 if (types != null) {
1485 foreach (var nested in types)
1489 return members_defined_ok;
1492 protected virtual bool DoDefineMembers ()
1494 if (iface_exprs != null) {
1495 foreach (TypeExpr iface in iface_exprs) {
1499 var iface_type = iface.Type;
1501 // Ensure the base is always setup
1502 var compiled_iface = iface_type.MemberDefinition as Interface;
1503 if (compiled_iface != null)
1504 compiled_iface.Define ();
1506 if (Kind == MemberKind.Interface)
1507 MemberCache.AddInterface (iface_type);
1509 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1510 if (oa != null && !IsObsolete)
1511 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1513 GenericTypeExpr ct = iface as GenericTypeExpr;
1515 // TODO: passing `this' is wrong, should be base type iface instead
1516 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1518 ct.CheckConstraints (this);
1520 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1521 Report.Error (1966, iface.Location,
1522 "`{0}': cannot implement a dynamic interface `{1}'",
1523 GetSignatureForError (), iface.GetSignatureForError ());
1530 if (base_type != null) {
1531 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1532 if (obsolete_attr != null && !IsObsolete)
1533 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1535 var ct = base_type_expr as GenericTypeExpr;
1537 ct.CheckConstraints (this);
1539 if (base_type.Interfaces != null) {
1540 foreach (var iface in base_type.Interfaces)
1541 spec.AddInterface (iface);
1544 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1545 if (baseContainer != null) {
1546 baseContainer.Define ();
1549 // It can trigger define of this type (for generic types only)
1551 if (HasMembersDefined)
1556 if (type_params != null) {
1557 foreach (var tp in type_params) {
1558 tp.CheckGenericConstraints ();
1562 DefineContainerMembers (constants);
1563 DefineContainerMembers (fields);
1565 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1566 pending = PendingImplementation.GetPendingImplementations (this);
1568 if (requires_delayed_unmanagedtype_check) {
1569 requires_delayed_unmanagedtype_check = false;
1570 foreach (FieldBase f in fields) {
1571 if (f.MemberType != null && f.MemberType.IsPointer)
1572 TypeManager.VerifyUnmanaged (Module, f.MemberType, f.Location);
1578 // Constructors are not in the defined_names array
1580 DefineContainerMembers (instance_constructors);
1582 DefineContainerMembers (events);
1583 DefineContainerMembers (ordered_explicit_member_list);
1584 DefineContainerMembers (ordered_member_list);
1586 if (operators != null) {
1587 DefineContainerMembers (operators);
1588 CheckPairedOperators ();
1591 ComputeIndexerName();
1592 CheckEqualsAndGetHashCode();
1594 if (Kind == MemberKind.Interface && iface_exprs != null) {
1595 MemberCache.RemoveHiddenMembers (spec);
1601 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1604 for (int i = 0; i < mcal.Count; ++i) {
1605 MemberCore mc = (MemberCore) mcal[i];
1608 } catch (Exception e) {
1609 throw new InternalErrorException (mc, e);
1615 protected virtual void ComputeIndexerName ()
1617 if (indexers == null)
1620 string class_indexer_name = null;
1623 // If there's both an explicit and an implicit interface implementation, the
1624 // explicit one actually implements the interface while the other one is just
1625 // a normal indexer. See bug #37714.
1628 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1629 foreach (Indexer i in indexers) {
1630 if (i.InterfaceType != null) {
1631 if (seen_normal_indexers)
1632 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1636 seen_normal_indexers = true;
1638 if (class_indexer_name == null) {
1639 class_indexer_name = i.ShortName;
1643 if (i.ShortName != class_indexer_name)
1644 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");
1647 if (class_indexer_name != null)
1648 indexer_name = class_indexer_name;
1651 void EmitIndexerName ()
1653 if (!seen_normal_indexers)
1656 PredefinedAttribute pa = Module.PredefinedAttributes.DefaultMember;
1657 if (pa.Constructor == null &&
1658 !pa.ResolveConstructor (Location, TypeManager.string_type))
1661 var encoder = new AttributeEncoder ();
1662 encoder.Encode (GetAttributeDefaultMember ());
1663 encoder.EncodeEmptyNamedArguments ();
1665 pa.EmitAttribute (TypeBuilder, encoder);
1668 protected virtual void CheckEqualsAndGetHashCode ()
1670 if (methods == null)
1673 if (HasEquals && !HasGetHashCode) {
1674 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1678 // Indicated whether container has StructLayout attribute set Explicit
1679 public bool HasExplicitLayout {
1680 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1681 set { caching_flags |= Flags.HasExplicitLayout; }
1684 public bool HasStructLayout {
1685 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1686 set { caching_flags |= Flags.HasStructLayout; }
1689 public MemberCache MemberCache {
1691 return spec.MemberCache;
1695 void CheckMemberUsage (List<MemberCore> al, string member_type)
1700 foreach (MemberCore mc in al) {
1701 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1704 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1705 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1710 public virtual void VerifyMembers ()
1713 // Check for internal or private fields that were never assigned
1715 if (Report.WarningLevel >= 3) {
1716 if (Compiler.Settings.EnhancedWarnings) {
1717 CheckMemberUsage (properties, "property");
1718 CheckMemberUsage (methods, "method");
1719 CheckMemberUsage (constants, "constant");
1722 if (fields != null){
1723 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1724 foreach (FieldBase f in fields) {
1725 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1726 if (is_type_exposed)
1733 if ((f.caching_flags & Flags.IsAssigned) == 0)
1734 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1736 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1737 f.GetSignatureForError ());
1743 // Only report 649 on level 4
1745 if (Report.WarningLevel < 4)
1748 if ((f.caching_flags & Flags.IsAssigned) != 0)
1752 // Don't be pendatic over serializable attributes
1754 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1757 Constant c = New.Constantify (f.MemberType, f.Location);
1758 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1759 f.GetSignatureForError (), c == null ? "null" : c.GetValueAsLiteral ());
1765 public override void Emit ()
1768 MemberSpec candidate;
1769 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1770 if (conflict_symbol == null && candidate == null) {
1771 if ((ModFlags & Modifiers.NEW) != 0)
1772 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1773 GetSignatureForError ());
1775 if ((ModFlags & Modifiers.NEW) == 0) {
1776 if (candidate == null)
1777 candidate = conflict_symbol;
1779 Report.SymbolRelatedToPreviousError (candidate);
1780 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1781 GetSignatureForError (), candidate.GetSignatureForError ());
1786 if (all_tp_builders != null) {
1787 int current_starts_index = CurrentTypeParametersStartIndex;
1788 for (int i = 0; i < all_tp_builders.Length; i++) {
1789 if (i < current_starts_index) {
1790 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1792 CurrentTypeParameters [i - current_starts_index].Emit ();
1797 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1798 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1801 if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
1802 TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
1808 // TODO: move to ClassOrStruct
1809 void EmitConstructors ()
1811 if (instance_constructors == null)
1814 if (spec.IsAttribute && IsExposedFromAssembly () && Compiler.Settings.VerifyClsCompliance && IsClsComplianceRequired ()) {
1815 bool has_compliant_args = false;
1817 foreach (Constructor c in instance_constructors) {
1821 catch (Exception e) {
1822 throw new InternalErrorException (c, e);
1825 if (has_compliant_args)
1828 has_compliant_args = c.HasCompliantArgs;
1830 if (!has_compliant_args)
1831 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1833 foreach (Constructor c in instance_constructors) {
1837 catch (Exception e) {
1838 throw new InternalErrorException (c, e);
1845 /// Emits the code, this step is performed after all
1846 /// the types, enumerations, constructors
1848 public virtual void EmitType ()
1850 if (OptAttributes != null)
1851 OptAttributes.Emit ();
1855 EmitConstructors ();
1857 if (constants != null)
1858 foreach (Const con in constants)
1861 if (default_static_constructor != null)
1862 default_static_constructor.Emit ();
1864 if (operators != null)
1865 foreach (Operator o in operators)
1868 if (properties != null)
1869 foreach (Property p in properties)
1872 if (indexers != null) {
1873 foreach (Indexer indx in indexers)
1878 if (events != null){
1879 foreach (Event e in Events)
1883 if (methods != null) {
1884 for (int i = 0; i < methods.Count; ++i)
1885 ((MethodOrOperator) methods [i]).Emit ();
1889 foreach (FieldBase f in fields)
1892 if (types != null) {
1893 foreach (TypeContainer t in types)
1897 if (pending != null)
1898 pending.VerifyPendingMethods (Report);
1900 if (Report.Errors > 0)
1903 if (compiler_generated != null) {
1904 for (int i = 0; i < compiler_generated.Count; ++i)
1905 compiler_generated [i].EmitType ();
1909 public virtual void CloseType ()
1911 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1914 // Close base type container first to avoid TypeLoadException
1915 if (spec.BaseType != null) {
1916 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1917 if (btype != null) {
1920 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1926 caching_flags |= Flags.CloseTypeCreated;
1927 TypeBuilder.CreateType ();
1928 } catch (TypeLoadException){
1930 // This is fine, the code still created the type
1932 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1933 // Console.WriteLine (e.Message);
1934 } catch (Exception e) {
1935 throw new InternalErrorException (this, e);
1939 foreach (TypeContainer tc in Types)
1943 if (compiler_generated != null)
1944 foreach (CompilerGeneratedClass c in compiler_generated)
1948 initialized_fields = null;
1949 initialized_static_fields = null;
1951 ordered_explicit_member_list = null;
1952 ordered_member_list = null;
1957 compiler_generated = null;
1958 default_constructor = null;
1959 default_static_constructor = null;
1961 OptAttributes = null;
1965 // Performs the validation on a Method's modifiers (properties have
1966 // the same properties).
1968 // TODO: Why is it not done at parse stage ?
1970 public bool MethodModifiersValid (MemberCore mc)
1972 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1973 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1975 var flags = mc.ModFlags;
1978 // At most one of static, virtual or override
1980 if ((flags & Modifiers.STATIC) != 0){
1981 if ((flags & vao) != 0){
1982 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1983 mc.GetSignatureForError ());
1988 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1989 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1990 mc.GetSignatureForError ());
1995 // If the declaration includes the abstract modifier, then the
1996 // declaration does not include static, virtual or extern
1998 if ((flags & Modifiers.ABSTRACT) != 0){
1999 if ((flags & Modifiers.EXTERN) != 0){
2001 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2005 if ((flags & Modifiers.SEALED) != 0) {
2006 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2010 if ((flags & Modifiers.VIRTUAL) != 0){
2011 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2015 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2016 Report.SymbolRelatedToPreviousError (this);
2017 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2018 mc.GetSignatureForError (), GetSignatureForError ());
2023 if ((flags & Modifiers.PRIVATE) != 0){
2024 if ((flags & vao) != 0){
2025 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2030 if ((flags & Modifiers.SEALED) != 0){
2031 if ((flags & Modifiers.OVERRIDE) == 0){
2032 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2040 public Constructor DefaultStaticConstructor {
2041 get { return default_static_constructor; }
2044 protected override bool VerifyClsCompliance ()
2046 if (!base.VerifyClsCompliance ())
2049 // Check this name against other containers
2050 NamespaceEntry.NS.VerifyClsCompliance ();
2052 // Check all container names for user classes
2053 if (Kind != MemberKind.Delegate)
2054 MemberCache.VerifyClsCompliance (Definition, Report);
2056 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2057 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2058 GetSignatureForError (), BaseType.GetSignatureForError ());
2064 /// Performs checks for an explicit interface implementation. First it
2065 /// checks whether the `interface_type' is a base inteface implementation.
2066 /// Then it checks whether `name' exists in the interface type.
2068 public bool VerifyImplements (InterfaceMemberBase mb)
2070 var ifaces = spec.Interfaces;
2071 if (ifaces != null) {
2072 foreach (TypeSpec t in ifaces){
2073 if (t == mb.InterfaceType)
2078 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2079 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2080 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2085 // Used for visiblity checks to tests whether this definition shares
2086 // base type baseType, it does member-definition search
2088 public bool IsBaseTypeDefinition (TypeSpec baseType)
2090 // RootContext check
2091 if (TypeBuilder == null)
2096 if (type.MemberDefinition == baseType.MemberDefinition)
2099 type = type.BaseType;
2100 } while (type != null);
2105 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2107 return Module.DeclaringAssembly == assembly;
2110 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2112 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2116 // Public function used to locate types.
2118 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2120 // Returns: Type or null if they type can not be found.
2122 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2124 FullNamedExpression e;
2125 if (arity == 0 && Cache.TryGetValue (name, out e))
2129 int errors = Report.Errors;
2132 TypeParameter[] tp = CurrentTypeParameters;
2134 TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2136 e = new TypeParameterExpr (tparam, Location.Null);
2141 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2144 e = new TypeExpression (t, Location.Null);
2145 else if (Parent != null) {
2146 e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2148 e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2151 // TODO MemberCache: How to cache arity stuff ?
2152 if (errors == Report.Errors && arity == 0)
2158 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2160 // TODO: GenericMethod only
2161 if (PartialContainer == null)
2164 // Has any nested type
2165 // Does not work, because base type can have
2166 //if (PartialContainer.Types == null)
2169 var container = PartialContainer.CurrentType;
2171 // Is not Root container
2172 if (container == null)
2175 var t = MemberCache.FindNestedType (container, name, arity);
2179 // FIXME: Breaks error reporting
2180 if (!t.IsAccessible (CurrentType))
2186 public void Mark_HasEquals ()
2188 cached_method |= CachedMethods.Equals;
2191 public void Mark_HasGetHashCode ()
2193 cached_method |= CachedMethods.GetHashCode;
2197 /// Method container contains Equals method
2199 public bool HasEquals {
2201 return (cached_method & CachedMethods.Equals) != 0;
2206 /// Method container contains GetHashCode method
2208 public bool HasGetHashCode {
2210 return (cached_method & CachedMethods.GetHashCode) != 0;
2214 public bool HasStaticFieldInitializer {
2216 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2220 cached_method |= CachedMethods.HasStaticFieldInitializer;
2222 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2227 // Generates xml doc comments (if any), and if required,
2228 // handle warning report.
2230 internal override void GenerateDocComment (DeclSpace ds)
2232 DocUtil.GenerateTypeDocComment (this, ds, Report);
2235 public override string DocCommentHeader {
2236 get { return "T:"; }
2240 public abstract class ClassOrStruct : TypeContainer
2242 SecurityType declarative_security;
2244 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2245 MemberName name, Attributes attrs, MemberKind kind)
2246 : base (ns, parent, name, attrs, kind)
2250 protected override bool AddToContainer (MemberCore symbol, string name)
2252 if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2253 if (symbol is TypeParameter) {
2254 Report.Error (694, symbol.Location,
2255 "Type parameter `{0}' has same name as containing type, or method",
2256 symbol.GetSignatureForError ());
2260 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2261 if (imb == null || !imb.IsExplicitImpl) {
2262 Report.SymbolRelatedToPreviousError (this);
2263 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2264 symbol.GetSignatureForError ());
2269 return base.AddToContainer (symbol, name);
2272 public override void VerifyMembers ()
2274 base.VerifyMembers ();
2276 if ((events != null) && Report.WarningLevel >= 3) {
2277 foreach (Event e in events){
2278 // Note: The event can be assigned from same class only, so we can report
2279 // this warning for all accessibility modes
2280 if ((e.caching_flags & Flags.IsUsed) == 0)
2281 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2285 if (types != null) {
2286 foreach (var t in types)
2291 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2293 if (a.IsValidSecurityAttribute ()) {
2294 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2298 if (a.Type == pa.StructLayout) {
2299 PartialContainer.HasStructLayout = true;
2300 if (a.IsExplicitLayoutKind ())
2301 PartialContainer.HasExplicitLayout = true;
2304 if (a.Type == pa.Dynamic) {
2305 a.Error_MisusedDynamicAttribute ();
2309 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2313 /// Defines the default constructors
2315 protected void DefineDefaultConstructor (bool is_static)
2317 // The default instance constructor is public
2318 // If the class is abstract, the default constructor is protected
2319 // The default static constructor is private
2323 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2325 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2328 Constructor c = new Constructor (this, MemberName.Name, mods,
2329 null, ParametersCompiled.EmptyReadOnlyParameters,
2330 new GeneratedBaseInitializer (Location),
2334 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2337 protected override bool DoDefineMembers ()
2339 CheckProtectedModifier ();
2341 base.DoDefineMembers ();
2343 if (default_static_constructor != null)
2344 default_static_constructor.Define ();
2349 public override void Emit ()
2351 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2352 DefineDefaultConstructor (true);
2353 default_static_constructor.Define ();
2358 if (declarative_security != null) {
2359 foreach (var de in declarative_security) {
2361 TypeBuilder.__AddDeclarativeSecurity (de);
2363 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2369 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2371 DeclSpace top_level = Parent;
2372 if (top_level != null) {
2373 while (top_level.Parent != null)
2374 top_level = top_level.Parent;
2376 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2377 if (candidates != null) {
2378 scope = NamespaceEntry;
2383 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2386 protected override TypeAttributes TypeAttr {
2388 if (default_static_constructor == null)
2389 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2391 return base.TypeAttr;
2397 // TODO: should be sealed
2398 public class Class : ClassOrStruct {
2399 const Modifiers AllowedModifiers =
2402 Modifiers.PROTECTED |
2403 Modifiers.INTERNAL |
2405 Modifiers.ABSTRACT |
2410 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2412 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2414 : base (ns, parent, name, attrs, MemberKind.Class)
2416 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2417 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2418 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2421 public override void Accept (StructuralVisitor visitor)
2423 visitor.Visit (this);
2426 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2428 if (part.Name == "System.Object")
2429 Report.Error (537, part.Location,
2430 "The class System.Object cannot have a base class or implement an interface.");
2431 base.AddBasesForPart (part, bases);
2434 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2436 if (a.Type == pa.AttributeUsage) {
2437 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2438 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2442 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2443 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2447 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2448 a.Error_MissingGuidAttribute ();
2452 if (a.Type == pa.Extension) {
2453 a.Error_MisusedExtensionAttribute ();
2457 if (a.Type.IsConditionallyExcluded (Location))
2460 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2463 public override AttributeTargets AttributeTargets {
2465 return AttributeTargets.Class;
2469 protected override void DefineContainerMembers (System.Collections.IList list)
2475 base.DefineContainerMembers (list);
2479 foreach (MemberCore m in list) {
2480 if (m is Operator) {
2481 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2485 if (m is Destructor) {
2486 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2491 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2495 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2498 if (m is Constructor) {
2499 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2503 Method method = m as Method;
2504 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2505 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2509 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2512 base.DefineContainerMembers (list);
2515 protected override bool DoDefineMembers ()
2517 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2518 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2521 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2522 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2525 if (InstanceConstructors == null && !IsStatic)
2526 DefineDefaultConstructor (false);
2528 return base.DoDefineMembers ();
2531 public override void Emit ()
2535 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2536 Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2538 if (base_type != null && base_type.HasDynamicElement) {
2539 Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
2543 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2545 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2547 if (base_class == null) {
2548 if (spec != TypeManager.object_type)
2549 base_type = TypeManager.object_type;
2551 if (base_type.IsGenericParameter){
2552 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2553 GetSignatureForError (), base_type.GetSignatureForError ());
2554 } else if (IsGeneric && base_type.IsAttribute) {
2555 Report.Error (698, base_class.Location,
2556 "A generic type cannot derive from `{0}' because it is an attribute class",
2557 base_class.GetSignatureForError ());
2558 } else if (base_type.IsStatic) {
2559 Report.SymbolRelatedToPreviousError (base_class.Type);
2560 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2561 GetSignatureForError (), base_type.GetSignatureForError ());
2562 } else if (base_type.IsSealed) {
2563 Report.SymbolRelatedToPreviousError (base_class.Type);
2564 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2565 GetSignatureForError (), base_type.GetSignatureForError ());
2566 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2567 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2568 GetSignatureForError (), base_class.GetSignatureForError ());
2571 if (base_type is BuildinTypeSpec && !(spec is BuildinTypeSpec) &&
2572 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2573 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2574 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2575 GetSignatureForError (), base_type.GetSignatureForError ());
2577 base_type = TypeManager.object_type;
2580 if (!IsAccessibleAs (base_type)) {
2581 Report.SymbolRelatedToPreviousError (base_type);
2582 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2583 base_type.GetSignatureForError (), GetSignatureForError ());
2587 if (PartialContainer.IsStatic && ifaces != null) {
2588 foreach (TypeExpr t in ifaces)
2589 Report.SymbolRelatedToPreviousError (t.Type);
2590 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2596 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2597 /// Valid only for attribute classes.
2598 public override string[] ConditionalConditions ()
2600 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2603 caching_flags &= ~Flags.Excluded_Undetected;
2605 if (OptAttributes == null)
2608 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
2612 string[] conditions = new string[attrs.Length];
2613 for (int i = 0; i < conditions.Length; ++i)
2614 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2616 caching_flags |= Flags.Excluded;
2621 // FIXME: How do we deal with the user specifying a different
2624 protected override TypeAttributes TypeAttr {
2626 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2628 ta |= StaticClassAttribute;
2634 public sealed class Struct : ClassOrStruct {
2636 bool is_unmanaged, has_unmanaged_check_done;
2640 // Modifiers allowed in a struct declaration
2642 const Modifiers AllowedModifiers =
2645 Modifiers.PROTECTED |
2646 Modifiers.INTERNAL |
2650 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2651 Modifiers mod, Attributes attrs)
2652 : base (ns, parent, name, attrs, MemberKind.Struct)
2654 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2655 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2656 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2659 public override AttributeTargets AttributeTargets {
2661 return AttributeTargets.Struct;
2665 public override void Accept (StructuralVisitor visitor)
2667 visitor.Visit (this);
2670 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2672 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2675 // When struct constains fixed fixed and struct layout has explicitly
2676 // set CharSet, its value has to be propagated to compiler generated
2679 if (a.Type == pa.StructLayout && Fields != null) {
2680 var value = a.GetNamedValue ("CharSet");
2684 for (int i = 0; i < Fields.Count; ++i) {
2685 FixedField ff = Fields [i] as FixedField;
2689 ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2694 bool CheckStructCycles (Struct s)
2696 if (s.Fields == null)
2703 foreach (FieldBase field in s.Fields) {
2704 TypeSpec ftype = field.Spec.MemberType;
2705 if (!ftype.IsStruct)
2708 if (ftype is BuildinTypeSpec)
2711 foreach (var targ in ftype.TypeArguments) {
2712 if (!CheckFieldTypeCycle (targ)) {
2713 Report.Error (523, field.Location,
2714 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2715 field.GetSignatureForError (), ftype.GetSignatureForError ());
2720 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2723 if (!CheckFieldTypeCycle (ftype)) {
2724 Report.Error (523, field.Location,
2725 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2726 field.GetSignatureForError (), ftype.GetSignatureForError ());
2731 s.InTransit = false;
2735 bool CheckFieldTypeCycle (TypeSpec ts)
2737 var fts = ts.MemberDefinition as Struct;
2741 return CheckStructCycles (fts);
2744 public override void Emit ()
2746 CheckStructCycles (this);
2751 public override bool IsUnmanagedType ()
2756 if (has_unmanaged_check_done)
2757 return is_unmanaged;
2759 if (requires_delayed_unmanagedtype_check)
2762 requires_delayed_unmanagedtype_check = true;
2764 foreach (FieldBase f in fields) {
2768 // It can happen when recursive unmanaged types are defined
2769 // struct S { S* s; }
2770 TypeSpec mt = f.MemberType;
2775 while (mt.IsPointer)
2776 mt = TypeManager.GetElementType (mt);
2778 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2779 has_unmanaged_check_done = true;
2783 if (TypeManager.IsUnmanagedType (mt))
2786 has_unmanaged_check_done = true;
2790 has_unmanaged_check_done = true;
2791 is_unmanaged = true;
2795 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2797 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2798 base_type = TypeManager.value_type;
2802 protected override TypeAttributes TypeAttr {
2804 const TypeAttributes DefaultTypeAttributes =
2805 TypeAttributes.SequentialLayout |
2806 TypeAttributes.Sealed;
2808 return base.TypeAttr | DefaultTypeAttributes;
2812 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2814 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2815 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2816 field.GetSignatureForError ());
2819 base.RegisterFieldForInitialization (field, expression);
2827 public sealed class Interface : TypeContainer {
2830 /// Modifiers allowed in a class declaration
2832 public const Modifiers AllowedModifiers =
2835 Modifiers.PROTECTED |
2836 Modifiers.INTERNAL |
2840 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2842 : base (ns, parent, name, attrs, MemberKind.Interface)
2844 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2846 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2847 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2852 public override AttributeTargets AttributeTargets {
2854 return AttributeTargets.Interface;
2858 protected override TypeAttributes TypeAttr {
2860 const TypeAttributes DefaultTypeAttributes =
2861 TypeAttributes.AutoLayout |
2862 TypeAttributes.Abstract |
2863 TypeAttributes.Interface;
2865 return base.TypeAttr | DefaultTypeAttributes;
2871 public override void Accept (StructuralVisitor visitor)
2873 visitor.Visit (this);
2876 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2878 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2879 a.Error_MissingGuidAttribute ();
2883 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2886 protected override bool VerifyClsCompliance ()
2888 if (!base.VerifyClsCompliance ())
2891 if (iface_exprs != null) {
2892 foreach (var iface in iface_exprs) {
2893 if (iface.Type.IsCLSCompliant ())
2896 Report.SymbolRelatedToPreviousError (iface.Type);
2897 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2898 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2906 public abstract class InterfaceMemberBase : MemberBase
2909 // Common modifiers allowed in a class declaration
2911 protected const Modifiers AllowedModifiersClass =
2914 Modifiers.PROTECTED |
2915 Modifiers.INTERNAL |
2920 Modifiers.OVERRIDE |
2921 Modifiers.ABSTRACT |
2926 // Common modifiers allowed in a struct declaration
2928 protected const Modifiers AllowedModifiersStruct =
2931 Modifiers.PROTECTED |
2932 Modifiers.INTERNAL |
2935 Modifiers.OVERRIDE |
2940 // Common modifiers allowed in a interface declaration
2942 protected const Modifiers AllowedModifiersInterface =
2947 // Whether this is an interface member.
2949 public bool IsInterface;
2952 // If true, this is an explicit interface implementation
2954 public bool IsExplicitImpl;
2956 protected bool is_external_implementation;
2959 // The interface type we are explicitly implementing
2961 public TypeSpec InterfaceType;
2964 // The method we're overriding if this is an override method.
2966 protected MethodSpec base_method;
2968 readonly Modifiers explicit_mod_flags;
2969 public MethodAttributes flags;
2971 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2972 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2973 MemberName name, Attributes attrs)
2974 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2977 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2978 IsExplicitImpl = (MemberName.Left != null);
2979 explicit_mod_flags = mod;
2982 protected override bool CheckBase ()
2984 if (!base.CheckBase ())
2987 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2988 CheckForDuplications ();
2993 // For System.Object only
2994 if (Parent.BaseType == null)
2997 MemberSpec candidate;
2998 var base_member = FindBaseMember (out candidate);
3000 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3001 if (base_member == null) {
3002 if (candidate == null) {
3003 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
3004 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
3005 "object.Finalize()");
3007 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3008 GetSignatureForError (), SimpleName.GetMemberType (this));
3011 Report.SymbolRelatedToPreviousError (candidate);
3013 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
3014 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3015 else if (this is PropertyBase)
3016 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
3017 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3019 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
3020 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3026 if (!CheckOverrideAgainstBase (base_member))
3029 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
3031 if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3032 Report.SymbolRelatedToPreviousError (base_member);
3033 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3034 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3037 if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3038 Report.SymbolRelatedToPreviousError (base_member);
3039 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3040 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3044 base_method = base_member as MethodSpec;
3048 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
3049 base_member = candidate;
3051 if (base_member == null) {
3052 if ((ModFlags & Modifiers.NEW) != 0) {
3053 if (base_member == null) {
3054 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3055 GetSignatureForError ());
3059 if ((ModFlags & Modifiers.NEW) == 0) {
3060 ModFlags |= Modifiers.NEW;
3061 if (!IsCompilerGenerated) {
3062 Report.SymbolRelatedToPreviousError (base_member);
3063 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3064 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",
3065 GetSignatureForError (), base_member.GetSignatureForError ());
3067 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3068 GetSignatureForError (), base_member.GetSignatureForError ());
3073 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3074 Report.SymbolRelatedToPreviousError (base_member);
3075 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3076 GetSignatureForError (), base_member.GetSignatureForError ());
3083 protected virtual bool CheckForDuplications ()
3085 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3089 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3090 // that have been defined.
3092 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3096 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3097 Report.SymbolRelatedToPreviousError (base_member);
3098 Report.Error (506, Location,
3099 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3100 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3104 // Now we check that the overriden method is not final
3105 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3106 Report.SymbolRelatedToPreviousError (base_member);
3107 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3108 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3112 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3113 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3114 Report.SymbolRelatedToPreviousError (base_member);
3115 if (this is PropertyBasedMember) {
3116 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3117 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3119 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3120 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3128 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3130 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3131 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3133 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3135 // It must be at least "protected"
3137 if ((thisp & Modifiers.PROTECTED) == 0) {
3142 // when overriding protected internal, the method can be declared
3143 // protected internal only within the same assembly or assembly
3144 // which has InternalsVisibleTo
3146 if ((thisp & Modifiers.INTERNAL) != 0) {
3147 return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3151 // protected overriding protected internal inside same assembly
3152 // requires internal modifier as well
3154 if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
3161 return thisp == base_classp;
3164 public override bool Define ()
3167 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3168 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3170 flags = MethodAttributes.Public |
3171 MethodAttributes.Abstract |
3172 MethodAttributes.HideBySig |
3173 MethodAttributes.NewSlot |
3174 MethodAttributes.Virtual;
3176 Parent.PartialContainer.MethodModifiersValid (this);
3178 flags = ModifiersExtensions.MethodAttr (ModFlags);
3181 if (IsExplicitImpl) {
3182 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3183 if (iface_texpr == null)
3186 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3187 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3188 GetSignatureForError ());
3191 InterfaceType = iface_texpr.Type;
3193 if (!InterfaceType.IsInterface) {
3194 Report.SymbolRelatedToPreviousError (InterfaceType);
3195 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3196 TypeManager.CSharpName (InterfaceType));
3198 Parent.PartialContainer.VerifyImplements (this);
3201 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3204 return base.Define ();
3207 protected bool DefineParameters (ParametersCompiled parameters)
3209 if (!parameters.Resolve (this))
3213 for (int i = 0; i < parameters.Count; ++i) {
3214 Parameter p = parameters [i];
3216 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3217 p.Warning_UselessOptionalParameter (Report);
3219 if (p.CheckAccessibility (this))
3222 TypeSpec t = parameters.Types [i];
3223 Report.SymbolRelatedToPreviousError (t);
3224 if (this is Indexer)
3225 Report.Error (55, Location,
3226 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3227 TypeManager.CSharpName (t), GetSignatureForError ());
3228 else if (this is Operator)
3229 Report.Error (57, Location,
3230 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3231 TypeManager.CSharpName (t), GetSignatureForError ());
3233 Report.Error (51, Location,
3234 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3235 TypeManager.CSharpName (t), GetSignatureForError ());
3241 public override void Emit()
3243 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3244 // We are more strict than csc and report this as an error because SRE does not allow emit that
3245 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3246 if (this is Constructor) {
3247 Report.Warning (824, 1, Location,
3248 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3250 Report.Warning (626, 1, Location,
3251 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3252 GetSignatureForError ());
3259 public override bool EnableOverloadChecks (MemberCore overload)
3262 // Two members can differ in their explicit interface
3263 // type parameter only
3265 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3266 if (imb != null && imb.IsExplicitImpl) {
3267 if (IsExplicitImpl) {
3268 caching_flags |= Flags.MethodOverloadsExist;
3273 return IsExplicitImpl;
3276 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3278 var base_modifiers = base_member.Modifiers;
3280 // Remove internal modifier from types which are not internally accessible
3281 if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
3282 !base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
3283 base_modifiers = Modifiers.PROTECTED;
3285 Report.SymbolRelatedToPreviousError (base_member);
3286 Report.Error (507, member.Location,
3287 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3288 member.GetSignatureForError (),
3289 ModifiersExtensions.AccessibilityName (base_modifiers),
3290 base_member.GetSignatureForError ());
3293 protected void Error_StaticReturnType ()
3295 Report.Error (722, Location,
3296 "`{0}': static types cannot be used as return types",
3297 MemberType.GetSignatureForError ());
3301 /// Gets base method and its return type
3303 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3305 return MemberCache.FindBaseMember (this, out bestCandidate);
3309 // The "short" name of this property / indexer / event. This is the
3310 // name without the explicit interface.
3312 public string ShortName {
3313 get { return MemberName.Name; }
3314 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3318 // Returns full metadata method name
3320 public string GetFullName (MemberName name)
3322 return GetFullName (name.Name);
3325 public string GetFullName (string name)
3327 if (!IsExplicitImpl)
3331 // When dealing with explicit members a full interface type
3332 // name is added to member name to avoid possible name conflicts
3334 // We use CSharpName which gets us full name with benefit of
3335 // replacing predefined names which saves some space and name
3338 return TypeManager.CSharpName (InterfaceType) + "." + name;
3341 protected override bool VerifyClsCompliance ()
3343 if (!base.VerifyClsCompliance ()) {
3347 if (GenericMethod != null)
3348 GenericMethod.VerifyClsCompliance ();
3353 public override bool IsUsed
3355 get { return IsExplicitImpl || base.IsUsed; }
3360 public abstract class MemberBase : MemberCore
3362 protected FullNamedExpression type_expr;
3363 protected TypeSpec member_type;
3365 public readonly DeclSpace ds;
3366 public readonly GenericMethod GenericMethod;
3368 protected MemberBase (DeclSpace parent, GenericMethod generic,
3369 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3370 MemberName name, Attributes attrs)
3371 : base (parent, name, attrs)
3373 this.ds = generic != null ? generic : (DeclSpace) parent;
3374 this.type_expr = type;
3375 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3376 GenericMethod = generic;
3377 if (GenericMethod != null)
3378 GenericMethod.ModFlags = ModFlags;
3383 public TypeSpec MemberType {
3389 public FullNamedExpression TypeExpression {
3398 // Main member define entry
3400 public override bool Define ()
3402 DoMemberTypeIndependentChecks ();
3405 // Returns false only when type resolution failed
3407 if (!ResolveMemberType ())
3410 DoMemberTypeDependentChecks ();
3415 // Any type_name independent checks
3417 protected virtual void DoMemberTypeIndependentChecks ()
3419 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3420 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3421 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3422 GetSignatureForError (), Parent.GetSignatureForError ());
3427 // Any type_name dependent checks
3429 protected virtual void DoMemberTypeDependentChecks ()
3431 // verify accessibility
3432 if (!IsAccessibleAs (MemberType)) {
3433 Report.SymbolRelatedToPreviousError (MemberType);
3434 if (this is Property)
3435 Report.Error (53, Location,
3436 "Inconsistent accessibility: property type `" +
3437 TypeManager.CSharpName (MemberType) + "' is less " +
3438 "accessible than property `" + GetSignatureForError () + "'");
3439 else if (this is Indexer)
3440 Report.Error (54, Location,
3441 "Inconsistent accessibility: indexer return type `" +
3442 TypeManager.CSharpName (MemberType) + "' is less " +
3443 "accessible than indexer `" + GetSignatureForError () + "'");
3444 else if (this is MethodCore) {
3445 if (this is Operator)
3446 Report.Error (56, Location,
3447 "Inconsistent accessibility: return type `" +
3448 TypeManager.CSharpName (MemberType) + "' is less " +
3449 "accessible than operator `" + GetSignatureForError () + "'");
3451 Report.Error (50, Location,
3452 "Inconsistent accessibility: return type `" +
3453 TypeManager.CSharpName (MemberType) + "' is less " +
3454 "accessible than method `" + GetSignatureForError () + "'");
3456 Report.Error (52, Location,
3457 "Inconsistent accessibility: field type `" +
3458 TypeManager.CSharpName (MemberType) + "' is less " +
3459 "accessible than field `" + GetSignatureForError () + "'");
3463 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3464 TypeManager.CheckTypeVariance (MemberType, variance, this);
3467 protected bool IsTypePermitted ()
3469 if (TypeManager.IsSpecialType (MemberType)) {
3470 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3476 protected virtual bool CheckBase ()
3478 CheckProtectedModifier ();
3483 protected virtual bool ResolveMemberType ()
3485 if (member_type != null)
3486 throw new InternalErrorException ("Multi-resolve");
3488 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3493 // Replace original type name, error reporting can use fully resolved name
3497 member_type = te.Type;