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)
11 // TODO: Move the method verification stuff from the class.cs and interface.cs here
16 using System.Collections;
17 using System.Globalization;
18 using System.Reflection.Emit;
19 using System.Reflection;
21 namespace Mono.CSharp {
23 public class MemberName {
24 public readonly string Name;
25 public readonly TypeArguments TypeArguments;
27 public readonly MemberName Left;
29 public static readonly MemberName Null = new MemberName ("");
31 public MemberName (string name)
36 public MemberName (string name, TypeArguments args)
39 this.TypeArguments = args;
42 public MemberName (MemberName left, string name, TypeArguments args)
48 public MemberName (MemberName left, MemberName right)
49 : this (left, right.Name, right.TypeArguments)
53 public string GetName ()
56 return Left.GetName () + "." + Name;
61 public bool IsGeneric {
63 if (TypeArguments != null)
65 else if (Left != null)
66 return Left.IsGeneric;
72 public string GetName (bool is_generic)
74 string name = is_generic ? Basename : Name;
76 return Left.GetName (is_generic) + "." + name;
81 public int CountTypeArguments {
83 if (TypeArguments == null)
86 return TypeArguments.Count;
90 public string GetFullName ()
93 if (TypeArguments != null)
94 full_name = Name + "<" + TypeArguments + ">";
98 return Left.GetFullName () + "." + full_name;
103 public static string MakeName (string name, TypeArguments args)
108 return name + "`" + args.Count;
111 public static string MakeName (string name, int count)
113 return name + "`" + count;
116 public string GetTypeName ()
120 return Left.GetTypeName () + "." +
121 MakeName (Name, TypeArguments);
123 return MakeName (Name, TypeArguments);
126 public Expression GetTypeExpression (Location loc)
129 Expression lexpr = Left.GetTypeExpression (loc);
131 return new MemberAccess (lexpr, Name, TypeArguments, loc);
133 if (TypeArguments != null)
134 return new ConstructedType (Name, TypeArguments, loc);
136 return new SimpleName (Name, loc);
140 public string Basename {
142 if (TypeArguments != null)
143 return MakeName (Name, TypeArguments);
149 public override string ToString ()
152 if (TypeArguments != null)
153 full_name = Name + "<" + TypeArguments + ">";
158 return Left + "." + full_name;
165 /// Base representation for members. This is used to keep track
166 /// of Name, Location and Modifier flags, and handling Attributes.
168 public abstract class MemberCore : Attributable {
174 public readonly MemberName MemberName;
177 /// Modifier flags that the user specified in the source code
181 public readonly TypeContainer Parent;
184 /// Location where this declaration happens
186 public readonly Location Location;
190 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
191 Obsolete = 1 << 1, // Type has obsolete attribute
192 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
193 ClsCompliant = 1 << 3, // Type is CLS Compliant
194 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
195 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
196 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
197 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
198 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
199 Excluded = 1 << 9 // Method is conditional
204 /// MemberCore flags at first detected then cached
206 protected Flags caching_flags;
208 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
213 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
216 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
220 /// Tests presence of ObsoleteAttribute and report proper error
222 protected void CheckUsageOfObsoleteAttribute (Type type)
227 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
228 if (obsolete_attr == null)
231 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
234 public abstract bool Define ();
237 // Returns full member name for error message
239 public virtual string GetSignatureForError ()
245 /// Base Emit method. This is also entry point for CLS-Compliant verification.
247 public virtual void Emit ()
249 VerifyObsoleteAttribute ();
251 if (!RootContext.VerifyClsCompliance)
254 VerifyClsCompliance (Parent);
258 // Whehter is it ok to use an unsafe pointer in this type container
260 public bool UnsafeOK (DeclSpace parent)
263 // First check if this MemberCore modifier flags has unsafe set
265 if ((ModFlags & Modifiers.UNSAFE) != 0)
268 if (parent.UnsafeContext)
271 Expression.UnsafeError (Location);
276 /// Returns instance of ObsoleteAttribute for this MemberCore
278 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
280 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
281 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
285 caching_flags &= ~Flags.Obsolete_Undetected;
287 if (OptAttributes == null)
290 // TODO: remove this allocation
291 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
292 null, null, ds.ModFlags, false);
294 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
295 if (obsolete_attr == null)
298 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
299 if (obsolete == null)
302 caching_flags |= Flags.Obsolete;
307 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
309 public override bool IsClsCompliaceRequired (DeclSpace container)
311 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
312 return (caching_flags & Flags.ClsCompliant) != 0;
314 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
315 caching_flags &= ~Flags.ClsCompliance_Undetected;
316 caching_flags |= Flags.ClsCompliant;
320 caching_flags &= ~Flags.ClsCompliance_Undetected;
325 /// Returns true when MemberCore is exposed from assembly.
327 protected bool IsExposedFromAssembly (DeclSpace ds)
329 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
332 DeclSpace parentContainer = ds;
333 while (parentContainer != null && parentContainer.ModFlags != 0) {
334 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
336 parentContainer = parentContainer.Parent;
342 /// Resolve CLSCompliantAttribute value or gets cached value.
344 bool GetClsCompliantAttributeValue (DeclSpace ds)
346 if (OptAttributes != null) {
347 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
348 null, null, ds.ModFlags, false);
349 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
350 if (cls_attribute != null) {
351 caching_flags |= Flags.HasClsCompliantAttribute;
352 return cls_attribute.GetClsCompliantAttributeValue (ds);
355 return ds.GetClsCompliantAttributeValue ();
359 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
361 protected bool HasClsCompliantAttribute {
363 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
368 /// This method is used to testing error 3005 (Method or parameter name collision).
370 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
373 /// Common helper method for identifier and parameters CLS-Compliant testing.
374 /// When return false error 3005 is reported. True means no violation.
375 /// And error 3006 tests are peformed here because of speed.
377 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
379 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
380 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
385 bool error3006 = false;
386 for (int i = 0; i < ml.Count; ++i) {
387 MemberInfo mi = ml [i];
388 if (name == mi.Name) {
389 MethodBase method = mi as MethodBase;
390 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
393 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
401 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
402 // because BindingFlags.Public returns internal types too
403 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
405 // Type is external, we can get attribute directly
406 if (temp_ds == null) {
407 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
408 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
411 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
413 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
414 if (!mc.IsClsCompliaceRequired (ds))
418 for (int ii = 0; ii < ml.Count; ++ii) {
422 Report.SymbolRelatedToPreviousError (mi);
426 Report.Error_T (3006, Location, GetSignatureForError ());
435 /// The main virtual method for CLS-Compliant verifications.
436 /// The method returns true if member is CLS-Compliant and false if member is not
437 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
438 /// and add their extra verifications.
440 protected virtual bool VerifyClsCompliance (DeclSpace ds)
442 if (!IsClsCompliaceRequired (ds)) {
443 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
444 Report.Warning_T (3019, Location, GetSignatureForError ());
449 if (!CodeGen.Assembly.IsClsCompliant) {
450 if (HasClsCompliantAttribute) {
451 Report.Error_T (3014, Location, GetSignatureForError ());
455 int index = Name.LastIndexOf ('.');
456 if (Name [index > 0 ? index + 1 : 0] == '_') {
457 Report.Error_T (3008, Location, GetSignatureForError () );
460 if (!IsIdentifierClsCompliant (ds)) {
461 Report.Error_T (3005, Location, GetSignatureForError ());
467 protected abstract void VerifyObsoleteAttribute ();
472 /// Base class for structs, classes, enumerations and interfaces.
475 /// They all create new declaration spaces. This
476 /// provides the common foundation for managing those name
479 public abstract class DeclSpace : MemberCore, IAlias {
481 /// This points to the actual definition that is being
482 /// created with System.Reflection.Emit
484 public TypeBuilder TypeBuilder;
487 /// If we are a generic type, this is the type we are
488 /// currently defining. We need to lookup members on this
489 /// instead of the TypeBuilder.
491 public TypeExpr CurrentType;
494 // This is the namespace in which this typecontainer
495 // was declared. We use this to resolve names.
497 public NamespaceEntry NamespaceEntry;
499 public Hashtable Cache = new Hashtable ();
501 public string Basename;
504 /// defined_names is used for toplevel objects
506 protected Hashtable defined_names;
508 readonly bool is_generic;
509 readonly int count_type_params;
512 // Whether we are Generic
514 public bool IsGeneric {
518 else if (Parent != null)
519 return Parent.IsGeneric;
525 static string[] attribute_targets = new string [] { "type" };
527 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
528 Attributes attrs, Location l)
529 : base (parent, name, attrs, l)
532 Basename = name.Name;
533 defined_names = new Hashtable ();
534 if (name.TypeArguments != null) {
536 count_type_params = name.TypeArguments.Count;
539 count_type_params += parent.count_type_params;
542 public void RecordDecl ()
544 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
545 NamespaceEntry.DefineName (MemberName.Basename, this);
549 /// The result value from adding an declaration into
550 /// a struct or a class
552 public enum AdditionResult {
554 /// The declaration has been successfully
555 /// added to the declation space.
560 /// The symbol has already been defined.
565 /// Returned if the declation being added to the
566 /// name space clashes with its container name.
568 /// The only exceptions for this are constructors
569 /// and static constructors
574 /// Returned if a constructor was created (because syntactically
575 /// it looked like a constructor) but was not (because the name
576 /// of the method is not the same as the container class
581 /// This is only used by static constructors to emit the
582 /// error 111, but this error for other things really
583 /// happens at another level for other functions.
588 /// Some other error.
594 /// Returns a status code based purely on the name
595 /// of the member being added
597 protected AdditionResult IsValid (string basename, string name)
599 if (basename == Basename)
600 return AdditionResult.EnclosingClash;
602 if (defined_names.Contains (name))
603 return AdditionResult.NameExists;
605 return AdditionResult.Success;
608 public static int length;
609 public static int small;
612 /// Introduce @name into this declaration space and
613 /// associates it with the object @o. Note that for
614 /// methods this will just point to the first method. o
616 public void DefineName (string name, object o)
618 defined_names.Add (name, o);
621 int p = name.LastIndexOf ('.');
629 /// Returns the object associated with a given name in the declaration
630 /// space. This is the inverse operation of `DefineName'
632 public object GetDefinition (string name)
634 return defined_names [name];
637 bool in_transit = false;
640 /// This function is used to catch recursive definitions
643 public bool InTransit {
654 /// Looks up the alias for the name
656 public IAlias LookupAlias (string name)
658 if (NamespaceEntry != null)
659 return NamespaceEntry.LookupAlias (name);
665 // root_types contains all the types. All TopLevel types
666 // hence have a parent that points to `root_types', that is
667 // why there is a non-obvious test down here.
669 public bool IsTopLevel {
672 if (Parent.Parent == null)
679 public virtual void CloseType ()
681 if ((caching_flags & Flags.CloseTypeCreated) == 0){
683 TypeBuilder.CreateType ();
686 // The try/catch is needed because
687 // nested enumerations fail to load when they
690 // Even if this is the right order (enumerations
691 // declared after types).
693 // Note that this still creates the type and
694 // it is possible to save it
696 caching_flags |= Flags.CloseTypeCreated;
701 /// Should be overriten by the appropriate declaration space
703 public abstract TypeBuilder DefineType ();
706 /// Define all members, but don't apply any attributes or do anything which may
707 /// access not-yet-defined classes. This method also creates the MemberCache.
709 public abstract bool DefineMembers (TypeContainer parent);
712 // Whether this is an `unsafe context'
714 public bool UnsafeContext {
716 if ((ModFlags & Modifiers.UNSAFE) != 0)
719 return Parent.UnsafeContext;
724 public static string MakeFQN (string nsn, string name)
728 return String.Concat (nsn, ".", name);
731 EmitContext type_resolve_ec;
732 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
734 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
735 type_resolve_ec.ResolvingTypeTree = true;
737 return type_resolve_ec;
741 // Looks up the type, as parsed into the expression `e'
743 public Type ResolveType (Expression e, bool silent, Location loc)
745 TypeExpr d = ResolveTypeExpr (e, silent, loc);
749 return ResolveType (d, loc);
752 public Type ResolveType (TypeExpr d, Location loc)
754 if (!d.CheckAccessLevel (this)) {
755 Report.Error_T (122, loc, d.Name);
759 Type t = d.ResolveType (type_resolve_ec);
763 if (d is UnboundTypeExpression)
766 TypeContainer tc = TypeManager.LookupTypeContainer (t);
767 if ((tc != null) && tc.IsGeneric) {
769 int tnum = TypeManager.GetNumberOfTypeArguments (t);
770 Report.Error (305, loc,
771 "Using the generic type `{0}' " +
772 "requires {1} type arguments",
773 TypeManager.GetFullName (t), tnum);
777 ConstructedType ctype = new ConstructedType (
778 t, TypeParameters, loc);
780 t = ctype.ResolveType (type_resolve_ec);
787 // Resolves the expression `e' for a type, and will recursively define
790 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
792 if (type_resolve_ec == null)
793 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
794 type_resolve_ec.loc = loc;
795 if (this is GenericMethod)
796 type_resolve_ec.ContainerType = Parent.TypeBuilder;
798 type_resolve_ec.ContainerType = TypeBuilder;
800 int errors = Report.Errors;
802 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
804 if ((d != null) && (d.eclass == ExprClass.Type))
807 if (silent || (Report.Errors != errors))
810 if (e is SimpleName){
811 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
812 d = s.ResolveAsTypeTerminal (type_resolve_ec);
814 if ((d == null) || (d.Type == null)) {
815 Report.Error (246, loc, "Cannot find type `{0}'", e);
819 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
822 Report.Error (308, loc,
823 "The non-generic type `{0}' cannot " +
824 "be used with type arguments.",
825 TypeManager.CSharpName (d.Type));
829 Report.Error (305, loc,
830 "Using the generic type `{0}' " +
831 "requires {1} type arguments",
832 TypeManager.GetFullName (d.Type), num_args);
836 Report.Error (246, loc, "Cannot find type `{0}'", e);
840 public bool CheckAccessLevel (Type check_type)
843 if (this is GenericMethod)
844 tb = Parent.TypeBuilder;
848 if (check_type.IsGenericInstance)
849 check_type = check_type.GetGenericTypeDefinition ();
851 if (check_type == tb)
854 if (check_type.IsGenericParameter)
855 return true; // FIXME
857 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
860 // Broken Microsoft runtime, return public for arrays, no matter what
861 // the accessibility is for their underlying class, and they return
862 // NonPublic visibility for pointers
864 if (check_type.IsArray || check_type.IsPointer)
865 return CheckAccessLevel (TypeManager.GetElementType (check_type));
868 case TypeAttributes.Public:
871 case TypeAttributes.NotPublic:
873 // In same cases is null.
874 if (TypeBuilder == null)
878 // This test should probably use the declaringtype.
880 return check_type.Assembly == TypeBuilder.Assembly;
882 case TypeAttributes.NestedPublic:
885 case TypeAttributes.NestedPrivate:
886 string check_type_name = check_type.FullName;
887 string type_name = tb.FullName;
889 int cio = check_type_name.LastIndexOf ('+');
890 string container = check_type_name.Substring (0, cio);
893 // Check if the check_type is a nested class of the current type
895 if (check_type_name.StartsWith (type_name + "+")){
899 if (type_name.StartsWith (container)){
905 case TypeAttributes.NestedFamily:
907 // Only accessible to methods in current type or any subtypes
909 return FamilyAccessible (tb, check_type);
911 case TypeAttributes.NestedFamANDAssem:
912 return (check_type.Assembly == tb.Assembly) &&
913 FamilyAccessible (tb, check_type);
915 case TypeAttributes.NestedFamORAssem:
916 return (check_type.Assembly == tb.Assembly) ||
917 FamilyAccessible (tb, check_type);
919 case TypeAttributes.NestedAssembly:
920 return check_type.Assembly == tb.Assembly;
923 Console.WriteLine ("HERE: " + check_attr);
928 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
930 Type declaring = check_type.DeclaringType;
931 if (tb.IsSubclassOf (declaring))
934 string check_type_name = check_type.FullName;
936 int cio = check_type_name.LastIndexOf ('+');
937 string container = check_type_name.Substring (0, cio);
940 // Check if the check_type is a nested class of the current type
942 if (check_type_name.StartsWith (container + "+"))
948 // Access level of a type.
950 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
951 // Public Assembly Protected
952 Protected = (0 << 0) | (0 << 1) | (X << 2),
953 Public = (X << 0) | (X << 1) | (X << 2),
954 Private = (0 << 0) | (0 << 1) | (0 << 2),
955 Internal = (0 << 0) | (X << 1) | (0 << 2),
956 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
959 static AccessLevel GetAccessLevelFromModifiers (int flags)
961 if ((flags & Modifiers.INTERNAL) != 0) {
963 if ((flags & Modifiers.PROTECTED) != 0)
964 return AccessLevel.ProtectedOrInternal;
966 return AccessLevel.Internal;
968 } else if ((flags & Modifiers.PROTECTED) != 0)
969 return AccessLevel.Protected;
970 else if ((flags & Modifiers.PRIVATE) != 0)
971 return AccessLevel.Private;
973 return AccessLevel.Public;
976 // What is the effective access level of this?
978 AccessLevel EffectiveAccessLevel {
980 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
981 if (!IsTopLevel && (Parent != null))
982 return myAccess & Parent.EffectiveAccessLevel;
987 // Return the access level for type `t'
988 static AccessLevel TypeEffectiveAccessLevel (Type t)
991 return AccessLevel.Public;
992 if (t.IsNestedPrivate)
993 return AccessLevel.Private;
995 return AccessLevel.Internal;
997 // By now, it must be nested
998 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1000 if (t.IsNestedPublic)
1002 if (t.IsNestedAssembly)
1003 return parentLevel & AccessLevel.Internal;
1004 if (t.IsNestedFamily)
1005 return parentLevel & AccessLevel.Protected;
1006 if (t.IsNestedFamORAssem)
1007 return parentLevel & AccessLevel.ProtectedOrInternal;
1008 if (t.IsNestedFamANDAssem)
1009 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1011 // nested private is taken care of
1013 throw new Exception ("I give up, what are you?");
1017 // This answers `is the type P, as accessible as a member M which has the
1018 // accessability @flags which is declared as a nested member of the type T, this declspace'
1020 public bool AsAccessible (Type p, int flags)
1022 if (p.IsGenericParameter)
1023 return true; // FIXME
1026 // 1) if M is private, its accessability is the same as this declspace.
1027 // we already know that P is accessible to T before this method, so we
1031 if ((flags & Modifiers.PRIVATE) != 0)
1034 while (p.IsArray || p.IsPointer || p.IsByRef)
1035 p = TypeManager.GetElementType (p);
1037 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1038 AccessLevel mAccess = this.EffectiveAccessLevel &
1039 GetAccessLevelFromModifiers (flags);
1041 // for every place from which we can access M, we must
1042 // be able to access P as well. So, we want
1043 // For every bit in M and P, M_i -> P_1 == true
1044 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1046 return ~ (~ mAccess | pAccess) == 0;
1049 static DoubleHash dh = new DoubleHash (1000);
1051 Type DefineTypeAndParents (DeclSpace tc)
1053 DeclSpace container = tc.Parent;
1055 if (container.TypeBuilder == null && container.Name != "")
1056 DefineTypeAndParents (container);
1058 return tc.DefineType ();
1061 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1069 if (dh.Lookup (ns, name, out r))
1073 if (Namespace.IsNamespace (ns)){
1074 string fullname = (ns != "") ? ns + "." + name : name;
1075 t = TypeManager.LookupType (fullname);
1079 t = TypeManager.LookupType (name);
1083 dh.Insert (ns, name, t);
1088 // In case we are fed a composite name, normalize it.
1090 int p = name.LastIndexOf ('.');
1092 ns = MakeFQN (ns, name.Substring (0, p));
1093 name = name.Substring (p+1);
1096 parent = RootContext.Tree.LookupByNamespace (ns, name);
1097 if (parent == null) {
1098 dh.Insert (ns, name, null);
1102 t = DefineTypeAndParents (parent);
1108 dh.Insert (ns, name, t);
1112 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1114 Report.Error (104, loc,
1115 "`{0}' is an ambiguous reference ({1} or {2})",
1119 public Type FindNestedType (Location loc, string name,
1120 out DeclSpace containing_ds)
1125 containing_ds = this;
1126 while (containing_ds != null){
1127 Type container_type = containing_ds.TypeBuilder;
1128 Type current_type = container_type;
1130 while (current_type != null && current_type != TypeManager.object_type) {
1131 string pre = current_type.FullName;
1133 t = LookupInterfaceOrClass (pre, name, out error);
1137 if ((t != null) && containing_ds.CheckAccessLevel (t))
1140 current_type = current_type.BaseType;
1142 containing_ds = containing_ds.Parent;
1149 /// GetType is used to resolve type names at the DeclSpace level.
1150 /// Use this to lookup class/struct bases, interface bases or
1151 /// delegate type references
1155 /// Contrast this to LookupType which is used inside method bodies to
1156 /// lookup types that have already been defined. GetType is used
1157 /// during the tree resolution process and potentially define
1158 /// recursively the type
1160 public Type FindType (Location loc, string name)
1166 // For the case the type we are looking for is nested within this one
1167 // or is in any base class
1169 DeclSpace containing_ds = this;
1171 while (containing_ds != null){
1172 Type container_type = containing_ds.TypeBuilder;
1173 Type current_type = container_type;
1175 while (current_type != null && current_type != TypeManager.object_type) {
1176 string pre = current_type.FullName;
1178 t = LookupInterfaceOrClass (pre, name, out error);
1182 if ((t != null) && containing_ds.CheckAccessLevel (t))
1185 current_type = current_type.BaseType;
1187 containing_ds = containing_ds.Parent;
1191 // Attempt to lookup the class on our namespace and all it's implicit parents
1193 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1194 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1203 // Attempt to do a direct unqualified lookup
1205 t = LookupInterfaceOrClass ("", name, out error);
1213 // Attempt to lookup the class on any of the `using'
1217 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1219 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1226 if (name.IndexOf ('.') > 0)
1229 IAlias alias_value = ns.LookupAlias (name);
1230 if (alias_value != null) {
1231 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1240 // Now check the using clause list
1243 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1244 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1248 if (match != null) {
1250 if (CheckAccessLevel (match)) {
1251 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1264 //Report.Error (246, Location, "Can not find type `"+name+"'");
1269 /// This function is broken and not what you're looking for. It should only
1270 /// be used while the type is still being created since it doesn't use the cache
1271 /// and relies on the filter doing the member name check.
1273 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1274 MemberFilter filter, object criteria);
1277 /// If we have a MemberCache, return it. This property may return null if the
1278 /// class doesn't have a member cache or while it's still being created.
1280 public abstract MemberCache MemberCache {
1284 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1287 TypeBuilder.SetCustomAttribute (cb);
1288 } catch (System.ArgumentException e) {
1289 Report.Warning (-21, a.Location,
1290 "The CharSet named property on StructLayout\n"+
1291 "\tdoes not work correctly on Microsoft.NET\n"+
1292 "\tYou might want to remove the CharSet declaration\n"+
1293 "\tor compile using the Mono runtime instead of the\n"+
1294 "\tMicrosoft .NET runtime\n"+
1295 "\tThe runtime gave the error: " + e);
1300 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1301 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1303 public bool GetClsCompliantAttributeValue ()
1305 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1306 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1308 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1310 if (OptAttributes != null) {
1311 EmitContext ec = new EmitContext (Parent, this, Location,
1312 null, null, ModFlags, false);
1313 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1314 if (cls_attribute != null) {
1315 caching_flags |= Flags.HasClsCompliantAttribute;
1316 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1317 caching_flags |= Flags.ClsCompliantAttributeTrue;
1324 if (Parent == null) {
1325 if (CodeGen.Assembly.IsClsCompliant) {
1326 caching_flags |= Flags.ClsCompliantAttributeTrue;
1332 if (Parent.GetClsCompliantAttributeValue ()) {
1333 caching_flags |= Flags.ClsCompliantAttributeTrue;
1340 // Tests container name for CLS-Compliant name (differing only in case)
1341 // Possible optimalization: search in same namespace only
1342 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1344 int l = Name.Length;
1346 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1347 // Seek through all imported types
1348 foreach (string type_name in TypeManager.all_imported_types.Keys)
1350 if (l != type_name.Length)
1353 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1354 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1355 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1361 // Seek through generated types
1362 foreach (string name in RootContext.Tree.Decls.Keys) {
1363 if (l != name.Length)
1366 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1371 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1372 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1373 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1383 // Extensions for generics
1385 TypeParameter[] type_params;
1386 TypeParameter[] type_param_list;
1388 protected string GetInstantiationName ()
1390 StringBuilder sb = new StringBuilder (Name);
1392 for (int i = 0; i < type_param_list.Length; i++) {
1395 sb.Append (type_param_list [i].Name);
1398 return sb.ToString ();
1401 bool check_type_parameter (ArrayList list, int start, string name)
1403 for (int i = 0; i < start; i++) {
1404 TypeParameter param = (TypeParameter) list [i];
1406 if (param.Name != name)
1409 if (RootContext.WarningLevel >= 3)
1412 "Type parameter `{0}' has same name " +
1413 "as type parameter from outer type `{1}'",
1414 name, Parent.GetInstantiationName ());
1422 TypeParameter[] initialize_type_params ()
1424 if (type_param_list != null)
1425 return type_param_list;
1427 DeclSpace the_parent = Parent;
1428 if (this is GenericMethod)
1432 TypeParameter[] parent_params = null;
1433 if ((the_parent != null) && the_parent.IsGeneric) {
1434 parent_params = the_parent.initialize_type_params ();
1435 start = parent_params != null ? parent_params.Length : 0;
1438 ArrayList list = new ArrayList ();
1439 if (parent_params != null)
1440 list.AddRange (parent_params);
1442 int count = type_params != null ? type_params.Length : 0;
1443 for (int i = 0; i < count; i++) {
1444 TypeParameter param = type_params [i];
1445 check_type_parameter (list, start, param.Name);
1449 type_param_list = new TypeParameter [list.Count];
1450 list.CopyTo (type_param_list, 0);
1451 return type_param_list;
1454 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1457 if (constraints_list != null) {
1459 80, Location, "Contraints are not allowed " +
1460 "on non-generic declarations");
1461 return AdditionResult.Error;
1464 return AdditionResult.Success;
1467 string[] names = MemberName.TypeArguments.GetDeclarations ();
1468 type_params = new TypeParameter [names.Length];
1471 // Register all the names
1473 for (int i = 0; i < type_params.Length; i++) {
1474 string name = names [i];
1476 AdditionResult res = IsValid (name, name);
1478 if (res != AdditionResult.Success)
1481 Constraints constraints = null;
1482 if (constraints_list != null) {
1483 foreach (Constraints constraint in constraints_list) {
1484 if (constraint.TypeParameter == name) {
1485 constraints = constraint;
1491 type_params [i] = new TypeParameter (name, constraints, Location);
1493 DefineName (name, type_params [i]);
1496 return AdditionResult.Success;
1499 public TypeParameter[] TypeParameters {
1502 throw new InvalidOperationException ();
1503 if (type_param_list == null)
1504 initialize_type_params ();
1506 return type_param_list;
1510 protected TypeParameter[] CurrentTypeParameters {
1513 throw new InvalidOperationException ();
1514 if (type_params != null)
1517 return new TypeParameter [0];
1521 public int CountTypeParameters {
1523 return count_type_params;
1527 public TypeParameterExpr LookupGeneric (string name, Location loc)
1532 foreach (TypeParameter type_param in CurrentTypeParameters) {
1533 if (type_param.Name != name)
1536 return new TypeParameterExpr (type_param, loc);
1540 return Parent.LookupGeneric (name, loc);
1545 bool IAlias.IsType {
1546 get { return true; }
1549 string IAlias.Name {
1550 get { return Name; }
1553 TypeExpr IAlias.Type
1556 if (TypeBuilder == null)
1557 throw new InvalidOperationException ();
1559 if (CurrentType != null)
1562 return new TypeExpression (TypeBuilder, Location);
1566 protected override string[] ValidAttributeTargets {
1568 return attribute_targets;
1574 /// This is a readonly list of MemberInfo's.
1576 public class MemberList : IList {
1577 public readonly IList List;
1581 /// Create a new MemberList from the given IList.
1583 public MemberList (IList list)
1588 this.List = new ArrayList ();
1593 /// Concatenate the ILists `first' and `second' to a new MemberList.
1595 public MemberList (IList first, IList second)
1597 ArrayList list = new ArrayList ();
1598 list.AddRange (first);
1599 list.AddRange (second);
1604 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1607 /// Cast the MemberList into a MemberInfo[] array.
1610 /// This is an expensive operation, only use it if it's really necessary.
1612 public static explicit operator MemberInfo [] (MemberList list)
1614 Timer.StartTimer (TimerType.MiscTimer);
1615 MemberInfo [] result = new MemberInfo [list.Count];
1616 list.CopyTo (result, 0);
1617 Timer.StopTimer (TimerType.MiscTimer);
1629 public bool IsSynchronized {
1631 return List.IsSynchronized;
1635 public object SyncRoot {
1637 return List.SyncRoot;
1641 public void CopyTo (Array array, int index)
1643 List.CopyTo (array, index);
1648 public IEnumerator GetEnumerator ()
1650 return List.GetEnumerator ();
1655 public bool IsFixedSize {
1661 public bool IsReadOnly {
1667 object IList.this [int index] {
1669 return List [index];
1673 throw new NotSupportedException ();
1677 // FIXME: try to find out whether we can avoid the cast in this indexer.
1678 public MemberInfo this [int index] {
1680 return (MemberInfo) List [index];
1684 public int Add (object value)
1686 throw new NotSupportedException ();
1689 public void Clear ()
1691 throw new NotSupportedException ();
1694 public bool Contains (object value)
1696 return List.Contains (value);
1699 public int IndexOf (object value)
1701 return List.IndexOf (value);
1704 public void Insert (int index, object value)
1706 throw new NotSupportedException ();
1709 public void Remove (object value)
1711 throw new NotSupportedException ();
1714 public void RemoveAt (int index)
1716 throw new NotSupportedException ();
1721 /// This interface is used to get all members of a class when creating the
1722 /// member cache. It must be implemented by all DeclSpace derivatives which
1723 /// want to support the member cache and by TypeHandle to get caching of
1724 /// non-dynamic types.
1726 public interface IMemberContainer {
1728 /// The name of the IMemberContainer. This is only used for
1729 /// debugging purposes.
1736 /// The type of this IMemberContainer.
1743 /// Returns the IMemberContainer of the parent class or null if this
1744 /// is an interface or TypeManger.object_type.
1745 /// This is used when creating the member cache for a class to get all
1746 /// members from the parent class.
1748 IMemberContainer Parent {
1753 /// Whether this is an interface.
1760 /// Returns all members of this class with the corresponding MemberTypes
1761 /// and BindingFlags.
1764 /// When implementing this method, make sure not to return any inherited
1765 /// members and check the MemberTypes and BindingFlags properly.
1766 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1767 /// get the BindingFlags (static/non-static,public/non-public) in the
1768 /// MemberInfo class, but the cache needs this information. That's why
1769 /// this method is called multiple times with different BindingFlags.
1771 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1774 /// Return the container's member cache.
1776 MemberCache MemberCache {
1782 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1783 /// member lookups. It has a member name based hash table; it maps each member
1784 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1785 /// and the BindingFlags that were initially used to get it. The cache contains
1786 /// all members of the current class and all inherited members. If this cache is
1787 /// for an interface types, it also contains all inherited members.
1789 /// There are two ways to get a MemberCache:
1790 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1791 /// use the DeclSpace.MemberCache property.
1792 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1793 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1795 public class MemberCache {
1796 public readonly IMemberContainer Container;
1797 protected Hashtable member_hash;
1798 protected Hashtable method_hash;
1801 /// Create a new MemberCache for the given IMemberContainer `container'.
1803 public MemberCache (IMemberContainer container)
1805 this.Container = container;
1807 Timer.IncrementCounter (CounterType.MemberCache);
1808 Timer.StartTimer (TimerType.CacheInit);
1812 // If we have a parent class (we have a parent class unless we're
1813 // TypeManager.object_type), we deep-copy its MemberCache here.
1814 if (Container.IsInterface) {
1817 if (Container.Parent != null)
1818 parent = Container.Parent.MemberCache;
1820 parent = TypeHandle.ObjectType.MemberCache;
1821 member_hash = SetupCacheForInterface (parent);
1822 } else if (Container.Parent != null)
1823 member_hash = SetupCache (Container.Parent.MemberCache);
1825 member_hash = new Hashtable ();
1827 // If this is neither a dynamic type nor an interface, create a special
1828 // method cache with all declared and inherited methods.
1829 Type type = container.Type;
1830 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1831 method_hash = new Hashtable ();
1835 // Add all members from the current class.
1836 AddMembers (Container);
1838 Timer.StopTimer (TimerType.CacheInit);
1842 /// Bootstrap this member cache by doing a deep-copy of our parent.
1844 Hashtable SetupCache (MemberCache parent)
1846 Hashtable hash = new Hashtable ();
1848 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1849 while (it.MoveNext ()) {
1850 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1858 /// Add the contents of `new_hash' to `hash'.
1860 void AddHashtable (Hashtable hash, MemberCache cache)
1862 Hashtable new_hash = cache.member_hash;
1863 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1864 while (it.MoveNext ()) {
1865 ArrayList list = (ArrayList) hash [it.Key];
1867 hash [it.Key] = list = new ArrayList ();
1869 foreach (CacheEntry entry in (ArrayList) it.Value) {
1870 if (entry.Container != cache.Container)
1878 /// Bootstrap the member cache for an interface type.
1879 /// Type.GetMembers() won't return any inherited members for interface types,
1880 /// so we need to do this manually. Interfaces also inherit from System.Object.
1882 Hashtable SetupCacheForInterface (MemberCache parent)
1884 Hashtable hash = SetupCache (parent);
1885 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1887 foreach (Type itype in ifaces) {
1888 IMemberContainer iface_container =
1889 TypeManager.LookupMemberContainer (itype);
1891 MemberCache iface_cache = iface_container.MemberCache;
1893 AddHashtable (hash, iface_cache);
1900 /// Add all members from class `container' to the cache.
1902 void AddMembers (IMemberContainer container)
1904 // We need to call AddMembers() with a single member type at a time
1905 // to get the member type part of CacheEntry.EntryType right.
1906 AddMembers (MemberTypes.Constructor, container);
1907 AddMembers (MemberTypes.Field, container);
1908 AddMembers (MemberTypes.Method, container);
1909 AddMembers (MemberTypes.Property, container);
1910 AddMembers (MemberTypes.Event, container);
1911 // Nested types are returned by both Static and Instance searches.
1912 AddMembers (MemberTypes.NestedType,
1913 BindingFlags.Static | BindingFlags.Public, container);
1914 AddMembers (MemberTypes.NestedType,
1915 BindingFlags.Static | BindingFlags.NonPublic, container);
1918 void AddMembers (MemberTypes mt, IMemberContainer container)
1920 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1921 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1922 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1923 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1927 /// Add all members from class `container' with the requested MemberTypes and
1928 /// BindingFlags to the cache. This method is called multiple times with different
1929 /// MemberTypes and BindingFlags.
1931 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1933 MemberList members = container.GetMembers (mt, bf);
1935 foreach (MemberInfo member in members) {
1936 string name = member.Name;
1938 int pos = name.IndexOf ('<');
1940 name = name.Substring (0, pos);
1942 // We use a name-based hash table of ArrayList's.
1943 ArrayList list = (ArrayList) member_hash [name];
1945 list = new ArrayList ();
1946 member_hash.Add (name, list);
1949 // When this method is called for the current class, the list will
1950 // already contain all inherited members from our parent classes.
1951 // We cannot add new members in front of the list since this'd be an
1952 // expensive operation, that's why the list is sorted in reverse order
1953 // (ie. members from the current class are coming last).
1954 list.Add (new CacheEntry (container, member, mt, bf));
1959 /// Add all declared and inherited methods from class `type' to the method cache.
1961 void AddMethods (Type type)
1963 AddMethods (BindingFlags.Static | BindingFlags.Public |
1964 BindingFlags.FlattenHierarchy, type);
1965 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1966 BindingFlags.FlattenHierarchy, type);
1967 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1968 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1971 void AddMethods (BindingFlags bf, Type type)
1973 MemberInfo [] members = type.GetMethods (bf);
1975 Array.Reverse (members);
1977 foreach (MethodBase member in members) {
1978 string name = member.Name;
1980 // We use a name-based hash table of ArrayList's.
1981 ArrayList list = (ArrayList) method_hash [name];
1983 list = new ArrayList ();
1984 method_hash.Add (name, list);
1987 // Unfortunately, the elements returned by Type.GetMethods() aren't
1988 // sorted so we need to do this check for every member.
1989 BindingFlags new_bf = bf;
1990 if (member.DeclaringType == type)
1991 new_bf |= BindingFlags.DeclaredOnly;
1993 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1998 /// Compute and return a appropriate `EntryType' magic number for the given
1999 /// MemberTypes and BindingFlags.
2001 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
2003 EntryType type = EntryType.None;
2005 if ((mt & MemberTypes.Constructor) != 0)
2006 type |= EntryType.Constructor;
2007 if ((mt & MemberTypes.Event) != 0)
2008 type |= EntryType.Event;
2009 if ((mt & MemberTypes.Field) != 0)
2010 type |= EntryType.Field;
2011 if ((mt & MemberTypes.Method) != 0)
2012 type |= EntryType.Method;
2013 if ((mt & MemberTypes.Property) != 0)
2014 type |= EntryType.Property;
2015 // Nested types are returned by static and instance searches.
2016 if ((mt & MemberTypes.NestedType) != 0)
2017 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
2019 if ((bf & BindingFlags.Instance) != 0)
2020 type |= EntryType.Instance;
2021 if ((bf & BindingFlags.Static) != 0)
2022 type |= EntryType.Static;
2023 if ((bf & BindingFlags.Public) != 0)
2024 type |= EntryType.Public;
2025 if ((bf & BindingFlags.NonPublic) != 0)
2026 type |= EntryType.NonPublic;
2027 if ((bf & BindingFlags.DeclaredOnly) != 0)
2028 type |= EntryType.Declared;
2034 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2035 /// denote multiple member types. Returns true if the given flags value denotes a
2036 /// single member types.
2038 public static bool IsSingleMemberType (MemberTypes mt)
2041 case MemberTypes.Constructor:
2042 case MemberTypes.Event:
2043 case MemberTypes.Field:
2044 case MemberTypes.Method:
2045 case MemberTypes.Property:
2046 case MemberTypes.NestedType:
2055 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2056 /// number to speed up the searching process.
2059 protected enum EntryType {
2064 MaskStatic = Instance|Static,
2068 MaskProtection = Public|NonPublic,
2072 Constructor = 0x020,
2079 MaskType = Constructor|Event|Field|Method|Property|NestedType
2082 protected struct CacheEntry {
2083 public readonly IMemberContainer Container;
2084 public readonly EntryType EntryType;
2085 public readonly MemberInfo Member;
2087 public CacheEntry (IMemberContainer container, MemberInfo member,
2088 MemberTypes mt, BindingFlags bf)
2090 this.Container = container;
2091 this.Member = member;
2092 this.EntryType = GetEntryType (mt, bf);
2097 /// This is called each time we're walking up one level in the class hierarchy
2098 /// and checks whether we can abort the search since we've already found what
2099 /// we were looking for.
2101 protected bool DoneSearching (ArrayList list)
2104 // We've found exactly one member in the current class and it's not
2105 // a method or constructor.
2107 if (list.Count == 1 && !(list [0] is MethodBase))
2111 // Multiple properties: we query those just to find out the indexer
2114 if ((list.Count > 0) && (list [0] is PropertyInfo))
2121 /// Looks up members with name `name'. If you provide an optional
2122 /// filter function, it'll only be called with members matching the
2123 /// requested member name.
2125 /// This method will try to use the cache to do the lookup if possible.
2127 /// Unlike other FindMembers implementations, this method will always
2128 /// check all inherited members - even when called on an interface type.
2130 /// If you know that you're only looking for methods, you should use
2131 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2132 /// When doing a method-only search, it'll try to use a special method
2133 /// cache (unless it's a dynamic type or an interface) and the returned
2134 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2135 /// The lookup process will automatically restart itself in method-only
2136 /// search mode if it discovers that it's about to return methods.
2138 ArrayList global = new ArrayList ();
2139 bool using_global = false;
2141 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2143 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2144 MemberFilter filter, object criteria)
2147 throw new Exception ();
2149 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2150 bool method_search = mt == MemberTypes.Method;
2151 // If we have a method cache and we aren't already doing a method-only search,
2152 // then we restart a method search if the first match is a method.
2153 bool do_method_search = !method_search && (method_hash != null);
2155 ArrayList applicable;
2157 // If this is a method-only search, we try to use the method cache if
2158 // possible; a lookup in the method cache will return a MemberInfo with
2159 // the correct ReflectedType for inherited methods.
2161 if (method_search && (method_hash != null))
2162 applicable = (ArrayList) method_hash [name];
2164 applicable = (ArrayList) member_hash [name];
2166 if (applicable == null)
2167 return emptyMemberInfo;
2170 // 32 slots gives 53 rss/54 size
2171 // 2/4 slots gives 55 rss
2173 // Strange: from 25,000 calls, only 1,800
2174 // are above 2. Why does this impact it?
2177 using_global = true;
2179 Timer.StartTimer (TimerType.CachedLookup);
2181 EntryType type = GetEntryType (mt, bf);
2183 IMemberContainer current = Container;
2186 // `applicable' is a list of all members with the given member name `name'
2187 // in the current class and all its parent classes. The list is sorted in
2188 // reverse order due to the way how the cache is initialy created (to speed
2189 // things up, we're doing a deep-copy of our parent).
2191 for (int i = applicable.Count-1; i >= 0; i--) {
2192 CacheEntry entry = (CacheEntry) applicable [i];
2194 // This happens each time we're walking one level up in the class
2195 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2196 // the first time this happens (this may already happen in the first
2197 // iteration of this loop if there are no members with the name we're
2198 // looking for in the current class).
2199 if (entry.Container != current) {
2200 if (declared_only || DoneSearching (global))
2203 current = entry.Container;
2206 // Is the member of the correct type ?
2207 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2210 // Is the member static/non-static ?
2211 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2214 // Apply the filter to it.
2215 if (filter (entry.Member, criteria)) {
2216 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2217 do_method_search = false;
2218 global.Add (entry.Member);
2222 Timer.StopTimer (TimerType.CachedLookup);
2224 // If we have a method cache and we aren't already doing a method-only
2225 // search, we restart in method-only search mode if the first match is
2226 // a method. This ensures that we return a MemberInfo with the correct
2227 // ReflectedType for inherited methods.
2228 if (do_method_search && (global.Count > 0)){
2229 using_global = false;
2231 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2234 using_global = false;
2235 MemberInfo [] copy = new MemberInfo [global.Count];
2236 global.CopyTo (copy);
2241 // This finds the method or property for us to override. invocationType is the type where
2242 // the override is going to be declared, name is the name of the method/property, and
2243 // paramTypes is the parameters, if any to the method or property
2245 // Because the MemberCache holds members from this class and all the base classes,
2246 // we can avoid tons of reflection stuff.
2248 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2250 ArrayList applicable;
2251 if (method_hash != null && !is_property)
2252 applicable = (ArrayList) method_hash [name];
2254 applicable = (ArrayList) member_hash [name];
2256 if (applicable == null)
2259 // Walk the chain of methods, starting from the top.
2261 for (int i = applicable.Count - 1; i >= 0; i--) {
2262 CacheEntry entry = (CacheEntry) applicable [i];
2264 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2267 PropertyInfo pi = null;
2268 MethodInfo mi = null;
2269 FieldInfo fi = null;
2270 Type [] cmpAttrs = null;
2273 if ((entry.EntryType & EntryType.Field) != 0) {
2274 fi = (FieldInfo)entry.Member;
2276 // TODO: For this case we ignore member type
2277 //fb = TypeManager.GetField (fi);
2278 //cmpAttrs = new Type[] { fb.MemberType };
2280 pi = (PropertyInfo) entry.Member;
2281 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2284 mi = (MethodInfo) entry.Member;
2285 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2289 // TODO: Almost duplicate !
2291 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2292 case FieldAttributes.Private:
2294 // A private method is Ok if we are a nested subtype.
2295 // The spec actually is not very clear about this, see bug 52458.
2297 if (invocationType != entry.Container.Type &
2298 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2302 case FieldAttributes.FamANDAssem:
2303 case FieldAttributes.Assembly:
2305 // Check for assembly methods
2307 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2311 return entry.Member;
2315 // Check the arguments
2317 if (cmpAttrs.Length != paramTypes.Length)
2320 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2321 if (!paramTypes [j].Equals (cmpAttrs [j]))
2326 // get one of the methods because this has the visibility info.
2329 mi = pi.GetGetMethod (true);
2331 mi = pi.GetSetMethod (true);
2337 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2338 case MethodAttributes.Private:
2340 // A private method is Ok if we are a nested subtype.
2341 // The spec actually is not very clear about this, see bug 52458.
2343 if (invocationType == entry.Container.Type ||
2344 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2345 return entry.Member;
2348 case MethodAttributes.FamANDAssem:
2349 case MethodAttributes.Assembly:
2351 // Check for assembly methods
2353 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2354 return entry.Member;
2359 // A protected method is ok, because we are overriding.
2360 // public is always ok.
2362 return entry.Member;