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.EmitContext);
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.EmitContext);
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 (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
439 if (!IsExposedFromAssembly (ds))
440 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
441 if (!CodeGen.Assembly.IsClsCompliant)
442 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
447 if (!CodeGen.Assembly.IsClsCompliant) {
448 if (HasClsCompliantAttribute) {
449 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
454 int index = Name.LastIndexOf ('.');
455 if (Name [index > 0 ? index + 1 : 0] == '_') {
456 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
461 protected abstract void VerifyObsoleteAttribute ();
464 // Raised (and passed an XmlElement that contains the comment)
465 // when GenerateDocComment is writing documentation expectedly.
467 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
472 // Returns a string that represents the signature for this
473 // member which should be used in XML documentation.
475 public virtual string GetDocCommentName (DeclSpace ds)
477 if (ds == null || this is DeclSpace)
478 return DocCommentHeader + Name;
480 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
484 // Generates xml doc comments (if any), and if required,
485 // handle warning report.
487 internal virtual void GenerateDocComment (DeclSpace ds)
489 DocUtil.GenerateDocComment (this, ds);
494 /// Base class for structs, classes, enumerations and interfaces.
497 /// They all create new declaration spaces. This
498 /// provides the common foundation for managing those name
501 public abstract class DeclSpace : MemberCore, IAlias {
503 /// This points to the actual definition that is being
504 /// created with System.Reflection.Emit
506 public TypeBuilder TypeBuilder;
509 /// If we are a generic type, this is the type we are
510 /// currently defining. We need to lookup members on this
511 /// instead of the TypeBuilder.
513 public Type CurrentType;
516 // This is the namespace in which this typecontainer
517 // was declared. We use this to resolve names.
519 public NamespaceEntry NamespaceEntry;
521 public Hashtable Cache = new Hashtable ();
523 public string Basename;
525 protected Hashtable defined_names;
527 readonly bool is_generic;
528 readonly int count_type_params;
530 // The emit context for toplevel objects.
531 protected EmitContext ec;
533 public EmitContext EmitContext {
538 // Whether we are Generic
540 public bool IsGeneric {
544 else if (Parent != null)
545 return Parent.IsGeneric;
551 static string[] attribute_targets = new string [] { "type" };
553 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
554 Attributes attrs, Location l)
555 : base (parent, name, attrs, l)
558 Basename = name.Name;
559 defined_names = new Hashtable ();
560 if (name.TypeArguments != null) {
562 count_type_params = name.TypeArguments.Count;
565 count_type_params += parent.count_type_params;
569 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
571 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
573 if (basename == Basename && !(this is Interface)) {
574 if (symbol is TypeParameter)
575 Report.Error (694, "Type parameter `{0}' has same name as " +
576 "containing type or method", basename);
578 Report.SymbolRelatedToPreviousError (this);
579 Report.Error (542, "'{0}': member names cannot be the same as their " +
580 "enclosing type", symbol.Location, symbol.GetSignatureForError ());
585 MemberCore mc = (MemberCore)defined_names [fullname];
587 if (is_method && (mc is MethodCore || mc is IMethodData)) {
588 symbol.caching_flags |= Flags.TestMethodDuplication;
589 mc.caching_flags |= Flags.TestMethodDuplication;
594 if (symbol is TypeParameter)
595 Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", basename);
597 Report.SymbolRelatedToPreviousError (mc);
598 Report.Error (102, symbol.Location,
599 "The type '{0}' already contains a definition for '{1}'",
600 GetSignatureForError (), basename);
605 defined_names.Add (fullname, symbol);
609 public void RecordDecl ()
611 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
612 NamespaceEntry.DefineName (MemberName.Basename, this);
616 /// Returns the MemberCore associated with a given name in the declaration
617 /// space. It doesn't return method based symbols !!
620 public MemberCore GetDefinition (string name)
622 return (MemberCore)defined_names [name];
625 bool in_transit = false;
628 /// This function is used to catch recursive definitions
631 public bool InTransit {
642 /// Looks up the alias for the name
644 public IAlias LookupAlias (string name)
646 if (NamespaceEntry != null)
647 return NamespaceEntry.LookupAlias (name);
653 // root_types contains all the types. All TopLevel types
654 // hence have a parent that points to `root_types', that is
655 // why there is a non-obvious test down here.
657 public bool IsTopLevel {
660 if (Parent.Parent == null)
667 public virtual void CloseType ()
669 if ((caching_flags & Flags.CloseTypeCreated) == 0){
671 TypeBuilder.CreateType ();
674 // The try/catch is needed because
675 // nested enumerations fail to load when they
678 // Even if this is the right order (enumerations
679 // declared after types).
681 // Note that this still creates the type and
682 // it is possible to save it
684 caching_flags |= Flags.CloseTypeCreated;
689 /// Should be overriten by the appropriate declaration space
691 public abstract TypeBuilder DefineType ();
694 /// Define all members, but don't apply any attributes or do anything which may
695 /// access not-yet-defined classes. This method also creates the MemberCache.
697 public abstract bool DefineMembers (TypeContainer parent);
700 // Whether this is an `unsafe context'
702 public bool UnsafeContext {
704 if ((ModFlags & Modifiers.UNSAFE) != 0)
707 return Parent.UnsafeContext;
712 public static string MakeFQN (string nsn, string name)
716 return String.Concat (nsn, ".", name);
719 EmitContext type_resolve_ec;
720 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
722 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
723 type_resolve_ec.ResolvingTypeTree = true;
725 return type_resolve_ec;
728 public Type ResolveNestedType (Type t, Location loc)
730 TypeContainer tc = TypeManager.LookupTypeContainer (t);
731 if ((tc != null) && tc.IsGeneric) {
733 int tnum = TypeManager.GetNumberOfTypeArguments (t);
734 Report.Error (305, loc,
735 "Using the generic type `{0}' " +
736 "requires {1} type arguments",
737 TypeManager.GetFullName (t), tnum);
741 TypeParameter[] args;
742 if (this is GenericMethod)
743 args = Parent.TypeParameters;
745 args = TypeParameters;
747 TypeExpr ctype = new ConstructedType (t, args, loc);
748 ctype = ctype.ResolveAsTypeTerminal (ec);
759 // Resolves the expression `e' for a type, and will recursively define
760 // types. This should only be used for resolving base types.
762 public TypeExpr ResolveTypeExpr (Expression e, Location loc)
764 if (type_resolve_ec == null)
765 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
766 type_resolve_ec.loc = loc;
767 if (this is GenericMethod)
768 type_resolve_ec.ContainerType = Parent.TypeBuilder;
770 type_resolve_ec.ContainerType = TypeBuilder;
772 return e.ResolveAsTypeTerminal (type_resolve_ec);
775 public bool CheckAccessLevel (Type check_type)
778 if ((this is GenericMethod) || (this is Iterator))
779 tb = Parent.TypeBuilder;
783 if (check_type.IsGenericInstance)
784 check_type = check_type.GetGenericTypeDefinition ();
786 if (check_type == tb)
789 if (TypeBuilder == null)
790 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
791 // However, this is invoked again later -- so safe to return true.
792 // May also be null when resolving top-level attributes.
795 if (check_type.IsGenericParameter)
796 return true; // FIXME
798 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
801 // Broken Microsoft runtime, return public for arrays, no matter what
802 // the accessibility is for their underlying class, and they return
803 // NonPublic visibility for pointers
805 if (check_type.IsArray || check_type.IsPointer)
806 return CheckAccessLevel (TypeManager.GetElementType (check_type));
809 case TypeAttributes.Public:
812 case TypeAttributes.NotPublic:
814 if (TypeBuilder == null)
815 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
816 // However, this is invoked again later -- so safe to return true.
817 // May also be null when resolving top-level attributes.
820 // This test should probably use the declaringtype.
822 return check_type.Assembly == TypeBuilder.Assembly;
824 case TypeAttributes.NestedPublic:
827 case TypeAttributes.NestedPrivate:
828 return NestedAccessible (tb, check_type);
830 case TypeAttributes.NestedFamily:
832 // Only accessible to methods in current type or any subtypes
834 return FamilyAccessible (tb, check_type);
836 case TypeAttributes.NestedFamANDAssem:
837 return (check_type.Assembly == tb.Assembly) &&
838 FamilyAccessible (tb, check_type);
840 case TypeAttributes.NestedFamORAssem:
841 return (check_type.Assembly == tb.Assembly) ||
842 FamilyAccessible (tb, check_type);
844 case TypeAttributes.NestedAssembly:
845 return check_type.Assembly == tb.Assembly;
848 Console.WriteLine ("HERE: " + check_attr);
853 protected bool NestedAccessible (Type tb, Type check_type)
855 string check_type_name = check_type.FullName;
857 // At this point, we already know check_type is a nested class.
858 int cio = check_type_name.LastIndexOf ('+');
860 // Ensure that the string 'container' has a '+' in it to avoid false matches
861 string container = check_type_name.Substring (0, cio + 1);
863 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
864 string type_name = tb.FullName + "+";
866 // If the current class is nested inside the container of check_type,
867 // we can access check_type even if it is private or protected.
868 return type_name.StartsWith (container);
871 protected bool FamilyAccessible (Type tb, Type check_type)
873 Type declaring = check_type.DeclaringType;
874 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
877 return NestedAccessible (tb, check_type);
880 // Access level of a type.
882 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
883 // Public Assembly Protected
884 Protected = (0 << 0) | (0 << 1) | (X << 2),
885 Public = (X << 0) | (X << 1) | (X << 2),
886 Private = (0 << 0) | (0 << 1) | (0 << 2),
887 Internal = (0 << 0) | (X << 1) | (0 << 2),
888 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
891 static AccessLevel GetAccessLevelFromModifiers (int flags)
893 if ((flags & Modifiers.INTERNAL) != 0) {
895 if ((flags & Modifiers.PROTECTED) != 0)
896 return AccessLevel.ProtectedOrInternal;
898 return AccessLevel.Internal;
900 } else if ((flags & Modifiers.PROTECTED) != 0)
901 return AccessLevel.Protected;
902 else if ((flags & Modifiers.PRIVATE) != 0)
903 return AccessLevel.Private;
905 return AccessLevel.Public;
908 // What is the effective access level of this?
910 AccessLevel EffectiveAccessLevel {
912 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
913 if (!IsTopLevel && (Parent != null))
914 return myAccess & Parent.EffectiveAccessLevel;
919 // Return the access level for type `t'
920 static AccessLevel TypeEffectiveAccessLevel (Type t)
923 return AccessLevel.Public;
924 if (t.IsNestedPrivate)
925 return AccessLevel.Private;
927 return AccessLevel.Internal;
929 // By now, it must be nested
930 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
932 if (t.IsNestedPublic)
934 if (t.IsNestedAssembly)
935 return parentLevel & AccessLevel.Internal;
936 if (t.IsNestedFamily)
937 return parentLevel & AccessLevel.Protected;
938 if (t.IsNestedFamORAssem)
939 return parentLevel & AccessLevel.ProtectedOrInternal;
940 if (t.IsNestedFamANDAssem)
941 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
943 // nested private is taken care of
945 throw new Exception ("I give up, what are you?");
949 // This answers `is the type P, as accessible as a member M which has the
950 // accessability @flags which is declared as a nested member of the type T, this declspace'
952 public bool AsAccessible (Type p, int flags)
954 if (p.IsGenericParameter)
955 return true; // FIXME
958 // 1) if M is private, its accessability is the same as this declspace.
959 // we already know that P is accessible to T before this method, so we
963 if ((flags & Modifiers.PRIVATE) != 0)
966 while (p.IsArray || p.IsPointer || p.IsByRef)
967 p = TypeManager.GetElementType (p);
969 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
970 AccessLevel mAccess = this.EffectiveAccessLevel &
971 GetAccessLevelFromModifiers (flags);
973 // for every place from which we can access M, we must
974 // be able to access P as well. So, we want
975 // For every bit in M and P, M_i -> P_1 == true
976 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
978 return ~ (~ mAccess | pAccess) == 0;
981 static DoubleHash dh = new DoubleHash (1000);
983 Type DefineTypeAndParents (DeclSpace tc)
985 DeclSpace container = tc.Parent;
987 if (container.TypeBuilder == null && container.Name != "")
988 DefineTypeAndParents (container);
990 return tc.DefineType ();
993 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1001 if (dh.Lookup (ns, name, out r))
1005 if (Namespace.IsNamespace (ns)){
1006 string fullname = (ns != "") ? ns + "." + name : name;
1007 t = TypeManager.LookupType (fullname);
1011 t = TypeManager.LookupType (name);
1015 dh.Insert (ns, name, t);
1020 // In case we are fed a composite name, normalize it.
1022 int p = name.LastIndexOf ('.');
1024 ns = MakeFQN (ns, name.Substring (0, p));
1025 name = name.Substring (p+1);
1028 parent = RootContext.Tree.LookupByNamespace (ns, name);
1029 if (parent == null) {
1030 dh.Insert (ns, name, null);
1034 t = DefineTypeAndParents (parent);
1040 dh.Insert (ns, name, t);
1044 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1046 Report.Error (104, loc,
1047 "`{0}' is an ambiguous reference ({1} or {2})",
1051 public Type FindNestedType (Location loc, string name,
1052 out DeclSpace containing_ds)
1057 containing_ds = this;
1058 while (containing_ds != null){
1059 Type container_type = containing_ds.TypeBuilder;
1060 Type current_type = container_type;
1062 while (current_type != null && current_type != TypeManager.object_type) {
1063 string pre = current_type.FullName;
1065 t = LookupInterfaceOrClass (pre, name, out error);
1069 if ((t != null) && containing_ds.CheckAccessLevel (t))
1072 current_type = current_type.BaseType;
1074 containing_ds = containing_ds.Parent;
1081 /// GetType is used to resolve type names at the DeclSpace level.
1082 /// Use this to lookup class/struct bases, interface bases or
1083 /// delegate type references
1087 /// Contrast this to LookupType which is used inside method bodies to
1088 /// lookup types that have already been defined. GetType is used
1089 /// during the tree resolution process and potentially define
1090 /// recursively the type
1092 public Type FindType (Location loc, string name)
1098 // For the case the type we are looking for is nested within this one
1099 // or is in any base class
1101 DeclSpace containing_ds = this;
1103 while (containing_ds != null){
1104 Type container_type = containing_ds.TypeBuilder;
1105 Type current_type = container_type;
1107 while (current_type != null && current_type != TypeManager.object_type) {
1108 string pre = current_type.FullName;
1110 t = LookupInterfaceOrClass (pre, name, out error);
1114 if ((t != null) && containing_ds.CheckAccessLevel (t))
1115 return ResolveNestedType (t, loc);
1117 current_type = current_type.BaseType;
1119 containing_ds = containing_ds.Parent;
1123 // Attempt to lookup the class on our namespace and all it's implicit parents
1125 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1126 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1135 // Attempt to do a direct unqualified lookup
1137 t = LookupInterfaceOrClass ("", name, out error);
1145 // Attempt to lookup the class on any of the `using'
1149 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1151 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1158 if (name.IndexOf ('.') > 0)
1161 IAlias alias_value = ns.LookupAlias (name);
1162 if (alias_value != null) {
1163 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1172 // Now check the using clause list
1175 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1176 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1180 if (match != null) {
1182 if (CheckAccessLevel (match)) {
1183 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1196 //Report.Error (246, Location, "Can not find type `"+name+"'");
1201 /// This function is broken and not what you're looking for. It should only
1202 /// be used while the type is still being created since it doesn't use the cache
1203 /// and relies on the filter doing the member name check.
1205 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1206 MemberFilter filter, object criteria);
1209 /// If we have a MemberCache, return it. This property may return null if the
1210 /// class doesn't have a member cache or while it's still being created.
1212 public abstract MemberCache MemberCache {
1216 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1219 TypeBuilder.SetCustomAttribute (cb);
1220 } catch (System.ArgumentException e) {
1221 Report.Warning (-21, a.Location,
1222 "The CharSet named property on StructLayout\n"+
1223 "\tdoes not work correctly on Microsoft.NET\n"+
1224 "\tYou might want to remove the CharSet declaration\n"+
1225 "\tor compile using the Mono runtime instead of the\n"+
1226 "\tMicrosoft .NET runtime\n"+
1227 "\tThe runtime gave the error: " + e);
1232 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1233 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1235 public bool GetClsCompliantAttributeValue ()
1237 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1238 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1240 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1242 if (OptAttributes != null) {
1243 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1244 if (cls_attribute != null) {
1245 caching_flags |= Flags.HasClsCompliantAttribute;
1246 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1247 caching_flags |= Flags.ClsCompliantAttributeTrue;
1254 if (Parent == null) {
1255 if (CodeGen.Assembly.IsClsCompliant) {
1256 caching_flags |= Flags.ClsCompliantAttributeTrue;
1262 if (Parent.GetClsCompliantAttributeValue ()) {
1263 caching_flags |= Flags.ClsCompliantAttributeTrue;
1270 // Extensions for generics
1272 TypeParameter[] type_params;
1273 TypeParameter[] type_param_list;
1275 protected string GetInstantiationName ()
1277 StringBuilder sb = new StringBuilder (Name);
1279 for (int i = 0; i < type_param_list.Length; i++) {
1282 sb.Append (type_param_list [i].Name);
1285 return sb.ToString ();
1288 bool check_type_parameter (ArrayList list, int start, string name)
1290 for (int i = 0; i < start; i++) {
1291 TypeParameter param = (TypeParameter) list [i];
1293 if (param.Name != name)
1296 if (RootContext.WarningLevel >= 3)
1299 "Type parameter `{0}' has same name " +
1300 "as type parameter from outer type `{1}'",
1301 name, Parent.GetInstantiationName ());
1309 TypeParameter[] initialize_type_params ()
1311 if (type_param_list != null)
1312 return type_param_list;
1314 DeclSpace the_parent = Parent;
1315 if (this is GenericMethod)
1319 TypeParameter[] parent_params = null;
1320 if ((the_parent != null) && the_parent.IsGeneric) {
1321 parent_params = the_parent.initialize_type_params ();
1322 start = parent_params != null ? parent_params.Length : 0;
1325 ArrayList list = new ArrayList ();
1326 if (parent_params != null)
1327 list.AddRange (parent_params);
1329 int count = type_params != null ? type_params.Length : 0;
1330 for (int i = 0; i < count; i++) {
1331 TypeParameter param = type_params [i];
1332 check_type_parameter (list, start, param.Name);
1336 type_param_list = new TypeParameter [list.Count];
1337 list.CopyTo (type_param_list, 0);
1338 return type_param_list;
1341 public void SetParameterInfo (ArrayList constraints_list)
1344 if (constraints_list != null) {
1346 80, Location, "Contraints are not allowed " +
1347 "on non-generic declarations");
1353 string[] names = MemberName.TypeArguments.GetDeclarations ();
1354 type_params = new TypeParameter [names.Length];
1357 // Register all the names
1359 for (int i = 0; i < type_params.Length; i++) {
1360 string name = names [i];
1362 Constraints constraints = null;
1363 if (constraints_list != null) {
1364 foreach (Constraints constraint in constraints_list) {
1365 if (constraint.TypeParameter == name) {
1366 constraints = constraint;
1372 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1374 string full_name = Name + "." + name;
1375 AddToContainer (type_params [i], false, full_name, name);
1379 public TypeParameter[] TypeParameters {
1382 throw new InvalidOperationException ();
1383 if (type_param_list == null)
1384 initialize_type_params ();
1386 return type_param_list;
1390 protected TypeParameter[] CurrentTypeParameters {
1393 throw new InvalidOperationException ();
1394 if (type_params != null)
1397 return new TypeParameter [0];
1401 public int CountTypeParameters {
1403 return count_type_params;
1407 public TypeParameterExpr LookupGeneric (string name, Location loc)
1412 foreach (TypeParameter type_param in CurrentTypeParameters) {
1413 if (type_param.Name != name)
1416 return new TypeParameterExpr (type_param, loc);
1420 return Parent.LookupGeneric (name, loc);
1425 bool IAlias.IsType {
1426 get { return true; }
1429 string IAlias.Name {
1430 get { return Name; }
1433 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1435 if (TypeBuilder == null)
1436 throw new InvalidOperationException ();
1438 if (CurrentType != null)
1439 return new TypeExpression (CurrentType, Location);
1441 return new TypeExpression (TypeBuilder, Location);
1444 public override string[] ValidAttributeTargets {
1446 return attribute_targets;
1452 /// This is a readonly list of MemberInfo's.
1454 public class MemberList : IList {
1455 public readonly IList List;
1459 /// Create a new MemberList from the given IList.
1461 public MemberList (IList list)
1466 this.List = new ArrayList ();
1471 /// Concatenate the ILists `first' and `second' to a new MemberList.
1473 public MemberList (IList first, IList second)
1475 ArrayList list = new ArrayList ();
1476 list.AddRange (first);
1477 list.AddRange (second);
1482 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1485 /// Cast the MemberList into a MemberInfo[] array.
1488 /// This is an expensive operation, only use it if it's really necessary.
1490 public static explicit operator MemberInfo [] (MemberList list)
1492 Timer.StartTimer (TimerType.MiscTimer);
1493 MemberInfo [] result = new MemberInfo [list.Count];
1494 list.CopyTo (result, 0);
1495 Timer.StopTimer (TimerType.MiscTimer);
1507 public bool IsSynchronized {
1509 return List.IsSynchronized;
1513 public object SyncRoot {
1515 return List.SyncRoot;
1519 public void CopyTo (Array array, int index)
1521 List.CopyTo (array, index);
1526 public IEnumerator GetEnumerator ()
1528 return List.GetEnumerator ();
1533 public bool IsFixedSize {
1539 public bool IsReadOnly {
1545 object IList.this [int index] {
1547 return List [index];
1551 throw new NotSupportedException ();
1555 // FIXME: try to find out whether we can avoid the cast in this indexer.
1556 public MemberInfo this [int index] {
1558 return (MemberInfo) List [index];
1562 public int Add (object value)
1564 throw new NotSupportedException ();
1567 public void Clear ()
1569 throw new NotSupportedException ();
1572 public bool Contains (object value)
1574 return List.Contains (value);
1577 public int IndexOf (object value)
1579 return List.IndexOf (value);
1582 public void Insert (int index, object value)
1584 throw new NotSupportedException ();
1587 public void Remove (object value)
1589 throw new NotSupportedException ();
1592 public void RemoveAt (int index)
1594 throw new NotSupportedException ();
1599 /// This interface is used to get all members of a class when creating the
1600 /// member cache. It must be implemented by all DeclSpace derivatives which
1601 /// want to support the member cache and by TypeHandle to get caching of
1602 /// non-dynamic types.
1604 public interface IMemberContainer {
1606 /// The name of the IMemberContainer. This is only used for
1607 /// debugging purposes.
1614 /// The type of this IMemberContainer.
1621 /// Returns the IMemberContainer of the base class or null if this
1622 /// is an interface or TypeManger.object_type.
1623 /// This is used when creating the member cache for a class to get all
1624 /// members from the base class.
1626 MemberCache BaseCache {
1631 /// Whether this is an interface.
1638 /// Returns all members of this class with the corresponding MemberTypes
1639 /// and BindingFlags.
1642 /// When implementing this method, make sure not to return any inherited
1643 /// members and check the MemberTypes and BindingFlags properly.
1644 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1645 /// get the BindingFlags (static/non-static,public/non-public) in the
1646 /// MemberInfo class, but the cache needs this information. That's why
1647 /// this method is called multiple times with different BindingFlags.
1649 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1652 /// Return the container's member cache.
1654 MemberCache MemberCache {
1660 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1661 /// member lookups. It has a member name based hash table; it maps each member
1662 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1663 /// and the BindingFlags that were initially used to get it. The cache contains
1664 /// all members of the current class and all inherited members. If this cache is
1665 /// for an interface types, it also contains all inherited members.
1667 /// There are two ways to get a MemberCache:
1668 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1669 /// use the DeclSpace.MemberCache property.
1670 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1671 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1673 public class MemberCache {
1674 public readonly IMemberContainer Container;
1675 protected Hashtable member_hash;
1676 protected Hashtable method_hash;
1679 /// Create a new MemberCache for the given IMemberContainer `container'.
1681 public MemberCache (IMemberContainer container)
1683 this.Container = container;
1685 Timer.IncrementCounter (CounterType.MemberCache);
1686 Timer.StartTimer (TimerType.CacheInit);
1688 // If we have a base class (we have a base class unless we're
1689 // TypeManager.object_type), we deep-copy its MemberCache here.
1690 if (Container.BaseCache != null)
1691 member_hash = SetupCache (Container.BaseCache);
1693 member_hash = new Hashtable ();
1695 // If this is neither a dynamic type nor an interface, create a special
1696 // method cache with all declared and inherited methods.
1697 Type type = container.Type;
1698 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1699 method_hash = new Hashtable ();
1703 // Add all members from the current class.
1704 AddMembers (Container);
1706 Timer.StopTimer (TimerType.CacheInit);
1709 public MemberCache (Type[] ifaces)
1712 // The members of this cache all belong to other caches.
1713 // So, 'Container' will not be used.
1715 this.Container = null;
1717 member_hash = new Hashtable ();
1721 foreach (Type itype in ifaces)
1722 AddCacheContents (TypeManager.LookupMemberCache (itype));
1726 /// Bootstrap this member cache by doing a deep-copy of our base.
1728 Hashtable SetupCache (MemberCache base_class)
1730 Hashtable hash = new Hashtable ();
1732 if (base_class == null)
1735 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1736 while (it.MoveNext ()) {
1737 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1744 /// Add the contents of `cache' to the member_hash.
1746 void AddCacheContents (MemberCache cache)
1748 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1749 while (it.MoveNext ()) {
1750 ArrayList list = (ArrayList) member_hash [it.Key];
1752 member_hash [it.Key] = list = new ArrayList ();
1754 ArrayList entries = (ArrayList) it.Value;
1755 for (int i = entries.Count-1; i >= 0; i--) {
1756 CacheEntry entry = (CacheEntry) entries [i];
1758 if (entry.Container != cache.Container)
1766 /// Add all members from class `container' to the cache.
1768 void AddMembers (IMemberContainer container)
1770 // We need to call AddMembers() with a single member type at a time
1771 // to get the member type part of CacheEntry.EntryType right.
1772 if (!container.IsInterface) {
1773 AddMembers (MemberTypes.Constructor, container);
1774 AddMembers (MemberTypes.Field, container);
1776 AddMembers (MemberTypes.Method, container);
1777 AddMembers (MemberTypes.Property, container);
1778 AddMembers (MemberTypes.Event, container);
1779 // Nested types are returned by both Static and Instance searches.
1780 AddMembers (MemberTypes.NestedType,
1781 BindingFlags.Static | BindingFlags.Public, container);
1782 AddMembers (MemberTypes.NestedType,
1783 BindingFlags.Static | BindingFlags.NonPublic, container);
1786 void AddMembers (MemberTypes mt, IMemberContainer container)
1788 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1789 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1790 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1791 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1795 /// Add all members from class `container' with the requested MemberTypes and
1796 /// BindingFlags to the cache. This method is called multiple times with different
1797 /// MemberTypes and BindingFlags.
1799 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1801 MemberList members = container.GetMembers (mt, bf);
1803 foreach (MemberInfo member in members) {
1804 string name = member.Name;
1806 int pos = name.IndexOf ('<');
1808 name = name.Substring (0, pos);
1810 // We use a name-based hash table of ArrayList's.
1811 ArrayList list = (ArrayList) member_hash [name];
1813 list = new ArrayList ();
1814 member_hash.Add (name, list);
1817 // When this method is called for the current class, the list will
1818 // already contain all inherited members from our base classes.
1819 // We cannot add new members in front of the list since this'd be an
1820 // expensive operation, that's why the list is sorted in reverse order
1821 // (ie. members from the current class are coming last).
1822 list.Add (new CacheEntry (container, member, mt, bf));
1827 /// Add all declared and inherited methods from class `type' to the method cache.
1829 void AddMethods (Type type)
1831 AddMethods (BindingFlags.Static | BindingFlags.Public |
1832 BindingFlags.FlattenHierarchy, type);
1833 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1834 BindingFlags.FlattenHierarchy, type);
1835 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1836 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1839 void AddMethods (BindingFlags bf, Type type)
1841 MemberInfo [] members = type.GetMethods (bf);
1843 Array.Reverse (members);
1845 foreach (MethodBase member in members) {
1846 string name = member.Name;
1848 // We use a name-based hash table of ArrayList's.
1849 ArrayList list = (ArrayList) method_hash [name];
1851 list = new ArrayList ();
1852 method_hash.Add (name, list);
1855 // Unfortunately, the elements returned by Type.GetMethods() aren't
1856 // sorted so we need to do this check for every member.
1857 BindingFlags new_bf = bf;
1858 if (member.DeclaringType == type)
1859 new_bf |= BindingFlags.DeclaredOnly;
1861 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1866 /// Compute and return a appropriate `EntryType' magic number for the given
1867 /// MemberTypes and BindingFlags.
1869 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1871 EntryType type = EntryType.None;
1873 if ((mt & MemberTypes.Constructor) != 0)
1874 type |= EntryType.Constructor;
1875 if ((mt & MemberTypes.Event) != 0)
1876 type |= EntryType.Event;
1877 if ((mt & MemberTypes.Field) != 0)
1878 type |= EntryType.Field;
1879 if ((mt & MemberTypes.Method) != 0)
1880 type |= EntryType.Method;
1881 if ((mt & MemberTypes.Property) != 0)
1882 type |= EntryType.Property;
1883 // Nested types are returned by static and instance searches.
1884 if ((mt & MemberTypes.NestedType) != 0)
1885 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1887 if ((bf & BindingFlags.Instance) != 0)
1888 type |= EntryType.Instance;
1889 if ((bf & BindingFlags.Static) != 0)
1890 type |= EntryType.Static;
1891 if ((bf & BindingFlags.Public) != 0)
1892 type |= EntryType.Public;
1893 if ((bf & BindingFlags.NonPublic) != 0)
1894 type |= EntryType.NonPublic;
1895 if ((bf & BindingFlags.DeclaredOnly) != 0)
1896 type |= EntryType.Declared;
1902 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1903 /// denote multiple member types. Returns true if the given flags value denotes a
1904 /// single member types.
1906 public static bool IsSingleMemberType (MemberTypes mt)
1909 case MemberTypes.Constructor:
1910 case MemberTypes.Event:
1911 case MemberTypes.Field:
1912 case MemberTypes.Method:
1913 case MemberTypes.Property:
1914 case MemberTypes.NestedType:
1923 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1924 /// number to speed up the searching process.
1927 protected enum EntryType {
1932 MaskStatic = Instance|Static,
1936 MaskProtection = Public|NonPublic,
1940 Constructor = 0x020,
1947 MaskType = Constructor|Event|Field|Method|Property|NestedType
1950 protected struct CacheEntry {
1951 public readonly IMemberContainer Container;
1952 public readonly EntryType EntryType;
1953 public readonly MemberInfo Member;
1955 public CacheEntry (IMemberContainer container, MemberInfo member,
1956 MemberTypes mt, BindingFlags bf)
1958 this.Container = container;
1959 this.Member = member;
1960 this.EntryType = GetEntryType (mt, bf);
1963 public override string ToString ()
1965 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1971 /// This is called each time we're walking up one level in the class hierarchy
1972 /// and checks whether we can abort the search since we've already found what
1973 /// we were looking for.
1975 protected bool DoneSearching (ArrayList list)
1978 // We've found exactly one member in the current class and it's not
1979 // a method or constructor.
1981 if (list.Count == 1 && !(list [0] is MethodBase))
1985 // Multiple properties: we query those just to find out the indexer
1988 if ((list.Count > 0) && (list [0] is PropertyInfo))
1995 /// Looks up members with name `name'. If you provide an optional
1996 /// filter function, it'll only be called with members matching the
1997 /// requested member name.
1999 /// This method will try to use the cache to do the lookup if possible.
2001 /// Unlike other FindMembers implementations, this method will always
2002 /// check all inherited members - even when called on an interface type.
2004 /// If you know that you're only looking for methods, you should use
2005 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2006 /// When doing a method-only search, it'll try to use a special method
2007 /// cache (unless it's a dynamic type or an interface) and the returned
2008 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2009 /// The lookup process will automatically restart itself in method-only
2010 /// search mode if it discovers that it's about to return methods.
2012 ArrayList global = new ArrayList ();
2013 bool using_global = false;
2015 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2017 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2018 MemberFilter filter, object criteria)
2021 throw new Exception ();
2023 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2024 bool method_search = mt == MemberTypes.Method;
2025 // If we have a method cache and we aren't already doing a method-only search,
2026 // then we restart a method search if the first match is a method.
2027 bool do_method_search = !method_search && (method_hash != null);
2029 ArrayList applicable;
2031 // If this is a method-only search, we try to use the method cache if
2032 // possible; a lookup in the method cache will return a MemberInfo with
2033 // the correct ReflectedType for inherited methods.
2035 if (method_search && (method_hash != null))
2036 applicable = (ArrayList) method_hash [name];
2038 applicable = (ArrayList) member_hash [name];
2040 if (applicable == null)
2041 return emptyMemberInfo;
2044 // 32 slots gives 53 rss/54 size
2045 // 2/4 slots gives 55 rss
2047 // Strange: from 25,000 calls, only 1,800
2048 // are above 2. Why does this impact it?
2051 using_global = true;
2053 Timer.StartTimer (TimerType.CachedLookup);
2055 EntryType type = GetEntryType (mt, bf);
2057 IMemberContainer current = Container;
2060 // `applicable' is a list of all members with the given member name `name'
2061 // in the current class and all its base classes. The list is sorted in
2062 // reverse order due to the way how the cache is initialy created (to speed
2063 // things up, we're doing a deep-copy of our base).
2065 for (int i = applicable.Count-1; i >= 0; i--) {
2066 CacheEntry entry = (CacheEntry) applicable [i];
2068 // This happens each time we're walking one level up in the class
2069 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2070 // the first time this happens (this may already happen in the first
2071 // iteration of this loop if there are no members with the name we're
2072 // looking for in the current class).
2073 if (entry.Container != current) {
2074 if (declared_only || DoneSearching (global))
2077 current = entry.Container;
2080 // Is the member of the correct type ?
2081 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2084 // Is the member static/non-static ?
2085 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2088 // Apply the filter to it.
2089 if (filter (entry.Member, criteria)) {
2090 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2091 do_method_search = false;
2092 global.Add (entry.Member);
2096 Timer.StopTimer (TimerType.CachedLookup);
2098 // If we have a method cache and we aren't already doing a method-only
2099 // search, we restart in method-only search mode if the first match is
2100 // a method. This ensures that we return a MemberInfo with the correct
2101 // ReflectedType for inherited methods.
2102 if (do_method_search && (global.Count > 0)){
2103 using_global = false;
2105 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2108 using_global = false;
2109 MemberInfo [] copy = new MemberInfo [global.Count];
2110 global.CopyTo (copy);
2115 // This finds the method or property for us to override. invocationType is the type where
2116 // the override is going to be declared, name is the name of the method/property, and
2117 // paramTypes is the parameters, if any to the method or property
2119 // Because the MemberCache holds members from this class and all the base classes,
2120 // we can avoid tons of reflection stuff.
2122 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2124 ArrayList applicable;
2125 if (method_hash != null && !is_property)
2126 applicable = (ArrayList) method_hash [name];
2128 applicable = (ArrayList) member_hash [name];
2130 if (applicable == null)
2133 // Walk the chain of methods, starting from the top.
2135 for (int i = applicable.Count - 1; i >= 0; i--) {
2136 CacheEntry entry = (CacheEntry) applicable [i];
2138 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2141 PropertyInfo pi = null;
2142 MethodInfo mi = null;
2143 FieldInfo fi = null;
2144 Type [] cmpAttrs = null;
2147 if ((entry.EntryType & EntryType.Field) != 0) {
2148 fi = (FieldInfo)entry.Member;
2150 // TODO: For this case we ignore member type
2151 //fb = TypeManager.GetField (fi);
2152 //cmpAttrs = new Type[] { fb.MemberType };
2154 pi = (PropertyInfo) entry.Member;
2155 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2158 mi = (MethodInfo) entry.Member;
2159 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2163 // TODO: Almost duplicate !
2165 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2166 case FieldAttributes.Private:
2168 // A private method is Ok if we are a nested subtype.
2169 // The spec actually is not very clear about this, see bug 52458.
2171 if (invocationType != entry.Container.Type &
2172 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2176 case FieldAttributes.FamANDAssem:
2177 case FieldAttributes.Assembly:
2179 // Check for assembly methods
2181 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2185 return entry.Member;
2189 // Check the arguments
2191 if (cmpAttrs.Length != paramTypes.Length)
2194 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2195 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2200 // get one of the methods because this has the visibility info.
2203 mi = pi.GetGetMethod (true);
2205 mi = pi.GetSetMethod (true);
2211 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2212 case MethodAttributes.Private:
2214 // A private method is Ok if we are a nested subtype.
2215 // The spec actually is not very clear about this, see bug 52458.
2217 if (invocationType.Equals (entry.Container.Type) ||
2218 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2219 return entry.Member;
2222 case MethodAttributes.FamANDAssem:
2223 case MethodAttributes.Assembly:
2225 // Check for assembly methods
2227 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2228 return entry.Member;
2233 // A protected method is ok, because we are overriding.
2234 // public is always ok.
2236 return entry.Member;
2246 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2247 /// We handle two cases. The first is for types without parameters (events, field, properties).
2248 /// The second are methods, indexers and this is why ignore_complex_types is here.
2249 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2251 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2253 ArrayList applicable = null;
2255 if (method_hash != null)
2256 applicable = (ArrayList) method_hash [name];
2258 if (applicable != null) {
2259 for (int i = applicable.Count - 1; i >= 0; i--) {
2260 CacheEntry entry = (CacheEntry) applicable [i];
2261 if ((entry.EntryType & EntryType.Public) != 0)
2262 return entry.Member;
2266 if (member_hash == null)
2268 applicable = (ArrayList) member_hash [name];
2270 if (applicable != null) {
2271 for (int i = applicable.Count - 1; i >= 0; i--) {
2272 CacheEntry entry = (CacheEntry) applicable [i];
2273 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2274 if (ignore_complex_types) {
2275 if ((entry.EntryType & EntryType.Method) != 0)
2278 // Does exist easier way how to detect indexer ?
2279 if ((entry.EntryType & EntryType.Property) != 0) {
2280 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2281 if (arg_types.Length > 0)
2285 return entry.Member;
2292 Hashtable locase_table;
2295 /// Builds low-case table for CLS Compliance test
2297 public Hashtable GetPublicMembers ()
2299 if (locase_table != null)
2300 return locase_table;
2302 locase_table = new Hashtable ();
2303 foreach (DictionaryEntry entry in member_hash) {
2304 ArrayList members = (ArrayList)entry.Value;
2305 for (int ii = 0; ii < members.Count; ++ii) {
2306 CacheEntry member_entry = (CacheEntry) members [ii];
2308 if ((member_entry.EntryType & EntryType.Public) == 0)
2311 // TODO: Does anyone know easier way how to detect that member is internal ?
2312 switch (member_entry.EntryType & EntryType.MaskType) {
2313 case EntryType.Constructor:
2316 case EntryType.Field:
2317 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2321 case EntryType.Method:
2322 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2326 case EntryType.Property:
2327 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2328 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2332 case EntryType.Event:
2333 EventInfo ei = (EventInfo)member_entry.Member;
2334 MethodInfo mi = ei.GetAddMethod ();
2335 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2339 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2340 locase_table [lcase] = member_entry.Member;
2344 return locase_table;
2347 public Hashtable Members {
2354 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2356 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2358 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2360 for (int i = 0; i < al.Count; ++i) {
2361 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2364 if (entry.Member == this_builder)
2367 if ((entry.EntryType & tested_type) != tested_type)
2370 MethodBase method_to_compare = (MethodBase)entry.Member;
2371 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2374 IMethodData md = TypeManager.GetMethod (method_to_compare);
2376 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2377 // However it is exactly what csc does.
2378 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2381 Report.SymbolRelatedToPreviousError (entry.Member);
2382 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());