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 public abstract bool Define (TypeContainer parent);
49 // Whehter is it ok to use an unsafe pointer in this type container
51 public bool UnsafeOK (DeclSpace parent)
54 // First check if this MemberCore modifier flags has unsafe set
56 if ((ModFlags & Modifiers.UNSAFE) != 0)
59 if (parent.UnsafeContext)
62 Expression.UnsafeError (Location);
68 /// Base class for structs, classes, enumerations and interfaces.
71 /// They all create new declaration spaces. This
72 /// provides the common foundation for managing those name
75 public abstract class DeclSpace : MemberCore {
77 /// this points to the actual definition that is being
78 /// created with System.Reflection.Emit
80 public TypeBuilder TypeBuilder;
83 /// This variable tracks whether we have Closed the type
85 public bool Created = false;
88 // This is the namespace in which this typecontainer
89 // was declared. We use this to resolve names.
91 public NamespaceEntry NamespaceEntry;
93 public Hashtable Cache = new Hashtable ();
95 public string Basename;
98 /// defined_names is used for toplevel objects
100 protected Hashtable defined_names;
103 // Whether we are Generic
105 public bool IsGeneric;
107 TypeContainer parent;
109 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Location l)
113 Basename = name.Substring (1 + name.LastIndexOf ('.'));
114 defined_names = new Hashtable ();
115 this.parent = parent;
118 public void RecordDecl ()
120 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
121 NamespaceEntry.DefineName (Basename, this);
125 /// The result value from adding an declaration into
126 /// a struct or a class
128 public enum AdditionResult {
130 /// The declaration has been successfully
131 /// added to the declation space.
136 /// The symbol has already been defined.
141 /// Returned if the declation being added to the
142 /// name space clashes with its container name.
144 /// The only exceptions for this are constructors
145 /// and static constructors
150 /// Returned if a constructor was created (because syntactically
151 /// it looked like a constructor) but was not (because the name
152 /// of the method is not the same as the container class
157 /// This is only used by static constructors to emit the
158 /// error 111, but this error for other things really
159 /// happens at another level for other functions.
164 /// Some other error.
170 /// Returns a status code based purely on the name
171 /// of the member being added
173 protected AdditionResult IsValid (string basename, string name)
175 if (basename == Basename)
176 return AdditionResult.EnclosingClash;
178 if (defined_names.Contains (name))
179 return AdditionResult.NameExists;
181 return AdditionResult.Success;
184 public static int length;
185 public static int small;
188 /// Introduce @name into this declaration space and
189 /// associates it with the object @o. Note that for
190 /// methods this will just point to the first method. o
192 protected void DefineName (string name, object o)
194 defined_names.Add (name, o);
197 int p = name.LastIndexOf (".");
205 /// Returns the object associated with a given name in the declaration
206 /// space. This is the inverse operation of `DefineName'
208 public object GetDefinition (string name)
210 return defined_names [name];
213 bool in_transit = false;
216 /// This function is used to catch recursive definitions
219 public bool InTransit {
229 public TypeContainer Parent {
236 /// Looks up the alias for the name
238 public string LookupAlias (string name)
240 if (NamespaceEntry != null)
241 return NamespaceEntry.LookupAlias (name);
247 // root_types contains all the types. All TopLevel types
248 // hence have a parent that points to `root_types', that is
249 // why there is a non-obvious test down here.
251 public bool IsTopLevel {
254 if (parent.parent == null)
261 public virtual void CloseType ()
265 TypeBuilder.CreateType ();
268 // The try/catch is needed because
269 // nested enumerations fail to load when they
272 // Even if this is the right order (enumerations
273 // declared after types).
275 // Note that this still creates the type and
276 // it is possible to save it
283 /// Should be overriten by the appropriate declaration space
285 public abstract TypeBuilder DefineType ();
288 /// Define all members, but don't apply any attributes or do anything which may
289 /// access not-yet-defined classes. This method also creates the MemberCache.
291 public abstract bool DefineMembers (TypeContainer parent);
294 // Whether this is an `unsafe context'
296 public bool UnsafeContext {
298 if ((ModFlags & Modifiers.UNSAFE) != 0)
301 return parent.UnsafeContext;
306 public static string MakeFQN (string nsn, string name)
310 return String.Concat (nsn, ".", name);
313 EmitContext type_resolve_ec;
314 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
316 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
317 type_resolve_ec.ResolvingTypeTree = true;
319 return type_resolve_ec;
323 // Looks up the type, as parsed into the expression `e'
325 public Type ResolveType (Expression e, bool silent, Location loc)
327 if (type_resolve_ec == null)
328 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
329 type_resolve_ec.loc = loc;
330 type_resolve_ec.ContainerType = TypeBuilder;
332 int errors = Report.Errors;
333 Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
335 if (d == null || d.eclass != ExprClass.Type){
336 if (!silent && errors == Report.Errors){
337 Console.WriteLine ("Type is: " + e.GetType().ToString ());
338 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
343 if (d is ConstructedType)
344 ((ConstructedType) d).Resolve (type_resolve_ec, TypeBuilder);
346 if (!CheckAccessLevel (d.Type)) {
347 Report. Error (122, loc, "`" + d.Type + "' " +
348 "is inaccessible because of its protection level");
356 // Resolves the expression `e' for a type, and will recursively define
359 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
361 if (type_resolve_ec == null)
362 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
363 type_resolve_ec.loc = loc;
364 type_resolve_ec.ContainerType = TypeBuilder;
366 Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
368 if (d == null || d.eclass != ExprClass.Type){
370 Report.Error (246, loc, "Cannot find type `"+ e +"'");
378 public bool CheckAccessLevel (Type check_type)
380 if (check_type == TypeBuilder)
383 if (check_type.IsGenericParameter)
384 return true; // FIXME
386 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
389 // Broken Microsoft runtime, return public for arrays, no matter what
390 // the accessibility is for their underlying class, and they return
391 // NonPublic visibility for pointers
393 if (check_type.IsArray || check_type.IsPointer)
394 return CheckAccessLevel (TypeManager.GetElementType (check_type));
397 case TypeAttributes.Public:
400 case TypeAttributes.NotPublic:
402 // This test should probably use the declaringtype.
404 if (check_type.Assembly == TypeBuilder.Assembly){
409 case TypeAttributes.NestedPublic:
412 case TypeAttributes.NestedPrivate:
413 string check_type_name = check_type.FullName;
414 string type_name = TypeBuilder.FullName;
416 int cio = check_type_name.LastIndexOf ("+");
417 string container = check_type_name.Substring (0, cio);
420 // Check if the check_type is a nested class of the current type
422 if (check_type_name.StartsWith (type_name + "+")){
426 if (type_name.StartsWith (container)){
432 case TypeAttributes.NestedFamily:
434 // Only accessible to methods in current type or any subtypes
436 return FamilyAccessible (check_type);
438 case TypeAttributes.NestedFamANDAssem:
439 return (check_type.Assembly == TypeBuilder.Assembly) &&
440 FamilyAccessible (check_type);
442 case TypeAttributes.NestedFamORAssem:
443 return (check_type.Assembly == TypeBuilder.Assembly) ||
444 FamilyAccessible (check_type);
446 case TypeAttributes.NestedAssembly:
447 return check_type.Assembly == TypeBuilder.Assembly;
450 Console.WriteLine ("HERE: " + check_attr);
455 protected bool FamilyAccessible (Type check_type)
457 Type declaring = check_type.DeclaringType;
458 if (TypeBuilder.IsSubclassOf (declaring))
461 string check_type_name = check_type.FullName;
462 string type_name = TypeBuilder.FullName;
464 int cio = check_type_name.LastIndexOf ("+");
465 string container = check_type_name.Substring (0, cio);
468 // Check if the check_type is a nested class of the current type
470 if (check_type_name.StartsWith (container + "+"))
476 // Access level of a type.
479 ProtectedInternal = 1,
485 // Check whether `flags' denotes a more restricted access than `level'
486 // and return the new level.
487 static AccessLevel CheckAccessLevel (AccessLevel level, int flags)
489 AccessLevel old_level = level;
491 if ((flags & Modifiers.INTERNAL) != 0) {
492 if ((flags & Modifiers.PROTECTED) != 0) {
493 if ((int) level < (int) AccessLevel.ProtectedInternal)
494 level = AccessLevel.ProtectedInternal;
496 if ((int) level < (int) AccessLevel.Internal)
497 level = AccessLevel.Internal;
499 } else if ((flags & Modifiers.PROTECTED) != 0) {
500 if ((int) level < (int) AccessLevel.Protected)
501 level = AccessLevel.Protected;
502 } else if ((flags & Modifiers.PRIVATE) != 0)
503 level = AccessLevel.Private;
508 // Return the access level for a new member which is defined in the current
509 // TypeContainer with access modifiers `flags'.
510 AccessLevel GetAccessLevel (int flags)
512 if ((flags & Modifiers.PRIVATE) != 0)
513 return AccessLevel.Private;
516 if (!IsTopLevel && (Parent != null))
517 level = Parent.GetAccessLevel (flags);
519 level = AccessLevel.Public;
521 return CheckAccessLevel (CheckAccessLevel (level, flags), ModFlags);
524 // Return the access level for type `t', but don't give more access than `flags'.
525 static AccessLevel GetAccessLevel (Type t, int flags)
527 if (((flags & Modifiers.PRIVATE) != 0) || t.IsNestedPrivate)
528 return AccessLevel.Private;
531 if (TypeManager.IsBuiltinType (t))
532 return AccessLevel.Public;
533 else if ((t.DeclaringType != null) && (t != t.DeclaringType))
534 level = GetAccessLevel (t.DeclaringType, flags);
536 level = CheckAccessLevel (AccessLevel.Public, flags);
539 if (t.IsNestedPublic)
542 if (t.IsNestedAssembly || t.IsNotPublic) {
543 if ((int) level < (int) AccessLevel.Internal)
544 level = AccessLevel.Internal;
547 if (t.IsNestedFamily) {
548 if ((int) level < (int) AccessLevel.Protected)
549 level = AccessLevel.Protected;
552 if (t.IsNestedFamORAssem) {
553 if ((int) level < (int) AccessLevel.ProtectedInternal)
554 level = AccessLevel.ProtectedInternal;
561 // Returns true if `parent' is as accessible as the flags `flags'
562 // given for this member.
564 public bool AsAccessible (Type parent, int flags)
566 if (parent.IsGenericParameter)
567 return true; // FIXME
569 while (parent.IsArray || parent.IsPointer || parent.IsByRef)
570 parent = TypeManager.GetElementType (parent);
572 AccessLevel level = GetAccessLevel (flags);
573 AccessLevel level2 = GetAccessLevel (parent, flags);
575 return (int) level >= (int) level2;
578 static DoubleHash dh = new DoubleHash ();
580 Type LookupInterfaceOrClass (string ns, string name, out bool error)
588 if (dh.Lookup (ns, name, out r))
592 if (Namespace.IsNamespace (ns)){
593 string fullname = (ns != "") ? ns + "." + name : name;
594 t = TypeManager.LookupType (fullname);
598 t = TypeManager.LookupType (name);
605 // In case we are fed a composite name, normalize it.
607 int p = name.LastIndexOf ('.');
609 ns = MakeFQN (ns, name.Substring (0, p));
610 name = name.Substring (p+1);
613 parent = RootContext.Tree.LookupByNamespace (ns, name);
617 t = parent.DefineType ();
618 dh.Insert (ns, name, t);
626 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
628 Report.Error (104, loc,
629 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
630 t1.FullName, t2.FullName));
634 /// GetType is used to resolve type names at the DeclSpace level.
635 /// Use this to lookup class/struct bases, interface bases or
636 /// delegate type references
640 /// Contrast this to LookupType which is used inside method bodies to
641 /// lookup types that have already been defined. GetType is used
642 /// during the tree resolution process and potentially define
643 /// recursively the type
645 public Type FindType (Location loc, string name)
651 // For the case the type we are looking for is nested within this one
652 // or is in any base class
654 DeclSpace containing_ds = this;
656 while (containing_ds != null){
657 Type container_type = containing_ds.TypeBuilder;
658 Type current_type = container_type;
660 while (current_type != null) {
661 string pre = current_type.FullName;
663 t = LookupInterfaceOrClass (pre, name, out error);
667 if ((t != null) && containing_ds.CheckAccessLevel (t))
670 current_type = current_type.BaseType;
672 containing_ds = containing_ds.Parent;
676 // Attempt to lookup the class on our namespace and all it's implicit parents
678 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
679 t = LookupInterfaceOrClass (ns.FullName, name, out error);
688 // Attempt to do a direct unqualified lookup
690 t = LookupInterfaceOrClass ("", name, out error);
698 // Attempt to lookup the class on any of the `using'
702 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
704 t = LookupInterfaceOrClass (ns.FullName, name, out error);
712 // Now check the using clause list
715 foreach (Namespace using_ns in ns.GetUsingTable ()) {
716 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
722 if (CheckAccessLevel (match)) {
723 Error_AmbiguousTypeReference (loc, name, t, match);
736 //Report.Error (246, Location, "Can not find type `"+name+"'");
741 /// This function is broken and not what you're looking for. It should only
742 /// be used while the type is still being created since it doesn't use the cache
743 /// and relies on the filter doing the member name check.
745 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
746 MemberFilter filter, object criteria);
749 /// If we have a MemberCache, return it. This property may return null if the
750 /// class doesn't have a member cache or while it's still being created.
752 public abstract MemberCache MemberCache {
757 // Extensions for generics
759 TypeParameter[] type_params;
762 /// Called by the parser to configure the type_parameter_list for this
763 /// declaration space
765 public AdditionResult SetParameterInfo (ArrayList type_parameter_list, ArrayList constraints_list)
767 type_params = new TypeParameter [type_parameter_list.Count];
770 // Mark this type as Generic
775 // Register all the names
777 for (int i = 0; i < type_parameter_list.Count; i++) {
778 string name = (string) type_parameter_list [i];
780 AdditionResult res = IsValid (name, name);
782 if (res != AdditionResult.Success)
785 Constraints constraints = null;
786 if (constraints_list != null) {
787 foreach (Constraints constraint in constraints_list) {
788 if (constraint.TypeParameter == name) {
789 constraints = constraint;
795 type_params [i] = new TypeParameter (name, constraints, Location);
797 DefineName (name, type_params [i]);
800 return AdditionResult.Success;
803 public TypeParameter[] TypeParameters {
809 public TypeParameterExpr LookupGeneric (string name, Location loc)
811 if (TypeParameters != null) {
812 foreach (TypeParameter type_param in TypeParameters) {
813 if (type_param.Name != name)
816 return new TypeParameterExpr (type_param, loc);
821 return parent.LookupGeneric (name, loc);
828 /// This is a readonly list of MemberInfo's.
830 public class MemberList : IList {
831 public readonly IList List;
835 /// Create a new MemberList from the given IList.
837 public MemberList (IList list)
842 this.List = new ArrayList ();
847 /// Concatenate the ILists `first' and `second' to a new MemberList.
849 public MemberList (IList first, IList second)
851 ArrayList list = new ArrayList ();
852 list.AddRange (first);
853 list.AddRange (second);
858 public static readonly MemberList Empty = new MemberList (new ArrayList ());
861 /// Cast the MemberList into a MemberInfo[] array.
864 /// This is an expensive operation, only use it if it's really necessary.
866 public static explicit operator MemberInfo [] (MemberList list)
868 Timer.StartTimer (TimerType.MiscTimer);
869 MemberInfo [] result = new MemberInfo [list.Count];
870 list.CopyTo (result, 0);
871 Timer.StopTimer (TimerType.MiscTimer);
883 public bool IsSynchronized {
885 return List.IsSynchronized;
889 public object SyncRoot {
891 return List.SyncRoot;
895 public void CopyTo (Array array, int index)
897 List.CopyTo (array, index);
902 public IEnumerator GetEnumerator ()
904 return List.GetEnumerator ();
909 public bool IsFixedSize {
915 public bool IsReadOnly {
921 object IList.this [int index] {
927 throw new NotSupportedException ();
931 // FIXME: try to find out whether we can avoid the cast in this indexer.
932 public MemberInfo this [int index] {
934 return (MemberInfo) List [index];
938 public int Add (object value)
940 throw new NotSupportedException ();
945 throw new NotSupportedException ();
948 public bool Contains (object value)
950 return List.Contains (value);
953 public int IndexOf (object value)
955 return List.IndexOf (value);
958 public void Insert (int index, object value)
960 throw new NotSupportedException ();
963 public void Remove (object value)
965 throw new NotSupportedException ();
968 public void RemoveAt (int index)
970 throw new NotSupportedException ();
975 /// This interface is used to get all members of a class when creating the
976 /// member cache. It must be implemented by all DeclSpace derivatives which
977 /// want to support the member cache and by TypeHandle to get caching of
978 /// non-dynamic types.
980 public interface IMemberContainer {
982 /// The name of the IMemberContainer. This is only used for
983 /// debugging purposes.
990 /// The type of this IMemberContainer.
997 /// Returns the IMemberContainer of the parent class or null if this
998 /// is an interface or TypeManger.object_type.
999 /// This is used when creating the member cache for a class to get all
1000 /// members from the parent class.
1002 IMemberContainer Parent {
1007 /// Whether this is an interface.
1014 /// Returns all members of this class with the corresponding MemberTypes
1015 /// and BindingFlags.
1018 /// When implementing this method, make sure not to return any inherited
1019 /// members and check the MemberTypes and BindingFlags properly.
1020 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1021 /// get the BindingFlags (static/non-static,public/non-public) in the
1022 /// MemberInfo class, but the cache needs this information. That's why
1023 /// this method is called multiple times with different BindingFlags.
1025 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1028 /// Return the container's member cache.
1030 MemberCache MemberCache {
1036 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1037 /// member lookups. It has a member name based hash table; it maps each member
1038 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1039 /// and the BindingFlags that were initially used to get it. The cache contains
1040 /// all members of the current class and all inherited members. If this cache is
1041 /// for an interface types, it also contains all inherited members.
1043 /// There are two ways to get a MemberCache:
1044 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1045 /// use the DeclSpace.MemberCache property.
1046 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1047 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1049 public class MemberCache {
1050 public readonly IMemberContainer Container;
1051 protected Hashtable member_hash;
1052 protected Hashtable method_hash;
1053 protected Hashtable interface_hash;
1056 /// Create a new MemberCache for the given IMemberContainer `container'.
1058 public MemberCache (IMemberContainer container)
1060 this.Container = container;
1062 Timer.IncrementCounter (CounterType.MemberCache);
1063 Timer.StartTimer (TimerType.CacheInit);
1065 interface_hash = new Hashtable ();
1067 // If we have a parent class (we have a parent class unless we're
1068 // TypeManager.object_type), we deep-copy its MemberCache here.
1069 if (Container.IsInterface) {
1071 if (Container.Parent != null)
1072 parent = Container.Parent.MemberCache;
1074 parent = TypeHandle.ObjectType.MemberCache;
1075 member_hash = SetupCacheForInterface (parent);
1076 } else if (Container.Parent != null)
1077 member_hash = SetupCache (Container.Parent.MemberCache);
1079 member_hash = new Hashtable ();
1081 // If this is neither a dynamic type nor an interface, create a special
1082 // method cache with all declared and inherited methods.
1083 Type type = container.Type;
1084 if (!(type is TypeBuilder) && !type.IsInterface) {
1085 method_hash = new Hashtable ();
1089 // Add all members from the current class.
1090 AddMembers (Container);
1092 Timer.StopTimer (TimerType.CacheInit);
1096 /// Bootstrap this member cache by doing a deep-copy of our parent.
1098 Hashtable SetupCache (MemberCache parent)
1100 Hashtable hash = new Hashtable ();
1102 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1103 while (it.MoveNext ()) {
1104 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1110 void AddInterfaces (MemberCache parent)
1112 foreach (Type iface in parent.interface_hash.Keys) {
1113 if (!interface_hash.Contains (iface))
1114 interface_hash.Add (iface, true);
1119 /// Add the contents of `new_hash' to `hash'.
1121 void AddHashtable (Hashtable hash, Hashtable new_hash)
1123 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1124 while (it.MoveNext ()) {
1125 ArrayList list = (ArrayList) hash [it.Key];
1127 list.AddRange ((ArrayList) it.Value);
1129 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1134 /// Bootstrap the member cache for an interface type.
1135 /// Type.GetMembers() won't return any inherited members for interface types,
1136 /// so we need to do this manually. Interfaces also inherit from System.Object.
1138 Hashtable SetupCacheForInterface (MemberCache parent)
1140 Hashtable hash = SetupCache (parent);
1141 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1143 foreach (Type iface in ifaces) {
1144 if (interface_hash.Contains (iface))
1146 interface_hash.Add (iface, true);
1148 IMemberContainer iface_container =
1149 TypeManager.LookupMemberContainer (iface);
1151 MemberCache iface_cache = iface_container.MemberCache;
1153 AddHashtable (hash, iface_cache.member_hash);
1154 AddInterfaces (iface_cache);
1161 /// Add all members from class `container' to the cache.
1163 void AddMembers (IMemberContainer container)
1165 // We need to call AddMembers() with a single member type at a time
1166 // to get the member type part of CacheEntry.EntryType right.
1167 AddMembers (MemberTypes.Constructor, container);
1168 AddMembers (MemberTypes.Field, container);
1169 AddMembers (MemberTypes.Method, container);
1170 AddMembers (MemberTypes.Property, container);
1171 AddMembers (MemberTypes.Event, container);
1172 // Nested types are returned by both Static and Instance searches.
1173 AddMembers (MemberTypes.NestedType,
1174 BindingFlags.Static | BindingFlags.Public, container);
1175 AddMembers (MemberTypes.NestedType,
1176 BindingFlags.Static | BindingFlags.NonPublic, container);
1179 void AddMembers (MemberTypes mt, IMemberContainer container)
1181 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1182 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1183 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1184 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1188 /// Add all members from class `container' with the requested MemberTypes and
1189 /// BindingFlags to the cache. This method is called multiple times with different
1190 /// MemberTypes and BindingFlags.
1192 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1194 MemberList members = container.GetMembers (mt, bf);
1195 BindingFlags new_bf = (container == Container) ?
1196 bf | BindingFlags.DeclaredOnly : bf;
1198 foreach (MemberInfo member in members) {
1199 string name = member.Name;
1201 // We use a name-based hash table of ArrayList's.
1202 ArrayList list = (ArrayList) member_hash [name];
1204 list = new ArrayList ();
1205 member_hash.Add (name, list);
1208 // When this method is called for the current class, the list will
1209 // already contain all inherited members from our parent classes.
1210 // We cannot add new members in front of the list since this'd be an
1211 // expensive operation, that's why the list is sorted in reverse order
1212 // (ie. members from the current class are coming last).
1213 list.Add (new CacheEntry (container, member, mt, bf));
1218 /// Add all declared and inherited methods from class `type' to the method cache.
1220 void AddMethods (Type type)
1222 AddMethods (BindingFlags.Static | BindingFlags.Public |
1223 BindingFlags.FlattenHierarchy, type);
1224 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1225 BindingFlags.FlattenHierarchy, type);
1226 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1227 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1230 void AddMethods (BindingFlags bf, Type type)
1232 MemberInfo [] members = type.GetMethods (bf);
1234 foreach (MethodBase member in members) {
1235 string name = member.Name;
1237 // Varargs methods aren't allowed in C# code.
1238 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1241 // We use a name-based hash table of ArrayList's.
1242 ArrayList list = (ArrayList) method_hash [name];
1244 list = new ArrayList ();
1245 method_hash.Add (name, list);
1248 // Unfortunately, the elements returned by Type.GetMethods() aren't
1249 // sorted so we need to do this check for every member.
1250 BindingFlags new_bf = bf;
1251 if (member.DeclaringType == type)
1252 new_bf |= BindingFlags.DeclaredOnly;
1254 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1259 /// Compute and return a appropriate `EntryType' magic number for the given
1260 /// MemberTypes and BindingFlags.
1262 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1264 EntryType type = EntryType.None;
1266 if ((mt & MemberTypes.Constructor) != 0)
1267 type |= EntryType.Constructor;
1268 if ((mt & MemberTypes.Event) != 0)
1269 type |= EntryType.Event;
1270 if ((mt & MemberTypes.Field) != 0)
1271 type |= EntryType.Field;
1272 if ((mt & MemberTypes.Method) != 0)
1273 type |= EntryType.Method;
1274 if ((mt & MemberTypes.Property) != 0)
1275 type |= EntryType.Property;
1276 // Nested types are returned by static and instance searches.
1277 if ((mt & MemberTypes.NestedType) != 0)
1278 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1280 if ((bf & BindingFlags.Instance) != 0)
1281 type |= EntryType.Instance;
1282 if ((bf & BindingFlags.Static) != 0)
1283 type |= EntryType.Static;
1284 if ((bf & BindingFlags.Public) != 0)
1285 type |= EntryType.Public;
1286 if ((bf & BindingFlags.NonPublic) != 0)
1287 type |= EntryType.NonPublic;
1288 if ((bf & BindingFlags.DeclaredOnly) != 0)
1289 type |= EntryType.Declared;
1295 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1296 /// denote multiple member types. Returns true if the given flags value denotes a
1297 /// single member types.
1299 public static bool IsSingleMemberType (MemberTypes mt)
1302 case MemberTypes.Constructor:
1303 case MemberTypes.Event:
1304 case MemberTypes.Field:
1305 case MemberTypes.Method:
1306 case MemberTypes.Property:
1307 case MemberTypes.NestedType:
1316 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1317 /// number to speed up the searching process.
1320 protected enum EntryType {
1325 MaskStatic = Instance|Static,
1329 MaskProtection = Public|NonPublic,
1333 Constructor = 0x020,
1340 MaskType = Constructor|Event|Field|Method|Property|NestedType
1343 protected struct CacheEntry {
1344 public readonly IMemberContainer Container;
1345 public readonly EntryType EntryType;
1346 public readonly MemberInfo Member;
1348 public CacheEntry (IMemberContainer container, MemberInfo member,
1349 MemberTypes mt, BindingFlags bf)
1351 this.Container = container;
1352 this.Member = member;
1353 this.EntryType = GetEntryType (mt, bf);
1358 /// This is called each time we're walking up one level in the class hierarchy
1359 /// and checks whether we can abort the search since we've already found what
1360 /// we were looking for.
1362 protected bool DoneSearching (ArrayList list)
1365 // We've found exactly one member in the current class and it's not
1366 // a method or constructor.
1368 if (list.Count == 1 && !(list [0] is MethodBase))
1372 // Multiple properties: we query those just to find out the indexer
1375 if ((list.Count > 0) && (list [0] is PropertyInfo))
1382 /// Looks up members with name `name'. If you provide an optional
1383 /// filter function, it'll only be called with members matching the
1384 /// requested member name.
1386 /// This method will try to use the cache to do the lookup if possible.
1388 /// Unlike other FindMembers implementations, this method will always
1389 /// check all inherited members - even when called on an interface type.
1391 /// If you know that you're only looking for methods, you should use
1392 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1393 /// When doing a method-only search, it'll try to use a special method
1394 /// cache (unless it's a dynamic type or an interface) and the returned
1395 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1396 /// The lookup process will automatically restart itself in method-only
1397 /// search mode if it discovers that it's about to return methods.
1399 ArrayList global = new ArrayList ();
1400 bool using_global = false;
1402 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1403 MemberFilter filter, object criteria)
1406 throw new Exception ();
1408 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1409 bool method_search = mt == MemberTypes.Method;
1410 // If we have a method cache and we aren't already doing a method-only search,
1411 // then we restart a method search if the first match is a method.
1412 bool do_method_search = !method_search && (method_hash != null);
1414 ArrayList applicable;
1416 // If this is a method-only search, we try to use the method cache if
1417 // possible; a lookup in the method cache will return a MemberInfo with
1418 // the correct ReflectedType for inherited methods.
1420 if (method_search && (method_hash != null))
1421 applicable = (ArrayList) method_hash [name];
1423 applicable = (ArrayList) member_hash [name];
1425 if (applicable == null)
1426 return MemberList.Empty;
1429 // 32 slots gives 53 rss/54 size
1430 // 2/4 slots gives 55 rss
1432 // Strange: from 25,000 calls, only 1,800
1433 // are above 2. Why does this impact it?
1436 using_global = true;
1438 Timer.StartTimer (TimerType.CachedLookup);
1440 EntryType type = GetEntryType (mt, bf);
1442 IMemberContainer current = Container;
1444 // `applicable' is a list of all members with the given member name `name'
1445 // in the current class and all its parent classes. The list is sorted in
1446 // reverse order due to the way how the cache is initialy created (to speed
1447 // things up, we're doing a deep-copy of our parent).
1449 for (int i = applicable.Count-1; i >= 0; i--) {
1450 CacheEntry entry = (CacheEntry) applicable [i];
1452 // This happens each time we're walking one level up in the class
1453 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1454 // the first time this happens (this may already happen in the first
1455 // iteration of this loop if there are no members with the name we're
1456 // looking for in the current class).
1457 if (entry.Container != current) {
1458 if (declared_only || DoneSearching (global))
1461 current = entry.Container;
1464 // Is the member of the correct type ?
1465 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1468 // Is the member static/non-static ?
1469 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1472 // Apply the filter to it.
1473 if (filter (entry.Member, criteria)) {
1474 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1475 do_method_search = false;
1476 global.Add (entry.Member);
1480 Timer.StopTimer (TimerType.CachedLookup);
1482 // If we have a method cache and we aren't already doing a method-only
1483 // search, we restart in method-only search mode if the first match is
1484 // a method. This ensures that we return a MemberInfo with the correct
1485 // ReflectedType for inherited methods.
1486 if (do_method_search && (global.Count > 0)){
1487 using_global = false;
1489 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1492 using_global = false;
1493 MemberInfo [] copy = new MemberInfo [global.Count];
1494 global.CopyTo (copy);
1495 return new MemberList (copy);