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 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
563 public virtual bool IsOverloadable {
569 public void EnableOverloadChecks ()
571 caching_flags |= Flags.TestMethodDuplication;
575 /// The main virtual method for CLS-Compliant verifications.
576 /// The method returns true if member is CLS-Compliant and false if member is not
577 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
578 /// and add their extra verifications.
580 protected virtual bool VerifyClsCompliance ()
582 if (!IsClsComplianceRequired ()) {
583 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
584 if (!IsExposedFromAssembly ())
585 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
586 if (!CodeGen.Assembly.IsClsCompliant)
587 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
592 if (HasClsCompliantAttribute) {
593 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
594 Report.Error (3014, Location,
595 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
596 GetSignatureForError ());
600 if (!Parent.IsClsComplianceRequired ()) {
601 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
602 GetSignatureForError (), Parent.GetSignatureForError ());
607 if (member_name.Name [0] == '_') {
608 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
614 // Raised (and passed an XmlElement that contains the comment)
615 // when GenerateDocComment is writing documentation expectedly.
617 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
622 // Returns a string that represents the signature for this
623 // member which should be used in XML documentation.
625 public virtual string GetDocCommentName (DeclSpace ds)
627 if (ds == null || this is DeclSpace)
628 return DocCommentHeader + Name;
630 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
634 // Generates xml doc comments (if any), and if required,
635 // handle warning report.
637 internal virtual void GenerateDocComment (DeclSpace ds)
639 DocUtil.GenerateDocComment (this, ds);
642 public override IResolveContext ResolveContext {
646 #region IResolveContext Members
648 public DeclSpace DeclContainer {
649 get { return Parent; }
652 public virtual DeclSpace GenericDeclContainer {
653 get { return DeclContainer; }
656 public bool IsInObsoleteScope {
658 if (GetObsoleteAttribute () != null)
661 return Parent == null ? false : Parent.IsInObsoleteScope;
665 public bool IsInUnsafeScope {
667 if ((ModFlags & Modifiers.UNSAFE) != 0)
670 return Parent == null ? false : Parent.IsInUnsafeScope;
678 /// Base class for structs, classes, enumerations and interfaces.
681 /// They all create new declaration spaces. This
682 /// provides the common foundation for managing those name
685 public abstract class DeclSpace : MemberCore {
687 /// This points to the actual definition that is being
688 /// created with System.Reflection.Emit
690 public TypeBuilder TypeBuilder;
693 /// If we are a generic type, this is the type we are
694 /// currently defining. We need to lookup members on this
695 /// instead of the TypeBuilder.
697 public Type CurrentType;
700 // This is the namespace in which this typecontainer
701 // was declared. We use this to resolve names.
703 public NamespaceEntry NamespaceEntry;
705 private Hashtable Cache = new Hashtable ();
707 public readonly string Basename;
709 protected Hashtable defined_names;
711 public TypeContainer PartialContainer;
713 readonly bool is_generic;
714 readonly int count_type_params;
715 readonly int count_current_type_params;
718 // Whether we are Generic
720 public bool IsGeneric {
724 else if (Parent != null)
725 return Parent.IsGeneric;
731 static string[] attribute_targets = new string [] { "type" };
733 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
735 : base (parent, name, attrs)
738 Basename = name.Basename;
739 defined_names = new Hashtable ();
740 PartialContainer = null;
741 if (name.TypeArguments != null) {
743 count_type_params = count_current_type_params = name.TypeArguments.Count;
746 count_type_params += parent.count_type_params;
749 public override DeclSpace GenericDeclContainer {
754 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
756 protected virtual bool AddToContainer (MemberCore symbol, string name)
758 MemberCore mc = (MemberCore) defined_names [name];
761 defined_names.Add (name, symbol);
765 if (symbol.IsOverloadable && mc.IsOverloadable) {
767 // Enable both symbols check for indexers, because we don't know which one came first
769 if (symbol is Indexer.SetIndexerMethod || symbol is Indexer.GetIndexerMethod)
770 mc.EnableOverloadChecks ();
772 symbol.EnableOverloadChecks ();
776 Report.SymbolRelatedToPreviousError (mc);
777 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
778 Error_MissingPartialModifier (symbol);
782 if (this is RootTypes) {
783 Report.Error (101, symbol.Location,
784 "The namespace `{0}' already contains a definition for `{1}'",
785 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
786 } else if (symbol is TypeParameter) {
787 Report.Error (692, symbol.Location,
788 "Duplicate type parameter `{0}'", name);
790 Report.Error (102, symbol.Location,
791 "The type `{0}' already contains a definition for `{1}'",
792 GetSignatureForError (), symbol.MemberName.Name);
799 /// Returns the MemberCore associated with a given name in the declaration
800 /// space. It doesn't return method based symbols !!
803 public MemberCore GetDefinition (string name)
805 return (MemberCore)defined_names [name];
808 public bool IsStaticClass {
809 get { return (ModFlags & Modifiers.STATIC) != 0; }
813 // root_types contains all the types. All TopLevel types
814 // hence have a parent that points to `root_types', that is
815 // why there is a non-obvious test down here.
817 public bool IsTopLevel {
818 get { return (Parent != null && Parent.Parent == null); }
821 public virtual void CloseType ()
823 if ((caching_flags & Flags.CloseTypeCreated) == 0){
825 TypeBuilder.CreateType ();
828 // The try/catch is needed because
829 // nested enumerations fail to load when they
832 // Even if this is the right order (enumerations
833 // declared after types).
835 // Note that this still creates the type and
836 // it is possible to save it
838 caching_flags |= Flags.CloseTypeCreated;
842 protected virtual TypeAttributes TypeAttr {
843 get { return CodeGen.Module.DefaultCharSetType; }
847 /// Should be overriten by the appropriate declaration space
849 public abstract TypeBuilder DefineType ();
852 /// Define all members, but don't apply any attributes or do anything which may
853 /// access not-yet-defined classes. This method also creates the MemberCache.
855 public virtual bool DefineMembers ()
857 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
858 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
864 protected void Error_MissingPartialModifier (MemberCore type)
866 Report.Error (260, type.Location,
867 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
868 type.GetSignatureForError ());
871 public override string GetSignatureForError ()
874 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
876 // Parent.GetSignatureForError
880 public bool CheckAccessLevel (Type check_type)
883 if (this is GenericMethod)
884 tb = Parent.TypeBuilder;
888 check_type = TypeManager.DropGenericTypeArguments (check_type);
889 if (check_type == tb)
892 if (TypeBuilder == null)
893 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
894 // However, this is invoked again later -- so safe to return true.
895 // May also be null when resolving top-level attributes.
899 // Broken Microsoft runtime, return public for arrays, no matter what
900 // the accessibility is for their underlying class, and they return
901 // NonPublic visibility for pointers
903 if (check_type.IsArray || check_type.IsPointer)
904 return CheckAccessLevel (TypeManager.GetElementType (check_type));
906 if (TypeManager.IsGenericParameter(check_type))
907 return true; // FIXME
909 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
912 case TypeAttributes.Public:
915 case TypeAttributes.NotPublic:
917 if (TypeBuilder == null)
918 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
919 // However, this is invoked again later -- so safe to return true.
920 // May also be null when resolving top-level attributes.
923 // This test should probably use the declaringtype.
925 return check_type.Assembly == TypeBuilder.Assembly ||
926 TypeManager.IsFriendAssembly (check_type.Assembly);
928 case TypeAttributes.NestedPublic:
931 case TypeAttributes.NestedPrivate:
932 return NestedAccessible (tb, check_type);
934 case TypeAttributes.NestedFamily:
936 // Only accessible to methods in current type or any subtypes
938 return FamilyAccessible (tb, check_type);
940 case TypeAttributes.NestedFamANDAssem:
941 return ((check_type.Assembly == tb.Assembly) ||
942 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
943 FamilyAccessible (tb, check_type);
945 case TypeAttributes.NestedFamORAssem:
946 return (check_type.Assembly == tb.Assembly) ||
947 FamilyAccessible (tb, check_type) ||
948 TypeManager.IsFriendAssembly (check_type.Assembly);
950 case TypeAttributes.NestedAssembly:
951 return check_type.Assembly == tb.Assembly ||
952 TypeManager.IsFriendAssembly (check_type.Assembly);
955 Console.WriteLine ("HERE: " + check_attr);
960 protected bool NestedAccessible (Type tb, Type check_type)
962 Type declaring = check_type.DeclaringType;
963 return TypeBuilder == declaring ||
964 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
967 protected bool FamilyAccessible (Type tb, Type check_type)
969 Type declaring = check_type.DeclaringType;
970 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
973 // Access level of a type.
975 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
976 // Public Assembly Protected
977 Protected = (0 << 0) | (0 << 1) | (X << 2),
978 Public = (X << 0) | (X << 1) | (X << 2),
979 Private = (0 << 0) | (0 << 1) | (0 << 2),
980 Internal = (0 << 0) | (X << 1) | (0 << 2),
981 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
984 static AccessLevel GetAccessLevelFromModifiers (int flags)
986 if ((flags & Modifiers.INTERNAL) != 0) {
988 if ((flags & Modifiers.PROTECTED) != 0)
989 return AccessLevel.ProtectedOrInternal;
991 return AccessLevel.Internal;
993 } else if ((flags & Modifiers.PROTECTED) != 0)
994 return AccessLevel.Protected;
995 else if ((flags & Modifiers.PRIVATE) != 0)
996 return AccessLevel.Private;
998 return AccessLevel.Public;
1001 // What is the effective access level of this?
1002 // TODO: Cache this?
1003 AccessLevel EffectiveAccessLevel {
1005 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1006 if (!IsTopLevel && (Parent != null))
1007 return myAccess & Parent.EffectiveAccessLevel;
1012 // Return the access level for type `t'
1013 static AccessLevel TypeEffectiveAccessLevel (Type t)
1016 return AccessLevel.Public;
1017 if (t.IsNestedPrivate)
1018 return AccessLevel.Private;
1020 return AccessLevel.Internal;
1022 // By now, it must be nested
1023 AccessLevel parent_level = TypeEffectiveAccessLevel (t.DeclaringType);
1025 if (t.IsNestedPublic)
1026 return parent_level;
1027 if (t.IsNestedAssembly)
1028 return parent_level & AccessLevel.Internal;
1029 if (t.IsNestedFamily)
1030 return parent_level & AccessLevel.Protected;
1031 if (t.IsNestedFamORAssem)
1032 return parent_level & AccessLevel.ProtectedOrInternal;
1033 if (t.IsNestedFamANDAssem)
1034 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1036 // nested private is taken care of
1038 throw new Exception ("I give up, what are you?");
1042 // This answers `is the type P, as accessible as a member M which has the
1043 // accessability @flags which is declared as a nested member of the type T, this declspace'
1045 public bool AsAccessible (Type p, int flags)
1048 // 1) if M is private, its accessability is the same as this declspace.
1049 // we already know that P is accessible to T before this method, so we
1053 if ((flags & Modifiers.PRIVATE) != 0)
1056 while (p.IsArray || p.IsPointer || p.IsByRef)
1057 p = TypeManager.GetElementType (p);
1060 if (p.IsGenericParameter)
1063 if (TypeManager.IsGenericType (p)) {
1064 foreach (Type t in p.GetGenericArguments ()) {
1065 if (!AsAccessible (t, flags))
1070 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1071 AccessLevel mAccess = this.EffectiveAccessLevel &
1072 GetAccessLevelFromModifiers (flags);
1074 // for every place from which we can access M, we must
1075 // be able to access P as well. So, we want
1076 // For every bit in M and P, M_i -> P_1 == true
1077 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1079 return ~ (~ mAccess | pAccess) == 0;
1082 private Type LookupNestedTypeInHierarchy (string name)
1084 // if the member cache has been created, lets use it.
1085 // the member cache is MUCH faster.
1086 if (MemberCache != null)
1087 return MemberCache.FindNestedType (name);
1089 // no member cache. Do it the hard way -- reflection
1091 for (Type current_type = TypeBuilder;
1092 current_type != null && current_type != TypeManager.object_type;
1093 current_type = current_type.BaseType) {
1095 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1096 if (ct is TypeBuilder) {
1097 TypeContainer tc = ct == TypeBuilder
1098 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1100 t = tc.FindNestedType (name);
1102 t = TypeManager.GetNestedType (ct, name);
1105 if ((t == null) || !CheckAccessLevel (t))
1109 if (!TypeManager.IsGenericType (current_type))
1112 Type[] args = TypeManager.GetTypeArguments (current_type);
1113 Type[] targs = TypeManager.GetTypeArguments (t);
1114 for (int i = 0; i < args.Length; i++)
1115 targs [i] = args [i];
1117 t = t.MakeGenericType (targs);
1126 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1132 // Public function used to locate types.
1134 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1136 // Returns: Type or null if they type can not be found.
1138 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1140 if (Cache.Contains (name))
1141 return (FullNamedExpression) Cache [name];
1143 FullNamedExpression e;
1144 Type t = LookupNestedTypeInHierarchy (name);
1146 e = new TypeExpression (t, Location.Null);
1147 else if (Parent != null)
1148 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1150 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1157 /// This function is broken and not what you're looking for. It should only
1158 /// be used while the type is still being created since it doesn't use the cache
1159 /// and relies on the filter doing the member name check.
1161 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1162 MemberFilter filter, object criteria);
1165 /// If we have a MemberCache, return it. This property may return null if the
1166 /// class doesn't have a member cache or while it's still being created.
1168 public abstract MemberCache MemberCache {
1172 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1174 if (a.Type == TypeManager.required_attr_type) {
1175 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1178 TypeBuilder.SetCustomAttribute (cb);
1182 // Extensions for generics
1184 TypeParameter[] type_params;
1185 TypeParameter[] type_param_list;
1187 protected string GetInstantiationName ()
1189 StringBuilder sb = new StringBuilder (Name);
1191 for (int i = 0; i < type_param_list.Length; i++) {
1194 sb.Append (type_param_list [i].Name);
1197 return sb.ToString ();
1200 bool check_type_parameter (ArrayList list, int start, string name)
1202 for (int i = 0; i < start; i++) {
1203 TypeParameter param = (TypeParameter) list [i];
1205 if (param.Name != name)
1208 Report.SymbolRelatedToPreviousError (Parent);
1209 // TODO: Location is wrong (parent instead of child)
1210 Report.Warning (693, 3, Location,
1211 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1212 name, Parent.GetSignatureForError ());
1220 TypeParameter[] initialize_type_params ()
1222 if (type_param_list != null)
1223 return type_param_list;
1225 DeclSpace the_parent = Parent;
1226 if (this is GenericMethod)
1230 ArrayList list = new ArrayList ();
1231 if (the_parent != null && the_parent.IsGeneric) {
1232 // FIXME: move generics info out of DeclSpace
1233 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1234 start = parent_params.Length;
1235 list.AddRange (parent_params);
1238 int count = type_params != null ? type_params.Length : 0;
1239 for (int i = 0; i < count; i++) {
1240 TypeParameter param = type_params [i];
1241 check_type_parameter (list, start, param.Name);
1245 type_param_list = new TypeParameter [list.Count];
1246 list.CopyTo (type_param_list, 0);
1247 return type_param_list;
1250 public virtual void SetParameterInfo (ArrayList constraints_list)
1253 if (constraints_list != null) {
1255 80, Location, "Constraints are not allowed " +
1256 "on non-generic declarations");
1262 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1263 type_params = new TypeParameter [names.Length];
1266 // Register all the names
1268 for (int i = 0; i < type_params.Length; i++) {
1269 TypeParameterName name = names [i];
1271 Constraints constraints = null;
1272 if (constraints_list != null) {
1273 int total = constraints_list.Count;
1274 for (int ii = 0; ii < total; ++ii) {
1275 Constraints constraints_at = (Constraints)constraints_list[ii];
1276 // TODO: it is used by iterators only
1277 if (constraints_at == null) {
1278 constraints_list.RemoveAt (ii);
1282 if (constraints_at.TypeParameter == name.Name) {
1283 constraints = constraints_at;
1284 constraints_list.RemoveAt(ii);
1290 type_params [i] = new TypeParameter (
1291 Parent, this, name.Name, constraints, name.OptAttributes,
1294 AddToContainer (type_params [i], name.Name);
1297 if (constraints_list != null && constraints_list.Count > 0) {
1298 foreach (Constraints constraint in constraints_list) {
1299 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1300 GetSignatureForError (), constraint.TypeParameter);
1305 public TypeParameter[] TypeParameters {
1308 throw new InvalidOperationException ();
1309 if ((PartialContainer != null) && (PartialContainer != this))
1310 return PartialContainer.TypeParameters;
1311 if (type_param_list == null)
1312 initialize_type_params ();
1314 return type_param_list;
1318 public TypeParameter[] CurrentTypeParameters {
1321 throw new InvalidOperationException ();
1322 if ((PartialContainer != null) && (PartialContainer != this))
1323 return PartialContainer.CurrentTypeParameters;
1324 if (type_params != null)
1327 return new TypeParameter [0];
1331 public int CountTypeParameters {
1333 return count_type_params;
1337 public int CountCurrentTypeParameters {
1339 return count_current_type_params;
1343 public TypeParameterExpr LookupGeneric (string name, Location loc)
1348 TypeParameter [] current_params;
1349 if (this is TypeContainer)
1350 current_params = PartialContainer.CurrentTypeParameters;
1352 current_params = CurrentTypeParameters;
1354 foreach (TypeParameter type_param in current_params) {
1355 if (type_param.Name == name)
1356 return new TypeParameterExpr (type_param, loc);
1360 return Parent.LookupGeneric (name, loc);
1365 // Used for error reporting only
1366 public virtual Type LookupAnyGeneric (string typeName)
1368 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1371 public override string[] ValidAttributeTargets {
1372 get { return attribute_targets; }
1375 protected override bool VerifyClsCompliance ()
1377 if (!base.VerifyClsCompliance ()) {
1381 if (type_params != null) {
1382 foreach (TypeParameter tp in type_params) {
1383 if (tp.Constraints == null)
1386 tp.Constraints.VerifyClsCompliance ();
1390 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1394 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1395 if (!cache.Contains (lcase)) {
1396 cache.Add (lcase, this);
1400 object val = cache [lcase];
1402 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1405 Report.SymbolRelatedToPreviousError (t);
1408 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1411 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1413 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1420 /// This is a readonly list of MemberInfo's.
1422 public class MemberList : IList {
1423 public readonly IList List;
1427 /// Create a new MemberList from the given IList.
1429 public MemberList (IList list)
1434 this.List = new ArrayList ();
1439 /// Concatenate the ILists `first' and `second' to a new MemberList.
1441 public MemberList (IList first, IList second)
1443 ArrayList list = new ArrayList ();
1444 list.AddRange (first);
1445 list.AddRange (second);
1450 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1453 /// Cast the MemberList into a MemberInfo[] array.
1456 /// This is an expensive operation, only use it if it's really necessary.
1458 public static explicit operator MemberInfo [] (MemberList list)
1460 Timer.StartTimer (TimerType.MiscTimer);
1461 MemberInfo [] result = new MemberInfo [list.Count];
1462 list.CopyTo (result, 0);
1463 Timer.StopTimer (TimerType.MiscTimer);
1475 public bool IsSynchronized {
1477 return List.IsSynchronized;
1481 public object SyncRoot {
1483 return List.SyncRoot;
1487 public void CopyTo (Array array, int index)
1489 List.CopyTo (array, index);
1494 public IEnumerator GetEnumerator ()
1496 return List.GetEnumerator ();
1501 public bool IsFixedSize {
1507 public bool IsReadOnly {
1513 object IList.this [int index] {
1515 return List [index];
1519 throw new NotSupportedException ();
1523 // FIXME: try to find out whether we can avoid the cast in this indexer.
1524 public MemberInfo this [int index] {
1526 return (MemberInfo) List [index];
1530 public int Add (object value)
1532 throw new NotSupportedException ();
1535 public void Clear ()
1537 throw new NotSupportedException ();
1540 public bool Contains (object value)
1542 return List.Contains (value);
1545 public int IndexOf (object value)
1547 return List.IndexOf (value);
1550 public void Insert (int index, object value)
1552 throw new NotSupportedException ();
1555 public void Remove (object value)
1557 throw new NotSupportedException ();
1560 public void RemoveAt (int index)
1562 throw new NotSupportedException ();
1567 /// This interface is used to get all members of a class when creating the
1568 /// member cache. It must be implemented by all DeclSpace derivatives which
1569 /// want to support the member cache and by TypeHandle to get caching of
1570 /// non-dynamic types.
1572 public interface IMemberContainer {
1574 /// The name of the IMemberContainer. This is only used for
1575 /// debugging purposes.
1582 /// The type of this IMemberContainer.
1589 /// Returns the IMemberContainer of the base class or null if this
1590 /// is an interface or TypeManger.object_type.
1591 /// This is used when creating the member cache for a class to get all
1592 /// members from the base class.
1594 MemberCache BaseCache {
1599 /// Whether this is an interface.
1606 /// Returns all members of this class with the corresponding MemberTypes
1607 /// and BindingFlags.
1610 /// When implementing this method, make sure not to return any inherited
1611 /// members and check the MemberTypes and BindingFlags properly.
1612 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1613 /// get the BindingFlags (static/non-static,public/non-public) in the
1614 /// MemberInfo class, but the cache needs this information. That's why
1615 /// this method is called multiple times with different BindingFlags.
1617 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1620 /// Return the container's member cache.
1622 MemberCache MemberCache {
1628 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1629 /// member lookups. It has a member name based hash table; it maps each member
1630 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1631 /// and the BindingFlags that were initially used to get it. The cache contains
1632 /// all members of the current class and all inherited members. If this cache is
1633 /// for an interface types, it also contains all inherited members.
1635 /// There are two ways to get a MemberCache:
1636 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1637 /// use the DeclSpace.MemberCache property.
1638 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1639 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1641 public class MemberCache {
1642 public readonly IMemberContainer Container;
1643 protected Hashtable member_hash;
1644 protected Hashtable method_hash;
1647 /// Create a new MemberCache for the given IMemberContainer `container'.
1649 public MemberCache (IMemberContainer container)
1651 this.Container = container;
1653 Timer.IncrementCounter (CounterType.MemberCache);
1654 Timer.StartTimer (TimerType.CacheInit);
1656 // If we have a base class (we have a base class unless we're
1657 // TypeManager.object_type), we deep-copy its MemberCache here.
1658 if (Container.BaseCache != null)
1659 member_hash = SetupCache (Container.BaseCache);
1661 member_hash = new Hashtable ();
1663 // If this is neither a dynamic type nor an interface, create a special
1664 // method cache with all declared and inherited methods.
1665 Type type = container.Type;
1666 if (!(type is TypeBuilder) && !type.IsInterface &&
1667 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1668 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1669 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1670 method_hash = new Hashtable ();
1674 // Add all members from the current class.
1675 AddMembers (Container);
1677 Timer.StopTimer (TimerType.CacheInit);
1680 public MemberCache (Type[] ifaces)
1683 // The members of this cache all belong to other caches.
1684 // So, 'Container' will not be used.
1686 this.Container = null;
1688 member_hash = new Hashtable ();
1692 foreach (Type itype in ifaces)
1693 AddCacheContents (TypeManager.LookupMemberCache (itype));
1696 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1698 this.Container = container;
1700 // If we have a base class (we have a base class unless we're
1701 // TypeManager.object_type), we deep-copy its MemberCache here.
1702 if (Container.BaseCache != null)
1703 member_hash = SetupCache (Container.BaseCache);
1705 member_hash = new Hashtable ();
1707 if (base_class != null)
1708 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1709 if (ifaces != null) {
1710 foreach (Type itype in ifaces) {
1711 MemberCache cache = TypeManager.LookupMemberCache (itype);
1713 AddCacheContents (cache);
1719 /// Bootstrap this member cache by doing a deep-copy of our base.
1721 static Hashtable SetupCache (MemberCache base_class)
1723 Hashtable hash = new Hashtable ();
1725 if (base_class == null)
1728 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1729 while (it.MoveNext ()) {
1730 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1737 /// Add the contents of `cache' to the member_hash.
1739 void AddCacheContents (MemberCache cache)
1741 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1742 while (it.MoveNext ()) {
1743 ArrayList list = (ArrayList) member_hash [it.Key];
1745 member_hash [it.Key] = list = new ArrayList ();
1747 ArrayList entries = (ArrayList) it.Value;
1748 for (int i = entries.Count-1; i >= 0; i--) {
1749 CacheEntry entry = (CacheEntry) entries [i];
1751 if (entry.Container != cache.Container)
1759 /// Add all members from class `container' to the cache.
1761 void AddMembers (IMemberContainer container)
1763 // We need to call AddMembers() with a single member type at a time
1764 // to get the member type part of CacheEntry.EntryType right.
1765 if (!container.IsInterface) {
1766 AddMembers (MemberTypes.Constructor, container);
1767 AddMembers (MemberTypes.Field, container);
1769 AddMembers (MemberTypes.Method, container);
1770 AddMembers (MemberTypes.Property, container);
1771 AddMembers (MemberTypes.Event, container);
1772 // Nested types are returned by both Static and Instance searches.
1773 AddMembers (MemberTypes.NestedType,
1774 BindingFlags.Static | BindingFlags.Public, container);
1775 AddMembers (MemberTypes.NestedType,
1776 BindingFlags.Static | BindingFlags.NonPublic, container);
1779 void AddMembers (MemberTypes mt, IMemberContainer container)
1781 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1782 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1783 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1784 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1787 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1788 string name, MemberInfo member)
1790 // We use a name-based hash table of ArrayList's.
1791 ArrayList list = (ArrayList) member_hash [name];
1793 list = new ArrayList ();
1794 member_hash.Add (name, list);
1797 // When this method is called for the current class, the list will
1798 // already contain all inherited members from our base classes.
1799 // We cannot add new members in front of the list since this'd be an
1800 // expensive operation, that's why the list is sorted in reverse order
1801 // (ie. members from the current class are coming last).
1802 list.Add (new CacheEntry (container, member, mt, bf));
1806 /// Add all members from class `container' with the requested MemberTypes and
1807 /// BindingFlags to the cache. This method is called multiple times with different
1808 /// MemberTypes and BindingFlags.
1810 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1812 MemberList members = container.GetMembers (mt, bf);
1814 foreach (MemberInfo member in members) {
1815 string name = member.Name;
1817 AddMember (mt, bf, container, name, member);
1819 if (member is MethodInfo) {
1820 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1822 AddMember (mt, bf, container, gname, member);
1828 /// Add all declared and inherited methods from class `type' to the method cache.
1830 void AddMethods (Type type)
1832 AddMethods (BindingFlags.Static | BindingFlags.Public |
1833 BindingFlags.FlattenHierarchy, type);
1834 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1835 BindingFlags.FlattenHierarchy, type);
1836 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1837 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1840 static ArrayList overrides = new ArrayList ();
1842 void AddMethods (BindingFlags bf, Type type)
1844 MethodBase [] members = type.GetMethods (bf);
1846 Array.Reverse (members);
1848 foreach (MethodBase member in members) {
1849 string name = member.Name;
1851 // We use a name-based hash table of ArrayList's.
1852 ArrayList list = (ArrayList) method_hash [name];
1854 list = new ArrayList ();
1855 method_hash.Add (name, list);
1858 MethodInfo curr = (MethodInfo) member;
1859 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1860 MethodInfo base_method = curr.GetBaseDefinition ();
1862 if (base_method == curr)
1863 // Not every virtual function needs to have a NewSlot flag.
1866 overrides.Add (curr);
1867 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1871 if (overrides.Count > 0) {
1872 for (int i = 0; i < overrides.Count; ++i)
1873 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1877 // Unfortunately, the elements returned by Type.GetMethods() aren't
1878 // sorted so we need to do this check for every member.
1879 BindingFlags new_bf = bf;
1880 if (member.DeclaringType == type)
1881 new_bf |= BindingFlags.DeclaredOnly;
1883 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1888 /// Compute and return a appropriate `EntryType' magic number for the given
1889 /// MemberTypes and BindingFlags.
1891 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1893 EntryType type = EntryType.None;
1895 if ((mt & MemberTypes.Constructor) != 0)
1896 type |= EntryType.Constructor;
1897 if ((mt & MemberTypes.Event) != 0)
1898 type |= EntryType.Event;
1899 if ((mt & MemberTypes.Field) != 0)
1900 type |= EntryType.Field;
1901 if ((mt & MemberTypes.Method) != 0)
1902 type |= EntryType.Method;
1903 if ((mt & MemberTypes.Property) != 0)
1904 type |= EntryType.Property;
1905 // Nested types are returned by static and instance searches.
1906 if ((mt & MemberTypes.NestedType) != 0)
1907 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1909 if ((bf & BindingFlags.Instance) != 0)
1910 type |= EntryType.Instance;
1911 if ((bf & BindingFlags.Static) != 0)
1912 type |= EntryType.Static;
1913 if ((bf & BindingFlags.Public) != 0)
1914 type |= EntryType.Public;
1915 if ((bf & BindingFlags.NonPublic) != 0)
1916 type |= EntryType.NonPublic;
1917 if ((bf & BindingFlags.DeclaredOnly) != 0)
1918 type |= EntryType.Declared;
1924 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1925 /// denote multiple member types. Returns true if the given flags value denotes a
1926 /// single member types.
1928 public static bool IsSingleMemberType (MemberTypes mt)
1931 case MemberTypes.Constructor:
1932 case MemberTypes.Event:
1933 case MemberTypes.Field:
1934 case MemberTypes.Method:
1935 case MemberTypes.Property:
1936 case MemberTypes.NestedType:
1945 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1946 /// number to speed up the searching process.
1949 protected enum EntryType {
1954 MaskStatic = Instance|Static,
1958 MaskProtection = Public|NonPublic,
1962 Constructor = 0x020,
1969 NotExtensionMethod = 0x800,
1971 MaskType = Constructor|Event|Field|Method|Property|NestedType
1974 protected class CacheEntry {
1975 public readonly IMemberContainer Container;
1976 public EntryType EntryType;
1977 public readonly MemberInfo Member;
1979 public CacheEntry (IMemberContainer container, MemberInfo member,
1980 MemberTypes mt, BindingFlags bf)
1982 this.Container = container;
1983 this.Member = member;
1984 this.EntryType = GetEntryType (mt, bf);
1987 public override string ToString ()
1989 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1995 /// This is called each time we're walking up one level in the class hierarchy
1996 /// and checks whether we can abort the search since we've already found what
1997 /// we were looking for.
1999 protected bool DoneSearching (ArrayList list)
2002 // We've found exactly one member in the current class and it's not
2003 // a method or constructor.
2005 if (list.Count == 1 && !(list [0] is MethodBase))
2009 // Multiple properties: we query those just to find out the indexer
2012 if ((list.Count > 0) && (list [0] is PropertyInfo))
2019 /// Looks up members with name `name'. If you provide an optional
2020 /// filter function, it'll only be called with members matching the
2021 /// requested member name.
2023 /// This method will try to use the cache to do the lookup if possible.
2025 /// Unlike other FindMembers implementations, this method will always
2026 /// check all inherited members - even when called on an interface type.
2028 /// If you know that you're only looking for methods, you should use
2029 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2030 /// When doing a method-only search, it'll try to use a special method
2031 /// cache (unless it's a dynamic type or an interface) and the returned
2032 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2033 /// The lookup process will automatically restart itself in method-only
2034 /// search mode if it discovers that it's about to return methods.
2036 ArrayList global = new ArrayList ();
2037 bool using_global = false;
2039 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2041 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2042 MemberFilter filter, object criteria)
2045 throw new Exception ();
2047 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2048 bool method_search = mt == MemberTypes.Method;
2049 // If we have a method cache and we aren't already doing a method-only search,
2050 // then we restart a method search if the first match is a method.
2051 bool do_method_search = !method_search && (method_hash != null);
2053 ArrayList applicable;
2055 // If this is a method-only search, we try to use the method cache if
2056 // possible; a lookup in the method cache will return a MemberInfo with
2057 // the correct ReflectedType for inherited methods.
2059 if (method_search && (method_hash != null))
2060 applicable = (ArrayList) method_hash [name];
2062 applicable = (ArrayList) member_hash [name];
2064 if (applicable == null)
2065 return emptyMemberInfo;
2068 // 32 slots gives 53 rss/54 size
2069 // 2/4 slots gives 55 rss
2071 // Strange: from 25,000 calls, only 1,800
2072 // are above 2. Why does this impact it?
2075 using_global = true;
2077 Timer.StartTimer (TimerType.CachedLookup);
2079 EntryType type = GetEntryType (mt, bf);
2081 IMemberContainer current = Container;
2083 bool do_interface_search = current.IsInterface;
2085 // `applicable' is a list of all members with the given member name `name'
2086 // in the current class and all its base classes. The list is sorted in
2087 // reverse order due to the way how the cache is initialy created (to speed
2088 // things up, we're doing a deep-copy of our base).
2090 for (int i = applicable.Count-1; i >= 0; i--) {
2091 CacheEntry entry = (CacheEntry) applicable [i];
2093 // This happens each time we're walking one level up in the class
2094 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2095 // the first time this happens (this may already happen in the first
2096 // iteration of this loop if there are no members with the name we're
2097 // looking for in the current class).
2098 if (entry.Container != current) {
2102 if (!do_interface_search && DoneSearching (global))
2105 current = entry.Container;
2108 // Is the member of the correct type ?
2109 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2112 // Is the member static/non-static ?
2113 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2116 // Apply the filter to it.
2117 if (filter (entry.Member, criteria)) {
2118 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2119 do_method_search = false;
2122 // Because interfaces support multiple inheritance we have to be sure that
2123 // base member is from same interface, so only top level member will be returned
2124 if (do_interface_search && global.Count > 0) {
2125 bool member_already_exists = false;
2127 foreach (MemberInfo mi in global) {
2128 if (mi is MethodBase)
2131 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2132 member_already_exists = true;
2136 if (member_already_exists)
2140 global.Add (entry.Member);
2144 Timer.StopTimer (TimerType.CachedLookup);
2146 // If we have a method cache and we aren't already doing a method-only
2147 // search, we restart in method-only search mode if the first match is
2148 // a method. This ensures that we return a MemberInfo with the correct
2149 // ReflectedType for inherited methods.
2150 if (do_method_search && (global.Count > 0)){
2151 using_global = false;
2153 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2156 using_global = false;
2157 MemberInfo [] copy = new MemberInfo [global.Count];
2158 global.CopyTo (copy);
2163 /// Returns true if iterface exists in any base interfaces (ifaces)
2165 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2167 foreach (Type iface in ifaces) {
2168 if (iface == ifaceToFind)
2171 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2172 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2178 // find the nested type @name in @this.
2179 public Type FindNestedType (string name)
2181 ArrayList applicable = (ArrayList) member_hash [name];
2182 if (applicable == null)
2185 for (int i = applicable.Count-1; i >= 0; i--) {
2186 CacheEntry entry = (CacheEntry) applicable [i];
2187 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2188 return (Type) entry.Member;
2194 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2196 ArrayList applicable = (ArrayList) member_hash [name];
2197 if (applicable == null)
2201 // Walk the chain of events, starting from the top.
2203 for (int i = applicable.Count - 1; i >= 0; i--)
2205 CacheEntry entry = (CacheEntry) applicable [i];
2206 if ((entry.EntryType & EntryType.Event) == 0)
2209 EventInfo ei = (EventInfo)entry.Member;
2210 return ei.GetAddMethod (true);
2217 // Looks for extension methods with defined name and extension type
2219 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2222 if (method_hash != null)
2223 entries = (ArrayList)method_hash [name];
2225 entries = (ArrayList)member_hash [name];
2227 if (entries == null)
2230 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2232 entry_type |= EntryType.Public;
2234 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2236 ArrayList candidates = null;
2237 foreach (CacheEntry entry in entries) {
2238 if ((entry.EntryType & entry_type) == found_entry_type) {
2239 MethodBase mb = (MethodBase)entry.Member;
2241 IMethodData md = TypeManager.GetMethod (mb);
2242 ParameterData pd = md == null ?
2243 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2245 Type ex_type = pd.ExtensionMethodType;
2246 if (ex_type == null) {
2247 entry.EntryType |= EntryType.NotExtensionMethod;
2251 //if (implicit conversion between ex_type and extensionType exist) {
2252 if (candidates == null)
2253 candidates = new ArrayList (2);
2254 candidates.Add (mb);
2263 // This finds the method or property for us to override. invocation_type is the type where
2264 // the override is going to be declared, name is the name of the method/property, and
2265 // param_types is the parameters, if any to the method or property
2267 // Because the MemberCache holds members from this class and all the base classes,
2268 // we can avoid tons of reflection stuff.
2270 public MemberInfo FindMemberToOverride (Type invocation_type, string name, Type [] param_types, GenericMethod generic_method, bool is_property)
2272 ArrayList applicable;
2273 if (method_hash != null && !is_property)
2274 applicable = (ArrayList) method_hash [name];
2276 applicable = (ArrayList) member_hash [name];
2278 if (applicable == null)
2281 // Walk the chain of methods, starting from the top.
2283 for (int i = applicable.Count - 1; i >= 0; i--) {
2284 CacheEntry entry = (CacheEntry) applicable [i];
2286 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2289 PropertyInfo pi = null;
2290 MethodInfo mi = null;
2291 FieldInfo fi = null;
2292 Type [] cmp_attrs = null;
2295 if ((entry.EntryType & EntryType.Field) != 0) {
2296 fi = (FieldInfo)entry.Member;
2298 // TODO: For this case we ignore member type
2299 //fb = TypeManager.GetField (fi);
2300 //cmp_attrs = new Type[] { fb.MemberType };
2302 pi = (PropertyInfo) entry.Member;
2303 cmp_attrs = TypeManager.GetArgumentTypes (pi);
2306 mi = (MethodInfo) entry.Member;
2307 cmp_attrs = TypeManager.GetParameterData (mi).Types;
2311 // TODO: Almost duplicate !
2313 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2314 case FieldAttributes.PrivateScope:
2316 case FieldAttributes.Private:
2318 // A private method is Ok if we are a nested subtype.
2319 // The spec actually is not very clear about this, see bug 52458.
2321 if (!invocation_type.Equals (entry.Container.Type) &&
2322 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2325 case FieldAttributes.FamANDAssem:
2326 case FieldAttributes.Assembly:
2328 // Check for assembly methods
2330 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2334 return entry.Member;
2338 // Check the arguments
2340 if (cmp_attrs.Length != param_types.Length)
2344 for (j = 0; j < cmp_attrs.Length; ++j)
2345 if (!TypeManager.IsEqual (param_types [j], cmp_attrs [j]))
2347 if (j < cmp_attrs.Length)
2351 // check generic arguments for methods
2354 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2355 if (generic_method == null && cmpGenArgs.Length != 0)
2357 if (generic_method != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2362 // get one of the methods because this has the visibility info.
2365 mi = pi.GetGetMethod (true);
2367 mi = pi.GetSetMethod (true);
2373 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2374 case MethodAttributes.PrivateScope:
2376 case MethodAttributes.Private:
2378 // A private method is Ok if we are a nested subtype.
2379 // The spec actually is not very clear about this, see bug 52458.
2381 if (!invocation_type.Equals (entry.Container.Type) &&
2382 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2385 case MethodAttributes.FamANDAssem:
2386 case MethodAttributes.Assembly:
2388 // Check for assembly methods
2390 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2394 return entry.Member;
2401 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2402 /// We handle two cases. The first is for types without parameters (events, field, properties).
2403 /// The second are methods, indexers and this is why ignore_complex_types is here.
2404 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2406 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2408 ArrayList applicable = null;
2410 if (method_hash != null)
2411 applicable = (ArrayList) method_hash [name];
2413 if (applicable != null) {
2414 for (int i = applicable.Count - 1; i >= 0; i--) {
2415 CacheEntry entry = (CacheEntry) applicable [i];
2416 if ((entry.EntryType & EntryType.Public) != 0)
2417 return entry.Member;
2421 if (member_hash == null)
2423 applicable = (ArrayList) member_hash [name];
2425 if (applicable != null) {
2426 for (int i = applicable.Count - 1; i >= 0; i--) {
2427 CacheEntry entry = (CacheEntry) applicable [i];
2428 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2429 if (ignore_complex_types) {
2430 if ((entry.EntryType & EntryType.Method) != 0)
2433 // Does exist easier way how to detect indexer ?
2434 if ((entry.EntryType & EntryType.Property) != 0) {
2435 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2436 if (arg_types.Length > 0)
2440 return entry.Member;
2447 Hashtable locase_table;
2450 /// Builds low-case table for CLS Compliance test
2452 public Hashtable GetPublicMembers ()
2454 if (locase_table != null)
2455 return locase_table;
2457 locase_table = new Hashtable ();
2458 foreach (DictionaryEntry entry in member_hash) {
2459 ArrayList members = (ArrayList)entry.Value;
2460 for (int ii = 0; ii < members.Count; ++ii) {
2461 CacheEntry member_entry = (CacheEntry) members [ii];
2463 if ((member_entry.EntryType & EntryType.Public) == 0)
2466 // TODO: Does anyone know easier way how to detect that member is internal ?
2467 switch (member_entry.EntryType & EntryType.MaskType) {
2468 case EntryType.Constructor:
2471 case EntryType.Field:
2472 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2476 case EntryType.Method:
2477 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2481 case EntryType.Property:
2482 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2483 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2487 case EntryType.Event:
2488 EventInfo ei = (EventInfo)member_entry.Member;
2489 MethodInfo mi = ei.GetAddMethod ();
2490 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2494 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2495 locase_table [lcase] = member_entry.Member;
2499 return locase_table;
2502 public Hashtable Members {
2509 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2512 // TODO: refactor as method is always 'this'
2513 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2515 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2517 for (int i = 0; i < al.Count; ++i) {
2518 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2521 if (entry.Member == this_builder)
2524 if ((entry.EntryType & tested_type) != tested_type)
2527 MethodBase method_to_compare = (MethodBase)entry.Member;
2528 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2529 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2531 if (result == AttributeTester.Result.Ok)
2534 IMethodData md = TypeManager.GetMethod (method_to_compare);
2536 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2537 // However it is exactly what csc does.
2538 if (md != null && !md.IsClsComplianceRequired ())
2541 Report.SymbolRelatedToPreviousError (entry.Member);
2543 case AttributeTester.Result.RefOutArrayError:
2544 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2546 case AttributeTester.Result.ArrayArrayError:
2547 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2551 throw new NotImplementedException (result.ToString ());