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
14 using System.Collections;
15 using System.Reflection.Emit;
16 using System.Reflection;
18 namespace Mono.CSharp {
21 /// Base representation for members. This is only used to keep track
22 /// of Name, Location and Modifier flags.
24 public abstract class MemberCore {
31 /// Modifier flags that the user specified in the source code
36 /// Location where this declaration happens
38 public readonly Location Location;
40 public MemberCore (string name, Location loc)
46 protected void WarningNotHiding (TypeContainer parent)
50 "The member " + parent.MakeName (Name) + " does not hide an " +
51 "inherited member. The keyword new is not required");
55 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
59 // FIXME: report the old/new permissions?
62 507, Location, parent.MakeName (Name) +
63 ": can't change the access modifiers when overriding inherited " +
64 "member `" + name + "'");
68 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
69 // that have been defined.
71 // `name' is the user visible name for reporting errors (this is used to
72 // provide the right name regarding method names and properties)
74 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
75 MethodInfo mb, string name)
79 if ((ModFlags & Modifiers.OVERRIDE) != 0){
80 if (!(mb.IsAbstract || mb.IsVirtual)){
82 506, Location, parent.MakeName (Name) +
83 ": cannot override inherited member `" +
84 name + "' because it is not " +
85 "virtual, abstract or override");
89 // Now we check that the overriden method is not final
92 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
93 "override inherited member `" + name +
94 "' because it is sealed.");
98 // Check that the permissions are not being changed
100 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
101 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
104 // special case for "protected internal"
107 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
109 // when overriding protected internal, the method can be declared
110 // protected internal only within the same assembly
113 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
114 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
116 // assemblies differ - report an error
119 Error_CannotChangeAccessModifiers (parent, mb, name);
121 } else if (thisp != parentp) {
123 // same assembly, but other attributes differ - report an error
126 Error_CannotChangeAccessModifiers (parent, mb, name);
129 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
131 // if it's not "protected internal", it must be "protected"
134 Error_CannotChangeAccessModifiers (parent, mb, name);
136 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
138 // protected within the same assembly - an error
140 Error_CannotChangeAccessModifiers (parent, mb, name);
142 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
143 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
145 // protected ok, but other attributes differ - report an error
147 Error_CannotChangeAccessModifiers (parent, mb, name);
151 if (thisp != parentp){
152 Error_CannotChangeAccessModifiers (parent, mb, name);
158 if (mb.IsVirtual || mb.IsAbstract){
159 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
160 if (Name != "Finalize"){
162 114, 2, Location, parent.MakeName (Name) +
163 " hides inherited member `" + name +
164 "'. To make the current member override that " +
165 "implementation, add the override keyword, " +
166 "otherwise use the new keyword");
167 ModFlags |= Modifiers.NEW;
171 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
172 if (Name != "Finalize"){
174 108, 1, Location, "The keyword new is required on " +
175 parent.MakeName (Name) + " because it hides " +
176 "inherited member `" + name + "'");
177 ModFlags |= Modifiers.NEW;
185 public abstract bool Define (TypeContainer parent);
188 // Whehter is it ok to use an unsafe pointer in this type container
190 public bool UnsafeOK (DeclSpace parent)
193 // First check if this MemberCore modifier flags has unsafe set
195 if ((ModFlags & Modifiers.UNSAFE) != 0)
198 if (parent.UnsafeContext)
201 Expression.UnsafeError (Location);
207 // FIXME: This is temporary outside DeclSpace, because I have to fix a bug
208 // in MCS that makes it fail the lookup for the enum
212 /// The result value from adding an declaration into
213 /// a struct or a class
215 public enum AdditionResult {
217 /// The declaration has been successfully
218 /// added to the declation space.
223 /// The symbol has already been defined.
228 /// Returned if the declation being added to the
229 /// name space clashes with its container name.
231 /// The only exceptions for this are constructors
232 /// and static constructors
237 /// Returned if a constructor was created (because syntactically
238 /// it looked like a constructor) but was not (because the name
239 /// of the method is not the same as the container class
244 /// This is only used by static constructors to emit the
245 /// error 111, but this error for other things really
246 /// happens at another level for other functions.
252 /// Base class for structs, classes, enumerations and interfaces.
255 /// They all create new declaration spaces. This
256 /// provides the common foundation for managing those name
259 public abstract class DeclSpace : MemberCore {
261 /// this points to the actual definition that is being
262 /// created with System.Reflection.Emit
264 public TypeBuilder TypeBuilder;
267 /// This variable tracks whether we have Closed the type
269 public bool Created = false;
272 // This is the namespace in which this typecontainer
273 // was declared. We use this to resolve names.
275 public Namespace Namespace;
277 public Hashtable Cache = new Hashtable ();
279 public string Basename;
282 /// defined_names is used for toplevel objects
284 protected Hashtable defined_names;
286 TypeContainer parent;
288 public DeclSpace (TypeContainer parent, string name, Location l)
291 Basename = name.Substring (1 + name.LastIndexOf ('.'));
292 defined_names = new Hashtable ();
293 this.parent = parent;
297 /// Returns a status code based purely on the name
298 /// of the member being added
300 protected AdditionResult IsValid (string name)
302 if (name == Basename)
303 return AdditionResult.EnclosingClash;
305 if (defined_names.Contains (name))
306 return AdditionResult.NameExists;
308 return AdditionResult.Success;
311 public static int length;
312 public static int small;
315 /// Introduce @name into this declaration space and
316 /// associates it with the object @o. Note that for
317 /// methods this will just point to the first method. o
319 protected void DefineName (string name, object o)
321 defined_names.Add (name, o);
324 int p = name.LastIndexOf (".");
332 /// Returns the object associated with a given name in the declaration
333 /// space. This is the inverse operation of `DefineName'
335 public object GetDefinition (string name)
337 return defined_names [name];
340 bool in_transit = false;
343 /// This function is used to catch recursive definitions
346 public bool InTransit {
356 public TypeContainer Parent {
363 /// Looks up the alias for the name
365 public string LookupAlias (string name)
367 if (Namespace != null)
368 return Namespace.LookupAlias (name);
374 // root_types contains all the types. All TopLevel types
375 // hence have a parent that points to `root_types', that is
376 // why there is a non-obvious test down here.
378 public bool IsTopLevel {
381 if (parent.parent == null)
388 public virtual void CloseType ()
392 TypeBuilder.CreateType ();
395 // The try/catch is needed because
396 // nested enumerations fail to load when they
399 // Even if this is the right order (enumerations
400 // declared after types).
402 // Note that this still creates the type and
403 // it is possible to save it
410 /// Should be overriten by the appropriate declaration space
412 public abstract TypeBuilder DefineType ();
415 /// Define all members, but don't apply any attributes or do anything which may
416 /// access not-yet-defined classes. This method also creates the MemberCache.
418 public abstract bool DefineMembers (TypeContainer parent);
421 // Whether this is an `unsafe context'
423 public bool UnsafeContext {
425 if ((ModFlags & Modifiers.UNSAFE) != 0)
428 return parent.UnsafeContext;
433 public static string MakeFQN (string nsn, string name)
437 return String.Concat (nsn, ".", name);
440 EmitContext type_resolve_ec;
441 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
443 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
444 type_resolve_ec.ResolvingTypeTree = true;
446 return type_resolve_ec;
450 // Looks up the type, as parsed into the expression `e'
452 public Type ResolveType (Expression e, bool silent, Location loc)
454 if (type_resolve_ec == null)
455 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
456 type_resolve_ec.loc = loc;
457 type_resolve_ec.ContainerType = TypeBuilder;
459 int errors = Report.Errors;
460 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
462 if (d == null || d.eclass != ExprClass.Type){
463 if (!silent && errors == Report.Errors){
464 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
469 if (!CheckAccessLevel (d.Type)) {
470 Report. Error (122, loc, "`" + d.Type + "' " +
471 "is inaccessible because of its protection level");
479 // Resolves the expression `e' for a type, and will recursively define
482 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
484 if (type_resolve_ec == null)
485 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
487 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
489 if (d == null || d.eclass != ExprClass.Type){
491 Report.Error (246, loc, "Cannot find type `"+ e +"'");
499 bool CheckAccessLevel (Type check_type)
501 if (check_type == TypeBuilder)
504 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
507 // Broken Microsoft runtime, return public for arrays, no matter what
508 // the accessibility is for their underlying class, and they return
509 // NonPublic visibility for pointers
511 if (check_type.IsArray || check_type.IsPointer)
512 return CheckAccessLevel (check_type.GetElementType ());
514 if (check_attr == TypeAttributes.Public)
517 if (check_attr == TypeAttributes.NestedPublic)
520 if (check_attr == TypeAttributes.NestedPrivate){
521 string check_type_name = check_type.FullName;
522 string type_name = TypeBuilder.FullName;
524 int cio = check_type_name.LastIndexOf ("+");
525 string container = check_type_name.Substring (0, cio);
528 // Check if the check_type is a nested class of the current type
530 if (check_type_name.StartsWith (type_name + "+")){
534 if (type_name.StartsWith (container)){
541 if (check_type.Assembly == TypeBuilder.Assembly){
550 Type LookupInterfaceOrClass (string ns, string name, out bool error)
556 name = MakeFQN (ns, name);
558 t = TypeManager.LookupType (name);
562 parent = (DeclSpace) RootContext.Tree.Decls [name];
566 t = parent.DefineType ();
568 Report.Error (146, Location, "Class definition is circular: `"+name+"'");
575 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
577 Report.Error (104, loc,
578 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
579 t1.FullName, t2.FullName));
583 /// GetType is used to resolve type names at the DeclSpace level.
584 /// Use this to lookup class/struct bases, interface bases or
585 /// delegate type references
589 /// Contrast this to LookupType which is used inside method bodies to
590 /// lookup types that have already been defined. GetType is used
591 /// during the tree resolution process and potentially define
592 /// recursively the type
594 public Type FindType (Location loc, string name)
600 // For the case the type we are looking for is nested within this one
601 // or is in any base class
603 DeclSpace containing_ds = this;
605 while (containing_ds != null){
606 Type current_type = containing_ds.TypeBuilder;
608 while (current_type != null) {
609 string pre = current_type.FullName;
611 t = LookupInterfaceOrClass (pre, name, out error);
618 current_type = current_type.BaseType;
620 containing_ds = containing_ds.Parent;
624 // Attempt to lookup the class on our namespace and all it's implicit parents
626 for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
628 t = LookupInterfaceOrClass (ns, name, out error);
637 // Attempt to do a direct unqualified lookup
639 t = LookupInterfaceOrClass ("", name, out error);
647 // Attempt to lookup the class on any of the `using'
651 for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
653 t = LookupInterfaceOrClass (ns.Name, name, out error);
661 // Now check the using clause list
663 ArrayList using_list = ns.UsingTable;
665 if (using_list == null)
669 foreach (Namespace.UsingEntry ue in using_list){
670 match = LookupInterfaceOrClass (ue.Name, name, out error);
676 Error_AmbiguousTypeReference (loc, name, t, match);
688 //Report.Error (246, Location, "Can not find type `"+name+"'");
693 /// This function is broken and not what you're looking for. It should only
694 /// be used while the type is still being created since it doesn't use the cache
695 /// and relies on the filter doing the member name check.
697 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
698 MemberFilter filter, object criteria);
701 /// If we have a MemberCache, return it. This property may return null if the
702 /// class doesn't have a member cache or while it's still being created.
704 public abstract MemberCache MemberCache {
710 /// This is a readonly list of MemberInfo's.
712 public class MemberList : IList {
713 public readonly IList List;
717 /// Create a new MemberList from the given IList.
719 public MemberList (IList list)
724 this.List = new ArrayList ();
729 /// Concatenate the ILists `first' and `second' to a new MemberList.
731 public MemberList (IList first, IList second)
733 ArrayList list = new ArrayList ();
734 list.AddRange (first);
735 list.AddRange (second);
740 public static readonly MemberList Empty = new MemberList (new ArrayList ());
743 /// Cast the MemberList into a MemberInfo[] array.
746 /// This is an expensive operation, only use it if it's really necessary.
748 public static explicit operator MemberInfo [] (MemberList list)
750 Timer.StartTimer (TimerType.MiscTimer);
751 MemberInfo [] result = new MemberInfo [list.Count];
752 list.CopyTo (result, 0);
753 Timer.StopTimer (TimerType.MiscTimer);
765 public bool IsSynchronized {
767 return List.IsSynchronized;
771 public object SyncRoot {
773 return List.SyncRoot;
777 public void CopyTo (Array array, int index)
779 List.CopyTo (array, index);
784 public IEnumerator GetEnumerator ()
786 return List.GetEnumerator ();
791 public bool IsFixedSize {
797 public bool IsReadOnly {
803 object IList.this [int index] {
809 throw new NotSupportedException ();
813 // FIXME: try to find out whether we can avoid the cast in this indexer.
814 public MemberInfo this [int index] {
816 return (MemberInfo) List [index];
820 public int Add (object value)
822 throw new NotSupportedException ();
827 throw new NotSupportedException ();
830 public bool Contains (object value)
832 return List.Contains (value);
835 public int IndexOf (object value)
837 return List.IndexOf (value);
840 public void Insert (int index, object value)
842 throw new NotSupportedException ();
845 public void Remove (object value)
847 throw new NotSupportedException ();
850 public void RemoveAt (int index)
852 throw new NotSupportedException ();
857 /// This interface is used to get all members of a class when creating the
858 /// member cache. It must be implemented by all DeclSpace derivatives which
859 /// want to support the member cache and by TypeHandle to get caching of
860 /// non-dynamic types.
862 public interface IMemberContainer {
864 /// The name of the IMemberContainer. This is only used for
865 /// debugging purposes.
872 /// The type of this IMemberContainer.
879 /// Returns the IMemberContainer of the parent class or null if this
880 /// is an interface or TypeManger.object_type.
881 /// This is used when creating the member cache for a class to get all
882 /// members from the parent class.
884 IMemberContainer Parent {
889 /// Whether this is an interface.
896 /// Returns all members of this class with the corresponding MemberTypes
897 /// and BindingFlags.
900 /// When implementing this method, make sure not to return any inherited
901 /// members and check the MemberTypes and BindingFlags properly.
902 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
903 /// get the BindingFlags (static/non-static,public/non-public) in the
904 /// MemberInfo class, but the cache needs this information. That's why
905 /// this method is called multiple times with different BindingFlags.
907 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
910 /// Return the container's member cache.
912 MemberCache MemberCache {
918 /// The MemberCache is used by dynamic and non-dynamic types to speed up
919 /// member lookups. It has a member name based hash table; it maps each member
920 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
921 /// and the BindingFlags that were initially used to get it. The cache contains
922 /// all members of the current class and all inherited members. If this cache is
923 /// for an interface types, it also contains all inherited members.
925 /// There are two ways to get a MemberCache:
926 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
927 /// use the DeclSpace.MemberCache property.
928 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
929 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
931 public class MemberCache {
932 public readonly IMemberContainer Container;
933 protected Hashtable member_hash;
934 protected Hashtable method_hash;
935 protected Hashtable interface_hash;
938 /// Create a new MemberCache for the given IMemberContainer `container'.
940 public MemberCache (IMemberContainer container)
942 this.Container = container;
944 Timer.IncrementCounter (CounterType.MemberCache);
945 Timer.StartTimer (TimerType.CacheInit);
947 interface_hash = new Hashtable ();
949 // If we have a parent class (we have a parent class unless we're
950 // TypeManager.object_type), we deep-copy its MemberCache here.
951 if (Container.Parent != null)
952 member_hash = SetupCache (Container.Parent.MemberCache);
953 else if (Container.IsInterface)
954 member_hash = SetupCacheForInterface ();
956 member_hash = new Hashtable ();
958 // If this is neither a dynamic type nor an interface, create a special
959 // method cache with all declared and inherited methods.
960 Type type = container.Type;
961 if (!(type is TypeBuilder) && !type.IsInterface) {
962 method_hash = new Hashtable ();
966 // Add all members from the current class.
967 AddMembers (Container);
969 Timer.StopTimer (TimerType.CacheInit);
973 /// Bootstrap this member cache by doing a deep-copy of our parent.
975 Hashtable SetupCache (MemberCache parent)
977 Hashtable hash = new Hashtable ();
979 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
980 while (it.MoveNext ()) {
981 hash [it.Key] = ((ArrayList) it.Value).Clone ();
987 void AddInterfaces (MemberCache parent)
989 foreach (Type iface in parent.interface_hash.Keys) {
990 if (!interface_hash.Contains (iface))
991 interface_hash.Add (iface, true);
996 /// Add the contents of `new_hash' to `hash'.
998 void AddHashtable (Hashtable hash, Hashtable new_hash)
1000 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1001 while (it.MoveNext ()) {
1002 ArrayList list = (ArrayList) hash [it.Key];
1004 list.AddRange ((ArrayList) it.Value);
1006 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1011 /// Bootstrap the member cache for an interface type.
1012 /// Type.GetMembers() won't return any inherited members for interface types,
1013 /// so we need to do this manually. Interfaces also inherit from System.Object.
1015 Hashtable SetupCacheForInterface ()
1017 Hashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
1018 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1020 foreach (Type iface in ifaces) {
1021 if (interface_hash.Contains (iface))
1023 interface_hash.Add (iface, true);
1025 IMemberContainer iface_container =
1026 TypeManager.LookupMemberContainer (iface);
1028 MemberCache iface_cache = iface_container.MemberCache;
1029 AddHashtable (hash, iface_cache.member_hash);
1030 AddInterfaces (iface_cache);
1037 /// Add all members from class `container' to the cache.
1039 void AddMembers (IMemberContainer container)
1041 // We need to call AddMembers() with a single member type at a time
1042 // to get the member type part of CacheEntry.EntryType right.
1043 AddMembers (MemberTypes.Constructor, container);
1044 AddMembers (MemberTypes.Field, container);
1045 AddMembers (MemberTypes.Method, container);
1046 AddMembers (MemberTypes.Property, container);
1047 AddMembers (MemberTypes.Event, container);
1048 // Nested types are returned by both Static and Instance searches.
1049 AddMembers (MemberTypes.NestedType,
1050 BindingFlags.Static | BindingFlags.Public, container);
1051 AddMembers (MemberTypes.NestedType,
1052 BindingFlags.Static | BindingFlags.NonPublic, container);
1055 void AddMembers (MemberTypes mt, IMemberContainer container)
1057 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1058 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1059 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1060 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1064 /// Add all members from class `container' with the requested MemberTypes and
1065 /// BindingFlags to the cache. This method is called multiple times with different
1066 /// MemberTypes and BindingFlags.
1068 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1070 MemberList members = container.GetMembers (mt, bf);
1071 BindingFlags new_bf = (container == Container) ?
1072 bf | BindingFlags.DeclaredOnly : bf;
1074 foreach (MemberInfo member in members) {
1075 string name = member.Name;
1077 // We use a name-based hash table of ArrayList's.
1078 ArrayList list = (ArrayList) member_hash [name];
1080 list = new ArrayList ();
1081 member_hash.Add (name, list);
1084 // When this method is called for the current class, the list will
1085 // already contain all inherited members from our parent classes.
1086 // We cannot add new members in front of the list since this'd be an
1087 // expensive operation, that's why the list is sorted in reverse order
1088 // (ie. members from the current class are coming last).
1089 list.Add (new CacheEntry (container, member, mt, bf));
1094 /// Add all declared and inherited methods from class `type' to the method cache.
1096 void AddMethods (Type type)
1098 AddMethods (BindingFlags.Static | BindingFlags.Public |
1099 BindingFlags.FlattenHierarchy, type);
1100 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1101 BindingFlags.FlattenHierarchy, type);
1102 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1103 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1106 void AddMethods (BindingFlags bf, Type type)
1108 MemberInfo [] members = type.GetMethods (bf);
1110 foreach (MethodBase member in members) {
1111 string name = member.Name;
1113 // Varargs methods aren't allowed in C# code.
1114 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1117 // We use a name-based hash table of ArrayList's.
1118 ArrayList list = (ArrayList) method_hash [name];
1120 list = new ArrayList ();
1121 method_hash.Add (name, list);
1124 // Unfortunately, the elements returned by Type.GetMethods() aren't
1125 // sorted so we need to do this check for every member.
1126 BindingFlags new_bf = bf;
1127 if (member.DeclaringType == type)
1128 new_bf |= BindingFlags.DeclaredOnly;
1130 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1135 /// Compute and return a appropriate `EntryType' magic number for the given
1136 /// MemberTypes and BindingFlags.
1138 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1140 EntryType type = EntryType.None;
1142 if ((mt & MemberTypes.Constructor) != 0)
1143 type |= EntryType.Constructor;
1144 if ((mt & MemberTypes.Event) != 0)
1145 type |= EntryType.Event;
1146 if ((mt & MemberTypes.Field) != 0)
1147 type |= EntryType.Field;
1148 if ((mt & MemberTypes.Method) != 0)
1149 type |= EntryType.Method;
1150 if ((mt & MemberTypes.Property) != 0)
1151 type |= EntryType.Property;
1152 // Nested types are returned by static and instance searches.
1153 if ((mt & MemberTypes.NestedType) != 0)
1154 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1156 if ((bf & BindingFlags.Instance) != 0)
1157 type |= EntryType.Instance;
1158 if ((bf & BindingFlags.Static) != 0)
1159 type |= EntryType.Static;
1160 if ((bf & BindingFlags.Public) != 0)
1161 type |= EntryType.Public;
1162 if ((bf & BindingFlags.NonPublic) != 0)
1163 type |= EntryType.NonPublic;
1164 if ((bf & BindingFlags.DeclaredOnly) != 0)
1165 type |= EntryType.Declared;
1171 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1172 /// denote multiple member types. Returns true if the given flags value denotes a
1173 /// single member types.
1175 public static bool IsSingleMemberType (MemberTypes mt)
1178 case MemberTypes.Constructor:
1179 case MemberTypes.Event:
1180 case MemberTypes.Field:
1181 case MemberTypes.Method:
1182 case MemberTypes.Property:
1183 case MemberTypes.NestedType:
1192 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1193 /// number to speed up the searching process.
1196 protected enum EntryType {
1201 MaskStatic = Instance|Static,
1205 MaskProtection = Public|NonPublic,
1209 Constructor = 0x020,
1216 MaskType = Constructor|Event|Field|Method|Property|NestedType
1219 protected struct CacheEntry {
1220 public readonly IMemberContainer Container;
1221 public readonly EntryType EntryType;
1222 public readonly MemberInfo Member;
1224 public CacheEntry (IMemberContainer container, MemberInfo member,
1225 MemberTypes mt, BindingFlags bf)
1227 this.Container = container;
1228 this.Member = member;
1229 this.EntryType = GetEntryType (mt, bf);
1234 /// This is called each time we're walking up one level in the class hierarchy
1235 /// and checks whether we can abort the search since we've already found what
1236 /// we were looking for.
1238 protected bool DoneSearching (ArrayList list)
1241 // We've found exactly one member in the current class and it's not
1242 // a method or constructor.
1244 if (list.Count == 1 && !(list [0] is MethodBase))
1248 // Multiple properties: we query those just to find out the indexer
1251 if ((list.Count > 0) && (list [0] is PropertyInfo))
1258 /// Looks up members with name `name'. If you provide an optional
1259 /// filter function, it'll only be called with members matching the
1260 /// requested member name.
1262 /// This method will try to use the cache to do the lookup if possible.
1264 /// Unlike other FindMembers implementations, this method will always
1265 /// check all inherited members - even when called on an interface type.
1267 /// If you know that you're only looking for methods, you should use
1268 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1269 /// When doing a method-only search, it'll try to use a special method
1270 /// cache (unless it's a dynamic type or an interface) and the returned
1271 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1272 /// The lookup process will automatically restart itself in method-only
1273 /// search mode if it discovers that it's about to return methods.
1275 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1276 MemberFilter filter, object criteria)
1278 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1279 bool method_search = mt == MemberTypes.Method;
1280 // If we have a method cache and we aren't already doing a method-only search,
1281 // then we restart a method search if the first match is a method.
1282 bool do_method_search = !method_search && (method_hash != null);
1284 ArrayList applicable;
1286 // If this is a method-only search, we try to use the method cache if
1287 // possible; a lookup in the method cache will return a MemberInfo with
1288 // the correct ReflectedType for inherited methods.
1290 if (method_search && (method_hash != null))
1291 applicable = (ArrayList) method_hash [name];
1293 applicable = (ArrayList) member_hash [name];
1295 if (applicable == null)
1296 return MemberList.Empty;
1298 ArrayList list = new ArrayList ();
1300 Timer.StartTimer (TimerType.CachedLookup);
1302 EntryType type = GetEntryType (mt, bf);
1304 IMemberContainer current = Container;
1306 // `applicable' is a list of all members with the given member name `name'
1307 // in the current class and all its parent classes. The list is sorted in
1308 // reverse order due to the way how the cache is initialy created (to speed
1309 // things up, we're doing a deep-copy of our parent).
1311 for (int i = applicable.Count-1; i >= 0; i--) {
1312 CacheEntry entry = (CacheEntry) applicable [i];
1314 // This happens each time we're walking one level up in the class
1315 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1316 // the first time this happens (this may already happen in the first
1317 // iteration of this loop if there are no members with the name we're
1318 // looking for in the current class).
1319 if (entry.Container != current) {
1320 if (declared_only || DoneSearching (list))
1323 current = entry.Container;
1326 // Is the member of the correct type ?
1327 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1330 // Is the member static/non-static ?
1331 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1334 // Apply the filter to it.
1335 if (filter (entry.Member, criteria)) {
1336 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1337 do_method_search = false;
1338 list.Add (entry.Member);
1342 Timer.StopTimer (TimerType.CachedLookup);
1344 // If we have a method cache and we aren't already doing a method-only
1345 // search, we restart in method-only search mode if the first match is
1346 // a method. This ensures that we return a MemberInfo with the correct
1347 // ReflectedType for inherited methods.
1348 if (do_method_search && (list.Count > 0)){
1349 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1352 return new MemberList (list);