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
321 IsAssigned = 1 << 12 // Field is assigned
325 /// MemberCore flags at first detected then cached
327 internal Flags caching_flags;
329 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
333 if (parent is PartialContainer && !(this is PartialContainer))
334 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
339 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
342 protected virtual void SetMemberName (MemberName new_name)
344 member_name = new_name;
349 /// Tests presence of ObsoleteAttribute and report proper error
351 protected void CheckUsageOfObsoleteAttribute (Type type)
356 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
357 if (obsolete_attr == null)
360 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
363 public abstract bool Define ();
366 // Returns full member name for error message
368 public virtual string GetSignatureForError ()
370 if (Parent == null || Parent.Parent == null)
373 return String.Concat (Parent.GetSignatureForError (), '.', Name);
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 IsClsComplianceRequired (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 (!IsClsComplianceRequired (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 not visible from outside this assembly", GetSignatureForError ());
534 if (!CodeGen.Assembly.IsClsCompliant)
535 Report.Warning (3021, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
540 if (!CodeGen.Assembly.IsClsCompliant) {
541 if (HasClsCompliantAttribute) {
542 Report.Error (3014, Location,
543 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
544 GetSignatureForError ());
549 if (member_name.Name [0] == '_') {
550 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
555 protected abstract void VerifyObsoleteAttribute ();
558 // Raised (and passed an XmlElement that contains the comment)
559 // when GenerateDocComment is writing documentation expectedly.
561 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
566 // Returns a string that represents the signature for this
567 // member which should be used in XML documentation.
569 public virtual string GetDocCommentName (DeclSpace ds)
571 if (ds == null || this is DeclSpace)
572 return DocCommentHeader + Name;
574 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
578 // Generates xml doc comments (if any), and if required,
579 // handle warning report.
581 internal virtual void GenerateDocComment (DeclSpace ds)
583 DocUtil.GenerateDocComment (this, ds);
588 /// Base class for structs, classes, enumerations and interfaces.
591 /// They all create new declaration spaces. This
592 /// provides the common foundation for managing those name
595 public abstract class DeclSpace : MemberCore {
597 /// This points to the actual definition that is being
598 /// created with System.Reflection.Emit
600 public TypeBuilder TypeBuilder;
603 /// If we are a generic type, this is the type we are
604 /// currently defining. We need to lookup members on this
605 /// instead of the TypeBuilder.
607 public Type CurrentType;
610 // This is the namespace in which this typecontainer
611 // was declared. We use this to resolve names.
613 public NamespaceEntry NamespaceEntry;
615 private Hashtable Cache = new Hashtable ();
617 public readonly string Basename;
619 protected Hashtable defined_names;
621 readonly bool is_generic;
622 readonly int count_type_params;
623 readonly int count_current_type_params;
625 // The emit context for toplevel objects.
626 protected EmitContext ec;
628 public EmitContext EmitContext {
633 // Whether we are Generic
635 public bool IsGeneric {
639 else if (Parent != null)
640 return Parent.IsGeneric;
646 static string[] attribute_targets = new string [] { "type" };
648 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
649 Attributes attrs, Location l)
650 : base (parent, name, attrs, l)
653 Basename = name.Basename;
654 defined_names = new Hashtable ();
655 if (name.TypeArguments != null) {
657 count_type_params = count_current_type_params = name.TypeArguments.Count;
660 count_type_params += parent.count_type_params;
664 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
666 protected bool AddToContainer (MemberCore symbol, string name)
668 if (name == Basename && !(this is Interface) && !(this is Enum)) {
669 if (symbol is TypeParameter)
670 Report.Error (694, symbol.Location,
671 "Type parameter `{0}' has same name as " +
672 "containing type or method", name);
674 Report.SymbolRelatedToPreviousError (this);
675 Report.Error (542, symbol.Location,
676 "`{0}': member names cannot be the same " +
677 "as their enclosing type",
678 symbol.GetSignatureForError ());
683 MemberCore mc = (MemberCore) defined_names [name];
686 defined_names.Add (name, symbol);
690 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
693 if (this is RootTypes) {
694 // TODO: It should not reach this once we merge RecordDecl to AddTo
698 if (symbol is TypeParameter)
699 Report.Error (692, symbol.Location,
700 "Duplicate type parameter `{0}'", name);
702 Report.SymbolRelatedToPreviousError (mc);
703 Report.Error (102, symbol.Location,
704 "The type `{0}' already contains a definition for `{1}'",
705 GetSignatureForError (), symbol.MemberName.Name);
712 /// Returns the MemberCore associated with a given name in the declaration
713 /// space. It doesn't return method based symbols !!
716 public MemberCore GetDefinition (string name)
718 return (MemberCore)defined_names [name];
722 // root_types contains all the types. All TopLevel types
723 // hence have a parent that points to `root_types', that is
724 // why there is a non-obvious test down here.
726 public bool IsTopLevel {
727 get { return (Parent != null && Parent.Parent == null); }
730 public virtual void CloseType ()
732 if ((caching_flags & Flags.CloseTypeCreated) == 0){
734 TypeBuilder.CreateType ();
737 // The try/catch is needed because
738 // nested enumerations fail to load when they
741 // Even if this is the right order (enumerations
742 // declared after types).
744 // Note that this still creates the type and
745 // it is possible to save it
747 caching_flags |= Flags.CloseTypeCreated;
751 protected virtual TypeAttributes TypeAttr {
752 get { return CodeGen.Module.DefaultCharSetType; }
756 /// Should be overriten by the appropriate declaration space
758 public abstract TypeBuilder DefineType ();
761 /// Define all members, but don't apply any attributes or do anything which may
762 /// access not-yet-defined classes. This method also creates the MemberCache.
764 public virtual bool DefineMembers (TypeContainer parent)
766 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
767 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
773 public override string GetSignatureForError ()
775 // Parent.GetSignatureForError
780 // Whether this is an `unsafe context'
782 public bool UnsafeContext {
784 if ((ModFlags & Modifiers.UNSAFE) != 0)
787 return Parent.UnsafeContext;
792 EmitContext type_resolve_ec;
793 protected EmitContext TypeResolveEmitContext {
795 if (type_resolve_ec == null) {
796 // FIXME: I think this should really be one of:
798 // a. type_resolve_ec = Parent.EmitContext;
799 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
801 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
803 type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
805 return type_resolve_ec;
810 // Resolves the expression `e' for a type, and will recursively define
811 // types. This should only be used for resolving base types.
813 protected TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
815 TypeResolveEmitContext.loc = loc;
816 TypeResolveEmitContext.ContainerType = TypeBuilder;
817 TypeResolveEmitContext.ResolvingTypeTree = true;
818 if (this is GenericMethod)
819 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
821 TypeResolveEmitContext.ContainerType = TypeBuilder;
823 return e.ResolveAsTypeTerminal (TypeResolveEmitContext);
826 public bool CheckAccessLevel (Type check_type)
829 if ((this is GenericMethod) || (this is Iterator))
830 tb = Parent.TypeBuilder;
834 if (check_type.IsGenericInstance)
835 check_type = check_type.GetGenericTypeDefinition ();
837 if (check_type == tb)
840 if (TypeBuilder == null)
841 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
842 // However, this is invoked again later -- so safe to return true.
843 // May also be null when resolving top-level attributes.
846 if (check_type.IsGenericParameter)
847 return true; // FIXME
849 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
852 // Broken Microsoft runtime, return public for arrays, no matter what
853 // the accessibility is for their underlying class, and they return
854 // NonPublic visibility for pointers
856 if (check_type.IsArray || check_type.IsPointer)
857 return CheckAccessLevel (TypeManager.GetElementType (check_type));
860 case TypeAttributes.Public:
863 case TypeAttributes.NotPublic:
865 if (TypeBuilder == null)
866 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
867 // However, this is invoked again later -- so safe to return true.
868 // May also be null when resolving top-level attributes.
871 // This test should probably use the declaringtype.
873 return check_type.Assembly == TypeBuilder.Assembly;
875 case TypeAttributes.NestedPublic:
878 case TypeAttributes.NestedPrivate:
879 return NestedAccessible (tb, check_type);
881 case TypeAttributes.NestedFamily:
883 // Only accessible to methods in current type or any subtypes
885 return FamilyAccessible (tb, check_type);
887 case TypeAttributes.NestedFamANDAssem:
888 return (check_type.Assembly == tb.Assembly) &&
889 FamilyAccessible (tb, check_type);
891 case TypeAttributes.NestedFamORAssem:
892 return (check_type.Assembly == tb.Assembly) ||
893 FamilyAccessible (tb, check_type);
895 case TypeAttributes.NestedAssembly:
896 return check_type.Assembly == tb.Assembly;
899 Console.WriteLine ("HERE: " + check_attr);
904 protected bool NestedAccessible (Type tb, Type check_type)
906 Type declaring = check_type.DeclaringType;
907 return TypeBuilder == declaring ||
908 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
911 protected bool FamilyAccessible (Type tb, Type check_type)
913 Type declaring = check_type.DeclaringType;
914 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
917 // Access level of a type.
919 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
920 // Public Assembly Protected
921 Protected = (0 << 0) | (0 << 1) | (X << 2),
922 Public = (X << 0) | (X << 1) | (X << 2),
923 Private = (0 << 0) | (0 << 1) | (0 << 2),
924 Internal = (0 << 0) | (X << 1) | (0 << 2),
925 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
928 static AccessLevel GetAccessLevelFromModifiers (int flags)
930 if ((flags & Modifiers.INTERNAL) != 0) {
932 if ((flags & Modifiers.PROTECTED) != 0)
933 return AccessLevel.ProtectedOrInternal;
935 return AccessLevel.Internal;
937 } else if ((flags & Modifiers.PROTECTED) != 0)
938 return AccessLevel.Protected;
939 else if ((flags & Modifiers.PRIVATE) != 0)
940 return AccessLevel.Private;
942 return AccessLevel.Public;
945 // What is the effective access level of this?
947 AccessLevel EffectiveAccessLevel {
949 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
950 if (!IsTopLevel && (Parent != null))
951 return myAccess & Parent.EffectiveAccessLevel;
956 // Return the access level for type `t'
957 static AccessLevel TypeEffectiveAccessLevel (Type t)
960 return AccessLevel.Public;
961 if (t.IsNestedPrivate)
962 return AccessLevel.Private;
964 return AccessLevel.Internal;
966 // By now, it must be nested
967 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
969 if (t.IsNestedPublic)
971 if (t.IsNestedAssembly)
972 return parentLevel & AccessLevel.Internal;
973 if (t.IsNestedFamily)
974 return parentLevel & AccessLevel.Protected;
975 if (t.IsNestedFamORAssem)
976 return parentLevel & AccessLevel.ProtectedOrInternal;
977 if (t.IsNestedFamANDAssem)
978 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
980 // nested private is taken care of
982 throw new Exception ("I give up, what are you?");
986 // This answers `is the type P, as accessible as a member M which has the
987 // accessability @flags which is declared as a nested member of the type T, this declspace'
989 public bool AsAccessible (Type p, int flags)
991 if (p.IsGenericParameter)
992 return true; // FIXME
995 // 1) if M is private, its accessability is the same as this declspace.
996 // we already know that P is accessible to T before this method, so we
1000 if ((flags & Modifiers.PRIVATE) != 0)
1003 while (p.IsArray || p.IsPointer || p.IsByRef)
1004 p = TypeManager.GetElementType (p);
1006 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1007 AccessLevel mAccess = this.EffectiveAccessLevel &
1008 GetAccessLevelFromModifiers (flags);
1010 // for every place from which we can access M, we must
1011 // be able to access P as well. So, we want
1012 // For every bit in M and P, M_i -> P_1 == true
1013 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1015 return ~ (~ mAccess | pAccess) == 0;
1018 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1020 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1025 // Return the nested type with name @name. Ensures that the nested type
1026 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1028 public virtual Type FindNestedType (string name)
1033 private Type LookupNestedTypeInHierarchy (string name)
1035 // if the member cache has been created, lets use it.
1036 // the member cache is MUCH faster.
1037 if (MemberCache != null)
1038 return MemberCache.FindNestedType (name);
1040 // no member cache. Do it the hard way -- reflection
1042 for (Type current_type = TypeBuilder;
1043 current_type != null && current_type != TypeManager.object_type;
1044 current_type = current_type.BaseType) {
1045 if (current_type.IsGenericInstance)
1046 current_type = current_type.GetGenericTypeDefinition ();
1047 if (current_type is TypeBuilder) {
1048 DeclSpace decl = this;
1049 if (current_type != TypeBuilder)
1050 decl = TypeManager.LookupDeclSpace (current_type);
1051 t = decl.FindNestedType (name);
1053 t = TypeManager.GetNestedType (current_type, name);
1056 if (t != null && CheckAccessLevel (t))
1064 // Public function used to locate types, this can only
1065 // be used after the ResolveTree function has been invoked.
1067 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1069 // Returns: Type or null if they type can not be found.
1071 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1073 if (this is PartialContainer)
1074 throw new InternalErrorException ("Should not get here");
1076 if (Cache.Contains (name))
1077 return (FullNamedExpression) Cache [name];
1079 FullNamedExpression e;
1080 Type t = LookupNestedTypeInHierarchy (name);
1082 e = new TypeExpression (t, Location.Null);
1083 else if (Parent != null && Parent != RootContext.Tree.Types)
1084 e = Parent.LookupType (name, loc, ignore_cs0104);
1086 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1093 /// This function is broken and not what you're looking for. It should only
1094 /// be used while the type is still being created since it doesn't use the cache
1095 /// and relies on the filter doing the member name check.
1097 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1098 MemberFilter filter, object criteria);
1101 /// If we have a MemberCache, return it. This property may return null if the
1102 /// class doesn't have a member cache or while it's still being created.
1104 public abstract MemberCache MemberCache {
1108 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1110 if (a.Type == TypeManager.required_attr_type) {
1111 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1114 TypeBuilder.SetCustomAttribute (cb);
1118 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1119 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1121 public bool GetClsCompliantAttributeValue ()
1123 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1124 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1126 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1128 if (OptAttributes != null) {
1129 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1130 if (cls_attribute != null) {
1131 caching_flags |= Flags.HasClsCompliantAttribute;
1132 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1133 caching_flags |= Flags.ClsCompliantAttributeTrue;
1140 if (Parent == null) {
1141 if (CodeGen.Assembly.IsClsCompliant) {
1142 caching_flags |= Flags.ClsCompliantAttributeTrue;
1148 if (Parent.GetClsCompliantAttributeValue ()) {
1149 caching_flags |= Flags.ClsCompliantAttributeTrue;
1156 // Extensions for generics
1158 TypeParameter[] type_params;
1159 TypeParameter[] type_param_list;
1161 protected string GetInstantiationName ()
1163 StringBuilder sb = new StringBuilder (Name);
1165 for (int i = 0; i < type_param_list.Length; i++) {
1168 sb.Append (type_param_list [i].Name);
1171 return sb.ToString ();
1174 bool check_type_parameter (ArrayList list, int start, string name)
1176 for (int i = 0; i < start; i++) {
1177 TypeParameter param = (TypeParameter) list [i];
1179 if (param.Name != name)
1182 if (RootContext.WarningLevel >= 3)
1185 "Type parameter `{0}' has same name " +
1186 "as type parameter from outer type `{1}'",
1187 name, Parent.GetInstantiationName ());
1195 TypeParameter[] initialize_type_params ()
1197 if (type_param_list != null)
1198 return type_param_list;
1200 DeclSpace the_parent = Parent;
1201 if (this is GenericMethod)
1205 TypeParameter[] parent_params = null;
1206 if ((the_parent != null) && the_parent.IsGeneric) {
1207 parent_params = the_parent.initialize_type_params ();
1208 start = parent_params != null ? parent_params.Length : 0;
1211 ArrayList list = new ArrayList ();
1212 if (parent_params != null)
1213 list.AddRange (parent_params);
1215 int count = type_params != null ? type_params.Length : 0;
1216 for (int i = 0; i < count; i++) {
1217 TypeParameter param = type_params [i];
1218 check_type_parameter (list, start, param.Name);
1222 type_param_list = new TypeParameter [list.Count];
1223 list.CopyTo (type_param_list, 0);
1224 return type_param_list;
1227 public virtual void SetParameterInfo (ArrayList constraints_list)
1230 if (constraints_list != null) {
1232 80, Location, "Contraints are not allowed " +
1233 "on non-generic declarations");
1239 string[] names = MemberName.TypeArguments.GetDeclarations ();
1240 type_params = new TypeParameter [names.Length];
1243 // Register all the names
1245 for (int i = 0; i < type_params.Length; i++) {
1246 string name = names [i];
1248 Constraints constraints = null;
1249 if (constraints_list != null) {
1250 foreach (Constraints constraint in constraints_list) {
1251 if (constraint == null)
1253 if (constraint.TypeParameter == name) {
1254 constraints = constraint;
1260 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1262 AddToContainer (type_params [i], name);
1266 public TypeParameter[] TypeParameters {
1269 throw new InvalidOperationException ();
1270 if (type_param_list == null)
1271 initialize_type_params ();
1273 return type_param_list;
1277 protected TypeParameter[] CurrentTypeParameters {
1280 throw new InvalidOperationException ();
1281 if (type_params != null)
1284 return new TypeParameter [0];
1288 public int CountTypeParameters {
1290 return count_type_params;
1294 public int CountCurrentTypeParameters {
1296 return count_current_type_params;
1300 public TypeParameterExpr LookupGeneric (string name, Location loc)
1305 foreach (TypeParameter type_param in CurrentTypeParameters) {
1306 if (type_param.Name != name)
1309 return new TypeParameterExpr (type_param, loc);
1313 return Parent.LookupGeneric (name, loc);
1318 public override string[] ValidAttributeTargets {
1319 get { return attribute_targets; }
1324 /// This is a readonly list of MemberInfo's.
1326 public class MemberList : IList {
1327 public readonly IList List;
1331 /// Create a new MemberList from the given IList.
1333 public MemberList (IList list)
1338 this.List = new ArrayList ();
1343 /// Concatenate the ILists `first' and `second' to a new MemberList.
1345 public MemberList (IList first, IList second)
1347 ArrayList list = new ArrayList ();
1348 list.AddRange (first);
1349 list.AddRange (second);
1354 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1357 /// Cast the MemberList into a MemberInfo[] array.
1360 /// This is an expensive operation, only use it if it's really necessary.
1362 public static explicit operator MemberInfo [] (MemberList list)
1364 Timer.StartTimer (TimerType.MiscTimer);
1365 MemberInfo [] result = new MemberInfo [list.Count];
1366 list.CopyTo (result, 0);
1367 Timer.StopTimer (TimerType.MiscTimer);
1379 public bool IsSynchronized {
1381 return List.IsSynchronized;
1385 public object SyncRoot {
1387 return List.SyncRoot;
1391 public void CopyTo (Array array, int index)
1393 List.CopyTo (array, index);
1398 public IEnumerator GetEnumerator ()
1400 return List.GetEnumerator ();
1405 public bool IsFixedSize {
1411 public bool IsReadOnly {
1417 object IList.this [int index] {
1419 return List [index];
1423 throw new NotSupportedException ();
1427 // FIXME: try to find out whether we can avoid the cast in this indexer.
1428 public MemberInfo this [int index] {
1430 return (MemberInfo) List [index];
1434 public int Add (object value)
1436 throw new NotSupportedException ();
1439 public void Clear ()
1441 throw new NotSupportedException ();
1444 public bool Contains (object value)
1446 return List.Contains (value);
1449 public int IndexOf (object value)
1451 return List.IndexOf (value);
1454 public void Insert (int index, object value)
1456 throw new NotSupportedException ();
1459 public void Remove (object value)
1461 throw new NotSupportedException ();
1464 public void RemoveAt (int index)
1466 throw new NotSupportedException ();
1471 /// This interface is used to get all members of a class when creating the
1472 /// member cache. It must be implemented by all DeclSpace derivatives which
1473 /// want to support the member cache and by TypeHandle to get caching of
1474 /// non-dynamic types.
1476 public interface IMemberContainer {
1478 /// The name of the IMemberContainer. This is only used for
1479 /// debugging purposes.
1486 /// The type of this IMemberContainer.
1493 /// Returns the IMemberContainer of the base class or null if this
1494 /// is an interface or TypeManger.object_type.
1495 /// This is used when creating the member cache for a class to get all
1496 /// members from the base class.
1498 MemberCache BaseCache {
1503 /// Whether this is an interface.
1510 /// Returns all members of this class with the corresponding MemberTypes
1511 /// and BindingFlags.
1514 /// When implementing this method, make sure not to return any inherited
1515 /// members and check the MemberTypes and BindingFlags properly.
1516 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1517 /// get the BindingFlags (static/non-static,public/non-public) in the
1518 /// MemberInfo class, but the cache needs this information. That's why
1519 /// this method is called multiple times with different BindingFlags.
1521 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1524 /// Return the container's member cache.
1526 MemberCache MemberCache {
1532 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1533 /// member lookups. It has a member name based hash table; it maps each member
1534 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1535 /// and the BindingFlags that were initially used to get it. The cache contains
1536 /// all members of the current class and all inherited members. If this cache is
1537 /// for an interface types, it also contains all inherited members.
1539 /// There are two ways to get a MemberCache:
1540 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1541 /// use the DeclSpace.MemberCache property.
1542 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1543 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1545 public class MemberCache {
1546 public readonly IMemberContainer Container;
1547 protected Hashtable member_hash;
1548 protected Hashtable method_hash;
1551 /// Create a new MemberCache for the given IMemberContainer `container'.
1553 public MemberCache (IMemberContainer container)
1555 this.Container = container;
1557 Timer.IncrementCounter (CounterType.MemberCache);
1558 Timer.StartTimer (TimerType.CacheInit);
1560 // If we have a base class (we have a base class unless we're
1561 // TypeManager.object_type), we deep-copy its MemberCache here.
1562 if (Container.BaseCache != null)
1563 member_hash = SetupCache (Container.BaseCache);
1565 member_hash = new Hashtable ();
1567 // If this is neither a dynamic type nor an interface, create a special
1568 // method cache with all declared and inherited methods.
1569 Type type = container.Type;
1570 if (!(type is TypeBuilder) && !type.IsInterface &&
1571 // !(type.IsGenericInstance && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1572 !type.IsGenericInstance &&
1573 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1574 method_hash = new Hashtable ();
1578 // Add all members from the current class.
1579 AddMembers (Container);
1581 Timer.StopTimer (TimerType.CacheInit);
1584 public MemberCache (Type[] ifaces)
1587 // The members of this cache all belong to other caches.
1588 // So, 'Container' will not be used.
1590 this.Container = null;
1592 member_hash = new Hashtable ();
1596 foreach (Type itype in ifaces)
1597 AddCacheContents (TypeManager.LookupMemberCache (itype));
1601 /// Bootstrap this member cache by doing a deep-copy of our base.
1603 Hashtable SetupCache (MemberCache base_class)
1605 Hashtable hash = new Hashtable ();
1607 if (base_class == null)
1610 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1611 while (it.MoveNext ()) {
1612 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1619 /// Add the contents of `cache' to the member_hash.
1621 void AddCacheContents (MemberCache cache)
1623 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1624 while (it.MoveNext ()) {
1625 ArrayList list = (ArrayList) member_hash [it.Key];
1627 member_hash [it.Key] = list = new ArrayList ();
1629 ArrayList entries = (ArrayList) it.Value;
1630 for (int i = entries.Count-1; i >= 0; i--) {
1631 CacheEntry entry = (CacheEntry) entries [i];
1633 if (entry.Container != cache.Container)
1641 /// Add all members from class `container' to the cache.
1643 void AddMembers (IMemberContainer container)
1645 // We need to call AddMembers() with a single member type at a time
1646 // to get the member type part of CacheEntry.EntryType right.
1647 if (!container.IsInterface) {
1648 AddMembers (MemberTypes.Constructor, container);
1649 AddMembers (MemberTypes.Field, container);
1651 AddMembers (MemberTypes.Method, container);
1652 AddMembers (MemberTypes.Property, container);
1653 AddMembers (MemberTypes.Event, container);
1654 // Nested types are returned by both Static and Instance searches.
1655 AddMembers (MemberTypes.NestedType,
1656 BindingFlags.Static | BindingFlags.Public, container);
1657 AddMembers (MemberTypes.NestedType,
1658 BindingFlags.Static | BindingFlags.NonPublic, container);
1661 void AddMembers (MemberTypes mt, IMemberContainer container)
1663 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1664 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1665 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1666 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1670 /// Add all members from class `container' with the requested MemberTypes and
1671 /// BindingFlags to the cache. This method is called multiple times with different
1672 /// MemberTypes and BindingFlags.
1674 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1676 MemberList members = container.GetMembers (mt, bf);
1678 foreach (MemberInfo member in members) {
1679 string name = member.Name;
1681 int pos = name.IndexOf ('<');
1683 name = name.Substring (0, pos);
1685 // We use a name-based hash table of ArrayList's.
1686 ArrayList list = (ArrayList) member_hash [name];
1688 list = new ArrayList ();
1689 member_hash.Add (name, list);
1692 // When this method is called for the current class, the list will
1693 // already contain all inherited members from our base classes.
1694 // We cannot add new members in front of the list since this'd be an
1695 // expensive operation, that's why the list is sorted in reverse order
1696 // (ie. members from the current class are coming last).
1697 list.Add (new CacheEntry (container, member, mt, bf));
1702 /// Add all declared and inherited methods from class `type' to the method cache.
1704 void AddMethods (Type type)
1706 AddMethods (BindingFlags.Static | BindingFlags.Public |
1707 BindingFlags.FlattenHierarchy, type);
1708 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1709 BindingFlags.FlattenHierarchy, type);
1710 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1711 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1714 static ArrayList overrides = new ArrayList ();
1716 void AddMethods (BindingFlags bf, Type type)
1718 MethodBase [] members = type.GetMethods (bf);
1720 Array.Reverse (members);
1722 foreach (MethodBase member in members) {
1723 string name = member.Name;
1725 // We use a name-based hash table of ArrayList's.
1726 ArrayList list = (ArrayList) method_hash [name];
1728 list = new ArrayList ();
1729 method_hash.Add (name, list);
1732 MethodInfo curr = (MethodInfo) member;
1733 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1734 MethodInfo base_method = curr.GetBaseDefinition ();
1736 if (base_method == curr)
1737 // Not every virtual function needs to have a NewSlot flag.
1740 overrides.Add (curr);
1741 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1745 if (overrides.Count > 0) {
1746 for (int i = 0; i < overrides.Count; ++i)
1747 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1751 // Unfortunately, the elements returned by Type.GetMethods() aren't
1752 // sorted so we need to do this check for every member.
1753 BindingFlags new_bf = bf;
1754 if (member.DeclaringType == type)
1755 new_bf |= BindingFlags.DeclaredOnly;
1757 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1762 /// Compute and return a appropriate `EntryType' magic number for the given
1763 /// MemberTypes and BindingFlags.
1765 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1767 EntryType type = EntryType.None;
1769 if ((mt & MemberTypes.Constructor) != 0)
1770 type |= EntryType.Constructor;
1771 if ((mt & MemberTypes.Event) != 0)
1772 type |= EntryType.Event;
1773 if ((mt & MemberTypes.Field) != 0)
1774 type |= EntryType.Field;
1775 if ((mt & MemberTypes.Method) != 0)
1776 type |= EntryType.Method;
1777 if ((mt & MemberTypes.Property) != 0)
1778 type |= EntryType.Property;
1779 // Nested types are returned by static and instance searches.
1780 if ((mt & MemberTypes.NestedType) != 0)
1781 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1783 if ((bf & BindingFlags.Instance) != 0)
1784 type |= EntryType.Instance;
1785 if ((bf & BindingFlags.Static) != 0)
1786 type |= EntryType.Static;
1787 if ((bf & BindingFlags.Public) != 0)
1788 type |= EntryType.Public;
1789 if ((bf & BindingFlags.NonPublic) != 0)
1790 type |= EntryType.NonPublic;
1791 if ((bf & BindingFlags.DeclaredOnly) != 0)
1792 type |= EntryType.Declared;
1798 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1799 /// denote multiple member types. Returns true if the given flags value denotes a
1800 /// single member types.
1802 public static bool IsSingleMemberType (MemberTypes mt)
1805 case MemberTypes.Constructor:
1806 case MemberTypes.Event:
1807 case MemberTypes.Field:
1808 case MemberTypes.Method:
1809 case MemberTypes.Property:
1810 case MemberTypes.NestedType:
1819 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1820 /// number to speed up the searching process.
1823 protected enum EntryType {
1828 MaskStatic = Instance|Static,
1832 MaskProtection = Public|NonPublic,
1836 Constructor = 0x020,
1843 MaskType = Constructor|Event|Field|Method|Property|NestedType
1846 protected class CacheEntry {
1847 public readonly IMemberContainer Container;
1848 public EntryType EntryType;
1849 public MemberInfo Member;
1851 public CacheEntry (IMemberContainer container, MemberInfo member,
1852 MemberTypes mt, BindingFlags bf)
1854 this.Container = container;
1855 this.Member = member;
1856 this.EntryType = GetEntryType (mt, bf);
1859 public override string ToString ()
1861 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1867 /// This is called each time we're walking up one level in the class hierarchy
1868 /// and checks whether we can abort the search since we've already found what
1869 /// we were looking for.
1871 protected bool DoneSearching (ArrayList list)
1874 // We've found exactly one member in the current class and it's not
1875 // a method or constructor.
1877 if (list.Count == 1 && !(list [0] is MethodBase))
1881 // Multiple properties: we query those just to find out the indexer
1884 if ((list.Count > 0) && (list [0] is PropertyInfo))
1891 /// Looks up members with name `name'. If you provide an optional
1892 /// filter function, it'll only be called with members matching the
1893 /// requested member name.
1895 /// This method will try to use the cache to do the lookup if possible.
1897 /// Unlike other FindMembers implementations, this method will always
1898 /// check all inherited members - even when called on an interface type.
1900 /// If you know that you're only looking for methods, you should use
1901 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1902 /// When doing a method-only search, it'll try to use a special method
1903 /// cache (unless it's a dynamic type or an interface) and the returned
1904 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1905 /// The lookup process will automatically restart itself in method-only
1906 /// search mode if it discovers that it's about to return methods.
1908 ArrayList global = new ArrayList ();
1909 bool using_global = false;
1911 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1913 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1914 MemberFilter filter, object criteria)
1917 throw new Exception ();
1919 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1920 bool method_search = mt == MemberTypes.Method;
1921 // If we have a method cache and we aren't already doing a method-only search,
1922 // then we restart a method search if the first match is a method.
1923 bool do_method_search = !method_search && (method_hash != null);
1925 ArrayList applicable;
1927 // If this is a method-only search, we try to use the method cache if
1928 // possible; a lookup in the method cache will return a MemberInfo with
1929 // the correct ReflectedType for inherited methods.
1931 if (method_search && (method_hash != null))
1932 applicable = (ArrayList) method_hash [name];
1934 applicable = (ArrayList) member_hash [name];
1936 if (applicable == null)
1937 return emptyMemberInfo;
1940 // 32 slots gives 53 rss/54 size
1941 // 2/4 slots gives 55 rss
1943 // Strange: from 25,000 calls, only 1,800
1944 // are above 2. Why does this impact it?
1947 using_global = true;
1949 Timer.StartTimer (TimerType.CachedLookup);
1951 EntryType type = GetEntryType (mt, bf);
1953 IMemberContainer current = Container;
1956 // `applicable' is a list of all members with the given member name `name'
1957 // in the current class and all its base classes. The list is sorted in
1958 // reverse order due to the way how the cache is initialy created (to speed
1959 // things up, we're doing a deep-copy of our base).
1961 for (int i = applicable.Count-1; i >= 0; i--) {
1962 CacheEntry entry = (CacheEntry) applicable [i];
1964 // This happens each time we're walking one level up in the class
1965 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1966 // the first time this happens (this may already happen in the first
1967 // iteration of this loop if there are no members with the name we're
1968 // looking for in the current class).
1969 if (entry.Container != current) {
1970 if (declared_only || DoneSearching (global))
1973 current = entry.Container;
1976 // Is the member of the correct type ?
1977 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1980 // Is the member static/non-static ?
1981 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1984 // Apply the filter to it.
1985 if (filter (entry.Member, criteria)) {
1986 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1987 do_method_search = false;
1988 global.Add (entry.Member);
1992 Timer.StopTimer (TimerType.CachedLookup);
1994 // If we have a method cache and we aren't already doing a method-only
1995 // search, we restart in method-only search mode if the first match is
1996 // a method. This ensures that we return a MemberInfo with the correct
1997 // ReflectedType for inherited methods.
1998 if (do_method_search && (global.Count > 0)){
1999 using_global = false;
2001 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2004 using_global = false;
2005 MemberInfo [] copy = new MemberInfo [global.Count];
2006 global.CopyTo (copy);
2010 // find the nested type @name in @this.
2011 public Type FindNestedType (string name)
2013 ArrayList applicable = (ArrayList) member_hash [name];
2014 if (applicable == null)
2017 for (int i = applicable.Count-1; i >= 0; i--) {
2018 CacheEntry entry = (CacheEntry) applicable [i];
2019 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2020 return (Type) entry.Member;
2027 // This finds the method or property for us to override. invocationType is the type where
2028 // the override is going to be declared, name is the name of the method/property, and
2029 // paramTypes is the parameters, if any to the method or property
2031 // Because the MemberCache holds members from this class and all the base classes,
2032 // we can avoid tons of reflection stuff.
2034 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2036 ArrayList applicable;
2037 if (method_hash != null && !is_property)
2038 applicable = (ArrayList) method_hash [name];
2040 applicable = (ArrayList) member_hash [name];
2042 if (applicable == null)
2045 // Walk the chain of methods, starting from the top.
2047 for (int i = applicable.Count - 1; i >= 0; i--) {
2048 CacheEntry entry = (CacheEntry) applicable [i];
2050 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2053 PropertyInfo pi = null;
2054 MethodInfo mi = null;
2055 FieldInfo fi = null;
2056 Type [] cmpAttrs = null;
2059 if ((entry.EntryType & EntryType.Field) != 0) {
2060 fi = (FieldInfo)entry.Member;
2062 // TODO: For this case we ignore member type
2063 //fb = TypeManager.GetField (fi);
2064 //cmpAttrs = new Type[] { fb.MemberType };
2066 pi = (PropertyInfo) entry.Member;
2067 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2070 mi = (MethodInfo) entry.Member;
2071 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2075 // TODO: Almost duplicate !
2077 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2078 case FieldAttributes.Private:
2080 // A private method is Ok if we are a nested subtype.
2081 // The spec actually is not very clear about this, see bug 52458.
2083 if (invocationType != entry.Container.Type &
2084 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2088 case FieldAttributes.FamANDAssem:
2089 case FieldAttributes.Assembly:
2091 // Check for assembly methods
2093 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2097 return entry.Member;
2101 // Check the arguments
2103 if (cmpAttrs.Length != paramTypes.Length)
2106 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2107 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2112 // get one of the methods because this has the visibility info.
2115 mi = pi.GetGetMethod (true);
2117 mi = pi.GetSetMethod (true);
2123 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2124 case MethodAttributes.Private:
2126 // A private method is Ok if we are a nested subtype.
2127 // The spec actually is not very clear about this, see bug 52458.
2129 if (invocationType.Equals (entry.Container.Type) ||
2130 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2131 return entry.Member;
2134 case MethodAttributes.FamANDAssem:
2135 case MethodAttributes.Assembly:
2137 // Check for assembly methods
2139 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2140 return entry.Member;
2145 // A protected method is ok, because we are overriding.
2146 // public is always ok.
2148 return entry.Member;
2158 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2159 /// We handle two cases. The first is for types without parameters (events, field, properties).
2160 /// The second are methods, indexers and this is why ignore_complex_types is here.
2161 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2163 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2165 ArrayList applicable = null;
2167 if (method_hash != null)
2168 applicable = (ArrayList) method_hash [name];
2170 if (applicable != null) {
2171 for (int i = applicable.Count - 1; i >= 0; i--) {
2172 CacheEntry entry = (CacheEntry) applicable [i];
2173 if ((entry.EntryType & EntryType.Public) != 0)
2174 return entry.Member;
2178 if (member_hash == null)
2180 applicable = (ArrayList) member_hash [name];
2182 if (applicable != null) {
2183 for (int i = applicable.Count - 1; i >= 0; i--) {
2184 CacheEntry entry = (CacheEntry) applicable [i];
2185 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2186 if (ignore_complex_types) {
2187 if ((entry.EntryType & EntryType.Method) != 0)
2190 // Does exist easier way how to detect indexer ?
2191 if ((entry.EntryType & EntryType.Property) != 0) {
2192 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2193 if (arg_types.Length > 0)
2197 return entry.Member;
2204 Hashtable locase_table;
2207 /// Builds low-case table for CLS Compliance test
2209 public Hashtable GetPublicMembers ()
2211 if (locase_table != null)
2212 return locase_table;
2214 locase_table = new Hashtable ();
2215 foreach (DictionaryEntry entry in member_hash) {
2216 ArrayList members = (ArrayList)entry.Value;
2217 for (int ii = 0; ii < members.Count; ++ii) {
2218 CacheEntry member_entry = (CacheEntry) members [ii];
2220 if ((member_entry.EntryType & EntryType.Public) == 0)
2223 // TODO: Does anyone know easier way how to detect that member is internal ?
2224 switch (member_entry.EntryType & EntryType.MaskType) {
2225 case EntryType.Constructor:
2228 case EntryType.Field:
2229 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2233 case EntryType.Method:
2234 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2238 case EntryType.Property:
2239 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2240 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2244 case EntryType.Event:
2245 EventInfo ei = (EventInfo)member_entry.Member;
2246 MethodInfo mi = ei.GetAddMethod ();
2247 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2251 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2252 locase_table [lcase] = member_entry.Member;
2256 return locase_table;
2259 public Hashtable Members {
2266 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2268 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2270 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2272 for (int i = 0; i < al.Count; ++i) {
2273 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2276 if (entry.Member == this_builder)
2279 if ((entry.EntryType & tested_type) != tested_type)
2282 MethodBase method_to_compare = (MethodBase)entry.Member;
2283 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2284 method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare));
2286 if (result == AttributeTester.Result.Ok)
2289 IMethodData md = TypeManager.GetMethod (method_to_compare);
2291 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2292 // However it is exactly what csc does.
2293 if (md != null && !md.IsClsComplianceRequired (method.Parent))
2296 Report.SymbolRelatedToPreviousError (entry.Member);
2298 case AttributeTester.Result.RefOutArrayError:
2299 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2301 case AttributeTester.Result.ArrayArrayError:
2302 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2306 throw new NotImplementedException (result.ToString ());