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 ()
117 return Left.GetTypeName () + "." +
118 MakeName (Name, TypeArguments);
120 return MakeName (Name, TypeArguments);
123 protected bool IsUnbound {
125 if ((Left != null) && Left.IsUnbound)
127 else if (TypeArguments == null)
130 return TypeArguments.IsUnbound;
134 protected bool CheckUnbound (Location loc)
136 if ((Left != null) && !Left.CheckUnbound (loc))
138 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
139 Report.Error (1031, loc, "Type expected");
146 public Expression GetTypeExpression (Location loc)
149 if (!CheckUnbound (loc))
152 return new UnboundTypeExpression (GetTypeName ());
156 Expression lexpr = Left.GetTypeExpression (loc);
158 return new MemberAccess (lexpr, Name, TypeArguments, loc);
160 if (TypeArguments != null)
161 return new ConstructedType (Name, TypeArguments, loc);
163 return new SimpleName (Name, loc);
167 public MemberName Clone ()
170 return new MemberName (Left.Clone (), Name, TypeArguments);
172 return new MemberName (Name, TypeArguments);
175 public string Basename {
177 if (TypeArguments != null)
178 return MakeName (Name, TypeArguments);
184 public override string ToString ()
187 if (TypeArguments != null)
188 full_name = Name + "<" + TypeArguments + ">";
193 return Left + "." + full_name;
200 /// Base representation for members. This is used to keep track
201 /// of Name, Location and Modifier flags, and handling Attributes.
203 public abstract class MemberCore : Attributable {
209 return MemberName.GetName (!(this is GenericMethod) && !(this is Method));
213 // Is not readonly because of IndexerName attribute
214 public MemberName MemberName;
217 /// Modifier flags that the user specified in the source code
221 public readonly TypeContainer Parent;
224 /// Location where this declaration happens
226 public readonly Location Location;
229 /// XML documentation comment
231 public string DocComment;
234 /// Represents header string for documentation comment
235 /// for each member types.
237 public abstract string DocCommentHeader { get; }
241 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
242 Obsolete = 1 << 1, // Type has obsolete attribute
243 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
244 ClsCompliant = 1 << 3, // Type is CLS Compliant
245 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
246 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
247 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
248 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
249 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
250 Excluded = 1 << 9, // Method is conditional
251 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
255 /// MemberCore flags at first detected then cached
257 internal Flags caching_flags;
259 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
266 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
270 /// Tests presence of ObsoleteAttribute and report proper error
272 protected void CheckUsageOfObsoleteAttribute (Type type)
277 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
278 if (obsolete_attr == null)
281 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
284 public abstract bool Define ();
287 // Returns full member name for error message
289 public virtual string GetSignatureForError ()
295 /// Use this method when MethodBuilder is null
297 public virtual string GetSignatureForError (TypeContainer tc)
303 /// Base Emit method. This is also entry point for CLS-Compliant verification.
305 public virtual void Emit ()
307 // Hack with Parent == null is for EnumMember
308 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
309 VerifyObsoleteAttribute ();
311 if (!RootContext.VerifyClsCompliance)
314 VerifyClsCompliance (Parent);
317 public bool InUnsafe {
319 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
324 // Whehter is it ok to use an unsafe pointer in this type container
326 public bool UnsafeOK (DeclSpace parent)
329 // First check if this MemberCore modifier flags has unsafe set
331 if ((ModFlags & Modifiers.UNSAFE) != 0)
334 if (parent.UnsafeContext)
337 Expression.UnsafeError (Location);
342 /// Returns instance of ObsoleteAttribute for this MemberCore
344 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
346 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
347 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
351 caching_flags &= ~Flags.Obsolete_Undetected;
353 if (OptAttributes == null)
356 Attribute obsolete_attr = OptAttributes.Search (
357 TypeManager.obsolete_attribute_type, ds.EmitContext);
358 if (obsolete_attr == null)
361 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
362 if (obsolete == null)
365 caching_flags |= Flags.Obsolete;
370 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
372 public override bool IsClsCompliaceRequired (DeclSpace container)
374 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
375 return (caching_flags & Flags.ClsCompliant) != 0;
377 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
378 caching_flags &= ~Flags.ClsCompliance_Undetected;
379 caching_flags |= Flags.ClsCompliant;
383 caching_flags &= ~Flags.ClsCompliance_Undetected;
388 /// Returns true when MemberCore is exposed from assembly.
390 public bool IsExposedFromAssembly (DeclSpace ds)
392 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
395 DeclSpace parentContainer = ds;
396 while (parentContainer != null && parentContainer.ModFlags != 0) {
397 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
399 parentContainer = parentContainer.Parent;
405 /// Resolve CLSCompliantAttribute value or gets cached value.
407 bool GetClsCompliantAttributeValue (DeclSpace ds)
409 if (OptAttributes != null) {
410 Attribute cls_attribute = OptAttributes.Search (
411 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
412 if (cls_attribute != null) {
413 caching_flags |= Flags.HasClsCompliantAttribute;
414 return cls_attribute.GetClsCompliantAttributeValue (ds);
417 return ds.GetClsCompliantAttributeValue ();
421 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
423 protected bool HasClsCompliantAttribute {
425 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
430 /// The main virtual method for CLS-Compliant verifications.
431 /// The method returns true if member is CLS-Compliant and false if member is not
432 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
433 /// and add their extra verifications.
435 protected virtual bool VerifyClsCompliance (DeclSpace ds)
437 if (!IsClsCompliaceRequired (ds)) {
438 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
439 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
444 if (!CodeGen.Assembly.IsClsCompliant) {
445 if (HasClsCompliantAttribute) {
446 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
451 int index = Name.LastIndexOf ('.');
452 if (Name [index > 0 ? index + 1 : 0] == '_') {
453 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
458 protected abstract void VerifyObsoleteAttribute ();
461 // Raised (and passed an XmlElement that contains the comment)
462 // when GenerateDocComment is writing documentation expectedly.
464 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
469 // Returns a string that represents the signature for this
470 // member which should be used in XML documentation.
472 public virtual string GetDocCommentName (DeclSpace ds)
474 if (ds == null || this is DeclSpace)
475 return DocCommentHeader + Name;
477 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
481 // Generates xml doc comments (if any), and if required,
482 // handle warning report.
484 internal virtual void GenerateDocComment (DeclSpace ds)
486 DocUtil.GenerateDocComment (this, ds);
491 /// Base class for structs, classes, enumerations and interfaces.
494 /// They all create new declaration spaces. This
495 /// provides the common foundation for managing those name
498 public abstract class DeclSpace : MemberCore, IAlias {
500 /// This points to the actual definition that is being
501 /// created with System.Reflection.Emit
503 public TypeBuilder TypeBuilder;
506 /// If we are a generic type, this is the type we are
507 /// currently defining. We need to lookup members on this
508 /// instead of the TypeBuilder.
510 public Type CurrentType;
513 // This is the namespace in which this typecontainer
514 // was declared. We use this to resolve names.
516 public NamespaceEntry NamespaceEntry;
518 public Hashtable Cache = new Hashtable ();
520 public string Basename;
522 protected Hashtable defined_names;
524 readonly bool is_generic;
525 readonly int count_type_params;
527 // The emit context for toplevel objects.
528 protected EmitContext ec;
530 public EmitContext EmitContext {
535 // Whether we are Generic
537 public bool IsGeneric {
541 else if (Parent != null)
542 return Parent.IsGeneric;
548 static string[] attribute_targets = new string [] { "type" };
550 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
551 Attributes attrs, Location l)
552 : base (parent, name, attrs, l)
555 Basename = name.Name;
556 defined_names = new Hashtable ();
557 if (name.TypeArguments != null) {
559 count_type_params = name.TypeArguments.Count;
562 count_type_params += parent.count_type_params;
566 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
568 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
570 if (basename == Basename && !(this is Interface)) {
571 if (symbol is TypeParameter)
572 Report.Error (694, "Type parameter `{0}' has same name as " +
573 "containing type or method", basename);
575 Report.SymbolRelatedToPreviousError (this);
576 Report.Error (542, "'{0}': member names cannot be the same as their " +
577 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
582 MemberCore mc = (MemberCore)defined_names [fullname];
584 if (is_method && (mc is MethodCore || mc is IMethodData)) {
585 symbol.caching_flags |= Flags.TestMethodDuplication;
586 mc.caching_flags |= Flags.TestMethodDuplication;
591 if (symbol is TypeParameter)
592 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", basename);
594 Report.SymbolRelatedToPreviousError (mc);
595 Report.Error (102, symbol.Location,
596 "The type '{0}' already contains a definition for '{1}'",
597 GetSignatureForError (), basename);
602 defined_names.Add (fullname, symbol);
606 public void RecordDecl ()
608 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
609 NamespaceEntry.DefineName (MemberName.Basename, this);
613 /// Returns the MemberCore associated with a given name in the declaration
614 /// space. It doesn't return method based symbols !!
617 public MemberCore GetDefinition (string name)
619 return (MemberCore)defined_names [name];
622 bool in_transit = false;
625 /// This function is used to catch recursive definitions
628 public bool InTransit {
639 /// Looks up the alias for the name
641 public IAlias LookupAlias (string name)
643 if (NamespaceEntry != null)
644 return NamespaceEntry.LookupAlias (name);
650 // root_types contains all the types. All TopLevel types
651 // hence have a parent that points to `root_types', that is
652 // why there is a non-obvious test down here.
654 public bool IsTopLevel {
657 if (Parent.Parent == null)
664 public virtual void CloseType ()
666 if ((caching_flags & Flags.CloseTypeCreated) == 0){
668 TypeBuilder.CreateType ();
671 // The try/catch is needed because
672 // nested enumerations fail to load when they
675 // Even if this is the right order (enumerations
676 // declared after types).
678 // Note that this still creates the type and
679 // it is possible to save it
681 caching_flags |= Flags.CloseTypeCreated;
686 /// Should be overriten by the appropriate declaration space
688 public abstract TypeBuilder DefineType ();
691 /// Define all members, but don't apply any attributes or do anything which may
692 /// access not-yet-defined classes. This method also creates the MemberCache.
694 public abstract bool DefineMembers (TypeContainer parent);
697 // Whether this is an `unsafe context'
699 public bool UnsafeContext {
701 if ((ModFlags & Modifiers.UNSAFE) != 0)
704 return Parent.UnsafeContext;
709 public static string MakeFQN (string nsn, string name)
713 return String.Concat (nsn, ".", name);
716 EmitContext type_resolve_ec;
717 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
719 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
720 type_resolve_ec.ResolvingTypeTree = true;
722 return type_resolve_ec;
725 public Type ResolveNestedType (Type t, Location loc)
727 TypeContainer tc = TypeManager.LookupTypeContainer (t);
728 if ((tc != null) && tc.IsGeneric) {
730 int tnum = TypeManager.GetNumberOfTypeArguments (t);
731 Report.Error (305, loc,
732 "Using the generic type `{0}' " +
733 "requires {1} type arguments",
734 TypeManager.GetFullName (t), tnum);
738 TypeParameter[] args;
739 if (this is GenericMethod)
740 args = Parent.TypeParameters;
742 args = TypeParameters;
744 TypeExpr ctype = new ConstructedType (t, args, loc);
745 ctype = ctype.ResolveAsTypeTerminal (ec);
756 // Resolves the expression `e' for a type, and will recursively define
757 // types. This should only be used for resolving base types.
759 public TypeExpr ResolveTypeExpr (Expression e, Location loc)
761 if (type_resolve_ec == null)
762 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
763 type_resolve_ec.loc = loc;
764 if (this is GenericMethod)
765 type_resolve_ec.ContainerType = Parent.TypeBuilder;
767 type_resolve_ec.ContainerType = TypeBuilder;
769 return e.ResolveAsTypeTerminal (type_resolve_ec);
772 public bool CheckAccessLevel (Type check_type)
775 if ((this is GenericMethod) || (this is Iterator))
776 tb = Parent.TypeBuilder;
780 if (check_type.IsGenericInstance)
781 check_type = check_type.GetGenericTypeDefinition ();
783 if (check_type == tb)
786 if (TypeBuilder == null)
787 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
788 // However, this is invoked again later -- so safe to return true.
789 // May also be null when resolving top-level attributes.
792 if (check_type.IsGenericParameter)
793 return true; // FIXME
795 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
798 // Broken Microsoft runtime, return public for arrays, no matter what
799 // the accessibility is for their underlying class, and they return
800 // NonPublic visibility for pointers
802 if (check_type.IsArray || check_type.IsPointer)
803 return CheckAccessLevel (TypeManager.GetElementType (check_type));
806 case TypeAttributes.Public:
809 case TypeAttributes.NotPublic:
811 if (TypeBuilder == null)
812 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
813 // However, this is invoked again later -- so safe to return true.
814 // May also be null when resolving top-level attributes.
817 // This test should probably use the declaringtype.
819 return check_type.Assembly == TypeBuilder.Assembly;
821 case TypeAttributes.NestedPublic:
824 case TypeAttributes.NestedPrivate:
825 return NestedAccessible (tb, check_type);
827 case TypeAttributes.NestedFamily:
829 // Only accessible to methods in current type or any subtypes
831 return FamilyAccessible (tb, check_type);
833 case TypeAttributes.NestedFamANDAssem:
834 return (check_type.Assembly == tb.Assembly) &&
835 FamilyAccessible (tb, check_type);
837 case TypeAttributes.NestedFamORAssem:
838 return (check_type.Assembly == tb.Assembly) ||
839 FamilyAccessible (tb, check_type);
841 case TypeAttributes.NestedAssembly:
842 return check_type.Assembly == tb.Assembly;
845 Console.WriteLine ("HERE: " + check_attr);
850 protected bool NestedAccessible (Type tb, Type check_type)
852 string check_type_name = check_type.FullName;
854 // At this point, we already know check_type is a nested class.
855 int cio = check_type_name.LastIndexOf ('+');
857 // Ensure that the string 'container' has a '+' in it to avoid false matches
858 string container = check_type_name.Substring (0, cio + 1);
860 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
861 string type_name = tb.FullName + "+";
863 // If the current class is nested inside the container of check_type,
864 // we can access check_type even if it is private or protected.
865 return type_name.StartsWith (container);
868 protected bool FamilyAccessible (Type tb, Type check_type)
870 Type declaring = check_type.DeclaringType;
871 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
874 return NestedAccessible (tb, check_type);
877 // Access level of a type.
879 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
880 // Public Assembly Protected
881 Protected = (0 << 0) | (0 << 1) | (X << 2),
882 Public = (X << 0) | (X << 1) | (X << 2),
883 Private = (0 << 0) | (0 << 1) | (0 << 2),
884 Internal = (0 << 0) | (X << 1) | (0 << 2),
885 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
888 static AccessLevel GetAccessLevelFromModifiers (int flags)
890 if ((flags & Modifiers.INTERNAL) != 0) {
892 if ((flags & Modifiers.PROTECTED) != 0)
893 return AccessLevel.ProtectedOrInternal;
895 return AccessLevel.Internal;
897 } else if ((flags & Modifiers.PROTECTED) != 0)
898 return AccessLevel.Protected;
899 else if ((flags & Modifiers.PRIVATE) != 0)
900 return AccessLevel.Private;
902 return AccessLevel.Public;
905 // What is the effective access level of this?
907 AccessLevel EffectiveAccessLevel {
909 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
910 if (!IsTopLevel && (Parent != null))
911 return myAccess & Parent.EffectiveAccessLevel;
916 // Return the access level for type `t'
917 static AccessLevel TypeEffectiveAccessLevel (Type t)
920 return AccessLevel.Public;
921 if (t.IsNestedPrivate)
922 return AccessLevel.Private;
924 return AccessLevel.Internal;
926 // By now, it must be nested
927 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
929 if (t.IsNestedPublic)
931 if (t.IsNestedAssembly)
932 return parentLevel & AccessLevel.Internal;
933 if (t.IsNestedFamily)
934 return parentLevel & AccessLevel.Protected;
935 if (t.IsNestedFamORAssem)
936 return parentLevel & AccessLevel.ProtectedOrInternal;
937 if (t.IsNestedFamANDAssem)
938 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
940 // nested private is taken care of
942 throw new Exception ("I give up, what are you?");
946 // This answers `is the type P, as accessible as a member M which has the
947 // accessability @flags which is declared as a nested member of the type T, this declspace'
949 public bool AsAccessible (Type p, int flags)
951 if (p.IsGenericParameter)
952 return true; // FIXME
955 // 1) if M is private, its accessability is the same as this declspace.
956 // we already know that P is accessible to T before this method, so we
960 if ((flags & Modifiers.PRIVATE) != 0)
963 while (p.IsArray || p.IsPointer || p.IsByRef)
964 p = TypeManager.GetElementType (p);
966 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
967 AccessLevel mAccess = this.EffectiveAccessLevel &
968 GetAccessLevelFromModifiers (flags);
970 // for every place from which we can access M, we must
971 // be able to access P as well. So, we want
972 // For every bit in M and P, M_i -> P_1 == true
973 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
975 return ~ (~ mAccess | pAccess) == 0;
978 static DoubleHash dh = new DoubleHash (1000);
980 Type DefineTypeAndParents (DeclSpace tc)
982 DeclSpace container = tc.Parent;
984 if (container.TypeBuilder == null && container.Name != "")
985 DefineTypeAndParents (container);
987 return tc.DefineType ();
990 Type LookupInterfaceOrClass (string ns, string name, out bool error)
998 if (dh.Lookup (ns, name, out r))
1002 if (Namespace.IsNamespace (ns)){
1003 string fullname = (ns != "") ? ns + "." + name : name;
1004 t = TypeManager.LookupType (fullname);
1008 t = TypeManager.LookupType (name);
1012 dh.Insert (ns, name, t);
1017 // In case we are fed a composite name, normalize it.
1019 int p = name.LastIndexOf ('.');
1021 ns = MakeFQN (ns, name.Substring (0, p));
1022 name = name.Substring (p+1);
1025 parent = RootContext.Tree.LookupByNamespace (ns, name);
1026 if (parent == null) {
1027 dh.Insert (ns, name, null);
1031 t = DefineTypeAndParents (parent);
1037 dh.Insert (ns, name, t);
1041 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1043 Report.Error (104, loc,
1044 "`{0}' is an ambiguous reference ({1} or {2})",
1048 public Type FindNestedType (Location loc, string name,
1049 out DeclSpace containing_ds)
1054 containing_ds = this;
1055 while (containing_ds != null){
1056 Type container_type = containing_ds.TypeBuilder;
1057 Type current_type = container_type;
1059 while (current_type != null && current_type != TypeManager.object_type) {
1060 string pre = current_type.FullName;
1062 t = LookupInterfaceOrClass (pre, name, out error);
1066 if ((t != null) && containing_ds.CheckAccessLevel (t))
1069 current_type = current_type.BaseType;
1071 containing_ds = containing_ds.Parent;
1078 /// GetType is used to resolve type names at the DeclSpace level.
1079 /// Use this to lookup class/struct bases, interface bases or
1080 /// delegate type references
1084 /// Contrast this to LookupType which is used inside method bodies to
1085 /// lookup types that have already been defined. GetType is used
1086 /// during the tree resolution process and potentially define
1087 /// recursively the type
1089 public Type FindType (Location loc, string name)
1095 // For the case the type we are looking for is nested within this one
1096 // or is in any base class
1098 DeclSpace containing_ds = this;
1100 while (containing_ds != null){
1101 Type container_type = containing_ds.TypeBuilder;
1102 Type current_type = container_type;
1104 while (current_type != null && current_type != TypeManager.object_type) {
1105 string pre = current_type.FullName;
1107 t = LookupInterfaceOrClass (pre, name, out error);
1111 if ((t != null) && containing_ds.CheckAccessLevel (t))
1112 return ResolveNestedType (t, loc);
1114 current_type = current_type.BaseType;
1116 containing_ds = containing_ds.Parent;
1120 // Attempt to lookup the class on our namespace and all it's implicit parents
1122 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1123 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1132 // Attempt to do a direct unqualified lookup
1134 t = LookupInterfaceOrClass ("", name, out error);
1142 // Attempt to lookup the class on any of the `using'
1146 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1148 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1155 if (name.IndexOf ('.') > 0)
1158 IAlias alias_value = ns.LookupAlias (name);
1159 if (alias_value != null) {
1160 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1169 // Now check the using clause list
1172 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1173 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1177 if (match != null) {
1179 if (CheckAccessLevel (match)) {
1180 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1193 //Report.Error (246, Location, "Can not find type `"+name+"'");
1198 /// This function is broken and not what you're looking for. It should only
1199 /// be used while the type is still being created since it doesn't use the cache
1200 /// and relies on the filter doing the member name check.
1202 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1203 MemberFilter filter, object criteria);
1206 /// If we have a MemberCache, return it. This property may return null if the
1207 /// class doesn't have a member cache or while it's still being created.
1209 public abstract MemberCache MemberCache {
1213 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1216 TypeBuilder.SetCustomAttribute (cb);
1217 } catch (System.ArgumentException e) {
1218 Report.Warning (-21, a.Location,
1219 "The CharSet named property on StructLayout\n"+
1220 "\tdoes not work correctly on Microsoft.NET\n"+
1221 "\tYou might want to remove the CharSet declaration\n"+
1222 "\tor compile using the Mono runtime instead of the\n"+
1223 "\tMicrosoft .NET runtime\n"+
1224 "\tThe runtime gave the error: " + e);
1229 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1230 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1232 public bool GetClsCompliantAttributeValue ()
1234 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1235 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1237 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1239 if (OptAttributes != null) {
1240 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1241 if (cls_attribute != null) {
1242 caching_flags |= Flags.HasClsCompliantAttribute;
1243 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1244 caching_flags |= Flags.ClsCompliantAttributeTrue;
1251 if (Parent == null) {
1252 if (CodeGen.Assembly.IsClsCompliant) {
1253 caching_flags |= Flags.ClsCompliantAttributeTrue;
1259 if (Parent.GetClsCompliantAttributeValue ()) {
1260 caching_flags |= Flags.ClsCompliantAttributeTrue;
1267 // Extensions for generics
1269 TypeParameter[] type_params;
1270 TypeParameter[] type_param_list;
1272 protected string GetInstantiationName ()
1274 StringBuilder sb = new StringBuilder (Name);
1276 for (int i = 0; i < type_param_list.Length; i++) {
1279 sb.Append (type_param_list [i].Name);
1282 return sb.ToString ();
1285 bool check_type_parameter (ArrayList list, int start, string name)
1287 for (int i = 0; i < start; i++) {
1288 TypeParameter param = (TypeParameter) list [i];
1290 if (param.Name != name)
1293 if (RootContext.WarningLevel >= 3)
1296 "Type parameter `{0}' has same name " +
1297 "as type parameter from outer type `{1}'",
1298 name, Parent.GetInstantiationName ());
1306 TypeParameter[] initialize_type_params ()
1308 if (type_param_list != null)
1309 return type_param_list;
1311 DeclSpace the_parent = Parent;
1312 if (this is GenericMethod)
1316 TypeParameter[] parent_params = null;
1317 if ((the_parent != null) && the_parent.IsGeneric) {
1318 parent_params = the_parent.initialize_type_params ();
1319 start = parent_params != null ? parent_params.Length : 0;
1322 ArrayList list = new ArrayList ();
1323 if (parent_params != null)
1324 list.AddRange (parent_params);
1326 int count = type_params != null ? type_params.Length : 0;
1327 for (int i = 0; i < count; i++) {
1328 TypeParameter param = type_params [i];
1329 check_type_parameter (list, start, param.Name);
1333 type_param_list = new TypeParameter [list.Count];
1334 list.CopyTo (type_param_list, 0);
1335 return type_param_list;
1338 public void SetParameterInfo (ArrayList constraints_list)
1341 if (constraints_list != null) {
1343 80, Location, "Contraints are not allowed " +
1344 "on non-generic declarations");
1350 string[] names = MemberName.TypeArguments.GetDeclarations ();
1351 type_params = new TypeParameter [names.Length];
1354 // Register all the names
1356 for (int i = 0; i < type_params.Length; i++) {
1357 string name = names [i];
1359 Constraints constraints = null;
1360 if (constraints_list != null) {
1361 foreach (Constraints constraint in constraints_list) {
1362 if (constraint.TypeParameter == name) {
1363 constraints = constraint;
1369 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1371 string full_name = Name + "." + name;
1372 AddToContainer (type_params [i], false, full_name, name);
1376 public TypeParameter[] TypeParameters {
1379 throw new InvalidOperationException ();
1380 if (type_param_list == null)
1381 initialize_type_params ();
1383 return type_param_list;
1387 protected TypeParameter[] CurrentTypeParameters {
1390 throw new InvalidOperationException ();
1391 if (type_params != null)
1394 return new TypeParameter [0];
1398 public int CountTypeParameters {
1400 return count_type_params;
1404 public TypeParameterExpr LookupGeneric (string name, Location loc)
1409 foreach (TypeParameter type_param in CurrentTypeParameters) {
1410 if (type_param.Name != name)
1413 return new TypeParameterExpr (type_param, loc);
1417 return Parent.LookupGeneric (name, loc);
1422 bool IAlias.IsType {
1423 get { return true; }
1426 string IAlias.Name {
1427 get { return Name; }
1430 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1432 if (TypeBuilder == null)
1433 throw new InvalidOperationException ();
1435 if (CurrentType != null)
1436 return new TypeExpression (CurrentType, Location);
1438 return new TypeExpression (TypeBuilder, Location);
1441 public override string[] ValidAttributeTargets {
1443 return attribute_targets;
1449 /// This is a readonly list of MemberInfo's.
1451 public class MemberList : IList {
1452 public readonly IList List;
1456 /// Create a new MemberList from the given IList.
1458 public MemberList (IList list)
1463 this.List = new ArrayList ();
1468 /// Concatenate the ILists `first' and `second' to a new MemberList.
1470 public MemberList (IList first, IList second)
1472 ArrayList list = new ArrayList ();
1473 list.AddRange (first);
1474 list.AddRange (second);
1479 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1482 /// Cast the MemberList into a MemberInfo[] array.
1485 /// This is an expensive operation, only use it if it's really necessary.
1487 public static explicit operator MemberInfo [] (MemberList list)
1489 Timer.StartTimer (TimerType.MiscTimer);
1490 MemberInfo [] result = new MemberInfo [list.Count];
1491 list.CopyTo (result, 0);
1492 Timer.StopTimer (TimerType.MiscTimer);
1504 public bool IsSynchronized {
1506 return List.IsSynchronized;
1510 public object SyncRoot {
1512 return List.SyncRoot;
1516 public void CopyTo (Array array, int index)
1518 List.CopyTo (array, index);
1523 public IEnumerator GetEnumerator ()
1525 return List.GetEnumerator ();
1530 public bool IsFixedSize {
1536 public bool IsReadOnly {
1542 object IList.this [int index] {
1544 return List [index];
1548 throw new NotSupportedException ();
1552 // FIXME: try to find out whether we can avoid the cast in this indexer.
1553 public MemberInfo this [int index] {
1555 return (MemberInfo) List [index];
1559 public int Add (object value)
1561 throw new NotSupportedException ();
1564 public void Clear ()
1566 throw new NotSupportedException ();
1569 public bool Contains (object value)
1571 return List.Contains (value);
1574 public int IndexOf (object value)
1576 return List.IndexOf (value);
1579 public void Insert (int index, object value)
1581 throw new NotSupportedException ();
1584 public void Remove (object value)
1586 throw new NotSupportedException ();
1589 public void RemoveAt (int index)
1591 throw new NotSupportedException ();
1596 /// This interface is used to get all members of a class when creating the
1597 /// member cache. It must be implemented by all DeclSpace derivatives which
1598 /// want to support the member cache and by TypeHandle to get caching of
1599 /// non-dynamic types.
1601 public interface IMemberContainer {
1603 /// The name of the IMemberContainer. This is only used for
1604 /// debugging purposes.
1611 /// The type of this IMemberContainer.
1618 /// Returns the IMemberContainer of the parent class or null if this
1619 /// is an interface or TypeManger.object_type.
1620 /// This is used when creating the member cache for a class to get all
1621 /// members from the parent class.
1623 MemberCache ParentCache {
1628 /// Whether this is an interface.
1635 /// Returns all members of this class with the corresponding MemberTypes
1636 /// and BindingFlags.
1639 /// When implementing this method, make sure not to return any inherited
1640 /// members and check the MemberTypes and BindingFlags properly.
1641 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1642 /// get the BindingFlags (static/non-static,public/non-public) in the
1643 /// MemberInfo class, but the cache needs this information. That's why
1644 /// this method is called multiple times with different BindingFlags.
1646 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1649 /// Return the container's member cache.
1651 MemberCache MemberCache {
1657 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1658 /// member lookups. It has a member name based hash table; it maps each member
1659 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1660 /// and the BindingFlags that were initially used to get it. The cache contains
1661 /// all members of the current class and all inherited members. If this cache is
1662 /// for an interface types, it also contains all inherited members.
1664 /// There are two ways to get a MemberCache:
1665 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1666 /// use the DeclSpace.MemberCache property.
1667 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1668 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1670 public class MemberCache {
1671 public readonly IMemberContainer Container;
1672 protected Hashtable member_hash;
1673 protected Hashtable method_hash;
1676 /// Create a new MemberCache for the given IMemberContainer `container'.
1678 public MemberCache (IMemberContainer container)
1680 this.Container = container;
1682 Timer.IncrementCounter (CounterType.MemberCache);
1683 Timer.StartTimer (TimerType.CacheInit);
1685 // If we have a parent class (we have a parent class unless we're
1686 // TypeManager.object_type), we deep-copy its MemberCache here.
1687 if (Container.ParentCache != null)
1688 member_hash = SetupCache (Container.ParentCache);
1690 member_hash = new Hashtable ();
1692 // If this is neither a dynamic type nor an interface, create a special
1693 // method cache with all declared and inherited methods.
1694 Type type = container.Type;
1695 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1696 method_hash = new Hashtable ();
1700 // Add all members from the current class.
1701 AddMembers (Container);
1703 Timer.StopTimer (TimerType.CacheInit);
1706 public MemberCache (Type[] ifaces)
1709 // The members of this cache all belong to other caches.
1710 // So, 'Container' will not be used.
1712 this.Container = null;
1714 member_hash = new Hashtable ();
1718 foreach (Type itype in ifaces)
1719 AddCacheContents (TypeManager.LookupMemberCache (itype));
1723 /// Bootstrap this member cache by doing a deep-copy of our parent.
1725 Hashtable SetupCache (MemberCache parent)
1727 Hashtable hash = new Hashtable ();
1732 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1733 while (it.MoveNext ()) {
1734 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1741 /// Add the contents of `cache' to the member_hash.
1743 void AddCacheContents (MemberCache cache)
1745 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1746 while (it.MoveNext ()) {
1747 ArrayList list = (ArrayList) member_hash [it.Key];
1749 member_hash [it.Key] = list = new ArrayList ();
1751 ArrayList entries = (ArrayList) it.Value;
1752 for (int i = entries.Count-1; i >= 0; i--) {
1753 CacheEntry entry = (CacheEntry) entries [i];
1755 if (entry.Container != cache.Container)
1763 /// Add all members from class `container' to the cache.
1765 void AddMembers (IMemberContainer container)
1767 // We need to call AddMembers() with a single member type at a time
1768 // to get the member type part of CacheEntry.EntryType right.
1769 if (!container.IsInterface) {
1770 AddMembers (MemberTypes.Constructor, container);
1771 AddMembers (MemberTypes.Field, container);
1773 AddMembers (MemberTypes.Method, container);
1774 AddMembers (MemberTypes.Property, container);
1775 AddMembers (MemberTypes.Event, container);
1776 // Nested types are returned by both Static and Instance searches.
1777 AddMembers (MemberTypes.NestedType,
1778 BindingFlags.Static | BindingFlags.Public, container);
1779 AddMembers (MemberTypes.NestedType,
1780 BindingFlags.Static | BindingFlags.NonPublic, container);
1783 void AddMembers (MemberTypes mt, IMemberContainer container)
1785 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1786 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1787 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1788 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1792 /// Add all members from class `container' with the requested MemberTypes and
1793 /// BindingFlags to the cache. This method is called multiple times with different
1794 /// MemberTypes and BindingFlags.
1796 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1798 MemberList members = container.GetMembers (mt, bf);
1800 foreach (MemberInfo member in members) {
1801 string name = member.Name;
1803 int pos = name.IndexOf ('<');
1805 name = name.Substring (0, pos);
1807 // We use a name-based hash table of ArrayList's.
1808 ArrayList list = (ArrayList) member_hash [name];
1810 list = new ArrayList ();
1811 member_hash.Add (name, list);
1814 // When this method is called for the current class, the list will
1815 // already contain all inherited members from our parent classes.
1816 // We cannot add new members in front of the list since this'd be an
1817 // expensive operation, that's why the list is sorted in reverse order
1818 // (ie. members from the current class are coming last).
1819 list.Add (new CacheEntry (container, member, mt, bf));
1824 /// Add all declared and inherited methods from class `type' to the method cache.
1826 void AddMethods (Type type)
1828 AddMethods (BindingFlags.Static | BindingFlags.Public |
1829 BindingFlags.FlattenHierarchy, type);
1830 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1831 BindingFlags.FlattenHierarchy, type);
1832 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1833 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1836 void AddMethods (BindingFlags bf, Type type)
1838 MemberInfo [] members = type.GetMethods (bf);
1840 Array.Reverse (members);
1842 foreach (MethodBase member in members) {
1843 string name = member.Name;
1845 // We use a name-based hash table of ArrayList's.
1846 ArrayList list = (ArrayList) method_hash [name];
1848 list = new ArrayList ();
1849 method_hash.Add (name, list);
1852 // Unfortunately, the elements returned by Type.GetMethods() aren't
1853 // sorted so we need to do this check for every member.
1854 BindingFlags new_bf = bf;
1855 if (member.DeclaringType == type)
1856 new_bf |= BindingFlags.DeclaredOnly;
1858 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1863 /// Compute and return a appropriate `EntryType' magic number for the given
1864 /// MemberTypes and BindingFlags.
1866 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1868 EntryType type = EntryType.None;
1870 if ((mt & MemberTypes.Constructor) != 0)
1871 type |= EntryType.Constructor;
1872 if ((mt & MemberTypes.Event) != 0)
1873 type |= EntryType.Event;
1874 if ((mt & MemberTypes.Field) != 0)
1875 type |= EntryType.Field;
1876 if ((mt & MemberTypes.Method) != 0)
1877 type |= EntryType.Method;
1878 if ((mt & MemberTypes.Property) != 0)
1879 type |= EntryType.Property;
1880 // Nested types are returned by static and instance searches.
1881 if ((mt & MemberTypes.NestedType) != 0)
1882 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1884 if ((bf & BindingFlags.Instance) != 0)
1885 type |= EntryType.Instance;
1886 if ((bf & BindingFlags.Static) != 0)
1887 type |= EntryType.Static;
1888 if ((bf & BindingFlags.Public) != 0)
1889 type |= EntryType.Public;
1890 if ((bf & BindingFlags.NonPublic) != 0)
1891 type |= EntryType.NonPublic;
1892 if ((bf & BindingFlags.DeclaredOnly) != 0)
1893 type |= EntryType.Declared;
1899 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1900 /// denote multiple member types. Returns true if the given flags value denotes a
1901 /// single member types.
1903 public static bool IsSingleMemberType (MemberTypes mt)
1906 case MemberTypes.Constructor:
1907 case MemberTypes.Event:
1908 case MemberTypes.Field:
1909 case MemberTypes.Method:
1910 case MemberTypes.Property:
1911 case MemberTypes.NestedType:
1920 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1921 /// number to speed up the searching process.
1924 protected enum EntryType {
1929 MaskStatic = Instance|Static,
1933 MaskProtection = Public|NonPublic,
1937 Constructor = 0x020,
1944 MaskType = Constructor|Event|Field|Method|Property|NestedType
1947 protected struct CacheEntry {
1948 public readonly IMemberContainer Container;
1949 public readonly EntryType EntryType;
1950 public readonly MemberInfo Member;
1952 public CacheEntry (IMemberContainer container, MemberInfo member,
1953 MemberTypes mt, BindingFlags bf)
1955 this.Container = container;
1956 this.Member = member;
1957 this.EntryType = GetEntryType (mt, bf);
1960 public override string ToString ()
1962 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1968 /// This is called each time we're walking up one level in the class hierarchy
1969 /// and checks whether we can abort the search since we've already found what
1970 /// we were looking for.
1972 protected bool DoneSearching (ArrayList list)
1975 // We've found exactly one member in the current class and it's not
1976 // a method or constructor.
1978 if (list.Count == 1 && !(list [0] is MethodBase))
1982 // Multiple properties: we query those just to find out the indexer
1985 if ((list.Count > 0) && (list [0] is PropertyInfo))
1992 /// Looks up members with name `name'. If you provide an optional
1993 /// filter function, it'll only be called with members matching the
1994 /// requested member name.
1996 /// This method will try to use the cache to do the lookup if possible.
1998 /// Unlike other FindMembers implementations, this method will always
1999 /// check all inherited members - even when called on an interface type.
2001 /// If you know that you're only looking for methods, you should use
2002 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2003 /// When doing a method-only search, it'll try to use a special method
2004 /// cache (unless it's a dynamic type or an interface) and the returned
2005 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2006 /// The lookup process will automatically restart itself in method-only
2007 /// search mode if it discovers that it's about to return methods.
2009 ArrayList global = new ArrayList ();
2010 bool using_global = false;
2012 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2014 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2015 MemberFilter filter, object criteria)
2018 throw new Exception ();
2020 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2021 bool method_search = mt == MemberTypes.Method;
2022 // If we have a method cache and we aren't already doing a method-only search,
2023 // then we restart a method search if the first match is a method.
2024 bool do_method_search = !method_search && (method_hash != null);
2026 ArrayList applicable;
2028 // If this is a method-only search, we try to use the method cache if
2029 // possible; a lookup in the method cache will return a MemberInfo with
2030 // the correct ReflectedType for inherited methods.
2032 if (method_search && (method_hash != null))
2033 applicable = (ArrayList) method_hash [name];
2035 applicable = (ArrayList) member_hash [name];
2037 if (applicable == null)
2038 return emptyMemberInfo;
2041 // 32 slots gives 53 rss/54 size
2042 // 2/4 slots gives 55 rss
2044 // Strange: from 25,000 calls, only 1,800
2045 // are above 2. Why does this impact it?
2048 using_global = true;
2050 Timer.StartTimer (TimerType.CachedLookup);
2052 EntryType type = GetEntryType (mt, bf);
2054 IMemberContainer current = Container;
2057 // `applicable' is a list of all members with the given member name `name'
2058 // in the current class and all its parent classes. The list is sorted in
2059 // reverse order due to the way how the cache is initialy created (to speed
2060 // things up, we're doing a deep-copy of our parent).
2062 for (int i = applicable.Count-1; i >= 0; i--) {
2063 CacheEntry entry = (CacheEntry) applicable [i];
2065 // This happens each time we're walking one level up in the class
2066 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2067 // the first time this happens (this may already happen in the first
2068 // iteration of this loop if there are no members with the name we're
2069 // looking for in the current class).
2070 if (entry.Container != current) {
2071 if (declared_only || DoneSearching (global))
2074 current = entry.Container;
2077 // Is the member of the correct type ?
2078 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2081 // Is the member static/non-static ?
2082 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2085 // Apply the filter to it.
2086 if (filter (entry.Member, criteria)) {
2087 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2088 do_method_search = false;
2089 global.Add (entry.Member);
2093 Timer.StopTimer (TimerType.CachedLookup);
2095 // If we have a method cache and we aren't already doing a method-only
2096 // search, we restart in method-only search mode if the first match is
2097 // a method. This ensures that we return a MemberInfo with the correct
2098 // ReflectedType for inherited methods.
2099 if (do_method_search && (global.Count > 0)){
2100 using_global = false;
2102 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2105 using_global = false;
2106 MemberInfo [] copy = new MemberInfo [global.Count];
2107 global.CopyTo (copy);
2112 // This finds the method or property for us to override. invocationType is the type where
2113 // the override is going to be declared, name is the name of the method/property, and
2114 // paramTypes is the parameters, if any to the method or property
2116 // Because the MemberCache holds members from this class and all the base classes,
2117 // we can avoid tons of reflection stuff.
2119 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2121 ArrayList applicable;
2122 if (method_hash != null && !is_property)
2123 applicable = (ArrayList) method_hash [name];
2125 applicable = (ArrayList) member_hash [name];
2127 if (applicable == null)
2130 // Walk the chain of methods, starting from the top.
2132 for (int i = applicable.Count - 1; i >= 0; i--) {
2133 CacheEntry entry = (CacheEntry) applicable [i];
2135 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2138 PropertyInfo pi = null;
2139 MethodInfo mi = null;
2140 FieldInfo fi = null;
2141 Type [] cmpAttrs = null;
2144 if ((entry.EntryType & EntryType.Field) != 0) {
2145 fi = (FieldInfo)entry.Member;
2147 // TODO: For this case we ignore member type
2148 //fb = TypeManager.GetField (fi);
2149 //cmpAttrs = new Type[] { fb.MemberType };
2151 pi = (PropertyInfo) entry.Member;
2152 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2155 mi = (MethodInfo) entry.Member;
2156 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2160 // TODO: Almost duplicate !
2162 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2163 case FieldAttributes.Private:
2165 // A private method is Ok if we are a nested subtype.
2166 // The spec actually is not very clear about this, see bug 52458.
2168 if (invocationType != entry.Container.Type &
2169 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2173 case FieldAttributes.FamANDAssem:
2174 case FieldAttributes.Assembly:
2176 // Check for assembly methods
2178 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2182 return entry.Member;
2186 // Check the arguments
2188 if (cmpAttrs.Length != paramTypes.Length)
2191 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2192 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2197 // get one of the methods because this has the visibility info.
2200 mi = pi.GetGetMethod (true);
2202 mi = pi.GetSetMethod (true);
2208 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2209 case MethodAttributes.Private:
2211 // A private method is Ok if we are a nested subtype.
2212 // The spec actually is not very clear about this, see bug 52458.
2214 if (invocationType.Equals (entry.Container.Type) ||
2215 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2216 return entry.Member;
2219 case MethodAttributes.FamANDAssem:
2220 case MethodAttributes.Assembly:
2222 // Check for assembly methods
2224 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2225 return entry.Member;
2230 // A protected method is ok, because we are overriding.
2231 // public is always ok.
2233 return entry.Member;
2243 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2244 /// We handle two cases. The first is for types without parameters (events, field, properties).
2245 /// The second are methods, indexers and this is why ignore_complex_types is here.
2246 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2248 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2250 ArrayList applicable = null;
2252 if (method_hash != null)
2253 applicable = (ArrayList) method_hash [name];
2255 if (applicable != null) {
2256 for (int i = applicable.Count - 1; i >= 0; i--) {
2257 CacheEntry entry = (CacheEntry) applicable [i];
2258 if ((entry.EntryType & EntryType.Public) != 0)
2259 return entry.Member;
2263 if (member_hash == null)
2265 applicable = (ArrayList) member_hash [name];
2267 if (applicable != null) {
2268 for (int i = applicable.Count - 1; i >= 0; i--) {
2269 CacheEntry entry = (CacheEntry) applicable [i];
2270 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2271 if (ignore_complex_types) {
2272 if ((entry.EntryType & EntryType.Method) != 0)
2275 // Does exist easier way how to detect indexer ?
2276 if ((entry.EntryType & EntryType.Property) != 0) {
2277 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2278 if (arg_types.Length > 0)
2282 return entry.Member;
2289 Hashtable locase_table;
2292 /// Builds low-case table for CLS Compliance test
2294 public Hashtable GetPublicMembers ()
2296 if (locase_table != null)
2297 return locase_table;
2299 locase_table = new Hashtable ();
2300 foreach (DictionaryEntry entry in member_hash) {
2301 ArrayList members = (ArrayList)entry.Value;
2302 for (int ii = 0; ii < members.Count; ++ii) {
2303 CacheEntry member_entry = (CacheEntry) members [ii];
2305 if ((member_entry.EntryType & EntryType.Public) == 0)
2308 // TODO: Does anyone know easier way how to detect that member is internal ?
2309 switch (member_entry.EntryType & EntryType.MaskType) {
2310 case EntryType.Constructor:
2313 case EntryType.Field:
2314 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2318 case EntryType.Method:
2319 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2323 case EntryType.Property:
2324 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2325 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2329 case EntryType.Event:
2330 EventInfo ei = (EventInfo)member_entry.Member;
2331 MethodInfo mi = ei.GetAddMethod ();
2332 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2336 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2337 locase_table [lcase] = member_entry.Member;
2341 return locase_table;
2344 public Hashtable Members {
2351 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2353 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2355 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2357 for (int i = 0; i < al.Count; ++i) {
2358 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2361 if (entry.Member == this_builder)
2364 if ((entry.EntryType & tested_type) != tested_type)
2367 MethodBase method_to_compare = (MethodBase)entry.Member;
2368 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2371 IMethodData md = TypeManager.GetMethod (method_to_compare);
2373 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2374 // However it is exactly what csc does.
2375 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2378 Report.SymbolRelatedToPreviousError (entry.Member);
2379 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());