2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
12 // TODO: Move the method verification stuff from the class.cs and interface.cs here
17 using System.Collections;
18 using System.Globalization;
19 using System.Reflection.Emit;
20 using System.Reflection;
23 namespace Mono.CSharp {
25 public class MemberName {
26 public readonly string Name;
27 public readonly TypeArguments TypeArguments;
29 public readonly MemberName Left;
31 public static readonly MemberName Null = new MemberName ("");
33 public MemberName (string name)
38 public MemberName (string name, TypeArguments args)
41 this.TypeArguments = args;
44 public MemberName (MemberName left, string name)
45 : this (left, name, null)
49 public MemberName (MemberName left, string name, TypeArguments args)
55 public MemberName (MemberName left, MemberName right)
56 : this (left, right.Name, right.TypeArguments)
59 Left = (right.Left == null) ? left : new MemberName (left, right.Left);
60 TypeArguments = right.TypeArguments;
63 static readonly char [] dot_array = { '.' };
65 public static MemberName FromDotted (string name)
67 string [] elements = name.Split (dot_array);
68 int count = elements.Length;
70 MemberName n = new MemberName (elements [i++]);
72 n = new MemberName (n, elements [i++]);
76 public string GetName ()
79 return Left.GetName () + "." + Name;
84 public bool IsGeneric {
86 if (TypeArguments != null)
88 else if (Left != null)
89 return Left.IsGeneric;
95 public string GetName (bool is_generic)
97 string name = is_generic ? Basename : Name;
99 return Left.GetName (is_generic) + "." + name;
104 public int CountTypeArguments {
106 if (TypeArguments == null)
109 return TypeArguments.Count;
113 public string GetMethodName ()
116 return Left.GetTypeName () + "." + Name;
121 public static string MakeName (string name, TypeArguments args)
126 return name + "`" + args.Count;
129 public static string MakeName (string name, int count)
131 return name + "`" + count;
134 public string GetTypeName ()
137 return Left.GetTypeName () + "." +
138 MakeName (Name, TypeArguments);
140 return MakeName (Name, TypeArguments);
143 protected bool IsUnbound {
145 if ((Left != null) && Left.IsUnbound)
147 else if (TypeArguments == null)
150 return TypeArguments.IsUnbound;
154 protected bool CheckUnbound (Location loc)
156 if ((Left != null) && !Left.CheckUnbound (loc))
158 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
159 Report.Error (1031, loc, "Type expected");
166 public Expression GetTypeExpression (Location loc)
169 if (!CheckUnbound (loc))
172 return new UnboundTypeExpression (GetTypeName ());
176 Expression lexpr = Left.GetTypeExpression (loc);
178 return new MemberAccess (lexpr, Name, TypeArguments, loc);
180 if (TypeArguments != null)
181 return new SimpleName (Basename, TypeArguments, loc);
183 return new SimpleName (Name, loc);
187 public MemberName Clone ()
190 return new MemberName (Left.Clone (), Name, TypeArguments);
192 return new MemberName (Name, TypeArguments);
195 public string Basename {
197 if (TypeArguments != null)
198 return MakeName (Name, TypeArguments);
204 public override string ToString ()
207 if (TypeArguments != null)
208 full_name = Name + "<" + TypeArguments + ">";
213 return Left + "." + full_name;
218 public override bool Equals (object other)
220 return Equals (other as MemberName);
223 public bool Equals (MemberName other)
227 if (other == null || Name != other.Name)
230 if ((TypeArguments != null) &&
231 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
234 if ((TypeArguments == null) && (other.TypeArguments != null))
238 return other.Left == null;
240 return Left.Equals (other.Left);
243 public override int GetHashCode ()
245 int hash = Name.GetHashCode ();
246 for (MemberName n = Left; n != null; n = n.Left)
247 hash ^= n.Name.GetHashCode ();
249 if (TypeArguments != null)
250 hash ^= TypeArguments.Count << 5;
252 return hash & 0x7FFFFFFF;
257 /// Base representation for members. This is used to keep track
258 /// of Name, Location and Modifier flags, and handling Attributes.
260 public abstract class MemberCore : Attributable {
265 protected string cached_name;
268 if (cached_name == null)
269 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
274 // Is not readonly because of IndexerName attribute
275 private MemberName member_name;
276 public MemberName MemberName {
277 get { return member_name; }
281 /// Modifier flags that the user specified in the source code
285 public /*readonly*/ TypeContainer Parent;
288 /// Location where this declaration happens
290 public readonly Location Location;
293 /// XML documentation comment
295 public string DocComment;
298 /// Represents header string for documentation comment
299 /// for each member types.
301 public abstract string DocCommentHeader { get; }
305 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
306 Obsolete = 1 << 1, // Type has obsolete attribute
307 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
308 ClsCompliant = 1 << 3, // Type is CLS Compliant
309 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
310 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
311 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
312 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
313 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
314 Excluded = 1 << 9, // Method is conditional
315 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
320 /// MemberCore flags at first detected then cached
322 internal Flags caching_flags;
324 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
328 if (parent is PartialContainer && !(this is PartialContainer))
329 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
334 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
337 protected virtual void SetMemberName (MemberName new_name)
339 member_name = new_name;
344 /// Tests presence of ObsoleteAttribute and report proper error
346 protected void CheckUsageOfObsoleteAttribute (Type type)
351 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
352 if (obsolete_attr == null)
355 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
358 public abstract bool Define ();
361 // Returns full member name for error message
363 public virtual string GetSignatureForError ()
369 /// Use this method when MethodBuilder is null
371 public virtual string GetSignatureForError (TypeContainer tc)
377 /// Base Emit method. This is also entry point for CLS-Compliant verification.
379 public virtual void Emit ()
381 // Hack with Parent == null is for EnumMember
382 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
383 VerifyObsoleteAttribute ();
385 if (!RootContext.VerifyClsCompliance)
388 VerifyClsCompliance (Parent);
391 public bool InUnsafe {
393 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
397 public virtual bool IsUsed {
399 return (caching_flags & Flags.IsUsed) != 0;
403 public void SetMemberIsUsed ()
405 caching_flags |= Flags.IsUsed;
409 // Whehter is it ok to use an unsafe pointer in this type container
411 public bool UnsafeOK (DeclSpace parent)
414 // First check if this MemberCore modifier flags has unsafe set
416 if ((ModFlags & Modifiers.UNSAFE) != 0)
419 if (parent.UnsafeContext)
422 Expression.UnsafeError (Location);
427 /// Returns instance of ObsoleteAttribute for this MemberCore
429 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
431 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
432 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
436 caching_flags &= ~Flags.Obsolete_Undetected;
438 if (OptAttributes == null)
441 Attribute obsolete_attr = OptAttributes.Search (
442 TypeManager.obsolete_attribute_type, ds.EmitContext);
443 if (obsolete_attr == null)
446 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds.EmitContext);
447 if (obsolete == null)
450 caching_flags |= Flags.Obsolete;
455 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
457 public override bool IsClsCompliaceRequired (DeclSpace container)
459 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
460 return (caching_flags & Flags.ClsCompliant) != 0;
462 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
463 caching_flags &= ~Flags.ClsCompliance_Undetected;
464 caching_flags |= Flags.ClsCompliant;
468 caching_flags &= ~Flags.ClsCompliance_Undetected;
473 /// Returns true when MemberCore is exposed from assembly.
475 public bool IsExposedFromAssembly (DeclSpace ds)
477 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
480 DeclSpace parentContainer = ds;
481 while (parentContainer != null && parentContainer.ModFlags != 0) {
482 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
484 parentContainer = parentContainer.Parent;
490 /// Resolve CLSCompliantAttribute value or gets cached value.
492 bool GetClsCompliantAttributeValue (DeclSpace ds)
494 if (OptAttributes != null) {
495 Attribute cls_attribute = OptAttributes.Search (
496 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
497 if (cls_attribute != null) {
498 caching_flags |= Flags.HasClsCompliantAttribute;
499 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
502 return ds.GetClsCompliantAttributeValue ();
506 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
508 protected bool HasClsCompliantAttribute {
510 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
515 /// It helps to handle error 102 & 111 detection
517 public virtual bool MarkForDuplicationCheck ()
523 /// The main virtual method for CLS-Compliant verifications.
524 /// The method returns true if member is CLS-Compliant and false if member is not
525 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
526 /// and add their extra verifications.
528 protected virtual bool VerifyClsCompliance (DeclSpace ds)
530 if (!IsClsCompliaceRequired (ds)) {
531 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
532 if (!IsExposedFromAssembly (ds))
533 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
534 if (!CodeGen.Assembly.IsClsCompliant)
535 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
540 if (!CodeGen.Assembly.IsClsCompliant) {
541 if (HasClsCompliantAttribute) {
542 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
547 int index = Name.LastIndexOf ('.');
548 if (Name [index > 0 ? index + 1 : 0] == '_') {
549 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
554 protected abstract void VerifyObsoleteAttribute ();
557 // Raised (and passed an XmlElement that contains the comment)
558 // when GenerateDocComment is writing documentation expectedly.
560 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
565 // Returns a string that represents the signature for this
566 // member which should be used in XML documentation.
568 public virtual string GetDocCommentName (DeclSpace ds)
570 if (ds == null || this is DeclSpace)
571 return DocCommentHeader + Name;
573 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
577 // Generates xml doc comments (if any), and if required,
578 // handle warning report.
580 internal virtual void GenerateDocComment (DeclSpace ds)
582 DocUtil.GenerateDocComment (this, ds);
587 /// Base class for structs, classes, enumerations and interfaces.
590 /// They all create new declaration spaces. This
591 /// provides the common foundation for managing those name
594 public abstract class DeclSpace : MemberCore, IAlias {
596 /// This points to the actual definition that is being
597 /// created with System.Reflection.Emit
599 public TypeBuilder TypeBuilder;
602 /// If we are a generic type, this is the type we are
603 /// currently defining. We need to lookup members on this
604 /// instead of the TypeBuilder.
606 public Type CurrentType;
609 // This is the namespace in which this typecontainer
610 // was declared. We use this to resolve names.
612 public NamespaceEntry NamespaceEntry;
614 private Hashtable Cache = new Hashtable ();
616 public readonly string Basename;
618 protected Hashtable defined_names;
620 readonly bool is_generic;
621 readonly int count_type_params;
622 readonly int count_current_type_params;
624 // The emit context for toplevel objects.
625 protected EmitContext ec;
627 public EmitContext EmitContext {
632 // Whether we are Generic
634 public bool IsGeneric {
638 else if (Parent != null)
639 return Parent.IsGeneric;
645 static string[] attribute_targets = new string [] { "type" };
647 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
648 Attributes attrs, Location l)
649 : base (parent, name, attrs, l)
652 Basename = name.Basename;
653 defined_names = new Hashtable ();
654 if (name.TypeArguments != null) {
656 count_type_params = count_current_type_params = name.TypeArguments.Count;
659 count_type_params += parent.count_type_params;
663 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
665 protected bool AddToContainer (MemberCore symbol, string name)
667 if (name == Basename && !(this is Interface) && !(this is Enum)) {
668 if (symbol is TypeParameter)
669 Report.Error (694, "Type parameter `{0}' has same name as " +
670 "containing type or method", name);
672 Report.SymbolRelatedToPreviousError (this);
673 Report.Error (542, "'{0}': member names cannot be the same as their " +
674 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
679 MemberCore mc = (MemberCore) defined_names [name];
682 defined_names.Add (name, symbol);
686 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
689 if (symbol is TypeParameter)
690 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", name);
692 Report.SymbolRelatedToPreviousError (mc);
693 Report.Error (102, symbol.Location,
694 "The type '{0}' already contains a definition for '{1}'",
695 GetSignatureForError (), name);
700 public void RecordDecl ()
702 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
703 NamespaceEntry.DefineName (MemberName.Basename, this);
707 /// Returns the MemberCore associated with a given name in the declaration
708 /// space. It doesn't return method based symbols !!
711 public MemberCore GetDefinition (string name)
713 return (MemberCore)defined_names [name];
716 bool in_transit = false;
719 /// This function is used to catch recursive definitions
722 public bool InTransit {
733 // root_types contains all the types. All TopLevel types
734 // hence have a parent that points to `root_types', that is
735 // why there is a non-obvious test down here.
737 public bool IsTopLevel {
740 if (Parent.Parent == null)
747 public virtual void CloseType ()
749 if ((caching_flags & Flags.CloseTypeCreated) == 0){
751 TypeBuilder.CreateType ();
754 // The try/catch is needed because
755 // nested enumerations fail to load when they
758 // Even if this is the right order (enumerations
759 // declared after types).
761 // Note that this still creates the type and
762 // it is possible to save it
764 caching_flags |= Flags.CloseTypeCreated;
768 protected virtual TypeAttributes TypeAttr {
770 return CodeGen.Module.DefaultCharSetType;
775 /// Should be overriten by the appropriate declaration space
777 public abstract TypeBuilder DefineType ();
780 /// Define all members, but don't apply any attributes or do anything which may
781 /// access not-yet-defined classes. This method also creates the MemberCache.
783 public abstract bool DefineMembers (TypeContainer parent);
786 // Whether this is an `unsafe context'
788 public bool UnsafeContext {
790 if ((ModFlags & Modifiers.UNSAFE) != 0)
793 return Parent.UnsafeContext;
798 EmitContext type_resolve_ec;
799 protected EmitContext TypeResolveEmitContext {
801 if (type_resolve_ec == null) {
802 // FIXME: I think this should really be one of:
804 // a. type_resolve_ec = Parent.EmitContext;
805 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
807 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
809 type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
811 return type_resolve_ec;
816 // Resolves the expression `e' for a type, and will recursively define
817 // types. This should only be used for resolving base types.
819 public TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
821 TypeResolveEmitContext.loc = loc;
822 TypeResolveEmitContext.ContainerType = TypeBuilder;
823 if (this is GenericMethod)
824 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
826 TypeResolveEmitContext.ContainerType = TypeBuilder;
828 return e.ResolveAsTypeTerminal (TypeResolveEmitContext);
831 public bool CheckAccessLevel (Type check_type)
834 if ((this is GenericMethod) || (this is Iterator))
835 tb = Parent.TypeBuilder;
839 if (check_type.IsGenericInstance)
840 check_type = check_type.GetGenericTypeDefinition ();
842 if (check_type == tb)
845 if (TypeBuilder == null)
846 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
847 // However, this is invoked again later -- so safe to return true.
848 // May also be null when resolving top-level attributes.
851 if (check_type.IsGenericParameter)
852 return true; // FIXME
854 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
857 // Broken Microsoft runtime, return public for arrays, no matter what
858 // the accessibility is for their underlying class, and they return
859 // NonPublic visibility for pointers
861 if (check_type.IsArray || check_type.IsPointer)
862 return CheckAccessLevel (TypeManager.GetElementType (check_type));
865 case TypeAttributes.Public:
868 case TypeAttributes.NotPublic:
870 if (TypeBuilder == null)
871 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
872 // However, this is invoked again later -- so safe to return true.
873 // May also be null when resolving top-level attributes.
876 // This test should probably use the declaringtype.
878 return check_type.Assembly == TypeBuilder.Assembly;
880 case TypeAttributes.NestedPublic:
883 case TypeAttributes.NestedPrivate:
884 return NestedAccessible (tb, check_type);
886 case TypeAttributes.NestedFamily:
888 // Only accessible to methods in current type or any subtypes
890 return FamilyAccessible (tb, check_type);
892 case TypeAttributes.NestedFamANDAssem:
893 return (check_type.Assembly == tb.Assembly) &&
894 FamilyAccessible (tb, check_type);
896 case TypeAttributes.NestedFamORAssem:
897 return (check_type.Assembly == tb.Assembly) ||
898 FamilyAccessible (tb, check_type);
900 case TypeAttributes.NestedAssembly:
901 return check_type.Assembly == tb.Assembly;
904 Console.WriteLine ("HERE: " + check_attr);
909 protected bool NestedAccessible (Type tb, Type check_type)
911 Type declaring = check_type.DeclaringType;
912 return TypeBuilder == declaring ||
913 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
916 protected bool FamilyAccessible (Type tb, Type check_type)
918 Type declaring = check_type.DeclaringType;
919 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
922 return NestedAccessible (tb, check_type);
925 // Access level of a type.
927 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
928 // Public Assembly Protected
929 Protected = (0 << 0) | (0 << 1) | (X << 2),
930 Public = (X << 0) | (X << 1) | (X << 2),
931 Private = (0 << 0) | (0 << 1) | (0 << 2),
932 Internal = (0 << 0) | (X << 1) | (0 << 2),
933 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
936 static AccessLevel GetAccessLevelFromModifiers (int flags)
938 if ((flags & Modifiers.INTERNAL) != 0) {
940 if ((flags & Modifiers.PROTECTED) != 0)
941 return AccessLevel.ProtectedOrInternal;
943 return AccessLevel.Internal;
945 } else if ((flags & Modifiers.PROTECTED) != 0)
946 return AccessLevel.Protected;
947 else if ((flags & Modifiers.PRIVATE) != 0)
948 return AccessLevel.Private;
950 return AccessLevel.Public;
953 // What is the effective access level of this?
955 AccessLevel EffectiveAccessLevel {
957 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
958 if (!IsTopLevel && (Parent != null))
959 return myAccess & Parent.EffectiveAccessLevel;
964 // Return the access level for type `t'
965 static AccessLevel TypeEffectiveAccessLevel (Type t)
968 return AccessLevel.Public;
969 if (t.IsNestedPrivate)
970 return AccessLevel.Private;
972 return AccessLevel.Internal;
974 // By now, it must be nested
975 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
977 if (t.IsNestedPublic)
979 if (t.IsNestedAssembly)
980 return parentLevel & AccessLevel.Internal;
981 if (t.IsNestedFamily)
982 return parentLevel & AccessLevel.Protected;
983 if (t.IsNestedFamORAssem)
984 return parentLevel & AccessLevel.ProtectedOrInternal;
985 if (t.IsNestedFamANDAssem)
986 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
988 // nested private is taken care of
990 throw new Exception ("I give up, what are you?");
994 // This answers `is the type P, as accessible as a member M which has the
995 // accessability @flags which is declared as a nested member of the type T, this declspace'
997 public bool AsAccessible (Type p, int flags)
999 if (p.IsGenericParameter)
1000 return true; // FIXME
1003 // 1) if M is private, its accessability is the same as this declspace.
1004 // we already know that P is accessible to T before this method, so we
1008 if ((flags & Modifiers.PRIVATE) != 0)
1011 while (p.IsArray || p.IsPointer || p.IsByRef)
1012 p = TypeManager.GetElementType (p);
1014 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1015 AccessLevel mAccess = this.EffectiveAccessLevel &
1016 GetAccessLevelFromModifiers (flags);
1018 // for every place from which we can access M, we must
1019 // be able to access P as well. So, we want
1020 // For every bit in M and P, M_i -> P_1 == true
1021 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1023 return ~ (~ mAccess | pAccess) == 0;
1026 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1028 Report.Error (104, loc,
1029 "`{0}' is an ambiguous reference ({1} or {2})",
1034 // Return the nested type with name @name. Ensures that the nested type
1035 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1037 public virtual Type FindNestedType (string name)
1042 private Type LookupNestedTypeInHierarchy (string name)
1044 // if the member cache has been created, lets use it.
1045 // the member cache is MUCH faster.
1046 if (MemberCache != null)
1047 return MemberCache.FindNestedType (name);
1049 // no member cache. Do it the hard way -- reflection
1051 for (Type current_type = TypeBuilder;
1052 current_type != null && current_type != TypeManager.object_type;
1053 current_type = current_type.BaseType) {
1054 if (current_type is TypeBuilder) {
1055 DeclSpace decl = this;
1056 if (current_type != TypeBuilder)
1057 decl = TypeManager.LookupDeclSpace (current_type);
1058 t = decl.FindNestedType (name);
1060 t = TypeManager.GetNestedType (current_type, name);
1063 if (t != null && CheckAccessLevel (t))
1071 // Public function used to locate types, this can only
1072 // be used after the ResolveTree function has been invoked.
1074 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1076 // Returns: Type or null if they type can not be found.
1078 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1080 if (this is PartialContainer)
1081 throw new InternalErrorException ("Should not get here");
1083 if (Cache.Contains (name))
1084 return (FullNamedExpression) Cache [name];
1086 FullNamedExpression e;
1087 Type t = LookupNestedTypeInHierarchy (name);
1089 e = new TypeExpression (t, Location.Null);
1090 else if (Parent != null && Parent != RootContext.Tree.Types)
1091 e = Parent.LookupType (name, loc, ignore_cs0104);
1093 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1100 /// This function is broken and not what you're looking for. It should only
1101 /// be used while the type is still being created since it doesn't use the cache
1102 /// and relies on the filter doing the member name check.
1104 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1105 MemberFilter filter, object criteria);
1108 /// If we have a MemberCache, return it. This property may return null if the
1109 /// class doesn't have a member cache or while it's still being created.
1111 public abstract MemberCache MemberCache {
1115 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1117 if (a.Type == TypeManager.required_attr_type) {
1118 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1121 TypeBuilder.SetCustomAttribute (cb);
1125 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1126 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1128 public bool GetClsCompliantAttributeValue ()
1130 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1131 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1133 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1135 if (OptAttributes != null) {
1136 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1137 if (cls_attribute != null) {
1138 caching_flags |= Flags.HasClsCompliantAttribute;
1139 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1140 caching_flags |= Flags.ClsCompliantAttributeTrue;
1147 if (Parent == null) {
1148 if (CodeGen.Assembly.IsClsCompliant) {
1149 caching_flags |= Flags.ClsCompliantAttributeTrue;
1155 if (Parent.GetClsCompliantAttributeValue ()) {
1156 caching_flags |= Flags.ClsCompliantAttributeTrue;
1163 // Extensions for generics
1165 TypeParameter[] type_params;
1166 TypeParameter[] type_param_list;
1168 protected string GetInstantiationName ()
1170 StringBuilder sb = new StringBuilder (Name);
1172 for (int i = 0; i < type_param_list.Length; i++) {
1175 sb.Append (type_param_list [i].Name);
1178 return sb.ToString ();
1181 bool check_type_parameter (ArrayList list, int start, string name)
1183 for (int i = 0; i < start; i++) {
1184 TypeParameter param = (TypeParameter) list [i];
1186 if (param.Name != name)
1189 if (RootContext.WarningLevel >= 3)
1192 "Type parameter `{0}' has same name " +
1193 "as type parameter from outer type `{1}'",
1194 name, Parent.GetInstantiationName ());
1202 TypeParameter[] initialize_type_params ()
1204 if (type_param_list != null)
1205 return type_param_list;
1207 DeclSpace the_parent = Parent;
1208 if (this is GenericMethod)
1212 TypeParameter[] parent_params = null;
1213 if ((the_parent != null) && the_parent.IsGeneric) {
1214 parent_params = the_parent.initialize_type_params ();
1215 start = parent_params != null ? parent_params.Length : 0;
1218 ArrayList list = new ArrayList ();
1219 if (parent_params != null)
1220 list.AddRange (parent_params);
1222 int count = type_params != null ? type_params.Length : 0;
1223 for (int i = 0; i < count; i++) {
1224 TypeParameter param = type_params [i];
1225 check_type_parameter (list, start, param.Name);
1229 type_param_list = new TypeParameter [list.Count];
1230 list.CopyTo (type_param_list, 0);
1231 return type_param_list;
1234 public virtual void SetParameterInfo (ArrayList constraints_list)
1237 if (constraints_list != null) {
1239 80, Location, "Contraints are not allowed " +
1240 "on non-generic declarations");
1246 string[] names = MemberName.TypeArguments.GetDeclarations ();
1247 type_params = new TypeParameter [names.Length];
1250 // Register all the names
1252 for (int i = 0; i < type_params.Length; i++) {
1253 string name = names [i];
1255 Constraints constraints = null;
1256 if (constraints_list != null) {
1257 foreach (Constraints constraint in constraints_list) {
1258 if (constraint.TypeParameter == name) {
1259 constraints = constraint;
1265 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1267 AddToContainer (type_params [i], name);
1271 public TypeParameter[] TypeParameters {
1274 throw new InvalidOperationException ();
1275 if (type_param_list == null)
1276 initialize_type_params ();
1278 return type_param_list;
1282 protected TypeParameter[] CurrentTypeParameters {
1285 throw new InvalidOperationException ();
1286 if (type_params != null)
1289 return new TypeParameter [0];
1293 public int CountTypeParameters {
1295 return count_type_params;
1299 public int CountCurrentTypeParameters {
1301 return count_current_type_params;
1305 public TypeParameterExpr LookupGeneric (string name, Location loc)
1310 foreach (TypeParameter type_param in CurrentTypeParameters) {
1311 if (type_param.Name != name)
1314 return new TypeParameterExpr (type_param, loc);
1318 return Parent.LookupGeneric (name, loc);
1323 bool IAlias.IsType {
1324 get { return true; }
1327 string IAlias.Name {
1328 get { return Name; }
1331 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1333 if (TypeBuilder == null)
1334 throw new InvalidOperationException ();
1336 if (CurrentType != null)
1337 return new TypeExpression (CurrentType, Location);
1339 return new TypeExpression (TypeBuilder, Location);
1342 public override string[] ValidAttributeTargets {
1344 return attribute_targets;
1350 /// This is a readonly list of MemberInfo's.
1352 public class MemberList : IList {
1353 public readonly IList List;
1357 /// Create a new MemberList from the given IList.
1359 public MemberList (IList list)
1364 this.List = new ArrayList ();
1369 /// Concatenate the ILists `first' and `second' to a new MemberList.
1371 public MemberList (IList first, IList second)
1373 ArrayList list = new ArrayList ();
1374 list.AddRange (first);
1375 list.AddRange (second);
1380 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1383 /// Cast the MemberList into a MemberInfo[] array.
1386 /// This is an expensive operation, only use it if it's really necessary.
1388 public static explicit operator MemberInfo [] (MemberList list)
1390 Timer.StartTimer (TimerType.MiscTimer);
1391 MemberInfo [] result = new MemberInfo [list.Count];
1392 list.CopyTo (result, 0);
1393 Timer.StopTimer (TimerType.MiscTimer);
1405 public bool IsSynchronized {
1407 return List.IsSynchronized;
1411 public object SyncRoot {
1413 return List.SyncRoot;
1417 public void CopyTo (Array array, int index)
1419 List.CopyTo (array, index);
1424 public IEnumerator GetEnumerator ()
1426 return List.GetEnumerator ();
1431 public bool IsFixedSize {
1437 public bool IsReadOnly {
1443 object IList.this [int index] {
1445 return List [index];
1449 throw new NotSupportedException ();
1453 // FIXME: try to find out whether we can avoid the cast in this indexer.
1454 public MemberInfo this [int index] {
1456 return (MemberInfo) List [index];
1460 public int Add (object value)
1462 throw new NotSupportedException ();
1465 public void Clear ()
1467 throw new NotSupportedException ();
1470 public bool Contains (object value)
1472 return List.Contains (value);
1475 public int IndexOf (object value)
1477 return List.IndexOf (value);
1480 public void Insert (int index, object value)
1482 throw new NotSupportedException ();
1485 public void Remove (object value)
1487 throw new NotSupportedException ();
1490 public void RemoveAt (int index)
1492 throw new NotSupportedException ();
1497 /// This interface is used to get all members of a class when creating the
1498 /// member cache. It must be implemented by all DeclSpace derivatives which
1499 /// want to support the member cache and by TypeHandle to get caching of
1500 /// non-dynamic types.
1502 public interface IMemberContainer {
1504 /// The name of the IMemberContainer. This is only used for
1505 /// debugging purposes.
1512 /// The type of this IMemberContainer.
1519 /// Returns the IMemberContainer of the base class or null if this
1520 /// is an interface or TypeManger.object_type.
1521 /// This is used when creating the member cache for a class to get all
1522 /// members from the base class.
1524 MemberCache BaseCache {
1529 /// Whether this is an interface.
1536 /// Returns all members of this class with the corresponding MemberTypes
1537 /// and BindingFlags.
1540 /// When implementing this method, make sure not to return any inherited
1541 /// members and check the MemberTypes and BindingFlags properly.
1542 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1543 /// get the BindingFlags (static/non-static,public/non-public) in the
1544 /// MemberInfo class, but the cache needs this information. That's why
1545 /// this method is called multiple times with different BindingFlags.
1547 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1550 /// Return the container's member cache.
1552 MemberCache MemberCache {
1558 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1559 /// member lookups. It has a member name based hash table; it maps each member
1560 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1561 /// and the BindingFlags that were initially used to get it. The cache contains
1562 /// all members of the current class and all inherited members. If this cache is
1563 /// for an interface types, it also contains all inherited members.
1565 /// There are two ways to get a MemberCache:
1566 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1567 /// use the DeclSpace.MemberCache property.
1568 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1569 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1571 public class MemberCache {
1572 public readonly IMemberContainer Container;
1573 protected Hashtable member_hash;
1574 protected Hashtable method_hash;
1577 /// Create a new MemberCache for the given IMemberContainer `container'.
1579 public MemberCache (IMemberContainer container)
1581 this.Container = container;
1583 Timer.IncrementCounter (CounterType.MemberCache);
1584 Timer.StartTimer (TimerType.CacheInit);
1586 // If we have a base class (we have a base class unless we're
1587 // TypeManager.object_type), we deep-copy its MemberCache here.
1588 if (Container.BaseCache != null)
1589 member_hash = SetupCache (Container.BaseCache);
1591 member_hash = new Hashtable ();
1593 // If this is neither a dynamic type nor an interface, create a special
1594 // method cache with all declared and inherited methods.
1595 Type type = container.Type;
1596 if (!(type is TypeBuilder) && !type.IsInterface &&
1597 // !(type.IsGenericInstance && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1598 !type.IsGenericInstance &&
1599 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1600 method_hash = new Hashtable ();
1604 // Add all members from the current class.
1605 AddMembers (Container);
1607 Timer.StopTimer (TimerType.CacheInit);
1610 public MemberCache (Type[] ifaces)
1613 // The members of this cache all belong to other caches.
1614 // So, 'Container' will not be used.
1616 this.Container = null;
1618 member_hash = new Hashtable ();
1622 foreach (Type itype in ifaces)
1623 AddCacheContents (TypeManager.LookupMemberCache (itype));
1627 /// Bootstrap this member cache by doing a deep-copy of our base.
1629 Hashtable SetupCache (MemberCache base_class)
1631 Hashtable hash = new Hashtable ();
1633 if (base_class == null)
1636 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1637 while (it.MoveNext ()) {
1638 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1644 void ClearDeclaredOnly (Hashtable hash)
1646 IDictionaryEnumerator it = hash.GetEnumerator ();
1647 while (it.MoveNext ()) {
1648 foreach (CacheEntry ce in (ArrayList) it.Value)
1649 ce.EntryType &= ~EntryType.Declared;
1654 /// Add the contents of `cache' to the member_hash.
1656 void AddCacheContents (MemberCache cache)
1658 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1659 while (it.MoveNext ()) {
1660 ArrayList list = (ArrayList) member_hash [it.Key];
1662 member_hash [it.Key] = list = new ArrayList ();
1664 ArrayList entries = (ArrayList) it.Value;
1665 for (int i = entries.Count-1; i >= 0; i--) {
1666 CacheEntry entry = (CacheEntry) entries [i];
1668 if (entry.Container != cache.Container)
1676 /// Add all members from class `container' to the cache.
1678 void AddMembers (IMemberContainer container)
1680 // We need to call AddMembers() with a single member type at a time
1681 // to get the member type part of CacheEntry.EntryType right.
1682 if (!container.IsInterface) {
1683 AddMembers (MemberTypes.Constructor, container);
1684 AddMembers (MemberTypes.Field, container);
1686 AddMembers (MemberTypes.Method, container);
1687 AddMembers (MemberTypes.Property, container);
1688 AddMembers (MemberTypes.Event, container);
1689 // Nested types are returned by both Static and Instance searches.
1690 AddMembers (MemberTypes.NestedType,
1691 BindingFlags.Static | BindingFlags.Public, container);
1692 AddMembers (MemberTypes.NestedType,
1693 BindingFlags.Static | BindingFlags.NonPublic, container);
1696 void AddMembers (MemberTypes mt, IMemberContainer container)
1698 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1699 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1700 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1701 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1705 /// Add all members from class `container' with the requested MemberTypes and
1706 /// BindingFlags to the cache. This method is called multiple times with different
1707 /// MemberTypes and BindingFlags.
1709 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1711 MemberList members = container.GetMembers (mt, bf);
1713 foreach (MemberInfo member in members) {
1714 string name = member.Name;
1716 int pos = name.IndexOf ('<');
1718 name = name.Substring (0, pos);
1720 // We use a name-based hash table of ArrayList's.
1721 ArrayList list = (ArrayList) member_hash [name];
1723 list = new ArrayList ();
1724 member_hash.Add (name, list);
1727 // When this method is called for the current class, the list will
1728 // already contain all inherited members from our base classes.
1729 // We cannot add new members in front of the list since this'd be an
1730 // expensive operation, that's why the list is sorted in reverse order
1731 // (ie. members from the current class are coming last).
1732 list.Add (new CacheEntry (container, member, mt, bf));
1737 /// Add all declared and inherited methods from class `type' to the method cache.
1739 void AddMethods (Type type)
1741 AddMethods (BindingFlags.Static | BindingFlags.Public |
1742 BindingFlags.FlattenHierarchy, type);
1743 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1744 BindingFlags.FlattenHierarchy, type);
1745 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1746 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1749 void AddMethods (BindingFlags bf, Type type)
1752 // Consider the case:
1754 // class X { public virtual int f() {} }
1757 // When processing 'Y', the method_cache will already have a copy of 'f',
1758 // with ReflectedType == X. However, we want to ensure that its ReflectedType == Y
1760 MethodBase [] members = type.GetMethods (bf);
1762 Array.Reverse (members);
1764 foreach (MethodBase member in members) {
1765 string name = member.Name;
1767 // We use a name-based hash table of ArrayList's.
1768 ArrayList list = (ArrayList) method_hash [name];
1770 list = new ArrayList ();
1771 method_hash.Add (name, list);
1774 MethodInfo curr = (MethodInfo) member;
1775 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1776 MethodInfo base_method = curr.GetBaseDefinition ();
1778 if (base_method == curr) {
1780 // Both mcs and CSC 1.1 seem to emit a somewhat broken
1781 // ...Invoke () function for delegates: it's missing a 'newslot'.
1782 // CSC 2.0 emits a 'newslot' for a delegate's Invoke.
1784 // Also, CSC 1.1 appears to emit 'Finalize' without a newslot.
1786 if ((member.Name != "Invoke" ||
1787 !TypeManager.IsDelegateType (type)) &&
1788 (member.Name != "Finalize" ||
1789 type != TypeManager.object_type)) {
1790 Report.SymbolRelatedToPreviousError (base_method);
1791 Report.Warning (-28,
1792 "The method '{0}' is marked 'override'," +
1793 " but doesn't appear to override any virtual or abstract method:" +
1794 " it may be ignored during overload resolution",
1795 TypeManager.CSharpSignature (base_method));
1801 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1805 // Unfortunately, the elements returned by Type.GetMethods() aren't
1806 // sorted so we need to do this check for every member.
1807 BindingFlags new_bf = bf;
1808 if (member.DeclaringType == type)
1809 new_bf |= BindingFlags.DeclaredOnly;
1811 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1816 /// Compute and return a appropriate `EntryType' magic number for the given
1817 /// MemberTypes and BindingFlags.
1819 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1821 EntryType type = EntryType.None;
1823 if ((mt & MemberTypes.Constructor) != 0)
1824 type |= EntryType.Constructor;
1825 if ((mt & MemberTypes.Event) != 0)
1826 type |= EntryType.Event;
1827 if ((mt & MemberTypes.Field) != 0)
1828 type |= EntryType.Field;
1829 if ((mt & MemberTypes.Method) != 0)
1830 type |= EntryType.Method;
1831 if ((mt & MemberTypes.Property) != 0)
1832 type |= EntryType.Property;
1833 // Nested types are returned by static and instance searches.
1834 if ((mt & MemberTypes.NestedType) != 0)
1835 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1837 if ((bf & BindingFlags.Instance) != 0)
1838 type |= EntryType.Instance;
1839 if ((bf & BindingFlags.Static) != 0)
1840 type |= EntryType.Static;
1841 if ((bf & BindingFlags.Public) != 0)
1842 type |= EntryType.Public;
1843 if ((bf & BindingFlags.NonPublic) != 0)
1844 type |= EntryType.NonPublic;
1845 if ((bf & BindingFlags.DeclaredOnly) != 0)
1846 type |= EntryType.Declared;
1852 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1853 /// denote multiple member types. Returns true if the given flags value denotes a
1854 /// single member types.
1856 public static bool IsSingleMemberType (MemberTypes mt)
1859 case MemberTypes.Constructor:
1860 case MemberTypes.Event:
1861 case MemberTypes.Field:
1862 case MemberTypes.Method:
1863 case MemberTypes.Property:
1864 case MemberTypes.NestedType:
1873 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1874 /// number to speed up the searching process.
1877 protected enum EntryType {
1882 MaskStatic = Instance|Static,
1886 MaskProtection = Public|NonPublic,
1890 Constructor = 0x020,
1897 MaskType = Constructor|Event|Field|Method|Property|NestedType
1900 protected class CacheEntry {
1901 public readonly IMemberContainer Container;
1902 public EntryType EntryType;
1903 public MemberInfo Member;
1905 public CacheEntry (IMemberContainer container, MemberInfo member,
1906 MemberTypes mt, BindingFlags bf)
1908 this.Container = container;
1909 this.Member = member;
1910 this.EntryType = GetEntryType (mt, bf);
1913 public override string ToString ()
1915 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1921 /// This is called each time we're walking up one level in the class hierarchy
1922 /// and checks whether we can abort the search since we've already found what
1923 /// we were looking for.
1925 protected bool DoneSearching (ArrayList list)
1928 // We've found exactly one member in the current class and it's not
1929 // a method or constructor.
1931 if (list.Count == 1 && !(list [0] is MethodBase))
1935 // Multiple properties: we query those just to find out the indexer
1938 if ((list.Count > 0) && (list [0] is PropertyInfo))
1945 /// Looks up members with name `name'. If you provide an optional
1946 /// filter function, it'll only be called with members matching the
1947 /// requested member name.
1949 /// This method will try to use the cache to do the lookup if possible.
1951 /// Unlike other FindMembers implementations, this method will always
1952 /// check all inherited members - even when called on an interface type.
1954 /// If you know that you're only looking for methods, you should use
1955 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1956 /// When doing a method-only search, it'll try to use a special method
1957 /// cache (unless it's a dynamic type or an interface) and the returned
1958 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1959 /// The lookup process will automatically restart itself in method-only
1960 /// search mode if it discovers that it's about to return methods.
1962 ArrayList global = new ArrayList ();
1963 bool using_global = false;
1965 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1967 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1968 MemberFilter filter, object criteria)
1971 throw new Exception ();
1973 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1974 bool method_search = mt == MemberTypes.Method;
1975 // If we have a method cache and we aren't already doing a method-only search,
1976 // then we restart a method search if the first match is a method.
1977 bool do_method_search = !method_search && (method_hash != null);
1979 ArrayList applicable;
1981 // If this is a method-only search, we try to use the method cache if
1982 // possible; a lookup in the method cache will return a MemberInfo with
1983 // the correct ReflectedType for inherited methods.
1985 if (method_search && (method_hash != null))
1986 applicable = (ArrayList) method_hash [name];
1988 applicable = (ArrayList) member_hash [name];
1990 if (applicable == null)
1991 return emptyMemberInfo;
1994 // 32 slots gives 53 rss/54 size
1995 // 2/4 slots gives 55 rss
1997 // Strange: from 25,000 calls, only 1,800
1998 // are above 2. Why does this impact it?
2001 using_global = true;
2003 Timer.StartTimer (TimerType.CachedLookup);
2005 EntryType type = GetEntryType (mt, bf);
2007 IMemberContainer current = Container;
2010 // `applicable' is a list of all members with the given member name `name'
2011 // in the current class and all its base classes. The list is sorted in
2012 // reverse order due to the way how the cache is initialy created (to speed
2013 // things up, we're doing a deep-copy of our base).
2015 for (int i = applicable.Count-1; i >= 0; i--) {
2016 CacheEntry entry = (CacheEntry) applicable [i];
2018 // This happens each time we're walking one level up in the class
2019 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2020 // the first time this happens (this may already happen in the first
2021 // iteration of this loop if there are no members with the name we're
2022 // looking for in the current class).
2023 if (entry.Container != current) {
2024 if (declared_only || DoneSearching (global))
2027 current = entry.Container;
2030 // Is the member of the correct type ?
2031 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2034 // Is the member static/non-static ?
2035 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2038 // Apply the filter to it.
2039 if (filter (entry.Member, criteria)) {
2040 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2041 do_method_search = false;
2042 global.Add (entry.Member);
2046 Timer.StopTimer (TimerType.CachedLookup);
2048 // If we have a method cache and we aren't already doing a method-only
2049 // search, we restart in method-only search mode if the first match is
2050 // a method. This ensures that we return a MemberInfo with the correct
2051 // ReflectedType for inherited methods.
2052 if (do_method_search && (global.Count > 0)){
2053 using_global = false;
2055 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2058 using_global = false;
2059 MemberInfo [] copy = new MemberInfo [global.Count];
2060 global.CopyTo (copy);
2064 // find the nested type @name in @this.
2065 public Type FindNestedType (string name)
2067 ArrayList applicable = (ArrayList) member_hash [name];
2068 if (applicable == null)
2071 for (int i = applicable.Count-1; i >= 0; i--) {
2072 CacheEntry entry = (CacheEntry) applicable [i];
2073 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2074 return (Type) entry.Member;
2081 // This finds the method or property for us to override. invocationType is the type where
2082 // the override is going to be declared, name is the name of the method/property, and
2083 // paramTypes is the parameters, if any to the method or property
2085 // Because the MemberCache holds members from this class and all the base classes,
2086 // we can avoid tons of reflection stuff.
2088 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2090 ArrayList applicable;
2091 if (method_hash != null && !is_property)
2092 applicable = (ArrayList) method_hash [name];
2094 applicable = (ArrayList) member_hash [name];
2096 if (applicable == null)
2099 // Walk the chain of methods, starting from the top.
2101 for (int i = applicable.Count - 1; i >= 0; i--) {
2102 CacheEntry entry = (CacheEntry) applicable [i];
2104 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2107 PropertyInfo pi = null;
2108 MethodInfo mi = null;
2109 FieldInfo fi = null;
2110 Type [] cmpAttrs = null;
2113 if ((entry.EntryType & EntryType.Field) != 0) {
2114 fi = (FieldInfo)entry.Member;
2116 // TODO: For this case we ignore member type
2117 //fb = TypeManager.GetField (fi);
2118 //cmpAttrs = new Type[] { fb.MemberType };
2120 pi = (PropertyInfo) entry.Member;
2121 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2124 mi = (MethodInfo) entry.Member;
2125 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2129 // TODO: Almost duplicate !
2131 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2132 case FieldAttributes.Private:
2134 // A private method is Ok if we are a nested subtype.
2135 // The spec actually is not very clear about this, see bug 52458.
2137 if (invocationType != entry.Container.Type &
2138 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2142 case FieldAttributes.FamANDAssem:
2143 case FieldAttributes.Assembly:
2145 // Check for assembly methods
2147 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2151 return entry.Member;
2155 // Check the arguments
2157 if (cmpAttrs.Length != paramTypes.Length)
2160 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2161 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2166 // get one of the methods because this has the visibility info.
2169 mi = pi.GetGetMethod (true);
2171 mi = pi.GetSetMethod (true);
2177 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2178 case MethodAttributes.Private:
2180 // A private method is Ok if we are a nested subtype.
2181 // The spec actually is not very clear about this, see bug 52458.
2183 if (invocationType.Equals (entry.Container.Type) ||
2184 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2185 return entry.Member;
2188 case MethodAttributes.FamANDAssem:
2189 case MethodAttributes.Assembly:
2191 // Check for assembly methods
2193 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2194 return entry.Member;
2199 // A protected method is ok, because we are overriding.
2200 // public is always ok.
2202 return entry.Member;
2212 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2213 /// We handle two cases. The first is for types without parameters (events, field, properties).
2214 /// The second are methods, indexers and this is why ignore_complex_types is here.
2215 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2217 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2219 ArrayList applicable = null;
2221 if (method_hash != null)
2222 applicable = (ArrayList) method_hash [name];
2224 if (applicable != null) {
2225 for (int i = applicable.Count - 1; i >= 0; i--) {
2226 CacheEntry entry = (CacheEntry) applicable [i];
2227 if ((entry.EntryType & EntryType.Public) != 0)
2228 return entry.Member;
2232 if (member_hash == null)
2234 applicable = (ArrayList) member_hash [name];
2236 if (applicable != null) {
2237 for (int i = applicable.Count - 1; i >= 0; i--) {
2238 CacheEntry entry = (CacheEntry) applicable [i];
2239 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2240 if (ignore_complex_types) {
2241 if ((entry.EntryType & EntryType.Method) != 0)
2244 // Does exist easier way how to detect indexer ?
2245 if ((entry.EntryType & EntryType.Property) != 0) {
2246 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2247 if (arg_types.Length > 0)
2251 return entry.Member;
2258 Hashtable locase_table;
2261 /// Builds low-case table for CLS Compliance test
2263 public Hashtable GetPublicMembers ()
2265 if (locase_table != null)
2266 return locase_table;
2268 locase_table = new Hashtable ();
2269 foreach (DictionaryEntry entry in member_hash) {
2270 ArrayList members = (ArrayList)entry.Value;
2271 for (int ii = 0; ii < members.Count; ++ii) {
2272 CacheEntry member_entry = (CacheEntry) members [ii];
2274 if ((member_entry.EntryType & EntryType.Public) == 0)
2277 // TODO: Does anyone know easier way how to detect that member is internal ?
2278 switch (member_entry.EntryType & EntryType.MaskType) {
2279 case EntryType.Constructor:
2282 case EntryType.Field:
2283 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2287 case EntryType.Method:
2288 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2292 case EntryType.Property:
2293 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2294 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2298 case EntryType.Event:
2299 EventInfo ei = (EventInfo)member_entry.Member;
2300 MethodInfo mi = ei.GetAddMethod ();
2301 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2305 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2306 locase_table [lcase] = member_entry.Member;
2310 return locase_table;
2313 public Hashtable Members {
2320 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2322 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2324 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2326 for (int i = 0; i < al.Count; ++i) {
2327 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2330 if (entry.Member == this_builder)
2333 if ((entry.EntryType & tested_type) != tested_type)
2336 MethodBase method_to_compare = (MethodBase)entry.Member;
2337 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2340 IMethodData md = TypeManager.GetMethod (method_to_compare);
2342 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2343 // However it is exactly what csc does.
2344 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2347 Report.SymbolRelatedToPreviousError (entry.Member);
2348 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());