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;
41 /// Attributes for this type
43 Attributes attributes;
45 public MemberCore (string name, Attributes attrs, Location loc)
52 public abstract bool Define (TypeContainer parent);
54 public Attributes OptAttributes
65 // Whehter is it ok to use an unsafe pointer in this type container
67 public bool UnsafeOK (DeclSpace parent)
70 // First check if this MemberCore modifier flags has unsafe set
72 if ((ModFlags & Modifiers.UNSAFE) != 0)
75 if (parent.UnsafeContext)
78 Expression.UnsafeError (Location);
84 /// Base class for structs, classes, enumerations and interfaces.
87 /// They all create new declaration spaces. This
88 /// provides the common foundation for managing those name
91 public abstract class DeclSpace : MemberCore {
93 /// This points to the actual definition that is being
94 /// created with System.Reflection.Emit
96 public TypeBuilder TypeBuilder;
99 /// If we are a generic type, this is the type we are
100 /// currently defining. We need to lookup members on this
101 /// instead of the TypeBuilder.
103 public TypeExpr CurrentType;
106 /// This variable tracks whether we have Closed the type
108 public bool Created = false;
111 // This is the namespace in which this typecontainer
112 // was declared. We use this to resolve names.
114 public NamespaceEntry NamespaceEntry;
116 public Hashtable Cache = new Hashtable ();
118 public string Basename;
121 /// defined_names is used for toplevel objects
123 protected Hashtable defined_names;
126 // Whether we are Generic
128 public bool IsGeneric;
130 TypeContainer parent;
132 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
133 : base (name, attrs, l)
136 Basename = name.Substring (1 + name.LastIndexOf ('.'));
137 defined_names = new Hashtable ();
138 this.parent = parent;
141 public void RecordDecl ()
143 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
144 NamespaceEntry.DefineName (Basename, this);
148 /// The result value from adding an declaration into
149 /// a struct or a class
151 public enum AdditionResult {
153 /// The declaration has been successfully
154 /// added to the declation space.
159 /// The symbol has already been defined.
164 /// Returned if the declation being added to the
165 /// name space clashes with its container name.
167 /// The only exceptions for this are constructors
168 /// and static constructors
173 /// Returned if a constructor was created (because syntactically
174 /// it looked like a constructor) but was not (because the name
175 /// of the method is not the same as the container class
180 /// This is only used by static constructors to emit the
181 /// error 111, but this error for other things really
182 /// happens at another level for other functions.
187 /// Some other error.
193 /// Returns a status code based purely on the name
194 /// of the member being added
196 protected AdditionResult IsValid (string basename, string name)
198 if (basename == Basename)
199 return AdditionResult.EnclosingClash;
201 if (defined_names.Contains (name))
202 return AdditionResult.NameExists;
204 return AdditionResult.Success;
207 public static int length;
208 public static int small;
211 /// Introduce @name into this declaration space and
212 /// associates it with the object @o. Note that for
213 /// methods this will just point to the first method. o
215 protected void DefineName (string name, object o)
217 defined_names.Add (name, o);
220 int p = name.LastIndexOf ('.');
228 /// Returns the object associated with a given name in the declaration
229 /// space. This is the inverse operation of `DefineName'
231 public object GetDefinition (string name)
233 return defined_names [name];
236 bool in_transit = false;
239 /// This function is used to catch recursive definitions
242 public bool InTransit {
252 public TypeContainer Parent {
259 /// Looks up the alias for the name
261 public string LookupAlias (string name)
263 if (NamespaceEntry != null)
264 return NamespaceEntry.LookupAlias (name);
270 // root_types contains all the types. All TopLevel types
271 // hence have a parent that points to `root_types', that is
272 // why there is a non-obvious test down here.
274 public bool IsTopLevel {
277 if (parent.parent == null)
284 public virtual void CloseType ()
288 TypeBuilder.CreateType ();
291 // The try/catch is needed because
292 // nested enumerations fail to load when they
295 // Even if this is the right order (enumerations
296 // declared after types).
298 // Note that this still creates the type and
299 // it is possible to save it
306 /// Should be overriten by the appropriate declaration space
308 public abstract TypeBuilder DefineType ();
311 /// Define all members, but don't apply any attributes or do anything which may
312 /// access not-yet-defined classes. This method also creates the MemberCache.
314 public abstract bool DefineMembers (TypeContainer parent);
317 // Whether this is an `unsafe context'
319 public bool UnsafeContext {
321 if ((ModFlags & Modifiers.UNSAFE) != 0)
324 return parent.UnsafeContext;
329 public static string MakeFQN (string nsn, string name)
333 return String.Concat (nsn, ".", name);
336 EmitContext type_resolve_ec;
337 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
339 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
340 type_resolve_ec.ResolvingTypeTree = true;
342 return type_resolve_ec;
346 // Looks up the type, as parsed into the expression `e'
348 public Type ResolveType (Expression e, bool silent, Location loc)
350 if (type_resolve_ec == null)
351 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
352 type_resolve_ec.loc = loc;
353 type_resolve_ec.ContainerType = TypeBuilder;
355 int errors = Report.Errors;
356 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
358 if (d == null || d.eclass != ExprClass.Type){
359 if (!silent && errors == Report.Errors){
360 Console.WriteLine ("Type is: " + e.GetType().ToString ());
361 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
366 if (!d.CheckAccessLevel (this)) {
367 Report. Error (122, loc, "`" + d.Name + "' " +
368 "is inaccessible because of its protection level");
372 return d.ResolveType (type_resolve_ec);
376 // Resolves the expression `e' for a type, and will recursively define
379 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
381 if (type_resolve_ec == null)
382 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
383 type_resolve_ec.loc = loc;
384 type_resolve_ec.ContainerType = TypeBuilder;
386 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
388 if (d == null || d.eclass != ExprClass.Type){
390 Report.Error (246, loc, "Cannot find type `"+ e +"'");
398 public bool CheckAccessLevel (Type check_type)
400 if (check_type == TypeBuilder)
403 if (check_type.IsGenericParameter)
404 return true; // FIXME
406 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
409 // Broken Microsoft runtime, return public for arrays, no matter what
410 // the accessibility is for their underlying class, and they return
411 // NonPublic visibility for pointers
413 if (check_type.IsArray || check_type.IsPointer)
414 return CheckAccessLevel (TypeManager.GetElementType (check_type));
417 case TypeAttributes.Public:
420 case TypeAttributes.NotPublic:
422 // This test should probably use the declaringtype.
424 if (check_type.Assembly == TypeBuilder.Assembly){
429 case TypeAttributes.NestedPublic:
432 case TypeAttributes.NestedPrivate:
433 string check_type_name = check_type.FullName;
434 string type_name = TypeBuilder.FullName;
436 int cio = check_type_name.LastIndexOf ('+');
437 string container = check_type_name.Substring (0, cio);
440 // Check if the check_type is a nested class of the current type
442 if (check_type_name.StartsWith (type_name + "+")){
446 if (type_name.StartsWith (container)){
452 case TypeAttributes.NestedFamily:
454 // Only accessible to methods in current type or any subtypes
456 return FamilyAccessible (check_type);
458 case TypeAttributes.NestedFamANDAssem:
459 return (check_type.Assembly == TypeBuilder.Assembly) &&
460 FamilyAccessible (check_type);
462 case TypeAttributes.NestedFamORAssem:
463 return (check_type.Assembly == TypeBuilder.Assembly) ||
464 FamilyAccessible (check_type);
466 case TypeAttributes.NestedAssembly:
467 return check_type.Assembly == TypeBuilder.Assembly;
470 Console.WriteLine ("HERE: " + check_attr);
475 protected bool FamilyAccessible (Type check_type)
477 Type declaring = check_type.DeclaringType;
478 if (TypeBuilder.IsSubclassOf (declaring))
481 string check_type_name = check_type.FullName;
483 int cio = check_type_name.LastIndexOf ('+');
484 string container = check_type_name.Substring (0, cio);
487 // Check if the check_type is a nested class of the current type
489 if (check_type_name.StartsWith (container + "+"))
495 // Access level of a type.
497 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
498 // Public Assembly Protected
499 Protected = (0 << 0) | (0 << 1) | (X << 2),
500 Public = (X << 0) | (X << 1) | (X << 2),
501 Private = (0 << 0) | (0 << 1) | (0 << 2),
502 Internal = (0 << 0) | (X << 1) | (0 << 2),
503 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
506 static AccessLevel GetAccessLevelFromModifiers (int flags)
508 if ((flags & Modifiers.INTERNAL) != 0) {
510 if ((flags & Modifiers.PROTECTED) != 0)
511 return AccessLevel.ProtectedOrInternal;
513 return AccessLevel.Internal;
515 } else if ((flags & Modifiers.PROTECTED) != 0)
516 return AccessLevel.Protected;
517 else if ((flags & Modifiers.PRIVATE) != 0)
518 return AccessLevel.Private;
520 return AccessLevel.Public;
523 // What is the effective access level of this?
525 AccessLevel EffectiveAccessLevel {
527 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
528 if (!IsTopLevel && (Parent != null))
529 return myAccess & Parent.EffectiveAccessLevel;
534 // Return the access level for type `t'
535 static AccessLevel TypeEffectiveAccessLevel (Type t)
538 return AccessLevel.Public;
539 if (t.IsNestedPrivate)
540 return AccessLevel.Private;
542 return AccessLevel.Internal;
544 // By now, it must be nested
545 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
547 if (t.IsNestedPublic)
549 if (t.IsNestedAssembly)
550 return parentLevel & AccessLevel.Internal;
551 if (t.IsNestedFamily)
552 return parentLevel & AccessLevel.Protected;
553 if (t.IsNestedFamORAssem)
554 return parentLevel & AccessLevel.ProtectedOrInternal;
555 if (t.IsNestedFamANDAssem)
556 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
558 // nested private is taken care of
560 throw new Exception ("I give up, what are you?");
564 // This answers `is the type P, as accessible as a member M which has the
565 // accessability @flags which is declared as a nested member of the type T, this declspace'
567 public bool AsAccessible (Type p, int flags)
569 if (p.IsGenericParameter)
570 return true; // FIXME
573 // 1) if M is private, its accessability is the same as this declspace.
574 // we already know that P is accessible to T before this method, so we
578 if ((flags & Modifiers.PRIVATE) != 0)
581 while (p.IsArray || p.IsPointer || p.IsByRef)
582 p = TypeManager.GetElementType (p);
584 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
585 AccessLevel mAccess = this.EffectiveAccessLevel &
586 GetAccessLevelFromModifiers (flags);
588 // for every place from which we can access M, we must
589 // be able to access P as well. So, we want
590 // For every bit in M and P, M_i -> P_1 == true
591 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
593 return ~ (~ mAccess | pAccess) == 0;
596 static DoubleHash dh = new DoubleHash (1000);
598 Type LookupInterfaceOrClass (string ns, string name, out bool error)
606 if (dh.Lookup (ns, name, out r))
610 if (Namespace.IsNamespace (ns)){
611 string fullname = (ns != "") ? ns + "." + name : name;
612 t = TypeManager.LookupType (fullname);
616 t = TypeManager.LookupType (name);
620 dh.Insert (ns, name, t);
625 // In case we are fed a composite name, normalize it.
627 int p = name.LastIndexOf ('.');
629 ns = MakeFQN (ns, name.Substring (0, p));
630 name = name.Substring (p+1);
633 parent = RootContext.Tree.LookupByNamespace (ns, name);
634 if (parent == null) {
635 dh.Insert (ns, name, null);
639 t = parent.DefineType ();
645 dh.Insert (ns, name, t);
649 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
651 Report.Error (104, loc,
652 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
653 t1.FullName, t2.FullName));
657 /// GetType is used to resolve type names at the DeclSpace level.
658 /// Use this to lookup class/struct bases, interface bases or
659 /// delegate type references
663 /// Contrast this to LookupType which is used inside method bodies to
664 /// lookup types that have already been defined. GetType is used
665 /// during the tree resolution process and potentially define
666 /// recursively the type
668 public Type FindType (Location loc, string name)
674 // For the case the type we are looking for is nested within this one
675 // or is in any base class
677 DeclSpace containing_ds = this;
679 while (containing_ds != null){
680 Type container_type = containing_ds.TypeBuilder;
681 Type current_type = container_type;
683 while (current_type != null && current_type != TypeManager.object_type) {
684 string pre = current_type.FullName;
686 t = LookupInterfaceOrClass (pre, name, out error);
690 if ((t != null) && containing_ds.CheckAccessLevel (t))
693 current_type = current_type.BaseType;
695 containing_ds = containing_ds.Parent;
699 // Attempt to lookup the class on our namespace and all it's implicit parents
701 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
702 t = LookupInterfaceOrClass (ns.FullName, name, out error);
711 // Attempt to do a direct unqualified lookup
713 t = LookupInterfaceOrClass ("", name, out error);
721 // Attempt to lookup the class on any of the `using'
725 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
727 t = LookupInterfaceOrClass (ns.FullName, name, out error);
735 // Now check the using clause list
738 foreach (Namespace using_ns in ns.GetUsingTable ()) {
739 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
745 if (CheckAccessLevel (match)) {
746 Error_AmbiguousTypeReference (loc, name, t, match);
759 //Report.Error (246, Location, "Can not find type `"+name+"'");
764 /// This function is broken and not what you're looking for. It should only
765 /// be used while the type is still being created since it doesn't use the cache
766 /// and relies on the filter doing the member name check.
768 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
769 MemberFilter filter, object criteria);
772 /// If we have a MemberCache, return it. This property may return null if the
773 /// class doesn't have a member cache or while it's still being created.
775 public abstract MemberCache MemberCache {
780 // Extensions for generics
782 TypeParameter[] type_params;
785 /// Called by the parser to configure the type_parameter_list for this
786 /// declaration space
788 public AdditionResult SetParameterInfo (ArrayList type_parameter_list, ArrayList constraints_list)
790 type_params = new TypeParameter [type_parameter_list.Count];
793 // Mark this type as Generic
798 // Register all the names
800 for (int i = 0; i < type_parameter_list.Count; i++) {
801 string name = (string) type_parameter_list [i];
803 AdditionResult res = IsValid (name, name);
805 if (res != AdditionResult.Success)
808 Constraints constraints = null;
809 if (constraints_list != null) {
810 foreach (Constraints constraint in constraints_list) {
811 if (constraint.TypeParameter == name) {
812 constraints = constraint;
818 type_params [i] = new TypeParameter (name, constraints, Location);
820 DefineName (name, type_params [i]);
823 return AdditionResult.Success;
826 public TypeParameter[] TypeParameters {
832 public TypeParameterExpr LookupGeneric (string name, Location loc)
834 if (TypeParameters != null) {
835 foreach (TypeParameter type_param in TypeParameters) {
836 if (type_param.Name != name)
839 return new TypeParameterExpr (type_param, loc);
844 return parent.LookupGeneric (name, loc);
851 /// This is a readonly list of MemberInfo's.
853 public class MemberList : IList {
854 public readonly IList List;
858 /// Create a new MemberList from the given IList.
860 public MemberList (IList list)
865 this.List = new ArrayList ();
870 /// Concatenate the ILists `first' and `second' to a new MemberList.
872 public MemberList (IList first, IList second)
874 ArrayList list = new ArrayList ();
875 list.AddRange (first);
876 list.AddRange (second);
881 public static readonly MemberList Empty = new MemberList (new ArrayList ());
884 /// Cast the MemberList into a MemberInfo[] array.
887 /// This is an expensive operation, only use it if it's really necessary.
889 public static explicit operator MemberInfo [] (MemberList list)
891 Timer.StartTimer (TimerType.MiscTimer);
892 MemberInfo [] result = new MemberInfo [list.Count];
893 list.CopyTo (result, 0);
894 Timer.StopTimer (TimerType.MiscTimer);
906 public bool IsSynchronized {
908 return List.IsSynchronized;
912 public object SyncRoot {
914 return List.SyncRoot;
918 public void CopyTo (Array array, int index)
920 List.CopyTo (array, index);
925 public IEnumerator GetEnumerator ()
927 return List.GetEnumerator ();
932 public bool IsFixedSize {
938 public bool IsReadOnly {
944 object IList.this [int index] {
950 throw new NotSupportedException ();
954 // FIXME: try to find out whether we can avoid the cast in this indexer.
955 public MemberInfo this [int index] {
957 return (MemberInfo) List [index];
961 public int Add (object value)
963 throw new NotSupportedException ();
968 throw new NotSupportedException ();
971 public bool Contains (object value)
973 return List.Contains (value);
976 public int IndexOf (object value)
978 return List.IndexOf (value);
981 public void Insert (int index, object value)
983 throw new NotSupportedException ();
986 public void Remove (object value)
988 throw new NotSupportedException ();
991 public void RemoveAt (int index)
993 throw new NotSupportedException ();
998 /// This interface is used to get all members of a class when creating the
999 /// member cache. It must be implemented by all DeclSpace derivatives which
1000 /// want to support the member cache and by TypeHandle to get caching of
1001 /// non-dynamic types.
1003 public interface IMemberContainer {
1005 /// The name of the IMemberContainer. This is only used for
1006 /// debugging purposes.
1013 /// The type of this IMemberContainer.
1020 /// Returns the IMemberContainer of the parent class or null if this
1021 /// is an interface or TypeManger.object_type.
1022 /// This is used when creating the member cache for a class to get all
1023 /// members from the parent class.
1025 IMemberContainer Parent {
1030 /// Whether this is an interface.
1037 /// Returns all members of this class with the corresponding MemberTypes
1038 /// and BindingFlags.
1041 /// When implementing this method, make sure not to return any inherited
1042 /// members and check the MemberTypes and BindingFlags properly.
1043 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1044 /// get the BindingFlags (static/non-static,public/non-public) in the
1045 /// MemberInfo class, but the cache needs this information. That's why
1046 /// this method is called multiple times with different BindingFlags.
1048 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1051 /// Return the container's member cache.
1053 MemberCache MemberCache {
1059 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1060 /// member lookups. It has a member name based hash table; it maps each member
1061 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1062 /// and the BindingFlags that were initially used to get it. The cache contains
1063 /// all members of the current class and all inherited members. If this cache is
1064 /// for an interface types, it also contains all inherited members.
1066 /// There are two ways to get a MemberCache:
1067 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1068 /// use the DeclSpace.MemberCache property.
1069 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1070 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1072 public class MemberCache {
1073 public readonly IMemberContainer Container;
1074 protected Hashtable member_hash;
1075 protected Hashtable method_hash;
1077 Hashtable interface_hash;
1080 /// Create a new MemberCache for the given IMemberContainer `container'.
1082 public MemberCache (IMemberContainer container)
1084 this.Container = container;
1086 Timer.IncrementCounter (CounterType.MemberCache);
1087 Timer.StartTimer (TimerType.CacheInit);
1091 // If we have a parent class (we have a parent class unless we're
1092 // TypeManager.object_type), we deep-copy its MemberCache here.
1093 if (Container.IsInterface) {
1095 interface_hash = new Hashtable ();
1097 if (Container.Parent != null)
1098 parent = Container.Parent.MemberCache;
1100 parent = TypeHandle.ObjectType.MemberCache;
1101 member_hash = SetupCacheForInterface (parent);
1102 } else if (Container.Parent != null)
1103 member_hash = SetupCache (Container.Parent.MemberCache);
1105 member_hash = new Hashtable ();
1107 // If this is neither a dynamic type nor an interface, create a special
1108 // method cache with all declared and inherited methods.
1109 Type type = container.Type;
1110 if (!(type is TypeBuilder) && !type.IsInterface) {
1111 method_hash = new Hashtable ();
1115 // Add all members from the current class.
1116 AddMembers (Container);
1118 Timer.StopTimer (TimerType.CacheInit);
1122 /// Bootstrap this member cache by doing a deep-copy of our parent.
1124 Hashtable SetupCache (MemberCache parent)
1126 Hashtable hash = new Hashtable ();
1128 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1129 while (it.MoveNext ()) {
1130 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1138 /// Add the contents of `new_hash' to `hash'.
1140 void AddHashtable (Hashtable hash, Hashtable new_hash)
1142 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1143 while (it.MoveNext ()) {
1144 ArrayList list = (ArrayList) hash [it.Key];
1146 list.AddRange ((ArrayList) it.Value);
1148 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1153 /// Bootstrap the member cache for an interface type.
1154 /// Type.GetMembers() won't return any inherited members for interface types,
1155 /// so we need to do this manually. Interfaces also inherit from System.Object.
1157 Hashtable SetupCacheForInterface (MemberCache parent)
1159 Hashtable hash = SetupCache (parent);
1160 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1162 foreach (TypeExpr iface in ifaces) {
1163 Type itype = iface.Type;
1165 if (interface_hash.Contains (itype))
1168 interface_hash [itype] = null;
1170 IMemberContainer iface_container =
1171 TypeManager.LookupMemberContainer (itype);
1173 MemberCache iface_cache = iface_container.MemberCache;
1175 AddHashtable (hash, iface_cache.member_hash);
1177 if (iface_cache.interface_hash == null)
1180 foreach (Type parent_contains in iface_cache.interface_hash.Keys)
1181 interface_hash [parent_contains] = null;
1188 /// Add all members from class `container' to the cache.
1190 void AddMembers (IMemberContainer container)
1192 // We need to call AddMembers() with a single member type at a time
1193 // to get the member type part of CacheEntry.EntryType right.
1194 AddMembers (MemberTypes.Constructor, container);
1195 AddMembers (MemberTypes.Field, container);
1196 AddMembers (MemberTypes.Method, container);
1197 AddMembers (MemberTypes.Property, container);
1198 AddMembers (MemberTypes.Event, container);
1199 // Nested types are returned by both Static and Instance searches.
1200 AddMembers (MemberTypes.NestedType,
1201 BindingFlags.Static | BindingFlags.Public, container);
1202 AddMembers (MemberTypes.NestedType,
1203 BindingFlags.Static | BindingFlags.NonPublic, container);
1206 void AddMembers (MemberTypes mt, IMemberContainer container)
1208 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1209 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1210 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1211 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1215 /// Add all members from class `container' with the requested MemberTypes and
1216 /// BindingFlags to the cache. This method is called multiple times with different
1217 /// MemberTypes and BindingFlags.
1219 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1221 MemberList members = container.GetMembers (mt, bf);
1223 foreach (MemberInfo member in members) {
1224 string name = member.Name;
1226 // We use a name-based hash table of ArrayList's.
1227 ArrayList list = (ArrayList) member_hash [name];
1229 list = new ArrayList ();
1230 member_hash.Add (name, list);
1233 // When this method is called for the current class, the list will
1234 // already contain all inherited members from our parent classes.
1235 // We cannot add new members in front of the list since this'd be an
1236 // expensive operation, that's why the list is sorted in reverse order
1237 // (ie. members from the current class are coming last).
1238 list.Add (new CacheEntry (container, member, mt, bf));
1243 /// Add all declared and inherited methods from class `type' to the method cache.
1245 void AddMethods (Type type)
1247 AddMethods (BindingFlags.Static | BindingFlags.Public |
1248 BindingFlags.FlattenHierarchy, type);
1249 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1250 BindingFlags.FlattenHierarchy, type);
1251 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1252 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1255 void AddMethods (BindingFlags bf, Type type)
1257 MemberInfo [] members = type.GetMethods (bf);
1259 foreach (MethodBase member in members) {
1260 string name = member.Name;
1262 // Varargs methods aren't allowed in C# code.
1263 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1266 // We use a name-based hash table of ArrayList's.
1267 ArrayList list = (ArrayList) method_hash [name];
1269 list = new ArrayList ();
1270 method_hash.Add (name, list);
1273 // Unfortunately, the elements returned by Type.GetMethods() aren't
1274 // sorted so we need to do this check for every member.
1275 BindingFlags new_bf = bf;
1276 if (member.DeclaringType == type)
1277 new_bf |= BindingFlags.DeclaredOnly;
1279 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1284 /// Compute and return a appropriate `EntryType' magic number for the given
1285 /// MemberTypes and BindingFlags.
1287 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1289 EntryType type = EntryType.None;
1291 if ((mt & MemberTypes.Constructor) != 0)
1292 type |= EntryType.Constructor;
1293 if ((mt & MemberTypes.Event) != 0)
1294 type |= EntryType.Event;
1295 if ((mt & MemberTypes.Field) != 0)
1296 type |= EntryType.Field;
1297 if ((mt & MemberTypes.Method) != 0)
1298 type |= EntryType.Method;
1299 if ((mt & MemberTypes.Property) != 0)
1300 type |= EntryType.Property;
1301 // Nested types are returned by static and instance searches.
1302 if ((mt & MemberTypes.NestedType) != 0)
1303 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1305 if ((bf & BindingFlags.Instance) != 0)
1306 type |= EntryType.Instance;
1307 if ((bf & BindingFlags.Static) != 0)
1308 type |= EntryType.Static;
1309 if ((bf & BindingFlags.Public) != 0)
1310 type |= EntryType.Public;
1311 if ((bf & BindingFlags.NonPublic) != 0)
1312 type |= EntryType.NonPublic;
1313 if ((bf & BindingFlags.DeclaredOnly) != 0)
1314 type |= EntryType.Declared;
1320 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1321 /// denote multiple member types. Returns true if the given flags value denotes a
1322 /// single member types.
1324 public static bool IsSingleMemberType (MemberTypes mt)
1327 case MemberTypes.Constructor:
1328 case MemberTypes.Event:
1329 case MemberTypes.Field:
1330 case MemberTypes.Method:
1331 case MemberTypes.Property:
1332 case MemberTypes.NestedType:
1341 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1342 /// number to speed up the searching process.
1345 protected enum EntryType {
1350 MaskStatic = Instance|Static,
1354 MaskProtection = Public|NonPublic,
1358 Constructor = 0x020,
1365 MaskType = Constructor|Event|Field|Method|Property|NestedType
1368 protected struct CacheEntry {
1369 public readonly IMemberContainer Container;
1370 public readonly EntryType EntryType;
1371 public readonly MemberInfo Member;
1373 public CacheEntry (IMemberContainer container, MemberInfo member,
1374 MemberTypes mt, BindingFlags bf)
1376 this.Container = container;
1377 this.Member = member;
1378 this.EntryType = GetEntryType (mt, bf);
1383 /// This is called each time we're walking up one level in the class hierarchy
1384 /// and checks whether we can abort the search since we've already found what
1385 /// we were looking for.
1387 protected bool DoneSearching (ArrayList list)
1390 // We've found exactly one member in the current class and it's not
1391 // a method or constructor.
1393 if (list.Count == 1 && !(list [0] is MethodBase))
1397 // Multiple properties: we query those just to find out the indexer
1400 if ((list.Count > 0) && (list [0] is PropertyInfo))
1407 /// Looks up members with name `name'. If you provide an optional
1408 /// filter function, it'll only be called with members matching the
1409 /// requested member name.
1411 /// This method will try to use the cache to do the lookup if possible.
1413 /// Unlike other FindMembers implementations, this method will always
1414 /// check all inherited members - even when called on an interface type.
1416 /// If you know that you're only looking for methods, you should use
1417 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1418 /// When doing a method-only search, it'll try to use a special method
1419 /// cache (unless it's a dynamic type or an interface) and the returned
1420 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1421 /// The lookup process will automatically restart itself in method-only
1422 /// search mode if it discovers that it's about to return methods.
1424 ArrayList global = new ArrayList ();
1425 bool using_global = false;
1427 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1428 MemberFilter filter, object criteria)
1431 throw new Exception ();
1433 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1434 bool method_search = mt == MemberTypes.Method;
1435 // If we have a method cache and we aren't already doing a method-only search,
1436 // then we restart a method search if the first match is a method.
1437 bool do_method_search = !method_search && (method_hash != null);
1439 ArrayList applicable;
1441 // If this is a method-only search, we try to use the method cache if
1442 // possible; a lookup in the method cache will return a MemberInfo with
1443 // the correct ReflectedType for inherited methods.
1445 if (method_search && (method_hash != null))
1446 applicable = (ArrayList) method_hash [name];
1448 applicable = (ArrayList) member_hash [name];
1450 if (applicable == null)
1451 return MemberList.Empty;
1454 // 32 slots gives 53 rss/54 size
1455 // 2/4 slots gives 55 rss
1457 // Strange: from 25,000 calls, only 1,800
1458 // are above 2. Why does this impact it?
1461 using_global = true;
1463 Timer.StartTimer (TimerType.CachedLookup);
1465 EntryType type = GetEntryType (mt, bf);
1467 IMemberContainer current = Container;
1469 // `applicable' is a list of all members with the given member name `name'
1470 // in the current class and all its parent classes. The list is sorted in
1471 // reverse order due to the way how the cache is initialy created (to speed
1472 // things up, we're doing a deep-copy of our parent).
1474 for (int i = applicable.Count-1; i >= 0; i--) {
1475 CacheEntry entry = (CacheEntry) applicable [i];
1477 // This happens each time we're walking one level up in the class
1478 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1479 // the first time this happens (this may already happen in the first
1480 // iteration of this loop if there are no members with the name we're
1481 // looking for in the current class).
1482 if (entry.Container != current) {
1483 if (declared_only || DoneSearching (global))
1486 current = entry.Container;
1489 // Is the member of the correct type ?
1490 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1493 // Is the member static/non-static ?
1494 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1497 // Apply the filter to it.
1498 if (filter (entry.Member, criteria)) {
1499 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1500 do_method_search = false;
1501 global.Add (entry.Member);
1505 Timer.StopTimer (TimerType.CachedLookup);
1507 // If we have a method cache and we aren't already doing a method-only
1508 // search, we restart in method-only search mode if the first match is
1509 // a method. This ensures that we return a MemberInfo with the correct
1510 // ReflectedType for inherited methods.
1511 if (do_method_search && (global.Count > 0)){
1512 using_global = false;
1514 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1517 using_global = false;
1518 MemberInfo [] copy = new MemberInfo [global.Count];
1519 global.CopyTo (copy);
1520 return new MemberList (copy);