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.MonoBASIC {
21 /// Base representation for members. This is only used to keep track
22 /// of Name, Location and Modifier flags.
24 public abstract class MemberCore : Attributable
32 /// Modifier flags that the user specified in the source code
37 /// Location where this declaration happens
39 public readonly Location Location;
41 public MemberCore (string name, Attributes attrs, Location loc)
48 protected void WarningNotHiding (TypeContainer parent)
52 "The member " + parent.MakeName (Name) + " does not hide an " +
53 "inherited member. The keyword new is not required");
57 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
61 // FIXME: report the old/new permissions?
64 31048, Location, parent.MakeName (Name) +
65 ": can't change the access modifiers when overriding inherited " +
66 "member `" + name + "'");
70 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
71 // that have been defined.
73 // `name' is the user visible name for reporting errors (this is used to
74 // provide the right name regarding method names and properties)
76 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
77 MethodInfo mb, string name)
81 if ((ModFlags & Modifiers.OVERRIDE) != 0){
82 // Now we check that the overriden method is not final
85 Report.Error (30267, Location, parent.MakeName (Name) + " : cannot " +
86 "override inherited member `" + name +
87 "' because it is NotOverridable.");
90 else if (!(mb.IsAbstract || mb.IsVirtual)){
92 31086, Location, parent.MakeName (Name) +
93 ": Cannot override inherited member `" +
94 name + "' because it is not " +
95 "declared as Overridable");
100 // Check that the permissions are not being changed
102 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
103 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
105 if (thisp != parentp){
106 Error_CannotChangeAccessModifiers (parent, mb, name);
111 if ((ModFlags & ( Modifiers.NEW | Modifiers.SHADOWS | Modifiers.OVERRIDE )) == 0) {
112 if ((ModFlags & Modifiers.NONVIRTUAL) != 0) {
113 Report.Error (31088, Location,
114 parent.MakeName (Name) + " cannot " +
115 "be declared NotOverridable since this method is " +
116 "not marked as Overrides");
121 if ((ModFlags & (Modifiers.OVERRIDE)) == 0) {
122 if (Name != "Finalize") {
125 name + " cannot Shadows the method " +
126 parent.MakeName (Name) + " since it is declared " +
127 "'MustOverride' in base class");
131 else if (mb.IsVirtual){
132 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SHADOWS)) == 0){
133 if (Name != "Finalize"){
135 40005, 2, Location, parent.MakeName (Name) +
136 " shadows overridable member `" + name +
137 "'. To make the current member override that " +
138 "implementation, add the overrides keyword." );
139 ModFlags |= Modifiers.SHADOWS;
144 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE |
145 Modifiers.SHADOWS)) == 0){
146 if (Name != "Finalize"){
148 40004, 1, Location, "The keyword Shadows is required on " +
149 parent.MakeName (Name) + " because it hides " +
150 "inherited member `" + name + "'");
151 ModFlags |= Modifiers.SHADOWS;
159 public abstract bool Define (TypeContainer parent);
162 // Whehter is it ok to use an unsafe pointer in this type container
164 public bool UnsafeOK (DeclSpace parent)
167 // First check if this MemberCore modifier flags has unsafe set
169 if ((ModFlags & Modifiers.UNSAFE) != 0)
172 if (parent.UnsafeContext)
175 Expression.UnsafeError (Location);
181 // FIXME: This is temporary outside DeclSpace, because I have to fix a bug
182 // in MCS that makes it fail the lookup for the enum
186 /// The result value from adding an declaration into
187 /// a struct or a class
189 public enum AdditionResult {
191 /// The declaration has been successfully
192 /// added to the declation space.
197 /// The symbol has already been defined.
202 /// Returned if a constructor was created (because syntactically
203 /// it looked like a constructor) but was not (because the name
204 /// of the method is not the same as the container class
209 /// This is only used by static constructors to emit the
210 /// error 111, but this error for other things really
211 /// happens at another level for other functions.
217 /// Base class for structs, classes, enumerations and interfaces.
220 /// They all create new declaration spaces. This
221 /// provides the common foundation for managing those name
224 public abstract class DeclSpace : MemberCore {
226 /// this points to the actual definition that is being
227 /// created with System.Reflection.Emit
229 public TypeBuilder TypeBuilder;
232 /// This variable tracks whether we have Closed the type
234 public bool Created = false;
237 // This is the namespace in which this typecontainer
238 // was declared. We use this to resolve names.
240 public Namespace Namespace;
242 public Hashtable Cache = new Hashtable ();
244 public string Basename;
247 /// defined_names is used for toplevel objects
249 protected Hashtable defined_names;
251 TypeContainer parent;
253 public DeclSpace (TypeContainer parent, string name, Attributes attrs, Location l)
254 : base (name, attrs, l)
256 Basename = name.Substring (1 + name.LastIndexOf ('.'));
257 defined_names = new Hashtable ();
258 this.parent = parent;
262 /// Returns a status code based purely on the name
263 /// of the member being added
265 protected AdditionResult IsValid (string name)
267 if (defined_names.Contains (name))
268 return AdditionResult.NameExists;
270 return AdditionResult.Success;
274 /// Introduce @name into this declaration space and
275 /// associates it with the object @o. Note that for
276 /// methods this will just point to the first method. o
278 protected void DefineName (string name, object o)
281 defined_names.Add (name, o);
283 catch (ArgumentException exp) {
284 Report.Error (30260, /*Location,*/
285 "More than one defination with same name '" + name +
286 "' is found in the container '" + Name + "'");
292 /// Returns the object associated with a given name in the declaration
293 /// space. This is the inverse operation of `DefineName'
295 public object GetDefinition (string name)
297 return defined_names [name];
300 bool in_transit = false;
303 /// This function is used to catch recursive definitions
306 public bool InTransit {
316 public TypeContainer Parent {
323 /// Looks up the alias for the name
325 public string LookupAlias (string name)
327 return RootContext.SourceBeingCompiled.LookupAlias (name);
331 // root_types contains all the types. All TopLevel types
332 // hence have a parent that points to `root_types', that is
333 // why there is a non-obvious test down here.
335 public bool IsTopLevel {
338 if (parent.parent == null)
345 public virtual void CloseType ()
349 TypeBuilder.CreateType ();
352 // The try/catch is needed because
353 // nested enumerations fail to load when they
356 // Even if this is the right order (enumerations
357 // declared after types).
359 // Note that this still creates the type and
360 // it is possible to save it
367 /// Should be overriten by the appropriate declaration space
369 public abstract TypeBuilder DefineType ();
372 /// Define all members, but don't apply any attributes or do anything which may
373 /// access not-yet-defined classes. This method also creates the MemberCache.
375 public abstract bool DefineMembers (TypeContainer parent);
378 // Whether this is an `unsafe context'
380 public bool UnsafeContext {
382 if ((ModFlags & Modifiers.UNSAFE) != 0)
385 return parent.UnsafeContext;
390 public static string MakeFQN (string nsn, string name)
392 string prefix = (nsn == "" ? "" : nsn + ".");
394 return prefix + name;
397 EmitContext type_resolve_ec;
398 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
400 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
401 type_resolve_ec.ResolvingTypeTree = true;
403 return type_resolve_ec;
407 // Looks up the type, as parsed into the expression `e'
409 public Type ResolveType (Expression e, bool silent, Location loc)
411 if (type_resolve_ec == null)
412 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
413 type_resolve_ec.loc = loc;
415 int errors = Report.Errors;
416 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
417 if (d == null || d.eclass != ExprClass.Type){
418 if (!silent && errors == Report.Errors){
419 Report.Error (30002, loc, "Cannot find type `"+ e.ToString () +"'");
428 // Resolves the expression `e' for a type, and will recursively define
431 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
433 if (type_resolve_ec == null)
434 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
436 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
437 if (d == null || d.eclass != ExprClass.Type){
439 Report.Error (30002, loc, "Cannot find type `"+ e +"'");
447 Type LookupInterfaceOrClass (string ns, string name, out bool error)
453 name = MakeFQN (ns, name);
455 t = TypeManager.LookupType (name);
459 parent = (DeclSpace) RootContext.Tree.Decls [name];
463 t = parent.DefineType ();
465 Report.Error (30256, Location, "Class definition is circular: `"+name+"'");
472 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
474 Report.Error (104, loc,
475 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
476 t1.FullName, t2.FullName));
480 /// GetType is used to resolve type names at the DeclSpace level.
481 /// Use this to lookup class/struct bases, interface bases or
482 /// delegate type references
486 /// Contrast this to LookupType which is used inside method bodies to
487 /// lookup types that have already been defined. GetType is used
488 /// during the tree resolution process and potentially define
489 /// recursively the type
491 public Type FindType (Location loc, string name)
497 // For the case the type we are looking for is nested within this one
498 // or is in any base class
500 DeclSpace containing_ds = this;
502 while (containing_ds != null){
503 Type current_type = containing_ds.TypeBuilder;
505 while (current_type != null) {
506 string pre = current_type.FullName;
508 t = LookupInterfaceOrClass (pre, name, out error);
515 current_type = current_type.BaseType;
517 containing_ds = containing_ds.Parent;
521 // Attempt to lookup the class on our namespace and all it's implicit parents
523 for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
525 t = LookupInterfaceOrClass (ns, name, out error);
534 // Attempt to do a direct unqualified lookup
536 t = LookupInterfaceOrClass ("", name, out error);
544 // Attempt to lookup the class on any of the `using'
548 for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
550 t = LookupInterfaceOrClass (ns.Name, name, out error);
558 // Now check the using clause list
560 ICollection imports_list = RootContext.SourceBeingCompiled.ImportsTable;
562 if (imports_list == null)
566 foreach (SourceBeingCompiled.ImportsEntry ue in imports_list){
567 match = LookupInterfaceOrClass (ue.Name, name, out error);
573 Error_AmbiguousTypeReference (loc, name, t, match);
585 //Report.Error (246, Location, "Can not find type `"+name+"'");
590 /// This function is broken and not what you're looking for. It should only
591 /// be used while the type is still being created since it doesn't use the cache
592 /// and relies on the filter doing the member name check.
594 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
595 MemberFilter filter, object criteria);
598 /// If we have a MemberCache, return it. This property may return null if the
599 /// class doesn't have a member cache or while it's still being created.
601 public abstract MemberCache MemberCache {
605 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
608 TypeBuilder.SetCustomAttribute (cb);
609 } catch (System.ArgumentException e) {
610 Report.Warning (-21, a.Location,
611 "The CharSet named property on StructLayout\n"+
612 "\tdoes not work correctly on Microsoft.NET\n"+
613 "\tYou might want to remove the CharSet declaration\n"+
614 "\tor compile using the Mono runtime instead of the\n"+
615 "\tMicrosoft .NET runtime\n"+
616 "\tThe runtime gave the error: " + e);
623 /// This is a readonly list of MemberInfo's.
625 public class MemberList : IList {
626 public readonly IList List;
630 /// Create a new MemberList from the given IList.
632 public MemberList (IList list)
637 this.List = new ArrayList ();
642 /// Concatenate the ILists `first' and `second' to a new MemberList.
644 public MemberList (IList first, IList second)
646 ArrayList list = new ArrayList ();
647 list.AddRange (first);
648 list.AddRange (second);
653 public static readonly MemberList Empty = new MemberList (new ArrayList ());
656 /// Cast the MemberList into a MemberInfo[] array.
659 /// This is an expensive operation, only use it if it's really necessary.
661 public static explicit operator MemberInfo [] (MemberList list)
663 Timer.StartTimer (TimerType.MiscTimer);
664 MemberInfo [] result = new MemberInfo [list.Count];
665 list.CopyTo (result, 0);
666 Timer.StopTimer (TimerType.MiscTimer);
678 public bool IsSynchronized {
680 return List.IsSynchronized;
684 public object SyncRoot {
686 return List.SyncRoot;
690 public void CopyTo (Array array, int index)
692 List.CopyTo (array, index);
697 public IEnumerator GetEnumerator ()
699 return List.GetEnumerator ();
704 public bool IsFixedSize {
710 public bool IsReadOnly {
716 object IList.this [int index] {
722 throw new NotSupportedException ();
726 // FIXME: try to find out whether we can avoid the cast in this indexer.
727 public MemberInfo this [int index] {
729 return (MemberInfo) List [index];
733 public int Add (object value)
735 throw new NotSupportedException ();
740 throw new NotSupportedException ();
743 public bool Contains (object value)
745 return List.Contains (value);
748 public int IndexOf (object value)
750 return List.IndexOf (value);
753 public void Insert (int index, object value)
755 throw new NotSupportedException ();
758 public void Remove (object value)
760 throw new NotSupportedException ();
763 public void RemoveAt (int index)
765 throw new NotSupportedException ();
770 /// This interface is used to get all members of a class when creating the
771 /// member cache. It must be implemented by all DeclSpace derivatives which
772 /// want to support the member cache and by TypeHandle to get caching of
773 /// non-dynamic types.
775 public interface IMemberContainer {
777 /// The name of the IMemberContainer. This is only used for
778 /// debugging purposes.
785 /// The type of this IMemberContainer.
792 /// Returns the IMemberContainer of the parent class or null if this
793 /// is an interface or TypeManger.object_type.
794 /// This is used when creating the member cache for a class to get all
795 /// members from the parent class.
797 IMemberContainer Parent {
802 /// Whether this is an interface.
809 /// Returns all members of this class with the corresponding MemberTypes
810 /// and BindingFlags.
813 /// When implementing this method, make sure not to return any inherited
814 /// members and check the MemberTypes and BindingFlags properly.
815 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
816 /// get the BindingFlags (static/non-static,public/non-public) in the
817 /// MemberInfo class, but the cache needs this information. That's why
818 /// this method is called multiple times with different BindingFlags.
820 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
823 /// Return the container's member cache.
825 MemberCache MemberCache {
831 /// The MemberCache is used by dynamic and non-dynamic types to speed up
832 /// member lookups. It has a member name based hash table; it maps each member
833 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
834 /// and the BindingFlags that were initially used to get it. The cache contains
835 /// all members of the current class and all inherited members. If this cache is
836 /// for an interface types, it also contains all inherited members.
838 /// There are two ways to get a MemberCache:
839 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
840 /// use the DeclSpace.MemberCache property.
841 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
842 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
844 public class MemberCache {
845 public readonly IMemberContainer Container;
846 protected CaseInsensitiveHashtable member_hash;
847 protected CaseInsensitiveHashtable method_hash;
848 protected CaseInsensitiveHashtable interface_hash;
851 /// Create a new MemberCache for the given IMemberContainer `container'.
853 public MemberCache (IMemberContainer container)
855 this.Container = container;
857 Timer.IncrementCounter (CounterType.MemberCache);
858 Timer.StartTimer (TimerType.CacheInit);
860 interface_hash = new CaseInsensitiveHashtable ();
862 // If we have a parent class (we have a parent class unless we're
863 // TypeManager.object_type), we deep-copy its MemberCache here.
864 if (Container.Parent != null)
865 member_hash = SetupCache (Container.Parent.MemberCache);
866 else if (Container.IsInterface)
867 member_hash = SetupCacheForInterface ();
869 member_hash = new CaseInsensitiveHashtable ();
871 // If this is neither a dynamic type nor an interface, create a special
872 // method cache with all declared and inherited methods.
873 Type type = container.Type;
874 if (!(type is TypeBuilder) && !type.IsInterface) {
875 method_hash = new CaseInsensitiveHashtable ();
879 // Add all members from the current class.
880 AddMembers (Container);
882 Timer.StopTimer (TimerType.CacheInit);
886 /// Bootstrap this member cache by doing a deep-copy of our parent.
888 CaseInsensitiveHashtable SetupCache (MemberCache parent)
890 CaseInsensitiveHashtable hash = new CaseInsensitiveHashtable ();
892 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
893 while (it.MoveNext ()) {
894 ArrayList al = (ArrayList) it.Value;
895 // Constructors are never inherited and all have the same key
896 if ((((CacheEntry)al [0]).EntryType & EntryType.Constructor) == 0)
897 hash [it.Key] = ((ArrayList) it.Value).Clone ();
903 void AddInterfaces (MemberCache parent)
905 foreach (Type iface in parent.interface_hash.Keys) {
906 if (!interface_hash.Contains (iface))
907 interface_hash.Add (iface, true);
912 /// Add the contents of `new_hash' to `hash'.
914 void AddHashtable (Hashtable hash, Hashtable new_hash)
916 IDictionaryEnumerator it = new_hash.GetEnumerator ();
917 while (it.MoveNext ()) {
918 ArrayList list = (ArrayList) hash [it.Key];
920 list.AddRange ((ArrayList) it.Value);
922 hash [it.Key] = ((ArrayList) it.Value).Clone ();
927 /// Bootstrap the member cache for an interface type.
928 /// Type.GetMembers() won't return any inherited members for interface types,
929 /// so we need to do this manually. Interfaces also inherit from System.Object.
931 CaseInsensitiveHashtable SetupCacheForInterface ()
933 CaseInsensitiveHashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
934 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
936 foreach (Type iface in ifaces) {
937 if (interface_hash.Contains (iface))
939 interface_hash.Add (iface, true);
941 IMemberContainer iface_container =
942 TypeManager.LookupMemberContainer (iface);
944 MemberCache iface_cache = iface_container.MemberCache;
945 AddHashtable (hash, iface_cache.member_hash);
946 AddInterfaces (iface_cache);
953 /// Add all members from class `container' to the cache.
955 void AddMembers (IMemberContainer container)
957 // We need to call AddMembers() with a single member type at a time
958 // to get the member type part of CacheEntry.EntryType right.
959 AddMembers (MemberTypes.Constructor, container);
960 AddMembers (MemberTypes.Field, container);
961 AddMembers (MemberTypes.Method, container);
962 AddMembers (MemberTypes.Property, container);
963 AddMembers (MemberTypes.Event, container);
964 // Nested types are returned by both Static and Instance searches.
965 AddMembers (MemberTypes.NestedType,
966 BindingFlags.Static | BindingFlags.Public, container);
967 AddMembers (MemberTypes.NestedType,
968 BindingFlags.Static | BindingFlags.NonPublic, container);
971 void AddMembers (MemberTypes mt, IMemberContainer container)
973 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
974 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
975 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
976 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
980 /// Add all members from class `container' with the requested MemberTypes and
981 /// BindingFlags to the cache. This method is called multiple times with different
982 /// MemberTypes and BindingFlags.
984 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
986 MemberList members = container.GetMembers (mt, bf);
987 /*BindingFlags new_bf = (container == Container) ?
988 bf | BindingFlags.DeclaredOnly : bf;
990 foreach (MemberInfo member in members) {
991 string name = member.Name;
993 // We use a name-based hash table of ArrayList's.
994 ArrayList list = (ArrayList) member_hash [name];
996 list = new ArrayList ();
997 member_hash.Add (name, list);
1000 // When this method is called for the current class, the list will
1001 // already contain all inherited members from our parent classes.
1002 // We cannot add new members in front of the list since this'd be an
1003 // expensive operation, that's why the list is sorted in reverse order
1004 // (ie. members from the current class are coming last).
1005 list.Add (new CacheEntry (container, member, mt, bf));
1010 /// Add all declared and inherited methods from class `type' to the method cache.
1012 void AddMethods (Type type)
1014 AddMethods (BindingFlags.Static | BindingFlags.Public, type);
1015 AddMethods (BindingFlags.Static | BindingFlags.NonPublic, type);
1016 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1017 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1020 void AddMethods (BindingFlags bf, Type type)
1022 MemberInfo [] members = type.GetMethods (bf);
1024 foreach (MethodBase member in members) {
1025 string name = member.Name;
1027 // Varargs methods aren't allowed in C# code.
1028 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1031 // We use a name-based hash table of ArrayList's.
1032 ArrayList list = (ArrayList) method_hash [name];
1034 list = new ArrayList ();
1035 method_hash.Add (name, list);
1038 // Unfortunately, the elements returned by Type.GetMethods() aren't
1039 // sorted so we need to do this check for every member.
1040 BindingFlags new_bf = bf;
1041 if (member.DeclaringType == type)
1042 new_bf |= BindingFlags.DeclaredOnly;
1044 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1049 /// Compute and return a appropriate `EntryType' magic number for the given
1050 /// MemberTypes and BindingFlags.
1052 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1054 EntryType type = EntryType.None;
1056 if ((mt & MemberTypes.Constructor) != 0)
1057 type |= EntryType.Constructor;
1058 if ((mt & MemberTypes.Event) != 0)
1059 type |= EntryType.Event;
1060 if ((mt & MemberTypes.Field) != 0)
1061 type |= EntryType.Field;
1062 if ((mt & MemberTypes.Method) != 0)
1063 type |= EntryType.Method;
1064 if ((mt & MemberTypes.Property) != 0)
1065 type |= EntryType.Property;
1066 // Nested types are returned by static and instance searches.
1067 if ((mt & MemberTypes.NestedType) != 0)
1068 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1070 if ((bf & BindingFlags.Instance) != 0)
1071 type |= EntryType.Instance;
1072 if ((bf & BindingFlags.Static) != 0)
1073 type |= EntryType.Static;
1074 if ((bf & BindingFlags.Public) != 0)
1075 type |= EntryType.Public;
1076 if ((bf & BindingFlags.NonPublic) != 0)
1077 type |= EntryType.NonPublic;
1078 if ((bf & BindingFlags.DeclaredOnly) != 0)
1079 type |= EntryType.Declared;
1085 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1086 /// denote multiple member types. Returns true if the given flags value denotes a
1087 /// single member types.
1089 public static bool IsSingleMemberType (MemberTypes mt)
1092 case MemberTypes.Constructor:
1093 case MemberTypes.Event:
1094 case MemberTypes.Field:
1095 case MemberTypes.Method:
1096 case MemberTypes.Property:
1097 case MemberTypes.NestedType:
1106 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1107 /// number to speed up the searching process.
1110 protected enum EntryType {
1115 MaskStatic = Instance|Static,
1119 MaskProtection = Public|NonPublic,
1123 Constructor = 0x020,
1130 MaskType = Constructor|Event|Field|Method|Property|NestedType
1133 protected struct CacheEntry {
1134 public readonly IMemberContainer Container;
1135 public readonly EntryType EntryType;
1136 public readonly MemberInfo Member;
1138 public CacheEntry (IMemberContainer container, MemberInfo member,
1139 MemberTypes mt, BindingFlags bf)
1141 this.Container = container;
1142 this.Member = member;
1143 this.EntryType = GetEntryType (mt, bf);
1148 /// This is called each time we're walking up one level in the class hierarchy
1149 /// and checks whether we can abort the search since we've already found what
1150 /// we were looking for.
1152 protected bool DoneSearching (ArrayList list)
1155 // We've found exactly one member in the current class and it's not
1156 // a method or constructor.
1158 if (list.Count == 1 && !(list [0] is MethodBase))
1162 // Multiple properties: we query those just to find out the indexer
1165 if ((list.Count > 0) && (list [0] is PropertyInfo))
1172 /// Looks up members with name `name'. If you provide an optional
1173 /// filter function, it'll only be called with members matching the
1174 /// requested member name.
1176 /// This method will try to use the cache to do the lookup if possible.
1178 /// Unlike other FindMembers implementations, this method will always
1179 /// check all inherited members - even when called on an interface type.
1181 /// If you know that you're only looking for methods, you should use
1182 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1183 /// When doing a method-only search, it'll try to use a special method
1184 /// cache (unless it's a dynamic type or an interface) and the returned
1185 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1186 /// The lookup process will automatically restart itself in method-only
1187 /// search mode if it discovers that it's about to return methods.
1189 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1190 MemberFilter filter, object criteria)
1192 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1193 bool method_search = mt == MemberTypes.Method;
1194 // If we have a method cache and we aren't already doing a method-only search,
1195 // then we restart a method search if the first match is a method.
1196 bool do_method_search = !method_search && (method_hash != null);
1197 bf |= BindingFlags.IgnoreCase;
1198 ArrayList applicable;
1200 // If this is a method-only search, we try to use the method cache if
1201 // possible; a lookup in the method cache will return a MemberInfo with
1202 // the correct ReflectedType for inherited methods.
1203 if (method_search && (method_hash != null))
1204 applicable = (ArrayList) method_hash [name];
1206 applicable = (ArrayList) member_hash [name];
1208 if (applicable == null)
1209 return MemberList.Empty;
1211 ArrayList list = new ArrayList ();
1213 Timer.StartTimer (TimerType.CachedLookup);
1215 EntryType type = GetEntryType (mt, bf);
1217 IMemberContainer current = Container;
1219 // `applicable' is a list of all members with the given member name `name'
1220 // in the current class and all its parent classes. The list is sorted in
1221 // reverse order due to the way how the cache is initialy created (to speed
1222 // things up, we're doing a deep-copy of our parent).
1224 for (int i = applicable.Count-1; i >= 0; i--) {
1225 CacheEntry entry = (CacheEntry) applicable [i];
1227 // This happens each time we're walking one level up in the class
1228 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1229 // the first time this happens (this may already happen in the first
1230 // iteration of this loop if there are no members with the name we're
1231 // looking for in the current class).
1232 if (entry.Container != current) {
1233 //if (declared_only || DoneSearching (list))
1237 current = entry.Container;
1240 // Is the member of the correct type ?
1241 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1244 // Is the member static/non-static ?
1245 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1248 // Apply the filter to it.
1249 if (filter (entry.Member, criteria)) {
1250 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1251 do_method_search = false;
1252 list.Add (entry.Member);
1256 Timer.StopTimer (TimerType.CachedLookup);
1258 // If we have a method cache and we aren't already doing a method-only
1259 // search, we restart in method-only search mode if the first match is
1260 // a method. This ensures that we return a MemberInfo with the correct
1261 // ReflectedType for inherited methods.
1262 if (do_method_search && (list.Count > 0))
1263 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1265 return new MemberList (list);