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;
25 using XmlElement = System.Object;
30 using Mono.CompilerServices.SymbolWriter;
32 namespace Mono.CSharp {
35 /// This is the base class for structs and classes.
37 public abstract class TypeContainer : DeclSpace, IMemberContainer
40 // Different context is needed when resolving type container base
41 // types. Type names come from the parent scope but type parameter
42 // names from the container scope.
44 struct BaseContext : IMemberContext
48 public BaseContext (TypeContainer tc)
53 #region IMemberContext Members
55 public CompilerContext Compiler {
56 get { return tc.Compiler; }
59 public Type CurrentType {
60 get { return tc.Parent.CurrentType; }
63 public TypeParameter[] CurrentTypeParameters {
64 get { return tc.PartialContainer.CurrentTypeParameters; }
67 public TypeContainer CurrentTypeDefinition {
68 get { return tc.Parent.CurrentTypeDefinition; }
71 public bool IsObsolete {
72 get { return tc.IsObsolete; }
75 public bool IsUnsafe {
76 get { return tc.IsUnsafe; }
79 public bool IsStatic {
80 get { return tc.IsStatic; }
83 public string GetSignatureForError ()
85 throw new NotImplementedException ();
88 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
93 public FullNamedExpression LookupNamespaceAlias (string name)
95 return tc.Parent.LookupNamespaceAlias (name);
98 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
100 TypeParameter[] tp = CurrentTypeParameters;
102 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
104 return new TypeParameterExpr (t, loc);
107 return tc.Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
117 GetHashCode = 1 << 1,
118 HasStaticFieldInitializer = 1 << 2
122 // Whether this is a struct, class or interface
123 public readonly MemberKind Kind;
125 // Holds a list of classes and structures
126 protected List<TypeContainer> types;
128 List<MemberCore> ordered_explicit_member_list;
129 List<MemberCore> ordered_member_list;
131 // Holds the list of properties
132 List<MemberCore> properties;
134 // Holds the list of delegates
135 List<TypeContainer> delegates;
137 // Holds the list of constructors
138 protected List<MemberCore> instance_constructors;
140 // Holds the list of fields
141 protected List<MemberCore> fields;
143 // Holds a list of fields that have initializers
144 protected List<FieldInitializer> initialized_fields;
146 // Holds a list of static fields that have initializers
147 protected List<FieldInitializer> initialized_static_fields;
149 // Holds the list of constants
150 protected List<MemberCore> constants;
152 // Holds the methods.
153 List<MemberCore> methods;
156 protected List<MemberCore> events;
158 // Holds the indexers
159 List<MemberCore> indexers;
161 // Holds the operators
162 List<MemberCore> operators;
164 // Holds the compiler generated classes
165 List<CompilerGeneratedClass> compiler_generated;
168 // Pointers to the default constructor and the default static constructor
170 protected Constructor default_constructor;
171 protected Constructor default_static_constructor;
174 // Points to the first non-static field added to the container.
176 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
177 // and the first one's as good as any.
179 FieldBase first_nonstatic_field = null;
182 // This one is computed after we can distinguish interfaces
183 // from classes from the arraylist `type_bases'
186 TypeExpr[] iface_exprs;
188 GenericTypeParameterBuilder[] nested_gen_params;
190 protected List<FullNamedExpression> type_bases;
192 protected bool members_defined;
193 bool members_defined_ok;
195 // The interfaces we implement.
196 protected Type[] ifaces;
198 // The base member cache and our member cache
199 MemberCache base_cache;
200 protected MemberCache member_cache;
202 public const string DefaultIndexerName = "Item";
204 private bool seen_normal_indexers = false;
205 private string indexer_name = DefaultIndexerName;
206 protected bool requires_delayed_unmanagedtype_check;
208 private CachedMethods cached_method;
210 List<TypeContainer> partial_parts;
213 /// The pending methods that need to be implemented
214 // (interfaces or abstract methods)
216 PendingImplementation pending;
218 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
219 Attributes attrs, MemberKind kind)
220 : base (ns, parent, name, attrs)
222 if (parent != null && parent.NamespaceEntry != ns)
223 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
226 this.PartialContainer = this;
229 public bool AddMember (MemberCore symbol)
231 return AddToContainer (symbol, symbol.MemberName.Basename);
234 protected virtual bool AddMemberType (DeclSpace ds)
236 return AddToContainer (ds, ds.Basename);
239 protected virtual void RemoveMemberType (DeclSpace ds)
241 RemoveFromContainer (ds.Basename);
244 public void AddConstant (Const constant)
246 if (!AddMember (constant))
249 if (constants == null)
250 constants = new List<MemberCore> ();
252 constants.Add (constant);
255 public TypeContainer AddTypeContainer (TypeContainer tc)
257 if (!AddMemberType (tc))
261 types = new List<TypeContainer> ();
267 public virtual TypeContainer AddPartial (TypeContainer next_part)
269 return AddPartial (next_part, next_part.Basename);
272 protected TypeContainer AddPartial (TypeContainer next_part, string name)
274 next_part.ModFlags |= Modifiers.PARTIAL;
275 TypeContainer tc = GetDefinition (name) as TypeContainer;
277 return AddTypeContainer (next_part);
279 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
280 Report.SymbolRelatedToPreviousError (next_part);
281 Error_MissingPartialModifier (tc);
284 if (tc.Kind != next_part.Kind) {
285 Report.SymbolRelatedToPreviousError (tc);
286 Report.Error (261, next_part.Location,
287 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
288 next_part.GetSignatureForError ());
291 if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
292 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
293 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
294 Report.SymbolRelatedToPreviousError (tc);
295 Report.Error (262, next_part.Location,
296 "Partial declarations of `{0}' have conflicting accessibility modifiers",
297 next_part.GetSignatureForError ());
300 if (tc.partial_parts == null)
301 tc.partial_parts = new List<TypeContainer> (1);
303 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
304 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
305 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
306 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
307 tc.ModFlags |= next_part.ModFlags;
309 tc.ModFlags |= next_part.ModFlags;
312 if (next_part.attributes != null) {
313 if (tc.attributes == null)
314 tc.attributes = next_part.attributes;
316 tc.attributes.AddAttributes (next_part.attributes.Attrs);
319 next_part.PartialContainer = tc;
320 tc.partial_parts.Add (next_part);
324 public virtual void RemoveTypeContainer (TypeContainer next_part)
327 types.Remove (next_part);
328 RemoveMemberType (next_part);
331 public void AddDelegate (Delegate d)
333 if (!AddMemberType (d))
336 if (delegates == null)
337 delegates = new List<TypeContainer> ();
342 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
344 if (ordered_explicit_member_list == null) {
345 ordered_explicit_member_list = new List<MemberCore> ();
346 ordered_member_list = new List<MemberCore> ();
350 if (Kind == MemberKind.Interface) {
351 Report.Error (541, mc.Location,
352 "`{0}': explicit interface declaration can only be declared in a class or struct",
353 mc.GetSignatureForError ());
356 ordered_explicit_member_list.Add (mc);
357 alist.Insert (0, mc);
359 ordered_member_list.Add (mc);
365 public void AddMethod (MethodOrOperator method)
367 if (!AddToContainer (method, method.MemberName.Basename))
371 methods = new List<MemberCore> ();
373 if (method.MemberName.Left != null)
374 AddMemberToList (method, methods, true);
376 AddMemberToList (method, methods, false);
379 public void AddConstructor (Constructor c)
381 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
382 if (!AddToContainer (c, is_static ?
383 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
386 if (is_static && c.Parameters.IsEmpty){
387 if (default_static_constructor != null) {
388 Report.SymbolRelatedToPreviousError (default_static_constructor);
389 Report.Error (111, c.Location,
390 "A member `{0}' is already defined. Rename this member or use different parameter types",
391 c.GetSignatureForError ());
395 default_static_constructor = c;
397 if (c.Parameters.IsEmpty)
398 default_constructor = c;
400 if (instance_constructors == null)
401 instance_constructors = new List<MemberCore> ();
403 instance_constructors.Add (c);
407 public bool AddField (FieldBase field)
409 if (!AddMember (field))
413 fields = new List<MemberCore> ();
417 if ((field.ModFlags & Modifiers.STATIC) != 0)
420 if (first_nonstatic_field == null) {
421 first_nonstatic_field = field;
425 if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
426 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
427 Report.Warning (282, 3, field.Location,
428 "struct instance field `{0}' found in different declaration from instance field `{1}'",
429 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
434 public void AddProperty (Property prop)
436 if (!AddMember (prop) ||
437 !AddMember (prop.Get) || !AddMember (prop.Set))
440 if (properties == null)
441 properties = new List<MemberCore> ();
443 if (prop.MemberName.Left != null)
444 AddMemberToList (prop, properties, true);
446 AddMemberToList (prop, properties, false);
449 public void AddEvent (Event e)
454 if (e is EventProperty) {
455 if (!AddMember (e.Add))
458 if (!AddMember (e.Remove))
463 events = new List<MemberCore> ();
469 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
471 public void AddIndexer (Indexer i)
473 if (indexers == null)
474 indexers = new List<MemberCore> ();
476 if (i.IsExplicitImpl)
477 AddMemberToList (i, indexers, true);
479 AddMemberToList (i, indexers, false);
482 public void AddOperator (Operator op)
487 if (operators == null)
488 operators = new List<MemberCore> ();
493 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
495 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
497 if (compiler_generated == null)
498 compiler_generated = new List<CompilerGeneratedClass> ();
500 compiler_generated.Add (c);
503 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
505 if (a.Type == pa.DefaultMember) {
506 if (Indexers != null) {
507 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
512 base.ApplyAttributeBuilder (a, cb, pa);
515 public override AttributeTargets AttributeTargets {
517 throw new NotSupportedException ();
521 public IList<TypeContainer> Types {
527 public IList<MemberCore> Methods {
533 public IList<MemberCore> Constants {
539 protected virtual Type BaseType {
541 return TypeBuilder.BaseType;
545 public IList<MemberCore> Fields {
551 public IList<MemberCore> InstanceConstructors {
553 return instance_constructors;
557 public IList<MemberCore> Properties {
563 public IList<MemberCore> Events {
569 public IList<MemberCore> Indexers {
575 public IList<MemberCore> Operators {
581 public IList<TypeContainer> Delegates {
587 protected override TypeAttributes TypeAttr {
589 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
593 public string IndexerName {
595 return indexers == null ? DefaultIndexerName : indexer_name;
599 public bool IsComImport {
601 if (OptAttributes == null)
604 return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
608 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
610 if ((field.ModFlags & Modifiers.STATIC) != 0){
611 if (initialized_static_fields == null) {
612 PartialContainer.HasStaticFieldInitializer = true;
613 initialized_static_fields = new List<FieldInitializer> (4);
616 initialized_static_fields.Add (expression);
618 if (initialized_fields == null)
619 initialized_fields = new List<FieldInitializer> (4);
621 initialized_fields.Add (expression);
625 public void ResolveFieldInitializers (BlockContext ec)
627 if (partial_parts != null) {
628 foreach (TypeContainer part in partial_parts) {
629 part.DoResolveFieldInitializers (ec);
632 DoResolveFieldInitializers (ec);
635 void DoResolveFieldInitializers (BlockContext ec)
638 if (initialized_static_fields == null)
641 bool has_complex_initializer = !RootContext.Optimize;
643 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
644 for (i = 0; i < initialized_static_fields.Count; ++i) {
645 FieldInitializer fi = initialized_static_fields [i];
646 ExpressionStatement s = fi.ResolveStatement (ec);
648 s = EmptyExpressionStatement.Instance;
649 } else if (fi.IsComplexInitializer) {
650 has_complex_initializer |= true;
656 for (i = 0; i < initialized_static_fields.Count; ++i) {
657 FieldInitializer fi = initialized_static_fields [i];
659 // Need special check to not optimize code like this
660 // static int a = b = 5;
663 if (!has_complex_initializer && fi.IsDefaultInitializer)
666 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
672 if (initialized_fields == null)
675 for (int i = 0; i < initialized_fields.Count; ++i) {
676 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
677 ExpressionStatement s = fi.ResolveStatement (ec);
682 // Field is re-initialized to its default value => removed
684 if (fi.IsDefaultInitializer && RootContext.Optimize)
687 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
691 public override string DocComment {
703 public PendingImplementation PendingImplementations {
704 get { return pending; }
707 public override bool GetClsCompliantAttributeValue ()
709 if (PartialContainer != this)
710 return PartialContainer.GetClsCompliantAttributeValue ();
712 return base.GetClsCompliantAttributeValue ();
715 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
717 // FIXME: get rid of partial_parts and store lists of bases of each part here
718 // assumed, not verified: 'part' is in 'partial_parts'
719 ((TypeContainer) part).type_bases = bases;
723 /// This function computes the Base class and also the
724 /// list of interfaces that the class or struct @c implements.
726 /// The return value is an array (might be null) of
727 /// interfaces implemented (as Types).
729 /// The @base_class argument is set to the base object or null
730 /// if this is `System.Object'.
732 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
735 if (type_bases == null)
738 int count = type_bases.Count;
739 TypeExpr [] ifaces = null;
740 IMemberContext base_context = new BaseContext (this);
741 for (int i = 0, j = 0; i < count; i++){
742 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
745 // Standard ResolveAsTypeTerminal cannot be used in this case because
746 // it does ObsoleteAttribute and constraint checks which require
747 // base type to be set
749 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (base_context, false);
750 if (fne_resolved == null)
753 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
754 if (fne_resolved is DynamicTypeExpr)
755 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
756 GetSignatureForError ());
758 base_class = fne_resolved;
763 ifaces = new TypeExpr [count - i];
765 if (fne_resolved.Type.IsInterface) {
766 for (int ii = 0; ii < j; ++ii) {
767 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
768 Report.Error (528, Location, "`{0}' is already listed in interface list",
769 fne_resolved.GetSignatureForError ());
774 if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
775 Report.Error (61, fne.Location,
776 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
777 fne_resolved.GetSignatureForError (), GetSignatureForError ());
780 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
781 if (Kind != MemberKind.Class) {
782 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
783 } else if (base_class != null)
784 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
785 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
787 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
788 GetSignatureForError (), fne_resolved.GetSignatureForError ());
792 ifaces [j++] = fne_resolved;
798 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
800 var ifaces = new List<TypeExpr> (0);
801 if (iface_exprs != null)
802 ifaces.AddRange (iface_exprs);
804 foreach (TypeContainer part in partial_parts) {
805 TypeExpr new_base_class;
806 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
807 if (new_base_class != TypeManager.system_object_expr) {
808 if (base_class == TypeManager.system_object_expr)
809 base_class = new_base_class;
811 if (new_base_class != null && !TypeManager.IsEqual (new_base_class.Type, base_class.Type)) {
812 Report.SymbolRelatedToPreviousError (base_class.Location, "");
813 Report.Error (263, part.Location,
814 "Partial declarations of `{0}' must not specify different base classes",
815 part.GetSignatureForError ());
822 if (new_ifaces == null)
825 foreach (TypeExpr iface in new_ifaces) {
826 if (ifaces.Contains (iface))
833 if (ifaces.Count == 0)
836 return ifaces.ToArray ();
840 // Checks that some operators come in pairs:
846 // They are matched based on the return type and the argument types
848 void CheckPairedOperators ()
850 bool has_equality_or_inequality = false;
851 var operators = this.operators.ToArray ();
852 bool[] has_pair = new bool[operators.Length];
854 for (int i = 0; i < operators.Length; ++i) {
855 if (operators[i] == null)
858 Operator o_a = (Operator) operators[i];
859 Operator.OpType o_type = o_a.OperatorType;
860 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
861 has_equality_or_inequality = true;
863 Operator.OpType matching_type = o_a.GetMatchingOperator ();
864 if (matching_type == Operator.OpType.TOP) {
869 for (int ii = 0; ii < operators.Length; ++ii) {
870 Operator o_b = (Operator) operators[ii];
871 if (o_b == null || o_b.OperatorType != matching_type)
874 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
877 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
883 // Used to ignore duplicate user conversions
889 for (int i = 0; i < operators.Length; ++i) {
890 if (operators[i] == null || has_pair[i])
893 Operator o = (Operator) operators [i];
894 Report.Error (216, o.Location,
895 "The operator `{0}' requires a matching operator `{1}' to also be defined",
896 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
899 if (has_equality_or_inequality) {
900 if (Methods == null || !HasEquals)
901 Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
902 GetSignatureForError ());
904 if (Methods == null || !HasGetHashCode)
905 Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
906 GetSignatureForError ());
910 bool CheckGenericInterfaces (Type[] ifaces)
912 var already_checked = new List<Type> ();
914 for (int i = 0; i < ifaces.Length; i++) {
915 Type iface = ifaces [i];
916 foreach (Type t in already_checked) {
920 Type[] inferred = new Type [CountTypeParameters];
921 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
924 Report.Error (695, Location,
925 "`{0}' cannot implement both `{1}' and `{2}' " +
926 "because they may unify for some type parameter substitutions",
927 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
928 TypeManager.CSharpName (t));
932 already_checked.Add (iface);
940 bool CreateTypeBuilder ()
943 Type default_parent = null;
944 if (Kind == MemberKind.Struct)
945 default_parent = TypeManager.value_type;
946 else if (Kind == MemberKind.Enum)
947 default_parent = TypeManager.enum_type;
948 else if (Kind == MemberKind.Delegate)
949 default_parent = TypeManager.multicast_delegate_type;
952 // Sets .size to 1 for structs with no instance fields
954 int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
957 if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
958 Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
962 ModuleBuilder builder = Module.Compiled.Builder;
963 TypeBuilder = builder.DefineType (
964 Name, TypeAttr, default_parent, type_size);
966 TypeBuilder builder = Parent.TypeBuilder;
968 TypeBuilder = builder.DefineNestedType (
969 Basename, TypeAttr, default_parent, type_size);
971 } catch (ArgumentException) {
972 Report.RuntimeMissingSupport (Location, "static classes");
976 TypeManager.AddUserType (this);
979 string[] param_names = new string [TypeParameters.Length];
980 for (int i = 0; i < TypeParameters.Length; i++)
981 param_names [i] = TypeParameters [i].Name;
983 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
985 int offset = CountTypeParameters;
986 if (CurrentTypeParameters != null)
987 offset -= CurrentTypeParameters.Length;
990 nested_gen_params = new GenericTypeParameterBuilder [offset];
991 Array.Copy (gen_params, nested_gen_params, offset);
994 for (int i = offset; i < gen_params.Length; i++)
995 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1001 bool DefineBaseTypes ()
1003 iface_exprs = ResolveBaseTypes (out base_type);
1004 if (partial_parts != null) {
1005 iface_exprs = GetNormalPartialBases (ref base_type);
1009 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1010 // which in turn should have called DefineType()s on base types if necessary.
1012 // None of the code below should trigger DefineType()s on classes that we depend on.
1013 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1015 // Let's do it as soon as possible, since code below can call DefineType() on classes
1016 // that depend on us to be populated before they are.
1018 if (!(this is CompilerGeneratedClass) && !(this is Delegate))
1019 RootContext.RegisterOrder (this);
1021 if (!CheckRecursiveDefinition (this))
1024 if (base_type != null && base_type.Type != null) {
1025 TypeBuilder.SetParent (base_type.Type);
1028 // add interfaces that were not added at type creation
1029 if (iface_exprs != null) {
1030 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1034 foreach (Type itype in ifaces)
1035 TypeBuilder.AddInterfaceImplementation (itype);
1037 if (!CheckGenericInterfaces (ifaces))
1040 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1047 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1049 public TypeBuilder CreateType ()
1051 if (TypeBuilder != null)
1057 if (!CreateTypeBuilder ()) {
1062 if (partial_parts != null) {
1063 foreach (TypeContainer part in partial_parts)
1064 part.TypeBuilder = TypeBuilder;
1067 if (Types != null) {
1068 foreach (TypeContainer tc in Types) {
1069 if (tc.CreateType () == null) {
1081 public override TypeBuilder DefineType ()
1088 type_defined = true;
1090 if (CreateType () == null) {
1095 if (!DefineBaseTypes ()) {
1100 if (!DefineNestedTypes ()) {
1108 public override void SetParameterInfo (List<Constraints> constraints_list)
1110 base.SetParameterInfo (constraints_list);
1112 if (!is_generic || PartialContainer == this)
1115 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1116 for (int i = 0; i < tc_names.Length; ++i) {
1117 if (tc_names [i].Name != type_params [i].Name) {
1118 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1119 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1120 GetSignatureForError ());
1124 if (tc_names [i].Variance != type_params [i].Variance) {
1125 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1126 Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1127 GetSignatureForError ());
1133 void UpdateTypeParameterConstraints (TypeContainer part)
1135 TypeParameter[] current_params = type_params;
1136 for (int i = 0; i < current_params.Length; i++) {
1137 Constraints c = part.type_params [i].Constraints;
1141 if (current_params [i].UpdateConstraints (part, c))
1144 Report.SymbolRelatedToPreviousError (Location, "");
1145 Report.Error (265, part.Location,
1146 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1147 GetSignatureForError (), current_params [i].GetSignatureForError ());
1151 public bool ResolveType ()
1153 if (!DoResolveType ())
1156 if (compiler_generated != null) {
1157 foreach (CompilerGeneratedClass c in compiler_generated)
1158 if (!c.ResolveType ())
1165 protected virtual bool DoResolveType ()
1170 if (PartialContainer != this)
1171 throw new InternalErrorException ();
1173 TypeExpr current_type = null;
1174 if (CurrentTypeParameters != null) {
1175 foreach (TypeParameter type_param in CurrentTypeParameters) {
1176 if (!type_param.Resolve (this)) {
1182 if (partial_parts != null) {
1183 foreach (TypeContainer part in partial_parts)
1184 UpdateTypeParameterConstraints (part);
1188 for (int i = 0; i < TypeParameters.Length; ++i) {
1190 // FIXME: Same should be done for delegates
1191 // TODO: Quite ugly way how to propagate constraints to
1194 if (nested_gen_params != null && i < nested_gen_params.Length) {
1195 TypeParameters [i].SetConstraints (nested_gen_params [i]);
1197 if (!TypeParameters [i].DefineType (this)) {
1204 // TODO: Very strange, why not simple make generic type from
1205 // current type parameters
1206 current_type = new GenericTypeExpr (this, Location);
1207 current_type = current_type.ResolveAsTypeTerminal (this, false);
1208 if (current_type == null) {
1213 currentType = current_type.Type;
1217 protected virtual bool DefineNestedTypes ()
1219 if (Types != null) {
1220 foreach (TypeContainer tc in Types)
1221 if (tc.DefineType () == null)
1225 if (Delegates != null) {
1226 foreach (Delegate d in Delegates)
1227 if (d.DefineType () == null)
1234 TypeContainer InTransit;
1236 protected bool CheckRecursiveDefinition (TypeContainer tc)
1238 if (InTransit != null) {
1239 Report.SymbolRelatedToPreviousError (this);
1240 if (this is Interface)
1242 529, tc.Location, "Inherited interface `{0}' causes a " +
1243 "cycle in the interface hierarchy of `{1}'",
1244 GetSignatureForError (), tc.GetSignatureForError ());
1247 146, tc.Location, "Circular base class dependency " +
1248 "involving `{0}' and `{1}'",
1249 tc.GetSignatureForError (), GetSignatureForError ());
1255 if (base_type != null && base_type.Type != null) {
1256 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1257 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1258 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1262 if (iface_exprs != null) {
1263 foreach (TypeExpr iface in iface_exprs) {
1264 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1265 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1266 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1271 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1278 public override TypeParameter[] CurrentTypeParameters {
1280 return PartialContainer.type_params;
1285 /// Populates our TypeBuilder with fields and methods
1287 public sealed override bool Define ()
1289 if (members_defined)
1290 return members_defined_ok;
1292 members_defined_ok = DoDefineMembers ();
1293 members_defined = true;
1295 return members_defined_ok;
1298 protected virtual bool DoDefineMembers ()
1300 if (iface_exprs != null) {
1301 foreach (TypeExpr iface in iface_exprs) {
1302 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1303 if ((oa != null) && !IsObsolete)
1304 AttributeTester.Report_ObsoleteMessage (
1305 oa, iface.GetSignatureForError (), Location, Report);
1307 GenericTypeExpr ct = iface as GenericTypeExpr;
1309 // TODO: passing `this' is wrong, should be base type iface instead
1310 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1312 if (!ct.CheckConstraints (this))
1315 if (ct.HasDynamicArguments ()) {
1316 Report.Error (1966, iface.Location,
1317 "`{0}': cannot implement a dynamic interface `{1}'",
1318 GetSignatureForError (), iface.GetSignatureForError ());
1325 if (base_type != null) {
1326 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1327 if (obsolete_attr != null && !IsObsolete)
1328 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1330 GenericTypeExpr ct = base_type as GenericTypeExpr;
1331 if ((ct != null) && !ct.CheckConstraints (this))
1334 TypeContainer baseContainer = TypeManager.LookupTypeContainer(base_type.Type);
1335 if (baseContainer != null)
1336 baseContainer.Define();
1338 member_cache = new MemberCache (base_type.Type, this);
1339 } else if (Kind == MemberKind.Interface) {
1340 member_cache = new MemberCache (null, this);
1341 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1342 for (int i = 0; i < ifaces.Length; ++i)
1343 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1345 member_cache = new MemberCache (null, this);
1349 foreach (TypeContainer tc in types)
1350 member_cache.AddNestedType (tc);
1352 if (delegates != null)
1353 foreach (Delegate d in delegates)
1354 member_cache.AddNestedType (d);
1356 if (partial_parts != null) {
1357 foreach (TypeContainer part in partial_parts)
1358 part.member_cache = member_cache;
1362 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1363 if (conflict_symbol == null) {
1364 if ((ModFlags & Modifiers.NEW) != 0)
1365 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1367 if ((ModFlags & Modifiers.NEW) == 0) {
1368 Report.SymbolRelatedToPreviousError (conflict_symbol);
1369 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1370 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1375 DefineContainerMembers (constants);
1376 DefineContainerMembers (fields);
1378 if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1379 pending = PendingImplementation.GetPendingImplementations (this);
1381 if (requires_delayed_unmanagedtype_check) {
1382 requires_delayed_unmanagedtype_check = false;
1383 foreach (FieldBase f in fields) {
1384 if (f.MemberType != null && f.MemberType.IsPointer)
1385 TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1391 // Constructors are not in the defined_names array
1393 DefineContainerMembers (instance_constructors);
1395 DefineContainerMembers (events);
1396 DefineContainerMembers (ordered_explicit_member_list);
1397 DefineContainerMembers (ordered_member_list);
1399 if (operators != null) {
1400 DefineContainerMembers (operators);
1401 CheckPairedOperators ();
1404 DefineContainerMembers (delegates);
1406 ComputeIndexerName();
1407 CheckEqualsAndGetHashCode();
1409 if (CurrentType != null) {
1410 GenericType = CurrentType;
1414 // FIXME: This hack is needed because member cache does not work
1415 // with generic types, we rely on runtime to inflate dynamic types.
1416 // TODO: This hack requires member cache refactoring to be removed
1418 if (TypeManager.IsGenericType (TypeBuilder))
1419 member_cache = new MemberCache (this);
1424 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1427 foreach (MemberCore mc in mcal) {
1430 } catch (Exception e) {
1431 throw new InternalErrorException (mc, e);
1437 protected virtual void ComputeIndexerName ()
1439 if (indexers == null)
1442 string class_indexer_name = null;
1445 // If there's both an explicit and an implicit interface implementation, the
1446 // explicit one actually implements the interface while the other one is just
1447 // a normal indexer. See bug #37714.
1450 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1451 foreach (Indexer i in indexers) {
1452 if (i.InterfaceType != null) {
1453 if (seen_normal_indexers)
1454 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1458 seen_normal_indexers = true;
1460 if (class_indexer_name == null) {
1461 class_indexer_name = i.ShortName;
1465 if (i.ShortName != class_indexer_name)
1466 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");
1469 if (class_indexer_name != null)
1470 indexer_name = class_indexer_name;
1473 protected virtual void EmitIndexerName ()
1475 if (!seen_normal_indexers)
1478 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1479 if (pa.Constructor == null &&
1480 !pa.ResolveConstructor (Location, TypeManager.string_type))
1483 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { IndexerName });
1484 TypeBuilder.SetCustomAttribute (cb);
1487 protected virtual void CheckEqualsAndGetHashCode ()
1489 if (methods == null)
1492 if (HasEquals && !HasGetHashCode) {
1493 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1497 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1499 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1503 /// This function is based by a delegate to the FindMembers routine
1505 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1511 /// This filter is used by FindMembers, and we just keep
1512 /// a global for the filter to `AlwaysAccept'
1514 static MemberFilter accepting_filter;
1517 static TypeContainer ()
1519 accepting_filter = new MemberFilter (AlwaysAccept);
1522 public MethodInfo[] GetMethods ()
1524 var members = new List<MethodInfo> ();
1528 if (methods != null) {
1529 int len = methods.Count;
1530 for (int i = 0; i < len; i++) {
1531 Method m = (Method) methods [i];
1533 members.Add (m.MethodBuilder);
1537 if (operators != null) {
1538 int len = operators.Count;
1539 for (int i = 0; i < len; i++) {
1540 Operator o = (Operator) operators [i];
1542 members.Add (o.MethodBuilder);
1546 if (properties != null) {
1547 int len = properties.Count;
1548 for (int i = 0; i < len; i++) {
1549 Property p = (Property) properties [i];
1551 if (p.GetBuilder != null)
1552 members.Add (p.GetBuilder);
1553 if (p.SetBuilder != null)
1554 members.Add (p.SetBuilder);
1558 if (indexers != null) {
1559 int len = indexers.Count;
1560 for (int i = 0; i < len; i++) {
1561 Indexer ix = (Indexer) indexers [i];
1563 if (ix.GetBuilder != null)
1564 members.Add (ix.GetBuilder);
1565 if (ix.SetBuilder != null)
1566 members.Add (ix.SetBuilder);
1570 if (events != null) {
1571 int len = events.Count;
1572 for (int i = 0; i < len; i++) {
1573 Event e = (Event) events [i];
1575 if (e.AddBuilder != null)
1576 members.Add (e.AddBuilder);
1577 if (e.RemoveBuilder != null)
1578 members.Add (e.RemoveBuilder);
1582 return members.ToArray ();
1585 // Indicated whether container has StructLayout attribute set Explicit
1586 public bool HasExplicitLayout {
1587 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1588 set { caching_flags |= Flags.HasExplicitLayout; }
1591 public bool HasStructLayout {
1592 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1593 set { caching_flags |= Flags.HasStructLayout; }
1597 // Return the nested type with name @name. Ensures that the nested type
1598 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1600 public Type FindNestedType (string name)
1602 if (PartialContainer != this)
1603 throw new InternalErrorException ("should not happen");
1605 var lists = new[] { types, delegates };
1607 for (int j = 0; j < lists.Length; ++j) {
1608 var list = lists [j];
1612 int len = list.Count;
1613 for (int i = 0; i < len; ++i) {
1615 if (ds.Basename == name) {
1616 return ds.DefineType ();
1624 private void FindMembers_NestedTypes (Modifiers modflags,
1625 BindingFlags bf, MemberFilter filter, object criteria,
1626 ref List<MemberInfo> members)
1628 var lists = new[] { types, delegates };
1630 for (int j = 0; j < lists.Length; ++j) {
1631 var list = lists [j];
1635 int len = list.Count;
1636 for (int i = 0; i < len; i++) {
1639 if ((ds.ModFlags & modflags) == 0)
1642 TypeBuilder tb = ds.TypeBuilder;
1644 if (!(criteria is string) || ds.Basename.Equals (criteria))
1645 tb = ds.DefineType ();
1648 if (tb != null && (filter (tb, criteria) == true)) {
1649 if (members == null)
1650 members = new List<MemberInfo> ();
1659 /// This method returns the members of this type just like Type.FindMembers would
1660 /// Only, we need to use this for types which are _being_ defined because MS'
1661 /// implementation can't take care of that.
1664 // FIXME: return an empty static array instead of null, that cleans up
1665 // some code and is consistent with some coding conventions I just found
1669 // Notice that in various cases we check if our field is non-null,
1670 // something that would normally mean that there was a bug elsewhere.
1672 // The problem happens while we are defining p-invoke methods, as those
1673 // will trigger a FindMembers, but this happens before things are defined
1675 // Since the whole process is a no-op, it is fine to check for null here.
1677 // TODO: This approach will be one day completely removed, it's already
1678 // used at few places only
1681 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1682 MemberFilter filter, object criteria)
1684 List<MemberInfo> members = null;
1686 Modifiers modflags = 0;
1687 if ((bf & BindingFlags.Public) != 0)
1688 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1690 if ((bf & BindingFlags.NonPublic) != 0)
1691 modflags |= Modifiers.PRIVATE;
1693 Modifiers static_mask = 0, static_flags = 0;
1694 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1695 case BindingFlags.Static:
1696 static_mask = static_flags = Modifiers.STATIC;
1699 case BindingFlags.Instance:
1700 static_mask = Modifiers.STATIC;
1705 static_mask = static_flags = 0;
1709 Timer.StartTimer (TimerType.TcFindMembers);
1712 filter = accepting_filter;
1714 if ((mt & MemberTypes.Field) != 0) {
1715 if (fields != null) {
1716 int len = fields.Count;
1717 for (int i = 0; i < len; i++) {
1718 FieldBase f = (FieldBase) fields [i];
1720 if ((f.ModFlags & modflags) == 0)
1722 if ((f.ModFlags & static_mask) != static_flags)
1725 FieldBuilder fb = f.FieldBuilder;
1726 if (fb != null && filter (fb, criteria) == true) {
1727 if (members == null)
1728 members = new List<MemberInfo> ();
1735 if (constants != null) {
1736 int len = constants.Count;
1737 for (int i = 0; i < len; i++) {
1738 Const con = (Const) constants [i];
1740 if ((con.ModFlags & modflags) == 0)
1742 if ((con.ModFlags & static_mask) != static_flags)
1745 FieldBuilder fb = con.FieldBuilder;
1747 // Define parent and not member, otherwise membercache can be null
1748 if (con.Parent.Define ())
1749 fb = con.FieldBuilder;
1751 if (fb != null && filter (fb, criteria) == true) {
1752 if (members == null)
1753 members = new List<MemberInfo> ();
1761 if ((mt & MemberTypes.Method) != 0) {
1762 if (methods != null) {
1763 int len = methods.Count;
1764 for (int i = 0; i < len; i++) {
1765 MethodOrOperator m = (MethodOrOperator) methods [i];
1767 if ((m.ModFlags & modflags) == 0)
1769 if ((m.ModFlags & static_mask) != static_flags)
1772 MethodBuilder mb = m.MethodBuilder;
1774 if (mb != null && filter (mb, criteria) == true) {
1775 if (members == null)
1776 members = new List<MemberInfo> ();
1783 if (operators != null) {
1784 int len = operators.Count;
1785 for (int i = 0; i < len; i++) {
1786 Operator o = (Operator) operators [i];
1788 if ((o.ModFlags & modflags) == 0)
1790 if ((o.ModFlags & static_mask) != static_flags)
1793 MethodBuilder ob = o.MethodBuilder;
1794 if (ob != null && filter (ob, criteria) == true) {
1795 if (members == null)
1796 members = new List<MemberInfo> ();
1803 if (events != null) {
1804 foreach (Event e in events) {
1805 if ((e.ModFlags & modflags) == 0)
1807 if ((e.ModFlags & static_mask) != static_flags)
1810 MethodBuilder b = e.AddBuilder;
1811 if (b != null && filter (b, criteria)) {
1812 if (members == null)
1813 members = new List<MemberInfo> ();
1818 b = e.RemoveBuilder;
1819 if (b != null && filter (b, criteria)) {
1820 if (members == null)
1821 members = new List<MemberInfo> ();
1828 if (properties != null) {
1829 int len = properties.Count;
1830 for (int i = 0; i < len; i++) {
1831 Property p = (Property) properties [i];
1833 if ((p.ModFlags & modflags) == 0)
1835 if ((p.ModFlags & static_mask) != static_flags)
1841 if (b != null && filter (b, criteria) == true) {
1842 if (members == null)
1843 members = new List<MemberInfo> ();
1849 if (b != null && filter (b, criteria) == true) {
1850 if (members == null)
1851 members = new List<MemberInfo> ();
1858 if (indexers != null) {
1859 int len = indexers.Count;
1860 for (int i = 0; i < len; i++) {
1861 Indexer ix = (Indexer) indexers [i];
1863 if ((ix.ModFlags & modflags) == 0)
1865 if ((ix.ModFlags & static_mask) != static_flags)
1871 if (b != null && filter (b, criteria) == true) {
1872 if (members == null)
1873 members = new List<MemberInfo> ();
1879 if (b != null && filter (b, criteria) == true) {
1880 if (members == null)
1881 members = new List<MemberInfo> ();
1889 if ((mt & MemberTypes.Event) != 0) {
1890 if (events != null) {
1891 int len = events.Count;
1892 for (int i = 0; i < len; i++) {
1893 Event e = (Event) events [i];
1895 if ((e.ModFlags & modflags) == 0)
1897 if ((e.ModFlags & static_mask) != static_flags)
1900 MemberInfo eb = e.EventBuilder;
1901 if (eb != null && filter (eb, criteria) == true) {
1902 if (members == null)
1903 members = new List<MemberInfo> ();
1905 members.Add (e.EventBuilder);
1911 if ((mt & MemberTypes.Property) != 0){
1912 if (properties != null) {
1913 int len = properties.Count;
1914 for (int i = 0; i < len; i++) {
1915 Property p = (Property) properties [i];
1917 if ((p.ModFlags & modflags) == 0)
1919 if ((p.ModFlags & static_mask) != static_flags)
1922 MemberInfo pb = p.PropertyBuilder;
1923 if (pb != null && filter (pb, criteria) == true) {
1924 if (members == null)
1925 members = new List<MemberInfo> ();
1927 members.Add (p.PropertyBuilder);
1932 if (indexers != null) {
1933 int len = indexers.Count;
1934 for (int i = 0; i < len; i++) {
1935 Indexer ix = (Indexer) indexers [i];
1937 if ((ix.ModFlags & modflags) == 0)
1939 if ((ix.ModFlags & static_mask) != static_flags)
1942 MemberInfo ib = ix.PropertyBuilder;
1943 if (ib != null && filter (ib, criteria) == true) {
1944 if (members == null)
1945 members = new List<MemberInfo> ();
1947 members.Add (ix.PropertyBuilder);
1953 if ((mt & MemberTypes.NestedType) != 0)
1954 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1956 if ((mt & MemberTypes.Constructor) != 0){
1957 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1958 int len = instance_constructors.Count;
1959 for (int i = 0; i < len; i++) {
1960 Constructor c = (Constructor) instance_constructors [i];
1962 ConstructorBuilder cb = c.ConstructorBuilder;
1963 if (cb != null && filter (cb, criteria) == true) {
1964 if (members == null)
1965 members = new List<MemberInfo> ();
1972 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1973 ConstructorBuilder cb =
1974 default_static_constructor.ConstructorBuilder;
1976 if (cb != null && filter (cb, criteria) == true) {
1977 if (members == null)
1978 members = new List<MemberInfo> ();
1986 // Lookup members in base if requested.
1988 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1989 if (TypeBuilder.BaseType != null) {
1990 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1991 if (list.Count > 0) {
1992 if (members == null)
1993 members = new List<MemberInfo> ();
1995 members.AddRange (list);
2000 Timer.StopTimer (TimerType.TcFindMembers);
2002 if (members == null)
2003 return MemberList.Empty;
2005 return new MemberList (members);
2008 public override MemberCache MemberCache {
2010 return member_cache;
2014 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2015 MemberFilter filter, object criteria)
2017 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2020 return ds.FindMembers (mt, bf, filter, criteria);
2022 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2026 /// Emits the values for the constants
2028 public void EmitConstants ()
2030 if (constants != null)
2031 foreach (Const con in constants)
2036 void CheckMemberUsage (List<MemberCore> al, string member_type)
2041 foreach (MemberCore mc in al) {
2042 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
2045 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2046 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2051 public virtual void VerifyMembers ()
2054 // Check for internal or private fields that were never assigned
2056 if (Report.WarningLevel >= 3) {
2057 CheckMemberUsage (properties, "property");
2058 CheckMemberUsage (methods, "method");
2059 CheckMemberUsage (constants, "constant");
2061 if (fields != null){
2062 bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
2063 foreach (FieldBase f in fields) {
2064 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
2065 if (is_type_exposed)
2072 if ((f.caching_flags & Flags.IsAssigned) == 0)
2073 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2075 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2076 f.GetSignatureForError ());
2082 // Only report 649 on level 4
2084 if (Report.WarningLevel < 4)
2087 if ((f.caching_flags & Flags.IsAssigned) != 0)
2091 // Don't be pendatic over serializable attributes
2093 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2096 Constant c = New.Constantify (f.MemberType);
2097 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2098 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2104 // TODO: move to ClassOrStruct
2105 void EmitConstructors ()
2107 if (instance_constructors == null)
2110 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2111 bool has_compliant_args = false;
2113 foreach (Constructor c in instance_constructors) {
2117 catch (Exception e) {
2118 throw new InternalErrorException (c, e);
2121 if (has_compliant_args)
2124 has_compliant_args = c.HasCompliantArgs;
2126 if (!has_compliant_args)
2127 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2129 foreach (Constructor c in instance_constructors) {
2133 catch (Exception e) {
2134 throw new InternalErrorException (c, e);
2141 /// Emits the code, this step is performed after all
2142 /// the types, enumerations, constructors
2144 public virtual void EmitType ()
2146 if (OptAttributes != null)
2147 OptAttributes.Emit ();
2151 EmitConstructors ();
2153 // Can not continue if constants are broken
2155 if (Report.Errors > 0)
2158 if (default_static_constructor != null)
2159 default_static_constructor.Emit ();
2161 if (operators != null)
2162 foreach (Operator o in operators)
2165 if (properties != null)
2166 foreach (Property p in properties)
2169 if (indexers != null) {
2170 foreach (Indexer indx in indexers)
2175 if (events != null){
2176 foreach (Event e in Events)
2180 if (methods != null) {
2181 for (int i = 0; i < methods.Count; ++i)
2182 ((MethodOrOperator) methods [i]).Emit ();
2186 foreach (FieldBase f in fields)
2189 if (delegates != null) {
2190 foreach (Delegate d in Delegates) {
2195 if (pending != null)
2196 pending.VerifyPendingMethods (Report);
2198 if (Report.Errors > 0)
2201 if (compiler_generated != null) {
2202 for (int i = 0; i < compiler_generated.Count; ++i)
2203 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2207 public override void CloseType ()
2209 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2213 caching_flags |= Flags.CloseTypeCreated;
2214 TypeBuilder.CreateType ();
2215 } catch (TypeLoadException){
2217 // This is fine, the code still created the type
2219 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2220 // Console.WriteLine (e.Message);
2221 } catch (Exception e) {
2222 throw new InternalErrorException (this, e);
2226 foreach (TypeContainer tc in Types)
2227 if (tc.Kind == MemberKind.Struct)
2230 foreach (TypeContainer tc in Types)
2231 if (tc.Kind != MemberKind.Struct)
2235 if (Delegates != null)
2236 foreach (Delegate d in Delegates)
2239 if (compiler_generated != null)
2240 foreach (CompilerGeneratedClass c in compiler_generated)
2243 PartialContainer = null;
2245 // properties = null;
2248 initialized_fields = null;
2249 initialized_static_fields = null;
2251 ordered_explicit_member_list = null;
2252 ordered_member_list = null;
2257 compiler_generated = null;
2258 default_constructor = null;
2259 default_static_constructor = null;
2261 OptAttributes = null;
2264 member_cache = null;
2268 // Performs the validation on a Method's modifiers (properties have
2269 // the same properties).
2271 public bool MethodModifiersValid (MemberCore mc)
2273 const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2274 const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2275 const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2277 var flags = mc.ModFlags;
2280 // At most one of static, virtual or override
2282 if ((flags & Modifiers.STATIC) != 0){
2283 if ((flags & vao) != 0){
2284 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2285 mc.GetSignatureForError ());
2290 if (Kind == MemberKind.Struct){
2291 if ((flags & va) != 0){
2292 ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
2297 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2298 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2299 mc.GetSignatureForError ());
2304 // If the declaration includes the abstract modifier, then the
2305 // declaration does not include static, virtual or extern
2307 if ((flags & Modifiers.ABSTRACT) != 0){
2308 if ((flags & Modifiers.EXTERN) != 0){
2310 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2314 if ((flags & Modifiers.SEALED) != 0) {
2315 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2319 if ((flags & Modifiers.VIRTUAL) != 0){
2320 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2324 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2325 Report.SymbolRelatedToPreviousError (this);
2326 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2327 mc.GetSignatureForError (), GetSignatureForError ());
2332 if ((flags & Modifiers.PRIVATE) != 0){
2333 if ((flags & vao) != 0){
2334 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2339 if ((flags & Modifiers.SEALED) != 0){
2340 if ((flags & Modifiers.OVERRIDE) == 0){
2341 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2349 public Constructor DefaultStaticConstructor {
2350 get { return default_static_constructor; }
2353 protected override bool VerifyClsCompliance ()
2355 if (!base.VerifyClsCompliance ())
2360 Type base_type = TypeBuilder.BaseType;
2361 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2362 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2369 /// Checks whether container name is CLS Compliant
2371 void VerifyClsName ()
2373 Dictionary<string, object> base_members = base_cache == null ?
2374 new Dictionary<string, object> () :
2375 base_cache.GetPublicMembers ();
2376 var this_members = new Dictionary<string, object> ();
2378 foreach (var entry in defined_names) {
2379 MemberCore mc = entry.Value;
2380 if (!mc.IsClsComplianceRequired ())
2383 string name = entry.Key;
2384 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2386 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2388 if (!base_members.TryGetValue (lcase, out found)) {
2389 if (!this_members.TryGetValue (lcase, out found)) {
2390 this_members.Add (lcase, mc);
2395 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2398 if (found is MemberInfo) {
2399 if (basename == ((MemberInfo) found).Name)
2401 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2403 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2406 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2412 /// Performs checks for an explicit interface implementation. First it
2413 /// checks whether the `interface_type' is a base inteface implementation.
2414 /// Then it checks whether `name' exists in the interface type.
2416 public bool VerifyImplements (InterfaceMemberBase mb)
2418 if (ifaces != null) {
2419 foreach (Type t in ifaces){
2420 if (TypeManager.IsEqual (t, mb.InterfaceType))
2425 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2426 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2427 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2431 public override Type LookupAnyGeneric (string typeName)
2433 if (types != null) {
2434 foreach (TypeContainer tc in types) {
2438 int pos = tc.Basename.LastIndexOf ('`');
2439 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2440 return tc.TypeBuilder;
2444 return base.LookupAnyGeneric (typeName);
2447 public void Mark_HasEquals ()
2449 cached_method |= CachedMethods.Equals;
2452 public void Mark_HasGetHashCode ()
2454 cached_method |= CachedMethods.GetHashCode;
2458 /// Method container contains Equals method
2460 public bool HasEquals {
2462 return (cached_method & CachedMethods.Equals) != 0;
2467 /// Method container contains GetHashCode method
2469 public bool HasGetHashCode {
2471 return (cached_method & CachedMethods.GetHashCode) != 0;
2475 public bool HasStaticFieldInitializer {
2477 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2481 cached_method |= CachedMethods.HasStaticFieldInitializer;
2483 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2491 string IMemberContainer.Name {
2497 Type IMemberContainer.Type {
2503 bool IMemberContainer.IsInterface {
2505 return Kind == MemberKind.Interface;
2509 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2511 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2513 if (GenericType != null)
2514 return TypeManager.FindMembers (GenericType, mt, new_bf,
2517 return FindMembers (mt, new_bf, null, null);
2521 // Generates xml doc comments (if any), and if required,
2522 // handle warning report.
2524 internal override void GenerateDocComment (DeclSpace ds)
2526 DocUtil.GenerateTypeDocComment (this, ds, Report);
2529 public override string DocCommentHeader {
2530 get { return "T:"; }
2533 public MemberCache BaseCache {
2535 if (base_cache != null)
2537 if (TypeBuilder.BaseType != null)
2538 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2539 if (TypeBuilder.IsInterface)
2540 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2546 public abstract class ClassOrStruct : TypeContainer
2548 Dictionary<SecurityAction, PermissionSet> declarative_security;
2550 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2551 MemberName name, Attributes attrs, MemberKind kind)
2552 : base (ns, parent, name, attrs, kind)
2556 protected override bool AddToContainer (MemberCore symbol, string name)
2558 if (name == MemberName.Name) {
2559 if (symbol is TypeParameter) {
2560 Report.Error (694, symbol.Location,
2561 "Type parameter `{0}' has same name as containing type, or method",
2562 symbol.GetSignatureForError ());
2566 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2567 if (imb == null || !imb.IsExplicitImpl) {
2568 Report.SymbolRelatedToPreviousError (this);
2569 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2570 symbol.GetSignatureForError ());
2575 return base.AddToContainer (symbol, name);
2578 public override void VerifyMembers ()
2580 base.VerifyMembers ();
2582 if ((events != null) && Report.WarningLevel >= 3) {
2583 foreach (Event e in events){
2584 // Note: The event can be assigned from same class only, so we can report
2585 // this warning for all accessibility modes
2586 if ((e.caching_flags & Flags.IsUsed) == 0)
2587 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2592 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
2594 if (a.IsValidSecurityAttribute ()) {
2595 if (declarative_security == null)
2596 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2598 a.ExtractSecurityPermissionSet (declarative_security);
2602 if (a.Type == pa.StructLayout) {
2603 PartialContainer.HasStructLayout = true;
2605 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2606 PartialContainer.HasExplicitLayout = true;
2609 if (a.Type == pa.Dynamic) {
2610 a.Error_MisusedDynamicAttribute ();
2614 base.ApplyAttributeBuilder (a, cb, pa);
2618 /// Defines the default constructors
2620 protected void DefineDefaultConstructor (bool is_static)
2622 // The default instance constructor is public
2623 // If the class is abstract, the default constructor is protected
2624 // The default static constructor is private
2628 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2630 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2633 Constructor c = new Constructor (this, MemberName.Name, mods,
2634 null, ParametersCompiled.EmptyReadOnlyParameters,
2635 new GeneratedBaseInitializer (Location),
2639 c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2642 protected override bool DoDefineMembers ()
2644 CheckProtectedModifier ();
2646 base.DoDefineMembers ();
2648 if (default_static_constructor != null)
2649 default_static_constructor.Define ();
2654 public override void Emit ()
2656 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2657 DefineDefaultConstructor (true);
2658 default_static_constructor.Define ();
2663 if (declarative_security != null) {
2664 foreach (var de in declarative_security) {
2665 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2670 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2672 DeclSpace top_level = Parent;
2673 if (top_level != null) {
2674 while (top_level.Parent != null)
2675 top_level = top_level.Parent;
2677 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name);
2678 if (candidates != null)
2679 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2682 return NamespaceEntry.LookupExtensionMethod (extensionType, name, loc);
2685 protected override TypeAttributes TypeAttr {
2687 if (default_static_constructor == null)
2688 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2690 return base.TypeAttr;
2696 // TODO: should be sealed
2697 public class Class : ClassOrStruct {
2698 const Modifiers AllowedModifiers =
2701 Modifiers.PROTECTED |
2702 Modifiers.INTERNAL |
2704 Modifiers.ABSTRACT |
2709 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2711 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2713 : base (ns, parent, name, attrs, MemberKind.Class)
2715 var accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2716 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2718 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2719 Report.FeatureIsNotAvailable (Location, "static classes");
2723 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2725 if (part.Name == "System.Object")
2726 Report.Error (537, part.Location,
2727 "The class System.Object cannot have a base class or implement an interface.");
2728 base.AddBasesForPart (part, bases);
2731 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
2733 if (a.Type == pa.AttributeUsage) {
2734 if (!TypeManager.IsAttributeType (BaseType) &&
2735 TypeBuilder.FullName != "System.Attribute") {
2736 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2740 if (a.Type == pa.Conditional && !TypeManager.IsAttributeType (BaseType)) {
2741 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2745 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2746 a.Error_MissingGuidAttribute ();
2750 if (a.Type == pa.Extension) {
2751 a.Error_MisusedExtensionAttribute ();
2755 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2758 base.ApplyAttributeBuilder (a, cb, pa);
2761 public override AttributeTargets AttributeTargets {
2763 return AttributeTargets.Class;
2767 protected override void DefineContainerMembers (System.Collections.IList list)
2773 base.DefineContainerMembers (list);
2777 foreach (MemberCore m in list) {
2778 if (m is Operator) {
2779 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2783 if (m is Destructor) {
2784 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2789 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2793 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2796 if (m is Constructor) {
2797 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2801 Method method = m as Method;
2802 if (method != null && method.Parameters.HasExtensionMethodType) {
2803 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2807 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2810 base.DefineContainerMembers (list);
2813 protected override bool DoDefineMembers ()
2815 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2816 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2819 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2820 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2823 if (InstanceConstructors == null && !IsStatic)
2824 DefineDefaultConstructor (false);
2826 return base.DoDefineMembers ();
2829 public override void Emit ()
2833 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2834 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2837 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2839 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2841 if (base_class == null) {
2842 if (RootContext.StdLib)
2843 base_class = TypeManager.system_object_expr;
2844 else if (Name != "System.Object")
2845 base_class = TypeManager.system_object_expr;
2847 if (Kind == MemberKind.Class && TypeManager.IsGenericParameter (base_class.Type)){
2849 689, base_class.Location,
2850 "Cannot derive from `{0}' because it is a type parameter",
2851 base_class.GetSignatureForError ());
2855 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2856 Report.Error (698, base_class.Location,
2857 "A generic type cannot derive from `{0}' because it is an attribute class",
2858 base_class.GetSignatureForError ());
2861 if (base_class.IsSealed){
2862 Report.SymbolRelatedToPreviousError (base_class.Type);
2863 if (base_class.Type.IsAbstract) {
2864 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2865 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2867 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2868 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2873 if (!base_class.CanInheritFrom ()){
2874 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2875 GetSignatureForError (), base_class.GetSignatureForError ());
2879 if (!IsAccessibleAs (base_class.Type)) {
2880 Report.SymbolRelatedToPreviousError (base_class.Type);
2881 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2882 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2886 if (PartialContainer.IsStaticClass) {
2887 if (base_class.Type != TypeManager.object_type) {
2888 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2889 GetSignatureForError (), base_class.GetSignatureForError ());
2893 if (ifaces != null) {
2894 foreach (TypeExpr t in ifaces)
2895 Report.SymbolRelatedToPreviousError (t.Type);
2896 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2903 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2904 /// Valid only for attribute classes.
2905 public bool IsExcluded ()
2907 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2908 return (caching_flags & Flags.Excluded) != 0;
2910 caching_flags &= ~Flags.Excluded_Undetected;
2912 if (OptAttributes == null)
2915 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2919 foreach (Attribute a in attrs) {
2920 string condition = a.GetConditionalAttributeValue ();
2921 if (Location.CompilationUnit.IsConditionalDefined (condition))
2925 caching_flags |= Flags.Excluded;
2930 // FIXME: How do we deal with the user specifying a different
2933 protected override TypeAttributes TypeAttr {
2935 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2937 ta |= StaticClassAttribute;
2943 public sealed class Struct : ClassOrStruct {
2945 bool is_unmanaged, has_unmanaged_check_done;
2948 // Modifiers allowed in a struct declaration
2950 const Modifiers AllowedModifiers =
2953 Modifiers.PROTECTED |
2954 Modifiers.INTERNAL |
2958 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2959 Modifiers mod, Attributes attrs)
2960 : base (ns, parent, name, attrs, MemberKind.Struct)
2962 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2964 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2966 this.ModFlags |= Modifiers.SEALED;
2969 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
2971 base.ApplyAttributeBuilder (a, cb, pa);
2974 // When struct constains fixed fixed and struct layout has explicitly
2975 // set CharSet, its value has to be propagated to compiler generated
2976 // fixed field types
2978 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2979 for (int i = 0; i < Fields.Count; ++i) {
2980 FixedField ff = Fields [i] as FixedField;
2982 ff.SetCharSet (TypeBuilder.Attributes);
2987 public override AttributeTargets AttributeTargets {
2989 return AttributeTargets.Struct;
2993 public override bool IsUnmanagedType ()
2998 if (requires_delayed_unmanagedtype_check)
3001 if (has_unmanaged_check_done)
3002 return is_unmanaged;
3004 has_unmanaged_check_done = true;
3006 foreach (FieldBase f in fields) {
3007 if ((f.ModFlags & Modifiers.STATIC) != 0)
3010 // It can happen when recursive unmanaged types are defined
3011 // struct S { S* s; }
3012 Type mt = f.MemberType;
3014 has_unmanaged_check_done = false;
3015 requires_delayed_unmanagedtype_check = true;
3019 // TODO: Remove when pointer types are under mcs control
3020 while (mt.IsPointer)
3021 mt = TypeManager.GetElementType (mt);
3022 if (TypeManager.IsEqual (mt, TypeBuilder))
3025 if (TypeManager.IsUnmanagedType (mt))
3031 is_unmanaged = true;
3035 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
3037 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
3039 // If we are compiling our runtime,
3040 // and we are defining ValueType, then our
3041 // base is `System.Object'.
3043 if (base_class == null) {
3044 if (!RootContext.StdLib && Name == "System.ValueType")
3045 base_class = TypeManager.system_object_expr;
3047 base_class = TypeManager.system_valuetype_expr;
3054 // FIXME: Allow the user to specify a different set of attributes
3055 // in some cases (Sealed for example is mandatory for a class,
3056 // but what SequentialLayout can be changed
3058 protected override TypeAttributes TypeAttr {
3060 const TypeAttributes DefaultTypeAttributes =
3061 TypeAttributes.SequentialLayout |
3062 TypeAttributes.Sealed;
3064 return base.TypeAttr | DefaultTypeAttributes;
3068 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3070 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3071 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3072 field.GetSignatureForError ());
3075 base.RegisterFieldForInitialization (field, expression);
3083 public sealed class Interface : TypeContainer, IMemberContainer {
3086 /// Modifiers allowed in a class declaration
3088 public const Modifiers AllowedModifiers =
3091 Modifiers.PROTECTED |
3092 Modifiers.INTERNAL |
3096 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
3098 : base (ns, parent, name, attrs, MemberKind.Interface)
3100 var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3102 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
3105 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
3107 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
3108 a.Error_MissingGuidAttribute ();
3112 base.ApplyAttributeBuilder (a, cb, pa);
3116 public override AttributeTargets AttributeTargets {
3118 return AttributeTargets.Interface;
3122 protected override TypeAttributes TypeAttr {
3124 const TypeAttributes DefaultTypeAttributes =
3125 TypeAttributes.AutoLayout |
3126 TypeAttributes.Abstract |
3127 TypeAttributes.Interface;
3129 return base.TypeAttr | DefaultTypeAttributes;
3133 protected override bool VerifyClsCompliance ()
3135 if (!base.VerifyClsCompliance ())
3138 if (ifaces != null) {
3139 foreach (Type t in ifaces) {
3140 if (AttributeTester.IsClsCompliant (t))
3143 Report.SymbolRelatedToPreviousError (t);
3144 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3145 GetSignatureForError (), TypeManager.CSharpName (t));
3153 public abstract class InterfaceMemberBase : MemberBase {
3155 // Whether this is an interface member.
3157 public bool IsInterface;
3160 // If true, this is an explicit interface implementation
3162 public bool IsExplicitImpl;
3164 protected bool is_external_implementation;
3167 // The interface type we are explicitly implementing
3169 public Type InterfaceType;
3172 // The method we're overriding if this is an override method.
3174 protected MethodInfo base_method;
3176 readonly Modifiers explicit_mod_flags;
3177 public MethodAttributes flags;
3179 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3180 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
3181 MemberName name, Attributes attrs)
3182 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3185 IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
3186 IsExplicitImpl = (MemberName.Left != null);
3187 explicit_mod_flags = mod;
3190 protected override bool CheckBase ()
3192 if (!base.CheckBase ())
3195 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3196 CheckForDuplications ();
3198 if (IsExplicitImpl || this is Destructor)
3201 // Is null for System.Object while compiling corlib and base interfaces
3202 if (Parent.PartialContainer.BaseCache == null) {
3203 if ((ModFlags & Modifiers.NEW) != 0) {
3204 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3209 Type base_ret_type = null;
3210 base_method = FindOutBaseMethod (ref base_ret_type);
3212 // method is override
3213 if (base_method != null) {
3214 if (!CheckMethodAgainstBase (base_ret_type))
3217 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3218 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3220 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
3221 Report.SymbolRelatedToPreviousError (base_method);
3222 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3223 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3226 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
3227 Report.SymbolRelatedToPreviousError (base_method);
3228 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3229 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3236 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3237 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3238 if (conflict_symbol != null) {
3239 Report.SymbolRelatedToPreviousError (conflict_symbol);
3241 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3242 else if (this is PropertyBase)
3243 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3245 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3247 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3248 GetSignatureForError (), SimpleName.GetMemberType (this));
3253 if (conflict_symbol == null) {
3254 if ((ModFlags & Modifiers.NEW) != 0) {
3255 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3260 if ((ModFlags & Modifiers.NEW) == 0) {
3261 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3264 Report.SymbolRelatedToPreviousError (conflict_symbol);
3265 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3266 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3272 protected virtual bool CheckForDuplications ()
3274 return Parent.MemberCache.CheckExistingMembersOverloads (
3275 this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters, Report);
3279 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3280 // that have been defined.
3282 // `name' is the user visible name for reporting errors (this is used to
3283 // provide the right name regarding method names and properties)
3285 bool CheckMethodAgainstBase (Type base_method_type)
3289 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3290 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3291 Report.SymbolRelatedToPreviousError (base_method);
3292 Report.Error (506, Location,
3293 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3294 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3298 // Now we check that the overriden method is not final
3300 if (base_method.IsFinal) {
3301 Report.SymbolRelatedToPreviousError (base_method);
3302 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3303 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3307 // Check that the permissions are not being changed
3309 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3310 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3312 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3313 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3317 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3318 Report.SymbolRelatedToPreviousError (base_method);
3319 if (this is PropertyBasedMember) {
3320 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3321 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3324 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3325 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3331 if ((ModFlags & Modifiers.NEW) == 0) {
3332 if ((ModFlags & Modifiers.OVERRIDE) == 0) {
3333 ModFlags |= Modifiers.NEW;
3334 Report.SymbolRelatedToPreviousError (base_method);
3335 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3336 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",
3337 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3338 if (base_method.IsAbstract){
3339 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3340 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3344 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3345 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3349 if (base_method.IsAbstract && !IsInterface) {
3350 Report.SymbolRelatedToPreviousError (base_method);
3351 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3352 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3360 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3362 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3364 // when overriding protected internal, the method can be declared
3365 // protected internal only within the same assembly or assembly
3366 // which has InternalsVisibleTo
3368 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3369 return TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, base_method.DeclaringType.Assembly);
3370 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3372 // if it's not "protected internal", it must be "protected"
3376 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3378 // protected within the same assembly - an error
3381 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3382 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3384 // protected ok, but other attributes differ - report an error
3390 return (thisp == base_classp);
3394 public override bool Define ()
3397 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3398 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3400 flags = MethodAttributes.Public |
3401 MethodAttributes.Abstract |
3402 MethodAttributes.HideBySig |
3403 MethodAttributes.NewSlot |
3404 MethodAttributes.Virtual;
3406 Parent.PartialContainer.MethodModifiersValid (this);
3408 flags = ModifiersExtensions.MethodAttr (ModFlags);
3411 if (IsExplicitImpl) {
3412 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3413 if (iface_texpr == null)
3416 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3417 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3418 GetSignatureForError ());
3421 InterfaceType = iface_texpr.Type;
3423 if (!InterfaceType.IsInterface) {
3424 Report.SymbolRelatedToPreviousError (InterfaceType);
3425 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3426 TypeManager.CSharpName (InterfaceType));
3428 Parent.PartialContainer.VerifyImplements (this);
3431 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3434 return base.Define ();
3437 protected bool DefineParameters (ParametersCompiled parameters)
3439 if (!parameters.Resolve (this))
3443 for (int i = 0; i < parameters.Count; ++i) {
3444 Parameter p = parameters [i];
3446 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3447 p.Warning_UselessOptionalParameter (Report);
3449 if (p.CheckAccessibility (this))
3452 Type t = parameters.Types [i];
3453 Report.SymbolRelatedToPreviousError (t);
3454 if (this is Indexer)
3455 Report.Error (55, Location,
3456 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3457 TypeManager.CSharpName (t), GetSignatureForError ());
3458 else if (this is Operator)
3459 Report.Error (57, Location,
3460 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3461 TypeManager.CSharpName (t), GetSignatureForError ());
3463 Report.Error (51, Location,
3464 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3465 TypeManager.CSharpName (t), GetSignatureForError ());
3471 public override void Emit()
3473 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3474 // We are more strict than csc and report this as an error because SRE does not allow emit that
3475 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3476 if (this is Constructor) {
3477 Report.Error (824, Location,
3478 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3480 Report.Error (626, Location,
3481 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3482 GetSignatureForError ());
3489 public override bool EnableOverloadChecks (MemberCore overload)
3492 // Two members can differ in their explicit interface
3493 // type parameter only
3495 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3496 if (imb != null && imb.IsExplicitImpl) {
3497 if (IsExplicitImpl) {
3498 caching_flags |= Flags.MethodOverloadsExist;
3503 return IsExplicitImpl;
3506 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3508 Report.SymbolRelatedToPreviousError (base_method);
3509 string base_name = TypeManager.GetFullNameSignature (base_method);
3510 string this_name = GetSignatureForError ();
3511 if (suffix != null) {
3512 base_name += suffix;
3513 this_name += suffix;
3516 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3517 this_name, ModifiersExtensions.GetDescription (ma), base_name);
3520 protected static string Error722 {
3522 return "`{0}': static types cannot be used as return types";
3527 /// Gets base method and its return type
3529 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3532 // The "short" name of this property / indexer / event. This is the
3533 // name without the explicit interface.
3535 public string ShortName
3537 get { return MemberName.Name; }
3538 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3542 // Returns full metadata method name
3544 public string GetFullName (MemberName name)
3546 if (!IsExplicitImpl)
3550 // When dealing with explicit members a full interface type
3551 // name is added to member name to avoid possible name conflicts
3553 // We use CSharpName which gets us full name with benefit of
3554 // replacing predefined names which saves some space and name
3557 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3560 protected override bool VerifyClsCompliance ()
3562 if (!base.VerifyClsCompliance ()) {
3563 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3564 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3567 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3568 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3573 if (GenericMethod != null)
3574 GenericMethod.VerifyClsCompliance ();
3579 public override bool IsUsed
3581 get { return IsExplicitImpl || base.IsUsed; }
3586 public abstract class MemberBase : MemberCore
3588 protected FullNamedExpression type_name;
3589 protected Type member_type;
3591 public readonly DeclSpace ds;
3592 public readonly GenericMethod GenericMethod;
3594 protected MemberBase (DeclSpace parent, GenericMethod generic,
3595 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3596 MemberName name, Attributes attrs)
3597 : base (parent, name, attrs)
3599 this.ds = generic != null ? generic : (DeclSpace) parent;
3600 this.type_name = type;
3601 ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3602 GenericMethod = generic;
3603 if (GenericMethod != null)
3604 GenericMethod.ModFlags = ModFlags;
3608 // Main member define entry
3610 public override bool Define ()
3612 DoMemberTypeIndependentChecks ();
3615 // Returns false only when type resolution failed
3617 if (!ResolveMemberType ())
3620 DoMemberTypeDependentChecks ();
3625 // Any type_name independent checks
3627 protected virtual void DoMemberTypeIndependentChecks ()
3629 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3630 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3631 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3632 GetSignatureForError (), Parent.GetSignatureForError ());
3637 // Any type_name dependent checks
3639 protected virtual void DoMemberTypeDependentChecks ()
3641 // verify accessibility
3642 if (!IsAccessibleAs (MemberType)) {
3643 Report.SymbolRelatedToPreviousError (MemberType);
3644 if (this is Property)
3645 Report.Error (53, Location,
3646 "Inconsistent accessibility: property type `" +
3647 TypeManager.CSharpName (MemberType) + "' is less " +
3648 "accessible than property `" + GetSignatureForError () + "'");
3649 else if (this is Indexer)
3650 Report.Error (54, Location,
3651 "Inconsistent accessibility: indexer return type `" +
3652 TypeManager.CSharpName (MemberType) + "' is less " +
3653 "accessible than indexer `" + GetSignatureForError () + "'");
3654 else if (this is MethodCore) {
3655 if (this is Operator)
3656 Report.Error (56, Location,
3657 "Inconsistent accessibility: return type `" +
3658 TypeManager.CSharpName (MemberType) + "' is less " +
3659 "accessible than operator `" + GetSignatureForError () + "'");
3661 Report.Error (50, Location,
3662 "Inconsistent accessibility: return type `" +
3663 TypeManager.CSharpName (MemberType) + "' is less " +
3664 "accessible than method `" + GetSignatureForError () + "'");
3666 Report.Error (52, Location,
3667 "Inconsistent accessibility: field type `" +
3668 TypeManager.CSharpName (MemberType) + "' is less " +
3669 "accessible than field `" + GetSignatureForError () + "'");
3673 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3674 TypeManager.CheckTypeVariance (MemberType, variance, this);
3677 protected bool IsTypePermitted ()
3679 if (TypeManager.IsSpecialType (MemberType)) {
3680 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3686 protected virtual bool CheckBase ()
3688 CheckProtectedModifier ();
3693 public Type MemberType {
3694 get { return member_type; }
3697 protected virtual bool ResolveMemberType ()
3699 if (member_type != null)
3700 throw new InternalErrorException ("Multi-resolve");
3702 TypeExpr te = type_name.ResolveAsTypeTerminal (this, false);
3707 // Replace original type name, error reporting can use fully resolved name
3711 member_type = te.Type;