2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
14 using System.Collections;
15 using System.Reflection.Emit;
16 using System.Reflection;
18 namespace Mono.CSharp {
21 /// Base representation for members. This is only used to keep track
22 /// of Name, Location and Modifier flags.
24 public abstract class MemberCore {
31 /// Modifier flags that the user specified in the source code
36 /// Location where this declaration happens
38 public readonly Location Location;
40 public MemberCore (string name, Location loc)
46 protected void WarningNotHiding (TypeContainer parent)
50 "The member " + parent.MakeName (Name) + " does not hide an " +
51 "inherited member. The keyword new is not required");
55 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
59 // FIXME: report the old/new permissions?
62 507, Location, parent.MakeName (Name) +
63 ": can't change the access modifiers when overriding inherited " +
64 "member `" + name + "'");
68 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
69 // that have been defined.
71 // `name' is the user visible name for reporting errors (this is used to
72 // provide the right name regarding method names and properties)
74 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
75 MethodInfo mb, string name)
79 if ((ModFlags & Modifiers.OVERRIDE) != 0){
80 if (!(mb.IsAbstract || mb.IsVirtual)){
82 506, Location, parent.MakeName (Name) +
83 ": cannot override inherited member `" +
84 name + "' because it is not " +
85 "virtual, abstract or override");
89 // Now we check that the overriden method is not final
92 // This happens when implementing interface methods.
93 if (mb.IsHideBySig && mb.IsVirtual) {
95 506, Location, parent.MakeName (Name) +
96 ": cannot override inherited member `" +
97 name + "' because it is not " +
98 "virtual, abstract or override");
100 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
101 "override inherited member `" + name +
102 "' because it is sealed.");
106 // Check that the permissions are not being changed
108 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
109 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
112 // special case for "protected internal"
115 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
117 // when overriding protected internal, the method can be declared
118 // protected internal only within the same assembly
121 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
122 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
124 // assemblies differ - report an error
127 Error_CannotChangeAccessModifiers (parent, mb, name);
129 } else if (thisp != parentp) {
131 // same assembly, but other attributes differ - report an error
134 Error_CannotChangeAccessModifiers (parent, mb, name);
137 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
139 // if it's not "protected internal", it must be "protected"
142 Error_CannotChangeAccessModifiers (parent, mb, name);
144 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
146 // protected within the same assembly - an error
148 Error_CannotChangeAccessModifiers (parent, mb, name);
150 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
151 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
153 // protected ok, but other attributes differ - report an error
155 Error_CannotChangeAccessModifiers (parent, mb, name);
159 if (thisp != parentp){
160 Error_CannotChangeAccessModifiers (parent, mb, name);
166 if (mb.IsVirtual || mb.IsAbstract){
167 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
168 if (Name != "Finalize"){
170 114, 2, Location, parent.MakeName (Name) +
171 " hides inherited member `" + name +
172 "'. To make the current member override that " +
173 "implementation, add the override keyword, " +
174 "otherwise use the new keyword");
175 ModFlags |= Modifiers.NEW;
179 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
180 if (Name != "Finalize"){
182 108, 1, Location, "The keyword new is required on " +
183 parent.MakeName (Name) + " because it hides " +
184 "inherited member `" + name + "'");
185 ModFlags |= Modifiers.NEW;
193 public abstract bool Define (TypeContainer parent);
196 // Whehter is it ok to use an unsafe pointer in this type container
198 public bool UnsafeOK (DeclSpace parent)
201 // First check if this MemberCore modifier flags has unsafe set
203 if ((ModFlags & Modifiers.UNSAFE) != 0)
206 if (parent.UnsafeContext)
209 Expression.UnsafeError (Location);
215 // FIXME: This is temporary outside DeclSpace, because I have to fix a bug
216 // in MCS that makes it fail the lookup for the enum
220 /// The result value from adding an declaration into
221 /// a struct or a class
223 public enum AdditionResult {
225 /// The declaration has been successfully
226 /// added to the declation space.
231 /// The symbol has already been defined.
236 /// Returned if the declation being added to the
237 /// name space clashes with its container name.
239 /// The only exceptions for this are constructors
240 /// and static constructors
245 /// Returned if a constructor was created (because syntactically
246 /// it looked like a constructor) but was not (because the name
247 /// of the method is not the same as the container class
252 /// This is only used by static constructors to emit the
253 /// error 111, but this error for other things really
254 /// happens at another level for other functions.
259 /// Some other error.
265 /// Base class for structs, classes, enumerations and interfaces.
268 /// They all create new declaration spaces. This
269 /// provides the common foundation for managing those name
272 public abstract class DeclSpace : MemberCore {
274 /// this points to the actual definition that is being
275 /// created with System.Reflection.Emit
277 public TypeBuilder TypeBuilder;
280 /// This variable tracks whether we have Closed the type
282 public bool Created = false;
285 // This is the namespace in which this typecontainer
286 // was declared. We use this to resolve names.
288 public NamespaceEntry Namespace;
290 public Hashtable Cache = new Hashtable ();
292 public string Basename;
295 /// defined_names is used for toplevel objects
297 protected Hashtable defined_names;
300 // Whether we are Generic
302 public bool IsGeneric;
304 TypeContainer parent;
306 public DeclSpace (TypeContainer parent, string name, Location l)
309 Basename = name.Substring (1 + name.LastIndexOf ('.'));
310 defined_names = new Hashtable ();
311 this.parent = parent;
314 // We are generic if our parent is generic
317 IsGeneric = parent.IsGeneric;
321 /// Returns a status code based purely on the name
322 /// of the member being added
324 protected AdditionResult IsValid (string basename, string name)
326 if (basename == Basename)
327 return AdditionResult.EnclosingClash;
329 if (defined_names.Contains (name))
330 return AdditionResult.NameExists;
332 return AdditionResult.Success;
335 public static int length;
336 public static int small;
339 /// Introduce @name into this declaration space and
340 /// associates it with the object @o. Note that for
341 /// methods this will just point to the first method. o
343 protected void DefineName (string name, object o)
345 defined_names.Add (name, o);
348 int p = name.LastIndexOf (".");
356 /// Returns the object associated with a given name in the declaration
357 /// space. This is the inverse operation of `DefineName'
359 public object GetDefinition (string name)
361 return defined_names [name];
364 bool in_transit = false;
367 /// This function is used to catch recursive definitions
370 public bool InTransit {
380 public TypeContainer Parent {
387 /// Looks up the alias for the name
389 public string LookupAlias (string name)
391 if (Namespace != null)
392 return Namespace.LookupAlias (name);
398 // root_types contains all the types. All TopLevel types
399 // hence have a parent that points to `root_types', that is
400 // why there is a non-obvious test down here.
402 public bool IsTopLevel {
405 if (parent.parent == null)
412 public virtual void CloseType ()
416 TypeBuilder.CreateType ();
419 // The try/catch is needed because
420 // nested enumerations fail to load when they
423 // Even if this is the right order (enumerations
424 // declared after types).
426 // Note that this still creates the type and
427 // it is possible to save it
434 /// Should be overriten by the appropriate declaration space
436 public abstract TypeBuilder DefineType ();
439 /// Define all members, but don't apply any attributes or do anything which may
440 /// access not-yet-defined classes. This method also creates the MemberCache.
442 public abstract bool DefineMembers (TypeContainer parent);
445 // Whether this is an `unsafe context'
447 public bool UnsafeContext {
449 if ((ModFlags & Modifiers.UNSAFE) != 0)
452 return parent.UnsafeContext;
457 public static string MakeFQN (string nsn, string name)
461 return String.Concat (nsn, ".", name);
464 EmitContext type_resolve_ec;
465 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
467 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
468 type_resolve_ec.ResolvingTypeTree = true;
470 return type_resolve_ec;
474 // Looks up the type, as parsed into the expression `e'
476 public Type ResolveType (Expression e, bool silent, Location loc)
478 if (type_resolve_ec == null)
479 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
480 type_resolve_ec.loc = loc;
481 type_resolve_ec.ContainerType = TypeBuilder;
483 int errors = Report.Errors;
484 Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
486 if (d == null || d.eclass != ExprClass.Type){
487 if (!silent && errors == Report.Errors){
488 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
493 if (!CheckAccessLevel (d.Type)) {
494 Report. Error (122, loc, "`" + d.Type + "' " +
495 "is inaccessible because of its protection level");
503 // Resolves the expression `e' for a type, and will recursively define
506 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
508 if (type_resolve_ec == null)
509 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
510 type_resolve_ec.loc = loc;
511 type_resolve_ec.ContainerType = TypeBuilder;
513 Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
515 if (d == null || d.eclass != ExprClass.Type){
517 Report.Error (246, loc, "Cannot find type `"+ e +"'");
525 public bool CheckAccessLevel (Type check_type)
527 if (check_type == TypeBuilder)
530 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
533 // Broken Microsoft runtime, return public for arrays, no matter what
534 // the accessibility is for their underlying class, and they return
535 // NonPublic visibility for pointers
537 if (check_type.IsArray || check_type.IsPointer)
538 return CheckAccessLevel (TypeManager.GetElementType (check_type));
541 case TypeAttributes.Public:
544 case TypeAttributes.NotPublic:
546 // This test should probably use the declaringtype.
548 if (check_type.Assembly == TypeBuilder.Assembly){
553 case TypeAttributes.NestedPublic:
556 case TypeAttributes.NestedPrivate:
557 string check_type_name = check_type.FullName;
558 string type_name = TypeBuilder.FullName;
560 int cio = check_type_name.LastIndexOf ("+");
561 string container = check_type_name.Substring (0, cio);
564 // Check if the check_type is a nested class of the current type
566 if (check_type_name.StartsWith (type_name + "+")){
570 if (type_name.StartsWith (container)){
576 case TypeAttributes.NestedFamily:
578 // Only accessible to methods in current type or any subtypes
580 return FamilyAccessible (check_type);
582 case TypeAttributes.NestedFamANDAssem:
583 return (check_type.Assembly == TypeBuilder.Assembly) &&
584 FamilyAccessible (check_type);
586 case TypeAttributes.NestedFamORAssem:
587 return (check_type.Assembly == TypeBuilder.Assembly) ||
588 FamilyAccessible (check_type);
590 case TypeAttributes.NestedAssembly:
591 return check_type.Assembly == TypeBuilder.Assembly;
594 Console.WriteLine ("HERE: " + check_attr);
599 protected bool FamilyAccessible (Type check_type)
601 Type declaring = check_type.DeclaringType;
602 if (TypeBuilder.IsSubclassOf (declaring))
605 string check_type_name = check_type.FullName;
606 string type_name = TypeBuilder.FullName;
608 int cio = check_type_name.LastIndexOf ("+");
609 string container = check_type_name.Substring (0, cio);
612 // Check if the check_type is a nested class of the current type
614 if (check_type_name.StartsWith (container + "+"))
621 Type LookupInterfaceOrClass (string ns, string name, out bool error)
628 name = MakeFQN (ns, name);
630 t = TypeManager.LookupType (name);
634 parent = (DeclSpace) RootContext.Tree.Decls [name];
638 t = parent.DefineType ();
640 Report.Error (146, Location, "Class definition is circular: `"+name+"'");
647 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
649 Report.Error (104, loc,
650 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
651 t1.FullName, t2.FullName));
655 /// GetType is used to resolve type names at the DeclSpace level.
656 /// Use this to lookup class/struct bases, interface bases or
657 /// delegate type references
661 /// Contrast this to LookupType which is used inside method bodies to
662 /// lookup types that have already been defined. GetType is used
663 /// during the tree resolution process and potentially define
664 /// recursively the type
666 public Type FindType (Location loc, string name)
672 // For the case the type we are looking for is nested within this one
673 // or is in any base class
675 DeclSpace containing_ds = this;
677 while (containing_ds != null){
678 Type container_type = containing_ds.TypeBuilder;
679 Type current_type = container_type;
681 while (current_type != null) {
682 string pre = current_type.FullName;
684 t = LookupInterfaceOrClass (pre, name, out error);
688 if ((t != null) && containing_ds.CheckAccessLevel (t))
691 current_type = current_type.BaseType;
693 containing_ds = containing_ds.Parent;
697 // Attempt to lookup the class on our namespace and all it's implicit parents
699 for (NamespaceEntry ns = Namespace; ns != null; ns = ns.ImplicitParent) {
700 t = LookupInterfaceOrClass (ns.Name, name, out error);
709 // Attempt to do a direct unqualified lookup
711 t = LookupInterfaceOrClass ("", name, out error);
719 // Attempt to lookup the class on any of the `using'
723 for (NamespaceEntry ns = Namespace; ns != null; ns = ns.Parent){
725 t = LookupInterfaceOrClass (ns.Name, name, out error);
733 // Now check the using clause list
736 foreach (Namespace using_ns in ns.GetUsingTable ()) {
737 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
743 if (CheckAccessLevel (match)) {
744 Error_AmbiguousTypeReference (loc, name, t, match);
757 //Report.Error (246, Location, "Can not find type `"+name+"'");
762 /// This function is broken and not what you're looking for. It should only
763 /// be used while the type is still being created since it doesn't use the cache
764 /// and relies on the filter doing the member name check.
766 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
767 MemberFilter filter, object criteria);
770 /// If we have a MemberCache, return it. This property may return null if the
771 /// class doesn't have a member cache or while it's still being created.
773 public abstract MemberCache MemberCache {
778 // Extensions for generics
780 ArrayList type_parameter_list;
783 /// Called by the parser to configure the type_parameter_list for this
784 /// declaration space
786 public AdditionResult SetParameterInfo (ArrayList type_parameter_list, object constraints)
788 this.type_parameter_list = type_parameter_list;
791 // Mark this type as Generic
796 // Register all the names
798 foreach (string type_parameter in type_parameter_list){
799 AdditionResult res = IsValid (type_parameter, type_parameter);
801 if (res != AdditionResult.Success)
804 DefineName (type_parameter, GetGenericData ());
807 return AdditionResult.Success;
811 // This is just something to flag the defined names for now
813 const int GENERIC_COOKIE = 20;
814 static object generic_flag = GENERIC_COOKIE;
816 static object GetGenericData ()
822 /// Returns a GenericTypeExpr if `name' refers to a type parameter
824 public TypeParameterExpr LookupGeneric (string name, Location l)
826 foreach (string type_parameter in type_parameter_list){
827 Console.WriteLine (" trying: " + type_parameter);
828 if (name == type_parameter)
829 return new TypeParameterExpr (name, l);
837 /// This is a readonly list of MemberInfo's.
839 public class MemberList : IList {
840 public readonly IList List;
844 /// Create a new MemberList from the given IList.
846 public MemberList (IList list)
851 this.List = new ArrayList ();
856 /// Concatenate the ILists `first' and `second' to a new MemberList.
858 public MemberList (IList first, IList second)
860 ArrayList list = new ArrayList ();
861 list.AddRange (first);
862 list.AddRange (second);
867 public static readonly MemberList Empty = new MemberList (new ArrayList ());
870 /// Cast the MemberList into a MemberInfo[] array.
873 /// This is an expensive operation, only use it if it's really necessary.
875 public static explicit operator MemberInfo [] (MemberList list)
877 Timer.StartTimer (TimerType.MiscTimer);
878 MemberInfo [] result = new MemberInfo [list.Count];
879 list.CopyTo (result, 0);
880 Timer.StopTimer (TimerType.MiscTimer);
892 public bool IsSynchronized {
894 return List.IsSynchronized;
898 public object SyncRoot {
900 return List.SyncRoot;
904 public void CopyTo (Array array, int index)
906 List.CopyTo (array, index);
911 public IEnumerator GetEnumerator ()
913 return List.GetEnumerator ();
918 public bool IsFixedSize {
924 public bool IsReadOnly {
930 object IList.this [int index] {
936 throw new NotSupportedException ();
940 // FIXME: try to find out whether we can avoid the cast in this indexer.
941 public MemberInfo this [int index] {
943 return (MemberInfo) List [index];
947 public int Add (object value)
949 throw new NotSupportedException ();
954 throw new NotSupportedException ();
957 public bool Contains (object value)
959 return List.Contains (value);
962 public int IndexOf (object value)
964 return List.IndexOf (value);
967 public void Insert (int index, object value)
969 throw new NotSupportedException ();
972 public void Remove (object value)
974 throw new NotSupportedException ();
977 public void RemoveAt (int index)
979 throw new NotSupportedException ();
984 /// This interface is used to get all members of a class when creating the
985 /// member cache. It must be implemented by all DeclSpace derivatives which
986 /// want to support the member cache and by TypeHandle to get caching of
987 /// non-dynamic types.
989 public interface IMemberContainer {
991 /// The name of the IMemberContainer. This is only used for
992 /// debugging purposes.
999 /// The type of this IMemberContainer.
1006 /// Returns the IMemberContainer of the parent class or null if this
1007 /// is an interface or TypeManger.object_type.
1008 /// This is used when creating the member cache for a class to get all
1009 /// members from the parent class.
1011 IMemberContainer Parent {
1016 /// Whether this is an interface.
1023 /// Returns all members of this class with the corresponding MemberTypes
1024 /// and BindingFlags.
1027 /// When implementing this method, make sure not to return any inherited
1028 /// members and check the MemberTypes and BindingFlags properly.
1029 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1030 /// get the BindingFlags (static/non-static,public/non-public) in the
1031 /// MemberInfo class, but the cache needs this information. That's why
1032 /// this method is called multiple times with different BindingFlags.
1034 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1037 /// Return the container's member cache.
1039 MemberCache MemberCache {
1045 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1046 /// member lookups. It has a member name based hash table; it maps each member
1047 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1048 /// and the BindingFlags that were initially used to get it. The cache contains
1049 /// all members of the current class and all inherited members. If this cache is
1050 /// for an interface types, it also contains all inherited members.
1052 /// There are two ways to get a MemberCache:
1053 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1054 /// use the DeclSpace.MemberCache property.
1055 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1056 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1058 public class MemberCache {
1059 public readonly IMemberContainer Container;
1060 protected Hashtable member_hash;
1061 protected Hashtable method_hash;
1062 protected Hashtable interface_hash;
1065 /// Create a new MemberCache for the given IMemberContainer `container'.
1067 public MemberCache (IMemberContainer container)
1069 this.Container = container;
1071 Timer.IncrementCounter (CounterType.MemberCache);
1072 Timer.StartTimer (TimerType.CacheInit);
1074 interface_hash = new Hashtable ();
1076 // If we have a parent class (we have a parent class unless we're
1077 // TypeManager.object_type), we deep-copy its MemberCache here.
1078 if (Container.Parent != null) {
1079 member_hash = SetupCache (Container.Parent.MemberCache);
1080 } else if (Container.IsInterface)
1081 member_hash = SetupCacheForInterface ();
1083 member_hash = new Hashtable ();
1085 // If this is neither a dynamic type nor an interface, create a special
1086 // method cache with all declared and inherited methods.
1087 Type type = container.Type;
1088 if (!(type is TypeBuilder) && !type.IsInterface) {
1089 method_hash = new Hashtable ();
1093 // Add all members from the current class.
1094 AddMembers (Container);
1096 Timer.StopTimer (TimerType.CacheInit);
1100 /// Bootstrap this member cache by doing a deep-copy of our parent.
1102 Hashtable SetupCache (MemberCache parent)
1104 Hashtable hash = new Hashtable ();
1106 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1107 while (it.MoveNext ()) {
1108 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1114 void AddInterfaces (MemberCache parent)
1116 foreach (Type iface in parent.interface_hash.Keys) {
1117 if (!interface_hash.Contains (iface))
1118 interface_hash.Add (iface, true);
1123 /// Add the contents of `new_hash' to `hash'.
1125 void AddHashtable (Hashtable hash, Hashtable new_hash)
1127 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1128 while (it.MoveNext ()) {
1129 ArrayList list = (ArrayList) hash [it.Key];
1131 list.AddRange ((ArrayList) it.Value);
1133 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1138 /// Bootstrap the member cache for an interface type.
1139 /// Type.GetMembers() won't return any inherited members for interface types,
1140 /// so we need to do this manually. Interfaces also inherit from System.Object.
1142 Hashtable SetupCacheForInterface ()
1144 Hashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
1145 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1147 foreach (Type iface in ifaces) {
1148 if (interface_hash.Contains (iface))
1150 interface_hash.Add (iface, true);
1152 IMemberContainer iface_container =
1153 TypeManager.LookupMemberContainer (iface);
1155 MemberCache iface_cache = iface_container.MemberCache;
1156 AddHashtable (hash, iface_cache.member_hash);
1157 AddInterfaces (iface_cache);
1164 /// Add all members from class `container' to the cache.
1166 void AddMembers (IMemberContainer container)
1168 // We need to call AddMembers() with a single member type at a time
1169 // to get the member type part of CacheEntry.EntryType right.
1170 AddMembers (MemberTypes.Constructor, container);
1171 AddMembers (MemberTypes.Field, container);
1172 AddMembers (MemberTypes.Method, container);
1173 AddMembers (MemberTypes.Property, container);
1174 AddMembers (MemberTypes.Event, container);
1175 // Nested types are returned by both Static and Instance searches.
1176 AddMembers (MemberTypes.NestedType,
1177 BindingFlags.Static | BindingFlags.Public, container);
1178 AddMembers (MemberTypes.NestedType,
1179 BindingFlags.Static | BindingFlags.NonPublic, container);
1182 void AddMembers (MemberTypes mt, IMemberContainer container)
1184 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1185 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1186 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1187 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1191 /// Add all members from class `container' with the requested MemberTypes and
1192 /// BindingFlags to the cache. This method is called multiple times with different
1193 /// MemberTypes and BindingFlags.
1195 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1197 MemberList members = container.GetMembers (mt, bf);
1198 BindingFlags new_bf = (container == Container) ?
1199 bf | BindingFlags.DeclaredOnly : bf;
1201 foreach (MemberInfo member in members) {
1202 string name = member.Name;
1204 // We use a name-based hash table of ArrayList's.
1205 ArrayList list = (ArrayList) member_hash [name];
1207 list = new ArrayList ();
1208 member_hash.Add (name, list);
1211 // When this method is called for the current class, the list will
1212 // already contain all inherited members from our parent classes.
1213 // We cannot add new members in front of the list since this'd be an
1214 // expensive operation, that's why the list is sorted in reverse order
1215 // (ie. members from the current class are coming last).
1216 list.Add (new CacheEntry (container, member, mt, bf));
1221 /// Add all declared and inherited methods from class `type' to the method cache.
1223 void AddMethods (Type type)
1225 AddMethods (BindingFlags.Static | BindingFlags.Public |
1226 BindingFlags.FlattenHierarchy, type);
1227 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1228 BindingFlags.FlattenHierarchy, type);
1229 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1230 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1233 void AddMethods (BindingFlags bf, Type type)
1235 MemberInfo [] members = type.GetMethods (bf);
1237 foreach (MethodBase member in members) {
1238 string name = member.Name;
1240 // Varargs methods aren't allowed in C# code.
1241 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1244 // We use a name-based hash table of ArrayList's.
1245 ArrayList list = (ArrayList) method_hash [name];
1247 list = new ArrayList ();
1248 method_hash.Add (name, list);
1251 // Unfortunately, the elements returned by Type.GetMethods() aren't
1252 // sorted so we need to do this check for every member.
1253 BindingFlags new_bf = bf;
1254 if (member.DeclaringType == type)
1255 new_bf |= BindingFlags.DeclaredOnly;
1257 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1262 /// Compute and return a appropriate `EntryType' magic number for the given
1263 /// MemberTypes and BindingFlags.
1265 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1267 EntryType type = EntryType.None;
1269 if ((mt & MemberTypes.Constructor) != 0)
1270 type |= EntryType.Constructor;
1271 if ((mt & MemberTypes.Event) != 0)
1272 type |= EntryType.Event;
1273 if ((mt & MemberTypes.Field) != 0)
1274 type |= EntryType.Field;
1275 if ((mt & MemberTypes.Method) != 0)
1276 type |= EntryType.Method;
1277 if ((mt & MemberTypes.Property) != 0)
1278 type |= EntryType.Property;
1279 // Nested types are returned by static and instance searches.
1280 if ((mt & MemberTypes.NestedType) != 0)
1281 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1283 if ((bf & BindingFlags.Instance) != 0)
1284 type |= EntryType.Instance;
1285 if ((bf & BindingFlags.Static) != 0)
1286 type |= EntryType.Static;
1287 if ((bf & BindingFlags.Public) != 0)
1288 type |= EntryType.Public;
1289 if ((bf & BindingFlags.NonPublic) != 0)
1290 type |= EntryType.NonPublic;
1291 if ((bf & BindingFlags.DeclaredOnly) != 0)
1292 type |= EntryType.Declared;
1298 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1299 /// denote multiple member types. Returns true if the given flags value denotes a
1300 /// single member types.
1302 public static bool IsSingleMemberType (MemberTypes mt)
1305 case MemberTypes.Constructor:
1306 case MemberTypes.Event:
1307 case MemberTypes.Field:
1308 case MemberTypes.Method:
1309 case MemberTypes.Property:
1310 case MemberTypes.NestedType:
1319 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1320 /// number to speed up the searching process.
1323 protected enum EntryType {
1328 MaskStatic = Instance|Static,
1332 MaskProtection = Public|NonPublic,
1336 Constructor = 0x020,
1343 MaskType = Constructor|Event|Field|Method|Property|NestedType
1346 protected struct CacheEntry {
1347 public readonly IMemberContainer Container;
1348 public readonly EntryType EntryType;
1349 public readonly MemberInfo Member;
1351 public CacheEntry (IMemberContainer container, MemberInfo member,
1352 MemberTypes mt, BindingFlags bf)
1354 this.Container = container;
1355 this.Member = member;
1356 this.EntryType = GetEntryType (mt, bf);
1361 /// This is called each time we're walking up one level in the class hierarchy
1362 /// and checks whether we can abort the search since we've already found what
1363 /// we were looking for.
1365 protected bool DoneSearching (ArrayList list)
1368 // We've found exactly one member in the current class and it's not
1369 // a method or constructor.
1371 if (list.Count == 1 && !(list [0] is MethodBase))
1375 // Multiple properties: we query those just to find out the indexer
1378 if ((list.Count > 0) && (list [0] is PropertyInfo))
1385 /// Looks up members with name `name'. If you provide an optional
1386 /// filter function, it'll only be called with members matching the
1387 /// requested member name.
1389 /// This method will try to use the cache to do the lookup if possible.
1391 /// Unlike other FindMembers implementations, this method will always
1392 /// check all inherited members - even when called on an interface type.
1394 /// If you know that you're only looking for methods, you should use
1395 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1396 /// When doing a method-only search, it'll try to use a special method
1397 /// cache (unless it's a dynamic type or an interface) and the returned
1398 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1399 /// The lookup process will automatically restart itself in method-only
1400 /// search mode if it discovers that it's about to return methods.
1402 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1403 MemberFilter filter, object criteria)
1405 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1406 bool method_search = mt == MemberTypes.Method;
1407 // If we have a method cache and we aren't already doing a method-only search,
1408 // then we restart a method search if the first match is a method.
1409 bool do_method_search = !method_search && (method_hash != null);
1411 ArrayList applicable;
1413 // If this is a method-only search, we try to use the method cache if
1414 // possible; a lookup in the method cache will return a MemberInfo with
1415 // the correct ReflectedType for inherited methods.
1417 if (method_search && (method_hash != null))
1418 applicable = (ArrayList) method_hash [name];
1420 applicable = (ArrayList) member_hash [name];
1422 if (applicable == null)
1423 return MemberList.Empty;
1426 // 32 slots gives 53 rss/54 size
1427 // 2/4 slots gives 55 rss
1429 // Strange: from 25,000 calls, only 1,800
1430 // are above 2. Why does this impact it?
1432 ArrayList list = new ArrayList ();
1434 Timer.StartTimer (TimerType.CachedLookup);
1436 EntryType type = GetEntryType (mt, bf);
1438 IMemberContainer current = Container;
1440 // `applicable' is a list of all members with the given member name `name'
1441 // in the current class and all its parent classes. The list is sorted in
1442 // reverse order due to the way how the cache is initialy created (to speed
1443 // things up, we're doing a deep-copy of our parent).
1445 for (int i = applicable.Count-1; i >= 0; i--) {
1446 CacheEntry entry = (CacheEntry) applicable [i];
1448 // This happens each time we're walking one level up in the class
1449 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1450 // the first time this happens (this may already happen in the first
1451 // iteration of this loop if there are no members with the name we're
1452 // looking for in the current class).
1453 if (entry.Container != current) {
1454 if (declared_only || DoneSearching (list))
1457 current = entry.Container;
1460 // Is the member of the correct type ?
1461 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1464 // Is the member static/non-static ?
1465 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1468 // Apply the filter to it.
1469 if (filter (entry.Member, criteria)) {
1470 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1471 do_method_search = false;
1472 list.Add (entry.Member);
1476 Timer.StopTimer (TimerType.CachedLookup);
1478 // If we have a method cache and we aren't already doing a method-only
1479 // search, we restart in method-only search mode if the first match is
1480 // a method. This ensures that we return a MemberInfo with the correct
1481 // ReflectedType for inherited methods.
1482 if (do_method_search && (list.Count > 0)){
1483 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1486 return new MemberList (list);