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) | base.TypeAttr;
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 spec.SetMetaInfo (TypeBuilder);
1030 spec.MemberCache = new MemberCache (this);
1031 spec.DeclaringType = Parent.CurrentType;
1034 Parent.MemberCache.AddMember (spec);
1037 string[] param_names = new string[TypeParameters.Length];
1038 for (int i = 0; i < TypeParameters.Length; i++)
1039 param_names [i] = TypeParameters[i].Name;
1041 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1043 int offset = CurrentTypeParametersStartIndex;
1044 for (int i = offset; i < all_tp_builders.Length; i++) {
1045 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1053 // Creates a proxy base method call inside this container for hoisted base member calls
1055 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1057 Method proxy_method;
1060 // One proxy per base method is enough
1062 if (hoisted_base_call_proxies == null) {
1063 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1064 proxy_method = null;
1066 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1069 if (proxy_method == null) {
1070 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1071 var base_parameters = new Parameter[method.Parameters.Count];
1072 for (int i = 0; i < base_parameters.Length; ++i) {
1073 var base_param = method.Parameters.FixedParameters[i];
1074 base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1075 base_param.Name, base_param.ModFlags, null, Location);
1076 base_parameters[i].Resolve (this, i);
1079 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1080 if (method.Parameters.HasArglist) {
1081 cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1082 cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve (Location);
1085 GenericMethod generic_method;
1086 MemberName member_name;
1087 if (method.IsGeneric) {
1089 // Copy all base generic method type parameters info
1091 var hoisted_tparams = method.GenericDefinition.TypeParameters;
1092 var targs = new TypeArguments ();
1093 var type_params = new TypeParameter[hoisted_tparams.Length];
1094 for (int i = 0; i < type_params.Length; ++i) {
1095 var tp = hoisted_tparams[i];
1096 targs.Add (new TypeParameterName (tp.Name, null, Location));
1097 type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
1100 member_name = new MemberName (name, targs, Location);
1101 generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1102 new TypeExpression (method.ReturnType, Location), cloned_params);
1104 member_name = new MemberName (name);
1105 generic_method = null;
1108 // Compiler generated proxy
1109 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1110 Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1111 member_name, cloned_params, null);
1113 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1115 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1116 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1118 // Get all the method parameters and pass them as arguments
1119 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1120 Statement statement;
1121 if (method.ReturnType == TypeManager.void_type)
1122 statement = new StatementExpression (real_base_call);
1124 statement = new Return (real_base_call, Location);
1126 block.AddStatement (statement);
1127 proxy_method.Block = block;
1129 methods.Add (proxy_method);
1130 proxy_method.Define ();
1132 hoisted_base_call_proxies.Add (method, proxy_method);
1135 return proxy_method.Spec;
1138 bool DefineBaseTypes ()
1140 iface_exprs = ResolveBaseTypes (out base_type_expr);
1141 if (partial_parts != null) {
1142 iface_exprs = GetNormalPartialBases ();
1145 var cycle = CheckRecursiveDefinition (this);
1146 if (cycle != null) {
1147 Report.SymbolRelatedToPreviousError (cycle);
1148 if (this is Interface) {
1149 Report.Error (529, Location,
1150 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1151 GetSignatureForError (), cycle.GetSignatureForError ());
1155 Report.Error (146, Location,
1156 "Circular base class dependency involving `{0}' and `{1}'",
1157 GetSignatureForError (), cycle.GetSignatureForError ());
1163 if (iface_exprs != null) {
1164 foreach (TypeExpr iface in iface_exprs) {
1165 // Prevents a crash, the interface might not have been resolved: 442144
1169 var iface_type = iface.Type;
1171 if (!spec.AddInterface (iface_type))
1174 if (iface_type.IsGeneric && spec.Interfaces != null) {
1175 foreach (var prev_iface in iface_exprs) {
1176 if (prev_iface == iface)
1179 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1182 Report.Error (695, Location,
1183 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1184 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1188 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1190 // Ensure the base is always setup
1191 var compiled_iface = iface_type.MemberDefinition as Interface;
1192 if (compiled_iface != null) {
1193 // TODO: Need DefineBaseType only
1194 compiled_iface.DefineType ();
1197 if (iface_type.Interfaces != null) {
1198 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1199 for (int i = 0; i < base_ifaces.Count; ++i) {
1200 var ii_iface_type = base_ifaces[i];
1201 if (spec.AddInterface (ii_iface_type)) {
1202 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1204 if (ii_iface_type.Interfaces != null)
1205 base_ifaces.AddRange (ii_iface_type.Interfaces);
1212 if (Kind == MemberKind.Interface) {
1213 spec.BaseType = TypeManager.object_type;
1217 if (base_type != null) {
1218 spec.BaseType = base_type;
1220 // Set base type after type creation
1221 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1227 public virtual void DefineConstants ()
1229 if (constants != null) {
1230 foreach (Const c in constants) {
1235 if (instance_constructors != null) {
1236 foreach (MethodCore m in instance_constructors) {
1237 var p = m.ParameterInfo;
1239 p.ResolveDefaultValues (m);
1244 if (methods != null) {
1245 foreach (MethodCore m in methods) {
1246 var p = m.ParameterInfo;
1248 p.ResolveDefaultValues (m);
1253 if (indexers != null) {
1254 foreach (Indexer i in indexers) {
1255 i.ParameterInfo.ResolveDefaultValues (i);
1259 if (types != null) {
1260 foreach (var t in types)
1261 t.DefineConstants ();
1266 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1268 public bool CreateType ()
1270 if (TypeBuilder != null)
1276 if (!CreateTypeBuilder ()) {
1281 if (partial_parts != null) {
1282 foreach (TypeContainer part in partial_parts) {
1284 part.current_type = current_type;
1285 part.TypeBuilder = TypeBuilder;
1289 if (Types != null) {
1290 foreach (TypeContainer tc in Types) {
1298 public override void DefineType ()
1305 type_defined = true;
1307 if (!DefineBaseTypes ()) {
1312 if (!DefineNestedTypes ()) {
1318 public override void SetParameterInfo (List<Constraints> constraints_list)
1320 base.SetParameterInfo (constraints_list);
1322 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1325 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1326 for (int i = 0; i < tc_names.Length; ++i) {
1327 if (tc_names [i].Name != type_params [i].Name) {
1328 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1329 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1330 GetSignatureForError ());
1334 if (tc_names [i].Variance != type_params [i].Variance) {
1335 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1336 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1337 GetSignatureForError ());
1344 // Replaces normal spec with predefined one when compiling corlib
1345 // and this type container defines predefined type
1347 public void SetPredefinedSpec (BuildinTypeSpec spec)
1352 void UpdateTypeParameterConstraints (TypeContainer part)
1354 TypeParameter[] current_params = type_params;
1355 for (int i = 0; i < current_params.Length; i++) {
1356 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1359 Report.SymbolRelatedToPreviousError (Location, "");
1360 Report.Error (265, part.Location,
1361 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1362 GetSignatureForError (), current_params [i].GetSignatureForError ());
1366 public bool ResolveTypeParameters ()
1368 if (!DoResolveTypeParameters ())
1371 if (types != null) {
1372 foreach (var type in types)
1373 if (!type.ResolveTypeParameters ())
1377 if (compiler_generated != null) {
1378 foreach (CompilerGeneratedClass c in compiler_generated)
1379 if (!c.ResolveTypeParameters ())
1386 protected virtual bool DoResolveTypeParameters ()
1388 if (CurrentTypeParameters == null)
1391 if (PartialContainer != this)
1392 throw new InternalErrorException ();
1394 var base_context = new BaseContext (this);
1395 foreach (TypeParameter type_param in CurrentTypeParameters) {
1396 if (!type_param.ResolveConstraints (base_context)) {
1402 if (partial_parts != null) {
1403 foreach (TypeContainer part in partial_parts)
1404 UpdateTypeParameterConstraints (part);
1410 protected virtual bool DefineNestedTypes ()
1412 if (Types != null) {
1413 foreach (TypeContainer tc in Types)
1420 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1422 if (InTransit != null)
1427 if (base_type_expr != null) {
1428 var ptc = base_type.MemberDefinition as TypeContainer;
1429 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1433 if (iface_exprs != null) {
1434 foreach (TypeExpr iface in iface_exprs) {
1435 // the interface might not have been resolved, prevents a crash, see #442144
1438 var ptc = iface.Type.MemberDefinition as Interface;
1439 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1444 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1452 /// Populates our TypeBuilder with fields and methods
1454 public sealed override bool Define ()
1456 if (members_defined)
1457 return members_defined_ok;
1459 members_defined_ok = DoDefineMembers ();
1460 members_defined = true;
1462 if (types != null) {
1463 foreach (var nested in types)
1467 return members_defined_ok;
1470 protected virtual bool DoDefineMembers ()
1472 if (iface_exprs != null) {
1473 foreach (TypeExpr iface in iface_exprs) {
1477 var iface_type = iface.Type;
1479 // Ensure the base is always setup
1480 var compiled_iface = iface_type.MemberDefinition as Interface;
1481 if (compiled_iface != null)
1482 compiled_iface.Define ();
1484 if (Kind == MemberKind.Interface)
1485 MemberCache.AddInterface (iface_type);
1487 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1488 if (oa != null && !IsObsolete)
1489 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1491 GenericTypeExpr ct = iface as GenericTypeExpr;
1493 // TODO: passing `this' is wrong, should be base type iface instead
1494 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1496 ct.CheckConstraints (this);
1498 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1499 Report.Error (1966, iface.Location,
1500 "`{0}': cannot implement a dynamic interface `{1}'",
1501 GetSignatureForError (), iface.GetSignatureForError ());
1508 if (base_type != null) {
1509 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1510 if (obsolete_attr != null && !IsObsolete)
1511 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1513 var ct = base_type_expr as GenericTypeExpr;
1515 ct.CheckConstraints (this);
1517 if (base_type.Interfaces != null) {
1518 foreach (var iface in base_type.Interfaces)
1519 spec.AddInterface (iface);
1522 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1523 if (baseContainer != null) {
1524 baseContainer.Define ();
1527 // It can trigger define of this type (for generic types only)
1529 if (HasMembersDefined)
1534 if (type_params != null) {
1535 foreach (var tp in type_params) {
1536 tp.CheckGenericConstraints ();
1540 DefineContainerMembers (constants);
1541 DefineContainerMembers (fields);
1543 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1544 pending = PendingImplementation.GetPendingImplementations (this);
1546 if (requires_delayed_unmanagedtype_check) {
1547 requires_delayed_unmanagedtype_check = false;
1548 foreach (FieldBase f in fields) {
1549 if (f.MemberType != null && f.MemberType.IsPointer)
1550 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1556 // Constructors are not in the defined_names array
1558 DefineContainerMembers (instance_constructors);
1560 DefineContainerMembers (events);
1561 DefineContainerMembers (ordered_explicit_member_list);
1562 DefineContainerMembers (ordered_member_list);
1564 if (operators != null) {
1565 DefineContainerMembers (operators);
1566 CheckPairedOperators ();
1569 ComputeIndexerName();
1570 CheckEqualsAndGetHashCode();
1575 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1578 for (int i = 0; i < mcal.Count; ++i) {
1579 MemberCore mc = (MemberCore) mcal[i];
1582 } catch (Exception e) {
1583 throw new InternalErrorException (mc, e);
1589 protected virtual void ComputeIndexerName ()
1591 if (indexers == null)
1594 string class_indexer_name = null;
1597 // If there's both an explicit and an implicit interface implementation, the
1598 // explicit one actually implements the interface while the other one is just
1599 // a normal indexer. See bug #37714.
1602 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1603 foreach (Indexer i in indexers) {
1604 if (i.InterfaceType != null) {
1605 if (seen_normal_indexers)
1606 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1610 seen_normal_indexers = true;
1612 if (class_indexer_name == null) {
1613 class_indexer_name = i.ShortName;
1617 if (i.ShortName != class_indexer_name)
1618 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");
1621 if (class_indexer_name != null)
1622 indexer_name = class_indexer_name;
1625 void EmitIndexerName ()
1627 if (!seen_normal_indexers)
1630 PredefinedAttribute pa = Module.PredefinedAttributes.DefaultMember;
1631 if (pa.Constructor == null &&
1632 !pa.ResolveConstructor (Location, TypeManager.string_type))
1635 var encoder = new AttributeEncoder (false);
1636 encoder.Encode (GetAttributeDefaultMember ());
1637 encoder.EncodeEmptyNamedArguments ();
1639 pa.EmitAttribute (TypeBuilder, encoder);
1642 protected virtual void CheckEqualsAndGetHashCode ()
1644 if (methods == null)
1647 if (HasEquals && !HasGetHashCode) {
1648 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1652 // Indicated whether container has StructLayout attribute set Explicit
1653 public bool HasExplicitLayout {
1654 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1655 set { caching_flags |= Flags.HasExplicitLayout; }
1658 public bool HasStructLayout {
1659 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1660 set { caching_flags |= Flags.HasStructLayout; }
1663 public MemberCache MemberCache {
1665 return spec.MemberCache;
1669 void CheckMemberUsage (List<MemberCore> al, string member_type)
1674 foreach (MemberCore mc in al) {
1675 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1678 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1679 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1684 public virtual void VerifyMembers ()
1687 // Check for internal or private fields that were never assigned
1689 if (Report.WarningLevel >= 3) {
1690 if (RootContext.EnhancedWarnings) {
1691 CheckMemberUsage (properties, "property");
1692 CheckMemberUsage (methods, "method");
1693 CheckMemberUsage (constants, "constant");
1696 if (fields != null){
1697 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1698 foreach (FieldBase f in fields) {
1699 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1700 if (is_type_exposed)
1707 if ((f.caching_flags & Flags.IsAssigned) == 0)
1708 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1710 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1711 f.GetSignatureForError ());
1717 // Only report 649 on level 4
1719 if (Report.WarningLevel < 4)
1722 if ((f.caching_flags & Flags.IsAssigned) != 0)
1726 // Don't be pendatic over serializable attributes
1728 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1731 Constant c = New.Constantify (f.MemberType, f.Location);
1732 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1733 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1739 public override void Emit ()
1742 MemberSpec candidate;
1743 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1744 if (conflict_symbol == null && candidate == null) {
1745 if ((ModFlags & Modifiers.NEW) != 0)
1746 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1747 GetSignatureForError ());
1749 if ((ModFlags & Modifiers.NEW) == 0) {
1750 if (candidate == null)
1751 candidate = conflict_symbol;
1753 Report.SymbolRelatedToPreviousError (candidate);
1754 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1755 GetSignatureForError (), candidate.GetSignatureForError ());
1760 if (all_tp_builders != null) {
1761 int current_starts_index = CurrentTypeParametersStartIndex;
1762 for (int i = 0; i < all_tp_builders.Length; i++) {
1763 if (i < current_starts_index) {
1764 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1766 CurrentTypeParameters [i - current_starts_index].Emit ();
1771 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1772 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1777 // TODO: move to ClassOrStruct
1778 void EmitConstructors ()
1780 if (instance_constructors == null)
1783 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1784 bool has_compliant_args = false;
1786 foreach (Constructor c in instance_constructors) {
1790 catch (Exception e) {
1791 throw new InternalErrorException (c, e);
1794 if (has_compliant_args)
1797 has_compliant_args = c.HasCompliantArgs;
1799 if (!has_compliant_args)
1800 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1802 foreach (Constructor c in instance_constructors) {
1806 catch (Exception e) {
1807 throw new InternalErrorException (c, e);
1814 /// Emits the code, this step is performed after all
1815 /// the types, enumerations, constructors
1817 public virtual void EmitType ()
1819 if (OptAttributes != null)
1820 OptAttributes.Emit ();
1824 EmitConstructors ();
1826 if (constants != null)
1827 foreach (Const con in constants)
1830 if (default_static_constructor != null)
1831 default_static_constructor.Emit ();
1833 if (operators != null)
1834 foreach (Operator o in operators)
1837 if (properties != null)
1838 foreach (Property p in properties)
1841 if (indexers != null) {
1842 foreach (Indexer indx in indexers)
1847 if (events != null){
1848 foreach (Event e in Events)
1852 if (methods != null) {
1853 for (int i = 0; i < methods.Count; ++i)
1854 ((MethodOrOperator) methods [i]).Emit ();
1858 foreach (FieldBase f in fields)
1861 if (types != null) {
1862 foreach (TypeContainer t in types)
1866 if (pending != null)
1867 pending.VerifyPendingMethods (Report);
1869 if (Report.Errors > 0)
1872 if (compiler_generated != null) {
1873 for (int i = 0; i < compiler_generated.Count; ++i)
1874 compiler_generated [i].EmitType ();
1878 public virtual void CloseType ()
1880 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1883 // Close base type container first to avoid TypeLoadException
1884 if (spec.BaseType != null) {
1885 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1886 if (btype != null) {
1889 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1895 caching_flags |= Flags.CloseTypeCreated;
1896 TypeBuilder.CreateType ();
1897 } catch (TypeLoadException){
1899 // This is fine, the code still created the type
1901 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1902 // Console.WriteLine (e.Message);
1903 } catch (Exception e) {
1904 throw new InternalErrorException (this, e);
1908 foreach (TypeContainer tc in Types)
1912 if (compiler_generated != null)
1913 foreach (CompilerGeneratedClass c in compiler_generated)
1918 initialized_fields = null;
1919 initialized_static_fields = null;
1921 ordered_explicit_member_list = null;
1922 ordered_member_list = null;
1927 compiler_generated = null;
1928 default_constructor = null;
1929 default_static_constructor = null;
1931 OptAttributes = null;
1935 // Performs the validation on a Method's modifiers (properties have
1936 // the same properties).
1938 // TODO: Why is it not done at parse stage ?
1940 public bool MethodModifiersValid (MemberCore mc)
1942 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1943 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1945 var flags = mc.ModFlags;
1948 // At most one of static, virtual or override
1950 if ((flags & Modifiers.STATIC) != 0){
1951 if ((flags & vao) != 0){
1952 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1953 mc.GetSignatureForError ());
1958 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1959 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1960 mc.GetSignatureForError ());
1965 // If the declaration includes the abstract modifier, then the
1966 // declaration does not include static, virtual or extern
1968 if ((flags & Modifiers.ABSTRACT) != 0){
1969 if ((flags & Modifiers.EXTERN) != 0){
1971 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1975 if ((flags & Modifiers.SEALED) != 0) {
1976 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1980 if ((flags & Modifiers.VIRTUAL) != 0){
1981 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1985 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1986 Report.SymbolRelatedToPreviousError (this);
1987 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1988 mc.GetSignatureForError (), GetSignatureForError ());
1993 if ((flags & Modifiers.PRIVATE) != 0){
1994 if ((flags & vao) != 0){
1995 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2000 if ((flags & Modifiers.SEALED) != 0){
2001 if ((flags & Modifiers.OVERRIDE) == 0){
2002 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2010 public Constructor DefaultStaticConstructor {
2011 get { return default_static_constructor; }
2014 protected override bool VerifyClsCompliance ()
2016 if (!base.VerifyClsCompliance ())
2019 // Check this name against other containers
2020 NamespaceEntry.NS.VerifyClsCompliance ();
2022 // Check all container names for user classes
2023 if (Kind != MemberKind.Delegate)
2024 MemberCache.VerifyClsCompliance (Definition, Report);
2026 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2027 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2028 GetSignatureForError (), BaseType.GetSignatureForError ());
2034 /// Performs checks for an explicit interface implementation. First it
2035 /// checks whether the `interface_type' is a base inteface implementation.
2036 /// Then it checks whether `name' exists in the interface type.
2038 public bool VerifyImplements (InterfaceMemberBase mb)
2040 var ifaces = spec.Interfaces;
2041 if (ifaces != null) {
2042 foreach (TypeSpec t in ifaces){
2043 if (t == mb.InterfaceType)
2048 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2049 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2050 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2055 // Used for visiblity checks to tests whether this definition shares
2056 // base type baseType, it does member-definition search
2058 public bool IsBaseTypeDefinition (TypeSpec baseType)
2060 // RootContext check
2061 if (TypeBuilder == null)
2066 if (type.MemberDefinition == baseType.MemberDefinition)
2069 type = type.BaseType;
2070 } while (type != null);
2075 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2077 return Module.DeclaringAssembly == assembly;
2080 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2082 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2086 // Public function used to locate types.
2088 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2090 // Returns: Type or null if they type can not be found.
2092 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2094 FullNamedExpression e;
2095 if (arity == 0 && Cache.TryGetValue (name, out e))
2099 int errors = Report.Errors;
2102 TypeParameter[] tp = CurrentTypeParameters;
2104 TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2106 e = new TypeParameterExpr (tparam, Location.Null);
2111 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2114 e = new TypeExpression (t, Location.Null);
2115 else if (Parent != null) {
2116 e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2118 e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2121 // TODO MemberCache: How to cache arity stuff ?
2122 if (errors == Report.Errors && arity == 0)
2128 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2130 // TODO: GenericMethod only
2131 if (PartialContainer == null)
2134 // Has any nested type
2135 // Does not work, because base type can have
2136 //if (PartialContainer.Types == null)
2139 var container = PartialContainer.CurrentType;
2141 // Is not Root container
2142 if (container == null)
2145 var t = MemberCache.FindNestedType (container, name, arity);
2149 // FIXME: Breaks error reporting
2150 if (!t.IsAccessible (CurrentType))
2156 public void Mark_HasEquals ()
2158 cached_method |= CachedMethods.Equals;
2161 public void Mark_HasGetHashCode ()
2163 cached_method |= CachedMethods.GetHashCode;
2167 /// Method container contains Equals method
2169 public bool HasEquals {
2171 return (cached_method & CachedMethods.Equals) != 0;
2176 /// Method container contains GetHashCode method
2178 public bool HasGetHashCode {
2180 return (cached_method & CachedMethods.GetHashCode) != 0;
2184 public bool HasStaticFieldInitializer {
2186 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2190 cached_method |= CachedMethods.HasStaticFieldInitializer;
2192 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2197 // Generates xml doc comments (if any), and if required,
2198 // handle warning report.
2200 internal override void GenerateDocComment (DeclSpace ds)
2202 DocUtil.GenerateTypeDocComment (this, ds, Report);
2205 public override string DocCommentHeader {
2206 get { return "T:"; }
2210 public abstract class ClassOrStruct : TypeContainer
2212 SecurityType declarative_security;
2214 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2215 MemberName name, Attributes attrs, MemberKind kind)
2216 : base (ns, parent, name, attrs, kind)
2220 protected override bool AddToContainer (MemberCore symbol, string name)
2222 if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2223 if (symbol is TypeParameter) {
2224 Report.Error (694, symbol.Location,
2225 "Type parameter `{0}' has same name as containing type, or method",
2226 symbol.GetSignatureForError ());
2230 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2231 if (imb == null || !imb.IsExplicitImpl) {
2232 Report.SymbolRelatedToPreviousError (this);
2233 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2234 symbol.GetSignatureForError ());
2239 return base.AddToContainer (symbol, name);
2242 public override void VerifyMembers ()
2244 base.VerifyMembers ();
2246 if ((events != null) && Report.WarningLevel >= 3) {
2247 foreach (Event e in events){
2248 // Note: The event can be assigned from same class only, so we can report
2249 // this warning for all accessibility modes
2250 if ((e.caching_flags & Flags.IsUsed) == 0)
2251 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2255 if (types != null) {
2256 foreach (var t in types)
2261 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2263 if (a.IsValidSecurityAttribute ()) {
2264 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2268 if (a.Type == pa.StructLayout) {
2269 PartialContainer.HasStructLayout = true;
2270 if (a.IsExplicitLayoutKind ())
2271 PartialContainer.HasExplicitLayout = true;
2274 if (a.Type == pa.Dynamic) {
2275 a.Error_MisusedDynamicAttribute ();
2279 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2283 /// Defines the default constructors
2285 protected void DefineDefaultConstructor (bool is_static)
2287 // The default instance constructor is public
2288 // If the class is abstract, the default constructor is protected
2289 // The default static constructor is private
2293 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2295 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2298 Constructor c = new Constructor (this, MemberName.Name, mods,
2299 null, ParametersCompiled.EmptyReadOnlyParameters,
2300 new GeneratedBaseInitializer (Location),
2304 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2307 protected override bool DoDefineMembers ()
2309 CheckProtectedModifier ();
2311 base.DoDefineMembers ();
2313 if (default_static_constructor != null)
2314 default_static_constructor.Define ();
2319 public override void Emit ()
2321 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2322 DefineDefaultConstructor (true);
2323 default_static_constructor.Define ();
2328 if (declarative_security != null) {
2329 foreach (var de in declarative_security) {
2331 TypeBuilder.__AddDeclarativeSecurity (de);
2333 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2339 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2341 DeclSpace top_level = Parent;
2342 if (top_level != null) {
2343 while (top_level.Parent != null)
2344 top_level = top_level.Parent;
2346 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2347 if (candidates != null) {
2348 scope = NamespaceEntry;
2353 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2356 protected override TypeAttributes TypeAttr {
2358 if (default_static_constructor == null)
2359 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2361 return base.TypeAttr;
2367 // TODO: should be sealed
2368 public class Class : ClassOrStruct {
2369 const Modifiers AllowedModifiers =
2372 Modifiers.PROTECTED |
2373 Modifiers.INTERNAL |
2375 Modifiers.ABSTRACT |
2380 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2382 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2384 : base (ns, parent, name, attrs, MemberKind.Class)
2386 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2387 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2388 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2390 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2391 Report.FeatureIsNotAvailable (Location, "static classes");
2395 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2397 if (part.Name == "System.Object")
2398 Report.Error (537, part.Location,
2399 "The class System.Object cannot have a base class or implement an interface.");
2400 base.AddBasesForPart (part, bases);
2403 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2405 if (a.Type == pa.AttributeUsage) {
2406 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2407 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2411 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2412 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2416 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2417 a.Error_MissingGuidAttribute ();
2421 if (a.Type == pa.Extension) {
2422 a.Error_MisusedExtensionAttribute ();
2426 if (a.Type.IsConditionallyExcluded (Location))
2429 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2432 public override AttributeTargets AttributeTargets {
2434 return AttributeTargets.Class;
2438 protected override void DefineContainerMembers (System.Collections.IList list)
2444 base.DefineContainerMembers (list);
2448 foreach (MemberCore m in list) {
2449 if (m is Operator) {
2450 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2454 if (m is Destructor) {
2455 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2460 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2464 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2467 if (m is Constructor) {
2468 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2472 Method method = m as Method;
2473 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2474 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2478 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2481 base.DefineContainerMembers (list);
2484 protected override bool DoDefineMembers ()
2486 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2487 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2490 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2491 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2494 if (InstanceConstructors == null && !IsStatic)
2495 DefineDefaultConstructor (false);
2497 return base.DoDefineMembers ();
2500 public override void Emit ()
2504 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2505 Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2507 if (base_type != null && base_type.HasDynamicElement) {
2508 Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
2512 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2514 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2516 if (base_class == null) {
2517 if (spec != TypeManager.object_type)
2518 base_type = TypeManager.object_type;
2520 if (base_type.IsGenericParameter){
2521 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2522 GetSignatureForError (), base_type.GetSignatureForError ());
2523 } else if (IsGeneric && base_type.IsAttribute) {
2524 Report.Error (698, base_class.Location,
2525 "A generic type cannot derive from `{0}' because it is an attribute class",
2526 base_class.GetSignatureForError ());
2527 } else if (base_type.IsStatic) {
2528 Report.SymbolRelatedToPreviousError (base_class.Type);
2529 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2530 GetSignatureForError (), base_type.GetSignatureForError ());
2531 } else if (base_type.IsSealed) {
2532 Report.SymbolRelatedToPreviousError (base_class.Type);
2533 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2534 GetSignatureForError (), base_type.GetSignatureForError ());
2535 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2536 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2537 GetSignatureForError (), base_class.GetSignatureForError ());
2540 if (base_type is BuildinTypeSpec && !(spec is BuildinTypeSpec) &&
2541 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2542 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2543 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2544 GetSignatureForError (), base_type.GetSignatureForError ());
2546 base_type = TypeManager.object_type;
2549 if (!IsAccessibleAs (base_type)) {
2550 Report.SymbolRelatedToPreviousError (base_type);
2551 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2552 base_type.GetSignatureForError (), GetSignatureForError ());
2556 if (PartialContainer.IsStatic && ifaces != null) {
2557 foreach (TypeExpr t in ifaces)
2558 Report.SymbolRelatedToPreviousError (t.Type);
2559 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2565 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2566 /// Valid only for attribute classes.
2567 public override string[] ConditionalConditions ()
2569 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2572 caching_flags &= ~Flags.Excluded_Undetected;
2574 if (OptAttributes == null)
2577 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
2581 string[] conditions = new string[attrs.Length];
2582 for (int i = 0; i < conditions.Length; ++i)
2583 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2585 caching_flags |= Flags.Excluded;
2590 // FIXME: How do we deal with the user specifying a different
2593 protected override TypeAttributes TypeAttr {
2595 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2597 ta |= StaticClassAttribute;
2603 public sealed class Struct : ClassOrStruct {
2605 bool is_unmanaged, has_unmanaged_check_done;
2609 // Modifiers allowed in a struct declaration
2611 const Modifiers AllowedModifiers =
2614 Modifiers.PROTECTED |
2615 Modifiers.INTERNAL |
2619 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2620 Modifiers mod, Attributes attrs)
2621 : base (ns, parent, name, attrs, MemberKind.Struct)
2623 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2624 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2625 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2628 public override AttributeTargets AttributeTargets {
2630 return AttributeTargets.Struct;
2634 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2636 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2639 // When struct constains fixed fixed and struct layout has explicitly
2640 // set CharSet, its value has to be propagated to compiler generated
2643 if (a.Type == pa.StructLayout && Fields != null) {
2644 var value = a.GetNamedValue ("CharSet");
2648 for (int i = 0; i < Fields.Count; ++i) {
2649 FixedField ff = Fields [i] as FixedField;
2653 ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2658 bool CheckStructCycles (Struct s)
2660 if (s.Fields == null)
2667 foreach (FieldBase field in s.Fields) {
2668 TypeSpec ftype = field.Spec.MemberType;
2669 if (!ftype.IsStruct)
2672 if (ftype is BuildinTypeSpec)
2675 foreach (var targ in ftype.TypeArguments) {
2676 if (!CheckFieldTypeCycle (targ)) {
2677 Report.Error (523, field.Location,
2678 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2679 field.GetSignatureForError (), ftype.GetSignatureForError ());
2684 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2687 if (!CheckFieldTypeCycle (ftype)) {
2688 Report.Error (523, field.Location,
2689 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2690 field.GetSignatureForError (), ftype.GetSignatureForError ());
2695 s.InTransit = false;
2699 bool CheckFieldTypeCycle (TypeSpec ts)
2701 var fts = ts.MemberDefinition as Struct;
2705 return CheckStructCycles (fts);
2708 public override void Emit ()
2710 CheckStructCycles (this);
2715 public override bool IsUnmanagedType ()
2720 if (has_unmanaged_check_done)
2721 return is_unmanaged;
2723 if (requires_delayed_unmanagedtype_check)
2726 requires_delayed_unmanagedtype_check = true;
2728 foreach (FieldBase f in fields) {
2732 // It can happen when recursive unmanaged types are defined
2733 // struct S { S* s; }
2734 TypeSpec mt = f.MemberType;
2739 while (mt.IsPointer)
2740 mt = TypeManager.GetElementType (mt);
2742 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2743 has_unmanaged_check_done = true;
2747 if (TypeManager.IsUnmanagedType (mt))
2750 has_unmanaged_check_done = true;
2754 has_unmanaged_check_done = true;
2755 is_unmanaged = true;
2759 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2761 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2762 base_type = TypeManager.value_type;
2766 protected override TypeAttributes TypeAttr {
2768 const TypeAttributes DefaultTypeAttributes =
2769 TypeAttributes.SequentialLayout |
2770 TypeAttributes.Sealed;
2772 return base.TypeAttr | DefaultTypeAttributes;
2776 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2778 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2779 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2780 field.GetSignatureForError ());
2783 base.RegisterFieldForInitialization (field, expression);
2791 public sealed class Interface : TypeContainer {
2794 /// Modifiers allowed in a class declaration
2796 public const Modifiers AllowedModifiers =
2799 Modifiers.PROTECTED |
2800 Modifiers.INTERNAL |
2804 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2806 : base (ns, parent, name, attrs, MemberKind.Interface)
2808 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2810 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2811 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2814 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2816 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2817 a.Error_MissingGuidAttribute ();
2821 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2825 public override AttributeTargets AttributeTargets {
2827 return AttributeTargets.Interface;
2831 protected override TypeAttributes TypeAttr {
2833 const TypeAttributes DefaultTypeAttributes =
2834 TypeAttributes.AutoLayout |
2835 TypeAttributes.Abstract |
2836 TypeAttributes.Interface;
2838 return base.TypeAttr | DefaultTypeAttributes;
2842 protected override bool VerifyClsCompliance ()
2844 if (!base.VerifyClsCompliance ())
2847 if (iface_exprs != null) {
2848 foreach (var iface in iface_exprs) {
2849 if (iface.Type.IsCLSCompliant ())
2852 Report.SymbolRelatedToPreviousError (iface.Type);
2853 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2854 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2862 public abstract class InterfaceMemberBase : MemberBase
2865 // Common modifiers allowed in a class declaration
2867 protected const Modifiers AllowedModifiersClass =
2870 Modifiers.PROTECTED |
2871 Modifiers.INTERNAL |
2876 Modifiers.OVERRIDE |
2877 Modifiers.ABSTRACT |
2882 // Common modifiers allowed in a struct declaration
2884 protected const Modifiers AllowedModifiersStruct =
2887 Modifiers.PROTECTED |
2888 Modifiers.INTERNAL |
2891 Modifiers.OVERRIDE |
2896 // Common modifiers allowed in a interface declaration
2898 protected const Modifiers AllowedModifiersInterface =
2903 // Whether this is an interface member.
2905 public bool IsInterface;
2908 // If true, this is an explicit interface implementation
2910 public bool IsExplicitImpl;
2912 protected bool is_external_implementation;
2915 // The interface type we are explicitly implementing
2917 public TypeSpec InterfaceType;
2920 // The method we're overriding if this is an override method.
2922 protected MethodSpec base_method;
2924 readonly Modifiers explicit_mod_flags;
2925 public MethodAttributes flags;
2927 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2928 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2929 MemberName name, Attributes attrs)
2930 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2933 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2934 IsExplicitImpl = (MemberName.Left != null);
2935 explicit_mod_flags = mod;
2938 protected override bool CheckBase ()
2940 if (!base.CheckBase ())
2943 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2944 CheckForDuplications ();
2949 // For System.Object only
2950 if (Parent.BaseType == null)
2953 MemberSpec candidate;
2954 var base_member = FindBaseMember (out candidate);
2956 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2957 if (base_member == null) {
2958 if (candidate == null) {
2959 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2960 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2961 "object.Finalize()");
2963 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2964 GetSignatureForError (), SimpleName.GetMemberType (this));
2967 Report.SymbolRelatedToPreviousError (candidate);
2969 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2970 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2971 else if (this is PropertyBase)
2972 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2973 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2975 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2976 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2982 if (!CheckOverrideAgainstBase (base_member))
2985 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2987 if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
2988 Report.SymbolRelatedToPreviousError (base_member);
2989 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2990 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2993 if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
2994 Report.SymbolRelatedToPreviousError (base_member);
2995 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2996 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3000 base_method = base_member as MethodSpec;
3004 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
3005 base_member = candidate;
3007 if (base_member == null) {
3008 if ((ModFlags & Modifiers.NEW) != 0) {
3009 if (base_member == null) {
3010 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3011 GetSignatureForError ());
3015 if ((ModFlags & Modifiers.NEW) == 0) {
3016 ModFlags |= Modifiers.NEW;
3017 if (!IsCompilerGenerated) {
3018 Report.SymbolRelatedToPreviousError (base_member);
3019 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3020 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",
3021 GetSignatureForError (), base_member.GetSignatureForError ());
3023 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3024 GetSignatureForError (), base_member.GetSignatureForError ());
3029 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3030 Report.SymbolRelatedToPreviousError (base_member);
3031 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3032 GetSignatureForError (), base_member.GetSignatureForError ());
3039 protected virtual bool CheckForDuplications ()
3041 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3045 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3046 // that have been defined.
3048 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3052 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3053 Report.SymbolRelatedToPreviousError (base_member);
3054 Report.Error (506, Location,
3055 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3056 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3060 // Now we check that the overriden method is not final
3061 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3062 Report.SymbolRelatedToPreviousError (base_member);
3063 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3064 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3068 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3069 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3070 Report.SymbolRelatedToPreviousError (base_member);
3071 if (this is PropertyBasedMember) {
3072 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3073 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3075 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3076 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3084 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3086 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3087 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3089 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3091 // when overriding protected internal, the method can be declared
3092 // protected internal only within the same assembly or assembly
3093 // which has InternalsVisibleTo
3095 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3096 return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3098 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
3100 // if it's not "protected internal", it must be "protected"
3105 if (this_member.Parent.PartialContainer.DeclaringAssembly == base_member.DeclaringType.MemberDefinition.DeclaringAssembly) {
3107 // protected within the same assembly - an error
3111 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
3112 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
3114 // protected ok, but other attributes differ - report an error
3121 return thisp == base_classp;
3124 public override bool Define ()
3127 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3128 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3130 flags = MethodAttributes.Public |
3131 MethodAttributes.Abstract |
3132 MethodAttributes.HideBySig |
3133 MethodAttributes.NewSlot |
3134 MethodAttributes.Virtual;
3136 Parent.PartialContainer.MethodModifiersValid (this);
3138 flags = ModifiersExtensions.MethodAttr (ModFlags);
3141 if (IsExplicitImpl) {
3142 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3143 if (iface_texpr == null)
3146 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3147 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3148 GetSignatureForError ());
3151 InterfaceType = iface_texpr.Type;
3153 if (!InterfaceType.IsInterface) {
3154 Report.SymbolRelatedToPreviousError (InterfaceType);
3155 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3156 TypeManager.CSharpName (InterfaceType));
3158 Parent.PartialContainer.VerifyImplements (this);
3161 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3164 return base.Define ();
3167 protected bool DefineParameters (ParametersCompiled parameters)
3169 if (!parameters.Resolve (this))
3173 for (int i = 0; i < parameters.Count; ++i) {
3174 Parameter p = parameters [i];
3176 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3177 p.Warning_UselessOptionalParameter (Report);
3179 if (p.CheckAccessibility (this))
3182 TypeSpec t = parameters.Types [i];
3183 Report.SymbolRelatedToPreviousError (t);
3184 if (this is Indexer)
3185 Report.Error (55, Location,
3186 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3187 TypeManager.CSharpName (t), GetSignatureForError ());
3188 else if (this is Operator)
3189 Report.Error (57, Location,
3190 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3191 TypeManager.CSharpName (t), GetSignatureForError ());
3193 Report.Error (51, Location,
3194 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3195 TypeManager.CSharpName (t), GetSignatureForError ());
3201 public override void Emit()
3203 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3204 // We are more strict than csc and report this as an error because SRE does not allow emit that
3205 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3206 if (this is Constructor) {
3207 Report.Error (824, Location,
3208 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3210 Report.Error (626, Location,
3211 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3212 GetSignatureForError ());
3219 public override bool EnableOverloadChecks (MemberCore overload)
3222 // Two members can differ in their explicit interface
3223 // type parameter only
3225 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3226 if (imb != null && imb.IsExplicitImpl) {
3227 if (IsExplicitImpl) {
3228 caching_flags |= Flags.MethodOverloadsExist;
3233 return IsExplicitImpl;
3236 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3238 Report.SymbolRelatedToPreviousError (base_member);
3239 Report.Error (507, member.Location,
3240 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3241 member.GetSignatureForError (),
3242 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3243 base_member.GetSignatureForError ());
3246 protected void Error_StaticReturnType ()
3248 Report.Error (722, Location,
3249 "`{0}': static types cannot be used as return types",
3250 MemberType.GetSignatureForError ());
3254 /// Gets base method and its return type
3256 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3258 return MemberCache.FindBaseMember (this, out bestCandidate);
3262 // The "short" name of this property / indexer / event. This is the
3263 // name without the explicit interface.
3265 public string ShortName {
3266 get { return MemberName.Name; }
3267 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3271 // Returns full metadata method name
3273 public string GetFullName (MemberName name)
3275 return GetFullName (name.Name);
3278 public string GetFullName (string name)
3280 if (!IsExplicitImpl)
3284 // When dealing with explicit members a full interface type
3285 // name is added to member name to avoid possible name conflicts
3287 // We use CSharpName which gets us full name with benefit of
3288 // replacing predefined names which saves some space and name
3291 return TypeManager.CSharpName (InterfaceType) + "." + name;
3294 protected override bool VerifyClsCompliance ()
3296 if (!base.VerifyClsCompliance ()) {
3300 if (GenericMethod != null)
3301 GenericMethod.VerifyClsCompliance ();
3306 public override bool IsUsed
3308 get { return IsExplicitImpl || base.IsUsed; }
3313 public abstract class MemberBase : MemberCore
3315 protected FullNamedExpression type_expr;
3316 protected TypeSpec member_type;
3318 public readonly DeclSpace ds;
3319 public readonly GenericMethod GenericMethod;
3321 protected MemberBase (DeclSpace parent, GenericMethod generic,
3322 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3323 MemberName name, Attributes attrs)
3324 : base (parent, name, attrs)
3326 this.ds = generic != null ? generic : (DeclSpace) parent;
3327 this.type_expr = type;
3328 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3329 GenericMethod = generic;
3330 if (GenericMethod != null)
3331 GenericMethod.ModFlags = ModFlags;
3336 public TypeSpec MemberType {
3342 public FullNamedExpression TypeExpression {
3351 // Main member define entry
3353 public override bool Define ()
3355 DoMemberTypeIndependentChecks ();
3358 // Returns false only when type resolution failed
3360 if (!ResolveMemberType ())
3363 DoMemberTypeDependentChecks ();
3368 // Any type_name independent checks
3370 protected virtual void DoMemberTypeIndependentChecks ()
3372 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3373 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3374 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3375 GetSignatureForError (), Parent.GetSignatureForError ());
3380 // Any type_name dependent checks
3382 protected virtual void DoMemberTypeDependentChecks ()
3384 // verify accessibility
3385 if (!IsAccessibleAs (MemberType)) {
3386 Report.SymbolRelatedToPreviousError (MemberType);
3387 if (this is Property)
3388 Report.Error (53, Location,
3389 "Inconsistent accessibility: property type `" +
3390 TypeManager.CSharpName (MemberType) + "' is less " +
3391 "accessible than property `" + GetSignatureForError () + "'");
3392 else if (this is Indexer)
3393 Report.Error (54, Location,
3394 "Inconsistent accessibility: indexer return type `" +
3395 TypeManager.CSharpName (MemberType) + "' is less " +
3396 "accessible than indexer `" + GetSignatureForError () + "'");
3397 else if (this is MethodCore) {
3398 if (this is Operator)
3399 Report.Error (56, Location,
3400 "Inconsistent accessibility: return type `" +
3401 TypeManager.CSharpName (MemberType) + "' is less " +
3402 "accessible than operator `" + GetSignatureForError () + "'");
3404 Report.Error (50, Location,
3405 "Inconsistent accessibility: return type `" +
3406 TypeManager.CSharpName (MemberType) + "' is less " +
3407 "accessible than method `" + GetSignatureForError () + "'");
3409 Report.Error (52, Location,
3410 "Inconsistent accessibility: field type `" +
3411 TypeManager.CSharpName (MemberType) + "' is less " +
3412 "accessible than field `" + GetSignatureForError () + "'");
3416 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3417 TypeManager.CheckTypeVariance (MemberType, variance, this);
3420 protected bool IsTypePermitted ()
3422 if (TypeManager.IsSpecialType (MemberType)) {
3423 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3429 protected virtual bool CheckBase ()
3431 CheckProtectedModifier ();
3436 protected virtual bool ResolveMemberType ()
3438 if (member_type != null)
3439 throw new InternalErrorException ("Multi-resolve");
3441 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3446 // Replace original type name, error reporting can use fully resolved name
3450 member_type = te.Type;