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;
22 #if BOOTSTRAP_WITH_OLDLIB
23 using XmlElement = System.Object;
28 namespace Mono.CSharp {
30 public class MemberName {
31 public readonly string Name;
32 public readonly TypeArguments TypeArguments;
34 public readonly MemberName Left;
35 public readonly Location Location;
37 public static readonly MemberName Null = new MemberName ("");
41 private MemberName (MemberName left, string name, bool is_double_colon,
46 this.is_double_colon = is_double_colon;
50 private MemberName (MemberName left, string name, bool is_double_colon,
51 TypeArguments args, Location loc)
52 : this (left, name, is_double_colon, loc)
54 this.TypeArguments = args;
57 public MemberName (string name)
58 : this (name, Location.Null)
61 public MemberName (string name, Location loc)
62 : this (null, name, false, loc)
65 public MemberName (string name, TypeArguments args, Location loc)
66 : this (null, name, false, args, loc)
69 public MemberName (MemberName left, string name)
70 : this (left, name, left != null ? left.Location : Location.Null)
73 public MemberName (MemberName left, string name, Location loc)
74 : this (left, name, false, loc)
77 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
78 : this (left, name, false, args, loc)
81 public MemberName (string alias, string name, Location loc)
82 : this (new MemberName (alias, loc), name, true, loc)
85 public MemberName (MemberName left, MemberName right)
86 : this (left, right, right.Location)
89 public MemberName (MemberName left, MemberName right, Location loc)
90 : this (null, right.Name, false, right.TypeArguments, loc)
92 if (right.is_double_colon)
93 throw new InternalErrorException ("Cannot append double_colon member name");
94 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
97 public string GetName ()
99 return GetName (false);
102 public bool IsGeneric {
104 if (TypeArguments != null)
106 else if (Left != null)
107 return Left.IsGeneric;
113 public string GetName (bool is_generic)
115 string name = is_generic ? Basename : Name;
116 string connect = is_double_colon ? "::" : ".";
118 return Left.GetName (is_generic) + connect + name;
123 public string GetTypeName ()
125 string connect = is_double_colon ? "::" : ".";
127 return Left.GetTypeName () + connect + MakeName (Name, TypeArguments);
129 return MakeName (Name, TypeArguments);
132 public Expression GetTypeExpression ()
136 if (!CheckUnbound (Location))
139 return new UnboundTypeExpression (this, Location);
144 if (TypeArguments != null)
145 return new SimpleName (Basename, TypeArguments, Location);
147 return new SimpleName (Name, Location);
150 if (is_double_colon) {
151 if (Left.Left != null)
152 throw new InternalErrorException ("The left side of a :: should be an identifier");
153 return new QualifiedAliasMember (Left.Name, Name, Location);
156 Expression lexpr = Left.GetTypeExpression ();
157 return new MemberAccess (lexpr, Name, TypeArguments, Location);
160 public MemberName Clone ()
162 MemberName left_clone = Left == null ? null : Left.Clone ();
163 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
166 public string Basename {
168 if (TypeArguments != null)
169 return MakeName (Name, TypeArguments);
175 public string FullName {
177 if (TypeArguments != null)
178 return Name + "<" + TypeArguments + ">";
184 public string MethodName {
186 string connect = is_double_colon ? "::" : ".";
188 return Left.FullName + connect + Name;
194 public override string ToString ()
196 string connect = is_double_colon ? "::" : ".";
198 return Left.FullName + connect + FullName;
203 public override bool Equals (object other)
205 return Equals (other as MemberName);
208 public bool Equals (MemberName other)
212 if (other == null || Name != other.Name)
214 if (is_double_colon != other.is_double_colon)
217 if ((TypeArguments != null) &&
218 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
221 if ((TypeArguments == null) && (other.TypeArguments != null))
225 return other.Left == null;
227 return Left.Equals (other.Left);
230 public override int GetHashCode ()
232 int hash = Name.GetHashCode ();
233 for (MemberName n = Left; n != null; n = n.Left)
234 hash ^= n.Name.GetHashCode ();
238 if (TypeArguments != null)
239 hash ^= TypeArguments.Count << 5;
241 return hash & 0x7FFFFFFF;
244 public int CountTypeArguments {
246 if (TypeArguments == null)
249 return TypeArguments.Count;
253 public static string MakeName (string name, TypeArguments args)
258 return name + "`" + args.Count;
261 public static string MakeName (string name, int count)
263 return name + "`" + count;
266 protected bool IsUnbound {
268 if ((Left != null) && Left.IsUnbound)
270 else if (TypeArguments == null)
273 return TypeArguments.IsUnbound;
277 protected bool CheckUnbound (Location loc)
279 if ((Left != null) && !Left.CheckUnbound (loc))
281 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
282 Report.Error (1031, loc, "Type expected");
291 /// Base representation for members. This is used to keep track
292 /// of Name, Location and Modifier flags, and handling Attributes.
294 public abstract class MemberCore : Attributable, IResolveContext {
299 protected string cached_name;
302 if (cached_name == null)
303 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
308 // Is not readonly because of IndexerName attribute
309 private MemberName member_name;
310 public MemberName MemberName {
311 get { return member_name; }
315 /// Modifier flags that the user specified in the source code
319 public readonly DeclSpace Parent;
322 /// Location where this declaration happens
324 public Location Location {
325 get { return member_name.Location; }
329 /// XML documentation comment
331 protected string comment;
334 /// Represents header string for documentation comment
335 /// for each member types.
337 public abstract string DocCommentHeader { get; }
341 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
342 Obsolete = 1 << 1, // Type has obsolete attribute
343 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
344 ClsCompliant = 1 << 3, // Type is CLS Compliant
345 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
346 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
347 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
348 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
349 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
350 Excluded = 1 << 9, // Method is conditional
351 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
353 IsAssigned = 1 << 12, // Field is assigned
354 HasExplicitLayout = 1 << 13
358 /// MemberCore flags at first detected then cached
360 internal Flags caching_flags;
362 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
365 this.Parent = parent;
367 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
370 protected virtual void SetMemberName (MemberName new_name)
372 member_name = new_name;
376 public abstract bool Define ();
378 public virtual string DocComment {
388 // Returns full member name for error message
390 public virtual string GetSignatureForError ()
392 if (Parent == null || Parent.Parent == null)
393 return member_name.ToString ();
395 return String.Concat (Parent.GetSignatureForError (), '.', member_name.ToString ());
399 /// Base Emit method. This is also entry point for CLS-Compliant verification.
401 public virtual void Emit ()
403 if (!RootContext.VerifyClsCompliance)
406 VerifyClsCompliance ();
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);
463 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
465 public override bool IsClsComplianceRequired ()
467 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
468 return (caching_flags & Flags.ClsCompliant) != 0;
470 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
471 caching_flags &= ~Flags.ClsCompliance_Undetected;
472 caching_flags |= Flags.ClsCompliant;
476 caching_flags &= ~Flags.ClsCompliance_Undetected;
481 /// Returns true when MemberCore is exposed from assembly.
483 public bool IsExposedFromAssembly ()
485 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
488 DeclSpace parentContainer = Parent;
489 while (parentContainer != null && parentContainer.ModFlags != 0) {
490 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
492 parentContainer = parentContainer.Parent;
498 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
499 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
501 public virtual bool GetClsCompliantAttributeValue ()
503 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
504 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
506 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
508 if (OptAttributes != null) {
509 Attribute cls_attribute = OptAttributes.Search (
510 TypeManager.cls_compliant_attribute_type);
511 if (cls_attribute != null) {
512 caching_flags |= Flags.HasClsCompliantAttribute;
513 bool value = cls_attribute.GetClsCompliantAttributeValue ();
515 caching_flags |= Flags.ClsCompliantAttributeTrue;
520 if (Parent.GetClsCompliantAttributeValue ()) {
521 caching_flags |= Flags.ClsCompliantAttributeTrue;
528 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
530 protected bool HasClsCompliantAttribute {
532 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
537 /// It helps to handle error 102 & 111 detection
539 public virtual bool MarkForDuplicationCheck ()
545 /// The main virtual method for CLS-Compliant verifications.
546 /// The method returns true if member is CLS-Compliant and false if member is not
547 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
548 /// and add their extra verifications.
550 protected virtual bool VerifyClsCompliance ()
552 if (!IsClsComplianceRequired ()) {
553 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
554 if (!IsExposedFromAssembly ())
555 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
556 if (!CodeGen.Assembly.IsClsCompliant)
557 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
562 if (HasClsCompliantAttribute) {
563 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
564 Report.Error (3014, Location,
565 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
566 GetSignatureForError ());
570 if (!Parent.IsClsComplianceRequired ()) {
571 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
572 GetSignatureForError (), Parent.GetSignatureForError ());
577 if (member_name.Name [0] == '_') {
578 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
584 // Raised (and passed an XmlElement that contains the comment)
585 // when GenerateDocComment is writing documentation expectedly.
587 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
592 // Returns a string that represents the signature for this
593 // member which should be used in XML documentation.
595 public virtual string GetDocCommentName (DeclSpace ds)
597 if (ds == null || this is DeclSpace)
598 return DocCommentHeader + Name;
600 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
604 // Generates xml doc comments (if any), and if required,
605 // handle warning report.
607 internal virtual void GenerateDocComment (DeclSpace ds)
609 DocUtil.GenerateDocComment (this, ds);
612 public override IResolveContext ResolveContext {
616 #region IResolveContext Members
618 public DeclSpace DeclContainer {
619 get { return Parent; }
622 public virtual DeclSpace GenericDeclContainer {
623 get { return DeclContainer; }
626 public bool IsInObsoleteScope {
628 if (GetObsoleteAttribute () != null)
631 return Parent == null ? false : Parent.IsInObsoleteScope;
635 public bool IsInUnsafeScope {
637 if ((ModFlags & Modifiers.UNSAFE) != 0)
640 return Parent == null ? false : Parent.IsInUnsafeScope;
648 /// Base class for structs, classes, enumerations and interfaces.
651 /// They all create new declaration spaces. This
652 /// provides the common foundation for managing those name
655 public abstract class DeclSpace : MemberCore {
657 /// This points to the actual definition that is being
658 /// created with System.Reflection.Emit
660 public TypeBuilder TypeBuilder;
663 /// If we are a generic type, this is the type we are
664 /// currently defining. We need to lookup members on this
665 /// instead of the TypeBuilder.
667 public Type CurrentType;
670 // This is the namespace in which this typecontainer
671 // was declared. We use this to resolve names.
673 public NamespaceEntry NamespaceEntry;
675 private Hashtable Cache = new Hashtable ();
677 public readonly string Basename;
679 protected Hashtable defined_names;
681 public TypeContainer PartialContainer;
683 readonly bool is_generic;
684 readonly int count_type_params;
685 readonly int count_current_type_params;
688 // Whether we are Generic
690 public bool IsGeneric {
694 else if (Parent != null)
695 return Parent.IsGeneric;
701 static string[] attribute_targets = new string [] { "type" };
703 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
705 : base (parent, name, attrs)
708 Basename = name.Basename;
709 defined_names = new Hashtable ();
710 PartialContainer = null;
711 if (name.TypeArguments != null) {
713 count_type_params = count_current_type_params = name.TypeArguments.Count;
716 count_type_params += parent.count_type_params;
719 public override DeclSpace GenericDeclContainer {
724 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
726 protected virtual bool AddToContainer (MemberCore symbol, string name)
728 MemberCore mc = (MemberCore) defined_names [name];
731 defined_names.Add (name, symbol);
735 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
738 Report.SymbolRelatedToPreviousError (mc);
739 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
740 Error_MissingPartialModifier (symbol);
744 if (this is RootTypes) {
745 Report.Error (101, symbol.Location,
746 "The namespace `{0}' already contains a definition for `{1}'",
747 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
748 } else if (symbol is TypeParameter) {
749 Report.Error (692, symbol.Location,
750 "Duplicate type parameter `{0}'", name);
752 Report.Error (102, symbol.Location,
753 "The type `{0}' already contains a definition for `{1}'",
754 GetSignatureForError (), symbol.MemberName.Name);
761 /// Returns the MemberCore associated with a given name in the declaration
762 /// space. It doesn't return method based symbols !!
765 public MemberCore GetDefinition (string name)
767 return (MemberCore)defined_names [name];
770 public bool IsStaticClass {
771 get { return (ModFlags & Modifiers.STATIC) != 0; }
775 // root_types contains all the types. All TopLevel types
776 // hence have a parent that points to `root_types', that is
777 // why there is a non-obvious test down here.
779 public bool IsTopLevel {
780 get { return (Parent != null && Parent.Parent == null); }
783 public virtual void CloseType ()
785 if ((caching_flags & Flags.CloseTypeCreated) == 0){
787 TypeBuilder.CreateType ();
790 // The try/catch is needed because
791 // nested enumerations fail to load when they
794 // Even if this is the right order (enumerations
795 // declared after types).
797 // Note that this still creates the type and
798 // it is possible to save it
800 caching_flags |= Flags.CloseTypeCreated;
804 protected virtual TypeAttributes TypeAttr {
805 get { return CodeGen.Module.DefaultCharSetType; }
809 /// Should be overriten by the appropriate declaration space
811 public abstract TypeBuilder DefineType ();
814 /// Define all members, but don't apply any attributes or do anything which may
815 /// access not-yet-defined classes. This method also creates the MemberCache.
817 public virtual bool DefineMembers ()
819 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
820 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
826 protected void Error_MissingPartialModifier (MemberCore type)
828 Report.Error (260, type.Location,
829 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
830 type.GetSignatureForError ());
833 public override string GetSignatureForError ()
836 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
838 // Parent.GetSignatureForError
842 public bool CheckAccessLevel (Type check_type)
845 if (this is GenericMethod)
846 tb = Parent.TypeBuilder;
850 check_type = TypeManager.DropGenericTypeArguments (check_type);
851 if (check_type == tb)
854 if (TypeBuilder == null)
855 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
856 // However, this is invoked again later -- so safe to return true.
857 // May also be null when resolving top-level attributes.
861 // Broken Microsoft runtime, return public for arrays, no matter what
862 // the accessibility is for their underlying class, and they return
863 // NonPublic visibility for pointers
865 if (check_type.IsArray || check_type.IsPointer)
866 return CheckAccessLevel (TypeManager.GetElementType (check_type));
868 if (TypeManager.IsGenericParameter(check_type))
869 return true; // FIXME
871 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
874 case TypeAttributes.Public:
877 case TypeAttributes.NotPublic:
879 if (TypeBuilder == null)
880 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
881 // However, this is invoked again later -- so safe to return true.
882 // May also be null when resolving top-level attributes.
885 // This test should probably use the declaringtype.
887 return check_type.Assembly == TypeBuilder.Assembly ||
888 TypeManager.IsFriendAssembly (check_type.Assembly);
890 case TypeAttributes.NestedPublic:
893 case TypeAttributes.NestedPrivate:
894 return NestedAccessible (tb, check_type);
896 case TypeAttributes.NestedFamily:
898 // Only accessible to methods in current type or any subtypes
900 return FamilyAccessible (tb, check_type);
902 case TypeAttributes.NestedFamANDAssem:
903 return ((check_type.Assembly == tb.Assembly) ||
904 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
905 FamilyAccessible (tb, check_type);
907 case TypeAttributes.NestedFamORAssem:
908 return (check_type.Assembly == tb.Assembly) ||
909 FamilyAccessible (tb, check_type) ||
910 TypeManager.IsFriendAssembly (check_type.Assembly);
912 case TypeAttributes.NestedAssembly:
913 return check_type.Assembly == tb.Assembly ||
914 TypeManager.IsFriendAssembly (check_type.Assembly);
917 Console.WriteLine ("HERE: " + check_attr);
922 protected bool NestedAccessible (Type tb, Type check_type)
924 Type declaring = check_type.DeclaringType;
925 return TypeBuilder == declaring ||
926 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
929 protected bool FamilyAccessible (Type tb, Type check_type)
931 Type declaring = check_type.DeclaringType;
932 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
935 // Access level of a type.
937 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
938 // Public Assembly Protected
939 Protected = (0 << 0) | (0 << 1) | (X << 2),
940 Public = (X << 0) | (X << 1) | (X << 2),
941 Private = (0 << 0) | (0 << 1) | (0 << 2),
942 Internal = (0 << 0) | (X << 1) | (0 << 2),
943 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
946 static AccessLevel GetAccessLevelFromModifiers (int flags)
948 if ((flags & Modifiers.INTERNAL) != 0) {
950 if ((flags & Modifiers.PROTECTED) != 0)
951 return AccessLevel.ProtectedOrInternal;
953 return AccessLevel.Internal;
955 } else if ((flags & Modifiers.PROTECTED) != 0)
956 return AccessLevel.Protected;
957 else if ((flags & Modifiers.PRIVATE) != 0)
958 return AccessLevel.Private;
960 return AccessLevel.Public;
963 // What is the effective access level of this?
965 AccessLevel EffectiveAccessLevel {
967 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
968 if (!IsTopLevel && (Parent != null))
969 return myAccess & Parent.EffectiveAccessLevel;
974 // Return the access level for type `t'
975 static AccessLevel TypeEffectiveAccessLevel (Type t)
978 return AccessLevel.Public;
979 if (t.IsNestedPrivate)
980 return AccessLevel.Private;
982 return AccessLevel.Internal;
984 // By now, it must be nested
985 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
987 if (t.IsNestedPublic)
989 if (t.IsNestedAssembly)
990 return parentLevel & AccessLevel.Internal;
991 if (t.IsNestedFamily)
992 return parentLevel & AccessLevel.Protected;
993 if (t.IsNestedFamORAssem)
994 return parentLevel & AccessLevel.ProtectedOrInternal;
995 if (t.IsNestedFamANDAssem)
996 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
998 // nested private is taken care of
1000 throw new Exception ("I give up, what are you?");
1004 // This answers `is the type P, as accessible as a member M which has the
1005 // accessability @flags which is declared as a nested member of the type T, this declspace'
1007 public bool AsAccessible (Type p, int flags)
1010 // 1) if M is private, its accessability is the same as this declspace.
1011 // we already know that P is accessible to T before this method, so we
1015 if ((flags & Modifiers.PRIVATE) != 0)
1018 while (p.IsArray || p.IsPointer || p.IsByRef)
1019 p = TypeManager.GetElementType (p);
1022 if (p.IsGenericParameter)
1025 if (TypeManager.IsGenericType (p)) {
1026 foreach (Type t in p.GetGenericArguments ()) {
1027 if (!AsAccessible (t, flags))
1032 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1033 AccessLevel mAccess = this.EffectiveAccessLevel &
1034 GetAccessLevelFromModifiers (flags);
1036 // for every place from which we can access M, we must
1037 // be able to access P as well. So, we want
1038 // For every bit in M and P, M_i -> P_1 == true
1039 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1041 return ~ (~ mAccess | pAccess) == 0;
1044 private Type LookupNestedTypeInHierarchy (string name)
1046 // if the member cache has been created, lets use it.
1047 // the member cache is MUCH faster.
1048 if (MemberCache != null)
1049 return MemberCache.FindNestedType (name);
1051 // no member cache. Do it the hard way -- reflection
1053 for (Type current_type = TypeBuilder;
1054 current_type != null && current_type != TypeManager.object_type;
1055 current_type = current_type.BaseType) {
1056 current_type = TypeManager.DropGenericTypeArguments (current_type);
1057 if (current_type is TypeBuilder) {
1058 TypeContainer tc = current_type == TypeBuilder
1060 : TypeManager.LookupTypeContainer (current_type);
1062 t = tc.FindNestedType (name);
1064 t = TypeManager.GetNestedType (current_type, name);
1067 if (t != null && CheckAccessLevel (t))
1074 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1076 return NamespaceEntry.LookupExtensionMethod (extensionType, true, name);
1080 // Public function used to locate types.
1082 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1084 // Returns: Type or null if they type can not be found.
1086 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1088 if (Cache.Contains (name))
1089 return (FullNamedExpression) Cache [name];
1091 FullNamedExpression e;
1092 Type t = LookupNestedTypeInHierarchy (name);
1094 e = new TypeExpression (t, Location.Null);
1095 else if (Parent != null)
1096 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1098 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1105 /// This function is broken and not what you're looking for. It should only
1106 /// be used while the type is still being created since it doesn't use the cache
1107 /// and relies on the filter doing the member name check.
1109 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1110 MemberFilter filter, object criteria);
1113 /// If we have a MemberCache, return it. This property may return null if the
1114 /// class doesn't have a member cache or while it's still being created.
1116 public abstract MemberCache MemberCache {
1120 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1122 if (a.Type == TypeManager.required_attr_type) {
1123 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1126 TypeBuilder.SetCustomAttribute (cb);
1130 // Extensions for generics
1132 TypeParameter[] type_params;
1133 TypeParameter[] type_param_list;
1135 protected string GetInstantiationName ()
1137 StringBuilder sb = new StringBuilder (Name);
1139 for (int i = 0; i < type_param_list.Length; i++) {
1142 sb.Append (type_param_list [i].Name);
1145 return sb.ToString ();
1148 bool check_type_parameter (ArrayList list, int start, string name)
1150 for (int i = 0; i < start; i++) {
1151 TypeParameter param = (TypeParameter) list [i];
1153 if (param.Name != name)
1156 Report.SymbolRelatedToPreviousError (Parent);
1157 // TODO: Location is wrong (parent instead of child)
1158 Report.Warning (693, 3, Location,
1159 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1160 name, Parent.GetSignatureForError ());
1168 TypeParameter[] initialize_type_params ()
1170 if (type_param_list != null)
1171 return type_param_list;
1173 DeclSpace the_parent = Parent;
1174 if (this is GenericMethod)
1178 ArrayList list = new ArrayList ();
1179 if (the_parent != null && the_parent.IsGeneric) {
1180 // FIXME: move generics info out of DeclSpace
1181 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1182 start = parent_params.Length;
1183 list.AddRange (parent_params);
1186 int count = type_params != null ? type_params.Length : 0;
1187 for (int i = 0; i < count; i++) {
1188 TypeParameter param = type_params [i];
1189 check_type_parameter (list, start, param.Name);
1193 type_param_list = new TypeParameter [list.Count];
1194 list.CopyTo (type_param_list, 0);
1195 return type_param_list;
1198 public virtual void SetParameterInfo (ArrayList constraints_list)
1201 if (constraints_list != null) {
1203 80, Location, "Constraints are not allowed " +
1204 "on non-generic declarations");
1210 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1211 type_params = new TypeParameter [names.Length];
1214 // Register all the names
1216 for (int i = 0; i < type_params.Length; i++) {
1217 TypeParameterName name = names [i];
1219 Constraints constraints = null;
1220 if (constraints_list != null) {
1221 int total = constraints_list.Count;
1222 for (int ii = 0; ii < total; ++ii) {
1223 Constraints constraints_at = (Constraints)constraints_list[ii];
1224 // TODO: it is used by iterators only
1225 if (constraints_at == null) {
1226 constraints_list.RemoveAt (ii);
1230 if (constraints_at.TypeParameter == name.Name) {
1231 constraints = constraints_at;
1232 constraints_list.RemoveAt(ii);
1238 type_params [i] = new TypeParameter (
1239 Parent, this, name.Name, constraints, name.OptAttributes,
1242 AddToContainer (type_params [i], name.Name);
1245 if (constraints_list != null && constraints_list.Count > 0) {
1246 foreach (Constraints constraint in constraints_list) {
1247 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1248 GetSignatureForError (), constraint.TypeParameter);
1253 public TypeParameter[] TypeParameters {
1256 throw new InvalidOperationException ();
1257 if ((PartialContainer != null) && (PartialContainer != this))
1258 return PartialContainer.TypeParameters;
1259 if (type_param_list == null)
1260 initialize_type_params ();
1262 return type_param_list;
1266 public TypeParameter[] CurrentTypeParameters {
1269 throw new InvalidOperationException ();
1270 if ((PartialContainer != null) && (PartialContainer != this))
1271 return PartialContainer.CurrentTypeParameters;
1272 if (type_params != null)
1275 return new TypeParameter [0];
1279 public int CountTypeParameters {
1281 return count_type_params;
1285 public int CountCurrentTypeParameters {
1287 return count_current_type_params;
1291 public TypeParameterExpr LookupGeneric (string name, Location loc)
1296 TypeParameter [] current_params;
1297 if (this is TypeContainer)
1298 current_params = PartialContainer.CurrentTypeParameters;
1300 current_params = CurrentTypeParameters;
1302 foreach (TypeParameter type_param in current_params) {
1303 if (type_param.Name == name)
1304 return new TypeParameterExpr (type_param, loc);
1308 return Parent.LookupGeneric (name, loc);
1313 // Used for error reporting only
1314 public virtual Type LookupAnyGeneric (string typeName)
1316 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1319 public override string[] ValidAttributeTargets {
1320 get { return attribute_targets; }
1323 protected override bool VerifyClsCompliance ()
1325 if (!base.VerifyClsCompliance ()) {
1329 if (type_params != null) {
1330 foreach (TypeParameter tp in type_params) {
1331 if (tp.Constraints == null)
1334 tp.Constraints.VerifyClsCompliance ();
1338 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1342 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1343 if (!cache.Contains (lcase)) {
1344 cache.Add (lcase, this);
1348 object val = cache [lcase];
1350 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1353 Report.SymbolRelatedToPreviousError (t);
1356 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1359 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1361 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1368 /// This is a readonly list of MemberInfo's.
1370 public class MemberList : IList {
1371 public readonly IList List;
1375 /// Create a new MemberList from the given IList.
1377 public MemberList (IList list)
1382 this.List = new ArrayList ();
1387 /// Concatenate the ILists `first' and `second' to a new MemberList.
1389 public MemberList (IList first, IList second)
1391 ArrayList list = new ArrayList ();
1392 list.AddRange (first);
1393 list.AddRange (second);
1398 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1401 /// Cast the MemberList into a MemberInfo[] array.
1404 /// This is an expensive operation, only use it if it's really necessary.
1406 public static explicit operator MemberInfo [] (MemberList list)
1408 Timer.StartTimer (TimerType.MiscTimer);
1409 MemberInfo [] result = new MemberInfo [list.Count];
1410 list.CopyTo (result, 0);
1411 Timer.StopTimer (TimerType.MiscTimer);
1423 public bool IsSynchronized {
1425 return List.IsSynchronized;
1429 public object SyncRoot {
1431 return List.SyncRoot;
1435 public void CopyTo (Array array, int index)
1437 List.CopyTo (array, index);
1442 public IEnumerator GetEnumerator ()
1444 return List.GetEnumerator ();
1449 public bool IsFixedSize {
1455 public bool IsReadOnly {
1461 object IList.this [int index] {
1463 return List [index];
1467 throw new NotSupportedException ();
1471 // FIXME: try to find out whether we can avoid the cast in this indexer.
1472 public MemberInfo this [int index] {
1474 return (MemberInfo) List [index];
1478 public int Add (object value)
1480 throw new NotSupportedException ();
1483 public void Clear ()
1485 throw new NotSupportedException ();
1488 public bool Contains (object value)
1490 return List.Contains (value);
1493 public int IndexOf (object value)
1495 return List.IndexOf (value);
1498 public void Insert (int index, object value)
1500 throw new NotSupportedException ();
1503 public void Remove (object value)
1505 throw new NotSupportedException ();
1508 public void RemoveAt (int index)
1510 throw new NotSupportedException ();
1515 /// This interface is used to get all members of a class when creating the
1516 /// member cache. It must be implemented by all DeclSpace derivatives which
1517 /// want to support the member cache and by TypeHandle to get caching of
1518 /// non-dynamic types.
1520 public interface IMemberContainer {
1522 /// The name of the IMemberContainer. This is only used for
1523 /// debugging purposes.
1530 /// The type of this IMemberContainer.
1537 /// Returns the IMemberContainer of the base class or null if this
1538 /// is an interface or TypeManger.object_type.
1539 /// This is used when creating the member cache for a class to get all
1540 /// members from the base class.
1542 MemberCache BaseCache {
1547 /// Whether this is an interface.
1554 /// Returns all members of this class with the corresponding MemberTypes
1555 /// and BindingFlags.
1558 /// When implementing this method, make sure not to return any inherited
1559 /// members and check the MemberTypes and BindingFlags properly.
1560 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1561 /// get the BindingFlags (static/non-static,public/non-public) in the
1562 /// MemberInfo class, but the cache needs this information. That's why
1563 /// this method is called multiple times with different BindingFlags.
1565 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1568 /// Return the container's member cache.
1570 MemberCache MemberCache {
1576 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1577 /// member lookups. It has a member name based hash table; it maps each member
1578 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1579 /// and the BindingFlags that were initially used to get it. The cache contains
1580 /// all members of the current class and all inherited members. If this cache is
1581 /// for an interface types, it also contains all inherited members.
1583 /// There are two ways to get a MemberCache:
1584 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1585 /// use the DeclSpace.MemberCache property.
1586 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1587 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1589 public class MemberCache {
1590 public readonly IMemberContainer Container;
1591 protected Hashtable member_hash;
1592 protected Hashtable method_hash;
1595 /// Create a new MemberCache for the given IMemberContainer `container'.
1597 public MemberCache (IMemberContainer container)
1599 this.Container = container;
1601 Timer.IncrementCounter (CounterType.MemberCache);
1602 Timer.StartTimer (TimerType.CacheInit);
1604 // If we have a base class (we have a base class unless we're
1605 // TypeManager.object_type), we deep-copy its MemberCache here.
1606 if (Container.BaseCache != null)
1607 member_hash = SetupCache (Container.BaseCache);
1609 member_hash = new Hashtable ();
1611 // If this is neither a dynamic type nor an interface, create a special
1612 // method cache with all declared and inherited methods.
1613 Type type = container.Type;
1614 if (!(type is TypeBuilder) && !type.IsInterface &&
1615 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1616 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1617 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1618 method_hash = new Hashtable ();
1622 // Add all members from the current class.
1623 AddMembers (Container);
1625 Timer.StopTimer (TimerType.CacheInit);
1628 public MemberCache (Type[] ifaces)
1631 // The members of this cache all belong to other caches.
1632 // So, 'Container' will not be used.
1634 this.Container = null;
1636 member_hash = new Hashtable ();
1640 foreach (Type itype in ifaces)
1641 AddCacheContents (TypeManager.LookupMemberCache (itype));
1644 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1646 this.Container = container;
1648 // If we have a base class (we have a base class unless we're
1649 // TypeManager.object_type), we deep-copy its MemberCache here.
1650 if (Container.BaseCache != null)
1651 member_hash = SetupCache (Container.BaseCache);
1653 member_hash = new Hashtable ();
1655 if (base_class != null)
1656 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1657 if (ifaces != null) {
1658 foreach (Type itype in ifaces) {
1659 MemberCache cache = TypeManager.LookupMemberCache (itype);
1661 AddCacheContents (cache);
1667 /// Bootstrap this member cache by doing a deep-copy of our base.
1669 static Hashtable SetupCache (MemberCache base_class)
1671 Hashtable hash = new Hashtable ();
1673 if (base_class == null)
1676 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1677 while (it.MoveNext ()) {
1678 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1685 /// Add the contents of `cache' to the member_hash.
1687 void AddCacheContents (MemberCache cache)
1689 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1690 while (it.MoveNext ()) {
1691 ArrayList list = (ArrayList) member_hash [it.Key];
1693 member_hash [it.Key] = list = new ArrayList ();
1695 ArrayList entries = (ArrayList) it.Value;
1696 for (int i = entries.Count-1; i >= 0; i--) {
1697 CacheEntry entry = (CacheEntry) entries [i];
1699 if (entry.Container != cache.Container)
1707 /// Add all members from class `container' to the cache.
1709 void AddMembers (IMemberContainer container)
1711 // We need to call AddMembers() with a single member type at a time
1712 // to get the member type part of CacheEntry.EntryType right.
1713 if (!container.IsInterface) {
1714 AddMembers (MemberTypes.Constructor, container);
1715 AddMembers (MemberTypes.Field, container);
1717 AddMembers (MemberTypes.Method, container);
1718 AddMembers (MemberTypes.Property, container);
1719 AddMembers (MemberTypes.Event, container);
1720 // Nested types are returned by both Static and Instance searches.
1721 AddMembers (MemberTypes.NestedType,
1722 BindingFlags.Static | BindingFlags.Public, container);
1723 AddMembers (MemberTypes.NestedType,
1724 BindingFlags.Static | BindingFlags.NonPublic, container);
1727 void AddMembers (MemberTypes mt, IMemberContainer container)
1729 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1730 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1731 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1732 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1735 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1736 string name, MemberInfo member)
1738 // We use a name-based hash table of ArrayList's.
1739 ArrayList list = (ArrayList) member_hash [name];
1741 list = new ArrayList ();
1742 member_hash.Add (name, list);
1745 // When this method is called for the current class, the list will
1746 // already contain all inherited members from our base classes.
1747 // We cannot add new members in front of the list since this'd be an
1748 // expensive operation, that's why the list is sorted in reverse order
1749 // (ie. members from the current class are coming last).
1750 list.Add (new CacheEntry (container, member, mt, bf));
1754 /// Add all members from class `container' with the requested MemberTypes and
1755 /// BindingFlags to the cache. This method is called multiple times with different
1756 /// MemberTypes and BindingFlags.
1758 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1760 MemberList members = container.GetMembers (mt, bf);
1762 foreach (MemberInfo member in members) {
1763 string name = member.Name;
1765 AddMember (mt, bf, container, name, member);
1767 if (member is MethodInfo) {
1768 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1770 AddMember (mt, bf, container, gname, member);
1776 /// Add all declared and inherited methods from class `type' to the method cache.
1778 void AddMethods (Type type)
1780 AddMethods (BindingFlags.Static | BindingFlags.Public |
1781 BindingFlags.FlattenHierarchy, type);
1782 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1783 BindingFlags.FlattenHierarchy, type);
1784 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1785 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1788 static ArrayList overrides = new ArrayList ();
1790 void AddMethods (BindingFlags bf, Type type)
1792 MethodBase [] members = type.GetMethods (bf);
1794 Array.Reverse (members);
1796 foreach (MethodBase member in members) {
1797 string name = member.Name;
1799 // We use a name-based hash table of ArrayList's.
1800 ArrayList list = (ArrayList) method_hash [name];
1802 list = new ArrayList ();
1803 method_hash.Add (name, list);
1806 MethodInfo curr = (MethodInfo) member;
1807 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1808 MethodInfo base_method = curr.GetBaseDefinition ();
1810 if (base_method == curr)
1811 // Not every virtual function needs to have a NewSlot flag.
1814 overrides.Add (curr);
1815 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1819 if (overrides.Count > 0) {
1820 for (int i = 0; i < overrides.Count; ++i)
1821 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1825 // Unfortunately, the elements returned by Type.GetMethods() aren't
1826 // sorted so we need to do this check for every member.
1827 BindingFlags new_bf = bf;
1828 if (member.DeclaringType == type)
1829 new_bf |= BindingFlags.DeclaredOnly;
1831 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1836 /// Compute and return a appropriate `EntryType' magic number for the given
1837 /// MemberTypes and BindingFlags.
1839 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1841 EntryType type = EntryType.None;
1843 if ((mt & MemberTypes.Constructor) != 0)
1844 type |= EntryType.Constructor;
1845 if ((mt & MemberTypes.Event) != 0)
1846 type |= EntryType.Event;
1847 if ((mt & MemberTypes.Field) != 0)
1848 type |= EntryType.Field;
1849 if ((mt & MemberTypes.Method) != 0)
1850 type |= EntryType.Method;
1851 if ((mt & MemberTypes.Property) != 0)
1852 type |= EntryType.Property;
1853 // Nested types are returned by static and instance searches.
1854 if ((mt & MemberTypes.NestedType) != 0)
1855 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1857 if ((bf & BindingFlags.Instance) != 0)
1858 type |= EntryType.Instance;
1859 if ((bf & BindingFlags.Static) != 0)
1860 type |= EntryType.Static;
1861 if ((bf & BindingFlags.Public) != 0)
1862 type |= EntryType.Public;
1863 if ((bf & BindingFlags.NonPublic) != 0)
1864 type |= EntryType.NonPublic;
1865 if ((bf & BindingFlags.DeclaredOnly) != 0)
1866 type |= EntryType.Declared;
1872 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1873 /// denote multiple member types. Returns true if the given flags value denotes a
1874 /// single member types.
1876 public static bool IsSingleMemberType (MemberTypes mt)
1879 case MemberTypes.Constructor:
1880 case MemberTypes.Event:
1881 case MemberTypes.Field:
1882 case MemberTypes.Method:
1883 case MemberTypes.Property:
1884 case MemberTypes.NestedType:
1893 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1894 /// number to speed up the searching process.
1897 protected enum EntryType {
1902 MaskStatic = Instance|Static,
1906 MaskProtection = Public|NonPublic,
1910 Constructor = 0x020,
1917 NotExtensionMethod = 0x800,
1919 MaskType = Constructor|Event|Field|Method|Property|NestedType
1922 protected class CacheEntry {
1923 public readonly IMemberContainer Container;
1924 public EntryType EntryType;
1925 public readonly MemberInfo Member;
1927 public CacheEntry (IMemberContainer container, MemberInfo member,
1928 MemberTypes mt, BindingFlags bf)
1930 this.Container = container;
1931 this.Member = member;
1932 this.EntryType = GetEntryType (mt, bf);
1935 public override string ToString ()
1937 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1943 /// This is called each time we're walking up one level in the class hierarchy
1944 /// and checks whether we can abort the search since we've already found what
1945 /// we were looking for.
1947 protected bool DoneSearching (ArrayList list)
1950 // We've found exactly one member in the current class and it's not
1951 // a method or constructor.
1953 if (list.Count == 1 && !(list [0] is MethodBase))
1957 // Multiple properties: we query those just to find out the indexer
1960 if ((list.Count > 0) && (list [0] is PropertyInfo))
1967 /// Looks up members with name `name'. If you provide an optional
1968 /// filter function, it'll only be called with members matching the
1969 /// requested member name.
1971 /// This method will try to use the cache to do the lookup if possible.
1973 /// Unlike other FindMembers implementations, this method will always
1974 /// check all inherited members - even when called on an interface type.
1976 /// If you know that you're only looking for methods, you should use
1977 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1978 /// When doing a method-only search, it'll try to use a special method
1979 /// cache (unless it's a dynamic type or an interface) and the returned
1980 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1981 /// The lookup process will automatically restart itself in method-only
1982 /// search mode if it discovers that it's about to return methods.
1984 ArrayList global = new ArrayList ();
1985 bool using_global = false;
1987 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1989 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1990 MemberFilter filter, object criteria)
1993 throw new Exception ();
1995 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1996 bool method_search = mt == MemberTypes.Method;
1997 // If we have a method cache and we aren't already doing a method-only search,
1998 // then we restart a method search if the first match is a method.
1999 bool do_method_search = !method_search && (method_hash != null);
2001 ArrayList applicable;
2003 // If this is a method-only search, we try to use the method cache if
2004 // possible; a lookup in the method cache will return a MemberInfo with
2005 // the correct ReflectedType for inherited methods.
2007 if (method_search && (method_hash != null))
2008 applicable = (ArrayList) method_hash [name];
2010 applicable = (ArrayList) member_hash [name];
2012 if (applicable == null)
2013 return emptyMemberInfo;
2016 // 32 slots gives 53 rss/54 size
2017 // 2/4 slots gives 55 rss
2019 // Strange: from 25,000 calls, only 1,800
2020 // are above 2. Why does this impact it?
2023 using_global = true;
2025 Timer.StartTimer (TimerType.CachedLookup);
2027 EntryType type = GetEntryType (mt, bf);
2029 IMemberContainer current = Container;
2031 bool do_interface_search = current.IsInterface;
2033 // `applicable' is a list of all members with the given member name `name'
2034 // in the current class and all its base classes. The list is sorted in
2035 // reverse order due to the way how the cache is initialy created (to speed
2036 // things up, we're doing a deep-copy of our base).
2038 for (int i = applicable.Count-1; i >= 0; i--) {
2039 CacheEntry entry = (CacheEntry) applicable [i];
2041 // This happens each time we're walking one level up in the class
2042 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2043 // the first time this happens (this may already happen in the first
2044 // iteration of this loop if there are no members with the name we're
2045 // looking for in the current class).
2046 if (entry.Container != current) {
2050 if (!do_interface_search && DoneSearching (global))
2053 current = entry.Container;
2056 // Is the member of the correct type ?
2057 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2060 // Is the member static/non-static ?
2061 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2064 // Apply the filter to it.
2065 if (filter (entry.Member, criteria)) {
2066 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2067 do_method_search = false;
2070 // Because interfaces support multiple inheritance we have to be sure that
2071 // base member is from same interface, so only top level member will be returned
2072 if (do_interface_search && global.Count > 0) {
2073 bool member_already_exists = false;
2075 foreach (MemberInfo mi in global) {
2076 if (mi is MethodBase)
2079 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2080 member_already_exists = true;
2084 if (member_already_exists)
2088 global.Add (entry.Member);
2092 Timer.StopTimer (TimerType.CachedLookup);
2094 // If we have a method cache and we aren't already doing a method-only
2095 // search, we restart in method-only search mode if the first match is
2096 // a method. This ensures that we return a MemberInfo with the correct
2097 // ReflectedType for inherited methods.
2098 if (do_method_search && (global.Count > 0)){
2099 using_global = false;
2101 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2104 using_global = false;
2105 MemberInfo [] copy = new MemberInfo [global.Count];
2106 global.CopyTo (copy);
2111 /// Returns true if iterface exists in any base interfaces (ifaces)
2113 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2115 foreach (Type iface in ifaces) {
2116 if (iface == ifaceToFind)
2119 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2120 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2126 // find the nested type @name in @this.
2127 public Type FindNestedType (string name)
2129 ArrayList applicable = (ArrayList) member_hash [name];
2130 if (applicable == null)
2133 for (int i = applicable.Count-1; i >= 0; i--) {
2134 CacheEntry entry = (CacheEntry) applicable [i];
2135 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2136 return (Type) entry.Member;
2142 public MemberInfo FindBaseEvent (Type invocationType, string name)
2144 ArrayList applicable = (ArrayList) member_hash [name];
2145 if (applicable == null)
2149 // Walk the chain of events, starting from the top.
2151 for (int i = applicable.Count - 1; i >= 0; i--)
2153 CacheEntry entry = (CacheEntry) applicable [i];
2154 if ((entry.EntryType & EntryType.Event) == 0)
2157 EventInfo ei = (EventInfo)entry.Member;
2158 return ei.GetAddMethod (true);
2165 // Looks for extension methods with defined name and extension type
2167 public ArrayList FindExtensionMethods (Type extensionType, string name)
2170 if (method_hash != null)
2171 entries = (ArrayList)method_hash [name];
2173 entries = (ArrayList)member_hash [name];
2175 if (entries == null)
2178 ArrayList candidates = null;
2179 foreach (CacheEntry entry in entries) {
2180 if ((entry.EntryType & (EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod)) == (EntryType.Static | EntryType.Method)) {
2181 MethodBase mb = (MethodBase)entry.Member;
2183 IMethodData md = TypeManager.GetMethod (mb);
2184 ParameterData pd = md == null ?
2185 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2187 Type ex_type = pd.ExtensionMethodType;
2188 if (ex_type == null) {
2189 entry.EntryType |= EntryType.NotExtensionMethod;
2193 if (ex_type == extensionType || TypeManager.IsGenericParameter (ex_type)) {
2194 if (candidates == null)
2195 candidates = new ArrayList (2);
2196 candidates.Add (mb);
2205 // This finds the method or property for us to override. invocationType is the type where
2206 // the override is going to be declared, name is the name of the method/property, and
2207 // paramTypes is the parameters, if any to the method or property
2209 // Because the MemberCache holds members from this class and all the base classes,
2210 // we can avoid tons of reflection stuff.
2212 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, GenericMethod genericMethod, bool is_property)
2214 ArrayList applicable;
2215 if (method_hash != null && !is_property)
2216 applicable = (ArrayList) method_hash [name];
2218 applicable = (ArrayList) member_hash [name];
2220 if (applicable == null)
2223 // Walk the chain of methods, starting from the top.
2225 for (int i = applicable.Count - 1; i >= 0; i--) {
2226 CacheEntry entry = (CacheEntry) applicable [i];
2228 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2231 PropertyInfo pi = null;
2232 MethodInfo mi = null;
2233 FieldInfo fi = null;
2234 Type [] cmpAttrs = null;
2237 if ((entry.EntryType & EntryType.Field) != 0) {
2238 fi = (FieldInfo)entry.Member;
2240 // TODO: For this case we ignore member type
2241 //fb = TypeManager.GetField (fi);
2242 //cmpAttrs = new Type[] { fb.MemberType };
2244 pi = (PropertyInfo) entry.Member;
2245 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2248 mi = (MethodInfo) entry.Member;
2249 cmpAttrs = TypeManager.GetParameterData (mi).Types;
2253 // TODO: Almost duplicate !
2255 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2256 case FieldAttributes.PrivateScope:
2258 case FieldAttributes.Private:
2260 // A private method is Ok if we are a nested subtype.
2261 // The spec actually is not very clear about this, see bug 52458.
2263 if (!invocationType.Equals (entry.Container.Type) &&
2264 !TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2267 case FieldAttributes.FamANDAssem:
2268 case FieldAttributes.Assembly:
2270 // Check for assembly methods
2272 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2276 return entry.Member;
2280 // Check the arguments
2282 if (cmpAttrs.Length != paramTypes.Length)
2286 for (j = 0; j < cmpAttrs.Length; ++j)
2287 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2289 if (j < cmpAttrs.Length)
2293 // check generic arguments for methods
2296 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2297 if (genericMethod == null && cmpGenArgs.Length != 0)
2299 if (genericMethod != null && cmpGenArgs.Length != genericMethod.TypeParameters.Length)
2304 // get one of the methods because this has the visibility info.
2307 mi = pi.GetGetMethod (true);
2309 mi = pi.GetSetMethod (true);
2315 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2316 case MethodAttributes.PrivateScope:
2318 case MethodAttributes.Private:
2320 // A private method is Ok if we are a nested subtype.
2321 // The spec actually is not very clear about this, see bug 52458.
2323 if (!invocationType.Equals (entry.Container.Type) &&
2324 !TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2327 case MethodAttributes.FamANDAssem:
2328 case MethodAttributes.Assembly:
2330 // Check for assembly methods
2332 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2336 return entry.Member;
2343 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2344 /// We handle two cases. The first is for types without parameters (events, field, properties).
2345 /// The second are methods, indexers and this is why ignore_complex_types is here.
2346 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2348 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2350 ArrayList applicable = null;
2352 if (method_hash != null)
2353 applicable = (ArrayList) method_hash [name];
2355 if (applicable != null) {
2356 for (int i = applicable.Count - 1; i >= 0; i--) {
2357 CacheEntry entry = (CacheEntry) applicable [i];
2358 if ((entry.EntryType & EntryType.Public) != 0)
2359 return entry.Member;
2363 if (member_hash == null)
2365 applicable = (ArrayList) member_hash [name];
2367 if (applicable != null) {
2368 for (int i = applicable.Count - 1; i >= 0; i--) {
2369 CacheEntry entry = (CacheEntry) applicable [i];
2370 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2371 if (ignore_complex_types) {
2372 if ((entry.EntryType & EntryType.Method) != 0)
2375 // Does exist easier way how to detect indexer ?
2376 if ((entry.EntryType & EntryType.Property) != 0) {
2377 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2378 if (arg_types.Length > 0)
2382 return entry.Member;
2389 Hashtable locase_table;
2392 /// Builds low-case table for CLS Compliance test
2394 public Hashtable GetPublicMembers ()
2396 if (locase_table != null)
2397 return locase_table;
2399 locase_table = new Hashtable ();
2400 foreach (DictionaryEntry entry in member_hash) {
2401 ArrayList members = (ArrayList)entry.Value;
2402 for (int ii = 0; ii < members.Count; ++ii) {
2403 CacheEntry member_entry = (CacheEntry) members [ii];
2405 if ((member_entry.EntryType & EntryType.Public) == 0)
2408 // TODO: Does anyone know easier way how to detect that member is internal ?
2409 switch (member_entry.EntryType & EntryType.MaskType) {
2410 case EntryType.Constructor:
2413 case EntryType.Field:
2414 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2418 case EntryType.Method:
2419 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2423 case EntryType.Property:
2424 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2425 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2429 case EntryType.Event:
2430 EventInfo ei = (EventInfo)member_entry.Member;
2431 MethodInfo mi = ei.GetAddMethod ();
2432 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2436 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2437 locase_table [lcase] = member_entry.Member;
2441 return locase_table;
2444 public Hashtable Members {
2451 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2454 // TODO: refactor as method is always 'this'
2455 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2457 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2459 for (int i = 0; i < al.Count; ++i) {
2460 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2463 if (entry.Member == this_builder)
2466 if ((entry.EntryType & tested_type) != tested_type)
2469 MethodBase method_to_compare = (MethodBase)entry.Member;
2470 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2471 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2473 if (result == AttributeTester.Result.Ok)
2476 IMethodData md = TypeManager.GetMethod (method_to_compare);
2478 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2479 // However it is exactly what csc does.
2480 if (md != null && !md.IsClsComplianceRequired ())
2483 Report.SymbolRelatedToPreviousError (entry.Member);
2485 case AttributeTester.Result.RefOutArrayError:
2486 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2488 case AttributeTester.Result.ArrayArrayError:
2489 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2493 throw new NotImplementedException (result.ToString ());