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 ()
135 if (TypeArguments != null)
136 return new SimpleName (Basename, TypeArguments, Location);
138 if (RootContext.Version == LanguageVersion.LINQ && Name == "var")
139 return new VarExpr (Name, Location);
141 return new SimpleName (Name, Location);
144 if (is_double_colon) {
145 if (Left.Left != null)
146 throw new InternalErrorException ("The left side of a :: should be an identifier");
147 return new QualifiedAliasMember (Left.Name, Name, Location);
150 Expression lexpr = Left.GetTypeExpression ();
151 return new MemberAccess (lexpr, Name, TypeArguments, Location);
154 public MemberName Clone ()
156 MemberName left_clone = Left == null ? null : Left.Clone ();
157 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
160 public string Basename {
162 if (TypeArguments != null)
163 return MakeName (Name, TypeArguments);
169 public string FullName {
171 if (TypeArguments != null)
172 return Name + "<" + TypeArguments + ">";
178 public string MethodName {
180 string connect = is_double_colon ? "::" : ".";
182 return Left.FullName + connect + Name;
188 public override string ToString ()
190 string connect = is_double_colon ? "::" : ".";
192 return Left.FullName + connect + FullName;
197 public override bool Equals (object other)
199 return Equals (other as MemberName);
202 public bool Equals (MemberName other)
206 if (other == null || Name != other.Name)
208 if (is_double_colon != other.is_double_colon)
211 if ((TypeArguments != null) &&
212 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
215 if ((TypeArguments == null) && (other.TypeArguments != null))
219 return other.Left == null;
221 return Left.Equals (other.Left);
224 public override int GetHashCode ()
226 int hash = Name.GetHashCode ();
227 for (MemberName n = Left; n != null; n = n.Left)
228 hash ^= n.Name.GetHashCode ();
232 if (TypeArguments != null)
233 hash ^= TypeArguments.Count << 5;
235 return hash & 0x7FFFFFFF;
238 public int CountTypeArguments {
240 if (TypeArguments == null)
243 return TypeArguments.Count;
247 public static string MakeName (string name, TypeArguments args)
252 return name + "`" + args.Count;
255 public static string MakeName (string name, int count)
257 return name + "`" + count;
262 /// Base representation for members. This is used to keep track
263 /// of Name, Location and Modifier flags, and handling Attributes.
265 public abstract class MemberCore : Attributable, IResolveContext {
270 protected string cached_name;
273 if (cached_name == null)
274 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
279 // Is not readonly because of IndexerName attribute
280 private MemberName member_name;
281 public MemberName MemberName {
282 get { return member_name; }
286 /// Modifier flags that the user specified in the source code
288 private int mod_flags;
289 public int ModFlags {
292 if ((value & Modifiers.COMPILER_GENERATED) != 0)
293 caching_flags = Flags.IsUsed | Flags.IsAssigned;
300 public readonly DeclSpace Parent;
303 /// Location where this declaration happens
305 public Location Location {
306 get { return member_name.Location; }
310 /// XML documentation comment
312 protected string comment;
315 /// Represents header string for documentation comment
316 /// for each member types.
318 public abstract string DocCommentHeader { get; }
322 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
323 Obsolete = 1 << 1, // Type has obsolete attribute
324 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
325 ClsCompliant = 1 << 3, // Type is CLS Compliant
326 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
327 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
328 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
329 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
330 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
331 Excluded = 1 << 9, // Method is conditional
332 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
334 IsAssigned = 1 << 12, // Field is assigned
335 HasExplicitLayout = 1 << 13
339 /// MemberCore flags at first detected then cached
341 internal Flags caching_flags;
343 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
346 this.Parent = parent;
348 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
351 protected virtual void SetMemberName (MemberName new_name)
353 member_name = new_name;
357 protected bool CheckAbstractAndExtern (bool has_block)
359 if (Parent.PartialContainer.Kind == Kind.Interface)
363 if ((ModFlags & Modifiers.EXTERN) != 0) {
364 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
365 GetSignatureForError ());
369 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
370 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
371 GetSignatureForError ());
375 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
376 if (RootContext.Version >= LanguageVersion.LINQ && this is Property.PropertyMethod) {
377 Report.Error (840, Location, "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
378 GetSignatureForError ());
380 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract or extern",
381 GetSignatureForError ());
390 public abstract bool Define ();
392 public virtual string DocComment {
402 // Returns full member name for error message
404 public virtual string GetSignatureForError ()
406 if (Parent == null || Parent.Parent == null)
407 return member_name.ToString ();
409 return String.Concat (Parent.GetSignatureForError (), '.', member_name.ToString ());
413 /// Base Emit method. This is also entry point for CLS-Compliant verification.
415 public virtual void Emit ()
417 if (!RootContext.VerifyClsCompliance)
420 VerifyClsCompliance ();
423 public virtual bool IsUsed {
424 get { return (caching_flags & Flags.IsUsed) != 0; }
427 public void SetMemberIsUsed ()
429 caching_flags |= Flags.IsUsed;
433 /// Returns instance of ObsoleteAttribute for this MemberCore
435 public virtual ObsoleteAttribute GetObsoleteAttribute ()
437 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
438 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
442 caching_flags &= ~Flags.Obsolete_Undetected;
444 if (OptAttributes == null)
447 Attribute obsolete_attr = OptAttributes.Search (
448 TypeManager.obsolete_attribute_type);
449 if (obsolete_attr == null)
452 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
453 if (obsolete == null)
456 caching_flags |= Flags.Obsolete;
461 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
463 public virtual void CheckObsoleteness (Location loc)
466 Parent.CheckObsoleteness (loc);
468 ObsoleteAttribute oa = GetObsoleteAttribute ();
473 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
477 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
479 public override bool IsClsComplianceRequired ()
481 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
482 return (caching_flags & Flags.ClsCompliant) != 0;
484 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
485 caching_flags &= ~Flags.ClsCompliance_Undetected;
486 caching_flags |= Flags.ClsCompliant;
490 caching_flags &= ~Flags.ClsCompliance_Undetected;
495 /// Returns true when MemberCore is exposed from assembly.
497 public bool IsExposedFromAssembly ()
499 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
502 DeclSpace parentContainer = Parent;
503 while (parentContainer != null && parentContainer.ModFlags != 0) {
504 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
506 parentContainer = parentContainer.Parent;
512 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
513 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
515 public virtual bool GetClsCompliantAttributeValue ()
517 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
518 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
520 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
522 if (OptAttributes != null) {
523 Attribute cls_attribute = OptAttributes.Search (
524 TypeManager.cls_compliant_attribute_type);
525 if (cls_attribute != null) {
526 caching_flags |= Flags.HasClsCompliantAttribute;
527 bool value = cls_attribute.GetClsCompliantAttributeValue ();
529 caching_flags |= Flags.ClsCompliantAttributeTrue;
534 if (Parent.GetClsCompliantAttributeValue ()) {
535 caching_flags |= Flags.ClsCompliantAttributeTrue;
542 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
544 protected bool HasClsCompliantAttribute {
546 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
551 /// It helps to handle error 102 & 111 detection
553 public virtual bool MarkForDuplicationCheck ()
559 /// The main virtual method for CLS-Compliant verifications.
560 /// The method returns true if member is CLS-Compliant and false if member is not
561 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
562 /// and add their extra verifications.
564 protected virtual bool VerifyClsCompliance ()
566 if (!IsClsComplianceRequired ()) {
567 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
568 if (!IsExposedFromAssembly ())
569 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
570 if (!CodeGen.Assembly.IsClsCompliant)
571 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
576 if (HasClsCompliantAttribute) {
577 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
578 Report.Error (3014, Location,
579 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
580 GetSignatureForError ());
584 if (!Parent.IsClsComplianceRequired ()) {
585 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
586 GetSignatureForError (), Parent.GetSignatureForError ());
591 if (member_name.Name [0] == '_') {
592 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
598 // Raised (and passed an XmlElement that contains the comment)
599 // when GenerateDocComment is writing documentation expectedly.
601 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
606 // Returns a string that represents the signature for this
607 // member which should be used in XML documentation.
609 public virtual string GetDocCommentName (DeclSpace ds)
611 if (ds == null || this is DeclSpace)
612 return DocCommentHeader + Name;
614 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
618 // Generates xml doc comments (if any), and if required,
619 // handle warning report.
621 internal virtual void GenerateDocComment (DeclSpace ds)
623 DocUtil.GenerateDocComment (this, ds);
626 public override IResolveContext ResolveContext {
630 #region IResolveContext Members
632 public DeclSpace DeclContainer {
633 get { return Parent; }
636 public virtual DeclSpace GenericDeclContainer {
637 get { return DeclContainer; }
640 public bool IsInObsoleteScope {
642 if (GetObsoleteAttribute () != null)
645 return Parent == null ? false : Parent.IsInObsoleteScope;
649 public bool IsInUnsafeScope {
651 if ((ModFlags & Modifiers.UNSAFE) != 0)
654 return Parent == null ? false : Parent.IsInUnsafeScope;
662 /// Base class for structs, classes, enumerations and interfaces.
665 /// They all create new declaration spaces. This
666 /// provides the common foundation for managing those name
669 public abstract class DeclSpace : MemberCore {
671 /// This points to the actual definition that is being
672 /// created with System.Reflection.Emit
674 public TypeBuilder TypeBuilder;
677 /// If we are a generic type, this is the type we are
678 /// currently defining. We need to lookup members on this
679 /// instead of the TypeBuilder.
681 public Type CurrentType;
684 // This is the namespace in which this typecontainer
685 // was declared. We use this to resolve names.
687 public NamespaceEntry NamespaceEntry;
689 private Hashtable Cache = new Hashtable ();
691 public readonly string Basename;
693 protected Hashtable defined_names;
695 public TypeContainer PartialContainer;
697 readonly bool is_generic;
698 readonly int count_type_params;
699 readonly int count_current_type_params;
702 // Whether we are Generic
704 public bool IsGeneric {
708 else if (Parent != null)
709 return Parent.IsGeneric;
715 static string[] attribute_targets = new string [] { "type" };
717 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
719 : base (parent, name, attrs)
722 Basename = name.Basename;
723 defined_names = new Hashtable ();
724 PartialContainer = null;
725 if (name.TypeArguments != null) {
727 count_type_params = count_current_type_params = name.TypeArguments.Count;
730 count_type_params += parent.count_type_params;
733 public override DeclSpace GenericDeclContainer {
738 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
740 protected virtual bool AddToContainer (MemberCore symbol, string name)
742 MemberCore mc = (MemberCore) defined_names [name];
745 defined_names.Add (name, symbol);
749 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
752 Report.SymbolRelatedToPreviousError (mc);
753 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
754 Error_MissingPartialModifier (symbol);
758 if (this is RootTypes) {
759 Report.Error (101, symbol.Location,
760 "The namespace `{0}' already contains a definition for `{1}'",
761 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
762 } else if (symbol is TypeParameter) {
763 Report.Error (692, symbol.Location,
764 "Duplicate type parameter `{0}'", name);
766 Report.Error (102, symbol.Location,
767 "The type `{0}' already contains a definition for `{1}'",
768 GetSignatureForError (), symbol.MemberName.Name);
775 /// Returns the MemberCore associated with a given name in the declaration
776 /// space. It doesn't return method based symbols !!
779 public MemberCore GetDefinition (string name)
781 return (MemberCore)defined_names [name];
784 public bool IsStaticClass {
785 get { return (ModFlags & Modifiers.STATIC) != 0; }
789 // root_types contains all the types. All TopLevel types
790 // hence have a parent that points to `root_types', that is
791 // why there is a non-obvious test down here.
793 public bool IsTopLevel {
794 get { return (Parent != null && Parent.Parent == null); }
797 public virtual void CloseType ()
799 if ((caching_flags & Flags.CloseTypeCreated) == 0){
801 TypeBuilder.CreateType ();
804 // The try/catch is needed because
805 // nested enumerations fail to load when they
808 // Even if this is the right order (enumerations
809 // declared after types).
811 // Note that this still creates the type and
812 // it is possible to save it
814 caching_flags |= Flags.CloseTypeCreated;
818 protected virtual TypeAttributes TypeAttr {
819 get { return CodeGen.Module.DefaultCharSetType; }
823 /// Should be overriten by the appropriate declaration space
825 public abstract TypeBuilder DefineType ();
828 /// Define all members, but don't apply any attributes or do anything which may
829 /// access not-yet-defined classes. This method also creates the MemberCache.
831 public virtual bool DefineMembers ()
833 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
834 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
840 protected void Error_MissingPartialModifier (MemberCore type)
842 Report.Error (260, type.Location,
843 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
844 type.GetSignatureForError ());
847 public override string GetSignatureForError ()
850 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
852 // Parent.GetSignatureForError
856 public bool CheckAccessLevel (Type check_type)
859 if (this is GenericMethod)
860 tb = Parent.TypeBuilder;
864 check_type = TypeManager.DropGenericTypeArguments (check_type);
865 if (check_type == tb)
868 if (TypeBuilder == null)
869 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
870 // However, this is invoked again later -- so safe to return true.
871 // May also be null when resolving top-level attributes.
875 // Broken Microsoft runtime, return public for arrays, no matter what
876 // the accessibility is for their underlying class, and they return
877 // NonPublic visibility for pointers
879 if (check_type.IsArray || check_type.IsPointer)
880 return CheckAccessLevel (TypeManager.GetElementType (check_type));
882 if (TypeManager.IsGenericParameter(check_type))
883 return true; // FIXME
885 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
888 case TypeAttributes.Public:
891 case TypeAttributes.NotPublic:
893 if (TypeBuilder == null)
894 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
895 // However, this is invoked again later -- so safe to return true.
896 // May also be null when resolving top-level attributes.
899 // This test should probably use the declaringtype.
901 return check_type.Assembly == TypeBuilder.Assembly ||
902 TypeManager.IsFriendAssembly (check_type.Assembly);
904 case TypeAttributes.NestedPublic:
907 case TypeAttributes.NestedPrivate:
908 return NestedAccessible (tb, check_type);
910 case TypeAttributes.NestedFamily:
912 // Only accessible to methods in current type or any subtypes
914 return FamilyAccessible (tb, check_type);
916 case TypeAttributes.NestedFamANDAssem:
917 return ((check_type.Assembly == tb.Assembly) ||
918 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
919 FamilyAccessible (tb, check_type);
921 case TypeAttributes.NestedFamORAssem:
922 return (check_type.Assembly == tb.Assembly) ||
923 FamilyAccessible (tb, check_type) ||
924 TypeManager.IsFriendAssembly (check_type.Assembly);
926 case TypeAttributes.NestedAssembly:
927 return check_type.Assembly == tb.Assembly ||
928 TypeManager.IsFriendAssembly (check_type.Assembly);
931 Console.WriteLine ("HERE: " + check_attr);
936 protected bool NestedAccessible (Type tb, Type check_type)
938 Type declaring = check_type.DeclaringType;
939 return TypeBuilder == declaring ||
940 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
943 protected bool FamilyAccessible (Type tb, Type check_type)
945 Type declaring = check_type.DeclaringType;
946 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
949 // Access level of a type.
951 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
952 // Public Assembly Protected
953 Protected = (0 << 0) | (0 << 1) | (X << 2),
954 Public = (X << 0) | (X << 1) | (X << 2),
955 Private = (0 << 0) | (0 << 1) | (0 << 2),
956 Internal = (0 << 0) | (X << 1) | (0 << 2),
957 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
960 static AccessLevel GetAccessLevelFromModifiers (int flags)
962 if ((flags & Modifiers.INTERNAL) != 0) {
964 if ((flags & Modifiers.PROTECTED) != 0)
965 return AccessLevel.ProtectedOrInternal;
967 return AccessLevel.Internal;
969 } else if ((flags & Modifiers.PROTECTED) != 0)
970 return AccessLevel.Protected;
971 else if ((flags & Modifiers.PRIVATE) != 0)
972 return AccessLevel.Private;
974 return AccessLevel.Public;
977 // What is the effective access level of this?
979 AccessLevel EffectiveAccessLevel {
981 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
982 if (!IsTopLevel && (Parent != null))
983 return myAccess & Parent.EffectiveAccessLevel;
988 // Return the access level for type `t'
989 static AccessLevel TypeEffectiveAccessLevel (Type t)
992 return AccessLevel.Public;
993 if (t.IsNestedPrivate)
994 return AccessLevel.Private;
996 return AccessLevel.Internal;
998 // By now, it must be nested
999 AccessLevel parent_level = TypeEffectiveAccessLevel (t.DeclaringType);
1001 if (t.IsNestedPublic)
1002 return parent_level;
1003 if (t.IsNestedAssembly)
1004 return parent_level & AccessLevel.Internal;
1005 if (t.IsNestedFamily)
1006 return parent_level & AccessLevel.Protected;
1007 if (t.IsNestedFamORAssem)
1008 return parent_level & AccessLevel.ProtectedOrInternal;
1009 if (t.IsNestedFamANDAssem)
1010 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1012 // nested private is taken care of
1014 throw new Exception ("I give up, what are you?");
1018 // This answers `is the type P, as accessible as a member M which has the
1019 // accessability @flags which is declared as a nested member of the type T, this declspace'
1021 public bool AsAccessible (Type p, int flags)
1024 // 1) if M is private, its accessability is the same as this declspace.
1025 // we already know that P is accessible to T before this method, so we
1029 if ((flags & Modifiers.PRIVATE) != 0)
1032 while (p.IsArray || p.IsPointer || p.IsByRef)
1033 p = TypeManager.GetElementType (p);
1036 if (p.IsGenericParameter)
1039 if (TypeManager.IsGenericType (p)) {
1040 foreach (Type t in p.GetGenericArguments ()) {
1041 if (!AsAccessible (t, flags))
1046 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1047 AccessLevel mAccess = this.EffectiveAccessLevel &
1048 GetAccessLevelFromModifiers (flags);
1050 // for every place from which we can access M, we must
1051 // be able to access P as well. So, we want
1052 // For every bit in M and P, M_i -> P_1 == true
1053 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1055 return ~ (~ mAccess | pAccess) == 0;
1058 private Type LookupNestedTypeInHierarchy (string name)
1060 // if the member cache has been created, lets use it.
1061 // the member cache is MUCH faster.
1062 if (MemberCache != null)
1063 return MemberCache.FindNestedType (name);
1065 // no member cache. Do it the hard way -- reflection
1067 for (Type current_type = TypeBuilder;
1068 current_type != null && current_type != TypeManager.object_type;
1069 current_type = current_type.BaseType) {
1071 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1072 if (ct is TypeBuilder) {
1073 TypeContainer tc = ct == TypeBuilder
1074 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1076 t = tc.FindNestedType (name);
1078 t = TypeManager.GetNestedType (ct, name);
1081 if ((t == null) || !CheckAccessLevel (t))
1085 if (!TypeManager.IsGenericType (current_type))
1088 Type[] args = TypeManager.GetTypeArguments (current_type);
1089 Type[] targs = TypeManager.GetTypeArguments (t);
1090 for (int i = 0; i < args.Length; i++)
1091 targs [i] = args [i];
1093 t = t.MakeGenericType (targs);
1102 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1108 // Public function used to locate types.
1110 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1112 // Returns: Type or null if they type can not be found.
1114 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1116 if (Cache.Contains (name))
1117 return (FullNamedExpression) Cache [name];
1119 FullNamedExpression e;
1120 Type t = LookupNestedTypeInHierarchy (name);
1122 e = new TypeExpression (t, Location.Null);
1123 else if (Parent != null)
1124 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1126 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1133 /// This function is broken and not what you're looking for. It should only
1134 /// be used while the type is still being created since it doesn't use the cache
1135 /// and relies on the filter doing the member name check.
1137 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1138 MemberFilter filter, object criteria);
1141 /// If we have a MemberCache, return it. This property may return null if the
1142 /// class doesn't have a member cache or while it's still being created.
1144 public abstract MemberCache MemberCache {
1148 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1150 if (a.Type == TypeManager.required_attr_type) {
1151 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1154 TypeBuilder.SetCustomAttribute (cb);
1158 // Extensions for generics
1160 TypeParameter[] type_params;
1161 TypeParameter[] type_param_list;
1163 protected string GetInstantiationName ()
1165 StringBuilder sb = new StringBuilder (Name);
1167 for (int i = 0; i < type_param_list.Length; i++) {
1170 sb.Append (type_param_list [i].Name);
1173 return sb.ToString ();
1176 bool check_type_parameter (ArrayList list, int start, string name)
1178 for (int i = 0; i < start; i++) {
1179 TypeParameter param = (TypeParameter) list [i];
1181 if (param.Name != name)
1184 Report.SymbolRelatedToPreviousError (Parent);
1185 // TODO: Location is wrong (parent instead of child)
1186 Report.Warning (693, 3, Location,
1187 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1188 name, Parent.GetSignatureForError ());
1196 TypeParameter[] initialize_type_params ()
1198 if (type_param_list != null)
1199 return type_param_list;
1201 DeclSpace the_parent = Parent;
1202 if (this is GenericMethod)
1206 ArrayList list = new ArrayList ();
1207 if (the_parent != null && the_parent.IsGeneric) {
1208 // FIXME: move generics info out of DeclSpace
1209 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1210 start = parent_params.Length;
1211 list.AddRange (parent_params);
1214 int count = type_params != null ? type_params.Length : 0;
1215 for (int i = 0; i < count; i++) {
1216 TypeParameter param = type_params [i];
1217 check_type_parameter (list, start, param.Name);
1221 type_param_list = new TypeParameter [list.Count];
1222 list.CopyTo (type_param_list, 0);
1223 return type_param_list;
1226 public virtual void SetParameterInfo (ArrayList constraints_list)
1229 if (constraints_list != null) {
1231 80, Location, "Constraints are not allowed " +
1232 "on non-generic declarations");
1238 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1239 type_params = new TypeParameter [names.Length];
1242 // Register all the names
1244 for (int i = 0; i < type_params.Length; i++) {
1245 TypeParameterName name = names [i];
1247 Constraints constraints = null;
1248 if (constraints_list != null) {
1249 int total = constraints_list.Count;
1250 for (int ii = 0; ii < total; ++ii) {
1251 Constraints constraints_at = (Constraints)constraints_list[ii];
1252 // TODO: it is used by iterators only
1253 if (constraints_at == null) {
1254 constraints_list.RemoveAt (ii);
1258 if (constraints_at.TypeParameter == name.Name) {
1259 constraints = constraints_at;
1260 constraints_list.RemoveAt(ii);
1266 type_params [i] = new TypeParameter (
1267 Parent, this, name.Name, constraints, name.OptAttributes,
1270 AddToContainer (type_params [i], name.Name);
1273 if (constraints_list != null && constraints_list.Count > 0) {
1274 foreach (Constraints constraint in constraints_list) {
1275 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1276 GetSignatureForError (), constraint.TypeParameter);
1281 public TypeParameter[] TypeParameters {
1284 throw new InvalidOperationException ();
1285 if ((PartialContainer != null) && (PartialContainer != this))
1286 return PartialContainer.TypeParameters;
1287 if (type_param_list == null)
1288 initialize_type_params ();
1290 return type_param_list;
1294 public TypeParameter[] CurrentTypeParameters {
1297 throw new InvalidOperationException ();
1298 if ((PartialContainer != null) && (PartialContainer != this))
1299 return PartialContainer.CurrentTypeParameters;
1300 if (type_params != null)
1303 return new TypeParameter [0];
1307 public int CountTypeParameters {
1309 return count_type_params;
1313 public int CountCurrentTypeParameters {
1315 return count_current_type_params;
1319 public TypeParameterExpr LookupGeneric (string name, Location loc)
1324 TypeParameter [] current_params;
1325 if (this is TypeContainer)
1326 current_params = PartialContainer.CurrentTypeParameters;
1328 current_params = CurrentTypeParameters;
1330 foreach (TypeParameter type_param in current_params) {
1331 if (type_param.Name == name)
1332 return new TypeParameterExpr (type_param, loc);
1336 return Parent.LookupGeneric (name, loc);
1341 // Used for error reporting only
1342 public virtual Type LookupAnyGeneric (string typeName)
1344 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1347 public override string[] ValidAttributeTargets {
1348 get { return attribute_targets; }
1351 protected override bool VerifyClsCompliance ()
1353 if (!base.VerifyClsCompliance ()) {
1357 if (type_params != null) {
1358 foreach (TypeParameter tp in type_params) {
1359 if (tp.Constraints == null)
1362 tp.Constraints.VerifyClsCompliance ();
1366 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1370 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1371 if (!cache.Contains (lcase)) {
1372 cache.Add (lcase, this);
1376 object val = cache [lcase];
1378 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1381 Report.SymbolRelatedToPreviousError (t);
1384 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1387 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1389 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1396 /// This is a readonly list of MemberInfo's.
1398 public class MemberList : IList {
1399 public readonly IList List;
1403 /// Create a new MemberList from the given IList.
1405 public MemberList (IList list)
1410 this.List = new ArrayList ();
1415 /// Concatenate the ILists `first' and `second' to a new MemberList.
1417 public MemberList (IList first, IList second)
1419 ArrayList list = new ArrayList ();
1420 list.AddRange (first);
1421 list.AddRange (second);
1426 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1429 /// Cast the MemberList into a MemberInfo[] array.
1432 /// This is an expensive operation, only use it if it's really necessary.
1434 public static explicit operator MemberInfo [] (MemberList list)
1436 Timer.StartTimer (TimerType.MiscTimer);
1437 MemberInfo [] result = new MemberInfo [list.Count];
1438 list.CopyTo (result, 0);
1439 Timer.StopTimer (TimerType.MiscTimer);
1451 public bool IsSynchronized {
1453 return List.IsSynchronized;
1457 public object SyncRoot {
1459 return List.SyncRoot;
1463 public void CopyTo (Array array, int index)
1465 List.CopyTo (array, index);
1470 public IEnumerator GetEnumerator ()
1472 return List.GetEnumerator ();
1477 public bool IsFixedSize {
1483 public bool IsReadOnly {
1489 object IList.this [int index] {
1491 return List [index];
1495 throw new NotSupportedException ();
1499 // FIXME: try to find out whether we can avoid the cast in this indexer.
1500 public MemberInfo this [int index] {
1502 return (MemberInfo) List [index];
1506 public int Add (object value)
1508 throw new NotSupportedException ();
1511 public void Clear ()
1513 throw new NotSupportedException ();
1516 public bool Contains (object value)
1518 return List.Contains (value);
1521 public int IndexOf (object value)
1523 return List.IndexOf (value);
1526 public void Insert (int index, object value)
1528 throw new NotSupportedException ();
1531 public void Remove (object value)
1533 throw new NotSupportedException ();
1536 public void RemoveAt (int index)
1538 throw new NotSupportedException ();
1543 /// This interface is used to get all members of a class when creating the
1544 /// member cache. It must be implemented by all DeclSpace derivatives which
1545 /// want to support the member cache and by TypeHandle to get caching of
1546 /// non-dynamic types.
1548 public interface IMemberContainer {
1550 /// The name of the IMemberContainer. This is only used for
1551 /// debugging purposes.
1558 /// The type of this IMemberContainer.
1565 /// Returns the IMemberContainer of the base class or null if this
1566 /// is an interface or TypeManger.object_type.
1567 /// This is used when creating the member cache for a class to get all
1568 /// members from the base class.
1570 MemberCache BaseCache {
1575 /// Whether this is an interface.
1582 /// Returns all members of this class with the corresponding MemberTypes
1583 /// and BindingFlags.
1586 /// When implementing this method, make sure not to return any inherited
1587 /// members and check the MemberTypes and BindingFlags properly.
1588 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1589 /// get the BindingFlags (static/non-static,public/non-public) in the
1590 /// MemberInfo class, but the cache needs this information. That's why
1591 /// this method is called multiple times with different BindingFlags.
1593 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1596 /// Return the container's member cache.
1598 MemberCache MemberCache {
1604 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1605 /// member lookups. It has a member name based hash table; it maps each member
1606 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1607 /// and the BindingFlags that were initially used to get it. The cache contains
1608 /// all members of the current class and all inherited members. If this cache is
1609 /// for an interface types, it also contains all inherited members.
1611 /// There are two ways to get a MemberCache:
1612 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1613 /// use the DeclSpace.MemberCache property.
1614 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1615 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1617 public class MemberCache {
1618 public readonly IMemberContainer Container;
1619 protected Hashtable member_hash;
1620 protected Hashtable method_hash;
1623 /// Create a new MemberCache for the given IMemberContainer `container'.
1625 public MemberCache (IMemberContainer container)
1627 this.Container = container;
1629 Timer.IncrementCounter (CounterType.MemberCache);
1630 Timer.StartTimer (TimerType.CacheInit);
1632 // If we have a base class (we have a base class unless we're
1633 // TypeManager.object_type), we deep-copy its MemberCache here.
1634 if (Container.BaseCache != null)
1635 member_hash = SetupCache (Container.BaseCache);
1637 member_hash = new Hashtable ();
1639 // If this is neither a dynamic type nor an interface, create a special
1640 // method cache with all declared and inherited methods.
1641 Type type = container.Type;
1642 if (!(type is TypeBuilder) && !type.IsInterface &&
1643 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1644 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1645 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1646 method_hash = new Hashtable ();
1650 // Add all members from the current class.
1651 AddMembers (Container);
1653 Timer.StopTimer (TimerType.CacheInit);
1656 public MemberCache (Type[] ifaces)
1659 // The members of this cache all belong to other caches.
1660 // So, 'Container' will not be used.
1662 this.Container = null;
1664 member_hash = new Hashtable ();
1668 foreach (Type itype in ifaces)
1669 AddCacheContents (TypeManager.LookupMemberCache (itype));
1672 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1674 this.Container = container;
1676 // If we have a base class (we have a base class unless we're
1677 // TypeManager.object_type), we deep-copy its MemberCache here.
1678 if (Container.BaseCache != null)
1679 member_hash = SetupCache (Container.BaseCache);
1681 member_hash = new Hashtable ();
1683 if (base_class != null)
1684 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1685 if (ifaces != null) {
1686 foreach (Type itype in ifaces) {
1687 MemberCache cache = TypeManager.LookupMemberCache (itype);
1689 AddCacheContents (cache);
1695 /// Bootstrap this member cache by doing a deep-copy of our base.
1697 static Hashtable SetupCache (MemberCache base_class)
1699 Hashtable hash = new Hashtable ();
1701 if (base_class == null)
1704 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1705 while (it.MoveNext ()) {
1706 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1713 /// Add the contents of `cache' to the member_hash.
1715 void AddCacheContents (MemberCache cache)
1717 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1718 while (it.MoveNext ()) {
1719 ArrayList list = (ArrayList) member_hash [it.Key];
1721 member_hash [it.Key] = list = new ArrayList ();
1723 ArrayList entries = (ArrayList) it.Value;
1724 for (int i = entries.Count-1; i >= 0; i--) {
1725 CacheEntry entry = (CacheEntry) entries [i];
1727 if (entry.Container != cache.Container)
1735 /// Add all members from class `container' to the cache.
1737 void AddMembers (IMemberContainer container)
1739 // We need to call AddMembers() with a single member type at a time
1740 // to get the member type part of CacheEntry.EntryType right.
1741 if (!container.IsInterface) {
1742 AddMembers (MemberTypes.Constructor, container);
1743 AddMembers (MemberTypes.Field, container);
1745 AddMembers (MemberTypes.Method, container);
1746 AddMembers (MemberTypes.Property, container);
1747 AddMembers (MemberTypes.Event, container);
1748 // Nested types are returned by both Static and Instance searches.
1749 AddMembers (MemberTypes.NestedType,
1750 BindingFlags.Static | BindingFlags.Public, container);
1751 AddMembers (MemberTypes.NestedType,
1752 BindingFlags.Static | BindingFlags.NonPublic, container);
1755 void AddMembers (MemberTypes mt, IMemberContainer container)
1757 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1758 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1759 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1760 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1763 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1764 string name, MemberInfo member)
1766 // We use a name-based hash table of ArrayList's.
1767 ArrayList list = (ArrayList) member_hash [name];
1769 list = new ArrayList ();
1770 member_hash.Add (name, list);
1773 // When this method is called for the current class, the list will
1774 // already contain all inherited members from our base classes.
1775 // We cannot add new members in front of the list since this'd be an
1776 // expensive operation, that's why the list is sorted in reverse order
1777 // (ie. members from the current class are coming last).
1778 list.Add (new CacheEntry (container, member, mt, bf));
1782 /// Add all members from class `container' with the requested MemberTypes and
1783 /// BindingFlags to the cache. This method is called multiple times with different
1784 /// MemberTypes and BindingFlags.
1786 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1788 MemberList members = container.GetMembers (mt, bf);
1790 foreach (MemberInfo member in members) {
1791 string name = member.Name;
1793 AddMember (mt, bf, container, name, member);
1795 if (member is MethodInfo) {
1796 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1798 AddMember (mt, bf, container, gname, member);
1804 /// Add all declared and inherited methods from class `type' to the method cache.
1806 void AddMethods (Type type)
1808 AddMethods (BindingFlags.Static | BindingFlags.Public |
1809 BindingFlags.FlattenHierarchy, type);
1810 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1811 BindingFlags.FlattenHierarchy, type);
1812 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1813 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1816 static ArrayList overrides = new ArrayList ();
1818 void AddMethods (BindingFlags bf, Type type)
1820 MethodBase [] members = type.GetMethods (bf);
1822 Array.Reverse (members);
1824 foreach (MethodBase member in members) {
1825 string name = member.Name;
1827 // We use a name-based hash table of ArrayList's.
1828 ArrayList list = (ArrayList) method_hash [name];
1830 list = new ArrayList ();
1831 method_hash.Add (name, list);
1834 MethodInfo curr = (MethodInfo) member;
1835 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1836 MethodInfo base_method = curr.GetBaseDefinition ();
1838 if (base_method == curr)
1839 // Not every virtual function needs to have a NewSlot flag.
1842 overrides.Add (curr);
1843 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1847 if (overrides.Count > 0) {
1848 for (int i = 0; i < overrides.Count; ++i)
1849 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1853 // Unfortunately, the elements returned by Type.GetMethods() aren't
1854 // sorted so we need to do this check for every member.
1855 BindingFlags new_bf = bf;
1856 if (member.DeclaringType == type)
1857 new_bf |= BindingFlags.DeclaredOnly;
1859 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1864 /// Compute and return a appropriate `EntryType' magic number for the given
1865 /// MemberTypes and BindingFlags.
1867 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1869 EntryType type = EntryType.None;
1871 if ((mt & MemberTypes.Constructor) != 0)
1872 type |= EntryType.Constructor;
1873 if ((mt & MemberTypes.Event) != 0)
1874 type |= EntryType.Event;
1875 if ((mt & MemberTypes.Field) != 0)
1876 type |= EntryType.Field;
1877 if ((mt & MemberTypes.Method) != 0)
1878 type |= EntryType.Method;
1879 if ((mt & MemberTypes.Property) != 0)
1880 type |= EntryType.Property;
1881 // Nested types are returned by static and instance searches.
1882 if ((mt & MemberTypes.NestedType) != 0)
1883 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1885 if ((bf & BindingFlags.Instance) != 0)
1886 type |= EntryType.Instance;
1887 if ((bf & BindingFlags.Static) != 0)
1888 type |= EntryType.Static;
1889 if ((bf & BindingFlags.Public) != 0)
1890 type |= EntryType.Public;
1891 if ((bf & BindingFlags.NonPublic) != 0)
1892 type |= EntryType.NonPublic;
1893 if ((bf & BindingFlags.DeclaredOnly) != 0)
1894 type |= EntryType.Declared;
1900 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1901 /// denote multiple member types. Returns true if the given flags value denotes a
1902 /// single member types.
1904 public static bool IsSingleMemberType (MemberTypes mt)
1907 case MemberTypes.Constructor:
1908 case MemberTypes.Event:
1909 case MemberTypes.Field:
1910 case MemberTypes.Method:
1911 case MemberTypes.Property:
1912 case MemberTypes.NestedType:
1921 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1922 /// number to speed up the searching process.
1925 protected enum EntryType {
1930 MaskStatic = Instance|Static,
1934 MaskProtection = Public|NonPublic,
1938 Constructor = 0x020,
1945 NotExtensionMethod = 0x800,
1947 MaskType = Constructor|Event|Field|Method|Property|NestedType
1950 protected class CacheEntry {
1951 public readonly IMemberContainer Container;
1952 public EntryType EntryType;
1953 public readonly MemberInfo Member;
1955 public CacheEntry (IMemberContainer container, MemberInfo member,
1956 MemberTypes mt, BindingFlags bf)
1958 this.Container = container;
1959 this.Member = member;
1960 this.EntryType = GetEntryType (mt, bf);
1963 public override string ToString ()
1965 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1971 /// This is called each time we're walking up one level in the class hierarchy
1972 /// and checks whether we can abort the search since we've already found what
1973 /// we were looking for.
1975 protected bool DoneSearching (ArrayList list)
1978 // We've found exactly one member in the current class and it's not
1979 // a method or constructor.
1981 if (list.Count == 1 && !(list [0] is MethodBase))
1985 // Multiple properties: we query those just to find out the indexer
1988 if ((list.Count > 0) && (list [0] is PropertyInfo))
1995 /// Looks up members with name `name'. If you provide an optional
1996 /// filter function, it'll only be called with members matching the
1997 /// requested member name.
1999 /// This method will try to use the cache to do the lookup if possible.
2001 /// Unlike other FindMembers implementations, this method will always
2002 /// check all inherited members - even when called on an interface type.
2004 /// If you know that you're only looking for methods, you should use
2005 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2006 /// When doing a method-only search, it'll try to use a special method
2007 /// cache (unless it's a dynamic type or an interface) and the returned
2008 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2009 /// The lookup process will automatically restart itself in method-only
2010 /// search mode if it discovers that it's about to return methods.
2012 ArrayList global = new ArrayList ();
2013 bool using_global = false;
2015 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2017 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2018 MemberFilter filter, object criteria)
2021 throw new Exception ();
2023 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2024 bool method_search = mt == MemberTypes.Method;
2025 // If we have a method cache and we aren't already doing a method-only search,
2026 // then we restart a method search if the first match is a method.
2027 bool do_method_search = !method_search && (method_hash != null);
2029 ArrayList applicable;
2031 // If this is a method-only search, we try to use the method cache if
2032 // possible; a lookup in the method cache will return a MemberInfo with
2033 // the correct ReflectedType for inherited methods.
2035 if (method_search && (method_hash != null))
2036 applicable = (ArrayList) method_hash [name];
2038 applicable = (ArrayList) member_hash [name];
2040 if (applicable == null)
2041 return emptyMemberInfo;
2044 // 32 slots gives 53 rss/54 size
2045 // 2/4 slots gives 55 rss
2047 // Strange: from 25,000 calls, only 1,800
2048 // are above 2. Why does this impact it?
2051 using_global = true;
2053 Timer.StartTimer (TimerType.CachedLookup);
2055 EntryType type = GetEntryType (mt, bf);
2057 IMemberContainer current = Container;
2059 bool do_interface_search = current.IsInterface;
2061 // `applicable' is a list of all members with the given member name `name'
2062 // in the current class and all its base classes. The list is sorted in
2063 // reverse order due to the way how the cache is initialy created (to speed
2064 // things up, we're doing a deep-copy of our base).
2066 for (int i = applicable.Count-1; i >= 0; i--) {
2067 CacheEntry entry = (CacheEntry) applicable [i];
2069 // This happens each time we're walking one level up in the class
2070 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2071 // the first time this happens (this may already happen in the first
2072 // iteration of this loop if there are no members with the name we're
2073 // looking for in the current class).
2074 if (entry.Container != current) {
2078 if (!do_interface_search && DoneSearching (global))
2081 current = entry.Container;
2084 // Is the member of the correct type ?
2085 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2088 // Is the member static/non-static ?
2089 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2092 // Apply the filter to it.
2093 if (filter (entry.Member, criteria)) {
2094 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2095 do_method_search = false;
2098 // Because interfaces support multiple inheritance we have to be sure that
2099 // base member is from same interface, so only top level member will be returned
2100 if (do_interface_search && global.Count > 0) {
2101 bool member_already_exists = false;
2103 foreach (MemberInfo mi in global) {
2104 if (mi is MethodBase)
2107 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2108 member_already_exists = true;
2112 if (member_already_exists)
2116 global.Add (entry.Member);
2120 Timer.StopTimer (TimerType.CachedLookup);
2122 // If we have a method cache and we aren't already doing a method-only
2123 // search, we restart in method-only search mode if the first match is
2124 // a method. This ensures that we return a MemberInfo with the correct
2125 // ReflectedType for inherited methods.
2126 if (do_method_search && (global.Count > 0)){
2127 using_global = false;
2129 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2132 using_global = false;
2133 MemberInfo [] copy = new MemberInfo [global.Count];
2134 global.CopyTo (copy);
2139 /// Returns true if iterface exists in any base interfaces (ifaces)
2141 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2143 foreach (Type iface in ifaces) {
2144 if (iface == ifaceToFind)
2147 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2148 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2154 // find the nested type @name in @this.
2155 public Type FindNestedType (string name)
2157 ArrayList applicable = (ArrayList) member_hash [name];
2158 if (applicable == null)
2161 for (int i = applicable.Count-1; i >= 0; i--) {
2162 CacheEntry entry = (CacheEntry) applicable [i];
2163 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2164 return (Type) entry.Member;
2170 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2172 ArrayList applicable = (ArrayList) member_hash [name];
2173 if (applicable == null)
2177 // Walk the chain of events, starting from the top.
2179 for (int i = applicable.Count - 1; i >= 0; i--)
2181 CacheEntry entry = (CacheEntry) applicable [i];
2182 if ((entry.EntryType & EntryType.Event) == 0)
2185 EventInfo ei = (EventInfo)entry.Member;
2186 return ei.GetAddMethod (true);
2193 // Looks for extension methods with defined name and extension type
2195 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2198 if (method_hash != null)
2199 entries = (ArrayList)method_hash [name];
2201 entries = (ArrayList)member_hash [name];
2203 if (entries == null)
2206 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2208 entry_type |= EntryType.Public;
2210 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2212 ArrayList candidates = null;
2213 foreach (CacheEntry entry in entries) {
2214 if ((entry.EntryType & entry_type) == found_entry_type) {
2215 MethodBase mb = (MethodBase)entry.Member;
2217 IMethodData md = TypeManager.GetMethod (mb);
2218 ParameterData pd = md == null ?
2219 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2221 Type ex_type = pd.ExtensionMethodType;
2222 if (ex_type == null) {
2223 entry.EntryType |= EntryType.NotExtensionMethod;
2227 //if (implicit conversion between ex_type and extensionType exist) {
2228 if (candidates == null)
2229 candidates = new ArrayList (2);
2230 candidates.Add (mb);
2239 // This finds the method or property for us to override. invocation_type is the type where
2240 // the override is going to be declared, name is the name of the method/property, and
2241 // param_types is the parameters, if any to the method or property
2243 // Because the MemberCache holds members from this class and all the base classes,
2244 // we can avoid tons of reflection stuff.
2246 public MemberInfo FindMemberToOverride (Type invocation_type, string name, Type [] param_types, GenericMethod generic_method, bool is_property)
2248 ArrayList applicable;
2249 if (method_hash != null && !is_property)
2250 applicable = (ArrayList) method_hash [name];
2252 applicable = (ArrayList) member_hash [name];
2254 if (applicable == null)
2257 // Walk the chain of methods, starting from the top.
2259 for (int i = applicable.Count - 1; i >= 0; i--) {
2260 CacheEntry entry = (CacheEntry) applicable [i];
2262 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2265 PropertyInfo pi = null;
2266 MethodInfo mi = null;
2267 FieldInfo fi = null;
2268 Type [] cmp_attrs = null;
2271 if ((entry.EntryType & EntryType.Field) != 0) {
2272 fi = (FieldInfo)entry.Member;
2274 // TODO: For this case we ignore member type
2275 //fb = TypeManager.GetField (fi);
2276 //cmp_attrs = new Type[] { fb.MemberType };
2278 pi = (PropertyInfo) entry.Member;
2279 cmp_attrs = TypeManager.GetArgumentTypes (pi);
2282 mi = (MethodInfo) entry.Member;
2283 cmp_attrs = TypeManager.GetParameterData (mi).Types;
2287 // TODO: Almost duplicate !
2289 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2290 case FieldAttributes.PrivateScope:
2292 case FieldAttributes.Private:
2294 // A private method is Ok if we are a nested subtype.
2295 // The spec actually is not very clear about this, see bug 52458.
2297 if (!invocation_type.Equals (entry.Container.Type) &&
2298 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2301 case FieldAttributes.FamANDAssem:
2302 case FieldAttributes.Assembly:
2304 // Check for assembly methods
2306 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2310 return entry.Member;
2314 // Check the arguments
2316 if (cmp_attrs.Length != param_types.Length)
2320 for (j = 0; j < cmp_attrs.Length; ++j)
2321 if (!TypeManager.IsEqual (param_types [j], cmp_attrs [j]))
2323 if (j < cmp_attrs.Length)
2327 // check generic arguments for methods
2330 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2331 if (generic_method == null && cmpGenArgs.Length != 0)
2333 if (generic_method != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2338 // get one of the methods because this has the visibility info.
2341 mi = pi.GetGetMethod (true);
2343 mi = pi.GetSetMethod (true);
2349 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2350 case MethodAttributes.PrivateScope:
2352 case MethodAttributes.Private:
2354 // A private method is Ok if we are a nested subtype.
2355 // The spec actually is not very clear about this, see bug 52458.
2357 if (!invocation_type.Equals (entry.Container.Type) &&
2358 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2361 case MethodAttributes.FamANDAssem:
2362 case MethodAttributes.Assembly:
2364 // Check for assembly methods
2366 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2370 return entry.Member;
2377 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2378 /// We handle two cases. The first is for types without parameters (events, field, properties).
2379 /// The second are methods, indexers and this is why ignore_complex_types is here.
2380 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2382 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2384 ArrayList applicable = null;
2386 if (method_hash != null)
2387 applicable = (ArrayList) method_hash [name];
2389 if (applicable != null) {
2390 for (int i = applicable.Count - 1; i >= 0; i--) {
2391 CacheEntry entry = (CacheEntry) applicable [i];
2392 if ((entry.EntryType & EntryType.Public) != 0)
2393 return entry.Member;
2397 if (member_hash == null)
2399 applicable = (ArrayList) member_hash [name];
2401 if (applicable != null) {
2402 for (int i = applicable.Count - 1; i >= 0; i--) {
2403 CacheEntry entry = (CacheEntry) applicable [i];
2404 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2405 if (ignore_complex_types) {
2406 if ((entry.EntryType & EntryType.Method) != 0)
2409 // Does exist easier way how to detect indexer ?
2410 if ((entry.EntryType & EntryType.Property) != 0) {
2411 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2412 if (arg_types.Length > 0)
2416 return entry.Member;
2423 Hashtable locase_table;
2426 /// Builds low-case table for CLS Compliance test
2428 public Hashtable GetPublicMembers ()
2430 if (locase_table != null)
2431 return locase_table;
2433 locase_table = new Hashtable ();
2434 foreach (DictionaryEntry entry in member_hash) {
2435 ArrayList members = (ArrayList)entry.Value;
2436 for (int ii = 0; ii < members.Count; ++ii) {
2437 CacheEntry member_entry = (CacheEntry) members [ii];
2439 if ((member_entry.EntryType & EntryType.Public) == 0)
2442 // TODO: Does anyone know easier way how to detect that member is internal ?
2443 switch (member_entry.EntryType & EntryType.MaskType) {
2444 case EntryType.Constructor:
2447 case EntryType.Field:
2448 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2452 case EntryType.Method:
2453 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2457 case EntryType.Property:
2458 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2459 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2463 case EntryType.Event:
2464 EventInfo ei = (EventInfo)member_entry.Member;
2465 MethodInfo mi = ei.GetAddMethod ();
2466 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2470 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2471 locase_table [lcase] = member_entry.Member;
2475 return locase_table;
2478 public Hashtable Members {
2485 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2488 // TODO: refactor as method is always 'this'
2489 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2491 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2493 for (int i = 0; i < al.Count; ++i) {
2494 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2497 if (entry.Member == this_builder)
2500 if ((entry.EntryType & tested_type) != tested_type)
2503 MethodBase method_to_compare = (MethodBase)entry.Member;
2504 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2505 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2507 if (result == AttributeTester.Result.Ok)
2510 IMethodData md = TypeManager.GetMethod (method_to_compare);
2512 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2513 // However it is exactly what csc does.
2514 if (md != null && !md.IsClsComplianceRequired ())
2517 Report.SymbolRelatedToPreviousError (entry.Member);
2519 case AttributeTester.Result.RefOutArrayError:
2520 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2522 case AttributeTester.Result.ArrayArrayError:
2523 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2527 throw new NotImplementedException (result.ToString ());