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 {
27 public readonly TypeArguments TypeArguments;
29 public readonly MemberName Left;
31 public static readonly MemberName Null = new MemberName ("");
33 public MemberName (string name)
38 public MemberName (string name, TypeArguments args)
41 this.TypeArguments = args;
44 public MemberName (MemberName left, string name, TypeArguments args)
50 public MemberName (MemberName left, MemberName right)
51 : this (left, right.Name, right.TypeArguments)
55 public string GetName ()
58 return Left.GetName () + "." + Name;
63 public bool IsGeneric {
65 if (TypeArguments != null)
67 else if (Left != null)
68 return Left.IsGeneric;
74 public string GetName (bool is_generic)
76 string name = is_generic ? Basename : Name;
78 return Left.GetName (is_generic) + "." + name;
83 public int CountTypeArguments {
85 if (TypeArguments == null)
88 return TypeArguments.Count;
92 public string GetMethodName ()
95 return Left.GetTypeName () + "." + Name;
100 public static string MakeName (string name, TypeArguments args)
105 return name + "`" + args.Count;
108 public static string MakeName (string name, int count)
110 return name + "`" + count;
113 public string GetTypeName ()
116 return Left.GetTypeName () + "." +
117 MakeName (Name, TypeArguments);
119 return MakeName (Name, TypeArguments);
122 protected bool IsUnbound {
124 if ((Left != null) && Left.IsUnbound)
126 else if (TypeArguments == null)
129 return TypeArguments.IsUnbound;
133 protected bool CheckUnbound (Location loc)
135 if ((Left != null) && !Left.CheckUnbound (loc))
137 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
138 Report.Error (1031, loc, "Type expected");
145 public Expression GetTypeExpression (Location loc)
148 if (!CheckUnbound (loc))
151 return new UnboundTypeExpression (GetTypeName ());
155 Expression lexpr = Left.GetTypeExpression (loc);
157 return new MemberAccess (lexpr, Name, TypeArguments, loc);
159 if (TypeArguments != null)
160 return new SimpleName (Basename, TypeArguments, loc);
162 return new SimpleName (Name, loc);
166 public MemberName Clone ()
169 return new MemberName (Left.Clone (), Name, TypeArguments);
171 return new MemberName (Name, TypeArguments);
174 public string Basename {
176 if (TypeArguments != null)
177 return MakeName (Name, TypeArguments);
183 public override string ToString ()
186 if (TypeArguments != null)
187 full_name = Name + "<" + TypeArguments + ">";
192 return Left + "." + full_name;
199 /// Base representation for members. This is used to keep track
200 /// of Name, Location and Modifier flags, and handling Attributes.
202 public abstract class MemberCore : Attributable {
208 return MemberName.GetName (!(this is GenericMethod) && !(this is Method));
212 // Is not readonly because of IndexerName attribute
213 public MemberName MemberName;
216 /// Modifier flags that the user specified in the source code
220 public /*readonly*/ TypeContainer Parent;
223 /// Location where this declaration happens
225 public readonly Location Location;
228 /// XML documentation comment
230 public string DocComment;
233 /// Represents header string for documentation comment
234 /// for each member types.
236 public abstract string DocCommentHeader { get; }
240 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
241 Obsolete = 1 << 1, // Type has obsolete attribute
242 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
243 ClsCompliant = 1 << 3, // Type is CLS Compliant
244 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
245 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
246 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
247 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
248 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
249 Excluded = 1 << 9, // Method is conditional
250 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
254 /// MemberCore flags at first detected then cached
256 internal Flags caching_flags;
258 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
262 if (parent is PartialContainer && !(this is PartialContainer))
263 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
268 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
272 /// Tests presence of ObsoleteAttribute and report proper error
274 protected void CheckUsageOfObsoleteAttribute (Type type)
279 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
280 if (obsolete_attr == null)
283 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
286 public abstract bool Define ();
289 // Returns full member name for error message
291 public virtual string GetSignatureForError ()
297 /// Use this method when MethodBuilder is null
299 public virtual string GetSignatureForError (TypeContainer tc)
305 /// Base Emit method. This is also entry point for CLS-Compliant verification.
307 public virtual void Emit ()
309 // Hack with Parent == null is for EnumMember
310 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
311 VerifyObsoleteAttribute ();
313 if (!RootContext.VerifyClsCompliance)
316 VerifyClsCompliance (Parent);
319 public bool InUnsafe {
321 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
326 // Whehter is it ok to use an unsafe pointer in this type container
328 public bool UnsafeOK (DeclSpace parent)
331 // First check if this MemberCore modifier flags has unsafe set
333 if ((ModFlags & Modifiers.UNSAFE) != 0)
336 if (parent.UnsafeContext)
339 Expression.UnsafeError (Location);
344 /// Returns instance of ObsoleteAttribute for this MemberCore
346 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
348 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
349 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
353 caching_flags &= ~Flags.Obsolete_Undetected;
355 if (OptAttributes == null)
358 Attribute obsolete_attr = OptAttributes.Search (
359 TypeManager.obsolete_attribute_type, ds.EmitContext);
360 if (obsolete_attr == null)
363 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds.EmitContext);
364 if (obsolete == null)
367 caching_flags |= Flags.Obsolete;
372 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
374 public override bool IsClsCompliaceRequired (DeclSpace container)
376 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
377 return (caching_flags & Flags.ClsCompliant) != 0;
379 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
380 caching_flags &= ~Flags.ClsCompliance_Undetected;
381 caching_flags |= Flags.ClsCompliant;
385 caching_flags &= ~Flags.ClsCompliance_Undetected;
390 /// Returns true when MemberCore is exposed from assembly.
392 public bool IsExposedFromAssembly (DeclSpace ds)
394 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
397 DeclSpace parentContainer = ds;
398 while (parentContainer != null && parentContainer.ModFlags != 0) {
399 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
401 parentContainer = parentContainer.Parent;
407 /// Resolve CLSCompliantAttribute value or gets cached value.
409 bool GetClsCompliantAttributeValue (DeclSpace ds)
411 if (OptAttributes != null) {
412 Attribute cls_attribute = OptAttributes.Search (
413 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
414 if (cls_attribute != null) {
415 caching_flags |= Flags.HasClsCompliantAttribute;
416 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
419 return ds.GetClsCompliantAttributeValue ();
423 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
425 protected bool HasClsCompliantAttribute {
427 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
432 /// It helps to handle error 102 & 111 detection
434 public virtual bool MarkForDuplicationCheck ()
440 /// The main virtual method for CLS-Compliant verifications.
441 /// The method returns true if member is CLS-Compliant and false if member is not
442 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
443 /// and add their extra verifications.
445 protected virtual bool VerifyClsCompliance (DeclSpace ds)
447 if (!IsClsCompliaceRequired (ds)) {
448 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
449 if (!IsExposedFromAssembly (ds))
450 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
451 if (!CodeGen.Assembly.IsClsCompliant)
452 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
457 if (!CodeGen.Assembly.IsClsCompliant) {
458 if (HasClsCompliantAttribute) {
459 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
464 int index = Name.LastIndexOf ('.');
465 if (Name [index > 0 ? index + 1 : 0] == '_') {
466 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
471 protected abstract void VerifyObsoleteAttribute ();
474 // Raised (and passed an XmlElement that contains the comment)
475 // when GenerateDocComment is writing documentation expectedly.
477 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
482 // Returns a string that represents the signature for this
483 // member which should be used in XML documentation.
485 public virtual string GetDocCommentName (DeclSpace ds)
487 if (ds == null || this is DeclSpace)
488 return DocCommentHeader + Name;
490 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
494 // Generates xml doc comments (if any), and if required,
495 // handle warning report.
497 internal virtual void GenerateDocComment (DeclSpace ds)
499 DocUtil.GenerateDocComment (this, ds);
504 /// Base class for structs, classes, enumerations and interfaces.
507 /// They all create new declaration spaces. This
508 /// provides the common foundation for managing those name
511 public abstract class DeclSpace : MemberCore, IAlias {
513 /// This points to the actual definition that is being
514 /// created with System.Reflection.Emit
516 public TypeBuilder TypeBuilder;
519 /// If we are a generic type, this is the type we are
520 /// currently defining. We need to lookup members on this
521 /// instead of the TypeBuilder.
523 public Type CurrentType;
526 // This is the namespace in which this typecontainer
527 // was declared. We use this to resolve names.
529 public NamespaceEntry NamespaceEntry;
531 private Hashtable Cache = new Hashtable ();
533 public readonly string Basename;
534 public readonly string Basename_with_arity;
536 protected Hashtable defined_names;
538 readonly bool is_generic;
539 readonly int count_type_params;
540 readonly int count_current_type_params;
542 // The emit context for toplevel objects.
543 protected EmitContext ec;
545 public EmitContext EmitContext {
550 // Whether we are Generic
552 public bool IsGeneric {
556 else if (Parent != null)
557 return Parent.IsGeneric;
563 static string[] attribute_targets = new string [] { "type" };
565 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
566 Attributes attrs, Location l)
567 : base (parent, name, attrs, l)
570 Basename = name.Name;
571 Basename_with_arity = name.Basename;
572 defined_names = new Hashtable ();
573 if (name.TypeArguments != null) {
575 count_type_params = count_current_type_params = name.TypeArguments.Count;
578 count_type_params += parent.count_type_params;
582 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
584 protected bool AddToContainer (MemberCore symbol, string fullname, string basename)
586 if (basename == Basename && !(this is Interface)) {
587 if (symbol is TypeParameter)
588 Report.Error (694, "Type parameter `{0}' has same name as " +
589 "containing type or method", basename);
591 Report.SymbolRelatedToPreviousError (this);
592 Report.Error (542, "'{0}': member names cannot be the same as their " +
593 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
598 MemberCore mc = (MemberCore)defined_names [fullname];
601 defined_names.Add (fullname, symbol);
605 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
608 if (symbol is TypeParameter)
609 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", basename);
611 Report.SymbolRelatedToPreviousError (mc);
612 Report.Error (102, symbol.Location,
613 "The type '{0}' already contains a definition for '{1}'",
614 GetSignatureForError (), basename);
619 public void RecordDecl ()
621 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
622 NamespaceEntry.DefineName (MemberName.Basename, this);
626 /// Returns the MemberCore associated with a given name in the declaration
627 /// space. It doesn't return method based symbols !!
630 public MemberCore GetDefinition (string name)
632 return (MemberCore)defined_names [name];
635 bool in_transit = false;
638 /// This function is used to catch recursive definitions
641 public bool InTransit {
652 // root_types contains all the types. All TopLevel types
653 // hence have a parent that points to `root_types', that is
654 // why there is a non-obvious test down here.
656 public bool IsTopLevel {
659 if (Parent.Parent == null)
666 public virtual void CloseType ()
668 if ((caching_flags & Flags.CloseTypeCreated) == 0){
670 TypeBuilder.CreateType ();
673 // The try/catch is needed because
674 // nested enumerations fail to load when they
677 // Even if this is the right order (enumerations
678 // declared after types).
680 // Note that this still creates the type and
681 // it is possible to save it
683 caching_flags |= Flags.CloseTypeCreated;
688 /// Should be overriten by the appropriate declaration space
690 public abstract TypeBuilder DefineType ();
693 /// Define all members, but don't apply any attributes or do anything which may
694 /// access not-yet-defined classes. This method also creates the MemberCache.
696 public abstract bool DefineMembers (TypeContainer parent);
699 // Whether this is an `unsafe context'
701 public bool UnsafeContext {
703 if ((ModFlags & Modifiers.UNSAFE) != 0)
706 return Parent.UnsafeContext;
711 public static string MakeFQN (string nsn, string name)
715 return String.Concat (nsn, ".", name);
718 EmitContext type_resolve_ec;
719 protected EmitContext TypeResolveEmitContext {
721 if (type_resolve_ec == null) {
722 // FIXME: I think this should really be one of:
724 // a. type_resolve_ec = Parent.EmitContext;
725 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
727 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
729 type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
731 return type_resolve_ec;
736 // Resolves the expression `e' for a type, and will recursively define
737 // types. This should only be used for resolving base types.
739 public TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
741 TypeResolveEmitContext.loc = loc;
742 TypeResolveEmitContext.ContainerType = TypeBuilder;
743 if (this is GenericMethod)
744 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
746 TypeResolveEmitContext.ContainerType = TypeBuilder;
748 return e.ResolveAsTypeTerminal (TypeResolveEmitContext);
751 public bool CheckAccessLevel (Type check_type)
754 if ((this is GenericMethod) || (this is Iterator))
755 tb = Parent.TypeBuilder;
759 if (check_type.IsGenericInstance)
760 check_type = check_type.GetGenericTypeDefinition ();
762 if (check_type == tb)
765 if (TypeBuilder == null)
766 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
767 // However, this is invoked again later -- so safe to return true.
768 // May also be null when resolving top-level attributes.
771 if (check_type.IsGenericParameter)
772 return true; // FIXME
774 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
777 // Broken Microsoft runtime, return public for arrays, no matter what
778 // the accessibility is for their underlying class, and they return
779 // NonPublic visibility for pointers
781 if (check_type.IsArray || check_type.IsPointer)
782 return CheckAccessLevel (TypeManager.GetElementType (check_type));
785 case TypeAttributes.Public:
788 case TypeAttributes.NotPublic:
790 if (TypeBuilder == null)
791 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
792 // However, this is invoked again later -- so safe to return true.
793 // May also be null when resolving top-level attributes.
796 // This test should probably use the declaringtype.
798 return check_type.Assembly == TypeBuilder.Assembly;
800 case TypeAttributes.NestedPublic:
803 case TypeAttributes.NestedPrivate:
804 return NestedAccessible (tb, check_type);
806 case TypeAttributes.NestedFamily:
808 // Only accessible to methods in current type or any subtypes
810 return FamilyAccessible (tb, check_type);
812 case TypeAttributes.NestedFamANDAssem:
813 return (check_type.Assembly == tb.Assembly) &&
814 FamilyAccessible (tb, check_type);
816 case TypeAttributes.NestedFamORAssem:
817 return (check_type.Assembly == tb.Assembly) ||
818 FamilyAccessible (tb, check_type);
820 case TypeAttributes.NestedAssembly:
821 return check_type.Assembly == tb.Assembly;
824 Console.WriteLine ("HERE: " + check_attr);
829 protected bool NestedAccessible (Type tb, Type check_type)
831 Type declaring = check_type.DeclaringType;
832 return TypeBuilder == declaring ||
833 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
836 protected bool FamilyAccessible (Type tb, Type check_type)
838 Type declaring = check_type.DeclaringType;
839 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
842 return NestedAccessible (tb, check_type);
845 // Access level of a type.
847 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
848 // Public Assembly Protected
849 Protected = (0 << 0) | (0 << 1) | (X << 2),
850 Public = (X << 0) | (X << 1) | (X << 2),
851 Private = (0 << 0) | (0 << 1) | (0 << 2),
852 Internal = (0 << 0) | (X << 1) | (0 << 2),
853 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
856 static AccessLevel GetAccessLevelFromModifiers (int flags)
858 if ((flags & Modifiers.INTERNAL) != 0) {
860 if ((flags & Modifiers.PROTECTED) != 0)
861 return AccessLevel.ProtectedOrInternal;
863 return AccessLevel.Internal;
865 } else if ((flags & Modifiers.PROTECTED) != 0)
866 return AccessLevel.Protected;
867 else if ((flags & Modifiers.PRIVATE) != 0)
868 return AccessLevel.Private;
870 return AccessLevel.Public;
873 // What is the effective access level of this?
875 AccessLevel EffectiveAccessLevel {
877 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
878 if (!IsTopLevel && (Parent != null))
879 return myAccess & Parent.EffectiveAccessLevel;
884 // Return the access level for type `t'
885 static AccessLevel TypeEffectiveAccessLevel (Type t)
888 return AccessLevel.Public;
889 if (t.IsNestedPrivate)
890 return AccessLevel.Private;
892 return AccessLevel.Internal;
894 // By now, it must be nested
895 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
897 if (t.IsNestedPublic)
899 if (t.IsNestedAssembly)
900 return parentLevel & AccessLevel.Internal;
901 if (t.IsNestedFamily)
902 return parentLevel & AccessLevel.Protected;
903 if (t.IsNestedFamORAssem)
904 return parentLevel & AccessLevel.ProtectedOrInternal;
905 if (t.IsNestedFamANDAssem)
906 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
908 // nested private is taken care of
910 throw new Exception ("I give up, what are you?");
914 // This answers `is the type P, as accessible as a member M which has the
915 // accessability @flags which is declared as a nested member of the type T, this declspace'
917 public bool AsAccessible (Type p, int flags)
919 if (p.IsGenericParameter)
920 return true; // FIXME
923 // 1) if M is private, its accessability is the same as this declspace.
924 // we already know that P is accessible to T before this method, so we
928 if ((flags & Modifiers.PRIVATE) != 0)
931 while (p.IsArray || p.IsPointer || p.IsByRef)
932 p = TypeManager.GetElementType (p);
934 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
935 AccessLevel mAccess = this.EffectiveAccessLevel &
936 GetAccessLevelFromModifiers (flags);
938 // for every place from which we can access M, we must
939 // be able to access P as well. So, we want
940 // For every bit in M and P, M_i -> P_1 == true
941 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
943 return ~ (~ mAccess | pAccess) == 0;
946 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
948 Report.Error (104, loc,
949 "`{0}' is an ambiguous reference ({1} or {2})",
954 // Return the nested type with name @name. Ensures that the nested type
955 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
957 public virtual Type FindNestedType (string name)
962 private Type LookupNestedTypeInHierarchy (string name)
964 // if the member cache has been created, lets use it.
965 // the member cache is MUCH faster.
966 if (MemberCache != null)
967 return MemberCache.FindNestedType (name);
969 // no member cache. Do it the hard way -- reflection
971 for (Type current_type = TypeBuilder;
972 current_type != null && current_type != TypeManager.object_type;
973 current_type = current_type.BaseType) {
974 if (current_type is TypeBuilder) {
975 DeclSpace decl = this;
976 if (current_type != TypeBuilder)
977 decl = TypeManager.LookupDeclSpace (current_type);
978 t = decl.FindNestedType (name);
980 t = TypeManager.LookupTypeDirect (current_type.FullName + "+" + name);
983 if (t != null && CheckAccessLevel (t))
991 // Public function used to locate types, this can only
992 // be used after the ResolveTree function has been invoked.
994 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
996 // Returns: Type or null if they type can not be found.
998 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1000 if (this is PartialContainer)
1001 throw new InternalErrorException ("Should not get here");
1003 if (Cache.Contains (name))
1004 return (FullNamedExpression) Cache [name];
1006 FullNamedExpression e;
1007 Type t = LookupNestedTypeInHierarchy (name);
1009 e = new TypeExpression (t, Location.Null);
1010 else if (Parent != null && Parent != RootContext.Tree.Types)
1011 e = Parent.LookupType (name, loc, ignore_cs0104);
1013 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1020 /// This function is broken and not what you're looking for. It should only
1021 /// be used while the type is still being created since it doesn't use the cache
1022 /// and relies on the filter doing the member name check.
1024 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1025 MemberFilter filter, object criteria);
1028 /// If we have a MemberCache, return it. This property may return null if the
1029 /// class doesn't have a member cache or while it's still being created.
1031 public abstract MemberCache MemberCache {
1035 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1037 TypeBuilder.SetCustomAttribute (cb);
1041 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1042 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1044 public bool GetClsCompliantAttributeValue ()
1046 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1047 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1049 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1051 if (OptAttributes != null) {
1052 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1053 if (cls_attribute != null) {
1054 caching_flags |= Flags.HasClsCompliantAttribute;
1055 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1056 caching_flags |= Flags.ClsCompliantAttributeTrue;
1063 if (Parent == null) {
1064 if (CodeGen.Assembly.IsClsCompliant) {
1065 caching_flags |= Flags.ClsCompliantAttributeTrue;
1071 if (Parent.GetClsCompliantAttributeValue ()) {
1072 caching_flags |= Flags.ClsCompliantAttributeTrue;
1079 // Extensions for generics
1081 TypeParameter[] type_params;
1082 TypeParameter[] type_param_list;
1084 protected string GetInstantiationName ()
1086 StringBuilder sb = new StringBuilder (Name);
1088 for (int i = 0; i < type_param_list.Length; i++) {
1091 sb.Append (type_param_list [i].Name);
1094 return sb.ToString ();
1097 bool check_type_parameter (ArrayList list, int start, string name)
1099 for (int i = 0; i < start; i++) {
1100 TypeParameter param = (TypeParameter) list [i];
1102 if (param.Name != name)
1105 if (RootContext.WarningLevel >= 3)
1108 "Type parameter `{0}' has same name " +
1109 "as type parameter from outer type `{1}'",
1110 name, Parent.GetInstantiationName ());
1118 TypeParameter[] initialize_type_params ()
1120 if (type_param_list != null)
1121 return type_param_list;
1123 DeclSpace the_parent = Parent;
1124 if (this is GenericMethod)
1128 TypeParameter[] parent_params = null;
1129 if ((the_parent != null) && the_parent.IsGeneric) {
1130 parent_params = the_parent.initialize_type_params ();
1131 start = parent_params != null ? parent_params.Length : 0;
1134 ArrayList list = new ArrayList ();
1135 if (parent_params != null)
1136 list.AddRange (parent_params);
1138 int count = type_params != null ? type_params.Length : 0;
1139 for (int i = 0; i < count; i++) {
1140 TypeParameter param = type_params [i];
1141 check_type_parameter (list, start, param.Name);
1145 type_param_list = new TypeParameter [list.Count];
1146 list.CopyTo (type_param_list, 0);
1147 return type_param_list;
1150 public virtual void SetParameterInfo (ArrayList constraints_list)
1153 if (constraints_list != null) {
1155 80, Location, "Contraints are not allowed " +
1156 "on non-generic declarations");
1162 string[] names = MemberName.TypeArguments.GetDeclarations ();
1163 type_params = new TypeParameter [names.Length];
1166 // Register all the names
1168 for (int i = 0; i < type_params.Length; i++) {
1169 string name = names [i];
1171 Constraints constraints = null;
1172 if (constraints_list != null) {
1173 foreach (Constraints constraint in constraints_list) {
1174 if (constraint.TypeParameter == name) {
1175 constraints = constraint;
1181 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1183 string full_name = Name + "." + name;
1184 AddToContainer (type_params [i], full_name, name);
1188 public TypeParameter[] TypeParameters {
1191 throw new InvalidOperationException ();
1192 if (type_param_list == null)
1193 initialize_type_params ();
1195 return type_param_list;
1199 protected TypeParameter[] CurrentTypeParameters {
1202 throw new InvalidOperationException ();
1203 if (type_params != null)
1206 return new TypeParameter [0];
1210 public int CountTypeParameters {
1212 return count_type_params;
1216 public int CountCurrentTypeParameters {
1218 return count_current_type_params;
1222 public TypeParameterExpr LookupGeneric (string name, Location loc)
1227 foreach (TypeParameter type_param in CurrentTypeParameters) {
1228 if (type_param.Name != name)
1231 return new TypeParameterExpr (type_param, loc);
1235 return Parent.LookupGeneric (name, loc);
1240 bool IAlias.IsType {
1241 get { return true; }
1244 string IAlias.Name {
1245 get { return Name; }
1248 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1250 if (TypeBuilder == null)
1251 throw new InvalidOperationException ();
1253 if (CurrentType != null)
1254 return new TypeExpression (CurrentType, Location);
1256 return new TypeExpression (TypeBuilder, Location);
1259 public override string[] ValidAttributeTargets {
1261 return attribute_targets;
1267 /// This is a readonly list of MemberInfo's.
1269 public class MemberList : IList {
1270 public readonly IList List;
1274 /// Create a new MemberList from the given IList.
1276 public MemberList (IList list)
1281 this.List = new ArrayList ();
1286 /// Concatenate the ILists `first' and `second' to a new MemberList.
1288 public MemberList (IList first, IList second)
1290 ArrayList list = new ArrayList ();
1291 list.AddRange (first);
1292 list.AddRange (second);
1297 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1300 /// Cast the MemberList into a MemberInfo[] array.
1303 /// This is an expensive operation, only use it if it's really necessary.
1305 public static explicit operator MemberInfo [] (MemberList list)
1307 Timer.StartTimer (TimerType.MiscTimer);
1308 MemberInfo [] result = new MemberInfo [list.Count];
1309 list.CopyTo (result, 0);
1310 Timer.StopTimer (TimerType.MiscTimer);
1322 public bool IsSynchronized {
1324 return List.IsSynchronized;
1328 public object SyncRoot {
1330 return List.SyncRoot;
1334 public void CopyTo (Array array, int index)
1336 List.CopyTo (array, index);
1341 public IEnumerator GetEnumerator ()
1343 return List.GetEnumerator ();
1348 public bool IsFixedSize {
1354 public bool IsReadOnly {
1360 object IList.this [int index] {
1362 return List [index];
1366 throw new NotSupportedException ();
1370 // FIXME: try to find out whether we can avoid the cast in this indexer.
1371 public MemberInfo this [int index] {
1373 return (MemberInfo) List [index];
1377 public int Add (object value)
1379 throw new NotSupportedException ();
1382 public void Clear ()
1384 throw new NotSupportedException ();
1387 public bool Contains (object value)
1389 return List.Contains (value);
1392 public int IndexOf (object value)
1394 return List.IndexOf (value);
1397 public void Insert (int index, object value)
1399 throw new NotSupportedException ();
1402 public void Remove (object value)
1404 throw new NotSupportedException ();
1407 public void RemoveAt (int index)
1409 throw new NotSupportedException ();
1414 /// This interface is used to get all members of a class when creating the
1415 /// member cache. It must be implemented by all DeclSpace derivatives which
1416 /// want to support the member cache and by TypeHandle to get caching of
1417 /// non-dynamic types.
1419 public interface IMemberContainer {
1421 /// The name of the IMemberContainer. This is only used for
1422 /// debugging purposes.
1429 /// The type of this IMemberContainer.
1436 /// Returns the IMemberContainer of the base class or null if this
1437 /// is an interface or TypeManger.object_type.
1438 /// This is used when creating the member cache for a class to get all
1439 /// members from the base class.
1441 MemberCache BaseCache {
1446 /// Whether this is an interface.
1453 /// Returns all members of this class with the corresponding MemberTypes
1454 /// and BindingFlags.
1457 /// When implementing this method, make sure not to return any inherited
1458 /// members and check the MemberTypes and BindingFlags properly.
1459 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1460 /// get the BindingFlags (static/non-static,public/non-public) in the
1461 /// MemberInfo class, but the cache needs this information. That's why
1462 /// this method is called multiple times with different BindingFlags.
1464 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1467 /// Return the container's member cache.
1469 MemberCache MemberCache {
1475 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1476 /// member lookups. It has a member name based hash table; it maps each member
1477 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1478 /// and the BindingFlags that were initially used to get it. The cache contains
1479 /// all members of the current class and all inherited members. If this cache is
1480 /// for an interface types, it also contains all inherited members.
1482 /// There are two ways to get a MemberCache:
1483 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1484 /// use the DeclSpace.MemberCache property.
1485 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1486 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1488 public class MemberCache {
1489 public readonly IMemberContainer Container;
1490 protected Hashtable member_hash;
1491 protected Hashtable method_hash;
1494 /// Create a new MemberCache for the given IMemberContainer `container'.
1496 public MemberCache (IMemberContainer container)
1498 this.Container = container;
1500 Timer.IncrementCounter (CounterType.MemberCache);
1501 Timer.StartTimer (TimerType.CacheInit);
1503 // If we have a base class (we have a base class unless we're
1504 // TypeManager.object_type), we deep-copy its MemberCache here.
1505 if (Container.BaseCache != null)
1506 member_hash = SetupCache (Container.BaseCache);
1508 member_hash = new Hashtable ();
1510 // If this is neither a dynamic type nor an interface, create a special
1511 // method cache with all declared and inherited methods.
1512 Type type = container.Type;
1513 if (!(type is TypeBuilder) && !type.IsInterface &&
1514 // !(type.IsGenericInstance && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1515 !type.IsGenericInstance &&
1516 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1517 method_hash = new Hashtable ();
1521 // Add all members from the current class.
1522 AddMembers (Container);
1524 Timer.StopTimer (TimerType.CacheInit);
1527 public MemberCache (Type[] ifaces)
1530 // The members of this cache all belong to other caches.
1531 // So, 'Container' will not be used.
1533 this.Container = null;
1535 member_hash = new Hashtable ();
1539 foreach (Type itype in ifaces)
1540 AddCacheContents (TypeManager.LookupMemberCache (itype));
1544 /// Bootstrap this member cache by doing a deep-copy of our base.
1546 Hashtable SetupCache (MemberCache base_class)
1548 Hashtable hash = new Hashtable ();
1550 if (base_class == null)
1553 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1554 while (it.MoveNext ()) {
1555 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1561 void ClearDeclaredOnly (Hashtable hash)
1563 IDictionaryEnumerator it = hash.GetEnumerator ();
1564 while (it.MoveNext ()) {
1565 foreach (CacheEntry ce in (ArrayList) it.Value)
1566 ce.EntryType &= ~EntryType.Declared;
1571 /// Add the contents of `cache' to the member_hash.
1573 void AddCacheContents (MemberCache cache)
1575 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1576 while (it.MoveNext ()) {
1577 ArrayList list = (ArrayList) member_hash [it.Key];
1579 member_hash [it.Key] = list = new ArrayList ();
1581 ArrayList entries = (ArrayList) it.Value;
1582 for (int i = entries.Count-1; i >= 0; i--) {
1583 CacheEntry entry = (CacheEntry) entries [i];
1585 if (entry.Container != cache.Container)
1593 /// Add all members from class `container' to the cache.
1595 void AddMembers (IMemberContainer container)
1597 // We need to call AddMembers() with a single member type at a time
1598 // to get the member type part of CacheEntry.EntryType right.
1599 if (!container.IsInterface) {
1600 AddMembers (MemberTypes.Constructor, container);
1601 AddMembers (MemberTypes.Field, container);
1603 AddMembers (MemberTypes.Method, container);
1604 AddMembers (MemberTypes.Property, container);
1605 AddMembers (MemberTypes.Event, container);
1606 // Nested types are returned by both Static and Instance searches.
1607 AddMembers (MemberTypes.NestedType,
1608 BindingFlags.Static | BindingFlags.Public, container);
1609 AddMembers (MemberTypes.NestedType,
1610 BindingFlags.Static | BindingFlags.NonPublic, container);
1613 void AddMembers (MemberTypes mt, IMemberContainer container)
1615 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1616 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1617 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1618 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1622 /// Add all members from class `container' with the requested MemberTypes and
1623 /// BindingFlags to the cache. This method is called multiple times with different
1624 /// MemberTypes and BindingFlags.
1626 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1628 MemberList members = container.GetMembers (mt, bf);
1630 foreach (MemberInfo member in members) {
1631 string name = member.Name;
1633 int pos = name.IndexOf ('<');
1635 name = name.Substring (0, pos);
1637 // We use a name-based hash table of ArrayList's.
1638 ArrayList list = (ArrayList) member_hash [name];
1640 list = new ArrayList ();
1641 member_hash.Add (name, list);
1644 // When this method is called for the current class, the list will
1645 // already contain all inherited members from our base classes.
1646 // We cannot add new members in front of the list since this'd be an
1647 // expensive operation, that's why the list is sorted in reverse order
1648 // (ie. members from the current class are coming last).
1649 list.Add (new CacheEntry (container, member, mt, bf));
1654 /// Add all declared and inherited methods from class `type' to the method cache.
1656 void AddMethods (Type type)
1658 AddMethods (BindingFlags.Static | BindingFlags.Public |
1659 BindingFlags.FlattenHierarchy, type);
1660 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1661 BindingFlags.FlattenHierarchy, type);
1662 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1663 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1666 void AddMethods (BindingFlags bf, Type type)
1669 // Consider the case:
1671 // class X { public virtual int f() {} }
1674 // When processing 'Y', the method_cache will already have a copy of 'f',
1675 // with ReflectedType == X. However, we want to ensure that its ReflectedType == Y
1677 MethodBase [] members = type.GetMethods (bf);
1679 Array.Reverse (members);
1681 foreach (MethodBase member in members) {
1682 string name = member.Name;
1684 // We use a name-based hash table of ArrayList's.
1685 ArrayList list = (ArrayList) method_hash [name];
1687 list = new ArrayList ();
1688 method_hash.Add (name, list);
1691 if (member.IsVirtual &&
1692 (member.Attributes & MethodAttributes.NewSlot) == 0) {
1693 MethodInfo base_method = ((MethodInfo) member).GetBaseDefinition ();
1695 if (base_method == member) {
1697 // Both mcs and CSC 1.1 seem to emit a somewhat broken
1698 // ...Invoke () function for delegates: it's missing a 'newslot'.
1699 // CSC 2.0 emits a 'newslot' for a delegate's Invoke.
1701 if (member.Name != "Invoke" ||
1702 !TypeManager.IsDelegateType (type)) {
1703 Report.SymbolRelatedToPreviousError (base_method);
1704 Report.Warning (-28,
1705 "{0} contains a method '{1}' that is marked " +
1706 " virtual, but doesn't appear to have a slot." +
1707 " The method may be ignored during overload resolution",
1714 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1715 if ((base_method.Attributes & MethodAttributes.NewSlot) != 0)
1719 // Shouldn't get here. Mono appears to be buggy.
1721 MethodInfo new_base_method = base_method.GetBaseDefinition ();
1722 if (new_base_method == base_method) {
1723 Report.SymbolRelatedToPreviousError (base_method);
1724 Report.Warning (-28,
1725 "{0} contains a method '{1}' that is marked " +
1726 " virtual, but doesn't appear to have a slot." +
1727 " The method may be ignored during overload resolution",
1730 base_method = new_base_method;
1737 // Unfortunately, the elements returned by Type.GetMethods() aren't
1738 // sorted so we need to do this check for every member.
1739 BindingFlags new_bf = bf;
1740 if (member.DeclaringType == type)
1741 new_bf |= BindingFlags.DeclaredOnly;
1743 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1748 /// Compute and return a appropriate `EntryType' magic number for the given
1749 /// MemberTypes and BindingFlags.
1751 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1753 EntryType type = EntryType.None;
1755 if ((mt & MemberTypes.Constructor) != 0)
1756 type |= EntryType.Constructor;
1757 if ((mt & MemberTypes.Event) != 0)
1758 type |= EntryType.Event;
1759 if ((mt & MemberTypes.Field) != 0)
1760 type |= EntryType.Field;
1761 if ((mt & MemberTypes.Method) != 0)
1762 type |= EntryType.Method;
1763 if ((mt & MemberTypes.Property) != 0)
1764 type |= EntryType.Property;
1765 // Nested types are returned by static and instance searches.
1766 if ((mt & MemberTypes.NestedType) != 0)
1767 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1769 if ((bf & BindingFlags.Instance) != 0)
1770 type |= EntryType.Instance;
1771 if ((bf & BindingFlags.Static) != 0)
1772 type |= EntryType.Static;
1773 if ((bf & BindingFlags.Public) != 0)
1774 type |= EntryType.Public;
1775 if ((bf & BindingFlags.NonPublic) != 0)
1776 type |= EntryType.NonPublic;
1777 if ((bf & BindingFlags.DeclaredOnly) != 0)
1778 type |= EntryType.Declared;
1784 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1785 /// denote multiple member types. Returns true if the given flags value denotes a
1786 /// single member types.
1788 public static bool IsSingleMemberType (MemberTypes mt)
1791 case MemberTypes.Constructor:
1792 case MemberTypes.Event:
1793 case MemberTypes.Field:
1794 case MemberTypes.Method:
1795 case MemberTypes.Property:
1796 case MemberTypes.NestedType:
1805 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1806 /// number to speed up the searching process.
1809 protected enum EntryType {
1814 MaskStatic = Instance|Static,
1818 MaskProtection = Public|NonPublic,
1822 Constructor = 0x020,
1829 MaskType = Constructor|Event|Field|Method|Property|NestedType
1832 protected class CacheEntry {
1833 public readonly IMemberContainer Container;
1834 public EntryType EntryType;
1835 public MemberInfo Member;
1837 public CacheEntry (IMemberContainer container, MemberInfo member,
1838 MemberTypes mt, BindingFlags bf)
1840 this.Container = container;
1841 this.Member = member;
1842 this.EntryType = GetEntryType (mt, bf);
1845 public override string ToString ()
1847 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1853 /// This is called each time we're walking up one level in the class hierarchy
1854 /// and checks whether we can abort the search since we've already found what
1855 /// we were looking for.
1857 protected bool DoneSearching (ArrayList list)
1860 // We've found exactly one member in the current class and it's not
1861 // a method or constructor.
1863 if (list.Count == 1 && !(list [0] is MethodBase))
1867 // Multiple properties: we query those just to find out the indexer
1870 if ((list.Count > 0) && (list [0] is PropertyInfo))
1877 /// Looks up members with name `name'. If you provide an optional
1878 /// filter function, it'll only be called with members matching the
1879 /// requested member name.
1881 /// This method will try to use the cache to do the lookup if possible.
1883 /// Unlike other FindMembers implementations, this method will always
1884 /// check all inherited members - even when called on an interface type.
1886 /// If you know that you're only looking for methods, you should use
1887 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1888 /// When doing a method-only search, it'll try to use a special method
1889 /// cache (unless it's a dynamic type or an interface) and the returned
1890 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1891 /// The lookup process will automatically restart itself in method-only
1892 /// search mode if it discovers that it's about to return methods.
1894 ArrayList global = new ArrayList ();
1895 bool using_global = false;
1897 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1899 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1900 MemberFilter filter, object criteria)
1903 throw new Exception ();
1905 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1906 bool method_search = mt == MemberTypes.Method;
1907 // If we have a method cache and we aren't already doing a method-only search,
1908 // then we restart a method search if the first match is a method.
1909 bool do_method_search = !method_search && (method_hash != null);
1911 ArrayList applicable;
1913 // If this is a method-only search, we try to use the method cache if
1914 // possible; a lookup in the method cache will return a MemberInfo with
1915 // the correct ReflectedType for inherited methods.
1917 if (method_search && (method_hash != null))
1918 applicable = (ArrayList) method_hash [name];
1920 applicable = (ArrayList) member_hash [name];
1922 if (applicable == null)
1923 return emptyMemberInfo;
1926 // 32 slots gives 53 rss/54 size
1927 // 2/4 slots gives 55 rss
1929 // Strange: from 25,000 calls, only 1,800
1930 // are above 2. Why does this impact it?
1933 using_global = true;
1935 Timer.StartTimer (TimerType.CachedLookup);
1937 EntryType type = GetEntryType (mt, bf);
1939 IMemberContainer current = Container;
1942 // `applicable' is a list of all members with the given member name `name'
1943 // in the current class and all its base classes. The list is sorted in
1944 // reverse order due to the way how the cache is initialy created (to speed
1945 // things up, we're doing a deep-copy of our base).
1947 for (int i = applicable.Count-1; i >= 0; i--) {
1948 CacheEntry entry = (CacheEntry) applicable [i];
1950 // This happens each time we're walking one level up in the class
1951 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1952 // the first time this happens (this may already happen in the first
1953 // iteration of this loop if there are no members with the name we're
1954 // looking for in the current class).
1955 if (entry.Container != current) {
1956 if (declared_only || DoneSearching (global))
1959 current = entry.Container;
1962 // Is the member of the correct type ?
1963 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1966 // Is the member static/non-static ?
1967 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1970 // Apply the filter to it.
1971 if (filter (entry.Member, criteria)) {
1972 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1973 do_method_search = false;
1974 global.Add (entry.Member);
1978 Timer.StopTimer (TimerType.CachedLookup);
1980 // If we have a method cache and we aren't already doing a method-only
1981 // search, we restart in method-only search mode if the first match is
1982 // a method. This ensures that we return a MemberInfo with the correct
1983 // ReflectedType for inherited methods.
1984 if (do_method_search && (global.Count > 0)){
1985 using_global = false;
1987 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1990 using_global = false;
1991 MemberInfo [] copy = new MemberInfo [global.Count];
1992 global.CopyTo (copy);
1996 // find the nested type @name in @this.
1997 public Type FindNestedType (string name)
1999 ArrayList applicable = (ArrayList) member_hash [name];
2000 if (applicable == null)
2003 for (int i = applicable.Count-1; i >= 0; i--) {
2004 CacheEntry entry = (CacheEntry) applicable [i];
2005 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2006 return (Type) entry.Member;
2013 // This finds the method or property for us to override. invocationType is the type where
2014 // the override is going to be declared, name is the name of the method/property, and
2015 // paramTypes is the parameters, if any to the method or property
2017 // Because the MemberCache holds members from this class and all the base classes,
2018 // we can avoid tons of reflection stuff.
2020 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2022 ArrayList applicable;
2023 if (method_hash != null && !is_property)
2024 applicable = (ArrayList) method_hash [name];
2026 applicable = (ArrayList) member_hash [name];
2028 if (applicable == null)
2031 // Walk the chain of methods, starting from the top.
2033 for (int i = applicable.Count - 1; i >= 0; i--) {
2034 CacheEntry entry = (CacheEntry) applicable [i];
2036 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2039 PropertyInfo pi = null;
2040 MethodInfo mi = null;
2041 FieldInfo fi = null;
2042 Type [] cmpAttrs = null;
2045 if ((entry.EntryType & EntryType.Field) != 0) {
2046 fi = (FieldInfo)entry.Member;
2048 // TODO: For this case we ignore member type
2049 //fb = TypeManager.GetField (fi);
2050 //cmpAttrs = new Type[] { fb.MemberType };
2052 pi = (PropertyInfo) entry.Member;
2053 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2056 mi = (MethodInfo) entry.Member;
2057 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2061 // TODO: Almost duplicate !
2063 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2064 case FieldAttributes.Private:
2066 // A private method is Ok if we are a nested subtype.
2067 // The spec actually is not very clear about this, see bug 52458.
2069 if (invocationType != entry.Container.Type &
2070 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2074 case FieldAttributes.FamANDAssem:
2075 case FieldAttributes.Assembly:
2077 // Check for assembly methods
2079 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2083 return entry.Member;
2087 // Check the arguments
2089 if (cmpAttrs.Length != paramTypes.Length)
2092 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2093 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2098 // get one of the methods because this has the visibility info.
2101 mi = pi.GetGetMethod (true);
2103 mi = pi.GetSetMethod (true);
2109 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2110 case MethodAttributes.Private:
2112 // A private method is Ok if we are a nested subtype.
2113 // The spec actually is not very clear about this, see bug 52458.
2115 if (invocationType.Equals (entry.Container.Type) ||
2116 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2117 return entry.Member;
2120 case MethodAttributes.FamANDAssem:
2121 case MethodAttributes.Assembly:
2123 // Check for assembly methods
2125 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2126 return entry.Member;
2131 // A protected method is ok, because we are overriding.
2132 // public is always ok.
2134 return entry.Member;
2144 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2145 /// We handle two cases. The first is for types without parameters (events, field, properties).
2146 /// The second are methods, indexers and this is why ignore_complex_types is here.
2147 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2149 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2151 ArrayList applicable = null;
2153 if (method_hash != null)
2154 applicable = (ArrayList) method_hash [name];
2156 if (applicable != null) {
2157 for (int i = applicable.Count - 1; i >= 0; i--) {
2158 CacheEntry entry = (CacheEntry) applicable [i];
2159 if ((entry.EntryType & EntryType.Public) != 0)
2160 return entry.Member;
2164 if (member_hash == null)
2166 applicable = (ArrayList) member_hash [name];
2168 if (applicable != null) {
2169 for (int i = applicable.Count - 1; i >= 0; i--) {
2170 CacheEntry entry = (CacheEntry) applicable [i];
2171 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2172 if (ignore_complex_types) {
2173 if ((entry.EntryType & EntryType.Method) != 0)
2176 // Does exist easier way how to detect indexer ?
2177 if ((entry.EntryType & EntryType.Property) != 0) {
2178 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2179 if (arg_types.Length > 0)
2183 return entry.Member;
2190 Hashtable locase_table;
2193 /// Builds low-case table for CLS Compliance test
2195 public Hashtable GetPublicMembers ()
2197 if (locase_table != null)
2198 return locase_table;
2200 locase_table = new Hashtable ();
2201 foreach (DictionaryEntry entry in member_hash) {
2202 ArrayList members = (ArrayList)entry.Value;
2203 for (int ii = 0; ii < members.Count; ++ii) {
2204 CacheEntry member_entry = (CacheEntry) members [ii];
2206 if ((member_entry.EntryType & EntryType.Public) == 0)
2209 // TODO: Does anyone know easier way how to detect that member is internal ?
2210 switch (member_entry.EntryType & EntryType.MaskType) {
2211 case EntryType.Constructor:
2214 case EntryType.Field:
2215 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2219 case EntryType.Method:
2220 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2224 case EntryType.Property:
2225 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2226 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2230 case EntryType.Event:
2231 EventInfo ei = (EventInfo)member_entry.Member;
2232 MethodInfo mi = ei.GetAddMethod ();
2233 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2237 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2238 locase_table [lcase] = member_entry.Member;
2242 return locase_table;
2245 public Hashtable Members {
2252 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2254 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2256 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2258 for (int i = 0; i < al.Count; ++i) {
2259 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2262 if (entry.Member == this_builder)
2265 if ((entry.EntryType & tested_type) != tested_type)
2268 MethodBase method_to_compare = (MethodBase)entry.Member;
2269 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2272 IMethodData md = TypeManager.GetMethod (method_to_compare);
2274 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2275 // However it is exactly what csc does.
2276 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2279 Report.SymbolRelatedToPreviousError (entry.Member);
2280 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());