2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
26 using XmlElement = System.Object;
31 using Mono.CompilerServices.SymbolWriter;
33 namespace Mono.CSharp {
36 /// This is the base class for structs and classes.
38 public abstract class TypeContainer : DeclSpace, ITypeDefinition
41 // Different context is needed when resolving type container base
42 // types. Type names come from the parent scope but type parameter
43 // names from the container scope.
45 public struct BaseContext : IMemberContext
49 public BaseContext (TypeContainer tc)
54 #region IMemberContext Members
56 public CompilerContext Compiler {
57 get { return tc.Compiler; }
60 public TypeSpec CurrentType {
61 get { return tc.Parent.CurrentType; }
64 public TypeParameter[] CurrentTypeParameters {
65 get { return tc.PartialContainer.CurrentTypeParameters; }
68 public MemberCore CurrentMemberDefinition {
72 public bool HasUnresolvedConstraints {
76 public bool IsObsolete {
77 get { return tc.IsObsolete; }
80 public bool IsUnsafe {
81 get { return tc.IsUnsafe; }
84 public bool IsStatic {
85 get { return tc.IsStatic; }
88 public string GetSignatureForError ()
90 return tc.GetSignatureForError ();
93 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
98 public FullNamedExpression LookupNamespaceAlias (string name)
100 return tc.Parent.LookupNamespaceAlias (name);
103 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
106 TypeParameter[] tp = CurrentTypeParameters;
108 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
110 return new TypeParameterExpr (t, loc);
114 return tc.Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
124 GetHashCode = 1 << 1,
125 HasStaticFieldInitializer = 1 << 2
129 // Whether this is a struct, class or interface
130 public readonly MemberKind Kind;
132 // Holds a list of classes and structures
133 protected List<TypeContainer> types;
135 List<MemberCore> ordered_explicit_member_list;
136 List<MemberCore> ordered_member_list;
138 // Holds the list of properties
139 List<MemberCore> properties;
141 // Holds the list of constructors
142 protected List<Constructor> instance_constructors;
144 // Holds the list of fields
145 protected List<FieldBase> fields;
147 // Holds a list of fields that have initializers
148 protected List<FieldInitializer> initialized_fields;
150 // Holds a list of static fields that have initializers
151 protected List<FieldInitializer> initialized_static_fields;
153 // Holds the list of constants
154 protected List<MemberCore> constants;
156 // Holds the methods.
157 List<MemberCore> methods;
160 protected List<MemberCore> events;
162 // Holds the indexers
163 List<MemberCore> indexers;
165 // Holds the operators
166 List<MemberCore> operators;
168 // Holds the compiler generated classes
169 List<CompilerGeneratedClass> compiler_generated;
171 Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
174 // Pointers to the default constructor and the default static constructor
176 protected Constructor default_constructor;
177 protected Constructor default_static_constructor;
180 // Points to the first non-static field added to the container.
182 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
183 // and the first one's as good as any.
185 FieldBase first_nonstatic_field = null;
188 // This one is computed after we can distinguish interfaces
189 // from classes from the arraylist `type_bases'
191 protected TypeSpec base_type;
192 protected TypeExpr base_type_expr;
193 protected TypeExpr[] iface_exprs;
195 protected List<FullNamedExpression> type_bases;
197 bool members_defined;
198 bool members_defined_ok;
201 TypeContainer InTransit;
203 GenericTypeParameterBuilder[] all_tp_builders;
205 public const string DefaultIndexerName = "Item";
207 private bool seen_normal_indexers = false;
208 private string indexer_name = DefaultIndexerName;
209 protected bool requires_delayed_unmanagedtype_check;
212 private CachedMethods cached_method;
214 protected TypeSpec spec;
215 TypeSpec current_type;
217 List<TypeContainer> partial_parts;
219 public int DynamicSitesCounter;
222 /// The pending methods that need to be implemented
223 // (interfaces or abstract methods)
225 PendingImplementation pending;
227 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
228 Attributes attrs, MemberKind kind)
229 : base (ns, parent, name, attrs)
231 if (parent != null && parent.NamespaceEntry != ns)
232 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
235 this.PartialContainer = this;
240 public override TypeSpec CurrentType {
242 if (current_type == null) {
245 // Switch to inflated version as it's used by all expressions
247 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
248 current_type = spec.MakeGenericType (targs);
258 public override TypeParameter[] CurrentTypeParameters {
260 return PartialContainer.type_params;
264 int CurrentTypeParametersStartIndex {
266 int total = all_tp_builders.Length;
267 if (CurrentTypeParameters != null) {
268 return total - CurrentTypeParameters.Length;
274 public TypeSpec Definition {
280 public bool HasMembersDefined {
282 return members_defined;
288 public bool AddMember (MemberCore symbol)
290 return AddToContainer (symbol, symbol.MemberName.Basename);
293 public bool AddMember (MemberCore symbol, string name)
295 return AddToContainer (symbol, name);
298 protected virtual bool AddMemberType (TypeContainer ds)
300 return AddToContainer (ds, ds.Basename);
303 protected virtual void RemoveMemberType (DeclSpace ds)
305 RemoveFromContainer (ds.Basename);
308 public void AddConstant (Const constant)
310 if (!AddMember (constant))
313 if (constants == null)
314 constants = new List<MemberCore> ();
316 constants.Add (constant);
319 public TypeContainer AddTypeContainer (TypeContainer tc)
321 if (!AddMemberType (tc))
325 types = new List<TypeContainer> ();
331 public virtual TypeContainer AddPartial (TypeContainer next_part)
333 return AddPartial (next_part, next_part.Basename);
336 protected TypeContainer AddPartial (TypeContainer next_part, string name)
338 next_part.ModFlags |= Modifiers.PARTIAL;
339 TypeContainer tc = GetDefinition (name) as TypeContainer;
341 return AddTypeContainer (next_part);
343 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
344 Report.SymbolRelatedToPreviousError (next_part);
345 Error_MissingPartialModifier (tc);
348 if (tc.Kind != next_part.Kind) {
349 Report.SymbolRelatedToPreviousError (tc);
350 Report.Error (261, next_part.Location,
351 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
352 next_part.GetSignatureForError ());
355 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
356 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
357 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
358 Report.SymbolRelatedToPreviousError (tc);
359 Report.Error (262, next_part.Location,
360 "Partial declarations of `{0}' have conflicting accessibility modifiers",
361 next_part.GetSignatureForError ());
364 if (tc.partial_parts == null)
365 tc.partial_parts = new List<TypeContainer> (1);
367 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
368 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
369 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
370 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
371 tc.ModFlags |= next_part.ModFlags;
373 tc.ModFlags |= next_part.ModFlags;
376 tc.spec.Modifiers = tc.ModFlags;
378 if (next_part.attributes != null) {
379 if (tc.attributes == null)
380 tc.attributes = next_part.attributes;
382 tc.attributes.AddAttributes (next_part.attributes.Attrs);
385 next_part.PartialContainer = tc;
386 tc.partial_parts.Add (next_part);
390 public virtual void RemoveTypeContainer (TypeContainer next_part)
393 types.Remove (next_part);
394 RemoveMemberType (next_part);
397 public virtual TypeSpec AddDelegate (Delegate d)
399 AddTypeContainer (d);
403 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
405 if (ordered_explicit_member_list == null) {
406 ordered_explicit_member_list = new List<MemberCore> ();
407 ordered_member_list = new List<MemberCore> ();
411 if (Kind == MemberKind.Interface) {
412 Report.Error (541, mc.Location,
413 "`{0}': explicit interface declaration can only be declared in a class or struct",
414 mc.GetSignatureForError ());
417 ordered_explicit_member_list.Add (mc);
418 alist.Insert (0, mc);
420 ordered_member_list.Add (mc);
426 public void AddMethod (MethodOrOperator method)
428 if (!AddToContainer (method, method.MemberName.Basename))
432 methods = new List<MemberCore> ();
434 if (method.MemberName.Left != null)
435 AddMemberToList (method, methods, true);
437 AddMemberToList (method, methods, false);
440 public void AddConstructor (Constructor c)
442 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
443 if (!AddToContainer (c, is_static ?
444 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
447 if (is_static && c.ParameterInfo.IsEmpty){
448 if (default_static_constructor != null) {
449 Report.SymbolRelatedToPreviousError (default_static_constructor);
450 Report.Error (111, c.Location,
451 "A member `{0}' is already defined. Rename this member or use different parameter types",
452 c.GetSignatureForError ());
456 default_static_constructor = c;
458 if (c.ParameterInfo.IsEmpty)
459 default_constructor = c;
461 if (instance_constructors == null)
462 instance_constructors = new List<Constructor> ();
464 instance_constructors.Add (c);
468 public bool AddField (FieldBase field)
470 if (!AddMember (field))
474 fields = new List<FieldBase> ();
478 if ((field.ModFlags & Modifiers.STATIC) != 0)
481 if (first_nonstatic_field == null) {
482 first_nonstatic_field = field;
486 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
487 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
488 Report.Warning (282, 3, field.Location,
489 "struct instance field `{0}' found in different declaration from instance field `{1}'",
490 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
495 public void AddProperty (Property prop)
497 if (!AddMember (prop))
500 if (properties == null)
501 properties = new List<MemberCore> ();
503 if (prop.MemberName.Left != null)
504 AddMemberToList (prop, properties, true);
506 AddMemberToList (prop, properties, false);
509 public void AddEvent (Event e)
515 events = new List<MemberCore> ();
521 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
523 public void AddIndexer (Indexer i)
525 if (indexers == null)
526 indexers = new List<MemberCore> ();
528 if (i.IsExplicitImpl)
529 AddMemberToList (i, indexers, true);
531 AddMemberToList (i, indexers, false);
534 public void AddOperator (Operator op)
539 if (operators == null)
540 operators = new List<MemberCore> ();
545 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
547 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
549 if (compiler_generated == null)
550 compiler_generated = new List<CompilerGeneratedClass> ();
552 compiler_generated.Add (c);
555 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
557 if (a.Type == pa.DefaultMember) {
558 if (Indexers != null) {
559 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
564 if (a.Type == pa.Required) {
565 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
569 TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
572 public override AttributeTargets AttributeTargets {
574 throw new NotSupportedException ();
578 public IList<TypeContainer> Types {
584 public IList<MemberCore> Methods {
590 public IList<MemberCore> Constants {
596 public TypeSpec BaseType {
598 return spec.BaseType;
602 public IList<FieldBase> Fields {
608 public IList<Constructor> InstanceConstructors {
610 return instance_constructors;
614 public IList<MemberCore> Properties {
620 public IList<MemberCore> Events {
626 public IList<MemberCore> Indexers {
632 public IList<MemberCore> Operators {
638 public IList<CompilerGeneratedClass> CompilerGeneratedClasses {
640 return compiler_generated;
644 protected override TypeAttributes TypeAttr {
646 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
650 public int TypeParametersCount {
652 return MemberName.Arity;
656 TypeParameterSpec[] ITypeDefinition.TypeParameters {
658 // TODO MemberCache: this is going to hurt
659 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
663 public string GetAttributeDefaultMember ()
665 return indexers == null ? DefaultIndexerName : indexer_name;
668 public bool IsComImport {
670 if (OptAttributes == null)
673 return OptAttributes.Contains (Compiler.PredefinedAttributes.ComImport);
677 string ITypeDefinition.Namespace {
679 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
683 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
685 if ((field.ModFlags & Modifiers.STATIC) != 0){
686 if (initialized_static_fields == null) {
687 PartialContainer.HasStaticFieldInitializer = true;
688 initialized_static_fields = new List<FieldInitializer> (4);
691 initialized_static_fields.Add (expression);
693 if (initialized_fields == null)
694 initialized_fields = new List<FieldInitializer> (4);
696 initialized_fields.Add (expression);
700 public void ResolveFieldInitializers (BlockContext ec)
702 if (partial_parts != null) {
703 foreach (TypeContainer part in partial_parts) {
704 part.DoResolveFieldInitializers (ec);
707 DoResolveFieldInitializers (ec);
710 void DoResolveFieldInitializers (BlockContext ec)
713 if (initialized_static_fields == null)
716 bool has_complex_initializer = !RootContext.Optimize;
718 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
719 for (i = 0; i < initialized_static_fields.Count; ++i) {
720 FieldInitializer fi = initialized_static_fields [i];
721 ExpressionStatement s = fi.ResolveStatement (ec);
723 s = EmptyExpressionStatement.Instance;
724 } else if (fi.IsComplexInitializer) {
725 has_complex_initializer |= true;
731 for (i = 0; i < initialized_static_fields.Count; ++i) {
732 FieldInitializer fi = initialized_static_fields [i];
734 // Need special check to not optimize code like this
735 // static int a = b = 5;
738 if (!has_complex_initializer && fi.IsDefaultInitializer)
741 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
747 if (initialized_fields == null)
750 for (int i = 0; i < initialized_fields.Count; ++i) {
751 FieldInitializer fi = initialized_fields [i];
752 ExpressionStatement s = fi.ResolveStatement (ec);
757 // Field is re-initialized to its default value => removed
759 if (fi.IsDefaultInitializer && RootContext.Optimize)
762 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
766 public override string DocComment {
778 public PendingImplementation PendingImplementations {
779 get { return pending; }
782 public TypeSpec GetAttributeCoClass ()
784 if (OptAttributes == null)
787 Attribute a = OptAttributes.Search (Compiler.PredefinedAttributes.CoClass);
791 return a.GetCoClassAttributeValue ();
794 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
797 if (OptAttributes != null) {
798 a = OptAttributes.Search (pa);
804 return a.GetAttributeUsageAttribute ();
807 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
809 // FIXME: get rid of partial_parts and store lists of bases of each part here
810 // assumed, not verified: 'part' is in 'partial_parts'
811 ((TypeContainer) part).type_bases = bases;
815 /// This function computes the Base class and also the
816 /// list of interfaces that the class or struct @c implements.
818 /// The return value is an array (might be null) of
819 /// interfaces implemented (as Types).
821 /// The @base_class argument is set to the base object or null
822 /// if this is `System.Object'.
824 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
827 if (type_bases == null)
830 int count = type_bases.Count;
831 TypeExpr [] ifaces = null;
832 var base_context = new BaseContext (this);
833 for (int i = 0, j = 0; i < count; i++){
834 FullNamedExpression fne = type_bases [i];
836 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
837 if (fne_resolved == null)
840 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
841 if (fne_resolved.Type == InternalType.Dynamic)
842 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
843 GetSignatureForError ());
845 base_type = fne_resolved.Type;
847 base_class = fne_resolved;
852 ifaces = new TypeExpr [count - i];
854 if (fne_resolved.Type.IsInterface) {
855 for (int ii = 0; ii < j; ++ii) {
856 if (fne_resolved.Type == ifaces [ii].Type) {
857 Report.Error (528, Location, "`{0}' is already listed in interface list",
858 fne_resolved.GetSignatureForError ());
863 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
864 Report.Error (61, fne.Location,
865 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
866 fne_resolved.GetSignatureForError (), GetSignatureForError ());
869 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
870 if (Kind != MemberKind.Class) {
871 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
872 } else if (base_class != null)
873 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
874 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
876 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
877 GetSignatureForError (), fne_resolved.GetSignatureForError ());
881 ifaces [j++] = fne_resolved;
887 TypeExpr[] GetNormalPartialBases ()
889 var ifaces = new List<TypeExpr> (0);
890 if (iface_exprs != null)
891 ifaces.AddRange (iface_exprs);
893 foreach (TypeContainer part in partial_parts) {
894 TypeExpr new_base_class;
895 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
896 if (new_base_class != null) {
897 if (base_type_expr != null && new_base_class.Type != base_type) {
898 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
899 Report.Error (263, part.Location,
900 "Partial declarations of `{0}' must not specify different base classes",
901 part.GetSignatureForError ());
903 base_type_expr = new_base_class;
904 base_type = base_type_expr.Type;
908 if (new_ifaces == null)
911 foreach (TypeExpr iface in new_ifaces) {
912 if (ifaces.Contains (iface))
919 if (ifaces.Count == 0)
922 return ifaces.ToArray ();
926 // Checks that some operators come in pairs:
932 // They are matched based on the return type and the argument types
934 void CheckPairedOperators ()
936 bool has_equality_or_inequality = false;
937 var operators = this.operators.ToArray ();
938 bool[] has_pair = new bool[operators.Length];
940 for (int i = 0; i < operators.Length; ++i) {
941 if (operators[i] == null)
944 Operator o_a = (Operator) operators[i];
945 Operator.OpType o_type = o_a.OperatorType;
946 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
947 has_equality_or_inequality = true;
949 Operator.OpType matching_type = o_a.GetMatchingOperator ();
950 if (matching_type == Operator.OpType.TOP) {
955 for (int ii = 0; ii < operators.Length; ++ii) {
956 Operator o_b = (Operator) operators[ii];
957 if (o_b == null || o_b.OperatorType != matching_type)
960 if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
963 if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
969 // Used to ignore duplicate user conversions
975 for (int i = 0; i < operators.Length; ++i) {
976 if (operators[i] == null || has_pair[i])
979 Operator o = (Operator) operators [i];
980 Report.Error (216, o.Location,
981 "The operator `{0}' requires a matching operator `{1}' to also be defined",
982 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
985 if (has_equality_or_inequality) {
986 if (Methods == null || !HasEquals)
987 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
988 GetSignatureForError ());
990 if (Methods == null || !HasGetHashCode)
991 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
992 GetSignatureForError ());
996 bool CreateTypeBuilder ()
999 // Sets .size to 1 for structs with no instance fields
1001 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1004 if (Compiler.GlobalRootNamespace.IsNamespace (Name)) {
1005 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1009 ModuleBuilder builder = Module.Compiled.Builder;
1010 TypeBuilder = builder.DefineType (Name, TypeAttr, null, type_size);
1012 TypeBuilder builder = Parent.TypeBuilder;
1014 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1017 spec.SetMetaInfo (TypeBuilder);
1018 spec.MemberCache = new MemberCache (this);
1019 spec.DeclaringType = Parent.CurrentType;
1022 Parent.MemberCache.AddMember (spec);
1025 string[] param_names = new string[TypeParameters.Length];
1026 for (int i = 0; i < TypeParameters.Length; i++)
1027 param_names [i] = TypeParameters[i].Name;
1029 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1031 int offset = CurrentTypeParametersStartIndex;
1032 for (int i = offset; i < all_tp_builders.Length; i++) {
1033 CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1041 // Creates a proxy base method call inside this container for hoisted base member calls
1043 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1045 Method proxy_method;
1048 // One proxy per base method is enough
1050 if (hoisted_base_call_proxies == null) {
1051 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1052 proxy_method = null;
1054 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1057 if (proxy_method == null) {
1058 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1059 var base_parameters = new Parameter[method.Parameters.Count];
1060 for (int i = 0; i < base_parameters.Length; ++i) {
1061 var base_param = method.Parameters.FixedParameters[i];
1062 base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1063 base_param.Name, base_param.ModFlags, null, Location);
1064 base_parameters[i].Resolve (this, i);
1067 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1068 if (method.Parameters.HasArglist) {
1069 cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1070 cloned_params.Types[0] = TypeManager.runtime_argument_handle_type;
1073 GenericMethod generic_method;
1074 MemberName member_name;
1075 if (method.IsGeneric) {
1077 // Copy all base generic method type parameters info
1079 var hoisted_tparams = method.GenericDefinition.TypeParameters;
1080 var targs = new TypeArguments ();
1081 var type_params = new TypeParameter[hoisted_tparams.Length];
1082 for (int i = 0; i < type_params.Length; ++i) {
1083 var tp = hoisted_tparams[i];
1084 targs.Add (new TypeParameterName (tp.Name, null, Location));
1085 type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
1088 member_name = new MemberName (name, targs, Location);
1089 generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1090 new TypeExpression (method.ReturnType, Location), cloned_params);
1092 member_name = new MemberName (name);
1093 generic_method = null;
1096 // Compiler generated proxy
1097 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1098 Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1099 member_name, cloned_params, null);
1101 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1103 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1104 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1106 // Get all the method parameters and pass them as arguments
1107 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1108 Statement statement;
1109 if (method.ReturnType == TypeManager.void_type)
1110 statement = new StatementExpression (real_base_call);
1112 statement = new Return (real_base_call, Location);
1114 block.AddStatement (statement);
1115 proxy_method.Block = block;
1117 methods.Add (proxy_method);
1118 proxy_method.Define ();
1120 hoisted_base_call_proxies.Add (method, proxy_method);
1123 return proxy_method.Spec;
1126 bool DefineBaseTypes ()
1128 iface_exprs = ResolveBaseTypes (out base_type_expr);
1129 if (partial_parts != null) {
1130 iface_exprs = GetNormalPartialBases ();
1133 var cycle = CheckRecursiveDefinition (this);
1134 if (cycle != null) {
1135 Report.SymbolRelatedToPreviousError (cycle);
1136 if (this is Interface) {
1137 Report.Error (529, Location,
1138 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1139 GetSignatureForError (), cycle.GetSignatureForError ());
1141 Report.Error (146, Location,
1142 "Circular base class dependency involving `{0}' and `{1}'",
1143 GetSignatureForError (), cycle.GetSignatureForError ());
1149 if (iface_exprs != null) {
1150 foreach (TypeExpr iface in iface_exprs) {
1151 // Prevents a crash, the interface might not have been resolved: 442144
1155 var iface_type = iface.Type;
1157 if (!spec.AddInterface (iface_type))
1160 if (iface_type.IsGeneric && spec.Interfaces != null) {
1161 foreach (var prev_iface in iface_exprs) {
1162 if (prev_iface == iface)
1165 if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1168 Report.Error (695, Location,
1169 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1170 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1174 TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1176 // Ensure the base is always setup
1177 var compiled_iface = iface_type.MemberDefinition as Interface;
1178 if (compiled_iface != null) {
1179 // TODO: Need DefineBaseType only
1180 compiled_iface.DefineType ();
1183 if (iface_type.Interfaces != null) {
1184 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1185 for (int i = 0; i < base_ifaces.Count; ++i) {
1186 var ii_iface_type = base_ifaces[i];
1187 if (spec.AddInterface (ii_iface_type)) {
1188 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1190 if (ii_iface_type.Interfaces != null)
1191 base_ifaces.AddRange (ii_iface_type.Interfaces);
1198 if (Kind == MemberKind.Interface) {
1199 spec.BaseType = TypeManager.object_type;
1203 if (base_type != null) {
1204 spec.BaseType = base_type;
1206 // Set base type after type creation
1207 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1213 public virtual void DefineConstants ()
1215 if (constants != null) {
1216 foreach (Const c in constants) {
1221 if (instance_constructors != null) {
1222 foreach (MethodCore m in instance_constructors) {
1223 var p = m.ParameterInfo;
1225 p.ResolveDefaultValues (m);
1230 if (methods != null) {
1231 foreach (MethodCore m in methods) {
1232 var p = m.ParameterInfo;
1234 p.ResolveDefaultValues (m);
1239 if (indexers != null) {
1240 foreach (Indexer i in indexers) {
1241 i.ParameterInfo.ResolveDefaultValues (i);
1245 if (types != null) {
1246 foreach (var t in types)
1247 t.DefineConstants ();
1252 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1254 public TypeBuilder CreateType ()
1256 if (TypeBuilder != null)
1262 if (!CreateTypeBuilder ()) {
1267 if (partial_parts != null) {
1268 foreach (TypeContainer part in partial_parts) {
1270 part.current_type = current_type;
1271 part.TypeBuilder = TypeBuilder;
1275 if (Types != null) {
1276 foreach (TypeContainer tc in Types) {
1277 if (tc.CreateType () == null) {
1287 public override TypeBuilder DefineType ()
1294 type_defined = true;
1296 if (!DefineBaseTypes ()) {
1301 if (!DefineNestedTypes ()) {
1309 public override void SetParameterInfo (List<Constraints> constraints_list)
1311 base.SetParameterInfo (constraints_list);
1313 if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1316 TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1317 for (int i = 0; i < tc_names.Length; ++i) {
1318 if (tc_names [i].Name != type_params [i].Name) {
1319 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1320 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1321 GetSignatureForError ());
1325 if (tc_names [i].Variance != type_params [i].Variance) {
1326 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1327 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1328 GetSignatureForError ());
1335 // Replaces normal spec with predefined one when compiling corlib
1336 // and this type container defines predefined type
1338 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1343 void UpdateTypeParameterConstraints (TypeContainer part)
1345 TypeParameter[] current_params = type_params;
1346 for (int i = 0; i < current_params.Length; i++) {
1347 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1350 Report.SymbolRelatedToPreviousError (Location, "");
1351 Report.Error (265, part.Location,
1352 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1353 GetSignatureForError (), current_params [i].GetSignatureForError ());
1357 public bool ResolveTypeParameters ()
1359 if (!DoResolveTypeParameters ())
1362 if (types != null) {
1363 foreach (var type in types)
1364 if (!type.ResolveTypeParameters ())
1368 if (compiler_generated != null) {
1369 foreach (CompilerGeneratedClass c in compiler_generated)
1370 if (!c.ResolveTypeParameters ())
1377 protected virtual bool DoResolveTypeParameters ()
1379 if (CurrentTypeParameters == null)
1382 if (PartialContainer != this)
1383 throw new InternalErrorException ();
1385 var base_context = new BaseContext (this);
1386 foreach (TypeParameter type_param in CurrentTypeParameters) {
1387 if (!type_param.ResolveConstraints (base_context)) {
1393 if (partial_parts != null) {
1394 foreach (TypeContainer part in partial_parts)
1395 UpdateTypeParameterConstraints (part);
1401 protected virtual bool DefineNestedTypes ()
1403 if (Types != null) {
1404 foreach (TypeContainer tc in Types)
1405 if (tc.DefineType () == null)
1412 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1414 if (InTransit != null)
1419 if (base_type_expr != null) {
1420 var ptc = base_type.MemberDefinition as TypeContainer;
1421 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1425 if (iface_exprs != null) {
1426 foreach (TypeExpr iface in iface_exprs) {
1427 // the interface might not have been resolved, prevents a crash, see #442144
1430 var ptc = iface.Type.MemberDefinition as Interface;
1431 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1436 if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1444 /// Populates our TypeBuilder with fields and methods
1446 public sealed override bool Define ()
1448 if (members_defined)
1449 return members_defined_ok;
1451 members_defined_ok = DoDefineMembers ();
1452 members_defined = true;
1454 if (types != null) {
1455 foreach (var nested in types)
1459 return members_defined_ok;
1462 protected virtual bool DoDefineMembers ()
1464 if (iface_exprs != null) {
1465 foreach (TypeExpr iface in iface_exprs) {
1466 var iface_type = iface.Type;
1468 // Ensure the base is always setup
1469 var compiled_iface = iface_type.MemberDefinition as Interface;
1470 if (compiled_iface != null)
1471 compiled_iface.Define ();
1473 if (Kind == MemberKind.Interface)
1474 MemberCache.AddInterface (iface_type);
1476 ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1477 if (oa != null && !IsObsolete)
1478 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1480 GenericTypeExpr ct = iface as GenericTypeExpr;
1482 // TODO: passing `this' is wrong, should be base type iface instead
1483 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1485 ct.CheckConstraints (this);
1487 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1488 Report.Error (1966, iface.Location,
1489 "`{0}': cannot implement a dynamic interface `{1}'",
1490 GetSignatureForError (), iface.GetSignatureForError ());
1497 if (base_type_expr != null) {
1498 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1499 if (obsolete_attr != null && !IsObsolete)
1500 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1502 var ct = base_type_expr as GenericTypeExpr;
1504 ct.CheckConstraints (this);
1507 if (base_type != null) {
1508 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1509 if (baseContainer != null) {
1510 baseContainer.Define ();
1513 // It can trigger define of this type (for generic types only)
1515 if (HasMembersDefined)
1520 if (type_params != null) {
1521 foreach (var tp in type_params) {
1522 tp.CheckGenericConstraints ();
1526 DefineContainerMembers (constants);
1527 DefineContainerMembers (fields);
1529 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1530 pending = PendingImplementation.GetPendingImplementations (this);
1532 if (requires_delayed_unmanagedtype_check) {
1533 requires_delayed_unmanagedtype_check = false;
1534 foreach (FieldBase f in fields) {
1535 if (f.MemberType != null && f.MemberType.IsPointer)
1536 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1542 // Constructors are not in the defined_names array
1544 DefineContainerMembers (instance_constructors);
1546 DefineContainerMembers (events);
1547 DefineContainerMembers (ordered_explicit_member_list);
1548 DefineContainerMembers (ordered_member_list);
1550 if (operators != null) {
1551 DefineContainerMembers (operators);
1552 CheckPairedOperators ();
1555 ComputeIndexerName();
1556 CheckEqualsAndGetHashCode();
1561 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1564 for (int i = 0; i < mcal.Count; ++i) {
1565 MemberCore mc = (MemberCore) mcal[i];
1568 } catch (Exception e) {
1569 throw new InternalErrorException (mc, e);
1575 protected virtual void ComputeIndexerName ()
1577 if (indexers == null)
1580 string class_indexer_name = null;
1583 // If there's both an explicit and an implicit interface implementation, the
1584 // explicit one actually implements the interface while the other one is just
1585 // a normal indexer. See bug #37714.
1588 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1589 foreach (Indexer i in indexers) {
1590 if (i.InterfaceType != null) {
1591 if (seen_normal_indexers)
1592 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1596 seen_normal_indexers = true;
1598 if (class_indexer_name == null) {
1599 class_indexer_name = i.ShortName;
1603 if (i.ShortName != class_indexer_name)
1604 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");
1607 if (class_indexer_name != null)
1608 indexer_name = class_indexer_name;
1611 void EmitIndexerName ()
1613 if (!seen_normal_indexers)
1616 PredefinedAttribute pa = Compiler.PredefinedAttributes.DefaultMember;
1617 if (pa.Constructor == null &&
1618 !pa.ResolveConstructor (Location, TypeManager.string_type))
1621 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1622 TypeBuilder.SetCustomAttribute (cb);
1625 protected virtual void CheckEqualsAndGetHashCode ()
1627 if (methods == null)
1630 if (HasEquals && !HasGetHashCode) {
1631 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1635 // Indicated whether container has StructLayout attribute set Explicit
1636 public bool HasExplicitLayout {
1637 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1638 set { caching_flags |= Flags.HasExplicitLayout; }
1641 public bool HasStructLayout {
1642 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1643 set { caching_flags |= Flags.HasStructLayout; }
1646 public MemberCache MemberCache {
1648 return spec.MemberCache;
1652 void CheckMemberUsage (List<MemberCore> al, string member_type)
1657 foreach (MemberCore mc in al) {
1658 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1661 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1662 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1667 public virtual void VerifyMembers ()
1670 // Check for internal or private fields that were never assigned
1672 if (Report.WarningLevel >= 3) {
1673 if (RootContext.EnhancedWarnings) {
1674 CheckMemberUsage (properties, "property");
1675 CheckMemberUsage (methods, "method");
1676 CheckMemberUsage (constants, "constant");
1679 if (fields != null){
1680 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1681 foreach (FieldBase f in fields) {
1682 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1683 if (is_type_exposed)
1690 if ((f.caching_flags & Flags.IsAssigned) == 0)
1691 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1693 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1694 f.GetSignatureForError ());
1700 // Only report 649 on level 4
1702 if (Report.WarningLevel < 4)
1705 if ((f.caching_flags & Flags.IsAssigned) != 0)
1709 // Don't be pendatic over serializable attributes
1711 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1714 Constant c = New.Constantify (f.MemberType, f.Location);
1715 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1716 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1722 public override void Emit ()
1725 MemberSpec candidate;
1726 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1727 if (conflict_symbol == null && candidate == null) {
1728 if ((ModFlags & Modifiers.NEW) != 0)
1729 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1730 GetSignatureForError ());
1732 if ((ModFlags & Modifiers.NEW) == 0) {
1733 if (candidate == null)
1734 candidate = conflict_symbol;
1736 Report.SymbolRelatedToPreviousError (candidate);
1737 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1738 GetSignatureForError (), candidate.GetSignatureForError ());
1743 if (all_tp_builders != null) {
1744 int current_starts_index = CurrentTypeParametersStartIndex;
1745 for (int i = 0; i < all_tp_builders.Length; i++) {
1746 if (i < current_starts_index) {
1747 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1749 CurrentTypeParameters [i - current_starts_index].Emit ();
1754 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1755 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1760 // TODO: move to ClassOrStruct
1761 void EmitConstructors ()
1763 if (instance_constructors == null)
1766 if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1767 bool has_compliant_args = false;
1769 foreach (Constructor c in instance_constructors) {
1773 catch (Exception e) {
1774 throw new InternalErrorException (c, e);
1777 if (has_compliant_args)
1780 has_compliant_args = c.HasCompliantArgs;
1782 if (!has_compliant_args)
1783 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1785 foreach (Constructor c in instance_constructors) {
1789 catch (Exception e) {
1790 throw new InternalErrorException (c, e);
1797 /// Emits the code, this step is performed after all
1798 /// the types, enumerations, constructors
1800 public virtual void EmitType ()
1802 if (OptAttributes != null)
1803 OptAttributes.Emit ();
1807 EmitConstructors ();
1809 if (constants != null)
1810 foreach (Const con in constants)
1813 if (default_static_constructor != null)
1814 default_static_constructor.Emit ();
1816 if (operators != null)
1817 foreach (Operator o in operators)
1820 if (properties != null)
1821 foreach (Property p in properties)
1824 if (indexers != null) {
1825 foreach (Indexer indx in indexers)
1830 if (events != null){
1831 foreach (Event e in Events)
1835 if (methods != null) {
1836 for (int i = 0; i < methods.Count; ++i)
1837 ((MethodOrOperator) methods [i]).Emit ();
1841 foreach (FieldBase f in fields)
1844 if (types != null) {
1845 foreach (TypeContainer t in types)
1849 if (pending != null)
1850 pending.VerifyPendingMethods (Report);
1852 if (Report.Errors > 0)
1855 if (compiler_generated != null) {
1856 for (int i = 0; i < compiler_generated.Count; ++i)
1857 compiler_generated [i].EmitType ();
1861 public void CloseType ()
1863 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1866 // Close base type container first to avoid TypeLoadException
1867 if (spec.BaseType != null) {
1868 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1874 caching_flags |= Flags.CloseTypeCreated;
1875 TypeBuilder.CreateType ();
1876 } catch (TypeLoadException){
1878 // This is fine, the code still created the type
1880 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1881 // Console.WriteLine (e.Message);
1882 } catch (Exception e) {
1883 throw new InternalErrorException (this, e);
1887 foreach (TypeContainer tc in Types)
1891 if (compiler_generated != null)
1892 foreach (CompilerGeneratedClass c in compiler_generated)
1897 initialized_fields = null;
1898 initialized_static_fields = null;
1900 ordered_explicit_member_list = null;
1901 ordered_member_list = null;
1906 compiler_generated = null;
1907 default_constructor = null;
1908 default_static_constructor = null;
1910 OptAttributes = null;
1914 // Performs the validation on a Method's modifiers (properties have
1915 // the same properties).
1917 // TODO: Why is it not done at parse stage ?
1919 public bool MethodModifiersValid (MemberCore mc)
1921 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1922 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1924 var flags = mc.ModFlags;
1927 // At most one of static, virtual or override
1929 if ((flags & Modifiers.STATIC) != 0){
1930 if ((flags & vao) != 0){
1931 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1932 mc.GetSignatureForError ());
1937 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1938 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1939 mc.GetSignatureForError ());
1944 // If the declaration includes the abstract modifier, then the
1945 // declaration does not include static, virtual or extern
1947 if ((flags & Modifiers.ABSTRACT) != 0){
1948 if ((flags & Modifiers.EXTERN) != 0){
1950 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1954 if ((flags & Modifiers.SEALED) != 0) {
1955 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1959 if ((flags & Modifiers.VIRTUAL) != 0){
1960 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1964 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1965 Report.SymbolRelatedToPreviousError (this);
1966 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1967 mc.GetSignatureForError (), GetSignatureForError ());
1972 if ((flags & Modifiers.PRIVATE) != 0){
1973 if ((flags & vao) != 0){
1974 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1979 if ((flags & Modifiers.SEALED) != 0){
1980 if ((flags & Modifiers.OVERRIDE) == 0){
1981 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1989 public Constructor DefaultStaticConstructor {
1990 get { return default_static_constructor; }
1993 protected override bool VerifyClsCompliance ()
1995 if (!base.VerifyClsCompliance ())
1998 // Check this name against other containers
1999 NamespaceEntry.NS.VerifyClsCompliance ();
2001 // Check all container names for user classes
2002 if (Kind != MemberKind.Delegate)
2003 MemberCache.VerifyClsCompliance (Definition, Report);
2005 if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2006 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2007 GetSignatureForError (), BaseType.GetSignatureForError ());
2013 /// Performs checks for an explicit interface implementation. First it
2014 /// checks whether the `interface_type' is a base inteface implementation.
2015 /// Then it checks whether `name' exists in the interface type.
2017 public bool VerifyImplements (InterfaceMemberBase mb)
2019 var ifaces = spec.Interfaces;
2020 if (ifaces != null) {
2021 foreach (TypeSpec t in ifaces){
2022 if (t == mb.InterfaceType)
2027 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2028 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2029 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2034 // Used for visiblity checks to tests whether this definition shares
2035 // base type baseType, it does member-definition search
2037 public bool IsBaseTypeDefinition (TypeSpec baseType)
2039 // RootContext check
2040 if (TypeBuilder == null)
2045 if (type.MemberDefinition == baseType.MemberDefinition)
2048 type = type.BaseType;
2049 } while (type != null);
2054 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2056 throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2059 public void Mark_HasEquals ()
2061 cached_method |= CachedMethods.Equals;
2064 public void Mark_HasGetHashCode ()
2066 cached_method |= CachedMethods.GetHashCode;
2070 /// Method container contains Equals method
2072 public bool HasEquals {
2074 return (cached_method & CachedMethods.Equals) != 0;
2079 /// Method container contains GetHashCode method
2081 public bool HasGetHashCode {
2083 return (cached_method & CachedMethods.GetHashCode) != 0;
2087 public bool HasStaticFieldInitializer {
2089 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2093 cached_method |= CachedMethods.HasStaticFieldInitializer;
2095 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2100 // Generates xml doc comments (if any), and if required,
2101 // handle warning report.
2103 internal override void GenerateDocComment (DeclSpace ds)
2105 DocUtil.GenerateTypeDocComment (this, ds, Report);
2108 public override string DocCommentHeader {
2109 get { return "T:"; }
2113 public abstract class ClassOrStruct : TypeContainer
2115 Dictionary<SecurityAction, PermissionSet> declarative_security;
2117 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2118 MemberName name, Attributes attrs, MemberKind kind)
2119 : base (ns, parent, name, attrs, kind)
2123 protected override bool AddToContainer (MemberCore symbol, string name)
2125 if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2126 if (symbol is TypeParameter) {
2127 Report.Error (694, symbol.Location,
2128 "Type parameter `{0}' has same name as containing type, or method",
2129 symbol.GetSignatureForError ());
2133 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2134 if (imb == null || !imb.IsExplicitImpl) {
2135 Report.SymbolRelatedToPreviousError (this);
2136 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2137 symbol.GetSignatureForError ());
2142 return base.AddToContainer (symbol, name);
2145 public override void VerifyMembers ()
2147 base.VerifyMembers ();
2149 if ((events != null) && Report.WarningLevel >= 3) {
2150 foreach (Event e in events){
2151 // Note: The event can be assigned from same class only, so we can report
2152 // this warning for all accessibility modes
2153 if ((e.caching_flags & Flags.IsUsed) == 0)
2154 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2159 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2161 if (a.IsValidSecurityAttribute ()) {
2162 if (declarative_security == null)
2163 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2165 a.ExtractSecurityPermissionSet (declarative_security);
2169 if (a.Type == pa.StructLayout) {
2170 PartialContainer.HasStructLayout = true;
2172 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2173 PartialContainer.HasExplicitLayout = true;
2176 if (a.Type == pa.Dynamic) {
2177 a.Error_MisusedDynamicAttribute ();
2181 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2185 /// Defines the default constructors
2187 protected void DefineDefaultConstructor (bool is_static)
2189 // The default instance constructor is public
2190 // If the class is abstract, the default constructor is protected
2191 // The default static constructor is private
2195 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2197 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2200 Constructor c = new Constructor (this, MemberName.Name, mods,
2201 null, ParametersCompiled.EmptyReadOnlyParameters,
2202 new GeneratedBaseInitializer (Location),
2206 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2209 protected override bool DoDefineMembers ()
2211 CheckProtectedModifier ();
2213 base.DoDefineMembers ();
2215 if (default_static_constructor != null)
2216 default_static_constructor.Define ();
2221 public override void Emit ()
2223 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2224 DefineDefaultConstructor (true);
2225 default_static_constructor.Define ();
2230 if (declarative_security != null) {
2231 foreach (var de in declarative_security) {
2232 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2237 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2239 DeclSpace top_level = Parent;
2240 if (top_level != null) {
2241 while (top_level.Parent != null)
2242 top_level = top_level.Parent;
2244 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2245 if (candidates != null) {
2246 scope = NamespaceEntry;
2251 return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2254 protected override TypeAttributes TypeAttr {
2256 if (default_static_constructor == null)
2257 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2259 return base.TypeAttr;
2265 // TODO: should be sealed
2266 public class Class : ClassOrStruct {
2267 const Modifiers AllowedModifiers =
2270 Modifiers.PROTECTED |
2271 Modifiers.INTERNAL |
2273 Modifiers.ABSTRACT |
2278 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2280 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2282 : base (ns, parent, name, attrs, MemberKind.Class)
2284 var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2285 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2286 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2288 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2289 Report.FeatureIsNotAvailable (Location, "static classes");
2293 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2295 if (part.Name == "System.Object")
2296 Report.Error (537, part.Location,
2297 "The class System.Object cannot have a base class or implement an interface.");
2298 base.AddBasesForPart (part, bases);
2301 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2303 if (a.Type == pa.AttributeUsage) {
2304 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2305 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2309 if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2310 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2314 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2315 a.Error_MissingGuidAttribute ();
2319 if (a.Type == pa.Extension) {
2320 a.Error_MisusedExtensionAttribute ();
2324 if (a.Type.IsConditionallyExcluded (Location))
2327 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2330 public override AttributeTargets AttributeTargets {
2332 return AttributeTargets.Class;
2336 protected override void DefineContainerMembers (System.Collections.IList list)
2342 base.DefineContainerMembers (list);
2346 foreach (MemberCore m in list) {
2347 if (m is Operator) {
2348 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2352 if (m is Destructor) {
2353 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2358 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2362 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2365 if (m is Constructor) {
2366 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2370 Method method = m as Method;
2371 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2372 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2376 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2379 base.DefineContainerMembers (list);
2382 protected override bool DoDefineMembers ()
2384 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2385 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2388 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2389 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2392 if (InstanceConstructors == null && !IsStatic)
2393 DefineDefaultConstructor (false);
2395 return base.DoDefineMembers ();
2398 public override void Emit ()
2402 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2403 Compiler.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2405 var trans_flags = TypeManager.HasDynamicTypeUsed (base_type);
2406 if (trans_flags != null) {
2407 var pa = Compiler.PredefinedAttributes.DynamicTransform;
2408 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
2409 TypeBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
2414 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2416 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2418 if (base_class == null) {
2419 if (spec != TypeManager.object_type)
2420 base_type = TypeManager.object_type;
2422 if (base_type.IsGenericParameter){
2423 Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2424 GetSignatureForError (), base_type.GetSignatureForError ());
2425 } else if (IsGeneric && base_type.IsAttribute) {
2426 Report.Error (698, base_class.Location,
2427 "A generic type cannot derive from `{0}' because it is an attribute class",
2428 base_class.GetSignatureForError ());
2429 } else if (base_type.IsStatic) {
2430 Report.SymbolRelatedToPreviousError (base_class.Type);
2431 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2432 GetSignatureForError (), base_type.GetSignatureForError ());
2433 } else if (base_type.IsSealed) {
2434 Report.SymbolRelatedToPreviousError (base_class.Type);
2435 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2436 GetSignatureForError (), base_type.GetSignatureForError ());
2437 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2438 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2439 GetSignatureForError (), base_class.GetSignatureForError ());
2442 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2443 (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2444 base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2445 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2446 GetSignatureForError (), base_type.GetSignatureForError ());
2448 base_type = TypeManager.object_type;
2451 if (!IsAccessibleAs (base_type)) {
2452 Report.SymbolRelatedToPreviousError (base_type);
2453 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2454 base_type.GetSignatureForError (), GetSignatureForError ());
2458 if (PartialContainer.IsStatic && ifaces != null) {
2459 foreach (TypeExpr t in ifaces)
2460 Report.SymbolRelatedToPreviousError (t.Type);
2461 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2467 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2468 /// Valid only for attribute classes.
2469 public override string[] ConditionalConditions ()
2471 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2474 caching_flags &= ~Flags.Excluded_Undetected;
2476 if (OptAttributes == null)
2479 Attribute[] attrs = OptAttributes.SearchMulti (Compiler.PredefinedAttributes.Conditional);
2483 string[] conditions = new string[attrs.Length];
2484 for (int i = 0; i < conditions.Length; ++i)
2485 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2487 caching_flags |= Flags.Excluded;
2492 // FIXME: How do we deal with the user specifying a different
2495 protected override TypeAttributes TypeAttr {
2497 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2499 ta |= StaticClassAttribute;
2505 public sealed class Struct : ClassOrStruct {
2507 bool is_unmanaged, has_unmanaged_check_done;
2511 // Modifiers allowed in a struct declaration
2513 const Modifiers AllowedModifiers =
2516 Modifiers.PROTECTED |
2517 Modifiers.INTERNAL |
2521 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2522 Modifiers mod, Attributes attrs)
2523 : base (ns, parent, name, attrs, MemberKind.Struct)
2525 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2526 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2527 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2530 public override AttributeTargets AttributeTargets {
2532 return AttributeTargets.Struct;
2536 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2538 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2541 // When struct constains fixed fixed and struct layout has explicitly
2542 // set CharSet, its value has to be propagated to compiler generated
2543 // fixed field types
2545 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2546 for (int i = 0; i < Fields.Count; ++i) {
2547 FixedField ff = Fields [i] as FixedField;
2549 ff.SetCharSet (TypeBuilder.Attributes);
2554 bool CheckStructCycles (Struct s)
2556 if (s.Fields == null)
2563 foreach (FieldBase field in s.Fields) {
2564 TypeSpec ftype = field.Spec.MemberType;
2565 if (!ftype.IsStruct)
2568 if (ftype is PredefinedTypeSpec)
2571 foreach (var targ in ftype.TypeArguments) {
2572 if (!CheckFieldTypeCycle (targ)) {
2573 Report.Error (523, field.Location,
2574 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2575 field.GetSignatureForError (), ftype.GetSignatureForError ());
2580 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2583 if (!CheckFieldTypeCycle (ftype)) {
2584 Report.Error (523, field.Location,
2585 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2586 field.GetSignatureForError (), ftype.GetSignatureForError ());
2591 s.InTransit = false;
2595 bool CheckFieldTypeCycle (TypeSpec ts)
2597 var fts = ts.MemberDefinition as Struct;
2601 return CheckStructCycles (fts);
2604 public override void Emit ()
2606 CheckStructCycles (this);
2611 public override bool IsUnmanagedType ()
2616 if (has_unmanaged_check_done)
2617 return is_unmanaged;
2619 if (requires_delayed_unmanagedtype_check)
2622 requires_delayed_unmanagedtype_check = true;
2624 foreach (FieldBase f in fields) {
2628 // It can happen when recursive unmanaged types are defined
2629 // struct S { S* s; }
2630 TypeSpec mt = f.MemberType;
2635 while (mt.IsPointer)
2636 mt = TypeManager.GetElementType (mt);
2638 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2639 has_unmanaged_check_done = true;
2643 if (TypeManager.IsUnmanagedType (mt))
2646 has_unmanaged_check_done = true;
2650 has_unmanaged_check_done = true;
2651 is_unmanaged = true;
2655 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2657 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2658 base_type = TypeManager.value_type;
2662 protected override TypeAttributes TypeAttr {
2664 const TypeAttributes DefaultTypeAttributes =
2665 TypeAttributes.SequentialLayout |
2666 TypeAttributes.Sealed;
2668 return base.TypeAttr | DefaultTypeAttributes;
2672 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2674 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2675 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2676 field.GetSignatureForError ());
2679 base.RegisterFieldForInitialization (field, expression);
2687 public sealed class Interface : TypeContainer {
2690 /// Modifiers allowed in a class declaration
2692 public const Modifiers AllowedModifiers =
2695 Modifiers.PROTECTED |
2696 Modifiers.INTERNAL |
2700 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2702 : base (ns, parent, name, attrs, MemberKind.Interface)
2704 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2706 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2707 spec = new TypeSpec (Kind, null, this, null, ModFlags);
2710 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2712 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2713 a.Error_MissingGuidAttribute ();
2717 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2721 public override AttributeTargets AttributeTargets {
2723 return AttributeTargets.Interface;
2727 protected override TypeAttributes TypeAttr {
2729 const TypeAttributes DefaultTypeAttributes =
2730 TypeAttributes.AutoLayout |
2731 TypeAttributes.Abstract |
2732 TypeAttributes.Interface;
2734 return base.TypeAttr | DefaultTypeAttributes;
2738 protected override bool VerifyClsCompliance ()
2740 if (!base.VerifyClsCompliance ())
2743 if (iface_exprs != null) {
2744 foreach (var iface in iface_exprs) {
2745 if (iface.Type.IsCLSCompliant ())
2748 Report.SymbolRelatedToPreviousError (iface.Type);
2749 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2750 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2758 public abstract class InterfaceMemberBase : MemberBase
2761 // Common modifiers allowed in a class declaration
2763 protected const Modifiers AllowedModifiersClass =
2766 Modifiers.PROTECTED |
2767 Modifiers.INTERNAL |
2772 Modifiers.OVERRIDE |
2773 Modifiers.ABSTRACT |
2778 // Common modifiers allowed in a struct declaration
2780 protected const Modifiers AllowedModifiersStruct =
2783 Modifiers.PROTECTED |
2784 Modifiers.INTERNAL |
2787 Modifiers.OVERRIDE |
2792 // Common modifiers allowed in a interface declaration
2794 protected const Modifiers AllowedModifiersInterface =
2799 // Whether this is an interface member.
2801 public bool IsInterface;
2804 // If true, this is an explicit interface implementation
2806 public bool IsExplicitImpl;
2808 protected bool is_external_implementation;
2811 // The interface type we are explicitly implementing
2813 public TypeSpec InterfaceType;
2816 // The method we're overriding if this is an override method.
2818 protected MethodSpec base_method;
2820 readonly Modifiers explicit_mod_flags;
2821 public MethodAttributes flags;
2823 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2824 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2825 MemberName name, Attributes attrs)
2826 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2829 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2830 IsExplicitImpl = (MemberName.Left != null);
2831 explicit_mod_flags = mod;
2834 protected override bool CheckBase ()
2836 if (!base.CheckBase ())
2839 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2840 CheckForDuplications ();
2845 // For System.Object only
2846 if (Parent.BaseType == null)
2849 MemberSpec candidate;
2850 var base_member = FindBaseMember (out candidate);
2852 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2853 if (base_member == null) {
2854 if (candidate == null) {
2855 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2856 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2857 "object.Finalize()");
2859 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2860 GetSignatureForError (), SimpleName.GetMemberType (this));
2863 Report.SymbolRelatedToPreviousError (candidate);
2865 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2866 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2867 else if (this is PropertyBase)
2868 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2869 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2871 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2872 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2878 if (!CheckOverrideAgainstBase (base_member))
2881 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2883 if (OptAttributes == null || !OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2884 Report.SymbolRelatedToPreviousError (base_member);
2885 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2886 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2889 if (OptAttributes != null && OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2890 Report.SymbolRelatedToPreviousError (base_member);
2891 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2892 GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2896 base_method = base_member as MethodSpec;
2900 if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2901 base_member = candidate;
2903 if (base_member == null) {
2904 if ((ModFlags & Modifiers.NEW) != 0) {
2905 if (base_member == null) {
2906 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2907 GetSignatureForError ());
2911 if ((ModFlags & Modifiers.NEW) == 0) {
2912 ModFlags |= Modifiers.NEW;
2913 Report.SymbolRelatedToPreviousError (base_member);
2914 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2915 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",
2916 GetSignatureForError (), base_member.GetSignatureForError ());
2918 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2919 GetSignatureForError (), base_member.GetSignatureForError ());
2923 if (!IsInterface && base_member.IsAbstract && candidate == null) {
2924 Report.SymbolRelatedToPreviousError (base_member);
2925 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2926 GetSignatureForError (), base_member.GetSignatureForError ());
2933 protected virtual bool CheckForDuplications ()
2935 return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2939 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2940 // that have been defined.
2942 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2946 if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
2947 Report.SymbolRelatedToPreviousError (base_member);
2948 Report.Error (506, Location,
2949 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2950 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2954 // Now we check that the overriden method is not final
2955 if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2956 Report.SymbolRelatedToPreviousError (base_member);
2957 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2958 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2962 var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2963 if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2964 Report.SymbolRelatedToPreviousError (base_member);
2965 if (this is PropertyBasedMember) {
2966 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2967 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2969 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2970 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2978 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2980 var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2981 var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2983 if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2985 // when overriding protected internal, the method can be declared
2986 // protected internal only within the same assembly or assembly
2987 // which has InternalsVisibleTo
2989 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2990 return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2992 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2994 // if it's not "protected internal", it must be "protected"
2999 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
3001 // protected within the same assembly - an error
3005 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
3006 (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
3008 // protected ok, but other attributes differ - report an error
3015 return thisp == base_classp;
3018 public override bool Define ()
3021 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3022 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3024 flags = MethodAttributes.Public |
3025 MethodAttributes.Abstract |
3026 MethodAttributes.HideBySig |
3027 MethodAttributes.NewSlot |
3028 MethodAttributes.Virtual;
3030 Parent.PartialContainer.MethodModifiersValid (this);
3032 flags = ModifiersExtensions.MethodAttr (ModFlags);
3035 if (IsExplicitImpl) {
3036 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3037 if (iface_texpr == null)
3040 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3041 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3042 GetSignatureForError ());
3045 InterfaceType = iface_texpr.Type;
3047 if (!InterfaceType.IsInterface) {
3048 Report.SymbolRelatedToPreviousError (InterfaceType);
3049 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3050 TypeManager.CSharpName (InterfaceType));
3052 Parent.PartialContainer.VerifyImplements (this);
3055 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3058 return base.Define ();
3061 protected bool DefineParameters (ParametersCompiled parameters)
3063 if (!parameters.Resolve (this))
3067 for (int i = 0; i < parameters.Count; ++i) {
3068 Parameter p = parameters [i];
3070 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3071 p.Warning_UselessOptionalParameter (Report);
3073 if (p.CheckAccessibility (this))
3076 TypeSpec t = parameters.Types [i];
3077 Report.SymbolRelatedToPreviousError (t);
3078 if (this is Indexer)
3079 Report.Error (55, Location,
3080 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3081 TypeManager.CSharpName (t), GetSignatureForError ());
3082 else if (this is Operator)
3083 Report.Error (57, Location,
3084 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3085 TypeManager.CSharpName (t), GetSignatureForError ());
3087 Report.Error (51, Location,
3088 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3089 TypeManager.CSharpName (t), GetSignatureForError ());
3095 public override void Emit()
3097 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3098 // We are more strict than csc and report this as an error because SRE does not allow emit that
3099 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3100 if (this is Constructor) {
3101 Report.Error (824, Location,
3102 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3104 Report.Error (626, Location,
3105 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3106 GetSignatureForError ());
3113 public override bool EnableOverloadChecks (MemberCore overload)
3116 // Two members can differ in their explicit interface
3117 // type parameter only
3119 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3120 if (imb != null && imb.IsExplicitImpl) {
3121 if (IsExplicitImpl) {
3122 caching_flags |= Flags.MethodOverloadsExist;
3127 return IsExplicitImpl;
3130 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3132 Report.SymbolRelatedToPreviousError (base_member);
3133 Report.Error (507, member.Location,
3134 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3135 member.GetSignatureForError (),
3136 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3137 base_member.GetSignatureForError ());
3140 protected void Error_StaticReturnType ()
3142 Report.Error (722, Location,
3143 "`{0}': static types cannot be used as return types",
3144 MemberType.GetSignatureForError ());
3148 /// Gets base method and its return type
3150 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3152 return MemberCache.FindBaseMember (this, out bestCandidate);
3156 // The "short" name of this property / indexer / event. This is the
3157 // name without the explicit interface.
3159 public string ShortName {
3160 get { return MemberName.Name; }
3161 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3165 // Returns full metadata method name
3167 public string GetFullName (MemberName name)
3169 return GetFullName (name.Name);
3172 public string GetFullName (string name)
3174 if (!IsExplicitImpl)
3178 // When dealing with explicit members a full interface type
3179 // name is added to member name to avoid possible name conflicts
3181 // We use CSharpName which gets us full name with benefit of
3182 // replacing predefined names which saves some space and name
3185 return TypeManager.CSharpName (InterfaceType) + "." + name;
3188 protected override bool VerifyClsCompliance ()
3190 if (!base.VerifyClsCompliance ()) {
3194 if (GenericMethod != null)
3195 GenericMethod.VerifyClsCompliance ();
3200 public override bool IsUsed
3202 get { return IsExplicitImpl || base.IsUsed; }
3207 public abstract class MemberBase : MemberCore
3209 protected FullNamedExpression type_expr;
3210 protected TypeSpec member_type;
3212 public readonly DeclSpace ds;
3213 public readonly GenericMethod GenericMethod;
3215 protected MemberBase (DeclSpace parent, GenericMethod generic,
3216 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3217 MemberName name, Attributes attrs)
3218 : base (parent, name, attrs)
3220 this.ds = generic != null ? generic : (DeclSpace) parent;
3221 this.type_expr = type;
3222 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3223 GenericMethod = generic;
3224 if (GenericMethod != null)
3225 GenericMethod.ModFlags = ModFlags;
3230 public TypeSpec MemberType {
3236 public FullNamedExpression TypeExpression {
3245 // Main member define entry
3247 public override bool Define ()
3249 DoMemberTypeIndependentChecks ();
3252 // Returns false only when type resolution failed
3254 if (!ResolveMemberType ())
3257 DoMemberTypeDependentChecks ();
3262 // Any type_name independent checks
3264 protected virtual void DoMemberTypeIndependentChecks ()
3266 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3267 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3268 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3269 GetSignatureForError (), Parent.GetSignatureForError ());
3274 // Any type_name dependent checks
3276 protected virtual void DoMemberTypeDependentChecks ()
3278 // verify accessibility
3279 if (!IsAccessibleAs (MemberType)) {
3280 Report.SymbolRelatedToPreviousError (MemberType);
3281 if (this is Property)
3282 Report.Error (53, Location,
3283 "Inconsistent accessibility: property type `" +
3284 TypeManager.CSharpName (MemberType) + "' is less " +
3285 "accessible than property `" + GetSignatureForError () + "'");
3286 else if (this is Indexer)
3287 Report.Error (54, Location,
3288 "Inconsistent accessibility: indexer return type `" +
3289 TypeManager.CSharpName (MemberType) + "' is less " +
3290 "accessible than indexer `" + GetSignatureForError () + "'");
3291 else if (this is MethodCore) {
3292 if (this is Operator)
3293 Report.Error (56, Location,
3294 "Inconsistent accessibility: return type `" +
3295 TypeManager.CSharpName (MemberType) + "' is less " +
3296 "accessible than operator `" + GetSignatureForError () + "'");
3298 Report.Error (50, Location,
3299 "Inconsistent accessibility: return type `" +
3300 TypeManager.CSharpName (MemberType) + "' is less " +
3301 "accessible than method `" + GetSignatureForError () + "'");
3303 Report.Error (52, Location,
3304 "Inconsistent accessibility: field type `" +
3305 TypeManager.CSharpName (MemberType) + "' is less " +
3306 "accessible than field `" + GetSignatureForError () + "'");
3310 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3311 TypeManager.CheckTypeVariance (MemberType, variance, this);
3314 protected bool IsTypePermitted ()
3316 if (TypeManager.IsSpecialType (MemberType)) {
3317 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3323 protected virtual bool CheckBase ()
3325 CheckProtectedModifier ();
3330 protected virtual bool ResolveMemberType ()
3332 if (member_type != null)
3333 throw new InternalErrorException ("Multi-resolve");
3335 TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3340 // Replace original type name, error reporting can use fully resolved name
3344 member_type = te.Type;