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;
30 public readonly Location Location;
32 public static readonly MemberName Null = new MemberName ("", Location.Null);
36 private MemberName (MemberName left, string name, bool is_double_colon,
37 TypeArguments args, Location loc)
41 this.is_double_colon = is_double_colon;
42 this.TypeArguments = args;
46 public MemberName (string name, TypeArguments args, Location loc)
49 this.TypeArguments = args;
52 public MemberName (string name, Location loc)
58 public MemberName (MemberName left, string name, Location loc)
64 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
65 : this (name, args, loc)
70 public MemberName (string alias, string name, Location loc)
71 : this (new MemberName (alias, loc), name, true, null, loc)
75 public MemberName (MemberName left, MemberName right)
76 : this (left, right, right.Location)
80 public MemberName (MemberName left, MemberName right, Location loc)
81 : this (null, right.Name, false, right.TypeArguments, loc)
83 if (right.is_double_colon)
84 throw new InternalErrorException ("Cannot append double_colon member name");
85 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
88 static readonly char [] dot_array = { '.' };
90 public static MemberName FromDotted (string name, Location loc)
92 string [] elements = name.Split (dot_array);
93 int count = elements.Length;
95 MemberName n = new MemberName (elements [i++], loc);
97 n = new MemberName (n, elements [i++], loc);
101 public string GetName ()
103 string connect = is_double_colon ? "::" : ".";
105 return Left.GetName () + connect + Name;
110 public bool IsGeneric {
112 if (TypeArguments != null)
114 else if (Left != null)
115 return Left.IsGeneric;
121 public string GetName (bool is_generic)
123 string name = is_generic ? Basename : Name;
124 string connect = is_double_colon ? "::" : ".";
126 return Left.GetName (is_generic) + connect + name;
131 public int CountTypeArguments {
133 if (TypeArguments == null)
136 return TypeArguments.Count;
140 public string MethodName {
142 string connect = is_double_colon ? "::" : ".";
144 return Left.FullName + connect + Name;
150 public static string MakeName (string name, TypeArguments args)
155 return name + "`" + args.Count;
158 public static string MakeName (string name, int count)
160 return name + "`" + count;
163 public string GetTypeName ()
165 string connect = is_double_colon ? "::" : ".";
167 return Left.GetTypeName () + connect +
168 MakeName (Name, TypeArguments);
170 return MakeName (Name, TypeArguments);
173 protected bool IsUnbound {
175 if ((Left != null) && Left.IsUnbound)
177 else if (TypeArguments == null)
180 return TypeArguments.IsUnbound;
184 protected bool CheckUnbound (Location loc)
186 if ((Left != null) && !Left.CheckUnbound (loc))
188 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
189 Report.Error (1031, loc, "Type expected");
196 public Expression GetTypeExpression ()
199 if (!CheckUnbound (Location))
202 return new UnboundTypeExpression (this, Location);
206 if (TypeArguments != null)
207 return new SimpleName (Basename, TypeArguments, Location);
209 return new SimpleName (Name, Location);
212 if (is_double_colon) {
213 if (Left.Left != null)
214 throw new InternalErrorException ("The left side of a :: should be an identifier");
215 return new QualifiedAliasMember (Left.Name, Name, Location);
218 Expression lexpr = Left.GetTypeExpression ();
219 return new MemberAccess (lexpr, Name, TypeArguments, Location);
222 public MemberName Clone ()
224 MemberName left_clone = Left == null ? null : Left.Clone ();
225 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
228 public string Basename {
230 if (TypeArguments != null)
231 return MakeName (Name, TypeArguments);
237 public string FullName {
239 if (TypeArguments != null)
240 return Name + "<" + TypeArguments + ">";
246 public override string ToString ()
248 string connect = is_double_colon ? "::" : ".";
250 return Left.FullName + connect + FullName;
255 public override bool Equals (object other)
257 return Equals (other as MemberName);
260 public bool Equals (MemberName other)
264 if (other == null || Name != other.Name)
266 if (is_double_colon != other.is_double_colon)
269 if ((TypeArguments != null) &&
270 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
273 if ((TypeArguments == null) && (other.TypeArguments != null))
277 return other.Left == null;
279 return Left.Equals (other.Left);
282 public override int GetHashCode ()
284 int hash = Name.GetHashCode ();
285 for (MemberName n = Left; n != null; n = n.Left)
286 hash ^= n.Name.GetHashCode ();
290 if (TypeArguments != null)
291 hash ^= TypeArguments.Count << 5;
293 return hash & 0x7FFFFFFF;
298 /// Base representation for members. This is used to keep track
299 /// of Name, Location and Modifier flags, and handling Attributes.
301 public abstract class MemberCore : Attributable, IResolveContext {
306 protected string cached_name;
309 if (cached_name == null)
310 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
315 // Is not readonly because of IndexerName attribute
316 private MemberName member_name;
317 public MemberName MemberName {
318 get { return member_name; }
322 /// Modifier flags that the user specified in the source code
326 public /*readonly*/ DeclSpace Parent;
329 /// Location where this declaration happens
331 public Location Location {
332 get { return member_name.Location; }
336 /// XML documentation comment
338 public string DocComment;
341 /// Represents header string for documentation comment
342 /// for each member types.
344 public abstract string DocCommentHeader { get; }
348 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
349 Obsolete = 1 << 1, // Type has obsolete attribute
350 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
351 ClsCompliant = 1 << 3, // Type is CLS Compliant
352 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
353 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
354 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
355 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
356 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
357 Excluded = 1 << 9, // Method is conditional
358 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
360 IsAssigned = 1 << 12 // Field is assigned
364 /// MemberCore flags at first detected then cached
366 internal Flags caching_flags;
368 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
371 if (parent is PartialContainer && !(this is PartialContainer))
372 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
376 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
379 protected virtual void SetMemberName (MemberName new_name)
381 member_name = new_name;
385 public abstract bool Define ();
388 // Returns full member name for error message
390 public virtual string GetSignatureForError ()
392 if (Parent == null || Parent.Parent == null)
395 return String.Concat (Parent.GetSignatureForError (), '.', Name);
399 /// Base Emit method. This is also entry point for CLS-Compliant verification.
401 public virtual void Emit ()
403 if (!RootContext.VerifyClsCompliance)
406 VerifyClsCompliance (Parent);
409 public virtual bool IsUsed {
410 get { return (caching_flags & Flags.IsUsed) != 0; }
413 public void SetMemberIsUsed ()
415 caching_flags |= Flags.IsUsed;
419 /// Returns instance of ObsoleteAttribute for this MemberCore
421 public virtual ObsoleteAttribute GetObsoleteAttribute ()
423 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
424 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
428 caching_flags &= ~Flags.Obsolete_Undetected;
430 if (OptAttributes == null)
433 Attribute obsolete_attr = OptAttributes.Search (
434 TypeManager.obsolete_attribute_type);
435 if (obsolete_attr == null)
438 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
439 if (obsolete == null)
442 caching_flags |= Flags.Obsolete;
447 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
449 public virtual void CheckObsoleteness (Location loc)
452 Parent.CheckObsoleteness (loc);
454 ObsoleteAttribute oa = GetObsoleteAttribute ();
459 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
462 protected void CheckObsoleteType (Expression type)
464 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type.Type);
465 if (obsolete_attr == null)
468 if (IsInObsoleteScope)
471 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (type.Type), type.Location);
475 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
477 public override bool IsClsComplianceRequired ()
479 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
480 return (caching_flags & Flags.ClsCompliant) != 0;
482 if (GetClsCompliantAttributeValue (Parent) && IsExposedFromAssembly (Parent)) {
483 caching_flags &= ~Flags.ClsCompliance_Undetected;
484 caching_flags |= Flags.ClsCompliant;
488 caching_flags &= ~Flags.ClsCompliance_Undetected;
493 /// Returns true when MemberCore is exposed from assembly.
495 public bool IsExposedFromAssembly (DeclSpace ds)
497 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
500 DeclSpace parentContainer = ds;
501 while (parentContainer != null && parentContainer.ModFlags != 0) {
502 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
504 parentContainer = parentContainer.Parent;
510 /// Resolve CLSCompliantAttribute value or gets cached value.
512 bool GetClsCompliantAttributeValue (DeclSpace ds)
514 if (OptAttributes != null) {
515 Attribute cls_attribute = OptAttributes.Search (
516 TypeManager.cls_compliant_attribute_type);
517 if (cls_attribute != null) {
518 caching_flags |= Flags.HasClsCompliantAttribute;
519 return cls_attribute.GetClsCompliantAttributeValue ();
522 return ds.GetClsCompliantAttributeValue ();
526 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
528 protected bool HasClsCompliantAttribute {
530 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
535 /// It helps to handle error 102 & 111 detection
537 public virtual bool MarkForDuplicationCheck ()
543 /// The main virtual method for CLS-Compliant verifications.
544 /// The method returns true if member is CLS-Compliant and false if member is not
545 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
546 /// and add their extra verifications.
548 protected virtual bool VerifyClsCompliance (DeclSpace ds)
550 if (!IsClsComplianceRequired ()) {
551 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
552 if (!IsExposedFromAssembly (ds))
553 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
554 if (!CodeGen.Assembly.IsClsCompliant)
555 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
560 if (!CodeGen.Assembly.IsClsCompliant) {
561 if (HasClsCompliantAttribute) {
562 Report.Error (3014, Location,
563 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
564 GetSignatureForError ());
569 if (member_name.Name [0] == '_') {
570 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
576 // Raised (and passed an XmlElement that contains the comment)
577 // when GenerateDocComment is writing documentation expectedly.
579 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
584 // Returns a string that represents the signature for this
585 // member which should be used in XML documentation.
587 public virtual string GetDocCommentName (DeclSpace ds)
589 if (ds == null || this is DeclSpace)
590 return DocCommentHeader + Name;
592 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
596 // Generates xml doc comments (if any), and if required,
597 // handle warning report.
599 internal virtual void GenerateDocComment (DeclSpace ds)
601 DocUtil.GenerateDocComment (this, ds);
604 public override IResolveContext ResolveContext {
610 #region IResolveContext Members
612 public virtual DeclSpace DeclContainer {
618 public bool IsInObsoleteScope {
620 if (GetObsoleteAttribute () != null)
623 return Parent == null ? false : Parent.IsInObsoleteScope;
627 public bool IsInUnsafeScope {
629 if ((ModFlags & Modifiers.UNSAFE) != 0)
632 return Parent == null ? false : Parent.IsInUnsafeScope;
640 /// Base class for structs, classes, enumerations and interfaces.
643 /// They all create new declaration spaces. This
644 /// provides the common foundation for managing those name
647 public abstract class DeclSpace : MemberCore {
649 /// This points to the actual definition that is being
650 /// created with System.Reflection.Emit
652 public TypeBuilder TypeBuilder;
655 /// If we are a generic type, this is the type we are
656 /// currently defining. We need to lookup members on this
657 /// instead of the TypeBuilder.
659 public Type CurrentType;
662 // This is the namespace in which this typecontainer
663 // was declared. We use this to resolve names.
665 public NamespaceEntry NamespaceEntry;
667 private Hashtable Cache = new Hashtable ();
669 public readonly string Basename;
671 protected Hashtable defined_names;
673 readonly bool is_generic;
674 readonly int count_type_params;
675 readonly int count_current_type_params;
678 // Whether we are Generic
680 public bool IsGeneric {
684 else if (Parent != null)
685 return Parent.IsGeneric;
691 static string[] attribute_targets = new string [] { "type" };
693 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
695 : base (parent, name, attrs)
698 Basename = name.Basename;
699 defined_names = new Hashtable ();
700 if (name.TypeArguments != null) {
702 count_type_params = count_current_type_params = name.TypeArguments.Count;
705 count_type_params += parent.count_type_params;
708 public override DeclSpace DeclContainer {
715 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
717 protected bool AddToContainer (MemberCore symbol, string name)
719 if (name == MemberName.Name && !(this is Interface) && !(this is Enum)) {
720 if (symbol is TypeParameter)
721 Report.Error (694, symbol.Location,
722 "Type parameter `{0}' has same name as " +
723 "containing type, or method", name);
725 Report.SymbolRelatedToPreviousError (this);
726 Report.Error (542, symbol.Location,
727 "`{0}': member names cannot be the same " +
728 "as their enclosing type",
729 symbol.GetSignatureForError ());
734 MemberCore mc = (MemberCore) defined_names [name];
737 defined_names.Add (name, symbol);
741 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
744 Report.SymbolRelatedToPreviousError (mc);
745 if (symbol is PartialContainer || mc is PartialContainer) {
746 Report.Error (260, symbol.Location,
747 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
752 if (this is RootTypes) {
753 Report.Error (101, symbol.Location,
754 "The namespace `{0}' already contains a definition for `{1}'",
755 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
756 } else if (symbol is TypeParameter) {
757 Report.Error (692, symbol.Location,
758 "Duplicate type parameter `{0}'", name);
760 Report.Error (102, symbol.Location,
761 "The type `{0}' already contains a definition for `{1}'",
762 GetSignatureForError (), symbol.MemberName.Name);
769 /// Returns the MemberCore associated with a given name in the declaration
770 /// space. It doesn't return method based symbols !!
773 public MemberCore GetDefinition (string name)
775 return (MemberCore)defined_names [name];
779 // root_types contains all the types. All TopLevel types
780 // hence have a parent that points to `root_types', that is
781 // why there is a non-obvious test down here.
783 public bool IsTopLevel {
784 get { return (Parent != null && Parent.Parent == null); }
787 public virtual void CloseType ()
789 if ((caching_flags & Flags.CloseTypeCreated) == 0){
791 TypeBuilder.CreateType ();
794 // The try/catch is needed because
795 // nested enumerations fail to load when they
798 // Even if this is the right order (enumerations
799 // declared after types).
801 // Note that this still creates the type and
802 // it is possible to save it
804 caching_flags |= Flags.CloseTypeCreated;
808 protected virtual TypeAttributes TypeAttr {
809 get { return CodeGen.Module.DefaultCharSetType; }
813 /// Should be overriten by the appropriate declaration space
815 public abstract TypeBuilder DefineType ();
818 /// Define all members, but don't apply any attributes or do anything which may
819 /// access not-yet-defined classes. This method also creates the MemberCache.
821 public virtual bool DefineMembers ()
823 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
824 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
830 public override string GetSignatureForError ()
833 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
835 // Parent.GetSignatureForError
840 // Resolves the expression `e' for a type, and will recursively define
841 // types. This should only be used for resolving base types.
843 protected TypeExpr ResolveBaseTypeExpr (Expression e)
845 return e.ResolveAsTypeTerminal (this, false);
848 public bool CheckAccessLevel (Type check_type)
851 if ((this is GenericMethod) || (this is Iterator))
852 tb = Parent.TypeBuilder;
856 check_type = TypeManager.DropGenericTypeArguments (check_type);
857 if (check_type == tb)
860 if (TypeBuilder == null)
861 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
862 // However, this is invoked again later -- so safe to return true.
863 // May also be null when resolving top-level attributes.
866 if (check_type.IsGenericParameter)
867 return true; // FIXME
869 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
872 // Broken Microsoft runtime, return public for arrays, no matter what
873 // the accessibility is for their underlying class, and they return
874 // NonPublic visibility for pointers
876 if (check_type.IsArray || check_type.IsPointer)
877 return CheckAccessLevel (TypeManager.GetElementType (check_type));
880 case TypeAttributes.Public:
883 case TypeAttributes.NotPublic:
885 if (TypeBuilder == null)
886 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
887 // However, this is invoked again later -- so safe to return true.
888 // May also be null when resolving top-level attributes.
891 // This test should probably use the declaringtype.
893 return check_type.Assembly == TypeBuilder.Assembly ||
894 TypeManager.IsFriendAssembly (check_type.Assembly);
896 case TypeAttributes.NestedPublic:
899 case TypeAttributes.NestedPrivate:
900 return NestedAccessible (tb, check_type);
902 case TypeAttributes.NestedFamily:
904 // Only accessible to methods in current type or any subtypes
906 return FamilyAccessible (tb, check_type);
908 case TypeAttributes.NestedFamANDAssem:
909 return ((check_type.Assembly == tb.Assembly) ||
910 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
911 FamilyAccessible (tb, check_type);
913 case TypeAttributes.NestedFamORAssem:
914 return (check_type.Assembly == tb.Assembly) ||
915 FamilyAccessible (tb, check_type) ||
916 TypeManager.IsFriendAssembly (check_type.Assembly);
918 case TypeAttributes.NestedAssembly:
919 return check_type.Assembly == tb.Assembly ||
920 TypeManager.IsFriendAssembly (check_type.Assembly);
923 Console.WriteLine ("HERE: " + check_attr);
928 protected bool NestedAccessible (Type tb, Type check_type)
930 Type declaring = check_type.DeclaringType;
931 return TypeBuilder == declaring ||
932 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
935 protected bool FamilyAccessible (Type tb, Type check_type)
937 Type declaring = check_type.DeclaringType;
938 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
941 // Access level of a type.
943 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
944 // Public Assembly Protected
945 Protected = (0 << 0) | (0 << 1) | (X << 2),
946 Public = (X << 0) | (X << 1) | (X << 2),
947 Private = (0 << 0) | (0 << 1) | (0 << 2),
948 Internal = (0 << 0) | (X << 1) | (0 << 2),
949 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
952 static AccessLevel GetAccessLevelFromModifiers (int flags)
954 if ((flags & Modifiers.INTERNAL) != 0) {
956 if ((flags & Modifiers.PROTECTED) != 0)
957 return AccessLevel.ProtectedOrInternal;
959 return AccessLevel.Internal;
961 } else if ((flags & Modifiers.PROTECTED) != 0)
962 return AccessLevel.Protected;
963 else if ((flags & Modifiers.PRIVATE) != 0)
964 return AccessLevel.Private;
966 return AccessLevel.Public;
969 // What is the effective access level of this?
971 AccessLevel EffectiveAccessLevel {
973 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
974 if (!IsTopLevel && (Parent != null))
975 return myAccess & Parent.EffectiveAccessLevel;
980 // Return the access level for type `t'
981 static AccessLevel TypeEffectiveAccessLevel (Type t)
984 return AccessLevel.Public;
985 if (t.IsNestedPrivate)
986 return AccessLevel.Private;
988 return AccessLevel.Internal;
990 // By now, it must be nested
991 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
993 if (t.IsNestedPublic)
995 if (t.IsNestedAssembly)
996 return parentLevel & AccessLevel.Internal;
997 if (t.IsNestedFamily)
998 return parentLevel & AccessLevel.Protected;
999 if (t.IsNestedFamORAssem)
1000 return parentLevel & AccessLevel.ProtectedOrInternal;
1001 if (t.IsNestedFamANDAssem)
1002 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1004 // nested private is taken care of
1006 throw new Exception ("I give up, what are you?");
1010 // This answers `is the type P, as accessible as a member M which has the
1011 // accessability @flags which is declared as a nested member of the type T, this declspace'
1013 public bool AsAccessible (Type p, int flags)
1015 if (p.IsGenericParameter)
1016 return true; // FIXME
1019 // 1) if M is private, its accessability is the same as this declspace.
1020 // we already know that P is accessible to T before this method, so we
1024 if ((flags & Modifiers.PRIVATE) != 0)
1027 while (p.IsArray || p.IsPointer || p.IsByRef)
1028 p = TypeManager.GetElementType (p);
1030 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1031 AccessLevel mAccess = this.EffectiveAccessLevel &
1032 GetAccessLevelFromModifiers (flags);
1034 // for every place from which we can access M, we must
1035 // be able to access P as well. So, we want
1036 // For every bit in M and P, M_i -> P_1 == true
1037 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1039 return ~ (~ mAccess | pAccess) == 0;
1043 // Return the nested type with name @name. Ensures that the nested type
1044 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1046 public virtual Type FindNestedType (string name)
1051 private Type LookupNestedTypeInHierarchy (string name)
1053 // if the member cache has been created, lets use it.
1054 // the member cache is MUCH faster.
1055 if (MemberCache != null)
1056 return MemberCache.FindNestedType (name);
1058 // no member cache. Do it the hard way -- reflection
1060 for (Type current_type = TypeBuilder;
1061 current_type != null && current_type != TypeManager.object_type;
1062 current_type = current_type.BaseType) {
1063 current_type = TypeManager.DropGenericTypeArguments (current_type);
1064 if (current_type is TypeBuilder) {
1065 DeclSpace decl = this;
1066 if (current_type != TypeBuilder)
1067 decl = TypeManager.LookupDeclSpace (current_type);
1068 t = decl.FindNestedType (name);
1070 t = TypeManager.GetNestedType (current_type, name);
1073 if (t != null && CheckAccessLevel (t))
1081 // Public function used to locate types.
1083 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1085 // Returns: Type or null if they type can not be found.
1087 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1089 if (this is PartialContainer)
1090 throw new InternalErrorException ("Should not get here");
1092 if (Cache.Contains (name))
1093 return (FullNamedExpression) Cache [name];
1095 FullNamedExpression e;
1096 Type t = LookupNestedTypeInHierarchy (name);
1098 e = new TypeExpression (t, Location.Null);
1099 else if (Parent != null && Parent != RootContext.Tree.Types)
1100 e = Parent.LookupType (name, loc, ignore_cs0104);
1102 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1109 /// This function is broken and not what you're looking for. It should only
1110 /// be used while the type is still being created since it doesn't use the cache
1111 /// and relies on the filter doing the member name check.
1113 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1114 MemberFilter filter, object criteria);
1117 /// If we have a MemberCache, return it. This property may return null if the
1118 /// class doesn't have a member cache or while it's still being created.
1120 public abstract MemberCache MemberCache {
1124 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1126 if (a.Type == TypeManager.required_attr_type) {
1127 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1130 TypeBuilder.SetCustomAttribute (cb);
1134 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1135 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1137 public bool GetClsCompliantAttributeValue ()
1139 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1140 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1142 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1144 if (OptAttributes != null) {
1145 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type);
1146 if (cls_attribute != null) {
1147 caching_flags |= Flags.HasClsCompliantAttribute;
1148 if (cls_attribute.GetClsCompliantAttributeValue ()) {
1149 caching_flags |= Flags.ClsCompliantAttributeTrue;
1156 if (Parent == null) {
1157 if (CodeGen.Assembly.IsClsCompliant) {
1158 caching_flags |= Flags.ClsCompliantAttributeTrue;
1164 if (Parent.GetClsCompliantAttributeValue ()) {
1165 caching_flags |= Flags.ClsCompliantAttributeTrue;
1172 // Extensions for generics
1174 TypeParameter[] type_params;
1175 TypeParameter[] type_param_list;
1177 protected string GetInstantiationName ()
1179 StringBuilder sb = new StringBuilder (Name);
1181 for (int i = 0; i < type_param_list.Length; i++) {
1184 sb.Append (type_param_list [i].Name);
1187 return sb.ToString ();
1190 bool check_type_parameter (ArrayList list, int start, string name)
1192 for (int i = 0; i < start; i++) {
1193 TypeParameter param = (TypeParameter) list [i];
1195 if (param.Name != name)
1198 Report.Warning (693, 3, Location,
1199 "Type parameter `{0}' has same name as type parameter from outer type `{1}'",
1200 name, Parent.GetInstantiationName ());
1208 TypeParameter[] initialize_type_params ()
1210 if (type_param_list != null)
1211 return type_param_list;
1213 DeclSpace the_parent = Parent;
1214 if (this is GenericMethod)
1218 TypeParameter[] parent_params = null;
1219 if ((the_parent != null) && the_parent.IsGeneric) {
1220 parent_params = the_parent.initialize_type_params ();
1221 start = parent_params != null ? parent_params.Length : 0;
1224 ArrayList list = new ArrayList ();
1225 if (parent_params != null)
1226 list.AddRange (parent_params);
1228 int count = type_params != null ? type_params.Length : 0;
1229 for (int i = 0; i < count; i++) {
1230 TypeParameter param = type_params [i];
1231 check_type_parameter (list, start, param.Name);
1235 type_param_list = new TypeParameter [list.Count];
1236 list.CopyTo (type_param_list, 0);
1237 return type_param_list;
1240 public virtual void SetParameterInfo (ArrayList constraints_list)
1243 if (constraints_list != null) {
1245 80, Location, "Constraints are not allowed " +
1246 "on non-generic declarations");
1252 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1253 type_params = new TypeParameter [names.Length];
1256 // Register all the names
1258 for (int i = 0; i < type_params.Length; i++) {
1259 TypeParameterName name = names [i];
1261 Constraints constraints = null;
1262 if (constraints_list != null) {
1263 foreach (Constraints constraint in constraints_list) {
1264 if (constraint == null)
1266 if (constraint.TypeParameter == name.Name) {
1267 constraints = constraint;
1273 type_params [i] = new TypeParameter (
1274 Parent, this, name.Name, constraints, name.OptAttributes,
1277 AddToContainer (type_params [i], name.Name);
1281 public TypeParameter[] TypeParameters {
1284 throw new InvalidOperationException ();
1285 if (type_param_list == null)
1286 initialize_type_params ();
1288 return type_param_list;
1292 public TypeParameter[] CurrentTypeParameters {
1295 throw new InvalidOperationException ();
1296 if (type_params != null)
1299 return new TypeParameter [0];
1303 public int CountTypeParameters {
1305 return count_type_params;
1309 public int CountCurrentTypeParameters {
1311 return count_current_type_params;
1315 public TypeParameterExpr LookupGeneric (string name, Location loc)
1320 foreach (TypeParameter type_param in CurrentTypeParameters) {
1321 if (type_param.Name != name)
1324 return new TypeParameterExpr (type_param, loc);
1328 return Parent.LookupGeneric (name, loc);
1333 public override string[] ValidAttributeTargets {
1334 get { return attribute_targets; }
1337 protected override bool VerifyClsCompliance (DeclSpace ds)
1339 if (!base.VerifyClsCompliance (ds)) {
1343 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1344 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1345 if (!cache.Contains (lcase)) {
1346 cache.Add (lcase, this);
1350 object val = cache [lcase];
1352 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1355 Report.SymbolRelatedToPreviousError (t);
1358 if (val is PartialContainer)
1361 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1363 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1369 /// This is a readonly list of MemberInfo's.
1371 public class MemberList : IList {
1372 public readonly IList List;
1376 /// Create a new MemberList from the given IList.
1378 public MemberList (IList list)
1383 this.List = new ArrayList ();
1388 /// Concatenate the ILists `first' and `second' to a new MemberList.
1390 public MemberList (IList first, IList second)
1392 ArrayList list = new ArrayList ();
1393 list.AddRange (first);
1394 list.AddRange (second);
1399 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1402 /// Cast the MemberList into a MemberInfo[] array.
1405 /// This is an expensive operation, only use it if it's really necessary.
1407 public static explicit operator MemberInfo [] (MemberList list)
1409 Timer.StartTimer (TimerType.MiscTimer);
1410 MemberInfo [] result = new MemberInfo [list.Count];
1411 list.CopyTo (result, 0);
1412 Timer.StopTimer (TimerType.MiscTimer);
1424 public bool IsSynchronized {
1426 return List.IsSynchronized;
1430 public object SyncRoot {
1432 return List.SyncRoot;
1436 public void CopyTo (Array array, int index)
1438 List.CopyTo (array, index);
1443 public IEnumerator GetEnumerator ()
1445 return List.GetEnumerator ();
1450 public bool IsFixedSize {
1456 public bool IsReadOnly {
1462 object IList.this [int index] {
1464 return List [index];
1468 throw new NotSupportedException ();
1472 // FIXME: try to find out whether we can avoid the cast in this indexer.
1473 public MemberInfo this [int index] {
1475 return (MemberInfo) List [index];
1479 public int Add (object value)
1481 throw new NotSupportedException ();
1484 public void Clear ()
1486 throw new NotSupportedException ();
1489 public bool Contains (object value)
1491 return List.Contains (value);
1494 public int IndexOf (object value)
1496 return List.IndexOf (value);
1499 public void Insert (int index, object value)
1501 throw new NotSupportedException ();
1504 public void Remove (object value)
1506 throw new NotSupportedException ();
1509 public void RemoveAt (int index)
1511 throw new NotSupportedException ();
1516 /// This interface is used to get all members of a class when creating the
1517 /// member cache. It must be implemented by all DeclSpace derivatives which
1518 /// want to support the member cache and by TypeHandle to get caching of
1519 /// non-dynamic types.
1521 public interface IMemberContainer {
1523 /// The name of the IMemberContainer. This is only used for
1524 /// debugging purposes.
1531 /// The type of this IMemberContainer.
1538 /// Returns the IMemberContainer of the base class or null if this
1539 /// is an interface or TypeManger.object_type.
1540 /// This is used when creating the member cache for a class to get all
1541 /// members from the base class.
1543 MemberCache BaseCache {
1548 /// Whether this is an interface.
1555 /// Returns all members of this class with the corresponding MemberTypes
1556 /// and BindingFlags.
1559 /// When implementing this method, make sure not to return any inherited
1560 /// members and check the MemberTypes and BindingFlags properly.
1561 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1562 /// get the BindingFlags (static/non-static,public/non-public) in the
1563 /// MemberInfo class, but the cache needs this information. That's why
1564 /// this method is called multiple times with different BindingFlags.
1566 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1569 /// Return the container's member cache.
1571 MemberCache MemberCache {
1577 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1578 /// member lookups. It has a member name based hash table; it maps each member
1579 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1580 /// and the BindingFlags that were initially used to get it. The cache contains
1581 /// all members of the current class and all inherited members. If this cache is
1582 /// for an interface types, it also contains all inherited members.
1584 /// There are two ways to get a MemberCache:
1585 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1586 /// use the DeclSpace.MemberCache property.
1587 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1588 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1590 public class MemberCache {
1591 public readonly IMemberContainer Container;
1592 protected Hashtable member_hash;
1593 protected Hashtable method_hash;
1596 /// Create a new MemberCache for the given IMemberContainer `container'.
1598 public MemberCache (IMemberContainer container)
1600 this.Container = container;
1602 Timer.IncrementCounter (CounterType.MemberCache);
1603 Timer.StartTimer (TimerType.CacheInit);
1605 // If we have a base class (we have a base class unless we're
1606 // TypeManager.object_type), we deep-copy its MemberCache here.
1607 if (Container.BaseCache != null)
1608 member_hash = SetupCache (Container.BaseCache);
1610 member_hash = new Hashtable ();
1612 // If this is neither a dynamic type nor an interface, create a special
1613 // method cache with all declared and inherited methods.
1614 Type type = container.Type;
1615 if (!(type is TypeBuilder) && !type.IsInterface &&
1616 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1617 !type.IsGenericType &&
1618 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1619 method_hash = new Hashtable ();
1623 // Add all members from the current class.
1624 AddMembers (Container);
1626 Timer.StopTimer (TimerType.CacheInit);
1629 public MemberCache (Type[] ifaces)
1632 // The members of this cache all belong to other caches.
1633 // So, 'Container' will not be used.
1635 this.Container = null;
1637 member_hash = new Hashtable ();
1641 foreach (Type itype in ifaces)
1642 AddCacheContents (TypeManager.LookupMemberCache (itype));
1646 /// Bootstrap this member cache by doing a deep-copy of our base.
1648 Hashtable SetupCache (MemberCache base_class)
1650 Hashtable hash = new Hashtable ();
1652 if (base_class == null)
1655 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1656 while (it.MoveNext ()) {
1657 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1664 /// Add the contents of `cache' to the member_hash.
1666 void AddCacheContents (MemberCache cache)
1668 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1669 while (it.MoveNext ()) {
1670 ArrayList list = (ArrayList) member_hash [it.Key];
1672 member_hash [it.Key] = list = new ArrayList ();
1674 ArrayList entries = (ArrayList) it.Value;
1675 for (int i = entries.Count-1; i >= 0; i--) {
1676 CacheEntry entry = (CacheEntry) entries [i];
1678 if (entry.Container != cache.Container)
1686 /// Add all members from class `container' to the cache.
1688 void AddMembers (IMemberContainer container)
1690 // We need to call AddMembers() with a single member type at a time
1691 // to get the member type part of CacheEntry.EntryType right.
1692 if (!container.IsInterface) {
1693 AddMembers (MemberTypes.Constructor, container);
1694 AddMembers (MemberTypes.Field, container);
1696 AddMembers (MemberTypes.Method, container);
1697 AddMembers (MemberTypes.Property, container);
1698 AddMembers (MemberTypes.Event, container);
1699 // Nested types are returned by both Static and Instance searches.
1700 AddMembers (MemberTypes.NestedType,
1701 BindingFlags.Static | BindingFlags.Public, container);
1702 AddMembers (MemberTypes.NestedType,
1703 BindingFlags.Static | BindingFlags.NonPublic, container);
1706 void AddMembers (MemberTypes mt, IMemberContainer container)
1708 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1709 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1710 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1711 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1715 /// Add all members from class `container' with the requested MemberTypes and
1716 /// BindingFlags to the cache. This method is called multiple times with different
1717 /// MemberTypes and BindingFlags.
1719 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1721 MemberList members = container.GetMembers (mt, bf);
1723 foreach (MemberInfo member in members) {
1724 string name = member.Name;
1726 int pos = name.IndexOf ('<');
1728 name = name.Substring (0, pos);
1730 // We use a name-based hash table of ArrayList's.
1731 ArrayList list = (ArrayList) member_hash [name];
1733 list = new ArrayList ();
1734 member_hash.Add (name, list);
1737 // When this method is called for the current class, the list will
1738 // already contain all inherited members from our base classes.
1739 // We cannot add new members in front of the list since this'd be an
1740 // expensive operation, that's why the list is sorted in reverse order
1741 // (ie. members from the current class are coming last).
1742 list.Add (new CacheEntry (container, member, mt, bf));
1747 /// Add all declared and inherited methods from class `type' to the method cache.
1749 void AddMethods (Type type)
1751 AddMethods (BindingFlags.Static | BindingFlags.Public |
1752 BindingFlags.FlattenHierarchy, type);
1753 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1754 BindingFlags.FlattenHierarchy, type);
1755 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1756 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1759 static ArrayList overrides = new ArrayList ();
1761 void AddMethods (BindingFlags bf, Type type)
1763 MethodBase [] members = type.GetMethods (bf);
1765 Array.Reverse (members);
1767 foreach (MethodBase member in members) {
1768 string name = member.Name;
1770 // We use a name-based hash table of ArrayList's.
1771 ArrayList list = (ArrayList) method_hash [name];
1773 list = new ArrayList ();
1774 method_hash.Add (name, list);
1777 MethodInfo curr = (MethodInfo) member;
1778 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1779 MethodInfo base_method = curr.GetBaseDefinition ();
1781 if (base_method == curr)
1782 // Not every virtual function needs to have a NewSlot flag.
1785 overrides.Add (curr);
1786 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1790 if (overrides.Count > 0) {
1791 for (int i = 0; i < overrides.Count; ++i)
1792 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1796 // Unfortunately, the elements returned by Type.GetMethods() aren't
1797 // sorted so we need to do this check for every member.
1798 BindingFlags new_bf = bf;
1799 if (member.DeclaringType == type)
1800 new_bf |= BindingFlags.DeclaredOnly;
1802 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1807 /// Compute and return a appropriate `EntryType' magic number for the given
1808 /// MemberTypes and BindingFlags.
1810 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1812 EntryType type = EntryType.None;
1814 if ((mt & MemberTypes.Constructor) != 0)
1815 type |= EntryType.Constructor;
1816 if ((mt & MemberTypes.Event) != 0)
1817 type |= EntryType.Event;
1818 if ((mt & MemberTypes.Field) != 0)
1819 type |= EntryType.Field;
1820 if ((mt & MemberTypes.Method) != 0)
1821 type |= EntryType.Method;
1822 if ((mt & MemberTypes.Property) != 0)
1823 type |= EntryType.Property;
1824 // Nested types are returned by static and instance searches.
1825 if ((mt & MemberTypes.NestedType) != 0)
1826 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1828 if ((bf & BindingFlags.Instance) != 0)
1829 type |= EntryType.Instance;
1830 if ((bf & BindingFlags.Static) != 0)
1831 type |= EntryType.Static;
1832 if ((bf & BindingFlags.Public) != 0)
1833 type |= EntryType.Public;
1834 if ((bf & BindingFlags.NonPublic) != 0)
1835 type |= EntryType.NonPublic;
1836 if ((bf & BindingFlags.DeclaredOnly) != 0)
1837 type |= EntryType.Declared;
1843 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1844 /// denote multiple member types. Returns true if the given flags value denotes a
1845 /// single member types.
1847 public static bool IsSingleMemberType (MemberTypes mt)
1850 case MemberTypes.Constructor:
1851 case MemberTypes.Event:
1852 case MemberTypes.Field:
1853 case MemberTypes.Method:
1854 case MemberTypes.Property:
1855 case MemberTypes.NestedType:
1864 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1865 /// number to speed up the searching process.
1868 protected enum EntryType {
1873 MaskStatic = Instance|Static,
1877 MaskProtection = Public|NonPublic,
1881 Constructor = 0x020,
1888 MaskType = Constructor|Event|Field|Method|Property|NestedType
1891 protected class CacheEntry {
1892 public readonly IMemberContainer Container;
1893 public readonly EntryType EntryType;
1894 public readonly MemberInfo Member;
1896 public CacheEntry (IMemberContainer container, MemberInfo member,
1897 MemberTypes mt, BindingFlags bf)
1899 this.Container = container;
1900 this.Member = member;
1901 this.EntryType = GetEntryType (mt, bf);
1904 public override string ToString ()
1906 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1912 /// This is called each time we're walking up one level in the class hierarchy
1913 /// and checks whether we can abort the search since we've already found what
1914 /// we were looking for.
1916 protected bool DoneSearching (ArrayList list)
1919 // We've found exactly one member in the current class and it's not
1920 // a method or constructor.
1922 if (list.Count == 1 && !(list [0] is MethodBase))
1926 // Multiple properties: we query those just to find out the indexer
1929 if ((list.Count > 0) && (list [0] is PropertyInfo))
1936 /// Looks up members with name `name'. If you provide an optional
1937 /// filter function, it'll only be called with members matching the
1938 /// requested member name.
1940 /// This method will try to use the cache to do the lookup if possible.
1942 /// Unlike other FindMembers implementations, this method will always
1943 /// check all inherited members - even when called on an interface type.
1945 /// If you know that you're only looking for methods, you should use
1946 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1947 /// When doing a method-only search, it'll try to use a special method
1948 /// cache (unless it's a dynamic type or an interface) and the returned
1949 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1950 /// The lookup process will automatically restart itself in method-only
1951 /// search mode if it discovers that it's about to return methods.
1953 ArrayList global = new ArrayList ();
1954 bool using_global = false;
1956 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1958 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1959 MemberFilter filter, object criteria)
1962 throw new Exception ();
1964 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1965 bool method_search = mt == MemberTypes.Method;
1966 // If we have a method cache and we aren't already doing a method-only search,
1967 // then we restart a method search if the first match is a method.
1968 bool do_method_search = !method_search && (method_hash != null);
1970 ArrayList applicable;
1972 // If this is a method-only search, we try to use the method cache if
1973 // possible; a lookup in the method cache will return a MemberInfo with
1974 // the correct ReflectedType for inherited methods.
1976 if (method_search && (method_hash != null))
1977 applicable = (ArrayList) method_hash [name];
1979 applicable = (ArrayList) member_hash [name];
1981 if (applicable == null)
1982 return emptyMemberInfo;
1985 // 32 slots gives 53 rss/54 size
1986 // 2/4 slots gives 55 rss
1988 // Strange: from 25,000 calls, only 1,800
1989 // are above 2. Why does this impact it?
1992 using_global = true;
1994 Timer.StartTimer (TimerType.CachedLookup);
1996 EntryType type = GetEntryType (mt, bf);
1998 IMemberContainer current = Container;
2001 // `applicable' is a list of all members with the given member name `name'
2002 // in the current class and all its base classes. The list is sorted in
2003 // reverse order due to the way how the cache is initialy created (to speed
2004 // things up, we're doing a deep-copy of our base).
2006 for (int i = applicable.Count-1; i >= 0; i--) {
2007 CacheEntry entry = (CacheEntry) applicable [i];
2009 // This happens each time we're walking one level up in the class
2010 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2011 // the first time this happens (this may already happen in the first
2012 // iteration of this loop if there are no members with the name we're
2013 // looking for in the current class).
2014 if (entry.Container != current) {
2015 if (declared_only || DoneSearching (global))
2018 current = entry.Container;
2021 // Is the member of the correct type ?
2022 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2025 // Is the member static/non-static ?
2026 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2029 // Apply the filter to it.
2030 if (filter (entry.Member, criteria)) {
2031 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2032 do_method_search = false;
2033 global.Add (entry.Member);
2037 Timer.StopTimer (TimerType.CachedLookup);
2039 // If we have a method cache and we aren't already doing a method-only
2040 // search, we restart in method-only search mode if the first match is
2041 // a method. This ensures that we return a MemberInfo with the correct
2042 // ReflectedType for inherited methods.
2043 if (do_method_search && (global.Count > 0)){
2044 using_global = false;
2046 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2049 using_global = false;
2050 MemberInfo [] copy = new MemberInfo [global.Count];
2051 global.CopyTo (copy);
2055 // find the nested type @name in @this.
2056 public Type FindNestedType (string name)
2058 ArrayList applicable = (ArrayList) member_hash [name];
2059 if (applicable == null)
2062 for (int i = applicable.Count-1; i >= 0; i--) {
2063 CacheEntry entry = (CacheEntry) applicable [i];
2064 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2065 return (Type) entry.Member;
2072 // This finds the method or property for us to override. invocationType is the type where
2073 // the override is going to be declared, name is the name of the method/property, and
2074 // paramTypes is the parameters, if any to the method or property
2076 // Because the MemberCache holds members from this class and all the base classes,
2077 // we can avoid tons of reflection stuff.
2079 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, GenericMethod genericMethod, bool is_property)
2081 ArrayList applicable;
2082 if (method_hash != null && !is_property)
2083 applicable = (ArrayList) method_hash [name];
2085 applicable = (ArrayList) member_hash [name];
2087 if (applicable == null)
2090 // Walk the chain of methods, starting from the top.
2092 for (int i = applicable.Count - 1; i >= 0; i--) {
2093 CacheEntry entry = (CacheEntry) applicable [i];
2095 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2098 PropertyInfo pi = null;
2099 MethodInfo mi = null;
2100 FieldInfo fi = null;
2101 Type [] cmpAttrs = null;
2104 if ((entry.EntryType & EntryType.Field) != 0) {
2105 fi = (FieldInfo)entry.Member;
2107 // TODO: For this case we ignore member type
2108 //fb = TypeManager.GetField (fi);
2109 //cmpAttrs = new Type[] { fb.MemberType };
2111 pi = (PropertyInfo) entry.Member;
2112 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2115 mi = (MethodInfo) entry.Member;
2116 cmpAttrs = TypeManager.GetParameterData (mi).Types;
2120 // TODO: Almost duplicate !
2122 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2123 case FieldAttributes.Private:
2125 // A private method is Ok if we are a nested subtype.
2126 // The spec actually is not very clear about this, see bug 52458.
2128 if (invocationType != entry.Container.Type &
2129 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2133 case FieldAttributes.FamANDAssem:
2134 case FieldAttributes.Assembly:
2136 // Check for assembly methods
2138 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2142 return entry.Member;
2146 // Check the arguments
2148 if (cmpAttrs.Length != paramTypes.Length)
2151 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2152 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2157 // check generic arguments for methods
2160 Type [] cmpGenArgs = mi.GetGenericArguments ();
2161 if (genericMethod != null && cmpGenArgs.Length > 0) {
2162 if (genericMethod.TypeParameters.Length != cmpGenArgs.Length)
2165 else if (! (genericMethod == null && cmpGenArgs.Length == 0))
2170 // get one of the methods because this has the visibility info.
2173 mi = pi.GetGetMethod (true);
2175 mi = pi.GetSetMethod (true);
2181 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2182 case MethodAttributes.Private:
2184 // A private method is Ok if we are a nested subtype.
2185 // The spec actually is not very clear about this, see bug 52458.
2187 if (invocationType.Equals (entry.Container.Type) ||
2188 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2189 return entry.Member;
2192 case MethodAttributes.FamANDAssem:
2193 case MethodAttributes.Assembly:
2195 // Check for assembly methods
2197 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2198 return entry.Member;
2203 // A protected method is ok, because we are overriding.
2204 // public is always ok.
2206 return entry.Member;
2216 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2217 /// We handle two cases. The first is for types without parameters (events, field, properties).
2218 /// The second are methods, indexers and this is why ignore_complex_types is here.
2219 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2221 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2223 ArrayList applicable = null;
2225 if (method_hash != null)
2226 applicable = (ArrayList) method_hash [name];
2228 if (applicable != null) {
2229 for (int i = applicable.Count - 1; i >= 0; i--) {
2230 CacheEntry entry = (CacheEntry) applicable [i];
2231 if ((entry.EntryType & EntryType.Public) != 0)
2232 return entry.Member;
2236 if (member_hash == null)
2238 applicable = (ArrayList) member_hash [name];
2240 if (applicable != null) {
2241 for (int i = applicable.Count - 1; i >= 0; i--) {
2242 CacheEntry entry = (CacheEntry) applicable [i];
2243 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2244 if (ignore_complex_types) {
2245 if ((entry.EntryType & EntryType.Method) != 0)
2248 // Does exist easier way how to detect indexer ?
2249 if ((entry.EntryType & EntryType.Property) != 0) {
2250 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2251 if (arg_types.Length > 0)
2255 return entry.Member;
2262 Hashtable locase_table;
2265 /// Builds low-case table for CLS Compliance test
2267 public Hashtable GetPublicMembers ()
2269 if (locase_table != null)
2270 return locase_table;
2272 locase_table = new Hashtable ();
2273 foreach (DictionaryEntry entry in member_hash) {
2274 ArrayList members = (ArrayList)entry.Value;
2275 for (int ii = 0; ii < members.Count; ++ii) {
2276 CacheEntry member_entry = (CacheEntry) members [ii];
2278 if ((member_entry.EntryType & EntryType.Public) == 0)
2281 // TODO: Does anyone know easier way how to detect that member is internal ?
2282 switch (member_entry.EntryType & EntryType.MaskType) {
2283 case EntryType.Constructor:
2286 case EntryType.Field:
2287 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2291 case EntryType.Method:
2292 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2296 case EntryType.Property:
2297 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2298 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2302 case EntryType.Event:
2303 EventInfo ei = (EventInfo)member_entry.Member;
2304 MethodInfo mi = ei.GetAddMethod ();
2305 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2309 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2310 locase_table [lcase] = member_entry.Member;
2314 return locase_table;
2317 public Hashtable Members {
2324 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2326 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2328 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2330 for (int i = 0; i < al.Count; ++i) {
2331 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2334 if (entry.Member == this_builder)
2337 if ((entry.EntryType & tested_type) != tested_type)
2340 MethodBase method_to_compare = (MethodBase)entry.Member;
2341 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2342 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2344 if (result == AttributeTester.Result.Ok)
2347 IMethodData md = TypeManager.GetMethod (method_to_compare);
2349 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2350 // However it is exactly what csc does.
2351 if (md != null && !md.IsClsComplianceRequired ())
2354 Report.SymbolRelatedToPreviousError (entry.Member);
2356 case AttributeTester.Result.RefOutArrayError:
2357 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2359 case AttributeTester.Result.ArrayArrayError:
2360 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2364 throw new NotImplementedException (result.ToString ());