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 MethodName {
116 return Left.FullName + "." + Name;
122 public static string MakeName (string name, TypeArguments args)
127 return name + "`" + args.Count;
130 public static string MakeName (string name, int count)
132 return name + "`" + count;
135 public string GetTypeName ()
138 return Left.GetTypeName () + "." +
139 MakeName (Name, TypeArguments);
141 return MakeName (Name, TypeArguments);
144 protected bool IsUnbound {
146 if ((Left != null) && Left.IsUnbound)
148 else if (TypeArguments == null)
151 return TypeArguments.IsUnbound;
155 protected bool CheckUnbound (Location loc)
157 if ((Left != null) && !Left.CheckUnbound (loc))
159 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
160 Report.Error (1031, loc, "Type expected");
167 public Expression GetTypeExpression (Location loc)
170 if (!CheckUnbound (loc))
173 return new UnboundTypeExpression (GetTypeName ());
177 Expression lexpr = Left.GetTypeExpression (loc);
179 return new MemberAccess (lexpr, Name, TypeArguments, loc);
181 if (TypeArguments != null)
182 return new SimpleName (Basename, TypeArguments, loc);
184 return new SimpleName (Name, loc);
188 public MemberName Clone ()
191 return new MemberName (Left.Clone (), Name, TypeArguments);
193 return new MemberName (Name, TypeArguments);
196 public string Basename {
198 if (TypeArguments != null)
199 return MakeName (Name, TypeArguments);
205 public string FullName {
207 if (TypeArguments != null)
208 return Name + "<" + TypeArguments + ">";
214 public override string ToString ()
217 return Left.FullName + "." + FullName;
222 public override bool Equals (object other)
224 return Equals (other as MemberName);
227 public bool Equals (MemberName other)
231 if (other == null || Name != other.Name)
234 if ((TypeArguments != null) &&
235 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
238 if ((TypeArguments == null) && (other.TypeArguments != null))
242 return other.Left == null;
244 return Left.Equals (other.Left);
247 public override int GetHashCode ()
249 int hash = Name.GetHashCode ();
250 for (MemberName n = Left; n != null; n = n.Left)
251 hash ^= n.Name.GetHashCode ();
253 if (TypeArguments != null)
254 hash ^= TypeArguments.Count << 5;
256 return hash & 0x7FFFFFFF;
261 /// Base representation for members. This is used to keep track
262 /// of Name, Location and Modifier flags, and handling Attributes.
264 public abstract class MemberCore : Attributable {
269 protected string cached_name;
272 if (cached_name == null)
273 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
278 // Is not readonly because of IndexerName attribute
279 private MemberName member_name;
280 public MemberName MemberName {
281 get { return member_name; }
285 /// Modifier flags that the user specified in the source code
289 public /*readonly*/ TypeContainer Parent;
292 /// Location where this declaration happens
294 public readonly Location Location;
297 /// XML documentation comment
299 public string DocComment;
302 /// Represents header string for documentation comment
303 /// for each member types.
305 public abstract string DocCommentHeader { get; }
309 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
310 Obsolete = 1 << 1, // Type has obsolete attribute
311 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
312 ClsCompliant = 1 << 3, // Type is CLS Compliant
313 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
314 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
315 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
316 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
317 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
318 Excluded = 1 << 9, // Method is conditional
319 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
324 /// MemberCore flags at first detected then cached
326 internal Flags caching_flags;
328 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
332 if (parent is PartialContainer && !(this is PartialContainer))
333 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
338 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
341 protected virtual void SetMemberName (MemberName new_name)
343 member_name = new_name;
348 /// Tests presence of ObsoleteAttribute and report proper error
350 protected void CheckUsageOfObsoleteAttribute (Type type)
355 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
356 if (obsolete_attr == null)
359 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
362 public abstract bool Define ();
365 // Returns full member name for error message
367 public virtual string GetSignatureForError ()
373 /// Use this method when MethodBuilder is null
375 public virtual string GetSignatureForError (TypeContainer tc)
381 /// Base Emit method. This is also entry point for CLS-Compliant verification.
383 public virtual void Emit ()
385 // Hack with Parent == null is for EnumMember
386 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
387 VerifyObsoleteAttribute ();
389 if (!RootContext.VerifyClsCompliance)
392 VerifyClsCompliance (Parent);
395 public bool InUnsafe {
397 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
401 public virtual bool IsUsed {
403 return (caching_flags & Flags.IsUsed) != 0;
407 public void SetMemberIsUsed ()
409 caching_flags |= Flags.IsUsed;
413 // Whehter is it ok to use an unsafe pointer in this type container
415 public bool UnsafeOK (DeclSpace parent)
418 // First check if this MemberCore modifier flags has unsafe set
420 if ((ModFlags & Modifiers.UNSAFE) != 0)
423 if (parent.UnsafeContext)
426 Expression.UnsafeError (Location);
431 /// Returns instance of ObsoleteAttribute for this MemberCore
433 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
435 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
436 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
440 caching_flags &= ~Flags.Obsolete_Undetected;
442 if (OptAttributes == null)
445 Attribute obsolete_attr = OptAttributes.Search (
446 TypeManager.obsolete_attribute_type, ds.EmitContext);
447 if (obsolete_attr == null)
450 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds.EmitContext);
451 if (obsolete == null)
454 caching_flags |= Flags.Obsolete;
459 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
461 public override bool IsClsComplianceRequired (DeclSpace container)
463 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
464 return (caching_flags & Flags.ClsCompliant) != 0;
466 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
467 caching_flags &= ~Flags.ClsCompliance_Undetected;
468 caching_flags |= Flags.ClsCompliant;
472 caching_flags &= ~Flags.ClsCompliance_Undetected;
477 /// Returns true when MemberCore is exposed from assembly.
479 public bool IsExposedFromAssembly (DeclSpace ds)
481 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
484 DeclSpace parentContainer = ds;
485 while (parentContainer != null && parentContainer.ModFlags != 0) {
486 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
488 parentContainer = parentContainer.Parent;
494 /// Resolve CLSCompliantAttribute value or gets cached value.
496 bool GetClsCompliantAttributeValue (DeclSpace ds)
498 if (OptAttributes != null) {
499 Attribute cls_attribute = OptAttributes.Search (
500 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
501 if (cls_attribute != null) {
502 caching_flags |= Flags.HasClsCompliantAttribute;
503 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
506 return ds.GetClsCompliantAttributeValue ();
510 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
512 protected bool HasClsCompliantAttribute {
514 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
519 /// It helps to handle error 102 & 111 detection
521 public virtual bool MarkForDuplicationCheck ()
527 /// The main virtual method for CLS-Compliant verifications.
528 /// The method returns true if member is CLS-Compliant and false if member is not
529 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
530 /// and add their extra verifications.
532 protected virtual bool VerifyClsCompliance (DeclSpace ds)
534 if (!IsClsComplianceRequired (ds)) {
535 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
536 if (!IsExposedFromAssembly (ds))
537 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
538 if (!CodeGen.Assembly.IsClsCompliant)
539 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
544 if (!CodeGen.Assembly.IsClsCompliant) {
545 if (HasClsCompliantAttribute) {
546 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
551 int index = Name.LastIndexOf ('.');
552 if (Name [index > 0 ? index + 1 : 0] == '_') {
553 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
558 protected abstract void VerifyObsoleteAttribute ();
561 // Raised (and passed an XmlElement that contains the comment)
562 // when GenerateDocComment is writing documentation expectedly.
564 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
569 // Returns a string that represents the signature for this
570 // member which should be used in XML documentation.
572 public virtual string GetDocCommentName (DeclSpace ds)
574 if (ds == null || this is DeclSpace)
575 return DocCommentHeader + Name;
577 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
581 // Generates xml doc comments (if any), and if required,
582 // handle warning report.
584 internal virtual void GenerateDocComment (DeclSpace ds)
586 DocUtil.GenerateDocComment (this, ds);
591 /// Base class for structs, classes, enumerations and interfaces.
594 /// They all create new declaration spaces. This
595 /// provides the common foundation for managing those name
598 public abstract class DeclSpace : MemberCore, IAlias {
600 /// This points to the actual definition that is being
601 /// created with System.Reflection.Emit
603 public TypeBuilder TypeBuilder;
606 /// If we are a generic type, this is the type we are
607 /// currently defining. We need to lookup members on this
608 /// instead of the TypeBuilder.
610 public Type CurrentType;
613 // This is the namespace in which this typecontainer
614 // was declared. We use this to resolve names.
616 public NamespaceEntry NamespaceEntry;
618 private Hashtable Cache = new Hashtable ();
620 public readonly string Basename;
622 protected Hashtable defined_names;
624 readonly bool is_generic;
625 readonly int count_type_params;
626 readonly int count_current_type_params;
628 // The emit context for toplevel objects.
629 protected EmitContext ec;
631 public EmitContext EmitContext {
636 // Whether we are Generic
638 public bool IsGeneric {
642 else if (Parent != null)
643 return Parent.IsGeneric;
649 static string[] attribute_targets = new string [] { "type" };
651 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
652 Attributes attrs, Location l)
653 : base (parent, name, attrs, l)
656 Basename = name.Basename;
657 defined_names = new Hashtable ();
658 if (name.TypeArguments != null) {
660 count_type_params = count_current_type_params = name.TypeArguments.Count;
663 count_type_params += parent.count_type_params;
667 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
669 protected bool AddToContainer (MemberCore symbol, string name)
671 if (name == Basename && !(this is Interface) && !(this is Enum)) {
672 if (symbol is TypeParameter)
673 Report.Error (694, "Type parameter `{0}' has same name as " +
674 "containing type or method", name);
676 Report.SymbolRelatedToPreviousError (this);
677 Report.Error (542, "'{0}': member names cannot be the same as their " +
678 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
683 MemberCore mc = (MemberCore) defined_names [name];
686 defined_names.Add (name, symbol);
690 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
693 if (symbol is TypeParameter)
694 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", name);
696 Report.SymbolRelatedToPreviousError (mc);
697 Report.Error (102, symbol.Location,
698 "The type '{0}' already contains a definition for '{1}'",
699 GetSignatureForError (), name);
704 public void RecordDecl ()
706 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
707 NamespaceEntry.DefineName (MemberName.Basename, this);
711 /// Returns the MemberCore associated with a given name in the declaration
712 /// space. It doesn't return method based symbols !!
715 public MemberCore GetDefinition (string name)
717 return (MemberCore)defined_names [name];
721 // root_types contains all the types. All TopLevel types
722 // hence have a parent that points to `root_types', that is
723 // why there is a non-obvious test down here.
725 public bool IsTopLevel {
728 if (Parent.Parent == null)
735 public virtual void CloseType ()
737 if ((caching_flags & Flags.CloseTypeCreated) == 0){
739 TypeBuilder.CreateType ();
742 // The try/catch is needed because
743 // nested enumerations fail to load when they
746 // Even if this is the right order (enumerations
747 // declared after types).
749 // Note that this still creates the type and
750 // it is possible to save it
752 caching_flags |= Flags.CloseTypeCreated;
756 protected virtual TypeAttributes TypeAttr {
758 return CodeGen.Module.DefaultCharSetType;
763 /// Should be overriten by the appropriate declaration space
765 public abstract TypeBuilder DefineType ();
768 /// Define all members, but don't apply any attributes or do anything which may
769 /// access not-yet-defined classes. This method also creates the MemberCache.
771 public abstract bool DefineMembers (TypeContainer parent);
774 // Whether this is an `unsafe context'
776 public bool UnsafeContext {
778 if ((ModFlags & Modifiers.UNSAFE) != 0)
781 return Parent.UnsafeContext;
786 EmitContext type_resolve_ec;
787 protected EmitContext TypeResolveEmitContext {
789 if (type_resolve_ec == null) {
790 // FIXME: I think this should really be one of:
792 // a. type_resolve_ec = Parent.EmitContext;
793 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
795 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
797 type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
799 return type_resolve_ec;
804 // Resolves the expression `e' for a type, and will recursively define
805 // types. This should only be used for resolving base types.
807 protected TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
809 TypeResolveEmitContext.loc = loc;
810 TypeResolveEmitContext.ContainerType = TypeBuilder;
811 TypeResolveEmitContext.ResolvingTypeTree = true;
812 if (this is GenericMethod)
813 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
815 TypeResolveEmitContext.ContainerType = TypeBuilder;
817 return e.ResolveAsTypeTerminal (TypeResolveEmitContext);
820 public bool CheckAccessLevel (Type check_type)
823 if ((this is GenericMethod) || (this is Iterator))
824 tb = Parent.TypeBuilder;
828 if (check_type.IsGenericInstance)
829 check_type = check_type.GetGenericTypeDefinition ();
831 if (check_type == tb)
834 if (TypeBuilder == null)
835 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
836 // However, this is invoked again later -- so safe to return true.
837 // May also be null when resolving top-level attributes.
840 if (check_type.IsGenericParameter)
841 return true; // FIXME
843 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
846 // Broken Microsoft runtime, return public for arrays, no matter what
847 // the accessibility is for their underlying class, and they return
848 // NonPublic visibility for pointers
850 if (check_type.IsArray || check_type.IsPointer)
851 return CheckAccessLevel (TypeManager.GetElementType (check_type));
854 case TypeAttributes.Public:
857 case TypeAttributes.NotPublic:
859 if (TypeBuilder == null)
860 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
861 // However, this is invoked again later -- so safe to return true.
862 // May also be null when resolving top-level attributes.
865 // This test should probably use the declaringtype.
867 return check_type.Assembly == TypeBuilder.Assembly;
869 case TypeAttributes.NestedPublic:
872 case TypeAttributes.NestedPrivate:
873 return NestedAccessible (tb, check_type);
875 case TypeAttributes.NestedFamily:
877 // Only accessible to methods in current type or any subtypes
879 return FamilyAccessible (tb, check_type);
881 case TypeAttributes.NestedFamANDAssem:
882 return (check_type.Assembly == tb.Assembly) &&
883 FamilyAccessible (tb, check_type);
885 case TypeAttributes.NestedFamORAssem:
886 return (check_type.Assembly == tb.Assembly) ||
887 FamilyAccessible (tb, check_type);
889 case TypeAttributes.NestedAssembly:
890 return check_type.Assembly == tb.Assembly;
893 Console.WriteLine ("HERE: " + check_attr);
898 protected bool NestedAccessible (Type tb, Type check_type)
900 Type declaring = check_type.DeclaringType;
901 return TypeBuilder == declaring ||
902 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
905 protected bool FamilyAccessible (Type tb, Type check_type)
907 Type declaring = check_type.DeclaringType;
908 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
911 // Access level of a type.
913 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
914 // Public Assembly Protected
915 Protected = (0 << 0) | (0 << 1) | (X << 2),
916 Public = (X << 0) | (X << 1) | (X << 2),
917 Private = (0 << 0) | (0 << 1) | (0 << 2),
918 Internal = (0 << 0) | (X << 1) | (0 << 2),
919 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
922 static AccessLevel GetAccessLevelFromModifiers (int flags)
924 if ((flags & Modifiers.INTERNAL) != 0) {
926 if ((flags & Modifiers.PROTECTED) != 0)
927 return AccessLevel.ProtectedOrInternal;
929 return AccessLevel.Internal;
931 } else if ((flags & Modifiers.PROTECTED) != 0)
932 return AccessLevel.Protected;
933 else if ((flags & Modifiers.PRIVATE) != 0)
934 return AccessLevel.Private;
936 return AccessLevel.Public;
939 // What is the effective access level of this?
941 AccessLevel EffectiveAccessLevel {
943 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
944 if (!IsTopLevel && (Parent != null))
945 return myAccess & Parent.EffectiveAccessLevel;
950 // Return the access level for type `t'
951 static AccessLevel TypeEffectiveAccessLevel (Type t)
954 return AccessLevel.Public;
955 if (t.IsNestedPrivate)
956 return AccessLevel.Private;
958 return AccessLevel.Internal;
960 // By now, it must be nested
961 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
963 if (t.IsNestedPublic)
965 if (t.IsNestedAssembly)
966 return parentLevel & AccessLevel.Internal;
967 if (t.IsNestedFamily)
968 return parentLevel & AccessLevel.Protected;
969 if (t.IsNestedFamORAssem)
970 return parentLevel & AccessLevel.ProtectedOrInternal;
971 if (t.IsNestedFamANDAssem)
972 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
974 // nested private is taken care of
976 throw new Exception ("I give up, what are you?");
980 // This answers `is the type P, as accessible as a member M which has the
981 // accessability @flags which is declared as a nested member of the type T, this declspace'
983 public bool AsAccessible (Type p, int flags)
985 if (p.IsGenericParameter)
986 return true; // FIXME
989 // 1) if M is private, its accessability is the same as this declspace.
990 // we already know that P is accessible to T before this method, so we
994 if ((flags & Modifiers.PRIVATE) != 0)
997 while (p.IsArray || p.IsPointer || p.IsByRef)
998 p = TypeManager.GetElementType (p);
1000 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1001 AccessLevel mAccess = this.EffectiveAccessLevel &
1002 GetAccessLevelFromModifiers (flags);
1004 // for every place from which we can access M, we must
1005 // be able to access P as well. So, we want
1006 // For every bit in M and P, M_i -> P_1 == true
1007 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1009 return ~ (~ mAccess | pAccess) == 0;
1012 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1014 Report.Error (104, loc,
1015 "`{0}' is an ambiguous reference ({1} or {2})",
1020 // Return the nested type with name @name. Ensures that the nested type
1021 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1023 public virtual Type FindNestedType (string name)
1028 private Type LookupNestedTypeInHierarchy (string name)
1030 // if the member cache has been created, lets use it.
1031 // the member cache is MUCH faster.
1032 if (MemberCache != null)
1033 return MemberCache.FindNestedType (name);
1035 // no member cache. Do it the hard way -- reflection
1037 for (Type current_type = TypeBuilder;
1038 current_type != null && current_type != TypeManager.object_type;
1039 current_type = current_type.BaseType) {
1040 if (current_type is TypeBuilder) {
1041 DeclSpace decl = this;
1042 if (current_type != TypeBuilder)
1043 decl = TypeManager.LookupDeclSpace (current_type);
1044 t = decl.FindNestedType (name);
1046 t = TypeManager.GetNestedType (current_type, name);
1049 if (t != null && CheckAccessLevel (t))
1057 // Public function used to locate types, this can only
1058 // be used after the ResolveTree function has been invoked.
1060 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1062 // Returns: Type or null if they type can not be found.
1064 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1066 if (this is PartialContainer)
1067 throw new InternalErrorException ("Should not get here");
1069 if (Cache.Contains (name))
1070 return (FullNamedExpression) Cache [name];
1072 FullNamedExpression e;
1073 Type t = LookupNestedTypeInHierarchy (name);
1075 e = new TypeExpression (t, Location.Null);
1076 else if (Parent != null && Parent != RootContext.Tree.Types)
1077 e = Parent.LookupType (name, loc, ignore_cs0104);
1079 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1086 /// This function is broken and not what you're looking for. It should only
1087 /// be used while the type is still being created since it doesn't use the cache
1088 /// and relies on the filter doing the member name check.
1090 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1091 MemberFilter filter, object criteria);
1094 /// If we have a MemberCache, return it. This property may return null if the
1095 /// class doesn't have a member cache or while it's still being created.
1097 public abstract MemberCache MemberCache {
1101 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1103 if (a.Type == TypeManager.required_attr_type) {
1104 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1107 TypeBuilder.SetCustomAttribute (cb);
1111 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1112 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1114 public bool GetClsCompliantAttributeValue ()
1116 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1117 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1119 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1121 if (OptAttributes != null) {
1122 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1123 if (cls_attribute != null) {
1124 caching_flags |= Flags.HasClsCompliantAttribute;
1125 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1126 caching_flags |= Flags.ClsCompliantAttributeTrue;
1133 if (Parent == null) {
1134 if (CodeGen.Assembly.IsClsCompliant) {
1135 caching_flags |= Flags.ClsCompliantAttributeTrue;
1141 if (Parent.GetClsCompliantAttributeValue ()) {
1142 caching_flags |= Flags.ClsCompliantAttributeTrue;
1149 // Extensions for generics
1151 TypeParameter[] type_params;
1152 TypeParameter[] type_param_list;
1154 protected string GetInstantiationName ()
1156 StringBuilder sb = new StringBuilder (Name);
1158 for (int i = 0; i < type_param_list.Length; i++) {
1161 sb.Append (type_param_list [i].Name);
1164 return sb.ToString ();
1167 bool check_type_parameter (ArrayList list, int start, string name)
1169 for (int i = 0; i < start; i++) {
1170 TypeParameter param = (TypeParameter) list [i];
1172 if (param.Name != name)
1175 if (RootContext.WarningLevel >= 3)
1178 "Type parameter `{0}' has same name " +
1179 "as type parameter from outer type `{1}'",
1180 name, Parent.GetInstantiationName ());
1188 TypeParameter[] initialize_type_params ()
1190 if (type_param_list != null)
1191 return type_param_list;
1193 DeclSpace the_parent = Parent;
1194 if (this is GenericMethod)
1198 TypeParameter[] parent_params = null;
1199 if ((the_parent != null) && the_parent.IsGeneric) {
1200 parent_params = the_parent.initialize_type_params ();
1201 start = parent_params != null ? parent_params.Length : 0;
1204 ArrayList list = new ArrayList ();
1205 if (parent_params != null)
1206 list.AddRange (parent_params);
1208 int count = type_params != null ? type_params.Length : 0;
1209 for (int i = 0; i < count; i++) {
1210 TypeParameter param = type_params [i];
1211 check_type_parameter (list, start, param.Name);
1215 type_param_list = new TypeParameter [list.Count];
1216 list.CopyTo (type_param_list, 0);
1217 return type_param_list;
1220 public virtual void SetParameterInfo (ArrayList constraints_list)
1223 if (constraints_list != null) {
1225 80, Location, "Contraints are not allowed " +
1226 "on non-generic declarations");
1232 string[] names = MemberName.TypeArguments.GetDeclarations ();
1233 type_params = new TypeParameter [names.Length];
1236 // Register all the names
1238 for (int i = 0; i < type_params.Length; i++) {
1239 string name = names [i];
1241 Constraints constraints = null;
1242 if (constraints_list != null) {
1243 foreach (Constraints constraint in constraints_list) {
1244 if (constraint.TypeParameter == name) {
1245 constraints = constraint;
1251 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1253 AddToContainer (type_params [i], name);
1257 public TypeParameter[] TypeParameters {
1260 throw new InvalidOperationException ();
1261 if (type_param_list == null)
1262 initialize_type_params ();
1264 return type_param_list;
1268 protected TypeParameter[] CurrentTypeParameters {
1271 throw new InvalidOperationException ();
1272 if (type_params != null)
1275 return new TypeParameter [0];
1279 public int CountTypeParameters {
1281 return count_type_params;
1285 public int CountCurrentTypeParameters {
1287 return count_current_type_params;
1291 public TypeParameterExpr LookupGeneric (string name, Location loc)
1296 foreach (TypeParameter type_param in CurrentTypeParameters) {
1297 if (type_param.Name != name)
1300 return new TypeParameterExpr (type_param, loc);
1304 return Parent.LookupGeneric (name, loc);
1309 bool IAlias.IsType {
1310 get { return true; }
1313 string IAlias.Name {
1314 get { return Name; }
1317 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1319 if (TypeBuilder == null)
1320 throw new InvalidOperationException ();
1322 if (CurrentType != null)
1323 return new TypeExpression (CurrentType, Location);
1325 return new TypeExpression (TypeBuilder, Location);
1328 public override string[] ValidAttributeTargets {
1330 return attribute_targets;
1336 /// This is a readonly list of MemberInfo's.
1338 public class MemberList : IList {
1339 public readonly IList List;
1343 /// Create a new MemberList from the given IList.
1345 public MemberList (IList list)
1350 this.List = new ArrayList ();
1355 /// Concatenate the ILists `first' and `second' to a new MemberList.
1357 public MemberList (IList first, IList second)
1359 ArrayList list = new ArrayList ();
1360 list.AddRange (first);
1361 list.AddRange (second);
1366 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1369 /// Cast the MemberList into a MemberInfo[] array.
1372 /// This is an expensive operation, only use it if it's really necessary.
1374 public static explicit operator MemberInfo [] (MemberList list)
1376 Timer.StartTimer (TimerType.MiscTimer);
1377 MemberInfo [] result = new MemberInfo [list.Count];
1378 list.CopyTo (result, 0);
1379 Timer.StopTimer (TimerType.MiscTimer);
1391 public bool IsSynchronized {
1393 return List.IsSynchronized;
1397 public object SyncRoot {
1399 return List.SyncRoot;
1403 public void CopyTo (Array array, int index)
1405 List.CopyTo (array, index);
1410 public IEnumerator GetEnumerator ()
1412 return List.GetEnumerator ();
1417 public bool IsFixedSize {
1423 public bool IsReadOnly {
1429 object IList.this [int index] {
1431 return List [index];
1435 throw new NotSupportedException ();
1439 // FIXME: try to find out whether we can avoid the cast in this indexer.
1440 public MemberInfo this [int index] {
1442 return (MemberInfo) List [index];
1446 public int Add (object value)
1448 throw new NotSupportedException ();
1451 public void Clear ()
1453 throw new NotSupportedException ();
1456 public bool Contains (object value)
1458 return List.Contains (value);
1461 public int IndexOf (object value)
1463 return List.IndexOf (value);
1466 public void Insert (int index, object value)
1468 throw new NotSupportedException ();
1471 public void Remove (object value)
1473 throw new NotSupportedException ();
1476 public void RemoveAt (int index)
1478 throw new NotSupportedException ();
1483 /// This interface is used to get all members of a class when creating the
1484 /// member cache. It must be implemented by all DeclSpace derivatives which
1485 /// want to support the member cache and by TypeHandle to get caching of
1486 /// non-dynamic types.
1488 public interface IMemberContainer {
1490 /// The name of the IMemberContainer. This is only used for
1491 /// debugging purposes.
1498 /// The type of this IMemberContainer.
1505 /// Returns the IMemberContainer of the base class or null if this
1506 /// is an interface or TypeManger.object_type.
1507 /// This is used when creating the member cache for a class to get all
1508 /// members from the base class.
1510 MemberCache BaseCache {
1515 /// Whether this is an interface.
1522 /// Returns all members of this class with the corresponding MemberTypes
1523 /// and BindingFlags.
1526 /// When implementing this method, make sure not to return any inherited
1527 /// members and check the MemberTypes and BindingFlags properly.
1528 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1529 /// get the BindingFlags (static/non-static,public/non-public) in the
1530 /// MemberInfo class, but the cache needs this information. That's why
1531 /// this method is called multiple times with different BindingFlags.
1533 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1536 /// Return the container's member cache.
1538 MemberCache MemberCache {
1544 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1545 /// member lookups. It has a member name based hash table; it maps each member
1546 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1547 /// and the BindingFlags that were initially used to get it. The cache contains
1548 /// all members of the current class and all inherited members. If this cache is
1549 /// for an interface types, it also contains all inherited members.
1551 /// There are two ways to get a MemberCache:
1552 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1553 /// use the DeclSpace.MemberCache property.
1554 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1555 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1557 public class MemberCache {
1558 public readonly IMemberContainer Container;
1559 protected Hashtable member_hash;
1560 protected Hashtable method_hash;
1563 /// Create a new MemberCache for the given IMemberContainer `container'.
1565 public MemberCache (IMemberContainer container)
1567 this.Container = container;
1569 Timer.IncrementCounter (CounterType.MemberCache);
1570 Timer.StartTimer (TimerType.CacheInit);
1572 // If we have a base class (we have a base class unless we're
1573 // TypeManager.object_type), we deep-copy its MemberCache here.
1574 if (Container.BaseCache != null)
1575 member_hash = SetupCache (Container.BaseCache);
1577 member_hash = new Hashtable ();
1579 // If this is neither a dynamic type nor an interface, create a special
1580 // method cache with all declared and inherited methods.
1581 Type type = container.Type;
1582 if (!(type is TypeBuilder) && !type.IsInterface &&
1583 // !(type.IsGenericInstance && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1584 !type.IsGenericInstance &&
1585 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1586 method_hash = new Hashtable ();
1590 // Add all members from the current class.
1591 AddMembers (Container);
1593 Timer.StopTimer (TimerType.CacheInit);
1596 public MemberCache (Type[] ifaces)
1599 // The members of this cache all belong to other caches.
1600 // So, 'Container' will not be used.
1602 this.Container = null;
1604 member_hash = new Hashtable ();
1608 foreach (Type itype in ifaces)
1609 AddCacheContents (TypeManager.LookupMemberCache (itype));
1613 /// Bootstrap this member cache by doing a deep-copy of our base.
1615 Hashtable SetupCache (MemberCache base_class)
1617 Hashtable hash = new Hashtable ();
1619 if (base_class == null)
1622 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1623 while (it.MoveNext ()) {
1624 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1631 /// Add the contents of `cache' to the member_hash.
1633 void AddCacheContents (MemberCache cache)
1635 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1636 while (it.MoveNext ()) {
1637 ArrayList list = (ArrayList) member_hash [it.Key];
1639 member_hash [it.Key] = list = new ArrayList ();
1641 ArrayList entries = (ArrayList) it.Value;
1642 for (int i = entries.Count-1; i >= 0; i--) {
1643 CacheEntry entry = (CacheEntry) entries [i];
1645 if (entry.Container != cache.Container)
1653 /// Add all members from class `container' to the cache.
1655 void AddMembers (IMemberContainer container)
1657 // We need to call AddMembers() with a single member type at a time
1658 // to get the member type part of CacheEntry.EntryType right.
1659 if (!container.IsInterface) {
1660 AddMembers (MemberTypes.Constructor, container);
1661 AddMembers (MemberTypes.Field, container);
1663 AddMembers (MemberTypes.Method, container);
1664 AddMembers (MemberTypes.Property, container);
1665 AddMembers (MemberTypes.Event, container);
1666 // Nested types are returned by both Static and Instance searches.
1667 AddMembers (MemberTypes.NestedType,
1668 BindingFlags.Static | BindingFlags.Public, container);
1669 AddMembers (MemberTypes.NestedType,
1670 BindingFlags.Static | BindingFlags.NonPublic, container);
1673 void AddMembers (MemberTypes mt, IMemberContainer container)
1675 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1676 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1677 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1678 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1682 /// Add all members from class `container' with the requested MemberTypes and
1683 /// BindingFlags to the cache. This method is called multiple times with different
1684 /// MemberTypes and BindingFlags.
1686 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1688 MemberList members = container.GetMembers (mt, bf);
1690 foreach (MemberInfo member in members) {
1691 string name = member.Name;
1693 int pos = name.IndexOf ('<');
1695 name = name.Substring (0, pos);
1697 // We use a name-based hash table of ArrayList's.
1698 ArrayList list = (ArrayList) member_hash [name];
1700 list = new ArrayList ();
1701 member_hash.Add (name, list);
1704 // When this method is called for the current class, the list will
1705 // already contain all inherited members from our base classes.
1706 // We cannot add new members in front of the list since this'd be an
1707 // expensive operation, that's why the list is sorted in reverse order
1708 // (ie. members from the current class are coming last).
1709 list.Add (new CacheEntry (container, member, mt, bf));
1714 /// Add all declared and inherited methods from class `type' to the method cache.
1716 void AddMethods (Type type)
1718 AddMethods (BindingFlags.Static | BindingFlags.Public |
1719 BindingFlags.FlattenHierarchy, type);
1720 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1721 BindingFlags.FlattenHierarchy, type);
1722 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1723 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1726 void AddMethods (BindingFlags bf, Type type)
1728 MethodBase [] members = type.GetMethods (bf);
1730 Array.Reverse (members);
1732 foreach (MethodBase member in members) {
1733 string name = member.Name;
1735 // We use a name-based hash table of ArrayList's.
1736 ArrayList list = (ArrayList) method_hash [name];
1738 list = new ArrayList ();
1739 method_hash.Add (name, list);
1742 MethodInfo curr = (MethodInfo) member;
1743 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1744 MethodInfo base_method = curr.GetBaseDefinition ();
1746 if (base_method == curr) {
1747 // Not every virtual function needs to have a NewSlot flag.
1748 TypeManager.RegisterNonOverride (base_method);
1752 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1756 // Unfortunately, the elements returned by Type.GetMethods() aren't
1757 // sorted so we need to do this check for every member.
1758 BindingFlags new_bf = bf;
1759 if (member.DeclaringType == type)
1760 new_bf |= BindingFlags.DeclaredOnly;
1762 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1767 /// Compute and return a appropriate `EntryType' magic number for the given
1768 /// MemberTypes and BindingFlags.
1770 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1772 EntryType type = EntryType.None;
1774 if ((mt & MemberTypes.Constructor) != 0)
1775 type |= EntryType.Constructor;
1776 if ((mt & MemberTypes.Event) != 0)
1777 type |= EntryType.Event;
1778 if ((mt & MemberTypes.Field) != 0)
1779 type |= EntryType.Field;
1780 if ((mt & MemberTypes.Method) != 0)
1781 type |= EntryType.Method;
1782 if ((mt & MemberTypes.Property) != 0)
1783 type |= EntryType.Property;
1784 // Nested types are returned by static and instance searches.
1785 if ((mt & MemberTypes.NestedType) != 0)
1786 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1788 if ((bf & BindingFlags.Instance) != 0)
1789 type |= EntryType.Instance;
1790 if ((bf & BindingFlags.Static) != 0)
1791 type |= EntryType.Static;
1792 if ((bf & BindingFlags.Public) != 0)
1793 type |= EntryType.Public;
1794 if ((bf & BindingFlags.NonPublic) != 0)
1795 type |= EntryType.NonPublic;
1796 if ((bf & BindingFlags.DeclaredOnly) != 0)
1797 type |= EntryType.Declared;
1803 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1804 /// denote multiple member types. Returns true if the given flags value denotes a
1805 /// single member types.
1807 public static bool IsSingleMemberType (MemberTypes mt)
1810 case MemberTypes.Constructor:
1811 case MemberTypes.Event:
1812 case MemberTypes.Field:
1813 case MemberTypes.Method:
1814 case MemberTypes.Property:
1815 case MemberTypes.NestedType:
1824 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1825 /// number to speed up the searching process.
1828 protected enum EntryType {
1833 MaskStatic = Instance|Static,
1837 MaskProtection = Public|NonPublic,
1841 Constructor = 0x020,
1848 MaskType = Constructor|Event|Field|Method|Property|NestedType
1851 protected class CacheEntry {
1852 public readonly IMemberContainer Container;
1853 public EntryType EntryType;
1854 public MemberInfo Member;
1856 public CacheEntry (IMemberContainer container, MemberInfo member,
1857 MemberTypes mt, BindingFlags bf)
1859 this.Container = container;
1860 this.Member = member;
1861 this.EntryType = GetEntryType (mt, bf);
1864 public override string ToString ()
1866 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1872 /// This is called each time we're walking up one level in the class hierarchy
1873 /// and checks whether we can abort the search since we've already found what
1874 /// we were looking for.
1876 protected bool DoneSearching (ArrayList list)
1879 // We've found exactly one member in the current class and it's not
1880 // a method or constructor.
1882 if (list.Count == 1 && !(list [0] is MethodBase))
1886 // Multiple properties: we query those just to find out the indexer
1889 if ((list.Count > 0) && (list [0] is PropertyInfo))
1896 /// Looks up members with name `name'. If you provide an optional
1897 /// filter function, it'll only be called with members matching the
1898 /// requested member name.
1900 /// This method will try to use the cache to do the lookup if possible.
1902 /// Unlike other FindMembers implementations, this method will always
1903 /// check all inherited members - even when called on an interface type.
1905 /// If you know that you're only looking for methods, you should use
1906 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1907 /// When doing a method-only search, it'll try to use a special method
1908 /// cache (unless it's a dynamic type or an interface) and the returned
1909 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1910 /// The lookup process will automatically restart itself in method-only
1911 /// search mode if it discovers that it's about to return methods.
1913 ArrayList global = new ArrayList ();
1914 bool using_global = false;
1916 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1918 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1919 MemberFilter filter, object criteria)
1922 throw new Exception ();
1924 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1925 bool method_search = mt == MemberTypes.Method;
1926 // If we have a method cache and we aren't already doing a method-only search,
1927 // then we restart a method search if the first match is a method.
1928 bool do_method_search = !method_search && (method_hash != null);
1930 ArrayList applicable;
1932 // If this is a method-only search, we try to use the method cache if
1933 // possible; a lookup in the method cache will return a MemberInfo with
1934 // the correct ReflectedType for inherited methods.
1936 if (method_search && (method_hash != null))
1937 applicable = (ArrayList) method_hash [name];
1939 applicable = (ArrayList) member_hash [name];
1941 if (applicable == null)
1942 return emptyMemberInfo;
1945 // 32 slots gives 53 rss/54 size
1946 // 2/4 slots gives 55 rss
1948 // Strange: from 25,000 calls, only 1,800
1949 // are above 2. Why does this impact it?
1952 using_global = true;
1954 Timer.StartTimer (TimerType.CachedLookup);
1956 EntryType type = GetEntryType (mt, bf);
1958 IMemberContainer current = Container;
1961 // `applicable' is a list of all members with the given member name `name'
1962 // in the current class and all its base classes. The list is sorted in
1963 // reverse order due to the way how the cache is initialy created (to speed
1964 // things up, we're doing a deep-copy of our base).
1966 for (int i = applicable.Count-1; i >= 0; i--) {
1967 CacheEntry entry = (CacheEntry) applicable [i];
1969 // This happens each time we're walking one level up in the class
1970 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1971 // the first time this happens (this may already happen in the first
1972 // iteration of this loop if there are no members with the name we're
1973 // looking for in the current class).
1974 if (entry.Container != current) {
1975 if (declared_only || DoneSearching (global))
1978 current = entry.Container;
1981 // Is the member of the correct type ?
1982 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1985 // Is the member static/non-static ?
1986 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1989 // Apply the filter to it.
1990 if (filter (entry.Member, criteria)) {
1991 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1992 do_method_search = false;
1993 global.Add (entry.Member);
1997 Timer.StopTimer (TimerType.CachedLookup);
1999 // If we have a method cache and we aren't already doing a method-only
2000 // search, we restart in method-only search mode if the first match is
2001 // a method. This ensures that we return a MemberInfo with the correct
2002 // ReflectedType for inherited methods.
2003 if (do_method_search && (global.Count > 0)){
2004 using_global = false;
2006 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2009 using_global = false;
2010 MemberInfo [] copy = new MemberInfo [global.Count];
2011 global.CopyTo (copy);
2015 // find the nested type @name in @this.
2016 public Type FindNestedType (string name)
2018 ArrayList applicable = (ArrayList) member_hash [name];
2019 if (applicable == null)
2022 for (int i = applicable.Count-1; i >= 0; i--) {
2023 CacheEntry entry = (CacheEntry) applicable [i];
2024 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2025 return (Type) entry.Member;
2032 // This finds the method or property for us to override. invocationType is the type where
2033 // the override is going to be declared, name is the name of the method/property, and
2034 // paramTypes is the parameters, if any to the method or property
2036 // Because the MemberCache holds members from this class and all the base classes,
2037 // we can avoid tons of reflection stuff.
2039 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2041 ArrayList applicable;
2042 if (method_hash != null && !is_property)
2043 applicable = (ArrayList) method_hash [name];
2045 applicable = (ArrayList) member_hash [name];
2047 if (applicable == null)
2050 // Walk the chain of methods, starting from the top.
2052 for (int i = applicable.Count - 1; i >= 0; i--) {
2053 CacheEntry entry = (CacheEntry) applicable [i];
2055 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2058 PropertyInfo pi = null;
2059 MethodInfo mi = null;
2060 FieldInfo fi = null;
2061 Type [] cmpAttrs = null;
2064 if ((entry.EntryType & EntryType.Field) != 0) {
2065 fi = (FieldInfo)entry.Member;
2067 // TODO: For this case we ignore member type
2068 //fb = TypeManager.GetField (fi);
2069 //cmpAttrs = new Type[] { fb.MemberType };
2071 pi = (PropertyInfo) entry.Member;
2072 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2075 mi = (MethodInfo) entry.Member;
2076 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2080 // TODO: Almost duplicate !
2082 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2083 case FieldAttributes.Private:
2085 // A private method is Ok if we are a nested subtype.
2086 // The spec actually is not very clear about this, see bug 52458.
2088 if (invocationType != entry.Container.Type &
2089 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2093 case FieldAttributes.FamANDAssem:
2094 case FieldAttributes.Assembly:
2096 // Check for assembly methods
2098 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2102 return entry.Member;
2106 // Check the arguments
2108 if (cmpAttrs.Length != paramTypes.Length)
2111 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2112 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2117 // get one of the methods because this has the visibility info.
2120 mi = pi.GetGetMethod (true);
2122 mi = pi.GetSetMethod (true);
2128 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2129 case MethodAttributes.Private:
2131 // A private method is Ok if we are a nested subtype.
2132 // The spec actually is not very clear about this, see bug 52458.
2134 if (invocationType.Equals (entry.Container.Type) ||
2135 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2136 return entry.Member;
2139 case MethodAttributes.FamANDAssem:
2140 case MethodAttributes.Assembly:
2142 // Check for assembly methods
2144 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2145 return entry.Member;
2150 // A protected method is ok, because we are overriding.
2151 // public is always ok.
2153 return entry.Member;
2163 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2164 /// We handle two cases. The first is for types without parameters (events, field, properties).
2165 /// The second are methods, indexers and this is why ignore_complex_types is here.
2166 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2168 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2170 ArrayList applicable = null;
2172 if (method_hash != null)
2173 applicable = (ArrayList) method_hash [name];
2175 if (applicable != null) {
2176 for (int i = applicable.Count - 1; i >= 0; i--) {
2177 CacheEntry entry = (CacheEntry) applicable [i];
2178 if ((entry.EntryType & EntryType.Public) != 0)
2179 return entry.Member;
2183 if (member_hash == null)
2185 applicable = (ArrayList) member_hash [name];
2187 if (applicable != null) {
2188 for (int i = applicable.Count - 1; i >= 0; i--) {
2189 CacheEntry entry = (CacheEntry) applicable [i];
2190 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2191 if (ignore_complex_types) {
2192 if ((entry.EntryType & EntryType.Method) != 0)
2195 // Does exist easier way how to detect indexer ?
2196 if ((entry.EntryType & EntryType.Property) != 0) {
2197 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2198 if (arg_types.Length > 0)
2202 return entry.Member;
2209 Hashtable locase_table;
2212 /// Builds low-case table for CLS Compliance test
2214 public Hashtable GetPublicMembers ()
2216 if (locase_table != null)
2217 return locase_table;
2219 locase_table = new Hashtable ();
2220 foreach (DictionaryEntry entry in member_hash) {
2221 ArrayList members = (ArrayList)entry.Value;
2222 for (int ii = 0; ii < members.Count; ++ii) {
2223 CacheEntry member_entry = (CacheEntry) members [ii];
2225 if ((member_entry.EntryType & EntryType.Public) == 0)
2228 // TODO: Does anyone know easier way how to detect that member is internal ?
2229 switch (member_entry.EntryType & EntryType.MaskType) {
2230 case EntryType.Constructor:
2233 case EntryType.Field:
2234 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2238 case EntryType.Method:
2239 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2243 case EntryType.Property:
2244 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2245 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2249 case EntryType.Event:
2250 EventInfo ei = (EventInfo)member_entry.Member;
2251 MethodInfo mi = ei.GetAddMethod ();
2252 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2256 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2257 locase_table [lcase] = member_entry.Member;
2261 return locase_table;
2264 public Hashtable Members {
2271 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2273 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2275 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2277 for (int i = 0; i < al.Count; ++i) {
2278 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2281 if (entry.Member == this_builder)
2284 if ((entry.EntryType & tested_type) != tested_type)
2287 MethodBase method_to_compare = (MethodBase)entry.Member;
2288 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2289 method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare));
2291 if (result == AttributeTester.Result.Ok)
2294 IMethodData md = TypeManager.GetMethod (method_to_compare);
2296 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2297 // However it is exactly what csc does.
2298 if (md != null && !md.IsClsComplianceRequired (method.Parent))
2301 Report.SymbolRelatedToPreviousError (entry.Member);
2303 case AttributeTester.Result.RefOutArrayError:
2304 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2306 case AttributeTester.Result.ArrayArrayError:
2307 Report.Error (3007, method.Location, "Overloaded method '{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2311 throw new NotImplementedException (result.ToString ());