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)
241 return TypeArguments.Count;
242 else if (Left != null)
243 return Left.CountTypeArguments;
249 public static string MakeName (string name, TypeArguments args)
254 return name + "`" + args.Count;
257 public static string MakeName (string name, int count)
259 return name + "`" + count;
264 /// Base representation for members. This is used to keep track
265 /// of Name, Location and Modifier flags, and handling Attributes.
267 public abstract class MemberCore : Attributable, IResolveContext {
272 protected string cached_name;
275 if (cached_name == null)
276 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
281 // Is not readonly because of IndexerName attribute
282 private MemberName member_name;
283 public MemberName MemberName {
284 get { return member_name; }
288 /// Modifier flags that the user specified in the source code
290 private int mod_flags;
291 public int ModFlags {
294 if ((value & Modifiers.COMPILER_GENERATED) != 0)
295 caching_flags = Flags.IsUsed | Flags.IsAssigned;
302 public readonly DeclSpace Parent;
305 /// Location where this declaration happens
307 public Location Location {
308 get { return member_name.Location; }
312 /// XML documentation comment
314 protected string comment;
317 /// Represents header string for documentation comment
318 /// for each member types.
320 public abstract string DocCommentHeader { get; }
324 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
325 Obsolete = 1 << 1, // Type has obsolete attribute
326 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
327 ClsCompliant = 1 << 3, // Type is CLS Compliant
328 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
329 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
330 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
331 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
332 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
333 Excluded = 1 << 9, // Method is conditional
334 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
336 IsAssigned = 1 << 12, // Field is assigned
337 HasExplicitLayout = 1 << 13
341 /// MemberCore flags at first detected then cached
343 internal Flags caching_flags;
345 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
348 this.Parent = parent;
350 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
353 protected virtual void SetMemberName (MemberName new_name)
355 member_name = new_name;
359 protected bool CheckAbstractAndExtern (bool has_block)
361 if (Parent.PartialContainer.Kind == Kind.Interface)
365 if ((ModFlags & Modifiers.EXTERN) != 0) {
366 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
367 GetSignatureForError ());
371 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
372 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
373 GetSignatureForError ());
377 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
378 if (RootContext.Version >= LanguageVersion.LINQ && this is Property.PropertyMethod) {
379 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",
380 GetSignatureForError ());
382 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract or extern",
383 GetSignatureForError ());
392 public abstract bool Define ();
394 public virtual string DocComment {
404 // Returns full member name for error message
406 public virtual string GetSignatureForError ()
408 if (Parent == null || Parent.Parent == null)
409 return member_name.ToString ();
411 return String.Concat (Parent.GetSignatureForError (), '.', member_name.ToString ());
415 /// Base Emit method. This is also entry point for CLS-Compliant verification.
417 public virtual void Emit ()
419 if (!RootContext.VerifyClsCompliance)
422 VerifyClsCompliance ();
425 public virtual bool IsUsed {
426 get { return (caching_flags & Flags.IsUsed) != 0; }
429 public void SetMemberIsUsed ()
431 caching_flags |= Flags.IsUsed;
435 /// Returns instance of ObsoleteAttribute for this MemberCore
437 public virtual ObsoleteAttribute GetObsoleteAttribute ()
439 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
440 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
444 caching_flags &= ~Flags.Obsolete_Undetected;
446 if (OptAttributes == null)
449 Attribute obsolete_attr = OptAttributes.Search (
450 TypeManager.obsolete_attribute_type);
451 if (obsolete_attr == null)
454 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
455 if (obsolete == null)
458 caching_flags |= Flags.Obsolete;
463 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
465 public virtual void CheckObsoleteness (Location loc)
468 Parent.CheckObsoleteness (loc);
470 ObsoleteAttribute oa = GetObsoleteAttribute ();
475 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
479 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
481 public override bool IsClsComplianceRequired ()
483 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
484 return (caching_flags & Flags.ClsCompliant) != 0;
486 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
487 caching_flags &= ~Flags.ClsCompliance_Undetected;
488 caching_flags |= Flags.ClsCompliant;
492 caching_flags &= ~Flags.ClsCompliance_Undetected;
497 /// Returns true when MemberCore is exposed from assembly.
499 public bool IsExposedFromAssembly ()
501 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
504 DeclSpace parentContainer = Parent;
505 while (parentContainer != null && parentContainer.ModFlags != 0) {
506 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
508 parentContainer = parentContainer.Parent;
514 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
515 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
517 public virtual bool GetClsCompliantAttributeValue ()
519 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
520 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
522 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
524 if (OptAttributes != null) {
525 Attribute cls_attribute = OptAttributes.Search (
526 TypeManager.cls_compliant_attribute_type);
527 if (cls_attribute != null) {
528 caching_flags |= Flags.HasClsCompliantAttribute;
529 bool value = cls_attribute.GetClsCompliantAttributeValue ();
531 caching_flags |= Flags.ClsCompliantAttributeTrue;
536 if (Parent.GetClsCompliantAttributeValue ()) {
537 caching_flags |= Flags.ClsCompliantAttributeTrue;
544 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
546 protected bool HasClsCompliantAttribute {
548 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
553 /// It helps to handle error 102 & 111 detection
555 public virtual bool MarkForDuplicationCheck ()
561 /// The main virtual method for CLS-Compliant verifications.
562 /// The method returns true if member is CLS-Compliant and false if member is not
563 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
564 /// and add their extra verifications.
566 protected virtual bool VerifyClsCompliance ()
568 if (!IsClsComplianceRequired ()) {
569 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
570 if (!IsExposedFromAssembly ())
571 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
572 if (!CodeGen.Assembly.IsClsCompliant)
573 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
578 if (HasClsCompliantAttribute) {
579 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
580 Report.Error (3014, Location,
581 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
582 GetSignatureForError ());
586 if (!Parent.IsClsComplianceRequired ()) {
587 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
588 GetSignatureForError (), Parent.GetSignatureForError ());
593 if (member_name.Name [0] == '_') {
594 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
600 // Raised (and passed an XmlElement that contains the comment)
601 // when GenerateDocComment is writing documentation expectedly.
603 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
608 // Returns a string that represents the signature for this
609 // member which should be used in XML documentation.
611 public virtual string GetDocCommentName (DeclSpace ds)
613 if (ds == null || this is DeclSpace)
614 return DocCommentHeader + Name;
616 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
620 // Generates xml doc comments (if any), and if required,
621 // handle warning report.
623 internal virtual void GenerateDocComment (DeclSpace ds)
625 DocUtil.GenerateDocComment (this, ds);
628 public override IResolveContext ResolveContext {
632 #region IResolveContext Members
634 public DeclSpace DeclContainer {
635 get { return Parent; }
638 public virtual DeclSpace GenericDeclContainer {
639 get { return DeclContainer; }
642 public bool IsInObsoleteScope {
644 if (GetObsoleteAttribute () != null)
647 return Parent == null ? false : Parent.IsInObsoleteScope;
651 public bool IsInUnsafeScope {
653 if ((ModFlags & Modifiers.UNSAFE) != 0)
656 return Parent == null ? false : Parent.IsInUnsafeScope;
664 /// Base class for structs, classes, enumerations and interfaces.
667 /// They all create new declaration spaces. This
668 /// provides the common foundation for managing those name
671 public abstract class DeclSpace : MemberCore {
673 /// This points to the actual definition that is being
674 /// created with System.Reflection.Emit
676 public TypeBuilder TypeBuilder;
679 /// If we are a generic type, this is the type we are
680 /// currently defining. We need to lookup members on this
681 /// instead of the TypeBuilder.
683 public Type CurrentType;
686 // This is the namespace in which this typecontainer
687 // was declared. We use this to resolve names.
689 public NamespaceEntry NamespaceEntry;
691 private Hashtable Cache = new Hashtable ();
693 public readonly string Basename;
695 protected Hashtable defined_names;
697 public TypeContainer PartialContainer;
699 readonly bool is_generic;
700 readonly int count_type_params;
701 readonly int count_current_type_params;
704 // Whether we are Generic
706 public bool IsGeneric {
710 else if (Parent != null)
711 return Parent.IsGeneric;
717 static string[] attribute_targets = new string [] { "type" };
719 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
721 : base (parent, name, attrs)
724 Basename = name.Basename;
725 defined_names = new Hashtable ();
726 PartialContainer = null;
727 if (name.TypeArguments != null) {
729 count_type_params = count_current_type_params = name.TypeArguments.Count;
732 count_type_params += parent.count_type_params;
735 public override DeclSpace GenericDeclContainer {
740 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
742 protected virtual bool AddToContainer (MemberCore symbol, string name)
744 MemberCore mc = (MemberCore) defined_names [name];
747 defined_names.Add (name, symbol);
751 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
754 Report.SymbolRelatedToPreviousError (mc);
755 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
756 Error_MissingPartialModifier (symbol);
760 if (this is RootTypes) {
761 Report.Error (101, symbol.Location,
762 "The namespace `{0}' already contains a definition for `{1}'",
763 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
764 } else if (symbol is TypeParameter) {
765 Report.Error (692, symbol.Location,
766 "Duplicate type parameter `{0}'", name);
768 Report.Error (102, symbol.Location,
769 "The type `{0}' already contains a definition for `{1}'",
770 GetSignatureForError (), symbol.MemberName.Name);
777 /// Returns the MemberCore associated with a given name in the declaration
778 /// space. It doesn't return method based symbols !!
781 public MemberCore GetDefinition (string name)
783 return (MemberCore)defined_names [name];
786 public bool IsStaticClass {
787 get { return (ModFlags & Modifiers.STATIC) != 0; }
791 // root_types contains all the types. All TopLevel types
792 // hence have a parent that points to `root_types', that is
793 // why there is a non-obvious test down here.
795 public bool IsTopLevel {
796 get { return (Parent != null && Parent.Parent == null); }
799 public virtual void CloseType ()
801 if ((caching_flags & Flags.CloseTypeCreated) == 0){
803 TypeBuilder.CreateType ();
806 // The try/catch is needed because
807 // nested enumerations fail to load when they
810 // Even if this is the right order (enumerations
811 // declared after types).
813 // Note that this still creates the type and
814 // it is possible to save it
816 caching_flags |= Flags.CloseTypeCreated;
820 protected virtual TypeAttributes TypeAttr {
821 get { return CodeGen.Module.DefaultCharSetType; }
825 /// Should be overriten by the appropriate declaration space
827 public abstract TypeBuilder DefineType ();
830 /// Define all members, but don't apply any attributes or do anything which may
831 /// access not-yet-defined classes. This method also creates the MemberCache.
833 public virtual bool DefineMembers ()
835 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
836 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
842 protected void Error_MissingPartialModifier (MemberCore type)
844 Report.Error (260, type.Location,
845 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
846 type.GetSignatureForError ());
849 public override string GetSignatureForError ()
852 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
854 // Parent.GetSignatureForError
858 public bool CheckAccessLevel (Type check_type)
861 if (this is GenericMethod)
862 tb = Parent.TypeBuilder;
866 check_type = TypeManager.DropGenericTypeArguments (check_type);
867 if (check_type == tb)
870 if (TypeBuilder == null)
871 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
872 // However, this is invoked again later -- so safe to return true.
873 // May also be null when resolving top-level attributes.
877 // Broken Microsoft runtime, return public for arrays, no matter what
878 // the accessibility is for their underlying class, and they return
879 // NonPublic visibility for pointers
881 if (check_type.IsArray || check_type.IsPointer)
882 return CheckAccessLevel (TypeManager.GetElementType (check_type));
884 if (TypeManager.IsGenericParameter(check_type))
885 return true; // FIXME
887 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
890 case TypeAttributes.Public:
893 case TypeAttributes.NotPublic:
895 if (TypeBuilder == null)
896 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
897 // However, this is invoked again later -- so safe to return true.
898 // May also be null when resolving top-level attributes.
901 // This test should probably use the declaringtype.
903 return check_type.Assembly == TypeBuilder.Assembly ||
904 TypeManager.IsFriendAssembly (check_type.Assembly);
906 case TypeAttributes.NestedPublic:
909 case TypeAttributes.NestedPrivate:
910 return NestedAccessible (tb, check_type);
912 case TypeAttributes.NestedFamily:
914 // Only accessible to methods in current type or any subtypes
916 return FamilyAccessible (tb, check_type);
918 case TypeAttributes.NestedFamANDAssem:
919 return ((check_type.Assembly == tb.Assembly) ||
920 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
921 FamilyAccessible (tb, check_type);
923 case TypeAttributes.NestedFamORAssem:
924 return (check_type.Assembly == tb.Assembly) ||
925 FamilyAccessible (tb, check_type) ||
926 TypeManager.IsFriendAssembly (check_type.Assembly);
928 case TypeAttributes.NestedAssembly:
929 return check_type.Assembly == tb.Assembly ||
930 TypeManager.IsFriendAssembly (check_type.Assembly);
933 Console.WriteLine ("HERE: " + check_attr);
938 protected bool NestedAccessible (Type tb, Type check_type)
940 Type declaring = check_type.DeclaringType;
941 return TypeBuilder == declaring ||
942 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
945 protected bool FamilyAccessible (Type tb, Type check_type)
947 Type declaring = check_type.DeclaringType;
948 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
951 // Access level of a type.
953 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
954 // Public Assembly Protected
955 Protected = (0 << 0) | (0 << 1) | (X << 2),
956 Public = (X << 0) | (X << 1) | (X << 2),
957 Private = (0 << 0) | (0 << 1) | (0 << 2),
958 Internal = (0 << 0) | (X << 1) | (0 << 2),
959 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
962 static AccessLevel GetAccessLevelFromModifiers (int flags)
964 if ((flags & Modifiers.INTERNAL) != 0) {
966 if ((flags & Modifiers.PROTECTED) != 0)
967 return AccessLevel.ProtectedOrInternal;
969 return AccessLevel.Internal;
971 } else if ((flags & Modifiers.PROTECTED) != 0)
972 return AccessLevel.Protected;
973 else if ((flags & Modifiers.PRIVATE) != 0)
974 return AccessLevel.Private;
976 return AccessLevel.Public;
979 // What is the effective access level of this?
981 AccessLevel EffectiveAccessLevel {
983 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
984 if (!IsTopLevel && (Parent != null))
985 return myAccess & Parent.EffectiveAccessLevel;
990 // Return the access level for type `t'
991 static AccessLevel TypeEffectiveAccessLevel (Type t)
994 return AccessLevel.Public;
995 if (t.IsNestedPrivate)
996 return AccessLevel.Private;
998 return AccessLevel.Internal;
1000 // By now, it must be nested
1001 AccessLevel parent_level = TypeEffectiveAccessLevel (t.DeclaringType);
1003 if (t.IsNestedPublic)
1004 return parent_level;
1005 if (t.IsNestedAssembly)
1006 return parent_level & AccessLevel.Internal;
1007 if (t.IsNestedFamily)
1008 return parent_level & AccessLevel.Protected;
1009 if (t.IsNestedFamORAssem)
1010 return parent_level & AccessLevel.ProtectedOrInternal;
1011 if (t.IsNestedFamANDAssem)
1012 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1014 // nested private is taken care of
1016 throw new Exception ("I give up, what are you?");
1020 // This answers `is the type P, as accessible as a member M which has the
1021 // accessability @flags which is declared as a nested member of the type T, this declspace'
1023 public bool AsAccessible (Type p, int flags)
1026 // 1) if M is private, its accessability is the same as this declspace.
1027 // we already know that P is accessible to T before this method, so we
1031 if ((flags & Modifiers.PRIVATE) != 0)
1034 while (p.IsArray || p.IsPointer || p.IsByRef)
1035 p = TypeManager.GetElementType (p);
1038 if (p.IsGenericParameter)
1041 if (TypeManager.IsGenericType (p)) {
1042 foreach (Type t in p.GetGenericArguments ()) {
1043 if (!AsAccessible (t, flags))
1048 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1049 AccessLevel mAccess = this.EffectiveAccessLevel &
1050 GetAccessLevelFromModifiers (flags);
1052 // for every place from which we can access M, we must
1053 // be able to access P as well. So, we want
1054 // For every bit in M and P, M_i -> P_1 == true
1055 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1057 return ~ (~ mAccess | pAccess) == 0;
1060 private Type LookupNestedTypeInHierarchy (string name)
1062 // if the member cache has been created, lets use it.
1063 // the member cache is MUCH faster.
1064 if (MemberCache != null)
1065 return MemberCache.FindNestedType (name);
1067 // no member cache. Do it the hard way -- reflection
1069 for (Type current_type = TypeBuilder;
1070 current_type != null && current_type != TypeManager.object_type;
1071 current_type = current_type.BaseType) {
1073 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1074 if (ct is TypeBuilder) {
1075 TypeContainer tc = ct == TypeBuilder
1076 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1078 t = tc.FindNestedType (name);
1080 t = TypeManager.GetNestedType (ct, name);
1083 if ((t == null) || !CheckAccessLevel (t))
1087 if (!TypeManager.IsGenericType (current_type))
1090 Type[] args = TypeManager.GetTypeArguments (current_type);
1091 Type[] targs = TypeManager.GetTypeArguments (t);
1092 for (int i = 0; i < args.Length; i++)
1093 targs [i] = args [i];
1095 t = t.MakeGenericType (targs);
1104 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1110 // Public function used to locate types.
1112 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1114 // Returns: Type or null if they type can not be found.
1116 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1118 if (Cache.Contains (name))
1119 return (FullNamedExpression) Cache [name];
1121 FullNamedExpression e;
1122 Type t = LookupNestedTypeInHierarchy (name);
1124 e = new TypeExpression (t, Location.Null);
1125 else if (Parent != null)
1126 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1128 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1135 /// This function is broken and not what you're looking for. It should only
1136 /// be used while the type is still being created since it doesn't use the cache
1137 /// and relies on the filter doing the member name check.
1139 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1140 MemberFilter filter, object criteria);
1143 /// If we have a MemberCache, return it. This property may return null if the
1144 /// class doesn't have a member cache or while it's still being created.
1146 public abstract MemberCache MemberCache {
1150 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1152 if (a.Type == TypeManager.required_attr_type) {
1153 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1156 TypeBuilder.SetCustomAttribute (cb);
1160 // Extensions for generics
1162 TypeParameter[] type_params;
1163 TypeParameter[] type_param_list;
1165 protected string GetInstantiationName ()
1167 StringBuilder sb = new StringBuilder (Name);
1169 for (int i = 0; i < type_param_list.Length; i++) {
1172 sb.Append (type_param_list [i].Name);
1175 return sb.ToString ();
1178 bool check_type_parameter (ArrayList list, int start, string name)
1180 for (int i = 0; i < start; i++) {
1181 TypeParameter param = (TypeParameter) list [i];
1183 if (param.Name != name)
1186 Report.SymbolRelatedToPreviousError (Parent);
1187 // TODO: Location is wrong (parent instead of child)
1188 Report.Warning (693, 3, Location,
1189 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1190 name, Parent.GetSignatureForError ());
1198 TypeParameter[] initialize_type_params ()
1200 if (type_param_list != null)
1201 return type_param_list;
1203 DeclSpace the_parent = Parent;
1204 if (this is GenericMethod)
1208 ArrayList list = new ArrayList ();
1209 if (the_parent != null && the_parent.IsGeneric) {
1210 // FIXME: move generics info out of DeclSpace
1211 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1212 start = parent_params.Length;
1213 list.AddRange (parent_params);
1216 int count = type_params != null ? type_params.Length : 0;
1217 for (int i = 0; i < count; i++) {
1218 TypeParameter param = type_params [i];
1219 check_type_parameter (list, start, param.Name);
1223 type_param_list = new TypeParameter [list.Count];
1224 list.CopyTo (type_param_list, 0);
1225 return type_param_list;
1228 public virtual void SetParameterInfo (ArrayList constraints_list)
1231 if (constraints_list != null) {
1233 80, Location, "Constraints are not allowed " +
1234 "on non-generic declarations");
1240 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1241 type_params = new TypeParameter [names.Length];
1244 // Register all the names
1246 for (int i = 0; i < type_params.Length; i++) {
1247 TypeParameterName name = names [i];
1249 Constraints constraints = null;
1250 if (constraints_list != null) {
1251 int total = constraints_list.Count;
1252 for (int ii = 0; ii < total; ++ii) {
1253 Constraints constraints_at = (Constraints)constraints_list[ii];
1254 // TODO: it is used by iterators only
1255 if (constraints_at == null) {
1256 constraints_list.RemoveAt (ii);
1260 if (constraints_at.TypeParameter == name.Name) {
1261 constraints = constraints_at;
1262 constraints_list.RemoveAt(ii);
1268 type_params [i] = new TypeParameter (
1269 Parent, this, name.Name, constraints, name.OptAttributes,
1272 AddToContainer (type_params [i], name.Name);
1275 if (constraints_list != null && constraints_list.Count > 0) {
1276 foreach (Constraints constraint in constraints_list) {
1277 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1278 GetSignatureForError (), constraint.TypeParameter);
1283 public TypeParameter[] TypeParameters {
1286 throw new InvalidOperationException ();
1287 if ((PartialContainer != null) && (PartialContainer != this))
1288 return PartialContainer.TypeParameters;
1289 if (type_param_list == null)
1290 initialize_type_params ();
1292 return type_param_list;
1296 public TypeParameter[] CurrentTypeParameters {
1299 throw new InvalidOperationException ();
1300 if ((PartialContainer != null) && (PartialContainer != this))
1301 return PartialContainer.CurrentTypeParameters;
1302 if (type_params != null)
1305 return new TypeParameter [0];
1309 public int CountTypeParameters {
1311 return count_type_params;
1315 public int CountCurrentTypeParameters {
1317 return count_current_type_params;
1321 public TypeParameterExpr LookupGeneric (string name, Location loc)
1326 TypeParameter [] current_params;
1327 if (this is TypeContainer)
1328 current_params = PartialContainer.CurrentTypeParameters;
1330 current_params = CurrentTypeParameters;
1332 foreach (TypeParameter type_param in current_params) {
1333 if (type_param.Name == name)
1334 return new TypeParameterExpr (type_param, loc);
1338 return Parent.LookupGeneric (name, loc);
1343 // Used for error reporting only
1344 public virtual Type LookupAnyGeneric (string typeName)
1346 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1349 public override string[] ValidAttributeTargets {
1350 get { return attribute_targets; }
1353 protected override bool VerifyClsCompliance ()
1355 if (!base.VerifyClsCompliance ()) {
1359 if (type_params != null) {
1360 foreach (TypeParameter tp in type_params) {
1361 if (tp.Constraints == null)
1364 tp.Constraints.VerifyClsCompliance ();
1368 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1372 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1373 if (!cache.Contains (lcase)) {
1374 cache.Add (lcase, this);
1378 object val = cache [lcase];
1380 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1383 Report.SymbolRelatedToPreviousError (t);
1386 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1389 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1391 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1398 /// This is a readonly list of MemberInfo's.
1400 public class MemberList : IList {
1401 public readonly IList List;
1405 /// Create a new MemberList from the given IList.
1407 public MemberList (IList list)
1412 this.List = new ArrayList ();
1417 /// Concatenate the ILists `first' and `second' to a new MemberList.
1419 public MemberList (IList first, IList second)
1421 ArrayList list = new ArrayList ();
1422 list.AddRange (first);
1423 list.AddRange (second);
1428 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1431 /// Cast the MemberList into a MemberInfo[] array.
1434 /// This is an expensive operation, only use it if it's really necessary.
1436 public static explicit operator MemberInfo [] (MemberList list)
1438 Timer.StartTimer (TimerType.MiscTimer);
1439 MemberInfo [] result = new MemberInfo [list.Count];
1440 list.CopyTo (result, 0);
1441 Timer.StopTimer (TimerType.MiscTimer);
1453 public bool IsSynchronized {
1455 return List.IsSynchronized;
1459 public object SyncRoot {
1461 return List.SyncRoot;
1465 public void CopyTo (Array array, int index)
1467 List.CopyTo (array, index);
1472 public IEnumerator GetEnumerator ()
1474 return List.GetEnumerator ();
1479 public bool IsFixedSize {
1485 public bool IsReadOnly {
1491 object IList.this [int index] {
1493 return List [index];
1497 throw new NotSupportedException ();
1501 // FIXME: try to find out whether we can avoid the cast in this indexer.
1502 public MemberInfo this [int index] {
1504 return (MemberInfo) List [index];
1508 public int Add (object value)
1510 throw new NotSupportedException ();
1513 public void Clear ()
1515 throw new NotSupportedException ();
1518 public bool Contains (object value)
1520 return List.Contains (value);
1523 public int IndexOf (object value)
1525 return List.IndexOf (value);
1528 public void Insert (int index, object value)
1530 throw new NotSupportedException ();
1533 public void Remove (object value)
1535 throw new NotSupportedException ();
1538 public void RemoveAt (int index)
1540 throw new NotSupportedException ();
1545 /// This interface is used to get all members of a class when creating the
1546 /// member cache. It must be implemented by all DeclSpace derivatives which
1547 /// want to support the member cache and by TypeHandle to get caching of
1548 /// non-dynamic types.
1550 public interface IMemberContainer {
1552 /// The name of the IMemberContainer. This is only used for
1553 /// debugging purposes.
1560 /// The type of this IMemberContainer.
1567 /// Returns the IMemberContainer of the base class or null if this
1568 /// is an interface or TypeManger.object_type.
1569 /// This is used when creating the member cache for a class to get all
1570 /// members from the base class.
1572 MemberCache BaseCache {
1577 /// Whether this is an interface.
1584 /// Returns all members of this class with the corresponding MemberTypes
1585 /// and BindingFlags.
1588 /// When implementing this method, make sure not to return any inherited
1589 /// members and check the MemberTypes and BindingFlags properly.
1590 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1591 /// get the BindingFlags (static/non-static,public/non-public) in the
1592 /// MemberInfo class, but the cache needs this information. That's why
1593 /// this method is called multiple times with different BindingFlags.
1595 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1598 /// Return the container's member cache.
1600 MemberCache MemberCache {
1606 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1607 /// member lookups. It has a member name based hash table; it maps each member
1608 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1609 /// and the BindingFlags that were initially used to get it. The cache contains
1610 /// all members of the current class and all inherited members. If this cache is
1611 /// for an interface types, it also contains all inherited members.
1613 /// There are two ways to get a MemberCache:
1614 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1615 /// use the DeclSpace.MemberCache property.
1616 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1617 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1619 public class MemberCache {
1620 public readonly IMemberContainer Container;
1621 protected Hashtable member_hash;
1622 protected Hashtable method_hash;
1625 /// Create a new MemberCache for the given IMemberContainer `container'.
1627 public MemberCache (IMemberContainer container)
1629 this.Container = container;
1631 Timer.IncrementCounter (CounterType.MemberCache);
1632 Timer.StartTimer (TimerType.CacheInit);
1634 // If we have a base class (we have a base class unless we're
1635 // TypeManager.object_type), we deep-copy its MemberCache here.
1636 if (Container.BaseCache != null)
1637 member_hash = SetupCache (Container.BaseCache);
1639 member_hash = new Hashtable ();
1641 // If this is neither a dynamic type nor an interface, create a special
1642 // method cache with all declared and inherited methods.
1643 Type type = container.Type;
1644 if (!(type is TypeBuilder) && !type.IsInterface &&
1645 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1646 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1647 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1648 method_hash = new Hashtable ();
1652 // Add all members from the current class.
1653 AddMembers (Container);
1655 Timer.StopTimer (TimerType.CacheInit);
1658 public MemberCache (Type[] ifaces)
1661 // The members of this cache all belong to other caches.
1662 // So, 'Container' will not be used.
1664 this.Container = null;
1666 member_hash = new Hashtable ();
1670 foreach (Type itype in ifaces)
1671 AddCacheContents (TypeManager.LookupMemberCache (itype));
1674 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1676 this.Container = container;
1678 // If we have a base class (we have a base class unless we're
1679 // TypeManager.object_type), we deep-copy its MemberCache here.
1680 if (Container.BaseCache != null)
1681 member_hash = SetupCache (Container.BaseCache);
1683 member_hash = new Hashtable ();
1685 if (base_class != null)
1686 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1687 if (ifaces != null) {
1688 foreach (Type itype in ifaces) {
1689 MemberCache cache = TypeManager.LookupMemberCache (itype);
1691 AddCacheContents (cache);
1697 /// Bootstrap this member cache by doing a deep-copy of our base.
1699 static Hashtable SetupCache (MemberCache base_class)
1701 Hashtable hash = new Hashtable ();
1703 if (base_class == null)
1706 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1707 while (it.MoveNext ()) {
1708 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1715 /// Add the contents of `cache' to the member_hash.
1717 void AddCacheContents (MemberCache cache)
1719 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1720 while (it.MoveNext ()) {
1721 ArrayList list = (ArrayList) member_hash [it.Key];
1723 member_hash [it.Key] = list = new ArrayList ();
1725 ArrayList entries = (ArrayList) it.Value;
1726 for (int i = entries.Count-1; i >= 0; i--) {
1727 CacheEntry entry = (CacheEntry) entries [i];
1729 if (entry.Container != cache.Container)
1737 /// Add all members from class `container' to the cache.
1739 void AddMembers (IMemberContainer container)
1741 // We need to call AddMembers() with a single member type at a time
1742 // to get the member type part of CacheEntry.EntryType right.
1743 if (!container.IsInterface) {
1744 AddMembers (MemberTypes.Constructor, container);
1745 AddMembers (MemberTypes.Field, container);
1747 AddMembers (MemberTypes.Method, container);
1748 AddMembers (MemberTypes.Property, container);
1749 AddMembers (MemberTypes.Event, container);
1750 // Nested types are returned by both Static and Instance searches.
1751 AddMembers (MemberTypes.NestedType,
1752 BindingFlags.Static | BindingFlags.Public, container);
1753 AddMembers (MemberTypes.NestedType,
1754 BindingFlags.Static | BindingFlags.NonPublic, container);
1757 void AddMembers (MemberTypes mt, IMemberContainer container)
1759 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1760 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1761 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1762 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1765 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1766 string name, MemberInfo member)
1768 // We use a name-based hash table of ArrayList's.
1769 ArrayList list = (ArrayList) member_hash [name];
1771 list = new ArrayList ();
1772 member_hash.Add (name, list);
1775 // When this method is called for the current class, the list will
1776 // already contain all inherited members from our base classes.
1777 // We cannot add new members in front of the list since this'd be an
1778 // expensive operation, that's why the list is sorted in reverse order
1779 // (ie. members from the current class are coming last).
1780 list.Add (new CacheEntry (container, member, mt, bf));
1784 /// Add all members from class `container' with the requested MemberTypes and
1785 /// BindingFlags to the cache. This method is called multiple times with different
1786 /// MemberTypes and BindingFlags.
1788 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1790 MemberList members = container.GetMembers (mt, bf);
1792 foreach (MemberInfo member in members) {
1793 string name = member.Name;
1795 AddMember (mt, bf, container, name, member);
1797 if (member is MethodInfo) {
1798 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1800 AddMember (mt, bf, container, gname, member);
1806 /// Add all declared and inherited methods from class `type' to the method cache.
1808 void AddMethods (Type type)
1810 AddMethods (BindingFlags.Static | BindingFlags.Public |
1811 BindingFlags.FlattenHierarchy, type);
1812 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1813 BindingFlags.FlattenHierarchy, type);
1814 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1815 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1818 static ArrayList overrides = new ArrayList ();
1820 void AddMethods (BindingFlags bf, Type type)
1822 MethodBase [] members = type.GetMethods (bf);
1824 Array.Reverse (members);
1826 foreach (MethodBase member in members) {
1827 string name = member.Name;
1829 // We use a name-based hash table of ArrayList's.
1830 ArrayList list = (ArrayList) method_hash [name];
1832 list = new ArrayList ();
1833 method_hash.Add (name, list);
1836 MethodInfo curr = (MethodInfo) member;
1837 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1838 MethodInfo base_method = curr.GetBaseDefinition ();
1840 if (base_method == curr)
1841 // Not every virtual function needs to have a NewSlot flag.
1844 overrides.Add (curr);
1845 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1849 if (overrides.Count > 0) {
1850 for (int i = 0; i < overrides.Count; ++i)
1851 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1855 // Unfortunately, the elements returned by Type.GetMethods() aren't
1856 // sorted so we need to do this check for every member.
1857 BindingFlags new_bf = bf;
1858 if (member.DeclaringType == type)
1859 new_bf |= BindingFlags.DeclaredOnly;
1861 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1866 /// Compute and return a appropriate `EntryType' magic number for the given
1867 /// MemberTypes and BindingFlags.
1869 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1871 EntryType type = EntryType.None;
1873 if ((mt & MemberTypes.Constructor) != 0)
1874 type |= EntryType.Constructor;
1875 if ((mt & MemberTypes.Event) != 0)
1876 type |= EntryType.Event;
1877 if ((mt & MemberTypes.Field) != 0)
1878 type |= EntryType.Field;
1879 if ((mt & MemberTypes.Method) != 0)
1880 type |= EntryType.Method;
1881 if ((mt & MemberTypes.Property) != 0)
1882 type |= EntryType.Property;
1883 // Nested types are returned by static and instance searches.
1884 if ((mt & MemberTypes.NestedType) != 0)
1885 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1887 if ((bf & BindingFlags.Instance) != 0)
1888 type |= EntryType.Instance;
1889 if ((bf & BindingFlags.Static) != 0)
1890 type |= EntryType.Static;
1891 if ((bf & BindingFlags.Public) != 0)
1892 type |= EntryType.Public;
1893 if ((bf & BindingFlags.NonPublic) != 0)
1894 type |= EntryType.NonPublic;
1895 if ((bf & BindingFlags.DeclaredOnly) != 0)
1896 type |= EntryType.Declared;
1902 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1903 /// denote multiple member types. Returns true if the given flags value denotes a
1904 /// single member types.
1906 public static bool IsSingleMemberType (MemberTypes mt)
1909 case MemberTypes.Constructor:
1910 case MemberTypes.Event:
1911 case MemberTypes.Field:
1912 case MemberTypes.Method:
1913 case MemberTypes.Property:
1914 case MemberTypes.NestedType:
1923 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1924 /// number to speed up the searching process.
1927 protected enum EntryType {
1932 MaskStatic = Instance|Static,
1936 MaskProtection = Public|NonPublic,
1940 Constructor = 0x020,
1947 NotExtensionMethod = 0x800,
1949 MaskType = Constructor|Event|Field|Method|Property|NestedType
1952 protected class CacheEntry {
1953 public readonly IMemberContainer Container;
1954 public EntryType EntryType;
1955 public readonly MemberInfo Member;
1957 public CacheEntry (IMemberContainer container, MemberInfo member,
1958 MemberTypes mt, BindingFlags bf)
1960 this.Container = container;
1961 this.Member = member;
1962 this.EntryType = GetEntryType (mt, bf);
1965 public override string ToString ()
1967 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1973 /// This is called each time we're walking up one level in the class hierarchy
1974 /// and checks whether we can abort the search since we've already found what
1975 /// we were looking for.
1977 protected bool DoneSearching (ArrayList list)
1980 // We've found exactly one member in the current class and it's not
1981 // a method or constructor.
1983 if (list.Count == 1 && !(list [0] is MethodBase))
1987 // Multiple properties: we query those just to find out the indexer
1990 if ((list.Count > 0) && (list [0] is PropertyInfo))
1997 /// Looks up members with name `name'. If you provide an optional
1998 /// filter function, it'll only be called with members matching the
1999 /// requested member name.
2001 /// This method will try to use the cache to do the lookup if possible.
2003 /// Unlike other FindMembers implementations, this method will always
2004 /// check all inherited members - even when called on an interface type.
2006 /// If you know that you're only looking for methods, you should use
2007 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2008 /// When doing a method-only search, it'll try to use a special method
2009 /// cache (unless it's a dynamic type or an interface) and the returned
2010 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2011 /// The lookup process will automatically restart itself in method-only
2012 /// search mode if it discovers that it's about to return methods.
2014 ArrayList global = new ArrayList ();
2015 bool using_global = false;
2017 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2019 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2020 MemberFilter filter, object criteria)
2023 throw new Exception ();
2025 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2026 bool method_search = mt == MemberTypes.Method;
2027 // If we have a method cache and we aren't already doing a method-only search,
2028 // then we restart a method search if the first match is a method.
2029 bool do_method_search = !method_search && (method_hash != null);
2031 ArrayList applicable;
2033 // If this is a method-only search, we try to use the method cache if
2034 // possible; a lookup in the method cache will return a MemberInfo with
2035 // the correct ReflectedType for inherited methods.
2037 if (method_search && (method_hash != null))
2038 applicable = (ArrayList) method_hash [name];
2040 applicable = (ArrayList) member_hash [name];
2042 if (applicable == null)
2043 return emptyMemberInfo;
2046 // 32 slots gives 53 rss/54 size
2047 // 2/4 slots gives 55 rss
2049 // Strange: from 25,000 calls, only 1,800
2050 // are above 2. Why does this impact it?
2053 using_global = true;
2055 Timer.StartTimer (TimerType.CachedLookup);
2057 EntryType type = GetEntryType (mt, bf);
2059 IMemberContainer current = Container;
2061 bool do_interface_search = current.IsInterface;
2063 // `applicable' is a list of all members with the given member name `name'
2064 // in the current class and all its base classes. The list is sorted in
2065 // reverse order due to the way how the cache is initialy created (to speed
2066 // things up, we're doing a deep-copy of our base).
2068 for (int i = applicable.Count-1; i >= 0; i--) {
2069 CacheEntry entry = (CacheEntry) applicable [i];
2071 // This happens each time we're walking one level up in the class
2072 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2073 // the first time this happens (this may already happen in the first
2074 // iteration of this loop if there are no members with the name we're
2075 // looking for in the current class).
2076 if (entry.Container != current) {
2080 if (!do_interface_search && DoneSearching (global))
2083 current = entry.Container;
2086 // Is the member of the correct type ?
2087 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2090 // Is the member static/non-static ?
2091 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2094 // Apply the filter to it.
2095 if (filter (entry.Member, criteria)) {
2096 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2097 do_method_search = false;
2100 // Because interfaces support multiple inheritance we have to be sure that
2101 // base member is from same interface, so only top level member will be returned
2102 if (do_interface_search && global.Count > 0) {
2103 bool member_already_exists = false;
2105 foreach (MemberInfo mi in global) {
2106 if (mi is MethodBase)
2109 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2110 member_already_exists = true;
2114 if (member_already_exists)
2118 global.Add (entry.Member);
2122 Timer.StopTimer (TimerType.CachedLookup);
2124 // If we have a method cache and we aren't already doing a method-only
2125 // search, we restart in method-only search mode if the first match is
2126 // a method. This ensures that we return a MemberInfo with the correct
2127 // ReflectedType for inherited methods.
2128 if (do_method_search && (global.Count > 0)){
2129 using_global = false;
2131 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2134 using_global = false;
2135 MemberInfo [] copy = new MemberInfo [global.Count];
2136 global.CopyTo (copy);
2141 /// Returns true if iterface exists in any base interfaces (ifaces)
2143 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2145 foreach (Type iface in ifaces) {
2146 if (iface == ifaceToFind)
2149 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2150 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2156 // find the nested type @name in @this.
2157 public Type FindNestedType (string name)
2159 ArrayList applicable = (ArrayList) member_hash [name];
2160 if (applicable == null)
2163 for (int i = applicable.Count-1; i >= 0; i--) {
2164 CacheEntry entry = (CacheEntry) applicable [i];
2165 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2166 return (Type) entry.Member;
2172 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2174 ArrayList applicable = (ArrayList) member_hash [name];
2175 if (applicable == null)
2179 // Walk the chain of events, starting from the top.
2181 for (int i = applicable.Count - 1; i >= 0; i--)
2183 CacheEntry entry = (CacheEntry) applicable [i];
2184 if ((entry.EntryType & EntryType.Event) == 0)
2187 EventInfo ei = (EventInfo)entry.Member;
2188 return ei.GetAddMethod (true);
2195 // Looks for extension methods with defined name and extension type
2197 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2200 if (method_hash != null)
2201 entries = (ArrayList)method_hash [name];
2203 entries = (ArrayList)member_hash [name];
2205 if (entries == null)
2208 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2210 entry_type |= EntryType.Public;
2212 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2214 ArrayList candidates = null;
2215 foreach (CacheEntry entry in entries) {
2216 if ((entry.EntryType & entry_type) == found_entry_type) {
2217 MethodBase mb = (MethodBase)entry.Member;
2219 IMethodData md = TypeManager.GetMethod (mb);
2220 ParameterData pd = md == null ?
2221 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2223 Type ex_type = pd.ExtensionMethodType;
2224 if (ex_type == null) {
2225 entry.EntryType |= EntryType.NotExtensionMethod;
2229 //if (implicit conversion between ex_type and extensionType exist) {
2230 if (candidates == null)
2231 candidates = new ArrayList (2);
2232 candidates.Add (mb);
2241 // This finds the method or property for us to override. invocation_type is the type where
2242 // the override is going to be declared, name is the name of the method/property, and
2243 // param_types is the parameters, if any to the method or property
2245 // Because the MemberCache holds members from this class and all the base classes,
2246 // we can avoid tons of reflection stuff.
2248 public MemberInfo FindMemberToOverride (Type invocation_type, string name, Type [] param_types, GenericMethod generic_method, bool is_property)
2250 ArrayList applicable;
2251 if (method_hash != null && !is_property)
2252 applicable = (ArrayList) method_hash [name];
2254 applicable = (ArrayList) member_hash [name];
2256 if (applicable == null)
2259 // Walk the chain of methods, starting from the top.
2261 for (int i = applicable.Count - 1; i >= 0; i--) {
2262 CacheEntry entry = (CacheEntry) applicable [i];
2264 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2267 PropertyInfo pi = null;
2268 MethodInfo mi = null;
2269 FieldInfo fi = null;
2270 Type [] cmp_attrs = null;
2273 if ((entry.EntryType & EntryType.Field) != 0) {
2274 fi = (FieldInfo)entry.Member;
2276 // TODO: For this case we ignore member type
2277 //fb = TypeManager.GetField (fi);
2278 //cmp_attrs = new Type[] { fb.MemberType };
2280 pi = (PropertyInfo) entry.Member;
2281 cmp_attrs = TypeManager.GetArgumentTypes (pi);
2284 mi = (MethodInfo) entry.Member;
2285 cmp_attrs = TypeManager.GetParameterData (mi).Types;
2289 // TODO: Almost duplicate !
2291 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2292 case FieldAttributes.PrivateScope:
2294 case FieldAttributes.Private:
2296 // A private method is Ok if we are a nested subtype.
2297 // The spec actually is not very clear about this, see bug 52458.
2299 if (!invocation_type.Equals (entry.Container.Type) &&
2300 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2303 case FieldAttributes.FamANDAssem:
2304 case FieldAttributes.Assembly:
2306 // Check for assembly methods
2308 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2312 return entry.Member;
2316 // Check the arguments
2318 if (cmp_attrs.Length != param_types.Length)
2322 for (j = 0; j < cmp_attrs.Length; ++j)
2323 if (!TypeManager.IsEqual (param_types [j], cmp_attrs [j]))
2325 if (j < cmp_attrs.Length)
2329 // check generic arguments for methods
2332 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2333 if (generic_method == null && cmpGenArgs.Length != 0)
2335 if (generic_method != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2340 // get one of the methods because this has the visibility info.
2343 mi = pi.GetGetMethod (true);
2345 mi = pi.GetSetMethod (true);
2351 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2352 case MethodAttributes.PrivateScope:
2354 case MethodAttributes.Private:
2356 // A private method is Ok if we are a nested subtype.
2357 // The spec actually is not very clear about this, see bug 52458.
2359 if (!invocation_type.Equals (entry.Container.Type) &&
2360 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2363 case MethodAttributes.FamANDAssem:
2364 case MethodAttributes.Assembly:
2366 // Check for assembly methods
2368 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2372 return entry.Member;
2379 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2380 /// We handle two cases. The first is for types without parameters (events, field, properties).
2381 /// The second are methods, indexers and this is why ignore_complex_types is here.
2382 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2384 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2386 ArrayList applicable = null;
2388 if (method_hash != null)
2389 applicable = (ArrayList) method_hash [name];
2391 if (applicable != null) {
2392 for (int i = applicable.Count - 1; i >= 0; i--) {
2393 CacheEntry entry = (CacheEntry) applicable [i];
2394 if ((entry.EntryType & EntryType.Public) != 0)
2395 return entry.Member;
2399 if (member_hash == null)
2401 applicable = (ArrayList) member_hash [name];
2403 if (applicable != null) {
2404 for (int i = applicable.Count - 1; i >= 0; i--) {
2405 CacheEntry entry = (CacheEntry) applicable [i];
2406 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2407 if (ignore_complex_types) {
2408 if ((entry.EntryType & EntryType.Method) != 0)
2411 // Does exist easier way how to detect indexer ?
2412 if ((entry.EntryType & EntryType.Property) != 0) {
2413 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2414 if (arg_types.Length > 0)
2418 return entry.Member;
2425 Hashtable locase_table;
2428 /// Builds low-case table for CLS Compliance test
2430 public Hashtable GetPublicMembers ()
2432 if (locase_table != null)
2433 return locase_table;
2435 locase_table = new Hashtable ();
2436 foreach (DictionaryEntry entry in member_hash) {
2437 ArrayList members = (ArrayList)entry.Value;
2438 for (int ii = 0; ii < members.Count; ++ii) {
2439 CacheEntry member_entry = (CacheEntry) members [ii];
2441 if ((member_entry.EntryType & EntryType.Public) == 0)
2444 // TODO: Does anyone know easier way how to detect that member is internal ?
2445 switch (member_entry.EntryType & EntryType.MaskType) {
2446 case EntryType.Constructor:
2449 case EntryType.Field:
2450 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2454 case EntryType.Method:
2455 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2459 case EntryType.Property:
2460 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2461 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2465 case EntryType.Event:
2466 EventInfo ei = (EventInfo)member_entry.Member;
2467 MethodInfo mi = ei.GetAddMethod ();
2468 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2472 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2473 locase_table [lcase] = member_entry.Member;
2477 return locase_table;
2480 public Hashtable Members {
2487 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2490 // TODO: refactor as method is always 'this'
2491 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2493 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2495 for (int i = 0; i < al.Count; ++i) {
2496 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2499 if (entry.Member == this_builder)
2502 if ((entry.EntryType & tested_type) != tested_type)
2505 MethodBase method_to_compare = (MethodBase)entry.Member;
2506 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2507 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2509 if (result == AttributeTester.Result.Ok)
2512 IMethodData md = TypeManager.GetMethod (method_to_compare);
2514 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2515 // However it is exactly what csc does.
2516 if (md != null && !md.IsClsComplianceRequired ())
2519 Report.SymbolRelatedToPreviousError (entry.Member);
2521 case AttributeTester.Result.RefOutArrayError:
2522 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2524 case AttributeTester.Result.ArrayArrayError:
2525 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2529 throw new NotImplementedException (result.ToString ());