2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
15 using System.Collections;
16 using System.Reflection.Emit;
17 using System.Reflection;
19 namespace Mono.CSharp {
21 public class TypeName {
22 public readonly string Name;
23 public readonly TypeArguments TypeArguments;
25 public readonly TypeName Left;
27 public static readonly TypeName Null = new TypeName ("");
29 public TypeName (string name)
34 public TypeName (string name, TypeArguments args)
37 this.TypeArguments = args;
40 public TypeName (TypeName left, string name, TypeArguments args)
46 public string GetName ()
49 return Left.GetName () + "." + Name;
54 public int CountTypeArguments {
56 if (TypeArguments == null)
59 return TypeArguments.Count;
63 public string GetFullName ()
66 if (TypeArguments != null)
67 full_name = Name + "<" + TypeArguments + ">";
71 return Left.GetFullName () + "." + full_name;
76 public string GetTypeName (bool full)
79 if (full && (TypeArguments != null))
80 suffix = "!" + TypeArguments.Count;
82 return Left.GetTypeName (full) + "." + Name + suffix;
87 public Expression GetTypeExpression (Location loc)
90 Expression lexpr = Left.GetTypeExpression (loc);
92 return new MemberAccess (lexpr, Name, TypeArguments, loc);
94 if (TypeArguments != null)
95 return new ConstructedType (Name, TypeArguments, loc);
97 return new SimpleName (Name, loc);
101 public MemberName GetMemberName ()
103 if (TypeArguments != null) {
104 string[] type_params = TypeArguments.GetDeclarations ();
105 return new MemberName (Left, Name, type_params);
107 return new MemberName (Left, Name);
110 public override string ToString ()
113 if (TypeArguments != null)
114 full_name = Name + "<" + TypeArguments + ">";
119 return Left + "." + full_name;
125 public class MemberName {
126 public readonly TypeName TypeName;
127 public readonly string Name;
128 public readonly string[] TypeParameters;
130 public MemberName (string name)
135 public MemberName (TypeName type, string name)
137 this.TypeName = type;
141 public MemberName (TypeName type, MemberName name)
143 this.TypeName = type;
144 this.Name = name.Name;
145 this.TypeParameters = name.TypeParameters;
148 public MemberName (TypeName type, string name, ArrayList type_params)
151 if (type_params != null) {
152 TypeParameters = new string [type_params.Count];
153 type_params.CopyTo (TypeParameters, 0);
157 public MemberName (TypeName type, string name, string[] type_params)
160 this.TypeParameters = type_params;
163 public TypeName MakeTypeName (Location loc)
165 if (TypeParameters != null) {
166 TypeArguments args = new TypeArguments (loc);
167 foreach (string param in TypeParameters)
168 args.Add (new SimpleName (param, loc));
169 return new TypeName (TypeName, Name, args);
172 return new TypeName (TypeName, Name, null);
175 public static readonly MemberName Null = new MemberName ("");
177 public string Basename {
179 if (TypeParameters != null)
180 return Name + "!" + TypeParameters.Length;
186 public string GetName (bool is_generic)
188 string name = is_generic ? Basename : Name;
189 if (TypeName != null)
190 return TypeName.GetTypeName (is_generic) + "." + name;
195 public int CountTypeParameters {
197 if (TypeParameters != null)
200 return TypeParameters.Length;
204 protected string PrintTypeParams ()
206 if (TypeParameters != null) {
207 StringBuilder sb = new StringBuilder ();
209 for (int i = 0; i < TypeParameters.Length; i++) {
212 sb.Append (TypeParameters [i]);
215 return sb.ToString ();
221 public string FullName {
223 string full_name = Name + PrintTypeParams ();
225 if (TypeName != null)
226 return TypeName + "." + full_name;
232 public override string ToString ()
234 return String.Format ("MemberName [{0}:{1}:{2}]",
235 TypeName, Name, PrintTypeParams ());
240 /// Base representation for members. This is used to keep track
241 /// of Name, Location and Modifier flags, and handling Attributes.
243 public abstract class MemberCore : Attributable {
249 public readonly MemberName MemberName;
252 /// Modifier flags that the user specified in the source code
257 /// Location where this declaration happens
259 public readonly Location Location;
263 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
264 Obsolete = 1 << 1, // Type has obsolete attribute
265 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
266 ClsCompliant = 1 << 3, // Type is CLS Compliant
267 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
268 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
269 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
270 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
274 /// MemberCore flags at first detected then cached
276 protected Flags caching_flags;
278 public MemberCore (MemberName name, Attributes attrs, Location loc)
281 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
284 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected;
287 public abstract bool Define (TypeContainer parent);
290 // Returns full member name for error message
292 public virtual string GetSignatureForError ()
298 /// Base Emit method. This is also entry point for CLS-Compliant verification.
300 public virtual void Emit (TypeContainer container)
302 if (!RootContext.VerifyClsCompliance)
305 VerifyClsCompliance (container);
309 // Whehter is it ok to use an unsafe pointer in this type container
311 public bool UnsafeOK (DeclSpace parent)
314 // First check if this MemberCore modifier flags has unsafe set
316 if ((ModFlags & Modifiers.UNSAFE) != 0)
319 if (parent.UnsafeContext)
322 Expression.UnsafeError (Location);
327 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
329 public override bool IsClsCompliaceRequired (DeclSpace container)
331 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
332 return (caching_flags & Flags.ClsCompliant) != 0;
334 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
335 caching_flags &= ~Flags.ClsCompliance_Undetected;
336 caching_flags |= Flags.ClsCompliant;
340 caching_flags &= ~Flags.ClsCompliance_Undetected;
345 /// Returns true when MemberCore is exposed from assembly.
347 protected bool IsExposedFromAssembly (DeclSpace ds)
349 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
352 DeclSpace parentContainer = ds;
353 while (parentContainer != null && parentContainer.ModFlags != 0) {
354 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
356 parentContainer = parentContainer.Parent;
362 /// Resolve CLSCompliantAttribute value or gets cached value.
364 bool GetClsCompliantAttributeValue (DeclSpace ds)
366 if (OptAttributes != null) {
367 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
368 null, null, ds.ModFlags, false);
369 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
370 if (cls_attribute != null) {
371 caching_flags |= Flags.HasClsCompliantAttribute;
372 return cls_attribute.GetClsCompliantAttributeValue (ds);
375 return ds.GetClsCompliantAttributeValue ();
379 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
381 protected bool HasClsCompliantAttribute {
383 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
388 /// This method is used to testing error 3005 (Method or parameter name collision).
390 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
393 /// Common helper method for identifier and parameters CLS-Compliant testing.
394 /// When return false error 3005 is reported. True means no violation.
395 /// And error 3006 tests are peformed here because of speed.
397 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
399 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
400 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
405 bool error3006 = false;
406 for (int i = 0; i < ml.Count; ++i) {
407 MemberInfo mi = ml [i];
408 if (name == mi.Name) {
409 MethodBase method = mi as MethodBase;
410 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
413 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
421 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
422 // because BindingFlags.Public returns internal types too
423 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
425 // Type is external, we can get attribute directly
426 if (temp_ds == null) {
427 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
428 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
431 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
433 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
434 if (!mc.IsClsCompliaceRequired (ds))
438 for (int ii = 0; ii < ml.Count; ++ii) {
442 Report.SymbolRelatedToPreviousError (mi);
446 Report.Error_T (3006, Location, GetSignatureForError ());
455 /// The main virtual method for CLS-Compliant verifications.
456 /// The method returns true if member is CLS-Compliant and false if member is not
457 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
458 /// and add their extra verifications.
460 protected virtual bool VerifyClsCompliance (DeclSpace ds)
462 if (!IsClsCompliaceRequired (ds)) {
463 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
464 Report.Warning_T (3019, Location, GetSignatureForError ());
469 if (!CodeGen.Assembly.IsClsCompliant) {
470 if (HasClsCompliantAttribute) {
471 Report.Error_T (3014, Location, GetSignatureForError ());
475 int index = Name.LastIndexOf ('.');
476 if (Name [index > 0 ? index + 1 : 0] == '_') {
477 Report.Error_T (3008, Location, GetSignatureForError () );
480 if (!IsIdentifierClsCompliant (ds)) {
481 Report.Error_T (3005, Location, GetSignatureForError ());
490 /// Base class for structs, classes, enumerations and interfaces.
493 /// They all create new declaration spaces. This
494 /// provides the common foundation for managing those name
497 public abstract class DeclSpace : MemberCore, IAlias {
499 /// This points to the actual definition that is being
500 /// created with System.Reflection.Emit
502 public TypeBuilder TypeBuilder;
505 /// If we are a generic type, this is the type we are
506 /// currently defining. We need to lookup members on this
507 /// instead of the TypeBuilder.
509 public TypeExpr CurrentType;
512 // This is the namespace in which this typecontainer
513 // was declared. We use this to resolve names.
515 public NamespaceEntry NamespaceEntry;
517 public Hashtable Cache = new Hashtable ();
519 public string Basename;
522 /// defined_names is used for toplevel objects
524 protected Hashtable defined_names;
526 readonly bool is_generic;
527 readonly int count_type_params;
530 // Whether we are Generic
532 public bool IsGeneric {
536 else if (parent != null)
537 return parent.IsGeneric;
543 TypeContainer parent;
545 static string[] attribute_targets = new string [] { "type" };
547 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
548 Attributes attrs, Location l)
549 : base (name, attrs, l)
552 Basename = name.Name;
553 defined_names = new Hashtable ();
554 if (name.TypeParameters != null) {
556 count_type_params = name.TypeParameters.Length;
559 count_type_params += parent.count_type_params;
560 this.parent = parent;
563 public void RecordDecl ()
565 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
566 NamespaceEntry.DefineName (MemberName.Basename, this);
570 /// The result value from adding an declaration into
571 /// a struct or a class
573 public enum AdditionResult {
575 /// The declaration has been successfully
576 /// added to the declation space.
581 /// The symbol has already been defined.
586 /// Returned if the declation being added to the
587 /// name space clashes with its container name.
589 /// The only exceptions for this are constructors
590 /// and static constructors
595 /// Returned if a constructor was created (because syntactically
596 /// it looked like a constructor) but was not (because the name
597 /// of the method is not the same as the container class
602 /// This is only used by static constructors to emit the
603 /// error 111, but this error for other things really
604 /// happens at another level for other functions.
609 /// Some other error.
615 /// Returns a status code based purely on the name
616 /// of the member being added
618 protected AdditionResult IsValid (string basename, string name)
620 if (basename == Basename)
621 return AdditionResult.EnclosingClash;
623 if (defined_names.Contains (name))
624 return AdditionResult.NameExists;
626 return AdditionResult.Success;
629 public static int length;
630 public static int small;
633 /// Introduce @name into this declaration space and
634 /// associates it with the object @o. Note that for
635 /// methods this will just point to the first method. o
637 public void DefineName (string name, object o)
639 defined_names.Add (name, o);
642 int p = name.LastIndexOf ('.');
650 /// Returns the object associated with a given name in the declaration
651 /// space. This is the inverse operation of `DefineName'
653 public object GetDefinition (string name)
655 return defined_names [name];
658 bool in_transit = false;
661 /// This function is used to catch recursive definitions
664 public bool InTransit {
674 public TypeContainer Parent {
681 /// Looks up the alias for the name
683 public IAlias LookupAlias (string name)
685 if (NamespaceEntry != null)
686 return NamespaceEntry.LookupAlias (name);
692 // root_types contains all the types. All TopLevel types
693 // hence have a parent that points to `root_types', that is
694 // why there is a non-obvious test down here.
696 public bool IsTopLevel {
699 if (parent.parent == null)
706 public virtual void CloseType ()
708 if ((caching_flags & Flags.CloseTypeCreated) == 0){
710 TypeBuilder.CreateType ();
713 // The try/catch is needed because
714 // nested enumerations fail to load when they
717 // Even if this is the right order (enumerations
718 // declared after types).
720 // Note that this still creates the type and
721 // it is possible to save it
723 caching_flags |= Flags.CloseTypeCreated;
728 /// Should be overriten by the appropriate declaration space
730 public abstract TypeBuilder DefineType ();
733 /// Define all members, but don't apply any attributes or do anything which may
734 /// access not-yet-defined classes. This method also creates the MemberCache.
736 public abstract bool DefineMembers (TypeContainer parent);
739 // Whether this is an `unsafe context'
741 public bool UnsafeContext {
743 if ((ModFlags & Modifiers.UNSAFE) != 0)
746 return parent.UnsafeContext;
751 public static string MakeFQN (string nsn, string name)
755 return String.Concat (nsn, ".", name);
758 EmitContext type_resolve_ec;
759 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
761 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
762 type_resolve_ec.ResolvingTypeTree = true;
764 return type_resolve_ec;
768 // Looks up the type, as parsed into the expression `e'
770 public Type ResolveType (Expression e, bool silent, Location loc)
772 TypeExpr d = ResolveTypeExpr (e, silent, loc);
776 return ResolveType (d, loc);
779 public Type ResolveType (TypeExpr d, Location loc)
781 if (!d.CheckAccessLevel (this)) {
782 Report. Error (122, loc, "`" + d.Name + "' " +
783 "is inaccessible because of its protection level");
787 Type t = d.ResolveType (type_resolve_ec);
791 TypeContainer tc = TypeManager.LookupTypeContainer (t);
792 if ((tc != null) && tc.IsGeneric) {
794 int tnum = TypeManager.GetNumberOfTypeArguments (t);
795 Report.Error (305, loc,
796 "Using the generic type `{0}' " +
797 "requires {1} type arguments",
798 TypeManager.GetFullName (t), tnum);
802 ConstructedType ctype = new ConstructedType (
803 t, TypeParameters, loc);
805 t = ctype.ResolveType (type_resolve_ec);
812 // Resolves the expression `e' for a type, and will recursively define
815 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
817 if (type_resolve_ec == null)
818 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
819 type_resolve_ec.loc = loc;
820 if (this is GenericMethod)
821 type_resolve_ec.ContainerType = Parent.TypeBuilder;
823 type_resolve_ec.ContainerType = TypeBuilder;
825 int errors = Report.Errors;
827 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
829 if ((d != null) && (d.eclass == ExprClass.Type))
832 if (silent || (Report.Errors != errors))
835 if (e is SimpleName){
836 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
837 d = s.ResolveAsTypeTerminal (type_resolve_ec);
839 if ((d == null) || (d.Type == null)) {
840 Report.Error (246, loc, "Cannot find type `{0}'", e);
844 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
847 Report.Error (308, loc,
848 "The non-generic type `{0}' cannot " +
849 "be used with type arguments.",
850 TypeManager.CSharpName (d.Type));
854 Report.Error (305, loc,
855 "Using the generic type `{0}' " +
856 "requires {1} type arguments",
857 TypeManager.GetFullName (d.Type), num_args);
861 Report.Error (246, loc, "Cannot find type `{0}'", e);
865 public bool CheckAccessLevel (Type check_type)
868 if (this is GenericMethod)
869 tb = Parent.TypeBuilder;
873 if (check_type.IsGenericInstance)
874 check_type = check_type.GetGenericTypeDefinition ();
876 if (check_type == tb)
879 if (check_type.IsGenericParameter)
880 return true; // FIXME
882 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
885 // Broken Microsoft runtime, return public for arrays, no matter what
886 // the accessibility is for their underlying class, and they return
887 // NonPublic visibility for pointers
889 if (check_type.IsArray || check_type.IsPointer)
890 return CheckAccessLevel (TypeManager.GetElementType (check_type));
893 case TypeAttributes.Public:
896 case TypeAttributes.NotPublic:
898 // In same cases is null.
899 if (TypeBuilder == null)
903 // This test should probably use the declaringtype.
905 return check_type.Assembly == TypeBuilder.Assembly;
907 case TypeAttributes.NestedPublic:
910 case TypeAttributes.NestedPrivate:
911 string check_type_name = check_type.FullName;
912 string type_name = CurrentType != null ?
913 CurrentType.Name : tb.FullName;
915 int cio = check_type_name.LastIndexOf ('+');
916 string container = check_type_name.Substring (0, cio);
919 // Check if the check_type is a nested class of the current type
921 if (check_type_name.StartsWith (type_name + "+")){
925 if (type_name.StartsWith (container)){
931 case TypeAttributes.NestedFamily:
933 // Only accessible to methods in current type or any subtypes
935 return FamilyAccessible (tb, check_type);
937 case TypeAttributes.NestedFamANDAssem:
938 return (check_type.Assembly == tb.Assembly) &&
939 FamilyAccessible (tb, check_type);
941 case TypeAttributes.NestedFamORAssem:
942 return (check_type.Assembly == tb.Assembly) ||
943 FamilyAccessible (tb, check_type);
945 case TypeAttributes.NestedAssembly:
946 return check_type.Assembly == tb.Assembly;
949 Console.WriteLine ("HERE: " + check_attr);
954 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
956 Type declaring = check_type.DeclaringType;
957 if (tb.IsSubclassOf (declaring))
960 string check_type_name = check_type.FullName;
962 int cio = check_type_name.LastIndexOf ('+');
963 string container = check_type_name.Substring (0, cio);
966 // Check if the check_type is a nested class of the current type
968 if (check_type_name.StartsWith (container + "+"))
974 // Access level of a type.
976 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
977 // Public Assembly Protected
978 Protected = (0 << 0) | (0 << 1) | (X << 2),
979 Public = (X << 0) | (X << 1) | (X << 2),
980 Private = (0 << 0) | (0 << 1) | (0 << 2),
981 Internal = (0 << 0) | (X << 1) | (0 << 2),
982 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
985 static AccessLevel GetAccessLevelFromModifiers (int flags)
987 if ((flags & Modifiers.INTERNAL) != 0) {
989 if ((flags & Modifiers.PROTECTED) != 0)
990 return AccessLevel.ProtectedOrInternal;
992 return AccessLevel.Internal;
994 } else if ((flags & Modifiers.PROTECTED) != 0)
995 return AccessLevel.Protected;
996 else if ((flags & Modifiers.PRIVATE) != 0)
997 return AccessLevel.Private;
999 return AccessLevel.Public;
1002 // What is the effective access level of this?
1003 // TODO: Cache this?
1004 AccessLevel EffectiveAccessLevel {
1006 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1007 if (!IsTopLevel && (Parent != null))
1008 return myAccess & Parent.EffectiveAccessLevel;
1013 // Return the access level for type `t'
1014 static AccessLevel TypeEffectiveAccessLevel (Type t)
1017 return AccessLevel.Public;
1018 if (t.IsNestedPrivate)
1019 return AccessLevel.Private;
1021 return AccessLevel.Internal;
1023 // By now, it must be nested
1024 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1026 if (t.IsNestedPublic)
1028 if (t.IsNestedAssembly)
1029 return parentLevel & AccessLevel.Internal;
1030 if (t.IsNestedFamily)
1031 return parentLevel & AccessLevel.Protected;
1032 if (t.IsNestedFamORAssem)
1033 return parentLevel & AccessLevel.ProtectedOrInternal;
1034 if (t.IsNestedFamANDAssem)
1035 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1037 // nested private is taken care of
1039 throw new Exception ("I give up, what are you?");
1043 // This answers `is the type P, as accessible as a member M which has the
1044 // accessability @flags which is declared as a nested member of the type T, this declspace'
1046 public bool AsAccessible (Type p, int flags)
1048 if (p.IsGenericParameter)
1049 return true; // FIXME
1052 // 1) if M is private, its accessability is the same as this declspace.
1053 // we already know that P is accessible to T before this method, so we
1057 if ((flags & Modifiers.PRIVATE) != 0)
1060 while (p.IsArray || p.IsPointer || p.IsByRef)
1061 p = TypeManager.GetElementType (p);
1063 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1064 AccessLevel mAccess = this.EffectiveAccessLevel &
1065 GetAccessLevelFromModifiers (flags);
1067 // for every place from which we can access M, we must
1068 // be able to access P as well. So, we want
1069 // For every bit in M and P, M_i -> P_1 == true
1070 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1072 return ~ (~ mAccess | pAccess) == 0;
1075 static DoubleHash dh = new DoubleHash (1000);
1077 Type DefineTypeAndParents (DeclSpace tc)
1079 DeclSpace container = tc.Parent;
1081 if (container.TypeBuilder == null && container.Name != "")
1082 DefineTypeAndParents (container);
1084 return tc.DefineType ();
1087 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1095 if (dh.Lookup (ns, name, out r))
1099 if (Namespace.IsNamespace (ns)){
1100 string fullname = (ns != "") ? ns + "." + name : name;
1101 t = TypeManager.LookupType (fullname);
1105 t = TypeManager.LookupType (name);
1109 dh.Insert (ns, name, t);
1114 // In case we are fed a composite name, normalize it.
1116 int p = name.LastIndexOf ('.');
1118 ns = MakeFQN (ns, name.Substring (0, p));
1119 name = name.Substring (p+1);
1122 parent = RootContext.Tree.LookupByNamespace (ns, name);
1123 if (parent == null) {
1124 dh.Insert (ns, name, null);
1128 t = DefineTypeAndParents (parent);
1134 dh.Insert (ns, name, t);
1138 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1140 Report.Error (104, loc,
1141 "`{0}' is an ambiguous reference ({1} or {2})",
1145 public Type FindNestedType (Location loc, string name,
1146 out DeclSpace containing_ds)
1151 containing_ds = this;
1152 while (containing_ds != null){
1153 Type container_type = containing_ds.TypeBuilder;
1154 Type current_type = container_type;
1156 while (current_type != null && current_type != TypeManager.object_type) {
1157 string pre = current_type.FullName;
1159 t = LookupInterfaceOrClass (pre, name, out error);
1163 if ((t != null) && containing_ds.CheckAccessLevel (t))
1166 current_type = current_type.BaseType;
1168 containing_ds = containing_ds.Parent;
1175 /// GetType is used to resolve type names at the DeclSpace level.
1176 /// Use this to lookup class/struct bases, interface bases or
1177 /// delegate type references
1181 /// Contrast this to LookupType which is used inside method bodies to
1182 /// lookup types that have already been defined. GetType is used
1183 /// during the tree resolution process and potentially define
1184 /// recursively the type
1186 public Type FindType (Location loc, string name)
1192 // For the case the type we are looking for is nested within this one
1193 // or is in any base class
1195 DeclSpace containing_ds = this;
1197 while (containing_ds != null){
1198 Type container_type = containing_ds.TypeBuilder;
1199 Type current_type = container_type;
1201 while (current_type != null && current_type != TypeManager.object_type) {
1202 string pre = current_type.FullName;
1204 t = LookupInterfaceOrClass (pre, name, out error);
1208 if ((t != null) && containing_ds.CheckAccessLevel (t))
1211 current_type = current_type.BaseType;
1213 containing_ds = containing_ds.Parent;
1217 // Attempt to lookup the class on our namespace and all it's implicit parents
1219 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1220 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1229 // Attempt to do a direct unqualified lookup
1231 t = LookupInterfaceOrClass ("", name, out error);
1239 // Attempt to lookup the class on any of the `using'
1243 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1245 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1253 // Now check the using clause list
1256 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1257 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1261 if (match != null) {
1263 if (CheckAccessLevel (match)) {
1264 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1277 //Report.Error (246, Location, "Can not find type `"+name+"'");
1282 /// This function is broken and not what you're looking for. It should only
1283 /// be used while the type is still being created since it doesn't use the cache
1284 /// and relies on the filter doing the member name check.
1286 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1287 MemberFilter filter, object criteria);
1290 /// If we have a MemberCache, return it. This property may return null if the
1291 /// class doesn't have a member cache or while it's still being created.
1293 public abstract MemberCache MemberCache {
1297 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1300 TypeBuilder.SetCustomAttribute (cb);
1301 } catch (System.ArgumentException e) {
1302 Report.Warning (-21, a.Location,
1303 "The CharSet named property on StructLayout\n"+
1304 "\tdoes not work correctly on Microsoft.NET\n"+
1305 "\tYou might want to remove the CharSet declaration\n"+
1306 "\tor compile using the Mono runtime instead of the\n"+
1307 "\tMicrosoft .NET runtime\n"+
1308 "\tThe runtime gave the error: " + e);
1313 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1314 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1316 public bool GetClsCompliantAttributeValue ()
1318 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1319 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1321 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1323 if (OptAttributes != null) {
1324 EmitContext ec = new EmitContext (parent, this, Location,
1325 null, null, ModFlags, false);
1326 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1327 if (cls_attribute != null) {
1328 caching_flags |= Flags.HasClsCompliantAttribute;
1329 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1330 caching_flags |= Flags.ClsCompliantAttributeTrue;
1337 if (parent == null) {
1338 if (CodeGen.Assembly.IsClsCompliant) {
1339 caching_flags |= Flags.ClsCompliantAttributeTrue;
1345 if (parent.GetClsCompliantAttributeValue ()) {
1346 caching_flags |= Flags.ClsCompliantAttributeTrue;
1353 // Tests container name for CLS-Compliant name (differing only in case)
1354 // Possible optimalization: search in same namespace only
1355 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1357 int l = Name.Length;
1359 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1360 // Seek through all imported types
1361 foreach (string type_name in TypeManager.all_imported_types.Keys)
1363 if (l != type_name.Length)
1366 if (String.Compare (Name, type_name, true) == 0 &&
1367 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1368 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1374 // Seek through generated types
1375 foreach (string name in RootContext.Tree.Decls.Keys) {
1376 if (l != name.Length)
1379 if (String.Compare (Name, name, true) == 0) {
1384 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1385 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1386 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1396 // Extensions for generics
1398 TypeParameter[] type_params;
1399 TypeParameter[] type_param_list;
1401 protected string GetInstantiationName ()
1403 StringBuilder sb = new StringBuilder (Name);
1405 for (int i = 0; i < type_param_list.Length; i++) {
1408 sb.Append (type_param_list [i].Name);
1411 return sb.ToString ();
1414 bool check_type_parameter (ArrayList list, int start, string name)
1416 for (int i = 0; i < start; i++) {
1417 TypeParameter param = (TypeParameter) list [i];
1419 if (param.Name != name)
1422 if (RootContext.WarningLevel >= 3)
1425 "Type parameter `{0}' has same name " +
1426 "as type parameter from outer type `{1}'",
1427 name, parent.GetInstantiationName ());
1435 TypeParameter[] initialize_type_params ()
1437 if (type_param_list != null)
1438 return type_param_list;
1440 DeclSpace the_parent = parent;
1441 if (this is GenericMethod)
1445 TypeParameter[] parent_params = null;
1446 if ((the_parent != null) && the_parent.IsGeneric) {
1447 parent_params = the_parent.initialize_type_params ();
1448 start = parent_params != null ? parent_params.Length : 0;
1451 ArrayList list = new ArrayList ();
1452 if (parent_params != null)
1453 list.AddRange (parent_params);
1455 int count = type_params != null ? type_params.Length : 0;
1456 for (int i = 0; i < count; i++) {
1457 TypeParameter param = type_params [i];
1458 check_type_parameter (list, start, param.Name);
1462 type_param_list = new TypeParameter [list.Count];
1463 list.CopyTo (type_param_list, 0);
1464 return type_param_list;
1467 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1470 if (constraints_list != null) {
1472 80, Location, "Contraints are not allowed " +
1473 "on non-generic declarations");
1474 return AdditionResult.Error;
1477 return AdditionResult.Success;
1480 type_params = new TypeParameter [MemberName.TypeParameters.Length];
1483 // Register all the names
1485 for (int i = 0; i < MemberName.TypeParameters.Length; i++) {
1486 string name = MemberName.TypeParameters [i];
1488 AdditionResult res = IsValid (name, name);
1490 if (res != AdditionResult.Success)
1493 Constraints constraints = null;
1494 if (constraints_list != null) {
1495 foreach (Constraints constraint in constraints_list) {
1496 if (constraint.TypeParameter == name) {
1497 constraints = constraint;
1503 type_params [i] = new TypeParameter (name, constraints, Location);
1505 DefineName (name, type_params [i]);
1508 return AdditionResult.Success;
1511 public TypeParameter[] TypeParameters {
1514 throw new InvalidOperationException ();
1515 if (type_param_list == null)
1516 initialize_type_params ();
1518 return type_param_list;
1522 protected TypeParameter[] CurrentTypeParameters {
1525 throw new InvalidOperationException ();
1526 if (type_params != null)
1529 return new TypeParameter [0];
1533 public int CountTypeParameters {
1535 return count_type_params;
1539 public TypeParameterExpr LookupGeneric (string name, Location loc)
1544 foreach (TypeParameter type_param in CurrentTypeParameters) {
1545 if (type_param.Name != name)
1548 return new TypeParameterExpr (type_param, loc);
1552 return parent.LookupGeneric (name, loc);
1557 bool IAlias.IsType {
1558 get { return true; }
1561 string IAlias.Name {
1562 get { return Name; }
1565 TypeExpr IAlias.Type
1568 if (TypeBuilder == null)
1569 throw new InvalidOperationException ();
1571 if (CurrentType != null)
1574 return new TypeExpression (TypeBuilder, Location);
1578 protected override string[] ValidAttributeTargets {
1580 return attribute_targets;
1586 /// This is a readonly list of MemberInfo's.
1588 public class MemberList : IList {
1589 public readonly IList List;
1593 /// Create a new MemberList from the given IList.
1595 public MemberList (IList list)
1600 this.List = new ArrayList ();
1605 /// Concatenate the ILists `first' and `second' to a new MemberList.
1607 public MemberList (IList first, IList second)
1609 ArrayList list = new ArrayList ();
1610 list.AddRange (first);
1611 list.AddRange (second);
1616 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1619 /// Cast the MemberList into a MemberInfo[] array.
1622 /// This is an expensive operation, only use it if it's really necessary.
1624 public static explicit operator MemberInfo [] (MemberList list)
1626 Timer.StartTimer (TimerType.MiscTimer);
1627 MemberInfo [] result = new MemberInfo [list.Count];
1628 list.CopyTo (result, 0);
1629 Timer.StopTimer (TimerType.MiscTimer);
1641 public bool IsSynchronized {
1643 return List.IsSynchronized;
1647 public object SyncRoot {
1649 return List.SyncRoot;
1653 public void CopyTo (Array array, int index)
1655 List.CopyTo (array, index);
1660 public IEnumerator GetEnumerator ()
1662 return List.GetEnumerator ();
1667 public bool IsFixedSize {
1673 public bool IsReadOnly {
1679 object IList.this [int index] {
1681 return List [index];
1685 throw new NotSupportedException ();
1689 // FIXME: try to find out whether we can avoid the cast in this indexer.
1690 public MemberInfo this [int index] {
1692 return (MemberInfo) List [index];
1696 public int Add (object value)
1698 throw new NotSupportedException ();
1701 public void Clear ()
1703 throw new NotSupportedException ();
1706 public bool Contains (object value)
1708 return List.Contains (value);
1711 public int IndexOf (object value)
1713 return List.IndexOf (value);
1716 public void Insert (int index, object value)
1718 throw new NotSupportedException ();
1721 public void Remove (object value)
1723 throw new NotSupportedException ();
1726 public void RemoveAt (int index)
1728 throw new NotSupportedException ();
1733 /// This interface is used to get all members of a class when creating the
1734 /// member cache. It must be implemented by all DeclSpace derivatives which
1735 /// want to support the member cache and by TypeHandle to get caching of
1736 /// non-dynamic types.
1738 public interface IMemberContainer {
1740 /// The name of the IMemberContainer. This is only used for
1741 /// debugging purposes.
1748 /// The type of this IMemberContainer.
1755 /// Returns the IMemberContainer of the parent class or null if this
1756 /// is an interface or TypeManger.object_type.
1757 /// This is used when creating the member cache for a class to get all
1758 /// members from the parent class.
1760 IMemberContainer Parent {
1765 /// Whether this is an interface.
1772 /// Returns all members of this class with the corresponding MemberTypes
1773 /// and BindingFlags.
1776 /// When implementing this method, make sure not to return any inherited
1777 /// members and check the MemberTypes and BindingFlags properly.
1778 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1779 /// get the BindingFlags (static/non-static,public/non-public) in the
1780 /// MemberInfo class, but the cache needs this information. That's why
1781 /// this method is called multiple times with different BindingFlags.
1783 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1786 /// Return the container's member cache.
1788 MemberCache MemberCache {
1794 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1795 /// member lookups. It has a member name based hash table; it maps each member
1796 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1797 /// and the BindingFlags that were initially used to get it. The cache contains
1798 /// all members of the current class and all inherited members. If this cache is
1799 /// for an interface types, it also contains all inherited members.
1801 /// There are two ways to get a MemberCache:
1802 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1803 /// use the DeclSpace.MemberCache property.
1804 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1805 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1807 public class MemberCache {
1808 public readonly IMemberContainer Container;
1809 protected Hashtable member_hash;
1810 protected Hashtable method_hash;
1813 /// Create a new MemberCache for the given IMemberContainer `container'.
1815 public MemberCache (IMemberContainer container)
1817 this.Container = container;
1819 Timer.IncrementCounter (CounterType.MemberCache);
1820 Timer.StartTimer (TimerType.CacheInit);
1824 // If we have a parent class (we have a parent class unless we're
1825 // TypeManager.object_type), we deep-copy its MemberCache here.
1826 if (Container.IsInterface) {
1829 if (Container.Parent != null)
1830 parent = Container.Parent.MemberCache;
1832 parent = TypeHandle.ObjectType.MemberCache;
1833 member_hash = SetupCacheForInterface (parent);
1834 } else if (Container.Parent != null)
1835 member_hash = SetupCache (Container.Parent.MemberCache);
1837 member_hash = new Hashtable ();
1839 // If this is neither a dynamic type nor an interface, create a special
1840 // method cache with all declared and inherited methods.
1841 Type type = container.Type;
1842 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1843 method_hash = new Hashtable ();
1847 // Add all members from the current class.
1848 AddMembers (Container);
1850 Timer.StopTimer (TimerType.CacheInit);
1854 /// Bootstrap this member cache by doing a deep-copy of our parent.
1856 Hashtable SetupCache (MemberCache parent)
1858 Hashtable hash = new Hashtable ();
1860 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1861 while (it.MoveNext ()) {
1862 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1870 /// Add the contents of `new_hash' to `hash'.
1872 void AddHashtable (Hashtable hash, MemberCache cache)
1874 Hashtable new_hash = cache.member_hash;
1875 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1876 while (it.MoveNext ()) {
1877 ArrayList list = (ArrayList) hash [it.Key];
1879 hash [it.Key] = list = new ArrayList ();
1881 foreach (CacheEntry entry in (ArrayList) it.Value) {
1882 if (entry.Container != cache.Container)
1890 /// Bootstrap the member cache for an interface type.
1891 /// Type.GetMembers() won't return any inherited members for interface types,
1892 /// so we need to do this manually. Interfaces also inherit from System.Object.
1894 Hashtable SetupCacheForInterface (MemberCache parent)
1896 Hashtable hash = SetupCache (parent);
1897 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1899 foreach (TypeExpr iface in ifaces) {
1900 Type itype = iface.Type;
1902 IMemberContainer iface_container =
1903 TypeManager.LookupMemberContainer (itype);
1905 MemberCache iface_cache = iface_container.MemberCache;
1907 AddHashtable (hash, iface_cache);
1914 /// Add all members from class `container' to the cache.
1916 void AddMembers (IMemberContainer container)
1918 // We need to call AddMembers() with a single member type at a time
1919 // to get the member type part of CacheEntry.EntryType right.
1920 AddMembers (MemberTypes.Constructor, container);
1921 AddMembers (MemberTypes.Field, container);
1922 AddMembers (MemberTypes.Method, container);
1923 AddMembers (MemberTypes.Property, container);
1924 AddMembers (MemberTypes.Event, container);
1925 // Nested types are returned by both Static and Instance searches.
1926 AddMembers (MemberTypes.NestedType,
1927 BindingFlags.Static | BindingFlags.Public, container);
1928 AddMembers (MemberTypes.NestedType,
1929 BindingFlags.Static | BindingFlags.NonPublic, container);
1932 void AddMembers (MemberTypes mt, IMemberContainer container)
1934 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1935 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1936 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1937 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1941 /// Add all members from class `container' with the requested MemberTypes and
1942 /// BindingFlags to the cache. This method is called multiple times with different
1943 /// MemberTypes and BindingFlags.
1945 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1947 MemberList members = container.GetMembers (mt, bf);
1949 foreach (MemberInfo member in members) {
1950 string name = member.Name;
1952 int pos = name.IndexOf ('<');
1954 name = name.Substring (0, pos);
1956 // We use a name-based hash table of ArrayList's.
1957 ArrayList list = (ArrayList) member_hash [name];
1959 list = new ArrayList ();
1960 member_hash.Add (name, list);
1963 // When this method is called for the current class, the list will
1964 // already contain all inherited members from our parent classes.
1965 // We cannot add new members in front of the list since this'd be an
1966 // expensive operation, that's why the list is sorted in reverse order
1967 // (ie. members from the current class are coming last).
1968 list.Add (new CacheEntry (container, member, mt, bf));
1973 /// Add all declared and inherited methods from class `type' to the method cache.
1975 void AddMethods (Type type)
1977 AddMethods (BindingFlags.Static | BindingFlags.Public |
1978 BindingFlags.FlattenHierarchy, type);
1979 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1980 BindingFlags.FlattenHierarchy, type);
1981 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1982 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1985 void AddMethods (BindingFlags bf, Type type)
1987 MemberInfo [] members = type.GetMethods (bf);
1989 Array.Reverse (members);
1991 foreach (MethodBase member in members) {
1992 string name = member.Name;
1994 // Varargs methods aren't allowed in C# code.
1995 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1998 // We use a name-based hash table of ArrayList's.
1999 ArrayList list = (ArrayList) method_hash [name];
2001 list = new ArrayList ();
2002 method_hash.Add (name, list);
2005 // Unfortunately, the elements returned by Type.GetMethods() aren't
2006 // sorted so we need to do this check for every member.
2007 BindingFlags new_bf = bf;
2008 if (member.DeclaringType == type)
2009 new_bf |= BindingFlags.DeclaredOnly;
2011 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
2016 /// Compute and return a appropriate `EntryType' magic number for the given
2017 /// MemberTypes and BindingFlags.
2019 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
2021 EntryType type = EntryType.None;
2023 if ((mt & MemberTypes.Constructor) != 0)
2024 type |= EntryType.Constructor;
2025 if ((mt & MemberTypes.Event) != 0)
2026 type |= EntryType.Event;
2027 if ((mt & MemberTypes.Field) != 0)
2028 type |= EntryType.Field;
2029 if ((mt & MemberTypes.Method) != 0)
2030 type |= EntryType.Method;
2031 if ((mt & MemberTypes.Property) != 0)
2032 type |= EntryType.Property;
2033 // Nested types are returned by static and instance searches.
2034 if ((mt & MemberTypes.NestedType) != 0)
2035 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
2037 if ((bf & BindingFlags.Instance) != 0)
2038 type |= EntryType.Instance;
2039 if ((bf & BindingFlags.Static) != 0)
2040 type |= EntryType.Static;
2041 if ((bf & BindingFlags.Public) != 0)
2042 type |= EntryType.Public;
2043 if ((bf & BindingFlags.NonPublic) != 0)
2044 type |= EntryType.NonPublic;
2045 if ((bf & BindingFlags.DeclaredOnly) != 0)
2046 type |= EntryType.Declared;
2052 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2053 /// denote multiple member types. Returns true if the given flags value denotes a
2054 /// single member types.
2056 public static bool IsSingleMemberType (MemberTypes mt)
2059 case MemberTypes.Constructor:
2060 case MemberTypes.Event:
2061 case MemberTypes.Field:
2062 case MemberTypes.Method:
2063 case MemberTypes.Property:
2064 case MemberTypes.NestedType:
2073 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2074 /// number to speed up the searching process.
2077 protected enum EntryType {
2082 MaskStatic = Instance|Static,
2086 MaskProtection = Public|NonPublic,
2090 Constructor = 0x020,
2097 MaskType = Constructor|Event|Field|Method|Property|NestedType
2100 protected struct CacheEntry {
2101 public readonly IMemberContainer Container;
2102 public readonly EntryType EntryType;
2103 public readonly MemberInfo Member;
2105 public CacheEntry (IMemberContainer container, MemberInfo member,
2106 MemberTypes mt, BindingFlags bf)
2108 this.Container = container;
2109 this.Member = member;
2110 this.EntryType = GetEntryType (mt, bf);
2115 /// This is called each time we're walking up one level in the class hierarchy
2116 /// and checks whether we can abort the search since we've already found what
2117 /// we were looking for.
2119 protected bool DoneSearching (ArrayList list)
2122 // We've found exactly one member in the current class and it's not
2123 // a method or constructor.
2125 if (list.Count == 1 && !(list [0] is MethodBase))
2129 // Multiple properties: we query those just to find out the indexer
2132 if ((list.Count > 0) && (list [0] is PropertyInfo))
2139 /// Looks up members with name `name'. If you provide an optional
2140 /// filter function, it'll only be called with members matching the
2141 /// requested member name.
2143 /// This method will try to use the cache to do the lookup if possible.
2145 /// Unlike other FindMembers implementations, this method will always
2146 /// check all inherited members - even when called on an interface type.
2148 /// If you know that you're only looking for methods, you should use
2149 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2150 /// When doing a method-only search, it'll try to use a special method
2151 /// cache (unless it's a dynamic type or an interface) and the returned
2152 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2153 /// The lookup process will automatically restart itself in method-only
2154 /// search mode if it discovers that it's about to return methods.
2156 ArrayList global = new ArrayList ();
2157 bool using_global = false;
2159 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2161 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2162 MemberFilter filter, object criteria)
2165 throw new Exception ();
2167 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2168 bool method_search = mt == MemberTypes.Method;
2169 // If we have a method cache and we aren't already doing a method-only search,
2170 // then we restart a method search if the first match is a method.
2171 bool do_method_search = !method_search && (method_hash != null);
2173 ArrayList applicable;
2175 // If this is a method-only search, we try to use the method cache if
2176 // possible; a lookup in the method cache will return a MemberInfo with
2177 // the correct ReflectedType for inherited methods.
2179 if (method_search && (method_hash != null))
2180 applicable = (ArrayList) method_hash [name];
2182 applicable = (ArrayList) member_hash [name];
2184 if (applicable == null)
2185 return emptyMemberInfo;
2188 // 32 slots gives 53 rss/54 size
2189 // 2/4 slots gives 55 rss
2191 // Strange: from 25,000 calls, only 1,800
2192 // are above 2. Why does this impact it?
2195 using_global = true;
2197 Timer.StartTimer (TimerType.CachedLookup);
2199 EntryType type = GetEntryType (mt, bf);
2201 IMemberContainer current = Container;
2204 // `applicable' is a list of all members with the given member name `name'
2205 // in the current class and all its parent classes. The list is sorted in
2206 // reverse order due to the way how the cache is initialy created (to speed
2207 // things up, we're doing a deep-copy of our parent).
2209 for (int i = applicable.Count-1; i >= 0; i--) {
2210 CacheEntry entry = (CacheEntry) applicable [i];
2212 // This happens each time we're walking one level up in the class
2213 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2214 // the first time this happens (this may already happen in the first
2215 // iteration of this loop if there are no members with the name we're
2216 // looking for in the current class).
2217 if (entry.Container != current) {
2218 if (declared_only || DoneSearching (global))
2221 current = entry.Container;
2224 // Is the member of the correct type ?
2225 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2228 // Is the member static/non-static ?
2229 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2232 // Apply the filter to it.
2233 if (filter (entry.Member, criteria)) {
2234 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2235 do_method_search = false;
2236 global.Add (entry.Member);
2240 Timer.StopTimer (TimerType.CachedLookup);
2242 // If we have a method cache and we aren't already doing a method-only
2243 // search, we restart in method-only search mode if the first match is
2244 // a method. This ensures that we return a MemberInfo with the correct
2245 // ReflectedType for inherited methods.
2246 if (do_method_search && (global.Count > 0)){
2247 using_global = false;
2249 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2252 using_global = false;
2253 MemberInfo [] copy = new MemberInfo [global.Count];
2254 global.CopyTo (copy);
2259 // This finds the method or property for us to override. invocationType is the type where
2260 // the override is going to be declared, name is the name of the method/property, and
2261 // paramTypes is the parameters, if any to the method or property
2263 // Because the MemberCache holds members from this class and all the base classes,
2264 // we can avoid tons of reflection stuff.
2266 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2268 ArrayList applicable;
2269 if (method_hash != null && !is_property)
2270 applicable = (ArrayList) method_hash [name];
2272 applicable = (ArrayList) member_hash [name];
2274 if (applicable == null)
2277 // Walk the chain of methods, starting from the top.
2279 for (int i = applicable.Count - 1; i >= 0; i--) {
2280 CacheEntry entry = (CacheEntry) applicable [i];
2282 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2285 PropertyInfo pi = null;
2286 MethodInfo mi = null;
2287 FieldInfo fi = null;
2288 Type [] cmpAttrs = null;
2291 if ((entry.EntryType & EntryType.Field) != 0) {
2292 fi = (FieldInfo)entry.Member;
2294 // TODO: For this case we ignore member type
2295 //fb = TypeManager.GetField (fi);
2296 //cmpAttrs = new Type[] { fb.MemberType };
2298 pi = (PropertyInfo) entry.Member;
2299 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2302 mi = (MethodInfo) entry.Member;
2303 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2307 // TODO: Almost duplicate !
2309 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2310 case FieldAttributes.Private:
2312 // A private method is Ok if we are a nested subtype.
2313 // The spec actually is not very clear about this, see bug 52458.
2315 if (invocationType != entry.Container.Type &
2316 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2320 case FieldAttributes.FamANDAssem:
2321 case FieldAttributes.Assembly:
2323 // Check for assembly methods
2325 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2329 return entry.Member;
2333 // Check the arguments
2335 if (cmpAttrs.Length != paramTypes.Length)
2338 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2339 if (!paramTypes [j].Equals (cmpAttrs [j]))
2344 // get one of the methods because this has the visibility info.
2347 mi = pi.GetGetMethod (true);
2349 mi = pi.GetSetMethod (true);
2355 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2356 case MethodAttributes.Private:
2358 // A private method is Ok if we are a nested subtype.
2359 // The spec actually is not very clear about this, see bug 52458.
2361 if (invocationType == entry.Container.Type ||
2362 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2363 return entry.Member;
2366 case MethodAttributes.FamANDAssem:
2367 case MethodAttributes.Assembly:
2369 // Check for assembly methods
2371 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2372 return entry.Member;
2377 // A protected method is ok, because we are overriding.
2378 // public is always ok.
2380 return entry.Member;