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 (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 bool AddMember (MemberCore symbol)
310 return AddToContainer (symbol, symbol.MemberName.Basename);
313 public bool AddMember (MemberCore symbol, string name)
315 return AddToContainer (symbol, name);
318 protected virtual bool AddMemberType (TypeContainer ds)
320 return AddToContainer (ds, ds.Basename);
323 protected virtual void RemoveMemberType (DeclSpace ds)
325 RemoveFromContainer (ds.Basename);
328 public void AddConstant (Const constant)
330 if (!AddMember (constant))
333 if (constants == null)
334 constants = new List<MemberCore> ();
336 constants.Add (constant);
339 public TypeContainer AddTypeContainer (TypeContainer tc)
341 if (!AddMemberType (tc))
345 types = new List<TypeContainer> ();
351 public virtual TypeContainer AddPartial (TypeContainer next_part)
353 return AddPartial (next_part, next_part.Basename);
356 protected TypeContainer AddPartial (TypeContainer next_part, string name)
358 next_part.ModFlags |= Modifiers.PARTIAL;
359 TypeContainer tc = GetDefinition (name) as TypeContainer;
361 return AddTypeContainer (next_part);
363 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
364 Report.SymbolRelatedToPreviousError (next_part);
365 Error_MissingPartialModifier (tc);
368 if (tc.Kind != next_part.Kind) {
369 Report.SymbolRelatedToPreviousError (tc);
370 Report.Error (261, next_part.Location,
371 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
372 next_part.GetSignatureForError ());
375 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
376 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
377 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
378 Report.SymbolRelatedToPreviousError (tc);
379 Report.Error (262, next_part.Location,
380 "Partial declarations of `{0}' have conflicting accessibility modifiers",
381 next_part.GetSignatureForError ());
384 if (tc.partial_parts == null)
385 tc.partial_parts = new List<TypeContainer> (1);
387 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
388 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
389 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
390 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
391 tc.ModFlags |= next_part.ModFlags;
393 tc.ModFlags |= next_part.ModFlags;
396 tc.spec.Modifiers = tc.ModFlags;
398 if (next_part.attributes != null) {
399 if (tc.attributes == null)
400 tc.attributes = next_part.attributes;
402 tc.attributes.AddAttributes (next_part.attributes.Attrs);
405 next_part.PartialContainer = tc;
406 tc.partial_parts.Add (next_part);
410 public virtual void RemoveTypeContainer (TypeContainer next_part)
413 types.Remove (next_part);
414 RemoveMemberType (next_part);
417 public virtual TypeSpec AddDelegate (Delegate d)
419 AddTypeContainer (d);
423 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
425 if (ordered_explicit_member_list == null) {
426 ordered_explicit_member_list = new List<MemberCore> ();
427 ordered_member_list = new List<MemberCore> ();
431 if (Kind == MemberKind.Interface) {
432 Report.Error (541, mc.Location,
433 "`{0}': explicit interface declaration can only be declared in a class or struct",
434 mc.GetSignatureForError ());
437 ordered_explicit_member_list.Add (mc);
438 alist.Insert (0, mc);
440 ordered_member_list.Add (mc);
446 public void AddMethod (MethodOrOperator method)
448 if (!AddToContainer (method, method.MemberName.Basename))
452 methods = new List<MemberCore> ();
454 if (method.MemberName.Left != null)
455 AddMemberToList (method, methods, true);
457 AddMemberToList (method, methods, false);
460 public void AddConstructor (Constructor c)
462 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
463 if (!AddToContainer (c, is_static ? Constructor.ConstructorName : Constructor.TypeConstructorName))
466 if (is_static && c.ParameterInfo.IsEmpty){
467 if (default_static_constructor != null) {
468 Report.SymbolRelatedToPreviousError (default_static_constructor);
469 Report.Error (111, c.Location,
470 "A member `{0}' is already defined. Rename this member or use different parameter types",
471 c.GetSignatureForError ());
475 default_static_constructor = c;
477 if (c.ParameterInfo.IsEmpty)
478 default_constructor = c;
480 if (instance_constructors == null)
481 instance_constructors = new List<Constructor> ();
483 instance_constructors.Add (c);
487 public bool AddField (FieldBase field)
489 if (!AddMember (field))
493 fields = new List<FieldBase> ();
497 if ((field.ModFlags & Modifiers.STATIC) != 0)
500 if (first_nonstatic_field == null) {
501 first_nonstatic_field = field;
505 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
506 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
507 Report.Warning (282, 3, field.Location,
508 "struct instance field `{0}' found in different declaration from instance field `{1}'",
509 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
514 public void AddProperty (Property prop)
516 if (!AddMember (prop))
519 if (properties == null)
520 properties = new List<MemberCore> ();
522 if (prop.MemberName.Left != null)
523 AddMemberToList (prop, properties, true);
525 AddMemberToList (prop, properties, false);
528 public void AddEvent (Event e)
534 events = new List<MemberCore> ();
540 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
542 public void AddIndexer (Indexer i)
544 if (indexers == null)
545 indexers = new List<MemberCore> ();
547 if (i.IsExplicitImpl)
548 AddMemberToList (i, indexers, true);
550 AddMemberToList (i, indexers, false);
553 public void AddOperator (Operator op)
558 if (operators == null)
559 operators = new List<MemberCore> ();
564 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
566 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
568 if (compiler_generated == null)
569 compiler_generated = new List<CompilerGeneratedClass> ();
571 compiler_generated.Add (c);
574 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
576 if (a.Type == pa.DefaultMember) {
577 if (Indexers != null) {
578 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
583 if (a.Type == pa.Required) {
584 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
588 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
591 public override AttributeTargets AttributeTargets {
593 throw new NotSupportedException ();
597 public IList<TypeContainer> Types {
603 public IList<MemberCore> Methods {
609 public IList<MemberCore> Constants {
615 public TypeSpec BaseType {
617 return spec.BaseType;
621 public IList<FieldBase> Fields {
627 public IList<Constructor> InstanceConstructors {
629 return instance_constructors;
633 public IList<MemberCore> Properties {
639 public IList<MemberCore> Events {
645 public IList<MemberCore> Indexers {
651 public IList<MemberCore> Operators {
657 protected override TypeAttributes TypeAttr {
659 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel);
663 public int TypeParametersCount {
665 return MemberName.Arity;
669 TypeParameterSpec[] ITypeDefinition.TypeParameters {
671 // TODO MemberCache: this is going to hurt
672 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
676 public string GetAttributeDefaultMember ()
678 return indexers == null ? DefaultIndexerName : indexer_name;
681 public bool IsComImport {
683 if (OptAttributes == null)
686 return OptAttributes.Contains (Module.PredefinedAttributes.ComImport);
690 string ITypeDefinition.Namespace {
692 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
696 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
698 if ((field.ModFlags & Modifiers.STATIC) != 0){
699 if (initialized_static_fields == null) {
700 PartialContainer.HasStaticFieldInitializer = true;
701 initialized_static_fields = new List<FieldInitializer> (4);
704 initialized_static_fields.Add (expression);
706 if (initialized_fields == null)
707 initialized_fields = new List<FieldInitializer> (4);
709 initialized_fields.Add (expression);
713 public void ResolveFieldInitializers (BlockContext ec)
715 if (partial_parts != null) {
716 foreach (TypeContainer part in partial_parts) {
717 part.DoResolveFieldInitializers (ec);
720 DoResolveFieldInitializers (ec);
723 void DoResolveFieldInitializers (BlockContext ec)
726 if (initialized_static_fields == null)
729 bool has_complex_initializer = !RootContext.Optimize;
731 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
732 for (i = 0; i < initialized_static_fields.Count; ++i) {
733 FieldInitializer fi = initialized_static_fields [i];
734 ExpressionStatement s = fi.ResolveStatement (ec);
736 s = EmptyExpressionStatement.Instance;
737 } else if (fi.IsComplexInitializer) {
738 has_complex_initializer |= true;
744 for (i = 0; i < initialized_static_fields.Count; ++i) {
745 FieldInitializer fi = initialized_static_fields [i];
747 // Need special check to not optimize code like this
748 // static int a = b = 5;
751 if (!has_complex_initializer && fi.IsDefaultInitializer)
754 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
760 if (initialized_fields == null)
763 for (int i = 0; i < initialized_fields.Count; ++i) {
764 FieldInitializer fi = initialized_fields [i];
765 ExpressionStatement s = fi.ResolveStatement (ec);
770 // Field is re-initialized to its default value => removed
772 if (fi.IsDefaultInitializer && RootContext.Optimize)
775 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
779 public override string DocComment {
791 public PendingImplementation PendingImplementations {
792 get { return pending; }
795 public TypeSpec GetAttributeCoClass ()
797 if (OptAttributes == null)
800 Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass);
804 return a.GetCoClassAttributeValue ();
807 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
810 if (OptAttributes != null) {
811 a = OptAttributes.Search (pa);
817 return a.GetAttributeUsageAttribute ();
820 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
822 // FIXME: get rid of partial_parts and store lists of bases of each part here
823 // assumed, not verified: 'part' is in 'partial_parts'
824 ((TypeContainer) part).type_bases = bases;
828 /// This function computes the Base class and also the
829 /// list of interfaces that the class or struct @c implements.
831 /// The return value is an array (might be null) of
832 /// interfaces implemented (as Types).
834 /// The @base_class argument is set to the base object or null
835 /// if this is `System.Object'.
837 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
840 if (type_bases == null)
843 int count = type_bases.Count;
844 TypeExpr [] ifaces = null;
845 var base_context = new BaseContext (this);
846 for (int i = 0, j = 0; i < count; i++){
847 FullNamedExpression fne = type_bases [i];
849 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
850 if (fne_resolved == null)
853 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
854 if (fne_resolved.Type == InternalType.Dynamic) {
855 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
856 GetSignatureForError ());
861 base_type = fne_resolved.Type;
862 base_class = fne_resolved;
867 ifaces = new TypeExpr [count - i];
869 if (fne_resolved.Type.IsInterface) {
870 for (int ii = 0; ii < j; ++ii) {
871 if (fne_resolved.Type == ifaces [ii].Type) {
872 Report.Error (528, Location, "`{0}' is already listed in interface list",
873 fne_resolved.GetSignatureForError ());
878 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
879 Report.Error (61, fne.Location,
880 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
881 fne_resolved.GetSignatureForError (), GetSignatureForError ());
884 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
885 if (Kind != MemberKind.Class) {
886 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
887 } else if (base_class != null)
888 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
889 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
891 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
892 GetSignatureForError (), fne_resolved.GetSignatureForError ());
896 ifaces [j++] = fne_resolved;
902 TypeExpr[] GetNormalPartialBases ()
904 var ifaces = new List<TypeExpr> (0);
905 if (iface_exprs != null)
906 ifaces.AddRange (iface_exprs);
908 foreach (TypeContainer part in partial_parts) {
909 TypeExpr new_base_class;
910 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
911 if (new_base_class != null) {
912 if (base_type_expr != null && new_base_class.Type != base_type) {
913 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
914 Report.Error (263, part.Location,
915 "Partial declarations of `{0}' must not specify different base classes",
916 part.GetSignatureForError ());
918 base_type_expr = new_base_class;
919 base_type = base_type_expr.Type;
923 if (new_ifaces == null)
926 foreach (TypeExpr iface in new_ifaces) {
927 if (ifaces.Contains (iface))
934 if (ifaces.Count == 0)
937 return ifaces.ToArray ();
941 // Checks that some operators come in pairs:
947 // They are matched based on the return type and the argument types
949 void CheckPairedOperators ()
951 bool has_equality_or_inequality = false;
952 var operators = this.operators.ToArray ();
953 bool[] has_pair = new bool[operators.Length];
955 for (int i = 0; i < operators.Length; ++i) {
956 if (operators[i] == null)
959 Operator o_a = (Operator) operators[i];
960 Operator.OpType o_type = o_a.OperatorType;
961 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
962 has_equality_or_inequality = true;
964 Operator.OpType matching_type = o_a.GetMatchingOperator ();
965 if (matching_type == Operator.OpType.TOP) {
970 for (int ii = 0; ii < operators.Length; ++ii) {
971 Operator o_b = (Operator) operators[ii];
972 if (o_b == null || o_b.OperatorType != matching_type)
975 if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
978 if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
984 // Used to ignore duplicate user conversions
990 for (int i = 0; i < operators.Length; ++i) {
991 if (operators[i] == null || has_pair[i])
994 Operator o = (Operator) operators [i];
995 Report.Error (216, o.Location,
996 "The operator `{0}' requires a matching operator `{1}' to also be defined",
997 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
1000 if (has_equality_or_inequality) {
1001 if (Methods == null || !HasEquals)
1002 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
1003 GetSignatureForError ());
1005 if (Methods == null || !HasGetHashCode)
1006 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
1007 GetSignatureForError ());
1011 bool CreateTypeBuilder ()
1014 // Sets .size to 1 for structs with no instance fields
1016 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1019 // TODO: Completely wrong
1020 if (Module.GlobalRootNamespace.IsNamespace (Name)) {
1021 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1024 TypeBuilder = Module.CreateBuilder (Name, TypeAttr, type_size);
1026 TypeBuilder = Parent.TypeBuilder.DefineNestedType (Basename, TypeAttr, null, type_size);
1029 if (DeclaringAssembly.Importer != null)
1030 DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec);
1032 spec.SetMetaInfo (TypeBuilder);
1033 spec.MemberCache = new MemberCache (this);
1034 spec.DeclaringType = Parent.CurrentType;
1037 Parent.MemberCache.AddMember (spec);
1040 string[] param_names = new string[TypeParameters.Length];
1041 for (int i = 0; i < TypeParameters.Length; i++)
1042 param_names [i] = TypeParameters[i].Name;
1044 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1046 int offset = CurrentTypeParametersStartIndex;
1047 for (int i = offset; i < all_tp_builders.Length; i++) {
1048 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1056 // Creates a proxy base method call inside this container for hoisted base member calls
1058 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1060 Method proxy_method;
1063 // One proxy per base method is enough
1065 if (hoisted_base_call_proxies == null) {
1066 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1067 proxy_method = null;
1069 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1072 if (proxy_method == null) {
1073 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1074 var base_parameters = new Parameter[method.Parameters.Count];
1075 for (int i = 0; i < base_parameters.Length; ++i) {
1076 var base_param = method.Parameters.FixedParameters[i];
1077 base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1078 base_param.Name, base_param.ModFlags, null, Location);
1079 base_parameters[i].Resolve (this, i);
1082 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1083 if (method.Parameters.HasArglist) {
1084 cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1085 cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve (Location);
1088 GenericMethod generic_method;
1089 MemberName member_name;
1090 if (method.IsGeneric) {
1092 // Copy all base generic method type parameters info
1094 var hoisted_tparams = method.GenericDefinition.TypeParameters;
1095 var targs = new TypeArguments ();
1096 var type_params = new TypeParameter[hoisted_tparams.Length];
1097 for (int i = 0; i < type_params.Length; ++i) {
1098 var tp = hoisted_tparams[i];
1099 targs.Add (new TypeParameterName (tp.Name, null, Location));
1100 type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
1103 member_name = new MemberName (name, targs, Location);
1104 generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1105 new TypeExpression (method.ReturnType, Location), cloned_params);
1107 member_name = new MemberName (name);
1108 generic_method = null;
1111 // Compiler generated proxy
1112 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1113 Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1114 member_name, cloned_params, null);
1116 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1118 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1119 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1121 // Get all the method parameters and pass them as arguments
1122 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1123 Statement statement;
1124 if (method.ReturnType == TypeManager.void_type)
1125 statement = new StatementExpression (real_base_call);
1127 statement = new Return (real_base_call, Location);
1129 block.AddStatement (statement);
1130 proxy_method.Block = block;
1132 methods.Add (proxy_method);
1133 proxy_method.Define ();
1135 hoisted_base_call_proxies.Add (method, proxy_method);
1138 return proxy_method.Spec;
1141 bool DefineBaseTypes ()
1143 iface_exprs = ResolveBaseTypes (out base_type_expr);
1144 if (partial_parts != null) {
1145 iface_exprs = GetNormalPartialBases ();
1148 var cycle = CheckRecursiveDefinition (this);
1149 if (cycle != null) {
1150 Report.SymbolRelatedToPreviousError (cycle);
1151 if (this is Interface) {
1152 Report.Error (529, Location,
1153 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1154 GetSignatureForError (), cycle.GetSignatureForError ());
1158 Report.Error (146, Location,
1159 "Circular base class dependency involving `{0}' and `{1}'",
1160 GetSignatureForError (), cycle.GetSignatureForError ());
1166 if (iface_exprs != null) {
1167 foreach (TypeExpr iface in iface_exprs) {
1168 // Prevents a crash, the interface might not have been resolved: 442144
1172 var iface_type = iface.Type;
1174 if (!spec.AddInterface (iface_type))
1177 if (iface_type.IsGeneric && spec.Interfaces != null) {
1178 foreach (var prev_iface in iface_exprs) {
1179 if (prev_iface == iface)
1182 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1185 Report.Error (695, Location,
1186 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1187 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1191 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1193 // Ensure the base is always setup
1194 var compiled_iface = iface_type.MemberDefinition as Interface;
1195 if (compiled_iface != null) {
1196 // TODO: Need DefineBaseType only
1197 compiled_iface.DefineType ();
1200 if (iface_type.Interfaces != null) {
1201 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1202 for (int i = 0; i < base_ifaces.Count; ++i) {
1203 var ii_iface_type = base_ifaces[i];
1204 if (spec.AddInterface (ii_iface_type)) {
1205 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1207 if (ii_iface_type.Interfaces != null)
1208 base_ifaces.AddRange (ii_iface_type.Interfaces);
1215 if (Kind == MemberKind.Interface) {
1216 spec.BaseType = TypeManager.object_type;
1220 if (base_type != null) {
1221 spec.BaseType = base_type;
1223 // Set base type after type creation
1224 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1226 TypeBuilder.SetParent (null);
1232 public virtual void DefineConstants ()
1234 if (constants != null) {
1235 foreach (Const c in constants) {
1240 if (instance_constructors != null) {
1241 foreach (MethodCore m in instance_constructors) {
1242 var p = m.ParameterInfo;
1244 p.ResolveDefaultValues (m);
1249 if (methods != null) {
1250 foreach (MethodCore m in methods) {
1251 var p = m.ParameterInfo;
1253 p.ResolveDefaultValues (m);
1258 if (indexers != null) {
1259 foreach (Indexer i in indexers) {
1260 i.ParameterInfo.ResolveDefaultValues (i);
1264 if (types != null) {
1265 foreach (var t in types)
1266 t.DefineConstants ();
1271 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1273 public bool CreateType ()
1275 if (TypeBuilder != null)
1281 if (!CreateTypeBuilder ()) {
1286 if (partial_parts != null) {
1287 foreach (TypeContainer part in partial_parts) {
1289 part.current_type = current_type;
1290 part.TypeBuilder = TypeBuilder;
1294 if (Types != null) {
1295 foreach (TypeContainer tc in Types) {
1303 public override void DefineType ()
1310 type_defined = true;
1312 if (!DefineBaseTypes ()) {
1317 if (!DefineNestedTypes ()) {
1323 public override void SetParameterInfo (List<Constraints> constraints_list)
1325 base.SetParameterInfo (constraints_list);
1327 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1330 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1331 for (int i = 0; i < tc_names.Length; ++i) {
1332 if (tc_names [i].Name != type_params [i].Name) {
1333 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1334 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1335 GetSignatureForError ());
1339 if (tc_names [i].Variance != type_params [i].Variance) {
1340 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1341 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1342 GetSignatureForError ());
1349 // Replaces normal spec with predefined one when compiling corlib
1350 // and this type container defines predefined type
1352 public void SetPredefinedSpec (BuildinTypeSpec spec)
1354 // When compiling build-in types we start with two
1355 // version of same type. One is of BuildinTypeSpec and
1356 // second one is ordinary TypeSpec. The unification
1357 // happens at later stage when we know which type
1358 // really matches the buildin type signature. However
1359 // that means TypeSpec create during CreateType of this
1360 // type has to be replaced with buildin one
1362 spec.SetMetaInfo (TypeBuilder);
1363 spec.MemberCache = this.spec.MemberCache;
1364 spec.DeclaringType = this.spec.DeclaringType;
1367 current_type = null;
1370 void UpdateTypeParameterConstraints (TypeContainer part)
1372 TypeParameter[] current_params = type_params;
1373 for (int i = 0; i < current_params.Length; i++) {
1374 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1377 Report.SymbolRelatedToPreviousError (Location, "");
1378 Report.Error (265, part.Location,
1379 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1380 GetSignatureForError (), current_params [i].GetSignatureForError ());
1384 public bool ResolveTypeParameters ()
1386 if (!DoResolveTypeParameters ())
1389 if (types != null) {
1390 foreach (var type in types)
1391 if (!type.ResolveTypeParameters ())
1395 if (compiler_generated != null) {
1396 foreach (CompilerGeneratedClass c in compiler_generated)
1397 if (!c.ResolveTypeParameters ())
1404 protected virtual bool DoResolveTypeParameters ()
1406 if (CurrentTypeParameters == null)
1409 if (PartialContainer != this)
1410 throw new InternalErrorException ();
1412 var base_context = new BaseContext (this);
1413 foreach (TypeParameter type_param in CurrentTypeParameters) {
1414 if (!type_param.ResolveConstraints (base_context)) {
1420 if (partial_parts != null) {
1421 foreach (TypeContainer part in partial_parts)
1422 UpdateTypeParameterConstraints (part);
1428 protected virtual bool DefineNestedTypes ()
1430 if (Types != null) {
1431 foreach (TypeContainer tc in Types)
1438 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1440 if (InTransit != null)
1445 if (base_type_expr != null) {
1446 var ptc = base_type.MemberDefinition as TypeContainer;
1447 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1451 if (iface_exprs != null) {
1452 foreach (TypeExpr iface in iface_exprs) {
1453 // the interface might not have been resolved, prevents a crash, see #442144
1456 var ptc = iface.Type.MemberDefinition as Interface;
1457 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1462 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1470 /// Populates our TypeBuilder with fields and methods
1472 public sealed override bool Define ()
1474 if (members_defined)
1475 return members_defined_ok;
1477 members_defined_ok = DoDefineMembers ();
1478 members_defined = true;
1480 if (types != null) {
1481 foreach (var nested in types)
1485 return members_defined_ok;
1488 protected virtual bool DoDefineMembers ()
1490 if (iface_exprs != null) {
1491 foreach (TypeExpr iface in iface_exprs) {
1495 var iface_type = iface.Type;
1497 // Ensure the base is always setup
1498 var compiled_iface = iface_type.MemberDefinition as Interface;
1499 if (compiled_iface != null)
1500 compiled_iface.Define ();
1502 if (Kind == MemberKind.Interface)
1503 MemberCache.AddInterface (iface_type);
1505 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1506 if (oa != null && !IsObsolete)
1507 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1509 GenericTypeExpr ct = iface as GenericTypeExpr;
1511 // TODO: passing `this' is wrong, should be base type iface instead
1512 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1514 ct.CheckConstraints (this);
1516 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1517 Report.Error (1966, iface.Location,
1518 "`{0}': cannot implement a dynamic interface `{1}'",
1519 GetSignatureForError (), iface.GetSignatureForError ());
1526 if (base_type != null) {
1527 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1528 if (obsolete_attr != null && !IsObsolete)
1529 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1531 var ct = base_type_expr as GenericTypeExpr;
1533 ct.CheckConstraints (this);
1535 if (base_type.Interfaces != null) {
1536 foreach (var iface in base_type.Interfaces)
1537 spec.AddInterface (iface);
1540 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1541 if (baseContainer != null) {
1542 baseContainer.Define ();
1545 // It can trigger define of this type (for generic types only)
1547 if (HasMembersDefined)
1552 if (type_params != null) {
1553 foreach (var tp in type_params) {
1554 tp.CheckGenericConstraints ();
1558 DefineContainerMembers (constants);
1559 DefineContainerMembers (fields);
1561 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1562 pending = PendingImplementation.GetPendingImplementations (this);
1564 if (requires_delayed_unmanagedtype_check) {
1565 requires_delayed_unmanagedtype_check = false;
1566 foreach (FieldBase f in fields) {
1567 if (f.MemberType != null && f.MemberType.IsPointer)
1568 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1574 // Constructors are not in the defined_names array
1576 DefineContainerMembers (instance_constructors);
1578 DefineContainerMembers (events);
1579 DefineContainerMembers (ordered_explicit_member_list);
1580 DefineContainerMembers (ordered_member_list);
1582 if (operators != null) {
1583 DefineContainerMembers (operators);
1584 CheckPairedOperators ();
1587 ComputeIndexerName();
1588 CheckEqualsAndGetHashCode();
1590 if (Kind == MemberKind.Interface && iface_exprs != null) {
1591 MemberCache.RemoveHiddenMembers (spec);
1597 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1600 for (int i = 0; i < mcal.Count; ++i) {
1601 MemberCore mc = (MemberCore) mcal[i];
1604 } catch (Exception e) {
1605 throw new InternalErrorException (mc, e);
1611 protected virtual void ComputeIndexerName ()
1613 if (indexers == null)
1616 string class_indexer_name = null;
1619 // If there's both an explicit and an implicit interface implementation, the
1620 // explicit one actually implements the interface while the other one is just
1621 // a normal indexer. See bug #37714.
1624 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1625 foreach (Indexer i in indexers) {
1626 if (i.InterfaceType != null) {
1627 if (seen_normal_indexers)
1628 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1632 seen_normal_indexers = true;
1634 if (class_indexer_name == null) {
1635 class_indexer_name = i.ShortName;
1639 if (i.ShortName != class_indexer_name)
1640 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");
1643 if (class_indexer_name != null)
1644 indexer_name = class_indexer_name;
1647 void EmitIndexerName ()
1649 if (!seen_normal_indexers)
1652 PredefinedAttribute pa = Module.PredefinedAttributes.DefaultMember;
1653 if (pa.Constructor == null &&
1654 !pa.ResolveConstructor (Location, TypeManager.string_type))
1657 var encoder = new AttributeEncoder ();
1658 encoder.Encode (GetAttributeDefaultMember ());
1659 encoder.EncodeEmptyNamedArguments ();
1661 pa.EmitAttribute (TypeBuilder, encoder);
1664 protected virtual void CheckEqualsAndGetHashCode ()
1666 if (methods == null)
1669 if (HasEquals && !HasGetHashCode) {
1670 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1674 // Indicated whether container has StructLayout attribute set Explicit
1675 public bool HasExplicitLayout {
1676 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1677 set { caching_flags |= Flags.HasExplicitLayout; }
1680 public bool HasStructLayout {
1681 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1682 set { caching_flags |= Flags.HasStructLayout; }
1685 public MemberCache MemberCache {
1687 return spec.MemberCache;
1691 void CheckMemberUsage (List<MemberCore> al, string member_type)
1696 foreach (MemberCore mc in al) {
1697 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1700 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1701 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1706 public virtual void VerifyMembers ()
1709 // Check for internal or private fields that were never assigned
1711 if (Report.WarningLevel >= 3) {
1712 if (RootContext.EnhancedWarnings) {
1713 CheckMemberUsage (properties, "property");
1714 CheckMemberUsage (methods, "method");
1715 CheckMemberUsage (constants, "constant");
1718 if (fields != null){
1719 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1720 foreach (FieldBase f in fields) {
1721 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1722 if (is_type_exposed)
1729 if ((f.caching_flags & Flags.IsAssigned) == 0)
1730 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1732 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1733 f.GetSignatureForError ());
1739 // Only report 649 on level 4
1741 if (Report.WarningLevel < 4)
1744 if ((f.caching_flags & Flags.IsAssigned) != 0)
1748 // Don't be pendatic over serializable attributes
1750 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1753 Constant c = New.Constantify (f.MemberType, f.Location);
1754 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1755 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1761 public override void Emit ()
1764 MemberSpec candidate;
1765 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1766 if (conflict_symbol == null && candidate == null) {
1767 if ((ModFlags & Modifiers.NEW) != 0)
1768 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1769 GetSignatureForError ());
1771 if ((ModFlags & Modifiers.NEW) == 0) {
1772 if (candidate == null)
1773 candidate = conflict_symbol;
1775 Report.SymbolRelatedToPreviousError (candidate);
1776 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1777 GetSignatureForError (), candidate.GetSignatureForError ());
1782 if (all_tp_builders != null) {
1783 int current_starts_index = CurrentTypeParametersStartIndex;
1784 for (int i = 0; i < all_tp_builders.Length; i++) {
1785 if (i < current_starts_index) {
1786 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1788 CurrentTypeParameters [i - current_starts_index].Emit ();
1793 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1794 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1797 if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
1798 TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
1804 // TODO: move to ClassOrStruct
1805 void EmitConstructors ()
1807 if (instance_constructors == null)
1810 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1811 bool has_compliant_args = false;
1813 foreach (Constructor c in instance_constructors) {
1817 catch (Exception e) {
1818 throw new InternalErrorException (c, e);
1821 if (has_compliant_args)
1824 has_compliant_args = c.HasCompliantArgs;
1826 if (!has_compliant_args)
1827 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1829 foreach (Constructor c in instance_constructors) {
1833 catch (Exception e) {
1834 throw new InternalErrorException (c, e);
1841 /// Emits the code, this step is performed after all
1842 /// the types, enumerations, constructors
1844 public virtual void EmitType ()
1846 if (OptAttributes != null)
1847 OptAttributes.Emit ();
1851 EmitConstructors ();
1853 if (constants != null)
1854 foreach (Const con in constants)
1857 if (default_static_constructor != null)
1858 default_static_constructor.Emit ();
1860 if (operators != null)
1861 foreach (Operator o in operators)
1864 if (properties != null)
1865 foreach (Property p in properties)
1868 if (indexers != null) {
1869 foreach (Indexer indx in indexers)
1874 if (events != null){
1875 foreach (Event e in Events)
1879 if (methods != null) {
1880 for (int i = 0; i < methods.Count; ++i)
1881 ((MethodOrOperator) methods [i]).Emit ();
1885 foreach (FieldBase f in fields)
1888 if (types != null) {
1889 foreach (TypeContainer t in types)
1893 if (pending != null)
1894 pending.VerifyPendingMethods (Report);
1896 if (Report.Errors > 0)
1899 if (compiler_generated != null) {
1900 for (int i = 0; i < compiler_generated.Count; ++i)
1901 compiler_generated [i].EmitType ();
1905 public virtual void CloseType ()
1907 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1910 // Close base type container first to avoid TypeLoadException
1911 if (spec.BaseType != null) {
1912 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1913 if (btype != null) {
1916 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1922 caching_flags |= Flags.CloseTypeCreated;
1923 TypeBuilder.CreateType ();
1924 } catch (TypeLoadException){
1926 // This is fine, the code still created the type
1928 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1929 // Console.WriteLine (e.Message);
1930 } catch (Exception e) {
1931 throw new InternalErrorException (this, e);
1935 foreach (TypeContainer tc in Types)
1939 if (compiler_generated != null)
1940 foreach (CompilerGeneratedClass c in compiler_generated)
1945 initialized_fields = null;
1946 initialized_static_fields = null;
1948 ordered_explicit_member_list = null;
1949 ordered_member_list = null;
1954 compiler_generated = null;
1955 default_constructor = null;
1956 default_static_constructor = null;
1958 OptAttributes = null;
1962 // Performs the validation on a Method's modifiers (properties have
1963 // the same properties).
1965 // TODO: Why is it not done at parse stage ?
1967 public bool MethodModifiersValid (MemberCore mc)
1969 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1970 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1972 var flags = mc.ModFlags;
1975 // At most one of static, virtual or override
1977 if ((flags & Modifiers.STATIC) != 0){
1978 if ((flags & vao) != 0){
1979 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1980 mc.GetSignatureForError ());
1985 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1986 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1987 mc.GetSignatureForError ());
1992 // If the declaration includes the abstract modifier, then the
1993 // declaration does not include static, virtual or extern
1995 if ((flags & Modifiers.ABSTRACT) != 0){
1996 if ((flags & Modifiers.EXTERN) != 0){
1998 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2002 if ((flags & Modifiers.SEALED) != 0) {
2003 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2007 if ((flags & Modifiers.VIRTUAL) != 0){
2008 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2012 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2013 Report.SymbolRelatedToPreviousError (this);
2014 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2015 mc.GetSignatureForError (), GetSignatureForError ());
2020 if ((flags & Modifiers.PRIVATE) != 0){
2021 if ((flags & vao) != 0){
2022 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2027 if ((flags & Modifiers.SEALED) != 0){
2028 if ((flags & Modifiers.OVERRIDE) == 0){
2029 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2037 public Constructor DefaultStaticConstructor {
2038 get { return default_static_constructor; }
2041 protected override bool VerifyClsCompliance ()
2043 if (!base.VerifyClsCompliance ())
2046 // Check this name against other containers
2047 NamespaceEntry.NS.VerifyClsCompliance ();
2049 // Check all container names for user classes
2050 if (Kind != MemberKind.Delegate)
2051 MemberCache.VerifyClsCompliance (Definition, Report);
2053 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2054 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2055 GetSignatureForError (), BaseType.GetSignatureForError ());
2061 /// Performs checks for an explicit interface implementation. First it
2062 /// checks whether the `interface_type' is a base inteface implementation.
2063 /// Then it checks whether `name' exists in the interface type.
2065 public bool VerifyImplements (InterfaceMemberBase mb)
2067 var ifaces = spec.Interfaces;
2068 if (ifaces != null) {
2069 foreach (TypeSpec t in ifaces){
2070 if (t == mb.InterfaceType)
2075 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2076 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2077 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2082 // Used for visiblity checks to tests whether this definition shares
2083 // base type baseType, it does member-definition search
2085 public bool IsBaseTypeDefinition (TypeSpec baseType)
2087 // RootContext check
2088 if (TypeBuilder == null)
2093 if (type.MemberDefinition == baseType.MemberDefinition)
2096 type = type.BaseType;
2097 } while (type != null);
2102 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2104 return Module.DeclaringAssembly == assembly;
2107 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2109 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2113 // Public function used to locate types.
2115 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2117 // Returns: Type or null if they type can not be found.
2119 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2121 FullNamedExpression e;
2122 if (arity == 0 && Cache.TryGetValue (name, out e))
2126 int errors = Report.Errors;
2129 TypeParameter[] tp = CurrentTypeParameters;
2131 TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2133 e = new TypeParameterExpr (tparam, Location.Null);
2138 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2141 e = new TypeExpression (t, Location.Null);
2142 else if (Parent != null) {
2143 e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2145 e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2148 // TODO MemberCache: How to cache arity stuff ?
2149 if (errors == Report.Errors && arity == 0)
2155 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2157 // TODO: GenericMethod only
2158 if (PartialContainer == null)
2161 // Has any nested type
2162 // Does not work, because base type can have
2163 //if (PartialContainer.Types == null)
2166 var container = PartialContainer.CurrentType;
2168 // Is not Root container
2169 if (container == null)
2172 var t = MemberCache.FindNestedType (container, name, arity);
2176 // FIXME: Breaks error reporting
2177 if (!t.IsAccessible (CurrentType))
2183 public void Mark_HasEquals ()
2185 cached_method |= CachedMethods.Equals;
2188 public void Mark_HasGetHashCode ()
2190 cached_method |= CachedMethods.GetHashCode;
2194 /// Method container contains Equals method
2196 public bool HasEquals {
2198 return (cached_method & CachedMethods.Equals) != 0;
2203 /// Method container contains GetHashCode method
2205 public bool HasGetHashCode {
2207 return (cached_method & CachedMethods.GetHashCode) != 0;
2211 public bool HasStaticFieldInitializer {
2213 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2217 cached_method |= CachedMethods.HasStaticFieldInitializer;
2219 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2224 // Generates xml doc comments (if any), and if required,
2225 // handle warning report.
2227 internal override void GenerateDocComment (DeclSpace ds)
2229 DocUtil.GenerateTypeDocComment (this, ds, Report);
2232 public override string DocCommentHeader {
2233 get { return "T:"; }
2237 public abstract class ClassOrStruct : TypeContainer
2239 SecurityType declarative_security;
2241 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2242 MemberName name, Attributes attrs, MemberKind kind)
2243 : base (ns, parent, name, attrs, kind)
2247 protected override bool AddToContainer (MemberCore symbol, string name)
2249 if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2250 if (symbol is TypeParameter) {
2251 Report.Error (694, symbol.Location,
2252 "Type parameter `{0}' has same name as containing type, or method",
2253 symbol.GetSignatureForError ());
2257 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2258 if (imb == null || !imb.IsExplicitImpl) {
2259 Report.SymbolRelatedToPreviousError (this);
2260 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2261 symbol.GetSignatureForError ());
2266 return base.AddToContainer (symbol, name);
2269 public override void VerifyMembers ()
2271 base.VerifyMembers ();
2273 if ((events != null) && Report.WarningLevel >= 3) {
2274 foreach (Event e in events){
2275 // Note: The event can be assigned from same class only, so we can report
2276 // this warning for all accessibility modes
2277 if ((e.caching_flags & Flags.IsUsed) == 0)
2278 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2282 if (types != null) {
2283 foreach (var t in types)
2288 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2290 if (a.IsValidSecurityAttribute ()) {
2291 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2295 if (a.Type == pa.StructLayout) {
2296 PartialContainer.HasStructLayout = true;
2297 if (a.IsExplicitLayoutKind ())
2298 PartialContainer.HasExplicitLayout = true;
2301 if (a.Type == pa.Dynamic) {
2302 a.Error_MisusedDynamicAttribute ();
2306 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2310 /// Defines the default constructors
2312 protected void DefineDefaultConstructor (bool is_static)
2314 // The default instance constructor is public
2315 // If the class is abstract, the default constructor is protected
2316 // The default static constructor is private
2320 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2322 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2325 Constructor c = new Constructor (this, MemberName.Name, mods,
2326 null, ParametersCompiled.EmptyReadOnlyParameters,
2327 new GeneratedBaseInitializer (Location),
2331 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2334 protected override bool DoDefineMembers ()
2336 CheckProtectedModifier ();
2338 base.DoDefineMembers ();
2340 if (default_static_constructor != null)
2341 default_static_constructor.Define ();
2346 public override void Emit ()
2348 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2349 DefineDefaultConstructor (true);
2350 default_static_constructor.Define ();
2355 if (declarative_security != null) {
2356 foreach (var de in declarative_security) {
2358 TypeBuilder.__AddDeclarativeSecurity (de);
2360 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2366 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2368 DeclSpace top_level = Parent;
2369 if (top_level != null) {
2370 while (top_level.Parent != null)
2371 top_level = top_level.Parent;
2373 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2374 if (candidates != null) {
2375 scope = NamespaceEntry;
2380 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2383 protected override TypeAttributes TypeAttr {
2385 if (default_static_constructor == null)
2386 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2388 return base.TypeAttr;
2394 // TODO: should be sealed
2395 public class Class : ClassOrStruct {
2396 const Modifiers AllowedModifiers =
2399 Modifiers.PROTECTED |
2400 Modifiers.INTERNAL |
2402 Modifiers.ABSTRACT |
2407 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2409 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2411 : base (ns, parent, name, attrs, MemberKind.Class)
2413 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2414 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2415 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2417 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2418 Report.FeatureIsNotAvailable (Location, "static classes");
2422 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2424 if (part.Name == "System.Object")
2425 Report.Error (537, part.Location,
2426 "The class System.Object cannot have a base class or implement an interface.");
2427 base.AddBasesForPart (part, bases);
2430 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2432 if (a.Type == pa.AttributeUsage) {
2433 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2434 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2438 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2439 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2443 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2444 a.Error_MissingGuidAttribute ();
2448 if (a.Type == pa.Extension) {
2449 a.Error_MisusedExtensionAttribute ();
2453 if (a.Type.IsConditionallyExcluded (Location))
2456 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2459 public override AttributeTargets AttributeTargets {
2461 return AttributeTargets.Class;
2465 protected override void DefineContainerMembers (System.Collections.IList list)
2471 base.DefineContainerMembers (list);
2475 foreach (MemberCore m in list) {
2476 if (m is Operator) {
2477 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2481 if (m is Destructor) {
2482 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2487 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2491 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2494 if (m is Constructor) {
2495 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2499 Method method = m as Method;
2500 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2501 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2505 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2508 base.DefineContainerMembers (list);
2511 protected override bool DoDefineMembers ()
2513 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2514 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2517 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2518 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2521 if (InstanceConstructors == null && !IsStatic)
2522 DefineDefaultConstructor (false);
2524 return base.DoDefineMembers ();
2527 public override void Emit ()
2531 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2532 Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2534 if (base_type != null && base_type.HasDynamicElement) {
2535 Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
2539 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2541 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2543 if (base_class == null) {
2544 if (spec != TypeManager.object_type)
2545 base_type = TypeManager.object_type;
2547 if (base_type.IsGenericParameter){
2548 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2549 GetSignatureForError (), base_type.GetSignatureForError ());
2550 } else if (IsGeneric && base_type.IsAttribute) {
2551 Report.Error (698, base_class.Location,
2552 "A generic type cannot derive from `{0}' because it is an attribute class",
2553 base_class.GetSignatureForError ());
2554 } else if (base_type.IsStatic) {
2555 Report.SymbolRelatedToPreviousError (base_class.Type);
2556 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2557 GetSignatureForError (), base_type.GetSignatureForError ());
2558 } else if (base_type.IsSealed) {
2559 Report.SymbolRelatedToPreviousError (base_class.Type);
2560 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2561 GetSignatureForError (), base_type.GetSignatureForError ());
2562 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2563 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2564 GetSignatureForError (), base_class.GetSignatureForError ());
2567 if (base_type is BuildinTypeSpec && !(spec is BuildinTypeSpec) &&
2568 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2569 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2570 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2571 GetSignatureForError (), base_type.GetSignatureForError ());
2573 base_type = TypeManager.object_type;
2576 if (!IsAccessibleAs (base_type)) {
2577 Report.SymbolRelatedToPreviousError (base_type);
2578 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2579 base_type.GetSignatureForError (), GetSignatureForError ());
2583 if (PartialContainer.IsStatic && ifaces != null) {
2584 foreach (TypeExpr t in ifaces)
2585 Report.SymbolRelatedToPreviousError (t.Type);
2586 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2592 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2593 /// Valid only for attribute classes.
2594 public override string[] ConditionalConditions ()
2596 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2599 caching_flags &= ~Flags.Excluded_Undetected;
2601 if (OptAttributes == null)
2604 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
2608 string[] conditions = new string[attrs.Length];
2609 for (int i = 0; i < conditions.Length; ++i)
2610 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2612 caching_flags |= Flags.Excluded;
2617 // FIXME: How do we deal with the user specifying a different
2620 protected override TypeAttributes TypeAttr {
2622 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2624 ta |= StaticClassAttribute;
2630 public sealed class Struct : ClassOrStruct {
2632 bool is_unmanaged, has_unmanaged_check_done;
2636 // Modifiers allowed in a struct declaration
2638 const Modifiers AllowedModifiers =
2641 Modifiers.PROTECTED |
2642 Modifiers.INTERNAL |
2646 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2647 Modifiers mod, Attributes attrs)
2648 : base (ns, parent, name, attrs, MemberKind.Struct)
2650 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2651 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2652 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2655 public override AttributeTargets AttributeTargets {
2657 return AttributeTargets.Struct;
2661 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2663 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2666 // When struct constains fixed fixed and struct layout has explicitly
2667 // set CharSet, its value has to be propagated to compiler generated
2670 if (a.Type == pa.StructLayout && Fields != null) {
2671 var value = a.GetNamedValue ("CharSet");
2675 for (int i = 0; i < Fields.Count; ++i) {
2676 FixedField ff = Fields [i] as FixedField;
2680 ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2685 bool CheckStructCycles (Struct s)
2687 if (s.Fields == null)
2694 foreach (FieldBase field in s.Fields) {
2695 TypeSpec ftype = field.Spec.MemberType;
2696 if (!ftype.IsStruct)
2699 if (ftype is BuildinTypeSpec)
2702 foreach (var targ in ftype.TypeArguments) {
2703 if (!CheckFieldTypeCycle (targ)) {
2704 Report.Error (523, field.Location,
2705 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2706 field.GetSignatureForError (), ftype.GetSignatureForError ());
2711 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2714 if (!CheckFieldTypeCycle (ftype)) {
2715 Report.Error (523, field.Location,
2716 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2717 field.GetSignatureForError (), ftype.GetSignatureForError ());
2722 s.InTransit = false;
2726 bool CheckFieldTypeCycle (TypeSpec ts)
2728 var fts = ts.MemberDefinition as Struct;
2732 return CheckStructCycles (fts);
2735 public override void Emit ()
2737 CheckStructCycles (this);
2742 public override bool IsUnmanagedType ()
2747 if (has_unmanaged_check_done)
2748 return is_unmanaged;
2750 if (requires_delayed_unmanagedtype_check)
2753 requires_delayed_unmanagedtype_check = true;
2755 foreach (FieldBase f in fields) {
2759 // It can happen when recursive unmanaged types are defined
2760 // struct S { S* s; }
2761 TypeSpec mt = f.MemberType;
2766 while (mt.IsPointer)
2767 mt = TypeManager.GetElementType (mt);
2769 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2770 has_unmanaged_check_done = true;
2774 if (TypeManager.IsUnmanagedType (mt))
2777 has_unmanaged_check_done = true;
2781 has_unmanaged_check_done = true;
2782 is_unmanaged = true;
2786 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2788 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2789 base_type = TypeManager.value_type;
2793 protected override TypeAttributes TypeAttr {
2795 const TypeAttributes DefaultTypeAttributes =
2796 TypeAttributes.SequentialLayout |
2797 TypeAttributes.Sealed;
2799 return base.TypeAttr | DefaultTypeAttributes;
2803 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2805 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2806 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2807 field.GetSignatureForError ());
2810 base.RegisterFieldForInitialization (field, expression);
2818 public sealed class Interface : TypeContainer {
2821 /// Modifiers allowed in a class declaration
2823 public const Modifiers AllowedModifiers =
2826 Modifiers.PROTECTED |
2827 Modifiers.INTERNAL |
2831 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2833 : base (ns, parent, name, attrs, MemberKind.Interface)
2835 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2837 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2838 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2841 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2843 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2844 a.Error_MissingGuidAttribute ();
2848 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
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;
2869 protected override bool VerifyClsCompliance ()
2871 if (!base.VerifyClsCompliance ())
2874 if (iface_exprs != null) {
2875 foreach (var iface in iface_exprs) {
2876 if (iface.Type.IsCLSCompliant ())
2879 Report.SymbolRelatedToPreviousError (iface.Type);
2880 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2881 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2889 public abstract class InterfaceMemberBase : MemberBase
2892 // Common modifiers allowed in a class declaration
2894 protected const Modifiers AllowedModifiersClass =
2897 Modifiers.PROTECTED |
2898 Modifiers.INTERNAL |
2903 Modifiers.OVERRIDE |
2904 Modifiers.ABSTRACT |
2909 // Common modifiers allowed in a struct declaration
2911 protected const Modifiers AllowedModifiersStruct =
2914 Modifiers.PROTECTED |
2915 Modifiers.INTERNAL |
2918 Modifiers.OVERRIDE |
2923 // Common modifiers allowed in a interface declaration
2925 protected const Modifiers AllowedModifiersInterface =
2930 // Whether this is an interface member.
2932 public bool IsInterface;
2935 // If true, this is an explicit interface implementation
2937 public bool IsExplicitImpl;
2939 protected bool is_external_implementation;
2942 // The interface type we are explicitly implementing
2944 public TypeSpec InterfaceType;
2947 // The method we're overriding if this is an override method.
2949 protected MethodSpec base_method;
2951 readonly Modifiers explicit_mod_flags;
2952 public MethodAttributes flags;
2954 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2955 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2956 MemberName name, Attributes attrs)
2957 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2960 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2961 IsExplicitImpl = (MemberName.Left != null);
2962 explicit_mod_flags = mod;
2965 protected override bool CheckBase ()
2967 if (!base.CheckBase ())
2970 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2971 CheckForDuplications ();
2976 // For System.Object only
2977 if (Parent.BaseType == null)
2980 MemberSpec candidate;
2981 var base_member = FindBaseMember (out candidate);
2983 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2984 if (base_member == null) {
2985 if (candidate == null) {
2986 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2987 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2988 "object.Finalize()");
2990 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2991 GetSignatureForError (), SimpleName.GetMemberType (this));
2994 Report.SymbolRelatedToPreviousError (candidate);
2996 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2997 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2998 else if (this is PropertyBase)
2999 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
3000 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3002 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
3003 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3009 if (!CheckOverrideAgainstBase (base_member))
3012 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
3014 if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3015 Report.SymbolRelatedToPreviousError (base_member);
3016 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3017 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3020 if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3021 Report.SymbolRelatedToPreviousError (base_member);
3022 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3023 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3027 base_method = base_member as MethodSpec;
3031 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
3032 base_member = candidate;
3034 if (base_member == null) {
3035 if ((ModFlags & Modifiers.NEW) != 0) {
3036 if (base_member == null) {
3037 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3038 GetSignatureForError ());
3042 if ((ModFlags & Modifiers.NEW) == 0) {
3043 ModFlags |= Modifiers.NEW;
3044 if (!IsCompilerGenerated) {
3045 Report.SymbolRelatedToPreviousError (base_member);
3046 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3047 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",
3048 GetSignatureForError (), base_member.GetSignatureForError ());
3050 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3051 GetSignatureForError (), base_member.GetSignatureForError ());
3056 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3057 Report.SymbolRelatedToPreviousError (base_member);
3058 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3059 GetSignatureForError (), base_member.GetSignatureForError ());
3066 protected virtual bool CheckForDuplications ()
3068 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3072 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3073 // that have been defined.
3075 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3079 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3080 Report.SymbolRelatedToPreviousError (base_member);
3081 Report.Error (506, Location,
3082 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3083 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3087 // Now we check that the overriden method is not final
3088 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3089 Report.SymbolRelatedToPreviousError (base_member);
3090 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3091 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3095 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3096 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3097 Report.SymbolRelatedToPreviousError (base_member);
3098 if (this is PropertyBasedMember) {
3099 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3100 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3102 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3103 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3111 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3113 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3114 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3116 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3118 // It must be at least "protected"
3120 if ((thisp & Modifiers.PROTECTED) == 0) {
3125 // when overriding protected internal, the method can be declared
3126 // protected internal only within the same assembly or assembly
3127 // which has InternalsVisibleTo
3129 if ((thisp & Modifiers.INTERNAL) != 0) {
3130 return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3134 // protected overriding protected internal inside same assembly
3135 // requires internal modifier as well
3137 if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
3144 return thisp == base_classp;
3147 public override bool Define ()
3150 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3151 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3153 flags = MethodAttributes.Public |
3154 MethodAttributes.Abstract |
3155 MethodAttributes.HideBySig |
3156 MethodAttributes.NewSlot |
3157 MethodAttributes.Virtual;
3159 Parent.PartialContainer.MethodModifiersValid (this);
3161 flags = ModifiersExtensions.MethodAttr (ModFlags);
3164 if (IsExplicitImpl) {
3165 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3166 if (iface_texpr == null)
3169 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3170 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3171 GetSignatureForError ());
3174 InterfaceType = iface_texpr.Type;
3176 if (!InterfaceType.IsInterface) {
3177 Report.SymbolRelatedToPreviousError (InterfaceType);
3178 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3179 TypeManager.CSharpName (InterfaceType));
3181 Parent.PartialContainer.VerifyImplements (this);
3184 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3187 return base.Define ();
3190 protected bool DefineParameters (ParametersCompiled parameters)
3192 if (!parameters.Resolve (this))
3196 for (int i = 0; i < parameters.Count; ++i) {
3197 Parameter p = parameters [i];
3199 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3200 p.Warning_UselessOptionalParameter (Report);
3202 if (p.CheckAccessibility (this))
3205 TypeSpec t = parameters.Types [i];
3206 Report.SymbolRelatedToPreviousError (t);
3207 if (this is Indexer)
3208 Report.Error (55, Location,
3209 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3210 TypeManager.CSharpName (t), GetSignatureForError ());
3211 else if (this is Operator)
3212 Report.Error (57, Location,
3213 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3214 TypeManager.CSharpName (t), GetSignatureForError ());
3216 Report.Error (51, Location,
3217 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3218 TypeManager.CSharpName (t), GetSignatureForError ());
3224 public override void Emit()
3226 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3227 // We are more strict than csc and report this as an error because SRE does not allow emit that
3228 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3229 if (this is Constructor) {
3230 Report.Error (824, Location,
3231 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3233 Report.Error (626, Location,
3234 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3235 GetSignatureForError ());
3242 public override bool EnableOverloadChecks (MemberCore overload)
3245 // Two members can differ in their explicit interface
3246 // type parameter only
3248 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3249 if (imb != null && imb.IsExplicitImpl) {
3250 if (IsExplicitImpl) {
3251 caching_flags |= Flags.MethodOverloadsExist;
3256 return IsExplicitImpl;
3259 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3261 var base_modifiers = base_member.Modifiers;
3263 // Remove internal modifier from types which are not internally accessible
3264 if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
3265 !base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
3266 base_modifiers = Modifiers.PROTECTED;
3268 Report.SymbolRelatedToPreviousError (base_member);
3269 Report.Error (507, member.Location,
3270 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3271 member.GetSignatureForError (),
3272 ModifiersExtensions.AccessibilityName (base_modifiers),
3273 base_member.GetSignatureForError ());
3276 protected void Error_StaticReturnType ()
3278 Report.Error (722, Location,
3279 "`{0}': static types cannot be used as return types",
3280 MemberType.GetSignatureForError ());
3284 /// Gets base method and its return type
3286 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3288 return MemberCache.FindBaseMember (this, out bestCandidate);
3292 // The "short" name of this property / indexer / event. This is the
3293 // name without the explicit interface.
3295 public string ShortName {
3296 get { return MemberName.Name; }
3297 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3301 // Returns full metadata method name
3303 public string GetFullName (MemberName name)
3305 return GetFullName (name.Name);
3308 public string GetFullName (string name)
3310 if (!IsExplicitImpl)
3314 // When dealing with explicit members a full interface type
3315 // name is added to member name to avoid possible name conflicts
3317 // We use CSharpName which gets us full name with benefit of
3318 // replacing predefined names which saves some space and name
3321 return TypeManager.CSharpName (InterfaceType) + "." + name;
3324 protected override bool VerifyClsCompliance ()
3326 if (!base.VerifyClsCompliance ()) {
3330 if (GenericMethod != null)
3331 GenericMethod.VerifyClsCompliance ();
3336 public override bool IsUsed
3338 get { return IsExplicitImpl || base.IsUsed; }
3343 public abstract class MemberBase : MemberCore
3345 protected FullNamedExpression type_expr;
3346 protected TypeSpec member_type;
3348 public readonly DeclSpace ds;
3349 public readonly GenericMethod GenericMethod;
3351 protected MemberBase (DeclSpace parent, GenericMethod generic,
3352 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3353 MemberName name, Attributes attrs)
3354 : base (parent, name, attrs)
3356 this.ds = generic != null ? generic : (DeclSpace) parent;
3357 this.type_expr = type;
3358 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3359 GenericMethod = generic;
3360 if (GenericMethod != null)
3361 GenericMethod.ModFlags = ModFlags;
3366 public TypeSpec MemberType {
3372 public FullNamedExpression TypeExpression {
3381 // Main member define entry
3383 public override bool Define ()
3385 DoMemberTypeIndependentChecks ();
3388 // Returns false only when type resolution failed
3390 if (!ResolveMemberType ())
3393 DoMemberTypeDependentChecks ();
3398 // Any type_name independent checks
3400 protected virtual void DoMemberTypeIndependentChecks ()
3402 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3403 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3404 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3405 GetSignatureForError (), Parent.GetSignatureForError ());
3410 // Any type_name dependent checks
3412 protected virtual void DoMemberTypeDependentChecks ()
3414 // verify accessibility
3415 if (!IsAccessibleAs (MemberType)) {
3416 Report.SymbolRelatedToPreviousError (MemberType);
3417 if (this is Property)
3418 Report.Error (53, Location,
3419 "Inconsistent accessibility: property type `" +
3420 TypeManager.CSharpName (MemberType) + "' is less " +
3421 "accessible than property `" + GetSignatureForError () + "'");
3422 else if (this is Indexer)
3423 Report.Error (54, Location,
3424 "Inconsistent accessibility: indexer return type `" +
3425 TypeManager.CSharpName (MemberType) + "' is less " +
3426 "accessible than indexer `" + GetSignatureForError () + "'");
3427 else if (this is MethodCore) {
3428 if (this is Operator)
3429 Report.Error (56, Location,
3430 "Inconsistent accessibility: return type `" +
3431 TypeManager.CSharpName (MemberType) + "' is less " +
3432 "accessible than operator `" + GetSignatureForError () + "'");
3434 Report.Error (50, Location,
3435 "Inconsistent accessibility: return type `" +
3436 TypeManager.CSharpName (MemberType) + "' is less " +
3437 "accessible than method `" + GetSignatureForError () + "'");
3439 Report.Error (52, Location,
3440 "Inconsistent accessibility: field type `" +
3441 TypeManager.CSharpName (MemberType) + "' is less " +
3442 "accessible than field `" + GetSignatureForError () + "'");
3446 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3447 TypeManager.CheckTypeVariance (MemberType, variance, this);
3450 protected bool IsTypePermitted ()
3452 if (TypeManager.IsSpecialType (MemberType)) {
3453 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3459 protected virtual bool CheckBase ()
3461 CheckProtectedModifier ();
3466 protected virtual bool ResolveMemberType ()
3468 if (member_type != null)
3469 throw new InternalErrorException ("Multi-resolve");
3471 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3476 // Replace original type name, error reporting can use fully resolved name
3480 member_type = te.Type;