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;
23 namespace Mono.CSharp {
25 public class MemberName {
26 public readonly string Name;
27 public readonly TypeArguments TypeArguments;
29 public readonly MemberName Left;
30 public readonly Location Location;
32 public static readonly MemberName Null = new MemberName ("", Location.Null);
36 private MemberName (MemberName left, string name, bool is_double_colon,
37 TypeArguments args, Location loc)
41 this.is_double_colon = is_double_colon;
42 this.TypeArguments = args;
46 public MemberName (string name, TypeArguments args, Location loc)
49 this.TypeArguments = args;
52 public MemberName (string name, Location loc)
58 public MemberName (MemberName left, string name, Location loc)
64 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
65 : this (name, args, loc)
70 public MemberName (string alias, string name, Location loc)
71 : this (new MemberName (alias, loc), name, true, null, loc)
75 public MemberName (MemberName left, MemberName right)
76 : this (left, right, right.Location)
80 public MemberName (MemberName left, MemberName right, Location loc)
81 : this (null, right.Name, false, right.TypeArguments, loc)
83 if (right.is_double_colon)
84 throw new InternalErrorException ("Cannot append double_colon member name");
85 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
88 static readonly char [] dot_array = { '.' };
90 public static MemberName FromDotted (string name, Location loc)
92 string [] elements = name.Split (dot_array);
93 int count = elements.Length;
95 MemberName n = new MemberName (elements [i++], loc);
97 n = new MemberName (n, elements [i++], loc);
101 public string GetName ()
103 string connect = is_double_colon ? "::" : ".";
105 return Left.GetName () + connect + Name;
110 public bool IsGeneric {
112 if (TypeArguments != null)
114 else if (Left != null)
115 return Left.IsGeneric;
121 public string GetName (bool is_generic)
123 string name = is_generic ? Basename : Name;
124 string connect = is_double_colon ? "::" : ".";
126 return Left.GetName (is_generic) + connect + name;
131 public int CountTypeArguments {
133 if (TypeArguments == null)
136 return TypeArguments.Count;
140 public string MethodName {
142 string connect = is_double_colon ? "::" : ".";
144 return Left.FullName + connect + Name;
150 public static string MakeName (string name, TypeArguments args)
155 return name + "`" + args.Count;
158 public static string MakeName (string name, int count)
160 return name + "`" + count;
163 public string GetTypeName ()
165 string connect = is_double_colon ? "::" : ".";
167 return Left.GetTypeName () + connect +
168 MakeName (Name, TypeArguments);
170 return MakeName (Name, TypeArguments);
173 protected bool IsUnbound {
175 if ((Left != null) && Left.IsUnbound)
177 else if (TypeArguments == null)
180 return TypeArguments.IsUnbound;
184 protected bool CheckUnbound (Location loc)
186 if ((Left != null) && !Left.CheckUnbound (loc))
188 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
189 Report.Error (1031, loc, "Type expected");
196 public Expression GetTypeExpression ()
199 if (!CheckUnbound (Location))
202 return new UnboundTypeExpression (this, Location);
206 if (TypeArguments != null)
207 return new SimpleName (Basename, TypeArguments, Location);
209 return new SimpleName (Name, Location);
212 if (is_double_colon) {
213 if (Left.Left != null)
214 throw new InternalErrorException ("The left side of a :: should be an identifier");
215 return new QualifiedAliasMember (Left.Name, Name, Location);
218 Expression lexpr = Left.GetTypeExpression ();
219 return new MemberAccess (lexpr, Name, TypeArguments);
222 public MemberName Clone ()
224 MemberName left_clone = Left == null ? null : Left.Clone ();
225 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
228 public string Basename {
230 if (TypeArguments != null)
231 return MakeName (Name, TypeArguments);
237 public string FullName {
239 if (TypeArguments != null)
240 return Name + "<" + TypeArguments + ">";
246 public override string ToString ()
248 string connect = is_double_colon ? "::" : ".";
250 return Left.FullName + connect + FullName;
255 public override bool Equals (object other)
257 return Equals (other as MemberName);
260 public bool Equals (MemberName other)
264 if (other == null || Name != other.Name)
266 if (is_double_colon != other.is_double_colon)
269 if ((TypeArguments != null) &&
270 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
273 if ((TypeArguments == null) && (other.TypeArguments != null))
277 return other.Left == null;
279 return Left.Equals (other.Left);
282 public override int GetHashCode ()
284 int hash = Name.GetHashCode ();
285 for (MemberName n = Left; n != null; n = n.Left)
286 hash ^= n.Name.GetHashCode ();
290 if (TypeArguments != null)
291 hash ^= TypeArguments.Count << 5;
293 return hash & 0x7FFFFFFF;
298 /// Base representation for members. This is used to keep track
299 /// of Name, Location and Modifier flags, and handling Attributes.
301 public abstract class MemberCore : Attributable, IResolveContext {
306 protected string cached_name;
309 if (cached_name == null)
310 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
315 // Is not readonly because of IndexerName attribute
316 private MemberName member_name;
317 public MemberName MemberName {
318 get { return member_name; }
322 /// Modifier flags that the user specified in the source code
326 public readonly DeclSpace Parent;
329 /// Location where this declaration happens
331 public Location Location {
332 get { return member_name.Location; }
336 /// XML documentation comment
338 protected string comment;
341 /// Represents header string for documentation comment
342 /// for each member types.
344 public abstract string DocCommentHeader { get; }
348 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
349 Obsolete = 1 << 1, // Type has obsolete attribute
350 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
351 ClsCompliant = 1 << 3, // Type is CLS Compliant
352 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
353 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
354 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
355 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
356 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
357 Excluded = 1 << 9, // Method is conditional
358 TestMethodDuplication = 1 << 10, // Test for duplication must be performed
360 IsAssigned = 1 << 12, // Field is assigned
361 HasExplicitLayout = 1 << 13
365 /// MemberCore flags at first detected then cached
367 internal Flags caching_flags;
369 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
372 this.Parent = parent;
374 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
377 protected virtual void SetMemberName (MemberName new_name)
379 member_name = new_name;
383 public abstract bool Define ();
385 public virtual string DocComment {
395 // Returns full member name for error message
397 public virtual string GetSignatureForError ()
399 if (Parent == null || Parent.Parent == null)
402 return String.Concat (Parent.GetSignatureForError (), '.', Name);
406 /// Base Emit method. This is also entry point for CLS-Compliant verification.
408 public virtual void Emit ()
410 if (!RootContext.VerifyClsCompliance)
413 VerifyClsCompliance ();
416 public virtual bool IsUsed {
417 get { return (caching_flags & Flags.IsUsed) != 0; }
420 public void SetMemberIsUsed ()
422 caching_flags |= Flags.IsUsed;
426 /// Returns instance of ObsoleteAttribute for this MemberCore
428 public virtual ObsoleteAttribute GetObsoleteAttribute ()
430 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
431 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
435 caching_flags &= ~Flags.Obsolete_Undetected;
437 if (OptAttributes == null)
440 Attribute obsolete_attr = OptAttributes.Search (
441 TypeManager.obsolete_attribute_type);
442 if (obsolete_attr == null)
445 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
446 if (obsolete == null)
449 caching_flags |= Flags.Obsolete;
454 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
456 public virtual void CheckObsoleteness (Location loc)
459 Parent.CheckObsoleteness (loc);
461 ObsoleteAttribute oa = GetObsoleteAttribute ();
466 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
470 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
472 public override bool IsClsComplianceRequired ()
474 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
475 return (caching_flags & Flags.ClsCompliant) != 0;
477 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
478 caching_flags &= ~Flags.ClsCompliance_Undetected;
479 caching_flags |= Flags.ClsCompliant;
483 caching_flags &= ~Flags.ClsCompliance_Undetected;
488 /// Returns true when MemberCore is exposed from assembly.
490 public bool IsExposedFromAssembly ()
492 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
495 DeclSpace parentContainer = Parent;
496 while (parentContainer != null && parentContainer.ModFlags != 0) {
497 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
499 parentContainer = parentContainer.Parent;
505 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
506 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
508 public virtual bool GetClsCompliantAttributeValue ()
510 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
511 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
513 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
515 if (OptAttributes != null) {
516 Attribute cls_attribute = OptAttributes.Search (
517 TypeManager.cls_compliant_attribute_type);
518 if (cls_attribute != null) {
519 caching_flags |= Flags.HasClsCompliantAttribute;
520 return cls_attribute.GetClsCompliantAttributeValue ();
524 if (Parent.GetClsCompliantAttributeValue ()) {
525 caching_flags |= Flags.ClsCompliantAttributeTrue;
532 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
534 protected bool HasClsCompliantAttribute {
536 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
541 /// It helps to handle error 102 & 111 detection
543 public virtual bool MarkForDuplicationCheck ()
549 /// The main virtual method for CLS-Compliant verifications.
550 /// The method returns true if member is CLS-Compliant and false if member is not
551 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
552 /// and add their extra verifications.
554 protected virtual bool VerifyClsCompliance ()
556 if (!IsClsComplianceRequired ()) {
557 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
558 if (!IsExposedFromAssembly ())
559 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
560 if (!CodeGen.Assembly.IsClsCompliant)
561 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
566 if (!CodeGen.Assembly.IsClsCompliant) {
567 if (HasClsCompliantAttribute) {
568 Report.Error (3014, Location,
569 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
570 GetSignatureForError ());
575 if (member_name.Name [0] == '_') {
576 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
582 // Raised (and passed an XmlElement that contains the comment)
583 // when GenerateDocComment is writing documentation expectedly.
585 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
590 // Returns a string that represents the signature for this
591 // member which should be used in XML documentation.
593 public virtual string GetDocCommentName (DeclSpace ds)
595 if (ds == null || this is DeclSpace)
596 return DocCommentHeader + Name;
598 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
602 // Generates xml doc comments (if any), and if required,
603 // handle warning report.
605 internal virtual void GenerateDocComment (DeclSpace ds)
607 DocUtil.GenerateDocComment (this, ds);
610 public override IResolveContext ResolveContext {
616 #region IResolveContext Members
618 public virtual DeclSpace DeclContainer {
624 public bool IsInObsoleteScope {
626 if (GetObsoleteAttribute () != null)
629 return Parent == null ? false : Parent.IsInObsoleteScope;
633 public bool IsInUnsafeScope {
635 if ((ModFlags & Modifiers.UNSAFE) != 0)
638 return Parent == null ? false : Parent.IsInUnsafeScope;
646 /// Base class for structs, classes, enumerations and interfaces.
649 /// They all create new declaration spaces. This
650 /// provides the common foundation for managing those name
653 public abstract class DeclSpace : MemberCore {
655 /// This points to the actual definition that is being
656 /// created with System.Reflection.Emit
658 public TypeBuilder TypeBuilder;
661 /// If we are a generic type, this is the type we are
662 /// currently defining. We need to lookup members on this
663 /// instead of the TypeBuilder.
665 public Type CurrentType;
668 // This is the namespace in which this typecontainer
669 // was declared. We use this to resolve names.
671 public NamespaceEntry NamespaceEntry;
673 private Hashtable Cache = new Hashtable ();
675 public readonly string Basename;
677 protected Hashtable defined_names;
679 readonly bool is_generic;
680 readonly int count_type_params;
681 readonly int count_current_type_params;
684 // Whether we are Generic
686 public bool IsGeneric {
690 else if (Parent != null)
691 return Parent.IsGeneric;
697 static string[] attribute_targets = new string [] { "type" };
699 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
701 : base (parent, name, attrs)
704 Basename = name.Basename;
705 defined_names = new Hashtable ();
706 if (name.TypeArguments != null) {
708 count_type_params = count_current_type_params = name.TypeArguments.Count;
711 count_type_params += parent.count_type_params;
714 public override DeclSpace DeclContainer {
721 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
723 protected virtual bool AddToContainer (MemberCore symbol, string name)
725 MemberCore mc = (MemberCore) defined_names [name];
728 defined_names.Add (name, symbol);
732 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
735 Report.SymbolRelatedToPreviousError (mc);
736 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
737 Error_MissingPartialModifier (symbol);
741 if (this is RootTypes) {
742 Report.Error (101, symbol.Location,
743 "The namespace `{0}' already contains a definition for `{1}'",
744 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
745 } else if (symbol is TypeParameter) {
746 Report.Error (692, symbol.Location,
747 "Duplicate type parameter `{0}'", name);
749 Report.Error (102, symbol.Location,
750 "The type `{0}' already contains a definition for `{1}'",
751 GetSignatureForError (), symbol.MemberName.Name);
758 /// Returns the MemberCore associated with a given name in the declaration
759 /// space. It doesn't return method based symbols !!
762 public MemberCore GetDefinition (string name)
764 return (MemberCore)defined_names [name];
768 // root_types contains all the types. All TopLevel types
769 // hence have a parent that points to `root_types', that is
770 // why there is a non-obvious test down here.
772 public bool IsTopLevel {
773 get { return (Parent != null && Parent.Parent == null); }
776 public virtual void CloseType ()
778 if ((caching_flags & Flags.CloseTypeCreated) == 0){
780 TypeBuilder.CreateType ();
783 // The try/catch is needed because
784 // nested enumerations fail to load when they
787 // Even if this is the right order (enumerations
788 // declared after types).
790 // Note that this still creates the type and
791 // it is possible to save it
793 caching_flags |= Flags.CloseTypeCreated;
797 protected virtual TypeAttributes TypeAttr {
798 get { return CodeGen.Module.DefaultCharSetType; }
802 /// Should be overriten by the appropriate declaration space
804 public abstract TypeBuilder DefineType ();
807 /// Define all members, but don't apply any attributes or do anything which may
808 /// access not-yet-defined classes. This method also creates the MemberCache.
810 public virtual bool DefineMembers ()
812 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
813 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
819 protected void Error_MissingPartialModifier (MemberCore type)
821 Report.Error (260, type.Location,
822 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
823 type.GetSignatureForError ());
826 public override string GetSignatureForError ()
829 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
831 // Parent.GetSignatureForError
835 public bool CheckAccessLevel (Type check_type)
838 if ((this is GenericMethod) || (this is Iterator))
839 tb = Parent.TypeBuilder;
843 check_type = TypeManager.DropGenericTypeArguments (check_type);
844 if (check_type == tb)
847 if (TypeBuilder == null)
848 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
849 // However, this is invoked again later -- so safe to return true.
850 // May also be null when resolving top-level attributes.
853 if (check_type.IsGenericParameter)
854 return true; // FIXME
856 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
859 // Broken Microsoft runtime, return public for arrays, no matter what
860 // the accessibility is for their underlying class, and they return
861 // NonPublic visibility for pointers
863 if (check_type.IsArray || check_type.IsPointer)
864 return CheckAccessLevel (TypeManager.GetElementType (check_type));
867 case TypeAttributes.Public:
870 case TypeAttributes.NotPublic:
872 if (TypeBuilder == null)
873 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
874 // However, this is invoked again later -- so safe to return true.
875 // May also be null when resolving top-level attributes.
878 // This test should probably use the declaringtype.
880 return check_type.Assembly == TypeBuilder.Assembly ||
881 TypeManager.IsFriendAssembly (check_type.Assembly);
883 case TypeAttributes.NestedPublic:
886 case TypeAttributes.NestedPrivate:
887 return NestedAccessible (tb, check_type);
889 case TypeAttributes.NestedFamily:
891 // Only accessible to methods in current type or any subtypes
893 return FamilyAccessible (tb, check_type);
895 case TypeAttributes.NestedFamANDAssem:
896 return ((check_type.Assembly == tb.Assembly) ||
897 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
898 FamilyAccessible (tb, check_type);
900 case TypeAttributes.NestedFamORAssem:
901 return (check_type.Assembly == tb.Assembly) ||
902 FamilyAccessible (tb, check_type) ||
903 TypeManager.IsFriendAssembly (check_type.Assembly);
905 case TypeAttributes.NestedAssembly:
906 return check_type.Assembly == tb.Assembly ||
907 TypeManager.IsFriendAssembly (check_type.Assembly);
910 Console.WriteLine ("HERE: " + check_attr);
915 protected bool NestedAccessible (Type tb, Type check_type)
917 Type declaring = check_type.DeclaringType;
918 return TypeBuilder == declaring ||
919 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
922 protected bool FamilyAccessible (Type tb, Type check_type)
924 Type declaring = check_type.DeclaringType;
925 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
928 // Access level of a type.
930 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
931 // Public Assembly Protected
932 Protected = (0 << 0) | (0 << 1) | (X << 2),
933 Public = (X << 0) | (X << 1) | (X << 2),
934 Private = (0 << 0) | (0 << 1) | (0 << 2),
935 Internal = (0 << 0) | (X << 1) | (0 << 2),
936 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
939 static AccessLevel GetAccessLevelFromModifiers (int flags)
941 if ((flags & Modifiers.INTERNAL) != 0) {
943 if ((flags & Modifiers.PROTECTED) != 0)
944 return AccessLevel.ProtectedOrInternal;
946 return AccessLevel.Internal;
948 } else if ((flags & Modifiers.PROTECTED) != 0)
949 return AccessLevel.Protected;
950 else if ((flags & Modifiers.PRIVATE) != 0)
951 return AccessLevel.Private;
953 return AccessLevel.Public;
956 // What is the effective access level of this?
958 AccessLevel EffectiveAccessLevel {
960 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
961 if (!IsTopLevel && (Parent != null))
962 return myAccess & Parent.EffectiveAccessLevel;
967 // Return the access level for type `t'
968 static AccessLevel TypeEffectiveAccessLevel (Type t)
971 return AccessLevel.Public;
972 if (t.IsNestedPrivate)
973 return AccessLevel.Private;
975 return AccessLevel.Internal;
977 // By now, it must be nested
978 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
980 if (t.IsNestedPublic)
982 if (t.IsNestedAssembly)
983 return parentLevel & AccessLevel.Internal;
984 if (t.IsNestedFamily)
985 return parentLevel & AccessLevel.Protected;
986 if (t.IsNestedFamORAssem)
987 return parentLevel & AccessLevel.ProtectedOrInternal;
988 if (t.IsNestedFamANDAssem)
989 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
991 // nested private is taken care of
993 throw new Exception ("I give up, what are you?");
997 // This answers `is the type P, as accessible as a member M which has the
998 // accessability @flags which is declared as a nested member of the type T, this declspace'
1000 public bool AsAccessible (Type p, int flags)
1002 if (p.IsGenericParameter)
1003 return true; // FIXME
1006 // 1) if M is private, its accessability is the same as this declspace.
1007 // we already know that P is accessible to T before this method, so we
1011 if ((flags & Modifiers.PRIVATE) != 0)
1014 while (p.IsArray || p.IsPointer || p.IsByRef)
1015 p = TypeManager.GetElementType (p);
1017 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1018 AccessLevel mAccess = this.EffectiveAccessLevel &
1019 GetAccessLevelFromModifiers (flags);
1021 // for every place from which we can access M, we must
1022 // be able to access P as well. So, we want
1023 // For every bit in M and P, M_i -> P_1 == true
1024 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1026 return ~ (~ mAccess | pAccess) == 0;
1030 // Return the nested type with name @name. Ensures that the nested type
1031 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1033 public virtual Type FindNestedType (string name)
1038 private Type LookupNestedTypeInHierarchy (string name)
1040 // if the member cache has been created, lets use it.
1041 // the member cache is MUCH faster.
1042 if (MemberCache != null)
1043 return MemberCache.FindNestedType (name);
1045 // no member cache. Do it the hard way -- reflection
1047 for (Type current_type = TypeBuilder;
1048 current_type != null && current_type != TypeManager.object_type;
1049 current_type = current_type.BaseType) {
1050 current_type = TypeManager.DropGenericTypeArguments (current_type);
1051 if (current_type is TypeBuilder) {
1052 DeclSpace decl = this;
1053 if (current_type != TypeBuilder)
1054 decl = TypeManager.LookupDeclSpace (current_type);
1055 t = decl.FindNestedType (name);
1057 t = TypeManager.GetNestedType (current_type, name);
1060 if (t != null && CheckAccessLevel (t))
1068 // Public function used to locate types.
1070 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1072 // Returns: Type or null if they type can not be found.
1074 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1076 if (Cache.Contains (name))
1077 return (FullNamedExpression) Cache [name];
1079 FullNamedExpression e;
1080 Type t = LookupNestedTypeInHierarchy (name);
1082 e = new TypeExpression (t, Location.Null);
1083 else if (Parent != null && Parent != RootContext.Tree.Types)
1084 e = Parent.LookupType (name, loc, ignore_cs0104);
1086 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1093 /// This function is broken and not what you're looking for. It should only
1094 /// be used while the type is still being created since it doesn't use the cache
1095 /// and relies on the filter doing the member name check.
1097 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1098 MemberFilter filter, object criteria);
1101 /// If we have a MemberCache, return it. This property may return null if the
1102 /// class doesn't have a member cache or while it's still being created.
1104 public abstract MemberCache MemberCache {
1108 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1110 if (a.Type == TypeManager.required_attr_type) {
1111 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1114 TypeBuilder.SetCustomAttribute (cb);
1118 // Extensions for generics
1120 TypeParameter[] type_params;
1121 TypeParameter[] type_param_list;
1123 protected string GetInstantiationName ()
1125 StringBuilder sb = new StringBuilder (Name);
1127 for (int i = 0; i < type_param_list.Length; i++) {
1130 sb.Append (type_param_list [i].Name);
1133 return sb.ToString ();
1136 bool check_type_parameter (ArrayList list, int start, string name)
1138 for (int i = 0; i < start; i++) {
1139 TypeParameter param = (TypeParameter) list [i];
1141 if (param.Name != name)
1144 Report.Warning (693, 3, Location,
1145 "Type parameter `{0}' has same name as type parameter from outer type `{1}'",
1146 name, Parent.GetInstantiationName ());
1154 TypeParameter[] initialize_type_params ()
1156 if (type_param_list != null)
1157 return type_param_list;
1159 DeclSpace the_parent = Parent;
1160 if (this is GenericMethod)
1164 TypeParameter[] parent_params = null;
1165 if ((the_parent != null) && the_parent.IsGeneric) {
1166 parent_params = the_parent.initialize_type_params ();
1167 start = parent_params != null ? parent_params.Length : 0;
1170 ArrayList list = new ArrayList ();
1171 if (parent_params != null)
1172 list.AddRange (parent_params);
1174 int count = type_params != null ? type_params.Length : 0;
1175 for (int i = 0; i < count; i++) {
1176 TypeParameter param = type_params [i];
1177 check_type_parameter (list, start, param.Name);
1181 type_param_list = new TypeParameter [list.Count];
1182 list.CopyTo (type_param_list, 0);
1183 return type_param_list;
1186 public virtual void SetParameterInfo (ArrayList constraints_list)
1189 if (constraints_list != null) {
1191 80, Location, "Constraints are not allowed " +
1192 "on non-generic declarations");
1198 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1199 type_params = new TypeParameter [names.Length];
1202 // Register all the names
1204 for (int i = 0; i < type_params.Length; i++) {
1205 TypeParameterName name = names [i];
1207 Constraints constraints = null;
1208 if (constraints_list != null) {
1209 foreach (Constraints constraint in constraints_list) {
1210 if (constraint == null)
1212 if (constraint.TypeParameter == name.Name) {
1213 constraints = constraint;
1219 type_params [i] = new TypeParameter (
1220 Parent, this, name.Name, constraints, name.OptAttributes,
1223 AddToContainer (type_params [i], name.Name);
1227 public TypeParameter[] TypeParameters {
1230 throw new InvalidOperationException ();
1231 if (type_param_list == null)
1232 initialize_type_params ();
1234 return type_param_list;
1238 public TypeParameter[] CurrentTypeParameters {
1241 throw new InvalidOperationException ();
1242 if (type_params != null)
1245 return new TypeParameter [0];
1249 public int CountTypeParameters {
1251 return count_type_params;
1255 public int CountCurrentTypeParameters {
1257 return count_current_type_params;
1261 public TypeParameterExpr LookupGeneric (string name, Location loc)
1266 TypeParameter [] current_params;
1267 if (this is TypeContainer)
1268 current_params = ((TypeContainer) this).PartialContainer.CurrentTypeParameters;
1270 current_params = CurrentTypeParameters;
1272 foreach (TypeParameter type_param in current_params) {
1273 if (type_param.Name == name)
1274 return new TypeParameterExpr (type_param, loc);
1278 return Parent.LookupGeneric (name, loc);
1283 public override string[] ValidAttributeTargets {
1284 get { return attribute_targets; }
1287 protected override bool VerifyClsCompliance ()
1289 if (!base.VerifyClsCompliance ()) {
1293 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1294 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1295 if (!cache.Contains (lcase)) {
1296 cache.Add (lcase, this);
1300 object val = cache [lcase];
1302 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1305 Report.SymbolRelatedToPreviousError (t);
1308 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1310 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1316 /// This is a readonly list of MemberInfo's.
1318 public class MemberList : IList {
1319 public readonly IList List;
1323 /// Create a new MemberList from the given IList.
1325 public MemberList (IList list)
1330 this.List = new ArrayList ();
1335 /// Concatenate the ILists `first' and `second' to a new MemberList.
1337 public MemberList (IList first, IList second)
1339 ArrayList list = new ArrayList ();
1340 list.AddRange (first);
1341 list.AddRange (second);
1346 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1349 /// Cast the MemberList into a MemberInfo[] array.
1352 /// This is an expensive operation, only use it if it's really necessary.
1354 public static explicit operator MemberInfo [] (MemberList list)
1356 Timer.StartTimer (TimerType.MiscTimer);
1357 MemberInfo [] result = new MemberInfo [list.Count];
1358 list.CopyTo (result, 0);
1359 Timer.StopTimer (TimerType.MiscTimer);
1371 public bool IsSynchronized {
1373 return List.IsSynchronized;
1377 public object SyncRoot {
1379 return List.SyncRoot;
1383 public void CopyTo (Array array, int index)
1385 List.CopyTo (array, index);
1390 public IEnumerator GetEnumerator ()
1392 return List.GetEnumerator ();
1397 public bool IsFixedSize {
1403 public bool IsReadOnly {
1409 object IList.this [int index] {
1411 return List [index];
1415 throw new NotSupportedException ();
1419 // FIXME: try to find out whether we can avoid the cast in this indexer.
1420 public MemberInfo this [int index] {
1422 return (MemberInfo) List [index];
1426 public int Add (object value)
1428 throw new NotSupportedException ();
1431 public void Clear ()
1433 throw new NotSupportedException ();
1436 public bool Contains (object value)
1438 return List.Contains (value);
1441 public int IndexOf (object value)
1443 return List.IndexOf (value);
1446 public void Insert (int index, object value)
1448 throw new NotSupportedException ();
1451 public void Remove (object value)
1453 throw new NotSupportedException ();
1456 public void RemoveAt (int index)
1458 throw new NotSupportedException ();
1463 /// This interface is used to get all members of a class when creating the
1464 /// member cache. It must be implemented by all DeclSpace derivatives which
1465 /// want to support the member cache and by TypeHandle to get caching of
1466 /// non-dynamic types.
1468 public interface IMemberContainer {
1470 /// The name of the IMemberContainer. This is only used for
1471 /// debugging purposes.
1478 /// The type of this IMemberContainer.
1485 /// Returns the IMemberContainer of the base class or null if this
1486 /// is an interface or TypeManger.object_type.
1487 /// This is used when creating the member cache for a class to get all
1488 /// members from the base class.
1490 MemberCache BaseCache {
1495 /// Whether this is an interface.
1502 /// Returns all members of this class with the corresponding MemberTypes
1503 /// and BindingFlags.
1506 /// When implementing this method, make sure not to return any inherited
1507 /// members and check the MemberTypes and BindingFlags properly.
1508 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1509 /// get the BindingFlags (static/non-static,public/non-public) in the
1510 /// MemberInfo class, but the cache needs this information. That's why
1511 /// this method is called multiple times with different BindingFlags.
1513 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1516 /// Return the container's member cache.
1518 MemberCache MemberCache {
1524 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1525 /// member lookups. It has a member name based hash table; it maps each member
1526 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1527 /// and the BindingFlags that were initially used to get it. The cache contains
1528 /// all members of the current class and all inherited members. If this cache is
1529 /// for an interface types, it also contains all inherited members.
1531 /// There are two ways to get a MemberCache:
1532 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1533 /// use the DeclSpace.MemberCache property.
1534 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1535 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1537 public class MemberCache {
1538 public readonly IMemberContainer Container;
1539 protected Hashtable member_hash;
1540 protected Hashtable method_hash;
1543 /// Create a new MemberCache for the given IMemberContainer `container'.
1545 public MemberCache (IMemberContainer container)
1547 this.Container = container;
1549 Timer.IncrementCounter (CounterType.MemberCache);
1550 Timer.StartTimer (TimerType.CacheInit);
1552 // If we have a base class (we have a base class unless we're
1553 // TypeManager.object_type), we deep-copy its MemberCache here.
1554 if (Container.BaseCache != null)
1555 member_hash = SetupCache (Container.BaseCache);
1557 member_hash = new Hashtable ();
1559 // If this is neither a dynamic type nor an interface, create a special
1560 // method cache with all declared and inherited methods.
1561 Type type = container.Type;
1562 if (!(type is TypeBuilder) && !type.IsInterface &&
1563 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1564 !type.IsGenericType &&
1565 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1566 method_hash = new Hashtable ();
1570 // Add all members from the current class.
1571 AddMembers (Container);
1573 Timer.StopTimer (TimerType.CacheInit);
1576 public MemberCache (Type[] ifaces)
1579 // The members of this cache all belong to other caches.
1580 // So, 'Container' will not be used.
1582 this.Container = null;
1584 member_hash = new Hashtable ();
1588 foreach (Type itype in ifaces)
1589 AddCacheContents (TypeManager.LookupMemberCache (itype));
1593 /// Bootstrap this member cache by doing a deep-copy of our base.
1595 static Hashtable SetupCache (MemberCache base_class)
1597 Hashtable hash = new Hashtable ();
1599 if (base_class == null)
1602 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1603 while (it.MoveNext ()) {
1604 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1611 /// Add the contents of `cache' to the member_hash.
1613 void AddCacheContents (MemberCache cache)
1615 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1616 while (it.MoveNext ()) {
1617 ArrayList list = (ArrayList) member_hash [it.Key];
1619 member_hash [it.Key] = list = new ArrayList ();
1621 ArrayList entries = (ArrayList) it.Value;
1622 for (int i = entries.Count-1; i >= 0; i--) {
1623 CacheEntry entry = (CacheEntry) entries [i];
1625 if (entry.Container != cache.Container)
1633 /// Add all members from class `container' to the cache.
1635 void AddMembers (IMemberContainer container)
1637 // We need to call AddMembers() with a single member type at a time
1638 // to get the member type part of CacheEntry.EntryType right.
1639 if (!container.IsInterface) {
1640 AddMembers (MemberTypes.Constructor, container);
1641 AddMembers (MemberTypes.Field, container);
1643 AddMembers (MemberTypes.Method, container);
1644 AddMembers (MemberTypes.Property, container);
1645 AddMembers (MemberTypes.Event, container);
1646 // Nested types are returned by both Static and Instance searches.
1647 AddMembers (MemberTypes.NestedType,
1648 BindingFlags.Static | BindingFlags.Public, container);
1649 AddMembers (MemberTypes.NestedType,
1650 BindingFlags.Static | BindingFlags.NonPublic, container);
1653 void AddMembers (MemberTypes mt, IMemberContainer container)
1655 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1656 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1657 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1658 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1662 /// Add all members from class `container' with the requested MemberTypes and
1663 /// BindingFlags to the cache. This method is called multiple times with different
1664 /// MemberTypes and BindingFlags.
1666 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1668 MemberList members = container.GetMembers (mt, bf);
1670 foreach (MemberInfo member in members) {
1671 string name = member.Name;
1673 int pos = name.IndexOf ('<');
1675 name = name.Substring (0, pos);
1677 // We use a name-based hash table of ArrayList's.
1678 ArrayList list = (ArrayList) member_hash [name];
1680 list = new ArrayList ();
1681 member_hash.Add (name, list);
1684 // When this method is called for the current class, the list will
1685 // already contain all inherited members from our base classes.
1686 // We cannot add new members in front of the list since this'd be an
1687 // expensive operation, that's why the list is sorted in reverse order
1688 // (ie. members from the current class are coming last).
1689 list.Add (new CacheEntry (container, member, mt, bf));
1694 /// Add all declared and inherited methods from class `type' to the method cache.
1696 void AddMethods (Type type)
1698 AddMethods (BindingFlags.Static | BindingFlags.Public |
1699 BindingFlags.FlattenHierarchy, type);
1700 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1701 BindingFlags.FlattenHierarchy, type);
1702 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1703 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1706 static ArrayList overrides = new ArrayList ();
1708 void AddMethods (BindingFlags bf, Type type)
1710 MethodBase [] members = type.GetMethods (bf);
1712 Array.Reverse (members);
1714 foreach (MethodBase member in members) {
1715 string name = member.Name;
1717 // We use a name-based hash table of ArrayList's.
1718 ArrayList list = (ArrayList) method_hash [name];
1720 list = new ArrayList ();
1721 method_hash.Add (name, list);
1724 MethodInfo curr = (MethodInfo) member;
1725 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1726 MethodInfo base_method = curr.GetBaseDefinition ();
1728 if (base_method == curr)
1729 // Not every virtual function needs to have a NewSlot flag.
1732 overrides.Add (curr);
1733 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1737 if (overrides.Count > 0) {
1738 for (int i = 0; i < overrides.Count; ++i)
1739 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1743 // Unfortunately, the elements returned by Type.GetMethods() aren't
1744 // sorted so we need to do this check for every member.
1745 BindingFlags new_bf = bf;
1746 if (member.DeclaringType == type)
1747 new_bf |= BindingFlags.DeclaredOnly;
1749 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1754 /// Compute and return a appropriate `EntryType' magic number for the given
1755 /// MemberTypes and BindingFlags.
1757 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1759 EntryType type = EntryType.None;
1761 if ((mt & MemberTypes.Constructor) != 0)
1762 type |= EntryType.Constructor;
1763 if ((mt & MemberTypes.Event) != 0)
1764 type |= EntryType.Event;
1765 if ((mt & MemberTypes.Field) != 0)
1766 type |= EntryType.Field;
1767 if ((mt & MemberTypes.Method) != 0)
1768 type |= EntryType.Method;
1769 if ((mt & MemberTypes.Property) != 0)
1770 type |= EntryType.Property;
1771 // Nested types are returned by static and instance searches.
1772 if ((mt & MemberTypes.NestedType) != 0)
1773 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1775 if ((bf & BindingFlags.Instance) != 0)
1776 type |= EntryType.Instance;
1777 if ((bf & BindingFlags.Static) != 0)
1778 type |= EntryType.Static;
1779 if ((bf & BindingFlags.Public) != 0)
1780 type |= EntryType.Public;
1781 if ((bf & BindingFlags.NonPublic) != 0)
1782 type |= EntryType.NonPublic;
1783 if ((bf & BindingFlags.DeclaredOnly) != 0)
1784 type |= EntryType.Declared;
1790 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1791 /// denote multiple member types. Returns true if the given flags value denotes a
1792 /// single member types.
1794 public static bool IsSingleMemberType (MemberTypes mt)
1797 case MemberTypes.Constructor:
1798 case MemberTypes.Event:
1799 case MemberTypes.Field:
1800 case MemberTypes.Method:
1801 case MemberTypes.Property:
1802 case MemberTypes.NestedType:
1811 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1812 /// number to speed up the searching process.
1815 protected enum EntryType {
1820 MaskStatic = Instance|Static,
1824 MaskProtection = Public|NonPublic,
1828 Constructor = 0x020,
1835 MaskType = Constructor|Event|Field|Method|Property|NestedType
1838 protected class CacheEntry {
1839 public readonly IMemberContainer Container;
1840 public readonly EntryType EntryType;
1841 public readonly MemberInfo Member;
1843 public CacheEntry (IMemberContainer container, MemberInfo member,
1844 MemberTypes mt, BindingFlags bf)
1846 this.Container = container;
1847 this.Member = member;
1848 this.EntryType = GetEntryType (mt, bf);
1851 public override string ToString ()
1853 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1859 /// This is called each time we're walking up one level in the class hierarchy
1860 /// and checks whether we can abort the search since we've already found what
1861 /// we were looking for.
1863 protected bool DoneSearching (ArrayList list)
1866 // We've found exactly one member in the current class and it's not
1867 // a method or constructor.
1869 if (list.Count == 1 && !(list [0] is MethodBase))
1873 // Multiple properties: we query those just to find out the indexer
1876 if ((list.Count > 0) && (list [0] is PropertyInfo))
1883 /// Looks up members with name `name'. If you provide an optional
1884 /// filter function, it'll only be called with members matching the
1885 /// requested member name.
1887 /// This method will try to use the cache to do the lookup if possible.
1889 /// Unlike other FindMembers implementations, this method will always
1890 /// check all inherited members - even when called on an interface type.
1892 /// If you know that you're only looking for methods, you should use
1893 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1894 /// When doing a method-only search, it'll try to use a special method
1895 /// cache (unless it's a dynamic type or an interface) and the returned
1896 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1897 /// The lookup process will automatically restart itself in method-only
1898 /// search mode if it discovers that it's about to return methods.
1900 ArrayList global = new ArrayList ();
1901 bool using_global = false;
1903 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1905 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1906 MemberFilter filter, object criteria)
1909 throw new Exception ();
1911 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1912 bool method_search = mt == MemberTypes.Method;
1913 // If we have a method cache and we aren't already doing a method-only search,
1914 // then we restart a method search if the first match is a method.
1915 bool do_method_search = !method_search && (method_hash != null);
1917 ArrayList applicable;
1919 // If this is a method-only search, we try to use the method cache if
1920 // possible; a lookup in the method cache will return a MemberInfo with
1921 // the correct ReflectedType for inherited methods.
1923 if (method_search && (method_hash != null))
1924 applicable = (ArrayList) method_hash [name];
1926 applicable = (ArrayList) member_hash [name];
1928 if (applicable == null)
1929 return emptyMemberInfo;
1932 // 32 slots gives 53 rss/54 size
1933 // 2/4 slots gives 55 rss
1935 // Strange: from 25,000 calls, only 1,800
1936 // are above 2. Why does this impact it?
1939 using_global = true;
1941 Timer.StartTimer (TimerType.CachedLookup);
1943 EntryType type = GetEntryType (mt, bf);
1945 IMemberContainer current = Container;
1948 // `applicable' is a list of all members with the given member name `name'
1949 // in the current class and all its base classes. The list is sorted in
1950 // reverse order due to the way how the cache is initialy created (to speed
1951 // things up, we're doing a deep-copy of our base).
1953 for (int i = applicable.Count-1; i >= 0; i--) {
1954 CacheEntry entry = (CacheEntry) applicable [i];
1956 // This happens each time we're walking one level up in the class
1957 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1958 // the first time this happens (this may already happen in the first
1959 // iteration of this loop if there are no members with the name we're
1960 // looking for in the current class).
1961 if (entry.Container != current) {
1962 if (declared_only || DoneSearching (global))
1965 current = entry.Container;
1968 // Is the member of the correct type ?
1969 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1972 // Is the member static/non-static ?
1973 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1976 // Apply the filter to it.
1977 if (filter (entry.Member, criteria)) {
1978 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1979 do_method_search = false;
1980 global.Add (entry.Member);
1984 Timer.StopTimer (TimerType.CachedLookup);
1986 // If we have a method cache and we aren't already doing a method-only
1987 // search, we restart in method-only search mode if the first match is
1988 // a method. This ensures that we return a MemberInfo with the correct
1989 // ReflectedType for inherited methods.
1990 if (do_method_search && (global.Count > 0)){
1991 using_global = false;
1993 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1996 using_global = false;
1997 MemberInfo [] copy = new MemberInfo [global.Count];
1998 global.CopyTo (copy);
2002 // find the nested type @name in @this.
2003 public Type FindNestedType (string name)
2005 ArrayList applicable = (ArrayList) member_hash [name];
2006 if (applicable == null)
2009 for (int i = applicable.Count-1; i >= 0; i--) {
2010 CacheEntry entry = (CacheEntry) applicable [i];
2011 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2012 return (Type) entry.Member;
2019 // This finds the method or property for us to override. invocationType is the type where
2020 // the override is going to be declared, name is the name of the method/property, and
2021 // paramTypes is the parameters, if any to the method or property
2023 // Because the MemberCache holds members from this class and all the base classes,
2024 // we can avoid tons of reflection stuff.
2026 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, GenericMethod genericMethod, bool is_property)
2028 ArrayList applicable;
2029 if (method_hash != null && !is_property)
2030 applicable = (ArrayList) method_hash [name];
2032 applicable = (ArrayList) member_hash [name];
2034 if (applicable == null)
2037 // Walk the chain of methods, starting from the top.
2039 for (int i = applicable.Count - 1; i >= 0; i--) {
2040 CacheEntry entry = (CacheEntry) applicable [i];
2042 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2045 PropertyInfo pi = null;
2046 MethodInfo mi = null;
2047 FieldInfo fi = null;
2048 Type [] cmpAttrs = null;
2051 if ((entry.EntryType & EntryType.Field) != 0) {
2052 fi = (FieldInfo)entry.Member;
2054 // TODO: For this case we ignore member type
2055 //fb = TypeManager.GetField (fi);
2056 //cmpAttrs = new Type[] { fb.MemberType };
2058 pi = (PropertyInfo) entry.Member;
2059 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2062 mi = (MethodInfo) entry.Member;
2063 cmpAttrs = TypeManager.GetParameterData (mi).Types;
2067 // TODO: Almost duplicate !
2069 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2070 case FieldAttributes.Private:
2072 // A private method is Ok if we are a nested subtype.
2073 // The spec actually is not very clear about this, see bug 52458.
2075 if (invocationType != entry.Container.Type &
2076 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2080 case FieldAttributes.FamANDAssem:
2081 case FieldAttributes.Assembly:
2083 // Check for assembly methods
2085 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2089 return entry.Member;
2093 // Check the arguments
2095 if (cmpAttrs.Length != paramTypes.Length)
2098 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2099 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2104 // check generic arguments for methods
2107 Type [] cmpGenArgs = mi.GetGenericArguments ();
2108 if (genericMethod != null && cmpGenArgs.Length > 0) {
2109 if (genericMethod.TypeParameters.Length != cmpGenArgs.Length)
2112 else if (! (genericMethod == null && cmpGenArgs.Length == 0))
2117 // get one of the methods because this has the visibility info.
2120 mi = pi.GetGetMethod (true);
2122 mi = pi.GetSetMethod (true);
2128 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2129 case MethodAttributes.Private:
2131 // A private method is Ok if we are a nested subtype.
2132 // The spec actually is not very clear about this, see bug 52458.
2134 if (invocationType.Equals (entry.Container.Type) ||
2135 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2136 return entry.Member;
2139 case MethodAttributes.FamANDAssem:
2140 case MethodAttributes.Assembly:
2142 // Check for assembly methods
2144 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2145 return entry.Member;
2150 // A protected method is ok, because we are overriding.
2151 // public is always ok.
2153 return entry.Member;
2163 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2164 /// We handle two cases. The first is for types without parameters (events, field, properties).
2165 /// The second are methods, indexers and this is why ignore_complex_types is here.
2166 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2168 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2170 ArrayList applicable = null;
2172 if (method_hash != null)
2173 applicable = (ArrayList) method_hash [name];
2175 if (applicable != null) {
2176 for (int i = applicable.Count - 1; i >= 0; i--) {
2177 CacheEntry entry = (CacheEntry) applicable [i];
2178 if ((entry.EntryType & EntryType.Public) != 0)
2179 return entry.Member;
2183 if (member_hash == null)
2185 applicable = (ArrayList) member_hash [name];
2187 if (applicable != null) {
2188 for (int i = applicable.Count - 1; i >= 0; i--) {
2189 CacheEntry entry = (CacheEntry) applicable [i];
2190 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2191 if (ignore_complex_types) {
2192 if ((entry.EntryType & EntryType.Method) != 0)
2195 // Does exist easier way how to detect indexer ?
2196 if ((entry.EntryType & EntryType.Property) != 0) {
2197 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2198 if (arg_types.Length > 0)
2202 return entry.Member;
2209 Hashtable locase_table;
2212 /// Builds low-case table for CLS Compliance test
2214 public Hashtable GetPublicMembers ()
2216 if (locase_table != null)
2217 return locase_table;
2219 locase_table = new Hashtable ();
2220 foreach (DictionaryEntry entry in member_hash) {
2221 ArrayList members = (ArrayList)entry.Value;
2222 for (int ii = 0; ii < members.Count; ++ii) {
2223 CacheEntry member_entry = (CacheEntry) members [ii];
2225 if ((member_entry.EntryType & EntryType.Public) == 0)
2228 // TODO: Does anyone know easier way how to detect that member is internal ?
2229 switch (member_entry.EntryType & EntryType.MaskType) {
2230 case EntryType.Constructor:
2233 case EntryType.Field:
2234 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2238 case EntryType.Method:
2239 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2243 case EntryType.Property:
2244 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2245 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2249 case EntryType.Event:
2250 EventInfo ei = (EventInfo)member_entry.Member;
2251 MethodInfo mi = ei.GetAddMethod ();
2252 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2256 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2257 locase_table [lcase] = member_entry.Member;
2261 return locase_table;
2264 public Hashtable Members {
2271 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2274 // TODO: refactor as method is always 'this'
2275 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2277 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2279 for (int i = 0; i < al.Count; ++i) {
2280 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2283 if (entry.Member == this_builder)
2286 if ((entry.EntryType & tested_type) != tested_type)
2289 MethodBase method_to_compare = (MethodBase)entry.Member;
2290 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2291 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2293 if (result == AttributeTester.Result.Ok)
2296 IMethodData md = TypeManager.GetMethod (method_to_compare);
2298 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2299 // However it is exactly what csc does.
2300 if (md != null && !md.IsClsComplianceRequired ())
2303 Report.SymbolRelatedToPreviousError (entry.Member);
2305 case AttributeTester.Result.RefOutArrayError:
2306 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2308 case AttributeTester.Result.ArrayArrayError:
2309 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2313 throw new NotImplementedException (result.ToString ());