(DISTFILES): Comment out a few missing files.
[mono-project.git] / mcs / mbas / decl.cs
blob99122e1126e6b2fc4e2522a1669aa2ce4d091491
1 //
2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
13 using System;
14 using System.Collections;
15 using System.Reflection.Emit;
16 using System.Reflection;
18 namespace Mono.MonoBASIC {
20 /// <summary>
21 /// Base representation for members. This is only used to keep track
22 /// of Name, Location and Modifier flags.
23 /// </summary>
24 public abstract class MemberCore : Attributable
26 /// <summary>
27 /// Public name
28 /// </summary>
29 public string Name;
31 /// <summary>
32 /// Modifier flags that the user specified in the source code
33 /// </summary>
34 public int ModFlags;
36 /// <summary>
37 /// Location where this declaration happens
38 /// </summary>
39 public readonly Location Location;
41 public MemberCore (string name, Attributes attrs, Location loc)
42 : base (attrs)
44 Name = name;
45 Location = loc;
48 protected void WarningNotHiding (TypeContainer parent)
50 /*Report.Warning (
51 109, Location,
52 "The member " + parent.MakeName (Name) + " does not hide an " +
53 "inherited member. The keyword new is not required");
54 */
57 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
58 string name)
61 // FIXME: report the old/new permissions?
63 Report.Error (
64 507, Location, parent.MakeName (Name) +
65 ": can't change the access modifiers when overriding inherited " +
66 "member `" + name + "'");
70 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
71 // that have been defined.
73 // `name' is the user visible name for reporting errors (this is used to
74 // provide the right name regarding method names and properties)
76 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
77 MethodInfo mb, string name)
79 bool ok = true;
81 if ((ModFlags & Modifiers.OVERRIDE) != 0){
82 // Now we check that the overriden method is not final
83 if (mb.IsFinal)
85 Report.Error (30267, Location, parent.MakeName (Name) + " : cannot " +
86 "override inherited member `" + name +
87 "' because it is NotOverridable.");
88 ok = false;
90 else if (!(mb.IsAbstract || mb.IsVirtual)){
91 Report.Error (
92 31086, Location, parent.MakeName (Name) +
93 ": Cannot override inherited member `" +
94 name + "' because it is not " +
95 "declared as Overridable");
96 ok = false;
100 // Check that the permissions are not being changed
102 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
103 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
105 if (thisp != parentp){
106 Error_CannotChangeAccessModifiers (parent, mb, name);
107 ok = false;
111 if ((ModFlags & ( Modifiers.NEW | Modifiers.SHADOWS | Modifiers.OVERRIDE )) == 0) {
112 if ((ModFlags & Modifiers.NONVIRTUAL) != 0) {
113 Report.Error (31088, Location,
114 parent.MakeName (Name) + " cannot " +
115 "be declared NotOverridable since this method is " +
116 "not marked as Overrides");
120 if (mb.IsAbstract) {
121 if ((ModFlags & (Modifiers.OVERRIDE)) == 0) {
122 if (Name != "Finalize") {
123 Report.Error (
124 31404, Location,
125 name + " cannot Shadows the method " +
126 parent.MakeName (Name) + " since it is declared " +
127 "'MustOverride' in base class");
131 else if (mb.IsVirtual){
132 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SHADOWS)) == 0){
133 if (Name != "Finalize"){
134 Report.Warning (
135 40005, 2, Location, parent.MakeName (Name) +
136 " shadows overridable member `" + name +
137 "'. To make the current member override that " +
138 "implementation, add the overrides keyword." );
139 ModFlags |= Modifiers.SHADOWS;
143 else {
144 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE |
145 Modifiers.SHADOWS)) == 0){
146 if (Name != "Finalize"){
147 Report.Warning (
148 40004, 1, Location, "The keyword Shadows is required on " +
149 parent.MakeName (Name) + " because it hides " +
150 "inherited member `" + name + "'");
151 ModFlags |= Modifiers.SHADOWS;
156 return ok;
159 public abstract bool Define (TypeContainer parent);
162 // Whehter is it ok to use an unsafe pointer in this type container
164 public bool UnsafeOK (DeclSpace parent)
167 // First check if this MemberCore modifier flags has unsafe set
169 if ((ModFlags & Modifiers.UNSAFE) != 0)
170 return true;
172 if (parent.UnsafeContext)
173 return true;
175 Expression.UnsafeError (Location);
176 return false;
181 // FIXME: This is temporary outside DeclSpace, because I have to fix a bug
182 // in MCS that makes it fail the lookup for the enum
185 /// <summary>
186 /// The result value from adding an declaration into
187 /// a struct or a class
188 /// </summary>
189 public enum AdditionResult {
190 /// <summary>
191 /// The declaration has been successfully
192 /// added to the declation space.
193 /// </summary>
194 Success,
196 /// <summary>
197 /// The symbol has already been defined.
198 /// </summary>
199 NameExists,
201 /// <summary>
202 /// Returned if the declation being added to the
203 /// name space clashes with its container name.
205 /// The only exceptions for this are constructors
206 /// and static constructors
207 /// </summary>
208 EnclosingClash,
210 /// <summary>
211 /// Returned if a constructor was created (because syntactically
212 /// it looked like a constructor) but was not (because the name
213 /// of the method is not the same as the container class
214 /// </summary>
215 NotAConstructor,
217 /// <summary>
218 /// This is only used by static constructors to emit the
219 /// error 111, but this error for other things really
220 /// happens at another level for other functions.
221 /// </summary>
222 MethodExists
225 /// <summary>
226 /// Base class for structs, classes, enumerations and interfaces.
227 /// </summary>
228 /// <remarks>
229 /// They all create new declaration spaces. This
230 /// provides the common foundation for managing those name
231 /// spaces.
232 /// </remarks>
233 public abstract class DeclSpace : MemberCore {
234 /// <summary>
235 /// this points to the actual definition that is being
236 /// created with System.Reflection.Emit
237 /// </summary>
238 public TypeBuilder TypeBuilder;
240 /// <summary>
241 /// This variable tracks whether we have Closed the type
242 /// </summary>
243 public bool Created = false;
246 // This is the namespace in which this typecontainer
247 // was declared. We use this to resolve names.
249 public Namespace Namespace;
251 public Hashtable Cache = new Hashtable ();
253 public string Basename;
255 /// <summary>
256 /// defined_names is used for toplevel objects
257 /// </summary>
258 protected Hashtable defined_names;
260 TypeContainer parent;
262 public DeclSpace (TypeContainer parent, string name, Attributes attrs, Location l)
263 : base (name, attrs, l)
265 Basename = name.Substring (1 + name.LastIndexOf ('.'));
266 defined_names = new Hashtable ();
267 this.parent = parent;
270 /// <summary>
271 /// Returns a status code based purely on the name
272 /// of the member being added
273 /// </summary>
274 protected AdditionResult IsValid (string name)
276 if (name == Basename)
277 return AdditionResult.EnclosingClash;
279 if (defined_names.Contains (name))
280 return AdditionResult.NameExists;
282 return AdditionResult.Success;
285 /// <summary>
286 /// Introduce @name into this declaration space and
287 /// associates it with the object @o. Note that for
288 /// methods this will just point to the first method. o
289 /// </summary>
290 protected void DefineName (string name, object o)
292 try {
293 defined_names.Add (name, o);
295 catch (ArgumentException exp) {
296 Report.Error (30260, /*Location,*/
297 "More than one defination with same name '" + name +
298 "' is found in the container '" + Name + "'");
303 /// <summary>
304 /// Returns the object associated with a given name in the declaration
305 /// space. This is the inverse operation of `DefineName'
306 /// </summary>
307 public object GetDefinition (string name)
309 return defined_names [name];
312 bool in_transit = false;
314 /// <summary>
315 /// This function is used to catch recursive definitions
316 /// in declarations.
317 /// </summary>
318 public bool InTransit {
319 get {
320 return in_transit;
323 set {
324 in_transit = value;
328 public TypeContainer Parent {
329 get {
330 return parent;
334 /// <summary>
335 /// Looks up the alias for the name
336 /// </summary>
337 public string LookupAlias (string name)
339 return RootContext.SourceBeingCompiled.LookupAlias (name);
343 // root_types contains all the types. All TopLevel types
344 // hence have a parent that points to `root_types', that is
345 // why there is a non-obvious test down here.
347 public bool IsTopLevel {
348 get {
349 if (parent != null){
350 if (parent.parent == null)
351 return true;
353 return false;
357 public virtual void CloseType ()
359 if (!Created){
360 try {
361 TypeBuilder.CreateType ();
362 } catch {
364 // The try/catch is needed because
365 // nested enumerations fail to load when they
366 // are defined.
368 // Even if this is the right order (enumerations
369 // declared after types).
371 // Note that this still creates the type and
372 // it is possible to save it
374 Created = true;
378 /// <remarks>
379 /// Should be overriten by the appropriate declaration space
380 /// <remarks>
381 public abstract TypeBuilder DefineType ();
383 /// <summary>
384 /// Define all members, but don't apply any attributes or do anything which may
385 /// access not-yet-defined classes. This method also creates the MemberCache.
386 /// </summary>
387 public abstract bool DefineMembers (TypeContainer parent);
390 // Whether this is an `unsafe context'
392 public bool UnsafeContext {
393 get {
394 if ((ModFlags & Modifiers.UNSAFE) != 0)
395 return true;
396 if (parent != null)
397 return parent.UnsafeContext;
398 return false;
402 public static string MakeFQN (string nsn, string name)
404 string prefix = (nsn == "" ? "" : nsn + ".");
406 return prefix + name;
409 EmitContext type_resolve_ec;
410 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
412 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
413 type_resolve_ec.ResolvingTypeTree = true;
415 return type_resolve_ec;
418 // <summary>
419 // Looks up the type, as parsed into the expression `e'
420 // </summary>
421 public Type ResolveType (Expression e, bool silent, Location loc)
423 if (type_resolve_ec == null)
424 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
425 type_resolve_ec.loc = loc;
427 int errors = Report.Errors;
428 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
429 if (d == null || d.eclass != ExprClass.Type){
430 if (!silent && errors == Report.Errors){
431 Report.Error (30002, loc, "Cannot find type `"+ e.ToString () +"'");
433 return null;
436 return d.Type;
439 // <summary>
440 // Resolves the expression `e' for a type, and will recursively define
441 // types.
442 // </summary>
443 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
445 if (type_resolve_ec == null)
446 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
448 Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
449 if (d == null || d.eclass != ExprClass.Type){
450 if (!silent){
451 Report.Error (30002, loc, "Cannot find type `"+ e +"'");
453 return null;
456 return d;
459 Type LookupInterfaceOrClass (string ns, string name, out bool error)
461 DeclSpace parent;
462 Type t;
464 error = false;
465 name = MakeFQN (ns, name);
467 t = TypeManager.LookupType (name);
468 if (t != null)
469 return t;
471 parent = (DeclSpace) RootContext.Tree.Decls [name];
472 if (parent == null)
473 return null;
475 t = parent.DefineType ();
476 if (t == null){
477 Report.Error (30256, Location, "Class definition is circular: `"+name+"'");
478 error = true;
479 return null;
481 return t;
484 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
486 Report.Error (104, loc,
487 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
488 t1.FullName, t2.FullName));
491 /// <summary>
492 /// GetType is used to resolve type names at the DeclSpace level.
493 /// Use this to lookup class/struct bases, interface bases or
494 /// delegate type references
495 /// </summary>
497 /// <remarks>
498 /// Contrast this to LookupType which is used inside method bodies to
499 /// lookup types that have already been defined. GetType is used
500 /// during the tree resolution process and potentially define
501 /// recursively the type
502 /// </remarks>
503 public Type FindType (Location loc, string name)
505 Type t;
506 bool error;
509 // For the case the type we are looking for is nested within this one
510 // or is in any base class
512 DeclSpace containing_ds = this;
514 while (containing_ds != null){
515 Type current_type = containing_ds.TypeBuilder;
517 while (current_type != null) {
518 string pre = current_type.FullName;
520 t = LookupInterfaceOrClass (pre, name, out error);
521 if (error)
522 return null;
524 if (t != null)
525 return t;
527 current_type = current_type.BaseType;
529 containing_ds = containing_ds.Parent;
533 // Attempt to lookup the class on our namespace and all it's implicit parents
535 for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
537 t = LookupInterfaceOrClass (ns, name, out error);
538 if (error)
539 return null;
541 if (t != null)
542 return t;
546 // Attempt to do a direct unqualified lookup
548 t = LookupInterfaceOrClass ("", name, out error);
549 if (error)
550 return null;
552 if (t != null)
553 return t;
556 // Attempt to lookup the class on any of the `using'
557 // namespaces
560 for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
562 t = LookupInterfaceOrClass (ns.Name, name, out error);
563 if (error)
564 return null;
566 if (t != null)
567 return t;
570 // Now check the using clause list
572 ICollection imports_list = RootContext.SourceBeingCompiled.ImportsTable;
574 if (imports_list == null)
575 continue;
577 Type match = null;
578 foreach (SourceBeingCompiled.ImportsEntry ue in imports_list){
579 match = LookupInterfaceOrClass (ue.Name, name, out error);
580 if (error)
581 return null;
583 if (match != null){
584 if (t != null){
585 Error_AmbiguousTypeReference (loc, name, t, match);
586 return null;
589 t = match;
590 ue.Used = true;
593 if (t != null)
594 return t;
597 //Report.Error (246, Location, "Can not find type `"+name+"'");
598 return null;
601 /// <remarks>
602 /// This function is broken and not what you're looking for. It should only
603 /// be used while the type is still being created since it doesn't use the cache
604 /// and relies on the filter doing the member name check.
605 /// </remarks>
606 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
607 MemberFilter filter, object criteria);
609 /// <remarks>
610 /// If we have a MemberCache, return it. This property may return null if the
611 /// class doesn't have a member cache or while it's still being created.
612 /// </remarks>
613 public abstract MemberCache MemberCache {
614 get;
618 /// <summary>
619 /// This is a readonly list of MemberInfo's.
620 /// </summary>
621 public class MemberList : IList {
622 public readonly IList List;
623 int count;
625 /// <summary>
626 /// Create a new MemberList from the given IList.
627 /// </summary>
628 public MemberList (IList list)
630 if (list != null)
631 this.List = list;
632 else
633 this.List = new ArrayList ();
634 count = List.Count;
637 /// <summary>
638 /// Concatenate the ILists `first' and `second' to a new MemberList.
639 /// </summary>
640 public MemberList (IList first, IList second)
642 ArrayList list = new ArrayList ();
643 list.AddRange (first);
644 list.AddRange (second);
645 count = list.Count;
646 List = list;
649 public static readonly MemberList Empty = new MemberList (new ArrayList ());
651 /// <summary>
652 /// Cast the MemberList into a MemberInfo[] array.
653 /// </summary>
654 /// <remarks>
655 /// This is an expensive operation, only use it if it's really necessary.
656 /// </remarks>
657 public static explicit operator MemberInfo [] (MemberList list)
659 Timer.StartTimer (TimerType.MiscTimer);
660 MemberInfo [] result = new MemberInfo [list.Count];
661 list.CopyTo (result, 0);
662 Timer.StopTimer (TimerType.MiscTimer);
663 return result;
666 // ICollection
668 public int Count {
669 get {
670 return count;
674 public bool IsSynchronized {
675 get {
676 return List.IsSynchronized;
680 public object SyncRoot {
681 get {
682 return List.SyncRoot;
686 public void CopyTo (Array array, int index)
688 List.CopyTo (array, index);
691 // IEnumerable
693 public IEnumerator GetEnumerator ()
695 return List.GetEnumerator ();
698 // IList
700 public bool IsFixedSize {
701 get {
702 return true;
706 public bool IsReadOnly {
707 get {
708 return true;
712 object IList.this [int index] {
713 get {
714 return List [index];
717 set {
718 throw new NotSupportedException ();
722 // FIXME: try to find out whether we can avoid the cast in this indexer.
723 public MemberInfo this [int index] {
724 get {
725 return (MemberInfo) List [index];
729 public int Add (object value)
731 throw new NotSupportedException ();
734 public void Clear ()
736 throw new NotSupportedException ();
739 public bool Contains (object value)
741 return List.Contains (value);
744 public int IndexOf (object value)
746 return List.IndexOf (value);
749 public void Insert (int index, object value)
751 throw new NotSupportedException ();
754 public void Remove (object value)
756 throw new NotSupportedException ();
759 public void RemoveAt (int index)
761 throw new NotSupportedException ();
765 /// <summary>
766 /// This interface is used to get all members of a class when creating the
767 /// member cache. It must be implemented by all DeclSpace derivatives which
768 /// want to support the member cache and by TypeHandle to get caching of
769 /// non-dynamic types.
770 /// </summary>
771 public interface IMemberContainer {
772 /// <summary>
773 /// The name of the IMemberContainer. This is only used for
774 /// debugging purposes.
775 /// </summary>
776 string Name {
777 get;
780 /// <summary>
781 /// The type of this IMemberContainer.
782 /// </summary>
783 Type Type {
784 get;
787 /// <summary>
788 /// Returns the IMemberContainer of the parent class or null if this
789 /// is an interface or TypeManger.object_type.
790 /// This is used when creating the member cache for a class to get all
791 /// members from the parent class.
792 /// </summary>
793 IMemberContainer Parent {
794 get;
797 /// <summary>
798 /// Whether this is an interface.
799 /// </summary>
800 bool IsInterface {
801 get;
804 /// <summary>
805 /// Returns all members of this class with the corresponding MemberTypes
806 /// and BindingFlags.
807 /// </summary>
808 /// <remarks>
809 /// When implementing this method, make sure not to return any inherited
810 /// members and check the MemberTypes and BindingFlags properly.
811 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
812 /// get the BindingFlags (static/non-static,public/non-public) in the
813 /// MemberInfo class, but the cache needs this information. That's why
814 /// this method is called multiple times with different BindingFlags.
815 /// </remarks>
816 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
818 /// <summary>
819 /// Return the container's member cache.
820 /// </summary>
821 MemberCache MemberCache {
822 get;
826 /// <summary>
827 /// The MemberCache is used by dynamic and non-dynamic types to speed up
828 /// member lookups. It has a member name based hash table; it maps each member
829 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
830 /// and the BindingFlags that were initially used to get it. The cache contains
831 /// all members of the current class and all inherited members. If this cache is
832 /// for an interface types, it also contains all inherited members.
834 /// There are two ways to get a MemberCache:
835 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
836 /// use the DeclSpace.MemberCache property.
837 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
838 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
839 /// </summary>
840 public class MemberCache {
841 public readonly IMemberContainer Container;
842 protected CaseInsensitiveHashtable member_hash;
843 protected CaseInsensitiveHashtable method_hash;
844 protected CaseInsensitiveHashtable interface_hash;
846 /// <summary>
847 /// Create a new MemberCache for the given IMemberContainer `container'.
848 /// </summary>
849 public MemberCache (IMemberContainer container)
851 this.Container = container;
853 Timer.IncrementCounter (CounterType.MemberCache);
854 Timer.StartTimer (TimerType.CacheInit);
856 interface_hash = new CaseInsensitiveHashtable ();
858 // If we have a parent class (we have a parent class unless we're
859 // TypeManager.object_type), we deep-copy its MemberCache here.
860 if (Container.Parent != null)
861 member_hash = SetupCache (Container.Parent.MemberCache);
862 else if (Container.IsInterface)
863 member_hash = SetupCacheForInterface ();
864 else
865 member_hash = new CaseInsensitiveHashtable ();
867 // If this is neither a dynamic type nor an interface, create a special
868 // method cache with all declared and inherited methods.
869 Type type = container.Type;
870 if (!(type is TypeBuilder) && !type.IsInterface) {
871 method_hash = new CaseInsensitiveHashtable ();
872 AddMethods (type);
875 // Add all members from the current class.
876 AddMembers (Container);
878 Timer.StopTimer (TimerType.CacheInit);
881 /// <summary>
882 /// Bootstrap this member cache by doing a deep-copy of our parent.
883 /// </summary>
884 CaseInsensitiveHashtable SetupCache (MemberCache parent)
886 CaseInsensitiveHashtable hash = new CaseInsensitiveHashtable ();
888 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
889 while (it.MoveNext ()) {
890 ArrayList al = (ArrayList) it.Value;
891 // Constructors are never inherited and all have the same key
892 if ((((CacheEntry)al [0]).EntryType & EntryType.Constructor) == 0)
893 hash [it.Key] = ((ArrayList) it.Value).Clone ();
896 return hash;
899 void AddInterfaces (MemberCache parent)
901 foreach (Type iface in parent.interface_hash.Keys) {
902 if (!interface_hash.Contains (iface))
903 interface_hash.Add (iface, true);
907 /// <summary>
908 /// Add the contents of `new_hash' to `hash'.
909 /// </summary>
910 void AddHashtable (Hashtable hash, Hashtable new_hash)
912 IDictionaryEnumerator it = new_hash.GetEnumerator ();
913 while (it.MoveNext ()) {
914 ArrayList list = (ArrayList) hash [it.Key];
915 if (list != null)
916 list.AddRange ((ArrayList) it.Value);
917 else
918 hash [it.Key] = ((ArrayList) it.Value).Clone ();
922 /// <summary>
923 /// Bootstrap the member cache for an interface type.
924 /// Type.GetMembers() won't return any inherited members for interface types,
925 /// so we need to do this manually. Interfaces also inherit from System.Object.
926 /// </summary>
927 CaseInsensitiveHashtable SetupCacheForInterface ()
929 CaseInsensitiveHashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
930 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
932 foreach (Type iface in ifaces) {
933 if (interface_hash.Contains (iface))
934 continue;
935 interface_hash.Add (iface, true);
937 IMemberContainer iface_container =
938 TypeManager.LookupMemberContainer (iface);
940 MemberCache iface_cache = iface_container.MemberCache;
941 AddHashtable (hash, iface_cache.member_hash);
942 AddInterfaces (iface_cache);
945 return hash;
948 /// <summary>
949 /// Add all members from class `container' to the cache.
950 /// </summary>
951 void AddMembers (IMemberContainer container)
953 // We need to call AddMembers() with a single member type at a time
954 // to get the member type part of CacheEntry.EntryType right.
955 AddMembers (MemberTypes.Constructor, container);
956 AddMembers (MemberTypes.Field, container);
957 AddMembers (MemberTypes.Method, container);
958 AddMembers (MemberTypes.Property, container);
959 AddMembers (MemberTypes.Event, container);
960 // Nested types are returned by both Static and Instance searches.
961 AddMembers (MemberTypes.NestedType,
962 BindingFlags.Static | BindingFlags.Public, container);
963 AddMembers (MemberTypes.NestedType,
964 BindingFlags.Static | BindingFlags.NonPublic, container);
967 void AddMembers (MemberTypes mt, IMemberContainer container)
969 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
970 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
971 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
972 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
975 /// <summary>
976 /// Add all members from class `container' with the requested MemberTypes and
977 /// BindingFlags to the cache. This method is called multiple times with different
978 /// MemberTypes and BindingFlags.
979 /// </summary>
980 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
982 MemberList members = container.GetMembers (mt, bf);
983 BindingFlags new_bf = (container == Container) ?
984 bf | BindingFlags.DeclaredOnly : bf;
986 foreach (MemberInfo member in members) {
987 string name = member.Name;
989 // We use a name-based hash table of ArrayList's.
990 ArrayList list = (ArrayList) member_hash [name];
991 if (list == null) {
992 list = new ArrayList ();
993 member_hash.Add (name, list);
996 // When this method is called for the current class, the list will
997 // already contain all inherited members from our parent classes.
998 // We cannot add new members in front of the list since this'd be an
999 // expensive operation, that's why the list is sorted in reverse order
1000 // (ie. members from the current class are coming last).
1001 list.Add (new CacheEntry (container, member, mt, bf));
1005 /// <summary>
1006 /// Add all declared and inherited methods from class `type' to the method cache.
1007 /// </summary>
1008 void AddMethods (Type type)
1010 AddMethods (BindingFlags.Static | BindingFlags.Public, type);
1011 AddMethods (BindingFlags.Static | BindingFlags.NonPublic, type);
1012 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1013 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1016 void AddMethods (BindingFlags bf, Type type)
1018 MemberInfo [] members = type.GetMethods (bf);
1020 foreach (MethodBase member in members) {
1021 string name = member.Name;
1023 // Varargs methods aren't allowed in C# code.
1024 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1025 continue;
1027 // We use a name-based hash table of ArrayList's.
1028 ArrayList list = (ArrayList) method_hash [name];
1029 if (list == null) {
1030 list = new ArrayList ();
1031 method_hash.Add (name, list);
1034 // Unfortunately, the elements returned by Type.GetMethods() aren't
1035 // sorted so we need to do this check for every member.
1036 BindingFlags new_bf = bf;
1037 if (member.DeclaringType == type)
1038 new_bf |= BindingFlags.DeclaredOnly;
1040 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1044 /// <summary>
1045 /// Compute and return a appropriate `EntryType' magic number for the given
1046 /// MemberTypes and BindingFlags.
1047 /// </summary>
1048 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1050 EntryType type = EntryType.None;
1052 if ((mt & MemberTypes.Constructor) != 0)
1053 type |= EntryType.Constructor;
1054 if ((mt & MemberTypes.Event) != 0)
1055 type |= EntryType.Event;
1056 if ((mt & MemberTypes.Field) != 0)
1057 type |= EntryType.Field;
1058 if ((mt & MemberTypes.Method) != 0)
1059 type |= EntryType.Method;
1060 if ((mt & MemberTypes.Property) != 0)
1061 type |= EntryType.Property;
1062 // Nested types are returned by static and instance searches.
1063 if ((mt & MemberTypes.NestedType) != 0)
1064 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1066 if ((bf & BindingFlags.Instance) != 0)
1067 type |= EntryType.Instance;
1068 if ((bf & BindingFlags.Static) != 0)
1069 type |= EntryType.Static;
1070 if ((bf & BindingFlags.Public) != 0)
1071 type |= EntryType.Public;
1072 if ((bf & BindingFlags.NonPublic) != 0)
1073 type |= EntryType.NonPublic;
1074 if ((bf & BindingFlags.DeclaredOnly) != 0)
1075 type |= EntryType.Declared;
1077 return type;
1080 /// <summary>
1081 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1082 /// denote multiple member types. Returns true if the given flags value denotes a
1083 /// single member types.
1084 /// </summary>
1085 public static bool IsSingleMemberType (MemberTypes mt)
1087 switch (mt) {
1088 case MemberTypes.Constructor:
1089 case MemberTypes.Event:
1090 case MemberTypes.Field:
1091 case MemberTypes.Method:
1092 case MemberTypes.Property:
1093 case MemberTypes.NestedType:
1094 return true;
1096 default:
1097 return false;
1101 /// <summary>
1102 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1103 /// number to speed up the searching process.
1104 /// </summary>
1105 [Flags]
1106 protected enum EntryType {
1107 None = 0x000,
1109 Instance = 0x001,
1110 Static = 0x002,
1111 MaskStatic = Instance|Static,
1113 Public = 0x004,
1114 NonPublic = 0x008,
1115 MaskProtection = Public|NonPublic,
1117 Declared = 0x010,
1119 Constructor = 0x020,
1120 Event = 0x040,
1121 Field = 0x080,
1122 Method = 0x100,
1123 Property = 0x200,
1124 NestedType = 0x400,
1126 MaskType = Constructor|Event|Field|Method|Property|NestedType
1129 protected struct CacheEntry {
1130 public readonly IMemberContainer Container;
1131 public readonly EntryType EntryType;
1132 public readonly MemberInfo Member;
1134 public CacheEntry (IMemberContainer container, MemberInfo member,
1135 MemberTypes mt, BindingFlags bf)
1137 this.Container = container;
1138 this.Member = member;
1139 this.EntryType = GetEntryType (mt, bf);
1143 /// <summary>
1144 /// This is called each time we're walking up one level in the class hierarchy
1145 /// and checks whether we can abort the search since we've already found what
1146 /// we were looking for.
1147 /// </summary>
1148 protected bool DoneSearching (ArrayList list)
1151 // We've found exactly one member in the current class and it's not
1152 // a method or constructor.
1154 if (list.Count == 1 && !(list [0] is MethodBase))
1155 return true;
1158 // Multiple properties: we query those just to find out the indexer
1159 // name
1161 if ((list.Count > 0) && (list [0] is PropertyInfo))
1162 return true;
1164 return false;
1167 /// <summary>
1168 /// Looks up members with name `name'. If you provide an optional
1169 /// filter function, it'll only be called with members matching the
1170 /// requested member name.
1172 /// This method will try to use the cache to do the lookup if possible.
1174 /// Unlike other FindMembers implementations, this method will always
1175 /// check all inherited members - even when called on an interface type.
1177 /// If you know that you're only looking for methods, you should use
1178 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1179 /// When doing a method-only search, it'll try to use a special method
1180 /// cache (unless it's a dynamic type or an interface) and the returned
1181 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1182 /// The lookup process will automatically restart itself in method-only
1183 /// search mode if it discovers that it's about to return methods.
1184 /// </summary>
1185 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1186 MemberFilter filter, object criteria)
1188 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1189 bool method_search = mt == MemberTypes.Method;
1190 // If we have a method cache and we aren't already doing a method-only search,
1191 // then we restart a method search if the first match is a method.
1192 bool do_method_search = !method_search && (method_hash != null);
1193 bf |= BindingFlags.IgnoreCase;
1194 ArrayList applicable;
1196 // If this is a method-only search, we try to use the method cache if
1197 // possible; a lookup in the method cache will return a MemberInfo with
1198 // the correct ReflectedType for inherited methods.
1199 if (method_search && (method_hash != null))
1200 applicable = (ArrayList) method_hash [name];
1201 else
1202 applicable = (ArrayList) member_hash [name];
1204 if (applicable == null)
1205 return MemberList.Empty;
1207 ArrayList list = new ArrayList ();
1209 Timer.StartTimer (TimerType.CachedLookup);
1211 EntryType type = GetEntryType (mt, bf);
1213 IMemberContainer current = Container;
1215 // `applicable' is a list of all members with the given member name `name'
1216 // in the current class and all its parent classes. The list is sorted in
1217 // reverse order due to the way how the cache is initialy created (to speed
1218 // things up, we're doing a deep-copy of our parent).
1220 for (int i = applicable.Count-1; i >= 0; i--) {
1221 CacheEntry entry = (CacheEntry) applicable [i];
1223 // This happens each time we're walking one level up in the class
1224 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1225 // the first time this happens (this may already happen in the first
1226 // iteration of this loop if there are no members with the name we're
1227 // looking for in the current class).
1228 if (entry.Container != current) {
1229 if (declared_only || DoneSearching (list))
1230 break;
1232 current = entry.Container;
1235 // Is the member of the correct type ?
1236 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1237 continue;
1239 // Is the member static/non-static ?
1240 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1241 continue;
1243 // Apply the filter to it.
1244 if (filter (entry.Member, criteria)) {
1245 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1246 do_method_search = false;
1247 list.Add (entry.Member);
1251 Timer.StopTimer (TimerType.CachedLookup);
1253 // If we have a method cache and we aren't already doing a method-only
1254 // search, we restart in method-only search mode if the first match is
1255 // a method. This ensures that we return a MemberInfo with the correct
1256 // ReflectedType for inherited methods.
1257 if (do_method_search && (list.Count > 0))
1258 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1260 return new MemberList (list);