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 if (args != null && args.Count > 0)
55 this.TypeArguments = args;
58 public MemberName (string name)
59 : this (name, Location.Null)
62 public MemberName (string name, Location loc)
63 : this (null, name, false, loc)
66 public MemberName (string name, TypeArguments args, Location loc)
67 : this (null, name, false, args, loc)
70 public MemberName (MemberName left, string name)
71 : this (left, name, left != null ? left.Location : Location.Null)
74 public MemberName (MemberName left, string name, Location loc)
75 : this (left, name, false, loc)
78 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
79 : this (left, name, false, args, loc)
82 public MemberName (string alias, string name, Location loc)
83 : this (new MemberName (alias, loc), name, true, loc)
86 public MemberName (MemberName left, MemberName right)
87 : this (left, right, right.Location)
90 public MemberName (MemberName left, MemberName right, Location loc)
91 : this (null, right.Name, false, right.TypeArguments, loc)
93 if (right.is_double_colon)
94 throw new InternalErrorException ("Cannot append double_colon member name");
95 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
98 public string GetName ()
100 return GetName (false);
103 public bool IsGeneric {
105 if (TypeArguments != null)
107 else if (Left != null)
108 return Left.IsGeneric;
114 public string GetName (bool is_generic)
116 string name = is_generic ? Basename : Name;
117 string connect = is_double_colon ? "::" : ".";
119 return Left.GetName (is_generic) + connect + name;
124 public string GetTypeName ()
126 string connect = is_double_colon ? "::" : ".";
128 return Left.GetTypeName () + connect + MakeName (Name, TypeArguments);
130 return MakeName (Name, TypeArguments);
133 public Expression GetTypeExpression ()
136 if (TypeArguments != null)
137 return new SimpleName (Basename, TypeArguments, Location);
139 if (RootContext.Version == LanguageVersion.LINQ && Name == "var")
140 return new VarExpr (Name, Location);
142 return new SimpleName (Name, Location);
145 if (is_double_colon) {
146 if (Left.Left != null)
147 throw new InternalErrorException ("The left side of a :: should be an identifier");
148 return new QualifiedAliasMember (Left.Name, Name, Location);
151 Expression lexpr = Left.GetTypeExpression ();
152 return new MemberAccess (lexpr, Name, TypeArguments, Location);
155 public MemberName Clone ()
157 MemberName left_clone = Left == null ? null : Left.Clone ();
158 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
161 public string Basename {
163 if (TypeArguments != null)
164 return MakeName (Name, TypeArguments);
170 public string FullName {
172 if (TypeArguments != null)
173 return Name + "<" + TypeArguments + ">";
179 public string MethodName {
181 string connect = is_double_colon ? "::" : ".";
183 return Left.FullName + connect + Name;
189 public override string ToString ()
191 string connect = is_double_colon ? "::" : ".";
193 return Left.FullName + connect + FullName;
198 public override bool Equals (object other)
200 return Equals (other as MemberName);
203 public bool Equals (MemberName other)
207 if (other == null || Name != other.Name)
209 if (is_double_colon != other.is_double_colon)
212 if ((TypeArguments != null) &&
213 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
216 if ((TypeArguments == null) && (other.TypeArguments != null))
220 return other.Left == null;
222 return Left.Equals (other.Left);
225 public override int GetHashCode ()
227 int hash = Name.GetHashCode ();
228 for (MemberName n = Left; n != null; n = n.Left)
229 hash ^= n.Name.GetHashCode ();
233 if (TypeArguments != null)
234 hash ^= TypeArguments.Count << 5;
236 return hash & 0x7FFFFFFF;
239 public int CountTypeArguments {
241 if (TypeArguments != null)
242 return TypeArguments.Count;
243 else if (Left != null)
244 return Left.CountTypeArguments;
250 public static string MakeName (string name, TypeArguments args)
255 return name + "`" + args.Count;
258 public static string MakeName (string name, int count)
260 return name + "`" + count;
265 /// Base representation for members. This is used to keep track
266 /// of Name, Location and Modifier flags, and handling Attributes.
268 public abstract class MemberCore : Attributable, IResolveContext {
273 protected string cached_name;
276 if (cached_name == null)
277 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
282 // Is not readonly because of IndexerName attribute
283 private MemberName member_name;
284 public MemberName MemberName {
285 get { return member_name; }
289 /// Modifier flags that the user specified in the source code
291 private int mod_flags;
292 public int ModFlags {
295 if ((value & Modifiers.COMPILER_GENERATED) != 0)
296 caching_flags = Flags.IsUsed | Flags.IsAssigned;
303 public /*readonly*/ DeclSpace Parent;
306 /// Location where this declaration happens
308 public Location Location {
309 get { return member_name.Location; }
313 /// XML documentation comment
315 protected string comment;
318 /// Represents header string for documentation comment
319 /// for each member types.
321 public abstract string DocCommentHeader { get; }
325 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
326 Obsolete = 1 << 1, // Type has obsolete attribute
327 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
328 ClsCompliant = 1 << 3, // Type is CLS Compliant
329 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
330 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
331 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
332 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
333 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
334 Excluded = 1 << 9, // Method is conditional
335 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
337 IsAssigned = 1 << 12, // Field is assigned
338 HasExplicitLayout = 1 << 13
342 /// MemberCore flags at first detected then cached
344 internal Flags caching_flags;
346 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
349 this.Parent = parent;
351 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
354 protected virtual void SetMemberName (MemberName new_name)
356 member_name = new_name;
360 protected bool CheckAbstractAndExtern (bool has_block)
362 if (Parent.PartialContainer.Kind == Kind.Interface)
366 if ((ModFlags & Modifiers.EXTERN) != 0) {
367 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
368 GetSignatureForError ());
372 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
373 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
374 GetSignatureForError ());
378 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
379 if (RootContext.Version >= LanguageVersion.LINQ && this is Property.PropertyMethod) {
380 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",
381 GetSignatureForError ());
383 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract or extern",
384 GetSignatureForError ());
393 public abstract bool Define ();
395 public virtual string DocComment {
405 // Returns full member name for error message
407 public virtual string GetSignatureForError ()
409 if (Parent == null || Parent.Parent == null)
410 return member_name.ToString ();
412 return String.Concat (Parent.GetSignatureForError (), '.', member_name.ToString ());
416 /// Base Emit method. This is also entry point for CLS-Compliant verification.
418 public virtual void Emit ()
420 if (!RootContext.VerifyClsCompliance)
423 VerifyClsCompliance ();
426 public virtual bool IsUsed {
427 get { return (caching_flags & Flags.IsUsed) != 0; }
430 public void SetMemberIsUsed ()
432 caching_flags |= Flags.IsUsed;
436 /// Returns instance of ObsoleteAttribute for this MemberCore
438 public virtual ObsoleteAttribute GetObsoleteAttribute ()
440 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
441 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
445 caching_flags &= ~Flags.Obsolete_Undetected;
447 if (OptAttributes == null)
450 Attribute obsolete_attr = OptAttributes.Search (
451 TypeManager.obsolete_attribute_type);
452 if (obsolete_attr == null)
455 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
456 if (obsolete == null)
459 caching_flags |= Flags.Obsolete;
464 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
466 public virtual void CheckObsoleteness (Location loc)
469 Parent.CheckObsoleteness (loc);
471 ObsoleteAttribute oa = GetObsoleteAttribute ();
476 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
480 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
482 public override bool IsClsComplianceRequired ()
484 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
485 return (caching_flags & Flags.ClsCompliant) != 0;
487 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
488 caching_flags &= ~Flags.ClsCompliance_Undetected;
489 caching_flags |= Flags.ClsCompliant;
493 caching_flags &= ~Flags.ClsCompliance_Undetected;
498 /// Returns true when MemberCore is exposed from assembly.
500 public bool IsExposedFromAssembly ()
502 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
505 DeclSpace parentContainer = Parent;
506 while (parentContainer != null && parentContainer.ModFlags != 0) {
507 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
509 parentContainer = parentContainer.Parent;
515 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
516 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
518 public virtual bool GetClsCompliantAttributeValue ()
520 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
521 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
523 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
525 if (OptAttributes != null) {
526 Attribute cls_attribute = OptAttributes.Search (
527 TypeManager.cls_compliant_attribute_type);
528 if (cls_attribute != null) {
529 caching_flags |= Flags.HasClsCompliantAttribute;
530 bool value = cls_attribute.GetClsCompliantAttributeValue ();
532 caching_flags |= Flags.ClsCompliantAttributeTrue;
537 // It's null for TypeParameter
541 if (Parent.GetClsCompliantAttributeValue ()) {
542 caching_flags |= Flags.ClsCompliantAttributeTrue;
549 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
551 protected bool HasClsCompliantAttribute {
553 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) != 0)
554 GetClsCompliantAttributeValue ();
556 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
561 /// It helps to handle error 102 & 111 detection
563 public virtual bool MarkForDuplicationCheck ()
569 /// The main virtual method for CLS-Compliant verifications.
570 /// The method returns true if member is CLS-Compliant and false if member is not
571 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
572 /// and add their extra verifications.
574 protected virtual bool VerifyClsCompliance ()
576 if (!IsClsComplianceRequired ()) {
577 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
578 if (!IsExposedFromAssembly ())
579 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
580 if (!CodeGen.Assembly.IsClsCompliant)
581 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
586 if (HasClsCompliantAttribute) {
587 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
588 Report.Error (3014, Location,
589 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
590 GetSignatureForError ());
594 if (!Parent.IsClsComplianceRequired ()) {
595 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
596 GetSignatureForError (), Parent.GetSignatureForError ());
601 if (member_name.Name [0] == '_') {
602 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
608 // Raised (and passed an XmlElement that contains the comment)
609 // when GenerateDocComment is writing documentation expectedly.
611 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
616 // Returns a string that represents the signature for this
617 // member which should be used in XML documentation.
619 public virtual string GetDocCommentName (DeclSpace ds)
621 if (ds == null || this is DeclSpace)
622 return DocCommentHeader + Name;
624 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
628 // Generates xml doc comments (if any), and if required,
629 // handle warning report.
631 internal virtual void GenerateDocComment (DeclSpace ds)
633 DocUtil.GenerateDocComment (this, ds);
636 public override IResolveContext ResolveContext {
640 #region IResolveContext Members
642 public DeclSpace DeclContainer {
643 get { return Parent; }
646 public virtual DeclSpace GenericDeclContainer {
647 get { return DeclContainer; }
650 public bool IsInObsoleteScope {
652 if (GetObsoleteAttribute () != null)
655 return Parent == null ? false : Parent.IsInObsoleteScope;
659 public bool IsInUnsafeScope {
661 if ((ModFlags & Modifiers.UNSAFE) != 0)
664 return Parent == null ? false : Parent.IsInUnsafeScope;
672 /// Base class for structs, classes, enumerations and interfaces.
675 /// They all create new declaration spaces. This
676 /// provides the common foundation for managing those name
679 public abstract class DeclSpace : MemberCore {
681 /// This points to the actual definition that is being
682 /// created with System.Reflection.Emit
684 public TypeBuilder TypeBuilder;
687 /// If we are a generic type, this is the type we are
688 /// currently defining. We need to lookup members on this
689 /// instead of the TypeBuilder.
691 public Type CurrentType;
694 // This is the namespace in which this typecontainer
695 // was declared. We use this to resolve names.
697 public NamespaceEntry NamespaceEntry;
699 private Hashtable Cache = new Hashtable ();
701 public readonly string Basename;
703 protected Hashtable defined_names;
705 public TypeContainer PartialContainer;
707 readonly bool is_generic;
708 readonly int count_type_params;
709 readonly int count_current_type_params;
712 // Whether we are Generic
714 public bool IsGeneric {
718 else if (Parent != null)
719 return Parent.IsGeneric;
725 static string[] attribute_targets = new string [] { "type" };
727 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
729 : base (parent, name, attrs)
732 Basename = name.Basename;
733 defined_names = new Hashtable ();
734 PartialContainer = null;
735 if (name.TypeArguments != null) {
737 count_type_params = count_current_type_params = name.TypeArguments.Count;
740 count_type_params += parent.count_type_params;
743 public override DeclSpace GenericDeclContainer {
748 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
750 protected virtual bool AddToContainer (MemberCore symbol, string name)
752 MemberCore mc = (MemberCore) defined_names [name];
755 defined_names.Add (name, symbol);
759 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
762 Report.SymbolRelatedToPreviousError (mc);
763 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
764 Error_MissingPartialModifier (symbol);
768 if (this is RootTypes) {
769 Report.Error (101, symbol.Location,
770 "The namespace `{0}' already contains a definition for `{1}'",
771 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
772 } else if (symbol is TypeParameter) {
773 Report.Error (692, symbol.Location,
774 "Duplicate type parameter `{0}'", name);
776 Report.Error (102, symbol.Location,
777 "The type `{0}' already contains a definition for `{1}'",
778 GetSignatureForError (), symbol.MemberName.Name);
785 /// Returns the MemberCore associated with a given name in the declaration
786 /// space. It doesn't return method based symbols !!
789 public MemberCore GetDefinition (string name)
791 return (MemberCore)defined_names [name];
794 public bool IsStaticClass {
795 get { return (ModFlags & Modifiers.STATIC) != 0; }
799 // root_types contains all the types. All TopLevel types
800 // hence have a parent that points to `root_types', that is
801 // why there is a non-obvious test down here.
803 public bool IsTopLevel {
804 get { return (Parent != null && Parent.Parent == null); }
807 public virtual void CloseType ()
809 if ((caching_flags & Flags.CloseTypeCreated) == 0){
811 TypeBuilder.CreateType ();
814 // The try/catch is needed because
815 // nested enumerations fail to load when they
818 // Even if this is the right order (enumerations
819 // declared after types).
821 // Note that this still creates the type and
822 // it is possible to save it
824 caching_flags |= Flags.CloseTypeCreated;
828 protected virtual TypeAttributes TypeAttr {
829 get { return CodeGen.Module.DefaultCharSetType; }
833 /// Should be overriten by the appropriate declaration space
835 public abstract TypeBuilder DefineType ();
838 /// Define all members, but don't apply any attributes or do anything which may
839 /// access not-yet-defined classes. This method also creates the MemberCache.
841 public virtual bool DefineMembers ()
843 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
844 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
850 protected void Error_MissingPartialModifier (MemberCore type)
852 Report.Error (260, type.Location,
853 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
854 type.GetSignatureForError ());
857 public override string GetSignatureForError ()
860 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
862 // Parent.GetSignatureForError
866 public bool CheckAccessLevel (Type check_type)
869 if (this is GenericMethod)
870 tb = Parent.TypeBuilder;
874 check_type = TypeManager.DropGenericTypeArguments (check_type);
875 if (check_type == tb)
878 if (TypeBuilder == null)
879 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
880 // However, this is invoked again later -- so safe to return true.
881 // May also be null when resolving top-level attributes.
885 // Broken Microsoft runtime, return public for arrays, no matter what
886 // the accessibility is for their underlying class, and they return
887 // NonPublic visibility for pointers
889 if (check_type.IsArray || check_type.IsPointer)
890 return CheckAccessLevel (TypeManager.GetElementType (check_type));
892 if (TypeManager.IsGenericParameter(check_type))
893 return true; // FIXME
895 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
898 case TypeAttributes.Public:
901 case TypeAttributes.NotPublic:
903 if (TypeBuilder == null)
904 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
905 // However, this is invoked again later -- so safe to return true.
906 // May also be null when resolving top-level attributes.
909 // This test should probably use the declaringtype.
911 return check_type.Assembly == TypeBuilder.Assembly ||
912 TypeManager.IsFriendAssembly (check_type.Assembly);
914 case TypeAttributes.NestedPublic:
917 case TypeAttributes.NestedPrivate:
918 return NestedAccessible (tb, check_type);
920 case TypeAttributes.NestedFamily:
922 // Only accessible to methods in current type or any subtypes
924 return FamilyAccessible (tb, check_type);
926 case TypeAttributes.NestedFamANDAssem:
927 return ((check_type.Assembly == tb.Assembly) ||
928 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
929 FamilyAccessible (tb, check_type);
931 case TypeAttributes.NestedFamORAssem:
932 return (check_type.Assembly == tb.Assembly) ||
933 FamilyAccessible (tb, check_type) ||
934 TypeManager.IsFriendAssembly (check_type.Assembly);
936 case TypeAttributes.NestedAssembly:
937 return check_type.Assembly == tb.Assembly ||
938 TypeManager.IsFriendAssembly (check_type.Assembly);
941 Console.WriteLine ("HERE: " + check_attr);
946 protected bool NestedAccessible (Type tb, Type check_type)
948 Type declaring = check_type.DeclaringType;
949 return TypeBuilder == declaring ||
950 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
953 protected bool FamilyAccessible (Type tb, Type check_type)
955 Type declaring = check_type.DeclaringType;
956 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
959 // Access level of a type.
961 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
962 // Public Assembly Protected
963 Protected = (0 << 0) | (0 << 1) | (X << 2),
964 Public = (X << 0) | (X << 1) | (X << 2),
965 Private = (0 << 0) | (0 << 1) | (0 << 2),
966 Internal = (0 << 0) | (X << 1) | (0 << 2),
967 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
970 static AccessLevel GetAccessLevelFromModifiers (int flags)
972 if ((flags & Modifiers.INTERNAL) != 0) {
974 if ((flags & Modifiers.PROTECTED) != 0)
975 return AccessLevel.ProtectedOrInternal;
977 return AccessLevel.Internal;
979 } else if ((flags & Modifiers.PROTECTED) != 0)
980 return AccessLevel.Protected;
981 else if ((flags & Modifiers.PRIVATE) != 0)
982 return AccessLevel.Private;
984 return AccessLevel.Public;
987 // What is the effective access level of this?
989 AccessLevel EffectiveAccessLevel {
991 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
992 if (!IsTopLevel && (Parent != null))
993 return myAccess & Parent.EffectiveAccessLevel;
998 // Return the access level for type `t'
999 static AccessLevel TypeEffectiveAccessLevel (Type t)
1002 return AccessLevel.Public;
1003 if (t.IsNestedPrivate)
1004 return AccessLevel.Private;
1006 return AccessLevel.Internal;
1008 // By now, it must be nested
1009 AccessLevel parent_level = TypeEffectiveAccessLevel (t.DeclaringType);
1011 if (t.IsNestedPublic)
1012 return parent_level;
1013 if (t.IsNestedAssembly)
1014 return parent_level & AccessLevel.Internal;
1015 if (t.IsNestedFamily)
1016 return parent_level & AccessLevel.Protected;
1017 if (t.IsNestedFamORAssem)
1018 return parent_level & AccessLevel.ProtectedOrInternal;
1019 if (t.IsNestedFamANDAssem)
1020 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1022 // nested private is taken care of
1024 throw new Exception ("I give up, what are you?");
1028 // This answers `is the type P, as accessible as a member M which has the
1029 // accessability @flags which is declared as a nested member of the type T, this declspace'
1031 public bool AsAccessible (Type p, int flags)
1034 // 1) if M is private, its accessability is the same as this declspace.
1035 // we already know that P is accessible to T before this method, so we
1039 if ((flags & Modifiers.PRIVATE) != 0)
1042 while (p.IsArray || p.IsPointer || p.IsByRef)
1043 p = TypeManager.GetElementType (p);
1046 if (p.IsGenericParameter)
1049 if (TypeManager.IsGenericType (p)) {
1050 foreach (Type t in p.GetGenericArguments ()) {
1051 if (!AsAccessible (t, flags))
1056 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1057 AccessLevel mAccess = this.EffectiveAccessLevel &
1058 GetAccessLevelFromModifiers (flags);
1060 // for every place from which we can access M, we must
1061 // be able to access P as well. So, we want
1062 // For every bit in M and P, M_i -> P_1 == true
1063 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1065 return ~ (~ mAccess | pAccess) == 0;
1068 private Type LookupNestedTypeInHierarchy (string name)
1070 // if the member cache has been created, lets use it.
1071 // the member cache is MUCH faster.
1072 if (MemberCache != null)
1073 return MemberCache.FindNestedType (name);
1075 // no member cache. Do it the hard way -- reflection
1077 for (Type current_type = TypeBuilder;
1078 current_type != null && current_type != TypeManager.object_type;
1079 current_type = current_type.BaseType) {
1081 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1082 if (ct is TypeBuilder) {
1083 TypeContainer tc = ct == TypeBuilder
1084 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1086 t = tc.FindNestedType (name);
1088 t = TypeManager.GetNestedType (ct, name);
1091 if ((t == null) || !CheckAccessLevel (t))
1095 if (!TypeManager.IsGenericType (current_type))
1098 Type[] args = TypeManager.GetTypeArguments (current_type);
1099 Type[] targs = TypeManager.GetTypeArguments (t);
1100 for (int i = 0; i < args.Length; i++)
1101 targs [i] = args [i];
1103 t = t.MakeGenericType (targs);
1112 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1118 // Public function used to locate types.
1120 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1122 // Returns: Type or null if they type can not be found.
1124 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1126 if (Cache.Contains (name))
1127 return (FullNamedExpression) Cache [name];
1129 FullNamedExpression e;
1130 Type t = LookupNestedTypeInHierarchy (name);
1132 e = new TypeExpression (t, Location.Null);
1133 else if (Parent != null)
1134 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1136 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1143 /// This function is broken and not what you're looking for. It should only
1144 /// be used while the type is still being created since it doesn't use the cache
1145 /// and relies on the filter doing the member name check.
1147 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1148 MemberFilter filter, object criteria);
1151 /// If we have a MemberCache, return it. This property may return null if the
1152 /// class doesn't have a member cache or while it's still being created.
1154 public abstract MemberCache MemberCache {
1158 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1160 if (a.Type == TypeManager.required_attr_type) {
1161 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1164 TypeBuilder.SetCustomAttribute (cb);
1168 // Extensions for generics
1170 TypeParameter[] type_params;
1171 TypeParameter[] type_param_list;
1173 protected string GetInstantiationName ()
1175 StringBuilder sb = new StringBuilder (Name);
1177 for (int i = 0; i < type_param_list.Length; i++) {
1180 sb.Append (type_param_list [i].Name);
1183 return sb.ToString ();
1186 bool check_type_parameter (ArrayList list, int start, string name)
1188 for (int i = 0; i < start; i++) {
1189 TypeParameter param = (TypeParameter) list [i];
1191 if (param.Name != name)
1194 Report.SymbolRelatedToPreviousError (Parent);
1195 // TODO: Location is wrong (parent instead of child)
1196 Report.Warning (693, 3, Location,
1197 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1198 name, Parent.GetSignatureForError ());
1206 TypeParameter[] initialize_type_params ()
1208 if (type_param_list != null)
1209 return type_param_list;
1211 DeclSpace the_parent = Parent;
1212 if (this is GenericMethod)
1216 ArrayList list = new ArrayList ();
1217 if (the_parent != null && the_parent.IsGeneric) {
1218 // FIXME: move generics info out of DeclSpace
1219 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1220 start = parent_params.Length;
1221 list.AddRange (parent_params);
1224 int count = type_params != null ? type_params.Length : 0;
1225 for (int i = 0; i < count; i++) {
1226 TypeParameter param = type_params [i];
1227 check_type_parameter (list, start, param.Name);
1231 type_param_list = new TypeParameter [list.Count];
1232 list.CopyTo (type_param_list, 0);
1233 return type_param_list;
1236 public virtual void SetParameterInfo (ArrayList constraints_list)
1239 if (constraints_list != null) {
1241 80, Location, "Constraints are not allowed " +
1242 "on non-generic declarations");
1248 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1249 type_params = new TypeParameter [names.Length];
1252 // Register all the names
1254 for (int i = 0; i < type_params.Length; i++) {
1255 TypeParameterName name = names [i];
1257 Constraints constraints = null;
1258 if (constraints_list != null) {
1259 int total = constraints_list.Count;
1260 for (int ii = 0; ii < total; ++ii) {
1261 Constraints constraints_at = (Constraints)constraints_list[ii];
1262 // TODO: it is used by iterators only
1263 if (constraints_at == null) {
1264 constraints_list.RemoveAt (ii);
1268 if (constraints_at.TypeParameter == name.Name) {
1269 constraints = constraints_at;
1270 constraints_list.RemoveAt(ii);
1276 type_params [i] = new TypeParameter (
1277 Parent, this, name.Name, constraints, name.OptAttributes,
1280 AddToContainer (type_params [i], name.Name);
1283 if (constraints_list != null && constraints_list.Count > 0) {
1284 foreach (Constraints constraint in constraints_list) {
1285 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1286 GetSignatureForError (), constraint.TypeParameter);
1291 public TypeParameter[] TypeParameters {
1294 throw new InvalidOperationException ();
1295 if ((PartialContainer != null) && (PartialContainer != this))
1296 return PartialContainer.TypeParameters;
1297 if (type_param_list == null)
1298 initialize_type_params ();
1300 return type_param_list;
1304 public TypeParameter[] CurrentTypeParameters {
1307 throw new InvalidOperationException ();
1308 if ((PartialContainer != null) && (PartialContainer != this))
1309 return PartialContainer.CurrentTypeParameters;
1310 if (type_params != null)
1313 return new TypeParameter [0];
1317 public int CountTypeParameters {
1319 return count_type_params;
1323 public int CountCurrentTypeParameters {
1325 return count_current_type_params;
1329 public TypeParameterExpr LookupGeneric (string name, Location loc)
1334 TypeParameter [] current_params;
1335 if (this is TypeContainer)
1336 current_params = PartialContainer.CurrentTypeParameters;
1338 current_params = CurrentTypeParameters;
1340 foreach (TypeParameter type_param in current_params) {
1341 if (type_param.Name == name)
1342 return new TypeParameterExpr (type_param, loc);
1346 return Parent.LookupGeneric (name, loc);
1351 // Used for error reporting only
1352 public virtual Type LookupAnyGeneric (string typeName)
1354 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1357 public override string[] ValidAttributeTargets {
1358 get { return attribute_targets; }
1361 protected override bool VerifyClsCompliance ()
1363 if (!base.VerifyClsCompliance ()) {
1367 if (type_params != null) {
1368 foreach (TypeParameter tp in type_params) {
1369 if (tp.Constraints == null)
1372 tp.Constraints.VerifyClsCompliance ();
1376 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1380 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1381 if (!cache.Contains (lcase)) {
1382 cache.Add (lcase, this);
1386 object val = cache [lcase];
1388 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1391 Report.SymbolRelatedToPreviousError (t);
1394 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1397 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1399 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1406 /// This is a readonly list of MemberInfo's.
1408 public class MemberList : IList {
1409 public readonly IList List;
1413 /// Create a new MemberList from the given IList.
1415 public MemberList (IList list)
1420 this.List = new ArrayList ();
1425 /// Concatenate the ILists `first' and `second' to a new MemberList.
1427 public MemberList (IList first, IList second)
1429 ArrayList list = new ArrayList ();
1430 list.AddRange (first);
1431 list.AddRange (second);
1436 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1439 /// Cast the MemberList into a MemberInfo[] array.
1442 /// This is an expensive operation, only use it if it's really necessary.
1444 public static explicit operator MemberInfo [] (MemberList list)
1446 Timer.StartTimer (TimerType.MiscTimer);
1447 MemberInfo [] result = new MemberInfo [list.Count];
1448 list.CopyTo (result, 0);
1449 Timer.StopTimer (TimerType.MiscTimer);
1461 public bool IsSynchronized {
1463 return List.IsSynchronized;
1467 public object SyncRoot {
1469 return List.SyncRoot;
1473 public void CopyTo (Array array, int index)
1475 List.CopyTo (array, index);
1480 public IEnumerator GetEnumerator ()
1482 return List.GetEnumerator ();
1487 public bool IsFixedSize {
1493 public bool IsReadOnly {
1499 object IList.this [int index] {
1501 return List [index];
1505 throw new NotSupportedException ();
1509 // FIXME: try to find out whether we can avoid the cast in this indexer.
1510 public MemberInfo this [int index] {
1512 return (MemberInfo) List [index];
1516 public int Add (object value)
1518 throw new NotSupportedException ();
1521 public void Clear ()
1523 throw new NotSupportedException ();
1526 public bool Contains (object value)
1528 return List.Contains (value);
1531 public int IndexOf (object value)
1533 return List.IndexOf (value);
1536 public void Insert (int index, object value)
1538 throw new NotSupportedException ();
1541 public void Remove (object value)
1543 throw new NotSupportedException ();
1546 public void RemoveAt (int index)
1548 throw new NotSupportedException ();
1553 /// This interface is used to get all members of a class when creating the
1554 /// member cache. It must be implemented by all DeclSpace derivatives which
1555 /// want to support the member cache and by TypeHandle to get caching of
1556 /// non-dynamic types.
1558 public interface IMemberContainer {
1560 /// The name of the IMemberContainer. This is only used for
1561 /// debugging purposes.
1568 /// The type of this IMemberContainer.
1575 /// Returns the IMemberContainer of the base class or null if this
1576 /// is an interface or TypeManger.object_type.
1577 /// This is used when creating the member cache for a class to get all
1578 /// members from the base class.
1580 MemberCache BaseCache {
1585 /// Whether this is an interface.
1592 /// Returns all members of this class with the corresponding MemberTypes
1593 /// and BindingFlags.
1596 /// When implementing this method, make sure not to return any inherited
1597 /// members and check the MemberTypes and BindingFlags properly.
1598 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1599 /// get the BindingFlags (static/non-static,public/non-public) in the
1600 /// MemberInfo class, but the cache needs this information. That's why
1601 /// this method is called multiple times with different BindingFlags.
1603 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1606 /// Return the container's member cache.
1608 MemberCache MemberCache {
1614 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1615 /// member lookups. It has a member name based hash table; it maps each member
1616 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1617 /// and the BindingFlags that were initially used to get it. The cache contains
1618 /// all members of the current class and all inherited members. If this cache is
1619 /// for an interface types, it also contains all inherited members.
1621 /// There are two ways to get a MemberCache:
1622 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1623 /// use the DeclSpace.MemberCache property.
1624 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1625 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1627 public class MemberCache {
1628 public readonly IMemberContainer Container;
1629 protected Hashtable member_hash;
1630 protected Hashtable method_hash;
1633 /// Create a new MemberCache for the given IMemberContainer `container'.
1635 public MemberCache (IMemberContainer container)
1637 this.Container = container;
1639 Timer.IncrementCounter (CounterType.MemberCache);
1640 Timer.StartTimer (TimerType.CacheInit);
1642 // If we have a base class (we have a base class unless we're
1643 // TypeManager.object_type), we deep-copy its MemberCache here.
1644 if (Container.BaseCache != null)
1645 member_hash = SetupCache (Container.BaseCache);
1647 member_hash = new Hashtable ();
1649 // If this is neither a dynamic type nor an interface, create a special
1650 // method cache with all declared and inherited methods.
1651 Type type = container.Type;
1652 if (!(type is TypeBuilder) && !type.IsInterface &&
1653 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1654 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1655 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1656 method_hash = new Hashtable ();
1660 // Add all members from the current class.
1661 AddMembers (Container);
1663 Timer.StopTimer (TimerType.CacheInit);
1666 public MemberCache (Type[] ifaces)
1669 // The members of this cache all belong to other caches.
1670 // So, 'Container' will not be used.
1672 this.Container = null;
1674 member_hash = new Hashtable ();
1678 foreach (Type itype in ifaces)
1679 AddCacheContents (TypeManager.LookupMemberCache (itype));
1682 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1684 this.Container = container;
1686 // If we have a base class (we have a base class unless we're
1687 // TypeManager.object_type), we deep-copy its MemberCache here.
1688 if (Container.BaseCache != null)
1689 member_hash = SetupCache (Container.BaseCache);
1691 member_hash = new Hashtable ();
1693 if (base_class != null)
1694 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1695 if (ifaces != null) {
1696 foreach (Type itype in ifaces) {
1697 MemberCache cache = TypeManager.LookupMemberCache (itype);
1699 AddCacheContents (cache);
1705 /// Bootstrap this member cache by doing a deep-copy of our base.
1707 static Hashtable SetupCache (MemberCache base_class)
1709 Hashtable hash = new Hashtable ();
1711 if (base_class == null)
1714 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1715 while (it.MoveNext ()) {
1716 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1723 /// Add the contents of `cache' to the member_hash.
1725 void AddCacheContents (MemberCache cache)
1727 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1728 while (it.MoveNext ()) {
1729 ArrayList list = (ArrayList) member_hash [it.Key];
1731 member_hash [it.Key] = list = new ArrayList ();
1733 ArrayList entries = (ArrayList) it.Value;
1734 for (int i = entries.Count-1; i >= 0; i--) {
1735 CacheEntry entry = (CacheEntry) entries [i];
1737 if (entry.Container != cache.Container)
1745 /// Add all members from class `container' to the cache.
1747 void AddMembers (IMemberContainer container)
1749 // We need to call AddMembers() with a single member type at a time
1750 // to get the member type part of CacheEntry.EntryType right.
1751 if (!container.IsInterface) {
1752 AddMembers (MemberTypes.Constructor, container);
1753 AddMembers (MemberTypes.Field, container);
1755 AddMembers (MemberTypes.Method, container);
1756 AddMembers (MemberTypes.Property, container);
1757 AddMembers (MemberTypes.Event, container);
1758 // Nested types are returned by both Static and Instance searches.
1759 AddMembers (MemberTypes.NestedType,
1760 BindingFlags.Static | BindingFlags.Public, container);
1761 AddMembers (MemberTypes.NestedType,
1762 BindingFlags.Static | BindingFlags.NonPublic, container);
1765 void AddMembers (MemberTypes mt, IMemberContainer container)
1767 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1768 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1769 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1770 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1773 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1774 string name, MemberInfo member)
1776 // We use a name-based hash table of ArrayList's.
1777 ArrayList list = (ArrayList) member_hash [name];
1779 list = new ArrayList ();
1780 member_hash.Add (name, list);
1783 // When this method is called for the current class, the list will
1784 // already contain all inherited members from our base classes.
1785 // We cannot add new members in front of the list since this'd be an
1786 // expensive operation, that's why the list is sorted in reverse order
1787 // (ie. members from the current class are coming last).
1788 list.Add (new CacheEntry (container, member, mt, bf));
1792 /// Add all members from class `container' with the requested MemberTypes and
1793 /// BindingFlags to the cache. This method is called multiple times with different
1794 /// MemberTypes and BindingFlags.
1796 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1798 MemberList members = container.GetMembers (mt, bf);
1800 foreach (MemberInfo member in members) {
1801 string name = member.Name;
1803 AddMember (mt, bf, container, name, member);
1805 if (member is MethodInfo) {
1806 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1808 AddMember (mt, bf, container, gname, member);
1814 /// Add all declared and inherited methods from class `type' to the method cache.
1816 void AddMethods (Type type)
1818 AddMethods (BindingFlags.Static | BindingFlags.Public |
1819 BindingFlags.FlattenHierarchy, type);
1820 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1821 BindingFlags.FlattenHierarchy, type);
1822 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1823 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1826 static ArrayList overrides = new ArrayList ();
1828 void AddMethods (BindingFlags bf, Type type)
1830 MethodBase [] members = type.GetMethods (bf);
1832 Array.Reverse (members);
1834 foreach (MethodBase member in members) {
1835 string name = member.Name;
1837 // We use a name-based hash table of ArrayList's.
1838 ArrayList list = (ArrayList) method_hash [name];
1840 list = new ArrayList ();
1841 method_hash.Add (name, list);
1844 MethodInfo curr = (MethodInfo) member;
1845 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1846 MethodInfo base_method = curr.GetBaseDefinition ();
1848 if (base_method == curr)
1849 // Not every virtual function needs to have a NewSlot flag.
1852 overrides.Add (curr);
1853 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1857 if (overrides.Count > 0) {
1858 for (int i = 0; i < overrides.Count; ++i)
1859 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1863 // Unfortunately, the elements returned by Type.GetMethods() aren't
1864 // sorted so we need to do this check for every member.
1865 BindingFlags new_bf = bf;
1866 if (member.DeclaringType == type)
1867 new_bf |= BindingFlags.DeclaredOnly;
1869 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1874 /// Compute and return a appropriate `EntryType' magic number for the given
1875 /// MemberTypes and BindingFlags.
1877 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1879 EntryType type = EntryType.None;
1881 if ((mt & MemberTypes.Constructor) != 0)
1882 type |= EntryType.Constructor;
1883 if ((mt & MemberTypes.Event) != 0)
1884 type |= EntryType.Event;
1885 if ((mt & MemberTypes.Field) != 0)
1886 type |= EntryType.Field;
1887 if ((mt & MemberTypes.Method) != 0)
1888 type |= EntryType.Method;
1889 if ((mt & MemberTypes.Property) != 0)
1890 type |= EntryType.Property;
1891 // Nested types are returned by static and instance searches.
1892 if ((mt & MemberTypes.NestedType) != 0)
1893 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1895 if ((bf & BindingFlags.Instance) != 0)
1896 type |= EntryType.Instance;
1897 if ((bf & BindingFlags.Static) != 0)
1898 type |= EntryType.Static;
1899 if ((bf & BindingFlags.Public) != 0)
1900 type |= EntryType.Public;
1901 if ((bf & BindingFlags.NonPublic) != 0)
1902 type |= EntryType.NonPublic;
1903 if ((bf & BindingFlags.DeclaredOnly) != 0)
1904 type |= EntryType.Declared;
1910 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1911 /// denote multiple member types. Returns true if the given flags value denotes a
1912 /// single member types.
1914 public static bool IsSingleMemberType (MemberTypes mt)
1917 case MemberTypes.Constructor:
1918 case MemberTypes.Event:
1919 case MemberTypes.Field:
1920 case MemberTypes.Method:
1921 case MemberTypes.Property:
1922 case MemberTypes.NestedType:
1931 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1932 /// number to speed up the searching process.
1935 protected enum EntryType {
1940 MaskStatic = Instance|Static,
1944 MaskProtection = Public|NonPublic,
1948 Constructor = 0x020,
1955 NotExtensionMethod = 0x800,
1957 MaskType = Constructor|Event|Field|Method|Property|NestedType
1960 protected class CacheEntry {
1961 public readonly IMemberContainer Container;
1962 public EntryType EntryType;
1963 public readonly MemberInfo Member;
1965 public CacheEntry (IMemberContainer container, MemberInfo member,
1966 MemberTypes mt, BindingFlags bf)
1968 this.Container = container;
1969 this.Member = member;
1970 this.EntryType = GetEntryType (mt, bf);
1973 public override string ToString ()
1975 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1981 /// This is called each time we're walking up one level in the class hierarchy
1982 /// and checks whether we can abort the search since we've already found what
1983 /// we were looking for.
1985 protected bool DoneSearching (ArrayList list)
1988 // We've found exactly one member in the current class and it's not
1989 // a method or constructor.
1991 if (list.Count == 1 && !(list [0] is MethodBase))
1995 // Multiple properties: we query those just to find out the indexer
1998 if ((list.Count > 0) && (list [0] is PropertyInfo))
2005 /// Looks up members with name `name'. If you provide an optional
2006 /// filter function, it'll only be called with members matching the
2007 /// requested member name.
2009 /// This method will try to use the cache to do the lookup if possible.
2011 /// Unlike other FindMembers implementations, this method will always
2012 /// check all inherited members - even when called on an interface type.
2014 /// If you know that you're only looking for methods, you should use
2015 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2016 /// When doing a method-only search, it'll try to use a special method
2017 /// cache (unless it's a dynamic type or an interface) and the returned
2018 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2019 /// The lookup process will automatically restart itself in method-only
2020 /// search mode if it discovers that it's about to return methods.
2022 ArrayList global = new ArrayList ();
2023 bool using_global = false;
2025 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2027 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2028 MemberFilter filter, object criteria)
2031 throw new Exception ();
2033 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2034 bool method_search = mt == MemberTypes.Method;
2035 // If we have a method cache and we aren't already doing a method-only search,
2036 // then we restart a method search if the first match is a method.
2037 bool do_method_search = !method_search && (method_hash != null);
2039 ArrayList applicable;
2041 // If this is a method-only search, we try to use the method cache if
2042 // possible; a lookup in the method cache will return a MemberInfo with
2043 // the correct ReflectedType for inherited methods.
2045 if (method_search && (method_hash != null))
2046 applicable = (ArrayList) method_hash [name];
2048 applicable = (ArrayList) member_hash [name];
2050 if (applicable == null)
2051 return emptyMemberInfo;
2054 // 32 slots gives 53 rss/54 size
2055 // 2/4 slots gives 55 rss
2057 // Strange: from 25,000 calls, only 1,800
2058 // are above 2. Why does this impact it?
2061 using_global = true;
2063 Timer.StartTimer (TimerType.CachedLookup);
2065 EntryType type = GetEntryType (mt, bf);
2067 IMemberContainer current = Container;
2069 bool do_interface_search = current.IsInterface;
2071 // `applicable' is a list of all members with the given member name `name'
2072 // in the current class and all its base classes. The list is sorted in
2073 // reverse order due to the way how the cache is initialy created (to speed
2074 // things up, we're doing a deep-copy of our base).
2076 for (int i = applicable.Count-1; i >= 0; i--) {
2077 CacheEntry entry = (CacheEntry) applicable [i];
2079 // This happens each time we're walking one level up in the class
2080 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2081 // the first time this happens (this may already happen in the first
2082 // iteration of this loop if there are no members with the name we're
2083 // looking for in the current class).
2084 if (entry.Container != current) {
2088 if (!do_interface_search && DoneSearching (global))
2091 current = entry.Container;
2094 // Is the member of the correct type ?
2095 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2098 // Is the member static/non-static ?
2099 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2102 // Apply the filter to it.
2103 if (filter (entry.Member, criteria)) {
2104 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2105 do_method_search = false;
2108 // Because interfaces support multiple inheritance we have to be sure that
2109 // base member is from same interface, so only top level member will be returned
2110 if (do_interface_search && global.Count > 0) {
2111 bool member_already_exists = false;
2113 foreach (MemberInfo mi in global) {
2114 if (mi is MethodBase)
2117 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2118 member_already_exists = true;
2122 if (member_already_exists)
2126 global.Add (entry.Member);
2130 Timer.StopTimer (TimerType.CachedLookup);
2132 // If we have a method cache and we aren't already doing a method-only
2133 // search, we restart in method-only search mode if the first match is
2134 // a method. This ensures that we return a MemberInfo with the correct
2135 // ReflectedType for inherited methods.
2136 if (do_method_search && (global.Count > 0)){
2137 using_global = false;
2139 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2142 using_global = false;
2143 MemberInfo [] copy = new MemberInfo [global.Count];
2144 global.CopyTo (copy);
2149 /// Returns true if iterface exists in any base interfaces (ifaces)
2151 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2153 foreach (Type iface in ifaces) {
2154 if (iface == ifaceToFind)
2157 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2158 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2164 // find the nested type @name in @this.
2165 public Type FindNestedType (string name)
2167 ArrayList applicable = (ArrayList) member_hash [name];
2168 if (applicable == null)
2171 for (int i = applicable.Count-1; i >= 0; i--) {
2172 CacheEntry entry = (CacheEntry) applicable [i];
2173 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2174 return (Type) entry.Member;
2180 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2182 ArrayList applicable = (ArrayList) member_hash [name];
2183 if (applicable == null)
2187 // Walk the chain of events, starting from the top.
2189 for (int i = applicable.Count - 1; i >= 0; i--)
2191 CacheEntry entry = (CacheEntry) applicable [i];
2192 if ((entry.EntryType & EntryType.Event) == 0)
2195 EventInfo ei = (EventInfo)entry.Member;
2196 return ei.GetAddMethod (true);
2203 // Looks for extension methods with defined name and extension type
2205 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2208 if (method_hash != null)
2209 entries = (ArrayList)method_hash [name];
2211 entries = (ArrayList)member_hash [name];
2213 if (entries == null)
2216 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2218 entry_type |= EntryType.Public;
2220 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2222 ArrayList candidates = null;
2223 foreach (CacheEntry entry in entries) {
2224 if ((entry.EntryType & entry_type) == found_entry_type) {
2225 MethodBase mb = (MethodBase)entry.Member;
2227 IMethodData md = TypeManager.GetMethod (mb);
2228 ParameterData pd = md == null ?
2229 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2231 Type ex_type = pd.ExtensionMethodType;
2232 if (ex_type == null) {
2233 entry.EntryType |= EntryType.NotExtensionMethod;
2237 //if (implicit conversion between ex_type and extensionType exist) {
2238 if (candidates == null)
2239 candidates = new ArrayList (2);
2240 candidates.Add (mb);
2249 // This finds the method or property for us to override. invocation_type is the type where
2250 // the override is going to be declared, name is the name of the method/property, and
2251 // param_types is the parameters, if any to the method or property
2253 // Because the MemberCache holds members from this class and all the base classes,
2254 // we can avoid tons of reflection stuff.
2256 public MemberInfo FindMemberToOverride (Type invocation_type, string name, Type [] param_types, GenericMethod generic_method, bool is_property)
2258 ArrayList applicable;
2259 if (method_hash != null && !is_property)
2260 applicable = (ArrayList) method_hash [name];
2262 applicable = (ArrayList) member_hash [name];
2264 if (applicable == null)
2267 // Walk the chain of methods, starting from the top.
2269 for (int i = applicable.Count - 1; i >= 0; i--) {
2270 CacheEntry entry = (CacheEntry) applicable [i];
2272 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2275 PropertyInfo pi = null;
2276 MethodInfo mi = null;
2277 FieldInfo fi = null;
2278 Type [] cmp_attrs = null;
2281 if ((entry.EntryType & EntryType.Field) != 0) {
2282 fi = (FieldInfo)entry.Member;
2284 // TODO: For this case we ignore member type
2285 //fb = TypeManager.GetField (fi);
2286 //cmp_attrs = new Type[] { fb.MemberType };
2288 pi = (PropertyInfo) entry.Member;
2289 cmp_attrs = TypeManager.GetArgumentTypes (pi);
2292 mi = (MethodInfo) entry.Member;
2293 cmp_attrs = TypeManager.GetParameterData (mi).Types;
2297 // TODO: Almost duplicate !
2299 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2300 case FieldAttributes.PrivateScope:
2302 case FieldAttributes.Private:
2304 // A private method is Ok if we are a nested subtype.
2305 // The spec actually is not very clear about this, see bug 52458.
2307 if (!invocation_type.Equals (entry.Container.Type) &&
2308 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2311 case FieldAttributes.FamANDAssem:
2312 case FieldAttributes.Assembly:
2314 // Check for assembly methods
2316 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2320 return entry.Member;
2324 // Check the arguments
2326 if (cmp_attrs.Length != param_types.Length)
2330 for (j = 0; j < cmp_attrs.Length; ++j)
2331 if (!TypeManager.IsEqual (param_types [j], cmp_attrs [j]))
2333 if (j < cmp_attrs.Length)
2337 // check generic arguments for methods
2340 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2341 if (generic_method == null && cmpGenArgs.Length != 0)
2343 if (generic_method != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2348 // get one of the methods because this has the visibility info.
2351 mi = pi.GetGetMethod (true);
2353 mi = pi.GetSetMethod (true);
2359 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2360 case MethodAttributes.PrivateScope:
2362 case MethodAttributes.Private:
2364 // A private method is Ok if we are a nested subtype.
2365 // The spec actually is not very clear about this, see bug 52458.
2367 if (!invocation_type.Equals (entry.Container.Type) &&
2368 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2371 case MethodAttributes.FamANDAssem:
2372 case MethodAttributes.Assembly:
2374 // Check for assembly methods
2376 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2380 return entry.Member;
2387 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2388 /// We handle two cases. The first is for types without parameters (events, field, properties).
2389 /// The second are methods, indexers and this is why ignore_complex_types is here.
2390 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2392 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2394 ArrayList applicable = null;
2396 if (method_hash != null)
2397 applicable = (ArrayList) method_hash [name];
2399 if (applicable != null) {
2400 for (int i = applicable.Count - 1; i >= 0; i--) {
2401 CacheEntry entry = (CacheEntry) applicable [i];
2402 if ((entry.EntryType & EntryType.Public) != 0)
2403 return entry.Member;
2407 if (member_hash == null)
2409 applicable = (ArrayList) member_hash [name];
2411 if (applicable != null) {
2412 for (int i = applicable.Count - 1; i >= 0; i--) {
2413 CacheEntry entry = (CacheEntry) applicable [i];
2414 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2415 if (ignore_complex_types) {
2416 if ((entry.EntryType & EntryType.Method) != 0)
2419 // Does exist easier way how to detect indexer ?
2420 if ((entry.EntryType & EntryType.Property) != 0) {
2421 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2422 if (arg_types.Length > 0)
2426 return entry.Member;
2433 Hashtable locase_table;
2436 /// Builds low-case table for CLS Compliance test
2438 public Hashtable GetPublicMembers ()
2440 if (locase_table != null)
2441 return locase_table;
2443 locase_table = new Hashtable ();
2444 foreach (DictionaryEntry entry in member_hash) {
2445 ArrayList members = (ArrayList)entry.Value;
2446 for (int ii = 0; ii < members.Count; ++ii) {
2447 CacheEntry member_entry = (CacheEntry) members [ii];
2449 if ((member_entry.EntryType & EntryType.Public) == 0)
2452 // TODO: Does anyone know easier way how to detect that member is internal ?
2453 switch (member_entry.EntryType & EntryType.MaskType) {
2454 case EntryType.Constructor:
2457 case EntryType.Field:
2458 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2462 case EntryType.Method:
2463 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2467 case EntryType.Property:
2468 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2469 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2473 case EntryType.Event:
2474 EventInfo ei = (EventInfo)member_entry.Member;
2475 MethodInfo mi = ei.GetAddMethod ();
2476 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2480 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2481 locase_table [lcase] = member_entry.Member;
2485 return locase_table;
2488 public Hashtable Members {
2495 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2498 // TODO: refactor as method is always 'this'
2499 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2501 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2503 for (int i = 0; i < al.Count; ++i) {
2504 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2507 if (entry.Member == this_builder)
2510 if ((entry.EntryType & tested_type) != tested_type)
2513 MethodBase method_to_compare = (MethodBase)entry.Member;
2514 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2515 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2517 if (result == AttributeTester.Result.Ok)
2520 IMethodData md = TypeManager.GetMethod (method_to_compare);
2522 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2523 // However it is exactly what csc does.
2524 if (md != null && !md.IsClsComplianceRequired ())
2527 Report.SymbolRelatedToPreviousError (entry.Member);
2529 case AttributeTester.Result.RefOutArrayError:
2530 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2532 case AttributeTester.Result.ArrayArrayError:
2533 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2537 throw new NotImplementedException (result.ToString ());