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, Location);
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 {
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 public string DocComment;
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
364 /// MemberCore flags at first detected then cached
366 internal Flags caching_flags;
368 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
371 if (parent is PartialContainer && !(this is PartialContainer))
372 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
376 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
379 protected virtual void SetMemberName (MemberName new_name)
381 member_name = new_name;
385 public abstract bool Define ();
388 // Returns full member name for error message
390 public virtual string GetSignatureForError ()
392 if (Parent == null || Parent.Parent == null)
395 return String.Concat (Parent.GetSignatureForError (), '.', Name);
399 /// Base Emit method. This is also entry point for CLS-Compliant verification.
401 public virtual void Emit ()
403 if (!RootContext.VerifyClsCompliance)
406 VerifyClsCompliance (Parent);
409 public virtual EmitContext EmitContext {
410 get { return Parent.EmitContext; }
413 public bool InUnsafe {
414 get { return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext; }
417 public virtual bool IsUsed {
418 get { return (caching_flags & Flags.IsUsed) != 0; }
421 public void SetMemberIsUsed ()
423 caching_flags |= Flags.IsUsed;
427 // Whehter is it ok to use an unsafe pointer in this type container
429 public bool UnsafeOK (DeclSpace parent)
432 // First check if this MemberCore modifier flags has unsafe set
434 if ((ModFlags & Modifiers.UNSAFE) != 0)
437 if (parent.UnsafeContext)
440 Expression.UnsafeError (Location);
445 /// Returns instance of ObsoleteAttribute for this MemberCore
447 public virtual ObsoleteAttribute GetObsoleteAttribute ()
449 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
450 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
454 caching_flags &= ~Flags.Obsolete_Undetected;
456 if (OptAttributes == null)
459 Attribute obsolete_attr = OptAttributes.Search (
460 TypeManager.obsolete_attribute_type, EmitContext);
461 if (obsolete_attr == null)
464 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (EmitContext);
465 if (obsolete == null)
468 caching_flags |= Flags.Obsolete;
473 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
475 public virtual void CheckObsoleteness (Location loc)
478 Parent.CheckObsoleteness (loc);
480 ObsoleteAttribute oa = GetObsoleteAttribute ();
485 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
488 protected void CheckObsoleteType (Expression type)
490 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type.Type);
491 if (obsolete_attr == null)
494 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
497 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (type.Type), type.Location);
501 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
503 public override bool IsClsComplianceRequired (DeclSpace container)
505 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
506 return (caching_flags & Flags.ClsCompliant) != 0;
508 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
509 caching_flags &= ~Flags.ClsCompliance_Undetected;
510 caching_flags |= Flags.ClsCompliant;
514 caching_flags &= ~Flags.ClsCompliance_Undetected;
519 /// Returns true when MemberCore is exposed from assembly.
521 public bool IsExposedFromAssembly (DeclSpace ds)
523 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
526 DeclSpace parentContainer = ds;
527 while (parentContainer != null && parentContainer.ModFlags != 0) {
528 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
530 parentContainer = parentContainer.Parent;
536 /// Resolve CLSCompliantAttribute value or gets cached value.
538 bool GetClsCompliantAttributeValue (DeclSpace ds)
540 if (OptAttributes != null) {
541 Attribute cls_attribute = OptAttributes.Search (
542 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
543 if (cls_attribute != null) {
544 caching_flags |= Flags.HasClsCompliantAttribute;
545 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
548 return ds.GetClsCompliantAttributeValue ();
552 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
554 protected bool HasClsCompliantAttribute {
556 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
561 /// It helps to handle error 102 & 111 detection
563 public virtual bool MarkForDuplicationCheck ()
569 /// The main virtual method for CLS-Compliant verifications.
570 /// The method returns true if member is CLS-Compliant and false if member is not
571 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
572 /// and add their extra verifications.
574 protected virtual bool VerifyClsCompliance (DeclSpace ds)
576 if (!IsClsComplianceRequired (ds)) {
577 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
578 if (!IsExposedFromAssembly (ds))
579 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
580 if (!CodeGen.Assembly.IsClsCompliant)
581 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
586 if (!CodeGen.Assembly.IsClsCompliant) {
587 if (HasClsCompliantAttribute) {
588 Report.Error (3014, Location,
589 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
590 GetSignatureForError ());
595 if (member_name.Name [0] == '_') {
596 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
602 // Raised (and passed an XmlElement that contains the comment)
603 // when GenerateDocComment is writing documentation expectedly.
605 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
610 // Returns a string that represents the signature for this
611 // member which should be used in XML documentation.
613 public virtual string GetDocCommentName (DeclSpace ds)
615 if (ds == null || this is DeclSpace)
616 return DocCommentHeader + Name;
618 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
622 // Generates xml doc comments (if any), and if required,
623 // handle warning report.
625 internal virtual void GenerateDocComment (DeclSpace ds)
627 DocUtil.GenerateDocComment (this, ds);
632 /// Base class for structs, classes, enumerations and interfaces.
635 /// They all create new declaration spaces. This
636 /// provides the common foundation for managing those name
639 public abstract class DeclSpace : MemberCore {
641 /// This points to the actual definition that is being
642 /// created with System.Reflection.Emit
644 public TypeBuilder TypeBuilder;
647 /// If we are a generic type, this is the type we are
648 /// currently defining. We need to lookup members on this
649 /// instead of the TypeBuilder.
651 public Type CurrentType;
654 // This is the namespace in which this typecontainer
655 // was declared. We use this to resolve names.
657 public NamespaceEntry NamespaceEntry;
659 private Hashtable Cache = new Hashtable ();
661 public readonly string Basename;
663 protected Hashtable defined_names;
665 readonly bool is_generic;
666 readonly int count_type_params;
667 readonly int count_current_type_params;
669 // The emit context for toplevel objects.
670 protected EmitContext ec;
672 public override EmitContext EmitContext {
677 // Whether we are Generic
679 public bool IsGeneric {
683 else if (Parent != null)
684 return Parent.IsGeneric;
690 static string[] attribute_targets = new string [] { "type" };
692 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
694 : base (parent, name, attrs)
697 Basename = name.Basename;
698 defined_names = new Hashtable ();
699 if (name.TypeArguments != null) {
701 count_type_params = count_current_type_params = name.TypeArguments.Count;
704 count_type_params += parent.count_type_params;
708 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
710 protected bool AddToContainer (MemberCore symbol, string name)
712 if (name == MemberName.Name && !(this is Interface) && !(this is Enum)) {
713 if (symbol is TypeParameter)
714 Report.Error (694, symbol.Location,
715 "Type parameter `{0}' has same name as " +
716 "containing type, or method", name);
718 Report.SymbolRelatedToPreviousError (this);
719 Report.Error (542, symbol.Location,
720 "`{0}': member names cannot be the same " +
721 "as their enclosing type",
722 symbol.GetSignatureForError ());
727 MemberCore mc = (MemberCore) defined_names [name];
730 defined_names.Add (name, symbol);
734 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
737 Report.SymbolRelatedToPreviousError (mc);
738 if (symbol is PartialContainer || mc is PartialContainer) {
739 Report.Error (260, symbol.Location,
740 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
745 if (this is RootTypes) {
746 Report.Error (101, symbol.Location,
747 "The namespace `{0}' already contains a definition for `{1}'",
748 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
749 } else if (symbol is TypeParameter) {
750 Report.Error (692, symbol.Location,
751 "Duplicate type parameter `{0}'", name);
753 Report.Error (102, symbol.Location,
754 "The type `{0}' already contains a definition for `{1}'",
755 GetSignatureForError (), symbol.MemberName.Name);
762 /// Returns the MemberCore associated with a given name in the declaration
763 /// space. It doesn't return method based symbols !!
766 public MemberCore GetDefinition (string name)
768 return (MemberCore)defined_names [name];
772 // root_types contains all the types. All TopLevel types
773 // hence have a parent that points to `root_types', that is
774 // why there is a non-obvious test down here.
776 public bool IsTopLevel {
777 get { return (Parent != null && Parent.Parent == null); }
780 public virtual void CloseType ()
782 if ((caching_flags & Flags.CloseTypeCreated) == 0){
784 TypeBuilder.CreateType ();
787 // The try/catch is needed because
788 // nested enumerations fail to load when they
791 // Even if this is the right order (enumerations
792 // declared after types).
794 // Note that this still creates the type and
795 // it is possible to save it
797 caching_flags |= Flags.CloseTypeCreated;
801 protected virtual TypeAttributes TypeAttr {
802 get { return CodeGen.Module.DefaultCharSetType; }
806 /// Should be overriten by the appropriate declaration space
808 public abstract TypeBuilder DefineType ();
811 /// Define all members, but don't apply any attributes or do anything which may
812 /// access not-yet-defined classes. This method also creates the MemberCache.
814 public virtual bool DefineMembers ()
816 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
817 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
823 public override string GetSignatureForError ()
826 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
828 // Parent.GetSignatureForError
833 // Whether this is an `unsafe context'
835 public bool UnsafeContext {
837 if ((ModFlags & Modifiers.UNSAFE) != 0)
840 return Parent.UnsafeContext;
845 EmitContext type_resolve_ec;
846 protected EmitContext TypeResolveEmitContext {
848 if (type_resolve_ec == null) {
849 // FIXME: I think this should really be one of:
851 // a. type_resolve_ec = Parent.EmitContext;
852 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
854 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
856 type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
858 return type_resolve_ec;
863 // Resolves the expression `e' for a type, and will recursively define
864 // types. This should only be used for resolving base types.
866 protected TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
868 TypeResolveEmitContext.loc = loc;
869 TypeResolveEmitContext.ResolvingTypeTree = true;
870 if (this is GenericMethod)
871 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
872 return e.ResolveAsTypeTerminal (TypeResolveEmitContext);
875 public bool CheckAccessLevel (Type check_type)
878 if ((this is GenericMethod) || (this is Iterator))
879 tb = Parent.TypeBuilder;
883 check_type = TypeManager.DropGenericTypeArguments (check_type);
884 if (check_type == tb)
887 if (TypeBuilder == null)
888 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
889 // However, this is invoked again later -- so safe to return true.
890 // May also be null when resolving top-level attributes.
893 if (check_type.IsGenericParameter)
894 return true; // FIXME
896 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
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));
907 case TypeAttributes.Public:
910 case TypeAttributes.NotPublic:
912 if (TypeBuilder == null)
913 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
914 // However, this is invoked again later -- so safe to return true.
915 // May also be null when resolving top-level attributes.
918 // This test should probably use the declaringtype.
920 return check_type.Assembly == TypeBuilder.Assembly ||
921 TypeManager.IsFriendAssembly (check_type.Assembly);
923 case TypeAttributes.NestedPublic:
926 case TypeAttributes.NestedPrivate:
927 return NestedAccessible (tb, check_type);
929 case TypeAttributes.NestedFamily:
931 // Only accessible to methods in current type or any subtypes
933 return FamilyAccessible (tb, check_type);
935 case TypeAttributes.NestedFamANDAssem:
936 return ((check_type.Assembly == tb.Assembly) ||
937 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
938 FamilyAccessible (tb, check_type);
940 case TypeAttributes.NestedFamORAssem:
941 return (check_type.Assembly == tb.Assembly) ||
942 FamilyAccessible (tb, check_type) ||
943 TypeManager.IsFriendAssembly (check_type.Assembly);
945 case TypeAttributes.NestedAssembly:
946 return check_type.Assembly == tb.Assembly ||
947 TypeManager.IsFriendAssembly (check_type.Assembly);
950 Console.WriteLine ("HERE: " + check_attr);
955 protected bool NestedAccessible (Type tb, Type check_type)
957 Type declaring = check_type.DeclaringType;
958 return TypeBuilder == declaring ||
959 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
962 protected bool FamilyAccessible (Type tb, Type check_type)
964 Type declaring = check_type.DeclaringType;
965 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
968 // Access level of a type.
970 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
971 // Public Assembly Protected
972 Protected = (0 << 0) | (0 << 1) | (X << 2),
973 Public = (X << 0) | (X << 1) | (X << 2),
974 Private = (0 << 0) | (0 << 1) | (0 << 2),
975 Internal = (0 << 0) | (X << 1) | (0 << 2),
976 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
979 static AccessLevel GetAccessLevelFromModifiers (int flags)
981 if ((flags & Modifiers.INTERNAL) != 0) {
983 if ((flags & Modifiers.PROTECTED) != 0)
984 return AccessLevel.ProtectedOrInternal;
986 return AccessLevel.Internal;
988 } else if ((flags & Modifiers.PROTECTED) != 0)
989 return AccessLevel.Protected;
990 else if ((flags & Modifiers.PRIVATE) != 0)
991 return AccessLevel.Private;
993 return AccessLevel.Public;
996 // What is the effective access level of this?
998 AccessLevel EffectiveAccessLevel {
1000 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1001 if (!IsTopLevel && (Parent != null))
1002 return myAccess & Parent.EffectiveAccessLevel;
1007 // Return the access level for type `t'
1008 static AccessLevel TypeEffectiveAccessLevel (Type t)
1011 return AccessLevel.Public;
1012 if (t.IsNestedPrivate)
1013 return AccessLevel.Private;
1015 return AccessLevel.Internal;
1017 // By now, it must be nested
1018 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1020 if (t.IsNestedPublic)
1022 if (t.IsNestedAssembly)
1023 return parentLevel & AccessLevel.Internal;
1024 if (t.IsNestedFamily)
1025 return parentLevel & AccessLevel.Protected;
1026 if (t.IsNestedFamORAssem)
1027 return parentLevel & AccessLevel.ProtectedOrInternal;
1028 if (t.IsNestedFamANDAssem)
1029 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1031 // nested private is taken care of
1033 throw new Exception ("I give up, what are you?");
1037 // This answers `is the type P, as accessible as a member M which has the
1038 // accessability @flags which is declared as a nested member of the type T, this declspace'
1040 public bool AsAccessible (Type p, int flags)
1042 if (p.IsGenericParameter)
1043 return true; // FIXME
1046 // 1) if M is private, its accessability is the same as this declspace.
1047 // we already know that P is accessible to T before this method, so we
1051 if ((flags & Modifiers.PRIVATE) != 0)
1054 while (p.IsArray || p.IsPointer || p.IsByRef)
1055 p = TypeManager.GetElementType (p);
1057 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1058 AccessLevel mAccess = this.EffectiveAccessLevel &
1059 GetAccessLevelFromModifiers (flags);
1061 // for every place from which we can access M, we must
1062 // be able to access P as well. So, we want
1063 // For every bit in M and P, M_i -> P_1 == true
1064 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1066 return ~ (~ mAccess | pAccess) == 0;
1070 // Return the nested type with name @name. Ensures that the nested type
1071 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1073 public virtual Type FindNestedType (string name)
1078 private Type LookupNestedTypeInHierarchy (string name)
1080 // if the member cache has been created, lets use it.
1081 // the member cache is MUCH faster.
1082 if (MemberCache != null)
1083 return MemberCache.FindNestedType (name);
1085 // no member cache. Do it the hard way -- reflection
1087 for (Type current_type = TypeBuilder;
1088 current_type != null && current_type != TypeManager.object_type;
1089 current_type = current_type.BaseType) {
1090 current_type = TypeManager.DropGenericTypeArguments (current_type);
1091 if (current_type is TypeBuilder) {
1092 DeclSpace decl = this;
1093 if (current_type != TypeBuilder)
1094 decl = TypeManager.LookupDeclSpace (current_type);
1095 t = decl.FindNestedType (name);
1097 t = TypeManager.GetNestedType (current_type, name);
1100 if (t != null && CheckAccessLevel (t))
1108 // Public function used to locate types.
1110 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1112 // Returns: Type or null if they type can not be found.
1114 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1116 if (this is PartialContainer)
1117 throw new InternalErrorException ("Should not get here");
1119 if (Cache.Contains (name))
1120 return (FullNamedExpression) Cache [name];
1122 FullNamedExpression e;
1123 Type t = LookupNestedTypeInHierarchy (name);
1125 e = new TypeExpression (t, Location.Null);
1126 else if (Parent != null && Parent != RootContext.Tree.Types)
1127 e = Parent.LookupType (name, loc, ignore_cs0104);
1129 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1136 /// This function is broken and not what you're looking for. It should only
1137 /// be used while the type is still being created since it doesn't use the cache
1138 /// and relies on the filter doing the member name check.
1140 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1141 MemberFilter filter, object criteria);
1144 /// If we have a MemberCache, return it. This property may return null if the
1145 /// class doesn't have a member cache or while it's still being created.
1147 public abstract MemberCache MemberCache {
1151 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1153 if (a.Type == TypeManager.required_attr_type) {
1154 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1157 TypeBuilder.SetCustomAttribute (cb);
1161 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1162 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1164 public bool GetClsCompliantAttributeValue ()
1166 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1167 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1169 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1171 if (OptAttributes != null) {
1172 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1173 if (cls_attribute != null) {
1174 caching_flags |= Flags.HasClsCompliantAttribute;
1175 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1176 caching_flags |= Flags.ClsCompliantAttributeTrue;
1183 if (Parent == null) {
1184 if (CodeGen.Assembly.IsClsCompliant) {
1185 caching_flags |= Flags.ClsCompliantAttributeTrue;
1191 if (Parent.GetClsCompliantAttributeValue ()) {
1192 caching_flags |= Flags.ClsCompliantAttributeTrue;
1199 // Extensions for generics
1201 TypeParameter[] type_params;
1202 TypeParameter[] type_param_list;
1204 protected string GetInstantiationName ()
1206 StringBuilder sb = new StringBuilder (Name);
1208 for (int i = 0; i < type_param_list.Length; i++) {
1211 sb.Append (type_param_list [i].Name);
1214 return sb.ToString ();
1217 bool check_type_parameter (ArrayList list, int start, string name)
1219 for (int i = 0; i < start; i++) {
1220 TypeParameter param = (TypeParameter) list [i];
1222 if (param.Name != name)
1225 Report.Warning (693, 3, Location,
1226 "Type parameter `{0}' has same name as type parameter from outer type `{1}'",
1227 name, Parent.GetInstantiationName ());
1235 TypeParameter[] initialize_type_params ()
1237 if (type_param_list != null)
1238 return type_param_list;
1240 DeclSpace the_parent = Parent;
1241 if (this is GenericMethod)
1245 TypeParameter[] parent_params = null;
1246 if ((the_parent != null) && the_parent.IsGeneric) {
1247 parent_params = the_parent.initialize_type_params ();
1248 start = parent_params != null ? parent_params.Length : 0;
1251 ArrayList list = new ArrayList ();
1252 if (parent_params != null)
1253 list.AddRange (parent_params);
1255 int count = type_params != null ? type_params.Length : 0;
1256 for (int i = 0; i < count; i++) {
1257 TypeParameter param = type_params [i];
1258 check_type_parameter (list, start, param.Name);
1262 type_param_list = new TypeParameter [list.Count];
1263 list.CopyTo (type_param_list, 0);
1264 return type_param_list;
1267 public virtual void SetParameterInfo (ArrayList constraints_list)
1270 if (constraints_list != null) {
1272 80, Location, "Constraints are not allowed " +
1273 "on non-generic declarations");
1279 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1280 type_params = new TypeParameter [names.Length];
1283 // Register all the names
1285 for (int i = 0; i < type_params.Length; i++) {
1286 TypeParameterName name = names [i];
1288 Constraints constraints = null;
1289 if (constraints_list != null) {
1290 foreach (Constraints constraint in constraints_list) {
1291 if (constraint == null)
1293 if (constraint.TypeParameter == name.Name) {
1294 constraints = constraint;
1300 type_params [i] = new TypeParameter (
1301 Parent, this, name.Name, constraints, name.OptAttributes,
1304 AddToContainer (type_params [i], name.Name);
1308 public TypeParameter[] TypeParameters {
1311 throw new InvalidOperationException ();
1312 if (type_param_list == null)
1313 initialize_type_params ();
1315 return type_param_list;
1319 public TypeParameter[] CurrentTypeParameters {
1322 throw new InvalidOperationException ();
1323 if (type_params != null)
1326 return new TypeParameter [0];
1330 public int CountTypeParameters {
1332 return count_type_params;
1336 public int CountCurrentTypeParameters {
1338 return count_current_type_params;
1342 public TypeParameterExpr LookupGeneric (string name, Location loc)
1347 foreach (TypeParameter type_param in CurrentTypeParameters) {
1348 if (type_param.Name != name)
1351 return new TypeParameterExpr (type_param, loc);
1355 return Parent.LookupGeneric (name, loc);
1360 public override string[] ValidAttributeTargets {
1361 get { return attribute_targets; }
1364 protected override bool VerifyClsCompliance (DeclSpace ds)
1366 if (!base.VerifyClsCompliance (ds)) {
1370 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1371 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1372 if (!cache.Contains (lcase)) {
1373 cache.Add (lcase, this);
1377 object val = cache [lcase];
1379 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1382 Report.SymbolRelatedToPreviousError (t);
1385 if (val is PartialContainer)
1388 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1390 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1396 /// This is a readonly list of MemberInfo's.
1398 public class MemberList : IList {
1399 public readonly IList List;
1403 /// Create a new MemberList from the given IList.
1405 public MemberList (IList list)
1410 this.List = new ArrayList ();
1415 /// Concatenate the ILists `first' and `second' to a new MemberList.
1417 public MemberList (IList first, IList second)
1419 ArrayList list = new ArrayList ();
1420 list.AddRange (first);
1421 list.AddRange (second);
1426 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1429 /// Cast the MemberList into a MemberInfo[] array.
1432 /// This is an expensive operation, only use it if it's really necessary.
1434 public static explicit operator MemberInfo [] (MemberList list)
1436 Timer.StartTimer (TimerType.MiscTimer);
1437 MemberInfo [] result = new MemberInfo [list.Count];
1438 list.CopyTo (result, 0);
1439 Timer.StopTimer (TimerType.MiscTimer);
1451 public bool IsSynchronized {
1453 return List.IsSynchronized;
1457 public object SyncRoot {
1459 return List.SyncRoot;
1463 public void CopyTo (Array array, int index)
1465 List.CopyTo (array, index);
1470 public IEnumerator GetEnumerator ()
1472 return List.GetEnumerator ();
1477 public bool IsFixedSize {
1483 public bool IsReadOnly {
1489 object IList.this [int index] {
1491 return List [index];
1495 throw new NotSupportedException ();
1499 // FIXME: try to find out whether we can avoid the cast in this indexer.
1500 public MemberInfo this [int index] {
1502 return (MemberInfo) List [index];
1506 public int Add (object value)
1508 throw new NotSupportedException ();
1511 public void Clear ()
1513 throw new NotSupportedException ();
1516 public bool Contains (object value)
1518 return List.Contains (value);
1521 public int IndexOf (object value)
1523 return List.IndexOf (value);
1526 public void Insert (int index, object value)
1528 throw new NotSupportedException ();
1531 public void Remove (object value)
1533 throw new NotSupportedException ();
1536 public void RemoveAt (int index)
1538 throw new NotSupportedException ();
1543 /// This interface is used to get all members of a class when creating the
1544 /// member cache. It must be implemented by all DeclSpace derivatives which
1545 /// want to support the member cache and by TypeHandle to get caching of
1546 /// non-dynamic types.
1548 public interface IMemberContainer {
1550 /// The name of the IMemberContainer. This is only used for
1551 /// debugging purposes.
1558 /// The type of this IMemberContainer.
1565 /// Returns the IMemberContainer of the base class or null if this
1566 /// is an interface or TypeManger.object_type.
1567 /// This is used when creating the member cache for a class to get all
1568 /// members from the base class.
1570 MemberCache BaseCache {
1575 /// Whether this is an interface.
1582 /// Returns all members of this class with the corresponding MemberTypes
1583 /// and BindingFlags.
1586 /// When implementing this method, make sure not to return any inherited
1587 /// members and check the MemberTypes and BindingFlags properly.
1588 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1589 /// get the BindingFlags (static/non-static,public/non-public) in the
1590 /// MemberInfo class, but the cache needs this information. That's why
1591 /// this method is called multiple times with different BindingFlags.
1593 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1596 /// Return the container's member cache.
1598 MemberCache MemberCache {
1604 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1605 /// member lookups. It has a member name based hash table; it maps each member
1606 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1607 /// and the BindingFlags that were initially used to get it. The cache contains
1608 /// all members of the current class and all inherited members. If this cache is
1609 /// for an interface types, it also contains all inherited members.
1611 /// There are two ways to get a MemberCache:
1612 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1613 /// use the DeclSpace.MemberCache property.
1614 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1615 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1617 public class MemberCache {
1618 public readonly IMemberContainer Container;
1619 protected Hashtable member_hash;
1620 protected Hashtable method_hash;
1623 /// Create a new MemberCache for the given IMemberContainer `container'.
1625 public MemberCache (IMemberContainer container)
1627 this.Container = container;
1629 Timer.IncrementCounter (CounterType.MemberCache);
1630 Timer.StartTimer (TimerType.CacheInit);
1632 // If we have a base class (we have a base class unless we're
1633 // TypeManager.object_type), we deep-copy its MemberCache here.
1634 if (Container.BaseCache != null)
1635 member_hash = SetupCache (Container.BaseCache);
1637 member_hash = new Hashtable ();
1639 // If this is neither a dynamic type nor an interface, create a special
1640 // method cache with all declared and inherited methods.
1641 Type type = container.Type;
1642 if (!(type is TypeBuilder) && !type.IsInterface &&
1643 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1644 !type.IsGenericType &&
1645 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1646 method_hash = new Hashtable ();
1650 // Add all members from the current class.
1651 AddMembers (Container);
1653 Timer.StopTimer (TimerType.CacheInit);
1656 public MemberCache (Type[] ifaces)
1659 // The members of this cache all belong to other caches.
1660 // So, 'Container' will not be used.
1662 this.Container = null;
1664 member_hash = new Hashtable ();
1668 foreach (Type itype in ifaces)
1669 AddCacheContents (TypeManager.LookupMemberCache (itype));
1673 /// Bootstrap this member cache by doing a deep-copy of our base.
1675 Hashtable SetupCache (MemberCache base_class)
1677 Hashtable hash = new Hashtable ();
1679 if (base_class == null)
1682 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1683 while (it.MoveNext ()) {
1684 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1691 /// Add the contents of `cache' to the member_hash.
1693 void AddCacheContents (MemberCache cache)
1695 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1696 while (it.MoveNext ()) {
1697 ArrayList list = (ArrayList) member_hash [it.Key];
1699 member_hash [it.Key] = list = new ArrayList ();
1701 ArrayList entries = (ArrayList) it.Value;
1702 for (int i = entries.Count-1; i >= 0; i--) {
1703 CacheEntry entry = (CacheEntry) entries [i];
1705 if (entry.Container != cache.Container)
1713 /// Add all members from class `container' to the cache.
1715 void AddMembers (IMemberContainer container)
1717 // We need to call AddMembers() with a single member type at a time
1718 // to get the member type part of CacheEntry.EntryType right.
1719 if (!container.IsInterface) {
1720 AddMembers (MemberTypes.Constructor, container);
1721 AddMembers (MemberTypes.Field, container);
1723 AddMembers (MemberTypes.Method, container);
1724 AddMembers (MemberTypes.Property, container);
1725 AddMembers (MemberTypes.Event, container);
1726 // Nested types are returned by both Static and Instance searches.
1727 AddMembers (MemberTypes.NestedType,
1728 BindingFlags.Static | BindingFlags.Public, container);
1729 AddMembers (MemberTypes.NestedType,
1730 BindingFlags.Static | BindingFlags.NonPublic, container);
1733 void AddMembers (MemberTypes mt, IMemberContainer container)
1735 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1736 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1737 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1738 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1742 /// Add all members from class `container' with the requested MemberTypes and
1743 /// BindingFlags to the cache. This method is called multiple times with different
1744 /// MemberTypes and BindingFlags.
1746 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1748 MemberList members = container.GetMembers (mt, bf);
1750 foreach (MemberInfo member in members) {
1751 string name = member.Name;
1753 int pos = name.IndexOf ('<');
1755 name = name.Substring (0, pos);
1757 // We use a name-based hash table of ArrayList's.
1758 ArrayList list = (ArrayList) member_hash [name];
1760 list = new ArrayList ();
1761 member_hash.Add (name, list);
1764 // When this method is called for the current class, the list will
1765 // already contain all inherited members from our base classes.
1766 // We cannot add new members in front of the list since this'd be an
1767 // expensive operation, that's why the list is sorted in reverse order
1768 // (ie. members from the current class are coming last).
1769 list.Add (new CacheEntry (container, member, mt, bf));
1774 /// Add all declared and inherited methods from class `type' to the method cache.
1776 void AddMethods (Type type)
1778 AddMethods (BindingFlags.Static | BindingFlags.Public |
1779 BindingFlags.FlattenHierarchy, type);
1780 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1781 BindingFlags.FlattenHierarchy, type);
1782 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1783 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1786 static ArrayList overrides = new ArrayList ();
1788 void AddMethods (BindingFlags bf, Type type)
1790 MethodBase [] members = type.GetMethods (bf);
1792 Array.Reverse (members);
1794 foreach (MethodBase member in members) {
1795 string name = member.Name;
1797 // We use a name-based hash table of ArrayList's.
1798 ArrayList list = (ArrayList) method_hash [name];
1800 list = new ArrayList ();
1801 method_hash.Add (name, list);
1804 MethodInfo curr = (MethodInfo) member;
1805 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1806 MethodInfo base_method = curr.GetBaseDefinition ();
1808 if (base_method == curr)
1809 // Not every virtual function needs to have a NewSlot flag.
1812 overrides.Add (curr);
1813 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1817 if (overrides.Count > 0) {
1818 for (int i = 0; i < overrides.Count; ++i)
1819 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1823 // Unfortunately, the elements returned by Type.GetMethods() aren't
1824 // sorted so we need to do this check for every member.
1825 BindingFlags new_bf = bf;
1826 if (member.DeclaringType == type)
1827 new_bf |= BindingFlags.DeclaredOnly;
1829 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1834 /// Compute and return a appropriate `EntryType' magic number for the given
1835 /// MemberTypes and BindingFlags.
1837 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1839 EntryType type = EntryType.None;
1841 if ((mt & MemberTypes.Constructor) != 0)
1842 type |= EntryType.Constructor;
1843 if ((mt & MemberTypes.Event) != 0)
1844 type |= EntryType.Event;
1845 if ((mt & MemberTypes.Field) != 0)
1846 type |= EntryType.Field;
1847 if ((mt & MemberTypes.Method) != 0)
1848 type |= EntryType.Method;
1849 if ((mt & MemberTypes.Property) != 0)
1850 type |= EntryType.Property;
1851 // Nested types are returned by static and instance searches.
1852 if ((mt & MemberTypes.NestedType) != 0)
1853 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1855 if ((bf & BindingFlags.Instance) != 0)
1856 type |= EntryType.Instance;
1857 if ((bf & BindingFlags.Static) != 0)
1858 type |= EntryType.Static;
1859 if ((bf & BindingFlags.Public) != 0)
1860 type |= EntryType.Public;
1861 if ((bf & BindingFlags.NonPublic) != 0)
1862 type |= EntryType.NonPublic;
1863 if ((bf & BindingFlags.DeclaredOnly) != 0)
1864 type |= EntryType.Declared;
1870 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1871 /// denote multiple member types. Returns true if the given flags value denotes a
1872 /// single member types.
1874 public static bool IsSingleMemberType (MemberTypes mt)
1877 case MemberTypes.Constructor:
1878 case MemberTypes.Event:
1879 case MemberTypes.Field:
1880 case MemberTypes.Method:
1881 case MemberTypes.Property:
1882 case MemberTypes.NestedType:
1891 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1892 /// number to speed up the searching process.
1895 protected enum EntryType {
1900 MaskStatic = Instance|Static,
1904 MaskProtection = Public|NonPublic,
1908 Constructor = 0x020,
1915 MaskType = Constructor|Event|Field|Method|Property|NestedType
1918 protected class CacheEntry {
1919 public readonly IMemberContainer Container;
1920 public EntryType EntryType;
1921 public MemberInfo Member;
1923 public CacheEntry (IMemberContainer container, MemberInfo member,
1924 MemberTypes mt, BindingFlags bf)
1926 this.Container = container;
1927 this.Member = member;
1928 this.EntryType = GetEntryType (mt, bf);
1931 public override string ToString ()
1933 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1939 /// This is called each time we're walking up one level in the class hierarchy
1940 /// and checks whether we can abort the search since we've already found what
1941 /// we were looking for.
1943 protected bool DoneSearching (ArrayList list)
1946 // We've found exactly one member in the current class and it's not
1947 // a method or constructor.
1949 if (list.Count == 1 && !(list [0] is MethodBase))
1953 // Multiple properties: we query those just to find out the indexer
1956 if ((list.Count > 0) && (list [0] is PropertyInfo))
1963 /// Looks up members with name `name'. If you provide an optional
1964 /// filter function, it'll only be called with members matching the
1965 /// requested member name.
1967 /// This method will try to use the cache to do the lookup if possible.
1969 /// Unlike other FindMembers implementations, this method will always
1970 /// check all inherited members - even when called on an interface type.
1972 /// If you know that you're only looking for methods, you should use
1973 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1974 /// When doing a method-only search, it'll try to use a special method
1975 /// cache (unless it's a dynamic type or an interface) and the returned
1976 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1977 /// The lookup process will automatically restart itself in method-only
1978 /// search mode if it discovers that it's about to return methods.
1980 ArrayList global = new ArrayList ();
1981 bool using_global = false;
1983 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1985 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1986 MemberFilter filter, object criteria)
1989 throw new Exception ();
1991 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1992 bool method_search = mt == MemberTypes.Method;
1993 // If we have a method cache and we aren't already doing a method-only search,
1994 // then we restart a method search if the first match is a method.
1995 bool do_method_search = !method_search && (method_hash != null);
1997 ArrayList applicable;
1999 // If this is a method-only search, we try to use the method cache if
2000 // possible; a lookup in the method cache will return a MemberInfo with
2001 // the correct ReflectedType for inherited methods.
2003 if (method_search && (method_hash != null))
2004 applicable = (ArrayList) method_hash [name];
2006 applicable = (ArrayList) member_hash [name];
2008 if (applicable == null)
2009 return emptyMemberInfo;
2012 // 32 slots gives 53 rss/54 size
2013 // 2/4 slots gives 55 rss
2015 // Strange: from 25,000 calls, only 1,800
2016 // are above 2. Why does this impact it?
2019 using_global = true;
2021 Timer.StartTimer (TimerType.CachedLookup);
2023 EntryType type = GetEntryType (mt, bf);
2025 IMemberContainer current = Container;
2028 // `applicable' is a list of all members with the given member name `name'
2029 // in the current class and all its base classes. The list is sorted in
2030 // reverse order due to the way how the cache is initialy created (to speed
2031 // things up, we're doing a deep-copy of our base).
2033 for (int i = applicable.Count-1; i >= 0; i--) {
2034 CacheEntry entry = (CacheEntry) applicable [i];
2036 // This happens each time we're walking one level up in the class
2037 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2038 // the first time this happens (this may already happen in the first
2039 // iteration of this loop if there are no members with the name we're
2040 // looking for in the current class).
2041 if (entry.Container != current) {
2042 if (declared_only || DoneSearching (global))
2045 current = entry.Container;
2048 // Is the member of the correct type ?
2049 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2052 // Is the member static/non-static ?
2053 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2056 // Apply the filter to it.
2057 if (filter (entry.Member, criteria)) {
2058 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2059 do_method_search = false;
2060 global.Add (entry.Member);
2064 Timer.StopTimer (TimerType.CachedLookup);
2066 // If we have a method cache and we aren't already doing a method-only
2067 // search, we restart in method-only search mode if the first match is
2068 // a method. This ensures that we return a MemberInfo with the correct
2069 // ReflectedType for inherited methods.
2070 if (do_method_search && (global.Count > 0)){
2071 using_global = false;
2073 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2076 using_global = false;
2077 MemberInfo [] copy = new MemberInfo [global.Count];
2078 global.CopyTo (copy);
2082 // find the nested type @name in @this.
2083 public Type FindNestedType (string name)
2085 ArrayList applicable = (ArrayList) member_hash [name];
2086 if (applicable == null)
2089 for (int i = applicable.Count-1; i >= 0; i--) {
2090 CacheEntry entry = (CacheEntry) applicable [i];
2091 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2092 return (Type) entry.Member;
2099 // This finds the method or property for us to override. invocationType is the type where
2100 // the override is going to be declared, name is the name of the method/property, and
2101 // paramTypes is the parameters, if any to the method or property
2103 // Because the MemberCache holds members from this class and all the base classes,
2104 // we can avoid tons of reflection stuff.
2106 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, GenericMethod genericMethod, bool is_property)
2108 ArrayList applicable;
2109 if (method_hash != null && !is_property)
2110 applicable = (ArrayList) method_hash [name];
2112 applicable = (ArrayList) member_hash [name];
2114 if (applicable == null)
2117 // Walk the chain of methods, starting from the top.
2119 for (int i = applicable.Count - 1; i >= 0; i--) {
2120 CacheEntry entry = (CacheEntry) applicable [i];
2122 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2125 PropertyInfo pi = null;
2126 MethodInfo mi = null;
2127 FieldInfo fi = null;
2128 Type [] cmpAttrs = null;
2131 if ((entry.EntryType & EntryType.Field) != 0) {
2132 fi = (FieldInfo)entry.Member;
2134 // TODO: For this case we ignore member type
2135 //fb = TypeManager.GetField (fi);
2136 //cmpAttrs = new Type[] { fb.MemberType };
2138 pi = (PropertyInfo) entry.Member;
2139 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2142 mi = (MethodInfo) entry.Member;
2143 cmpAttrs = TypeManager.GetParameterData (mi).Types;
2147 // TODO: Almost duplicate !
2149 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2150 case FieldAttributes.Private:
2152 // A private method is Ok if we are a nested subtype.
2153 // The spec actually is not very clear about this, see bug 52458.
2155 if (invocationType != entry.Container.Type &
2156 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2160 case FieldAttributes.FamANDAssem:
2161 case FieldAttributes.Assembly:
2163 // Check for assembly methods
2165 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2169 return entry.Member;
2173 // Check the arguments
2175 if (cmpAttrs.Length != paramTypes.Length)
2178 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2179 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2184 // check generic arguments for methods
2187 Type [] cmpGenArgs = mi.GetGenericArguments ();
2188 if (genericMethod != null && cmpGenArgs.Length > 0) {
2189 if (genericMethod.TypeParameters.Length != cmpGenArgs.Length)
2192 else if (! (genericMethod == null && cmpGenArgs.Length == 0))
2197 // get one of the methods because this has the visibility info.
2200 mi = pi.GetGetMethod (true);
2202 mi = pi.GetSetMethod (true);
2208 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2209 case MethodAttributes.Private:
2211 // A private method is Ok if we are a nested subtype.
2212 // The spec actually is not very clear about this, see bug 52458.
2214 if (invocationType.Equals (entry.Container.Type) ||
2215 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2216 return entry.Member;
2219 case MethodAttributes.FamANDAssem:
2220 case MethodAttributes.Assembly:
2222 // Check for assembly methods
2224 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2225 return entry.Member;
2230 // A protected method is ok, because we are overriding.
2231 // public is always ok.
2233 return entry.Member;
2243 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2244 /// We handle two cases. The first is for types without parameters (events, field, properties).
2245 /// The second are methods, indexers and this is why ignore_complex_types is here.
2246 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2248 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2250 ArrayList applicable = null;
2252 if (method_hash != null)
2253 applicable = (ArrayList) method_hash [name];
2255 if (applicable != null) {
2256 for (int i = applicable.Count - 1; i >= 0; i--) {
2257 CacheEntry entry = (CacheEntry) applicable [i];
2258 if ((entry.EntryType & EntryType.Public) != 0)
2259 return entry.Member;
2263 if (member_hash == null)
2265 applicable = (ArrayList) member_hash [name];
2267 if (applicable != null) {
2268 for (int i = applicable.Count - 1; i >= 0; i--) {
2269 CacheEntry entry = (CacheEntry) applicable [i];
2270 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2271 if (ignore_complex_types) {
2272 if ((entry.EntryType & EntryType.Method) != 0)
2275 // Does exist easier way how to detect indexer ?
2276 if ((entry.EntryType & EntryType.Property) != 0) {
2277 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2278 if (arg_types.Length > 0)
2282 return entry.Member;
2289 Hashtable locase_table;
2292 /// Builds low-case table for CLS Compliance test
2294 public Hashtable GetPublicMembers ()
2296 if (locase_table != null)
2297 return locase_table;
2299 locase_table = new Hashtable ();
2300 foreach (DictionaryEntry entry in member_hash) {
2301 ArrayList members = (ArrayList)entry.Value;
2302 for (int ii = 0; ii < members.Count; ++ii) {
2303 CacheEntry member_entry = (CacheEntry) members [ii];
2305 if ((member_entry.EntryType & EntryType.Public) == 0)
2308 // TODO: Does anyone know easier way how to detect that member is internal ?
2309 switch (member_entry.EntryType & EntryType.MaskType) {
2310 case EntryType.Constructor:
2313 case EntryType.Field:
2314 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2318 case EntryType.Method:
2319 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2323 case EntryType.Property:
2324 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2325 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2329 case EntryType.Event:
2330 EventInfo ei = (EventInfo)member_entry.Member;
2331 MethodInfo mi = ei.GetAddMethod ();
2332 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2336 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2337 locase_table [lcase] = member_entry.Member;
2341 return locase_table;
2344 public Hashtable Members {
2351 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2353 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2355 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2357 for (int i = 0; i < al.Count; ++i) {
2358 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2361 if (entry.Member == this_builder)
2364 if ((entry.EntryType & tested_type) != tested_type)
2367 MethodBase method_to_compare = (MethodBase)entry.Member;
2368 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2369 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2371 if (result == AttributeTester.Result.Ok)
2374 IMethodData md = TypeManager.GetMethod (method_to_compare);
2376 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2377 // However it is exactly what csc does.
2378 if (md != null && !md.IsClsComplianceRequired (method.Parent))
2381 Report.SymbolRelatedToPreviousError (entry.Member);
2383 case AttributeTester.Result.RefOutArrayError:
2384 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2386 case AttributeTester.Result.ArrayArrayError:
2387 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2391 throw new NotImplementedException (result.ToString ());