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,
265 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
269 /// Tests presence of ObsoleteAttribute and report proper error
271 protected void CheckUsageOfObsoleteAttribute (Type type)
276 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
277 if (obsolete_attr == null)
280 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
283 public abstract bool Define ();
286 // Returns full member name for error message
288 public virtual string GetSignatureForError ()
294 /// Use this method when MethodBuilder is null
296 public virtual string GetSignatureForError (TypeContainer tc)
302 /// Base Emit method. This is also entry point for CLS-Compliant verification.
304 public virtual void Emit ()
306 // Hack with Parent == null is for EnumMember
307 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
308 VerifyObsoleteAttribute ();
310 if (!RootContext.VerifyClsCompliance)
313 VerifyClsCompliance (Parent);
316 public bool InUnsafe {
318 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
323 // Whehter is it ok to use an unsafe pointer in this type container
325 public bool UnsafeOK (DeclSpace parent)
328 // First check if this MemberCore modifier flags has unsafe set
330 if ((ModFlags & Modifiers.UNSAFE) != 0)
333 if (parent.UnsafeContext)
336 Expression.UnsafeError (Location);
341 /// Returns instance of ObsoleteAttribute for this MemberCore
343 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
345 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
346 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
350 caching_flags &= ~Flags.Obsolete_Undetected;
352 if (OptAttributes == null)
355 Attribute obsolete_attr = OptAttributes.Search (
356 TypeManager.obsolete_attribute_type, ds.EmitContext);
357 if (obsolete_attr == null)
360 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds.EmitContext);
361 if (obsolete == null)
364 caching_flags |= Flags.Obsolete;
369 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
371 public override bool IsClsCompliaceRequired (DeclSpace container)
373 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
374 return (caching_flags & Flags.ClsCompliant) != 0;
376 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
377 caching_flags &= ~Flags.ClsCompliance_Undetected;
378 caching_flags |= Flags.ClsCompliant;
382 caching_flags &= ~Flags.ClsCompliance_Undetected;
387 /// Returns true when MemberCore is exposed from assembly.
389 public bool IsExposedFromAssembly (DeclSpace ds)
391 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
394 DeclSpace parentContainer = ds;
395 while (parentContainer != null && parentContainer.ModFlags != 0) {
396 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
398 parentContainer = parentContainer.Parent;
404 /// Resolve CLSCompliantAttribute value or gets cached value.
406 bool GetClsCompliantAttributeValue (DeclSpace ds)
408 if (OptAttributes != null) {
409 Attribute cls_attribute = OptAttributes.Search (
410 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
411 if (cls_attribute != null) {
412 caching_flags |= Flags.HasClsCompliantAttribute;
413 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
416 return ds.GetClsCompliantAttributeValue ();
420 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
422 protected bool HasClsCompliantAttribute {
424 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
429 /// It helps to handle error 102 & 111 detection
431 public virtual bool MarkForDuplicationCheck ()
437 /// The main virtual method for CLS-Compliant verifications.
438 /// The method returns true if member is CLS-Compliant and false if member is not
439 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
440 /// and add their extra verifications.
442 protected virtual bool VerifyClsCompliance (DeclSpace ds)
444 if (!IsClsCompliaceRequired (ds)) {
445 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
446 if (!IsExposedFromAssembly (ds))
447 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
448 if (!CodeGen.Assembly.IsClsCompliant)
449 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
454 if (!CodeGen.Assembly.IsClsCompliant) {
455 if (HasClsCompliantAttribute) {
456 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
461 int index = Name.LastIndexOf ('.');
462 if (Name [index > 0 ? index + 1 : 0] == '_') {
463 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
468 protected abstract void VerifyObsoleteAttribute ();
471 // Raised (and passed an XmlElement that contains the comment)
472 // when GenerateDocComment is writing documentation expectedly.
474 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
479 // Returns a string that represents the signature for this
480 // member which should be used in XML documentation.
482 public virtual string GetDocCommentName (DeclSpace ds)
484 if (ds == null || this is DeclSpace)
485 return DocCommentHeader + Name;
487 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
491 // Generates xml doc comments (if any), and if required,
492 // handle warning report.
494 internal virtual void GenerateDocComment (DeclSpace ds)
496 DocUtil.GenerateDocComment (this, ds);
501 /// Base class for structs, classes, enumerations and interfaces.
504 /// They all create new declaration spaces. This
505 /// provides the common foundation for managing those name
508 public abstract class DeclSpace : MemberCore, IAlias {
510 /// This points to the actual definition that is being
511 /// created with System.Reflection.Emit
513 public TypeBuilder TypeBuilder;
516 /// If we are a generic type, this is the type we are
517 /// currently defining. We need to lookup members on this
518 /// instead of the TypeBuilder.
520 public Type CurrentType;
523 // This is the namespace in which this typecontainer
524 // was declared. We use this to resolve names.
526 public NamespaceEntry NamespaceEntry;
528 private Hashtable Cache = new Hashtable ();
530 public readonly string Basename;
531 public readonly string Basename_with_arity;
533 protected Hashtable defined_names;
535 readonly bool is_generic;
536 readonly int count_type_params;
538 // The emit context for toplevel objects.
539 protected EmitContext ec;
541 public EmitContext EmitContext {
546 // Whether we are Generic
548 public bool IsGeneric {
552 else if (Parent != null)
553 return Parent.IsGeneric;
559 static string[] attribute_targets = new string [] { "type" };
561 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
562 Attributes attrs, Location l)
563 : base (parent, name, attrs, l)
566 Basename = name.Name;
567 Basename_with_arity = name.Basename;
568 defined_names = new Hashtable ();
569 if (name.TypeArguments != null) {
571 count_type_params = name.TypeArguments.Count;
574 count_type_params += parent.count_type_params;
578 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
580 protected bool AddToContainer (MemberCore symbol, string fullname, string basename)
582 if (basename == Basename && !(this is Interface)) {
583 if (symbol is TypeParameter)
584 Report.Error (694, "Type parameter `{0}' has same name as " +
585 "containing type or method", basename);
587 Report.SymbolRelatedToPreviousError (this);
588 Report.Error (542, "'{0}': member names cannot be the same as their " +
589 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
594 MemberCore mc = (MemberCore)defined_names [fullname];
597 defined_names.Add (fullname, symbol);
601 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
604 if (symbol is TypeParameter)
605 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", basename);
607 Report.SymbolRelatedToPreviousError (mc);
608 Report.Error (102, symbol.Location,
609 "The type '{0}' already contains a definition for '{1}'",
610 GetSignatureForError (), basename);
615 public void RecordDecl ()
617 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
618 NamespaceEntry.DefineName (MemberName.Basename, this);
622 /// Returns the MemberCore associated with a given name in the declaration
623 /// space. It doesn't return method based symbols !!
626 public MemberCore GetDefinition (string name)
628 return (MemberCore)defined_names [name];
631 bool in_transit = false;
634 /// This function is used to catch recursive definitions
637 public bool InTransit {
648 // root_types contains all the types. All TopLevel types
649 // hence have a parent that points to `root_types', that is
650 // why there is a non-obvious test down here.
652 public bool IsTopLevel {
655 if (Parent.Parent == null)
662 public virtual void CloseType ()
664 if ((caching_flags & Flags.CloseTypeCreated) == 0){
666 TypeBuilder.CreateType ();
669 // The try/catch is needed because
670 // nested enumerations fail to load when they
673 // Even if this is the right order (enumerations
674 // declared after types).
676 // Note that this still creates the type and
677 // it is possible to save it
679 caching_flags |= Flags.CloseTypeCreated;
684 /// Should be overriten by the appropriate declaration space
686 public abstract TypeBuilder DefineType ();
689 /// Define all members, but don't apply any attributes or do anything which may
690 /// access not-yet-defined classes. This method also creates the MemberCache.
692 public abstract bool DefineMembers (TypeContainer parent);
695 // Whether this is an `unsafe context'
697 public bool UnsafeContext {
699 if ((ModFlags & Modifiers.UNSAFE) != 0)
702 return Parent.UnsafeContext;
707 public static string MakeFQN (string nsn, string name)
711 return String.Concat (nsn, ".", name);
714 EmitContext type_resolve_ec;
717 // Resolves the expression `e' for a type, and will recursively define
718 // types. This should only be used for resolving base types.
720 public TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
722 if (type_resolve_ec == null) {
723 // FIXME: I think this should really be one of:
725 // a. type_resolve_ec = Parent.EmitContext;
726 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
728 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
730 type_resolve_ec = new EmitContext (Parent, this, loc, null, null, ModFlags, false);
731 type_resolve_ec.ResolvingTypeTree = true;
733 type_resolve_ec.loc = loc;
734 if (this is GenericMethod)
735 type_resolve_ec.ContainerType = Parent.TypeBuilder;
737 type_resolve_ec.ContainerType = TypeBuilder;
739 return e.ResolveAsTypeTerminal (type_resolve_ec);
742 public bool CheckAccessLevel (Type check_type)
745 if ((this is GenericMethod) || (this is Iterator))
746 tb = Parent.TypeBuilder;
750 if (check_type.IsGenericInstance)
751 check_type = check_type.GetGenericTypeDefinition ();
753 if (check_type == tb)
756 if (TypeBuilder == null)
757 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
758 // However, this is invoked again later -- so safe to return true.
759 // May also be null when resolving top-level attributes.
762 if (check_type.IsGenericParameter)
763 return true; // FIXME
765 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
768 // Broken Microsoft runtime, return public for arrays, no matter what
769 // the accessibility is for their underlying class, and they return
770 // NonPublic visibility for pointers
772 if (check_type.IsArray || check_type.IsPointer)
773 return CheckAccessLevel (TypeManager.GetElementType (check_type));
776 case TypeAttributes.Public:
779 case TypeAttributes.NotPublic:
781 if (TypeBuilder == null)
782 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
783 // However, this is invoked again later -- so safe to return true.
784 // May also be null when resolving top-level attributes.
787 // This test should probably use the declaringtype.
789 return check_type.Assembly == TypeBuilder.Assembly;
791 case TypeAttributes.NestedPublic:
794 case TypeAttributes.NestedPrivate:
795 return NestedAccessible (tb, check_type);
797 case TypeAttributes.NestedFamily:
799 // Only accessible to methods in current type or any subtypes
801 return FamilyAccessible (tb, check_type);
803 case TypeAttributes.NestedFamANDAssem:
804 return (check_type.Assembly == tb.Assembly) &&
805 FamilyAccessible (tb, check_type);
807 case TypeAttributes.NestedFamORAssem:
808 return (check_type.Assembly == tb.Assembly) ||
809 FamilyAccessible (tb, check_type);
811 case TypeAttributes.NestedAssembly:
812 return check_type.Assembly == tb.Assembly;
815 Console.WriteLine ("HERE: " + check_attr);
820 protected bool NestedAccessible (Type tb, Type check_type)
822 Type declaring = check_type.DeclaringType;
823 return TypeBuilder == declaring ||
824 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
827 protected bool FamilyAccessible (Type tb, Type check_type)
829 Type declaring = check_type.DeclaringType;
830 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
833 return NestedAccessible (tb, check_type);
836 // Access level of a type.
838 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
839 // Public Assembly Protected
840 Protected = (0 << 0) | (0 << 1) | (X << 2),
841 Public = (X << 0) | (X << 1) | (X << 2),
842 Private = (0 << 0) | (0 << 1) | (0 << 2),
843 Internal = (0 << 0) | (X << 1) | (0 << 2),
844 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
847 static AccessLevel GetAccessLevelFromModifiers (int flags)
849 if ((flags & Modifiers.INTERNAL) != 0) {
851 if ((flags & Modifiers.PROTECTED) != 0)
852 return AccessLevel.ProtectedOrInternal;
854 return AccessLevel.Internal;
856 } else if ((flags & Modifiers.PROTECTED) != 0)
857 return AccessLevel.Protected;
858 else if ((flags & Modifiers.PRIVATE) != 0)
859 return AccessLevel.Private;
861 return AccessLevel.Public;
864 // What is the effective access level of this?
866 AccessLevel EffectiveAccessLevel {
868 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
869 if (!IsTopLevel && (Parent != null))
870 return myAccess & Parent.EffectiveAccessLevel;
875 // Return the access level for type `t'
876 static AccessLevel TypeEffectiveAccessLevel (Type t)
879 return AccessLevel.Public;
880 if (t.IsNestedPrivate)
881 return AccessLevel.Private;
883 return AccessLevel.Internal;
885 // By now, it must be nested
886 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
888 if (t.IsNestedPublic)
890 if (t.IsNestedAssembly)
891 return parentLevel & AccessLevel.Internal;
892 if (t.IsNestedFamily)
893 return parentLevel & AccessLevel.Protected;
894 if (t.IsNestedFamORAssem)
895 return parentLevel & AccessLevel.ProtectedOrInternal;
896 if (t.IsNestedFamANDAssem)
897 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
899 // nested private is taken care of
901 throw new Exception ("I give up, what are you?");
905 // This answers `is the type P, as accessible as a member M which has the
906 // accessability @flags which is declared as a nested member of the type T, this declspace'
908 public bool AsAccessible (Type p, int flags)
910 if (p.IsGenericParameter)
911 return true; // FIXME
914 // 1) if M is private, its accessability is the same as this declspace.
915 // we already know that P is accessible to T before this method, so we
919 if ((flags & Modifiers.PRIVATE) != 0)
922 while (p.IsArray || p.IsPointer || p.IsByRef)
923 p = TypeManager.GetElementType (p);
925 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
926 AccessLevel mAccess = this.EffectiveAccessLevel &
927 GetAccessLevelFromModifiers (flags);
929 // for every place from which we can access M, we must
930 // be able to access P as well. So, we want
931 // For every bit in M and P, M_i -> P_1 == true
932 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
934 return ~ (~ mAccess | pAccess) == 0;
937 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
939 Report.Error (104, loc,
940 "`{0}' is an ambiguous reference ({1} or {2})",
945 // Return the nested type with name @name. Ensures that the nested type
946 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
948 public virtual Type FindNestedType (string name)
954 // Public function used to locate types, this can only
955 // be used after the ResolveTree function has been invoked.
957 // Set 'silent' to true if you want to suppress "type not found" errors.
958 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
960 // Returns: Type or null if they type can not be found.
962 public FullNamedExpression LookupType (string name, Location loc, bool silent, bool ignore_cs0104)
964 FullNamedExpression e;
966 if (Cache.Contains (name)) {
967 e = (FullNamedExpression) Cache [name];
970 // For the case the type we are looking for is nested within this one
971 // or is in any base class
975 for (DeclSpace containing_ds = this; containing_ds != null; containing_ds = containing_ds.Parent) {
976 // if the member cache has been created, lets use it.
977 // the member cache is MUCH faster.
978 if (containing_ds.MemberCache != null) {
979 t = containing_ds.MemberCache.FindNestedType (name);
983 e = new TypeExpression (t, Location.Null);
988 // no member cache. Do it the hard way -- reflection
989 for (Type current_type = containing_ds.TypeBuilder;
990 current_type != null && current_type != TypeManager.object_type;
991 current_type = current_type.BaseType) {
992 if (current_type is TypeBuilder) {
993 DeclSpace decl = containing_ds;
994 if (current_type != containing_ds.TypeBuilder)
995 decl = TypeManager.LookupDeclSpace (current_type);
997 t = decl.FindNestedType (name);
999 t = TypeManager.LookupTypeDirect (current_type.FullName + "+" + name);
1002 if (t != null && containing_ds.CheckAccessLevel (t)) {
1003 e = new TypeExpression (t, Location.Null);
1010 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1014 if (e == null && !silent)
1015 Report.Error (246, loc, "Cannot find type `"+name+"'");
1021 /// This function is broken and not what you're looking for. It should only
1022 /// be used while the type is still being created since it doesn't use the cache
1023 /// and relies on the filter doing the member name check.
1025 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1026 MemberFilter filter, object criteria);
1029 /// If we have a MemberCache, return it. This property may return null if the
1030 /// class doesn't have a member cache or while it's still being created.
1032 public abstract MemberCache MemberCache {
1036 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1038 TypeBuilder.SetCustomAttribute (cb);
1042 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1043 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1045 public bool GetClsCompliantAttributeValue ()
1047 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1048 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1050 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1052 if (OptAttributes != null) {
1053 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1054 if (cls_attribute != null) {
1055 caching_flags |= Flags.HasClsCompliantAttribute;
1056 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1057 caching_flags |= Flags.ClsCompliantAttributeTrue;
1064 if (Parent == null) {
1065 if (CodeGen.Assembly.IsClsCompliant) {
1066 caching_flags |= Flags.ClsCompliantAttributeTrue;
1072 if (Parent.GetClsCompliantAttributeValue ()) {
1073 caching_flags |= Flags.ClsCompliantAttributeTrue;
1080 // Extensions for generics
1082 TypeParameter[] type_params;
1083 TypeParameter[] type_param_list;
1085 protected string GetInstantiationName ()
1087 StringBuilder sb = new StringBuilder (Name);
1089 for (int i = 0; i < type_param_list.Length; i++) {
1092 sb.Append (type_param_list [i].Name);
1095 return sb.ToString ();
1098 bool check_type_parameter (ArrayList list, int start, string name)
1100 for (int i = 0; i < start; i++) {
1101 TypeParameter param = (TypeParameter) list [i];
1103 if (param.Name != name)
1106 if (RootContext.WarningLevel >= 3)
1109 "Type parameter `{0}' has same name " +
1110 "as type parameter from outer type `{1}'",
1111 name, Parent.GetInstantiationName ());
1119 TypeParameter[] initialize_type_params ()
1121 if (type_param_list != null)
1122 return type_param_list;
1124 DeclSpace the_parent = Parent;
1125 if (this is GenericMethod)
1129 TypeParameter[] parent_params = null;
1130 if ((the_parent != null) && the_parent.IsGeneric) {
1131 parent_params = the_parent.initialize_type_params ();
1132 start = parent_params != null ? parent_params.Length : 0;
1135 ArrayList list = new ArrayList ();
1136 if (parent_params != null)
1137 list.AddRange (parent_params);
1139 int count = type_params != null ? type_params.Length : 0;
1140 for (int i = 0; i < count; i++) {
1141 TypeParameter param = type_params [i];
1142 check_type_parameter (list, start, param.Name);
1146 type_param_list = new TypeParameter [list.Count];
1147 list.CopyTo (type_param_list, 0);
1148 return type_param_list;
1151 public virtual void SetParameterInfo (ArrayList constraints_list)
1154 if (constraints_list != null) {
1156 80, Location, "Contraints are not allowed " +
1157 "on non-generic declarations");
1163 string[] names = MemberName.TypeArguments.GetDeclarations ();
1164 type_params = new TypeParameter [names.Length];
1167 // Register all the names
1169 for (int i = 0; i < type_params.Length; i++) {
1170 string name = names [i];
1172 Constraints constraints = null;
1173 if (constraints_list != null) {
1174 foreach (Constraints constraint in constraints_list) {
1175 if (constraint.TypeParameter == name) {
1176 constraints = constraint;
1182 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1184 string full_name = Name + "." + name;
1185 AddToContainer (type_params [i], full_name, name);
1189 public TypeParameter[] TypeParameters {
1192 throw new InvalidOperationException ();
1193 if (type_param_list == null)
1194 initialize_type_params ();
1196 return type_param_list;
1200 protected TypeParameter[] CurrentTypeParameters {
1203 throw new InvalidOperationException ();
1204 if (type_params != null)
1207 return new TypeParameter [0];
1211 public int CountTypeParameters {
1213 return count_type_params;
1217 public TypeParameterExpr LookupGeneric (string name, Location loc)
1222 foreach (TypeParameter type_param in CurrentTypeParameters) {
1223 if (type_param.Name != name)
1226 return new TypeParameterExpr (type_param, loc);
1230 return Parent.LookupGeneric (name, loc);
1235 bool IAlias.IsType {
1236 get { return true; }
1239 string IAlias.Name {
1240 get { return Name; }
1243 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1245 if (TypeBuilder == null)
1246 throw new InvalidOperationException ();
1248 if (CurrentType != null)
1249 return new TypeExpression (CurrentType, Location);
1251 return new TypeExpression (TypeBuilder, Location);
1254 public override string[] ValidAttributeTargets {
1256 return attribute_targets;
1262 /// This is a readonly list of MemberInfo's.
1264 public class MemberList : IList {
1265 public readonly IList List;
1269 /// Create a new MemberList from the given IList.
1271 public MemberList (IList list)
1276 this.List = new ArrayList ();
1281 /// Concatenate the ILists `first' and `second' to a new MemberList.
1283 public MemberList (IList first, IList second)
1285 ArrayList list = new ArrayList ();
1286 list.AddRange (first);
1287 list.AddRange (second);
1292 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1295 /// Cast the MemberList into a MemberInfo[] array.
1298 /// This is an expensive operation, only use it if it's really necessary.
1300 public static explicit operator MemberInfo [] (MemberList list)
1302 Timer.StartTimer (TimerType.MiscTimer);
1303 MemberInfo [] result = new MemberInfo [list.Count];
1304 list.CopyTo (result, 0);
1305 Timer.StopTimer (TimerType.MiscTimer);
1317 public bool IsSynchronized {
1319 return List.IsSynchronized;
1323 public object SyncRoot {
1325 return List.SyncRoot;
1329 public void CopyTo (Array array, int index)
1331 List.CopyTo (array, index);
1336 public IEnumerator GetEnumerator ()
1338 return List.GetEnumerator ();
1343 public bool IsFixedSize {
1349 public bool IsReadOnly {
1355 object IList.this [int index] {
1357 return List [index];
1361 throw new NotSupportedException ();
1365 // FIXME: try to find out whether we can avoid the cast in this indexer.
1366 public MemberInfo this [int index] {
1368 return (MemberInfo) List [index];
1372 public int Add (object value)
1374 throw new NotSupportedException ();
1377 public void Clear ()
1379 throw new NotSupportedException ();
1382 public bool Contains (object value)
1384 return List.Contains (value);
1387 public int IndexOf (object value)
1389 return List.IndexOf (value);
1392 public void Insert (int index, object value)
1394 throw new NotSupportedException ();
1397 public void Remove (object value)
1399 throw new NotSupportedException ();
1402 public void RemoveAt (int index)
1404 throw new NotSupportedException ();
1409 /// This interface is used to get all members of a class when creating the
1410 /// member cache. It must be implemented by all DeclSpace derivatives which
1411 /// want to support the member cache and by TypeHandle to get caching of
1412 /// non-dynamic types.
1414 public interface IMemberContainer {
1416 /// The name of the IMemberContainer. This is only used for
1417 /// debugging purposes.
1424 /// The type of this IMemberContainer.
1431 /// Returns the IMemberContainer of the base class or null if this
1432 /// is an interface or TypeManger.object_type.
1433 /// This is used when creating the member cache for a class to get all
1434 /// members from the base class.
1436 MemberCache BaseCache {
1441 /// Whether this is an interface.
1448 /// Returns all members of this class with the corresponding MemberTypes
1449 /// and BindingFlags.
1452 /// When implementing this method, make sure not to return any inherited
1453 /// members and check the MemberTypes and BindingFlags properly.
1454 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1455 /// get the BindingFlags (static/non-static,public/non-public) in the
1456 /// MemberInfo class, but the cache needs this information. That's why
1457 /// this method is called multiple times with different BindingFlags.
1459 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1462 /// Return the container's member cache.
1464 MemberCache MemberCache {
1470 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1471 /// member lookups. It has a member name based hash table; it maps each member
1472 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1473 /// and the BindingFlags that were initially used to get it. The cache contains
1474 /// all members of the current class and all inherited members. If this cache is
1475 /// for an interface types, it also contains all inherited members.
1477 /// There are two ways to get a MemberCache:
1478 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1479 /// use the DeclSpace.MemberCache property.
1480 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1481 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1483 public class MemberCache {
1484 public readonly IMemberContainer Container;
1485 protected Hashtable member_hash;
1486 protected Hashtable method_hash;
1489 /// Create a new MemberCache for the given IMemberContainer `container'.
1491 public MemberCache (IMemberContainer container)
1493 this.Container = container;
1495 Timer.IncrementCounter (CounterType.MemberCache);
1496 Timer.StartTimer (TimerType.CacheInit);
1498 // If we have a base class (we have a base class unless we're
1499 // TypeManager.object_type), we deep-copy its MemberCache here.
1500 if (Container.BaseCache != null)
1501 member_hash = SetupCache (Container.BaseCache);
1503 member_hash = new Hashtable ();
1505 // If this is neither a dynamic type nor an interface, create a special
1506 // method cache with all declared and inherited methods.
1507 Type type = container.Type;
1508 if (!(type is TypeBuilder) && !type.IsInterface &&
1509 // !(type.IsGenericInstance && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1510 !type.IsGenericInstance &&
1511 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1512 method_hash = new Hashtable ();
1516 // Add all members from the current class.
1517 AddMembers (Container);
1519 Timer.StopTimer (TimerType.CacheInit);
1522 public MemberCache (Type[] ifaces)
1525 // The members of this cache all belong to other caches.
1526 // So, 'Container' will not be used.
1528 this.Container = null;
1530 member_hash = new Hashtable ();
1534 foreach (Type itype in ifaces)
1535 AddCacheContents (TypeManager.LookupMemberCache (itype));
1539 /// Bootstrap this member cache by doing a deep-copy of our base.
1541 Hashtable SetupCache (MemberCache base_class)
1543 Hashtable hash = new Hashtable ();
1545 if (base_class == null)
1548 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1549 while (it.MoveNext ()) {
1550 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1556 void ClearDeclaredOnly (Hashtable hash)
1558 IDictionaryEnumerator it = hash.GetEnumerator ();
1559 while (it.MoveNext ()) {
1560 foreach (CacheEntry ce in (ArrayList) it.Value)
1561 ce.EntryType &= ~EntryType.Declared;
1566 /// Add the contents of `cache' to the member_hash.
1568 void AddCacheContents (MemberCache cache)
1570 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1571 while (it.MoveNext ()) {
1572 ArrayList list = (ArrayList) member_hash [it.Key];
1574 member_hash [it.Key] = list = new ArrayList ();
1576 ArrayList entries = (ArrayList) it.Value;
1577 for (int i = entries.Count-1; i >= 0; i--) {
1578 CacheEntry entry = (CacheEntry) entries [i];
1580 if (entry.Container != cache.Container)
1588 /// Add all members from class `container' to the cache.
1590 void AddMembers (IMemberContainer container)
1592 // We need to call AddMembers() with a single member type at a time
1593 // to get the member type part of CacheEntry.EntryType right.
1594 if (!container.IsInterface) {
1595 AddMembers (MemberTypes.Constructor, container);
1596 AddMembers (MemberTypes.Field, container);
1598 AddMembers (MemberTypes.Method, container);
1599 AddMembers (MemberTypes.Property, container);
1600 AddMembers (MemberTypes.Event, container);
1601 // Nested types are returned by both Static and Instance searches.
1602 AddMembers (MemberTypes.NestedType,
1603 BindingFlags.Static | BindingFlags.Public, container);
1604 AddMembers (MemberTypes.NestedType,
1605 BindingFlags.Static | BindingFlags.NonPublic, container);
1608 void AddMembers (MemberTypes mt, IMemberContainer container)
1610 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1611 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1612 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1613 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1617 /// Add all members from class `container' with the requested MemberTypes and
1618 /// BindingFlags to the cache. This method is called multiple times with different
1619 /// MemberTypes and BindingFlags.
1621 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1623 MemberList members = container.GetMembers (mt, bf);
1625 foreach (MemberInfo member in members) {
1626 string name = member.Name;
1628 int pos = name.IndexOf ('<');
1630 name = name.Substring (0, pos);
1632 // We use a name-based hash table of ArrayList's.
1633 ArrayList list = (ArrayList) member_hash [name];
1635 list = new ArrayList ();
1636 member_hash.Add (name, list);
1639 // When this method is called for the current class, the list will
1640 // already contain all inherited members from our base classes.
1641 // We cannot add new members in front of the list since this'd be an
1642 // expensive operation, that's why the list is sorted in reverse order
1643 // (ie. members from the current class are coming last).
1644 list.Add (new CacheEntry (container, member, mt, bf));
1649 /// Add all declared and inherited methods from class `type' to the method cache.
1651 void AddMethods (Type type)
1653 AddMethods (BindingFlags.Static | BindingFlags.Public |
1654 BindingFlags.FlattenHierarchy, type);
1655 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1656 BindingFlags.FlattenHierarchy, type);
1657 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1658 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1661 void AddMethods (BindingFlags bf, Type type)
1664 // Consider the case:
1666 // class X { public virtual int f() {} }
1669 // When processing 'Y', the method_cache will already have a copy of 'f',
1670 // with ReflectedType == X. However, we want to ensure that its ReflectedType == Y
1672 MethodBase [] members = type.GetMethods (bf);
1674 Array.Reverse (members);
1676 foreach (MethodBase member in members) {
1677 string name = member.Name;
1679 // We use a name-based hash table of ArrayList's.
1680 ArrayList list = (ArrayList) method_hash [name];
1682 list = new ArrayList ();
1683 method_hash.Add (name, list);
1686 if (member.IsVirtual &&
1687 (member.Attributes & MethodAttributes.NewSlot) == 0) {
1688 MethodInfo base_method = ((MethodInfo) member).GetBaseDefinition ();
1690 if (base_method == member) {
1692 // Both mcs and CSC 1.1 seem to emit a somewhat broken
1693 // ...Invoke () function for delegates: it's missing a 'newslot'.
1694 // CSC 2.0 emits a 'newslot' for a delegate's Invoke.
1696 if (member.Name != "Invoke" ||
1697 !TypeManager.IsDelegateType (type)) {
1698 Report.SymbolRelatedToPreviousError (base_method);
1699 Report.Warning (-28,
1700 "{0} contains a method '{1}' that is marked " +
1701 " virtual, but doesn't appear to have a slot." +
1702 " The method may be ignored during overload resolution",
1709 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1710 if ((base_method.Attributes & MethodAttributes.NewSlot) != 0)
1714 // Shouldn't get here. Mono appears to be buggy.
1716 MethodInfo new_base_method = base_method.GetBaseDefinition ();
1717 if (new_base_method == base_method) {
1718 Report.SymbolRelatedToPreviousError (base_method);
1719 Report.Warning (-28,
1720 "{0} contains a method '{1}' that is marked " +
1721 " virtual, but doesn't appear to have a slot." +
1722 " The method may be ignored during overload resolution",
1725 base_method = new_base_method;
1732 // Unfortunately, the elements returned by Type.GetMethods() aren't
1733 // sorted so we need to do this check for every member.
1734 BindingFlags new_bf = bf;
1735 if (member.DeclaringType == type)
1736 new_bf |= BindingFlags.DeclaredOnly;
1738 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1743 /// Compute and return a appropriate `EntryType' magic number for the given
1744 /// MemberTypes and BindingFlags.
1746 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1748 EntryType type = EntryType.None;
1750 if ((mt & MemberTypes.Constructor) != 0)
1751 type |= EntryType.Constructor;
1752 if ((mt & MemberTypes.Event) != 0)
1753 type |= EntryType.Event;
1754 if ((mt & MemberTypes.Field) != 0)
1755 type |= EntryType.Field;
1756 if ((mt & MemberTypes.Method) != 0)
1757 type |= EntryType.Method;
1758 if ((mt & MemberTypes.Property) != 0)
1759 type |= EntryType.Property;
1760 // Nested types are returned by static and instance searches.
1761 if ((mt & MemberTypes.NestedType) != 0)
1762 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1764 if ((bf & BindingFlags.Instance) != 0)
1765 type |= EntryType.Instance;
1766 if ((bf & BindingFlags.Static) != 0)
1767 type |= EntryType.Static;
1768 if ((bf & BindingFlags.Public) != 0)
1769 type |= EntryType.Public;
1770 if ((bf & BindingFlags.NonPublic) != 0)
1771 type |= EntryType.NonPublic;
1772 if ((bf & BindingFlags.DeclaredOnly) != 0)
1773 type |= EntryType.Declared;
1779 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1780 /// denote multiple member types. Returns true if the given flags value denotes a
1781 /// single member types.
1783 public static bool IsSingleMemberType (MemberTypes mt)
1786 case MemberTypes.Constructor:
1787 case MemberTypes.Event:
1788 case MemberTypes.Field:
1789 case MemberTypes.Method:
1790 case MemberTypes.Property:
1791 case MemberTypes.NestedType:
1800 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1801 /// number to speed up the searching process.
1804 protected enum EntryType {
1809 MaskStatic = Instance|Static,
1813 MaskProtection = Public|NonPublic,
1817 Constructor = 0x020,
1824 MaskType = Constructor|Event|Field|Method|Property|NestedType
1827 protected class CacheEntry {
1828 public readonly IMemberContainer Container;
1829 public EntryType EntryType;
1830 public MemberInfo Member;
1832 public CacheEntry (IMemberContainer container, MemberInfo member,
1833 MemberTypes mt, BindingFlags bf)
1835 this.Container = container;
1836 this.Member = member;
1837 this.EntryType = GetEntryType (mt, bf);
1840 public override string ToString ()
1842 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1848 /// This is called each time we're walking up one level in the class hierarchy
1849 /// and checks whether we can abort the search since we've already found what
1850 /// we were looking for.
1852 protected bool DoneSearching (ArrayList list)
1855 // We've found exactly one member in the current class and it's not
1856 // a method or constructor.
1858 if (list.Count == 1 && !(list [0] is MethodBase))
1862 // Multiple properties: we query those just to find out the indexer
1865 if ((list.Count > 0) && (list [0] is PropertyInfo))
1872 /// Looks up members with name `name'. If you provide an optional
1873 /// filter function, it'll only be called with members matching the
1874 /// requested member name.
1876 /// This method will try to use the cache to do the lookup if possible.
1878 /// Unlike other FindMembers implementations, this method will always
1879 /// check all inherited members - even when called on an interface type.
1881 /// If you know that you're only looking for methods, you should use
1882 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1883 /// When doing a method-only search, it'll try to use a special method
1884 /// cache (unless it's a dynamic type or an interface) and the returned
1885 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1886 /// The lookup process will automatically restart itself in method-only
1887 /// search mode if it discovers that it's about to return methods.
1889 ArrayList global = new ArrayList ();
1890 bool using_global = false;
1892 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1894 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1895 MemberFilter filter, object criteria)
1898 throw new Exception ();
1900 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1901 bool method_search = mt == MemberTypes.Method;
1902 // If we have a method cache and we aren't already doing a method-only search,
1903 // then we restart a method search if the first match is a method.
1904 bool do_method_search = !method_search && (method_hash != null);
1906 ArrayList applicable;
1908 // If this is a method-only search, we try to use the method cache if
1909 // possible; a lookup in the method cache will return a MemberInfo with
1910 // the correct ReflectedType for inherited methods.
1912 if (method_search && (method_hash != null))
1913 applicable = (ArrayList) method_hash [name];
1915 applicable = (ArrayList) member_hash [name];
1917 if (applicable == null)
1918 return emptyMemberInfo;
1921 // 32 slots gives 53 rss/54 size
1922 // 2/4 slots gives 55 rss
1924 // Strange: from 25,000 calls, only 1,800
1925 // are above 2. Why does this impact it?
1928 using_global = true;
1930 Timer.StartTimer (TimerType.CachedLookup);
1932 EntryType type = GetEntryType (mt, bf);
1934 IMemberContainer current = Container;
1937 // `applicable' is a list of all members with the given member name `name'
1938 // in the current class and all its base classes. The list is sorted in
1939 // reverse order due to the way how the cache is initialy created (to speed
1940 // things up, we're doing a deep-copy of our base).
1942 for (int i = applicable.Count-1; i >= 0; i--) {
1943 CacheEntry entry = (CacheEntry) applicable [i];
1945 // This happens each time we're walking one level up in the class
1946 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1947 // the first time this happens (this may already happen in the first
1948 // iteration of this loop if there are no members with the name we're
1949 // looking for in the current class).
1950 if (entry.Container != current) {
1951 if (declared_only || DoneSearching (global))
1954 current = entry.Container;
1957 // Is the member of the correct type ?
1958 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1961 // Is the member static/non-static ?
1962 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1965 // Apply the filter to it.
1966 if (filter (entry.Member, criteria)) {
1967 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1968 do_method_search = false;
1969 global.Add (entry.Member);
1973 Timer.StopTimer (TimerType.CachedLookup);
1975 // If we have a method cache and we aren't already doing a method-only
1976 // search, we restart in method-only search mode if the first match is
1977 // a method. This ensures that we return a MemberInfo with the correct
1978 // ReflectedType for inherited methods.
1979 if (do_method_search && (global.Count > 0)){
1980 using_global = false;
1982 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1985 using_global = false;
1986 MemberInfo [] copy = new MemberInfo [global.Count];
1987 global.CopyTo (copy);
1991 // find the nested type @name in @this.
1992 public Type FindNestedType (string name)
1994 ArrayList applicable = (ArrayList) member_hash [name];
1995 if (applicable == null)
1998 for (int i = applicable.Count-1; i >= 0; i--) {
1999 CacheEntry entry = (CacheEntry) applicable [i];
2000 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2001 return (Type) entry.Member;
2008 // This finds the method or property for us to override. invocationType is the type where
2009 // the override is going to be declared, name is the name of the method/property, and
2010 // paramTypes is the parameters, if any to the method or property
2012 // Because the MemberCache holds members from this class and all the base classes,
2013 // we can avoid tons of reflection stuff.
2015 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2017 ArrayList applicable;
2018 if (method_hash != null && !is_property)
2019 applicable = (ArrayList) method_hash [name];
2021 applicable = (ArrayList) member_hash [name];
2023 if (applicable == null)
2026 // Walk the chain of methods, starting from the top.
2028 for (int i = applicable.Count - 1; i >= 0; i--) {
2029 CacheEntry entry = (CacheEntry) applicable [i];
2031 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2034 PropertyInfo pi = null;
2035 MethodInfo mi = null;
2036 FieldInfo fi = null;
2037 Type [] cmpAttrs = null;
2040 if ((entry.EntryType & EntryType.Field) != 0) {
2041 fi = (FieldInfo)entry.Member;
2043 // TODO: For this case we ignore member type
2044 //fb = TypeManager.GetField (fi);
2045 //cmpAttrs = new Type[] { fb.MemberType };
2047 pi = (PropertyInfo) entry.Member;
2048 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2051 mi = (MethodInfo) entry.Member;
2052 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2056 // TODO: Almost duplicate !
2058 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2059 case FieldAttributes.Private:
2061 // A private method is Ok if we are a nested subtype.
2062 // The spec actually is not very clear about this, see bug 52458.
2064 if (invocationType != entry.Container.Type &
2065 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2069 case FieldAttributes.FamANDAssem:
2070 case FieldAttributes.Assembly:
2072 // Check for assembly methods
2074 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2078 return entry.Member;
2082 // Check the arguments
2084 if (cmpAttrs.Length != paramTypes.Length)
2087 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2088 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2093 // get one of the methods because this has the visibility info.
2096 mi = pi.GetGetMethod (true);
2098 mi = pi.GetSetMethod (true);
2104 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2105 case MethodAttributes.Private:
2107 // A private method is Ok if we are a nested subtype.
2108 // The spec actually is not very clear about this, see bug 52458.
2110 if (invocationType.Equals (entry.Container.Type) ||
2111 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2112 return entry.Member;
2115 case MethodAttributes.FamANDAssem:
2116 case MethodAttributes.Assembly:
2118 // Check for assembly methods
2120 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2121 return entry.Member;
2126 // A protected method is ok, because we are overriding.
2127 // public is always ok.
2129 return entry.Member;
2139 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2140 /// We handle two cases. The first is for types without parameters (events, field, properties).
2141 /// The second are methods, indexers and this is why ignore_complex_types is here.
2142 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2144 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2146 ArrayList applicable = null;
2148 if (method_hash != null)
2149 applicable = (ArrayList) method_hash [name];
2151 if (applicable != null) {
2152 for (int i = applicable.Count - 1; i >= 0; i--) {
2153 CacheEntry entry = (CacheEntry) applicable [i];
2154 if ((entry.EntryType & EntryType.Public) != 0)
2155 return entry.Member;
2159 if (member_hash == null)
2161 applicable = (ArrayList) member_hash [name];
2163 if (applicable != null) {
2164 for (int i = applicable.Count - 1; i >= 0; i--) {
2165 CacheEntry entry = (CacheEntry) applicable [i];
2166 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2167 if (ignore_complex_types) {
2168 if ((entry.EntryType & EntryType.Method) != 0)
2171 // Does exist easier way how to detect indexer ?
2172 if ((entry.EntryType & EntryType.Property) != 0) {
2173 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2174 if (arg_types.Length > 0)
2178 return entry.Member;
2185 Hashtable locase_table;
2188 /// Builds low-case table for CLS Compliance test
2190 public Hashtable GetPublicMembers ()
2192 if (locase_table != null)
2193 return locase_table;
2195 locase_table = new Hashtable ();
2196 foreach (DictionaryEntry entry in member_hash) {
2197 ArrayList members = (ArrayList)entry.Value;
2198 for (int ii = 0; ii < members.Count; ++ii) {
2199 CacheEntry member_entry = (CacheEntry) members [ii];
2201 if ((member_entry.EntryType & EntryType.Public) == 0)
2204 // TODO: Does anyone know easier way how to detect that member is internal ?
2205 switch (member_entry.EntryType & EntryType.MaskType) {
2206 case EntryType.Constructor:
2209 case EntryType.Field:
2210 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2214 case EntryType.Method:
2215 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2219 case EntryType.Property:
2220 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2221 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2225 case EntryType.Event:
2226 EventInfo ei = (EventInfo)member_entry.Member;
2227 MethodInfo mi = ei.GetAddMethod ();
2228 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2232 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2233 locase_table [lcase] = member_entry.Member;
2237 return locase_table;
2240 public Hashtable Members {
2247 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2249 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2251 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2253 for (int i = 0; i < al.Count; ++i) {
2254 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2257 if (entry.Member == this_builder)
2260 if ((entry.EntryType & tested_type) != tested_type)
2263 MethodBase method_to_compare = (MethodBase)entry.Member;
2264 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2267 IMethodData md = TypeManager.GetMethod (method_to_compare);
2269 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2270 // However it is exactly what csc does.
2271 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2274 Report.SymbolRelatedToPreviousError (entry.Member);
2275 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());