2002-09-03 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / mbas / decl.cs
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
11 //
12
13 using System;
14 using System.Collections;
15 using System.Reflection.Emit;
16 using System.Reflection;
17
18 namespace Mono.CSharp {
19
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 {
25                 /// <summary>
26                 ///   Public name
27                 /// </summary>
28                 public string Name;
29
30                 /// <summary>
31                 ///   Modifier flags that the user specified in the source code
32                 /// </summary>
33                 public int ModFlags;
34
35                 /// <summary>
36                 ///   Location where this declaration happens
37                 /// </summary>
38                 public readonly Location Location;
39
40                 public MemberCore (string name, Location loc)
41                 {
42                         Name = name;
43                         Location = loc;
44                 }
45
46                 protected void WarningNotHiding (TypeContainer parent)
47                 {
48                         Report.Warning (
49                                 109, Location,
50                                 "The member " + parent.MakeName (Name) + " does not hide an " +
51                                 "inherited member.  The keyword new is not required");
52                                                            
53                 }
54
55                 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
56                                                         string name)
57                 {
58                         //
59                         // FIXME: report the old/new permissions?
60                         //
61                         Report.Error (
62                                 507, Location, parent.MakeName (Name) +
63                                 ": can't change the access modifiers when overriding inherited " +
64                                 "member `" + name + "'");
65                 }
66                 
67                 //
68                 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
69                 // that have been defined.
70                 //
71                 // `name' is the user visible name for reporting errors (this is used to
72                 // provide the right name regarding method names and properties)
73                 //
74                 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
75                                                        MethodInfo mb, string name)
76                 {
77                         bool ok = true;
78                         
79                         if ((ModFlags & Modifiers.OVERRIDE) != 0){
80                                 if (!(mb.IsAbstract || mb.IsVirtual)){
81                                         Report.Error (
82                                                 506, Location, parent.MakeName (Name) +
83                                                 ": cannot override inherited member `" +
84                                                 name + "' because it is not " +
85                                                 "virtual, abstract or override");
86                                         ok = false;
87                                 }
88                                 
89                                 // Now we check that the overriden method is not final
90                                 
91                                 if (mb.IsFinal) {
92                                         Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
93                                                       "override inherited member `" + name +
94                                                       "' because it is sealed.");
95                                         ok = false;
96                                 }
97
98                                 //
99                                 // Check that the permissions are not being changed
100                                 //
101                                 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
102                                 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
103
104                                 if (thisp != parentp){
105                                         Error_CannotChangeAccessModifiers (parent, mb, name);
106                                         ok = false;
107                                 }
108                         }
109
110                         if (mb.IsVirtual || mb.IsAbstract){
111                                 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
112                                         if (Name != "Finalize"){
113                                                 Report.Warning (
114                                                         114, 2, Location, parent.MakeName (Name) + 
115                                                         " hides inherited member `" + name +
116                                                         "'.  To make the current member override that " +
117                                                         "implementation, add the override keyword, " +
118                                                         "otherwise use the new keyword");
119                                                 ModFlags |= Modifiers.NEW;
120                                         }
121                                 }
122                         } else {
123                                 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
124                                         if (Name != "Finalize"){
125                                                 Report.Warning (
126                                                         108, 1, Location, "The keyword new is required on " +
127                                                         parent.MakeName (Name) + " because it hides " +
128                                                         "inherited member `" + name + "'");
129                                                 ModFlags |= Modifiers.NEW;
130                                         }
131                                 }
132                         }
133
134                         return ok;
135                 }
136
137                 public abstract bool Define (TypeContainer parent);
138
139                 // 
140                 // Whehter is it ok to use an unsafe pointer in this type container
141                 //
142                 public bool UnsafeOK (DeclSpace parent)
143                 {
144                         //
145                         // First check if this MemberCore modifier flags has unsafe set
146                         //
147                         if ((ModFlags & Modifiers.UNSAFE) != 0)
148                                 return true;
149
150                         if (parent.UnsafeContext)
151                                 return true;
152
153                         Expression.UnsafeError (Location);
154                         return false;
155                 }
156         }
157
158         //
159         // FIXME: This is temporary outside DeclSpace, because I have to fix a bug
160         // in MCS that makes it fail the lookup for the enum
161         //
162
163                 /// <summary>
164                 ///   The result value from adding an declaration into
165                 ///   a struct or a class
166                 /// </summary>
167                 public enum AdditionResult {
168                         /// <summary>
169                         /// The declaration has been successfully
170                         /// added to the declation space.
171                         /// </summary>
172                         Success,
173
174                         /// <summary>
175                         ///   The symbol has already been defined.
176                         /// </summary>
177                         NameExists,
178
179                         /// <summary>
180                         ///   Returned if the declation being added to the
181                         ///   name space clashes with its container name.
182                         ///
183                         ///   The only exceptions for this are constructors
184                         ///   and static constructors
185                         /// </summary>
186                         EnclosingClash,
187
188                         /// <summary>
189                         ///   Returned if a constructor was created (because syntactically
190                         ///   it looked like a constructor) but was not (because the name
191                         ///   of the method is not the same as the container class
192                         /// </summary>
193                         NotAConstructor,
194
195                         /// <summary>
196                         ///   This is only used by static constructors to emit the
197                         ///   error 111, but this error for other things really
198                         ///   happens at another level for other functions.
199                         /// </summary>
200                         MethodExists
201                 }
202
203         /// <summary>
204         ///   Base class for structs, classes, enumerations and interfaces.  
205         /// </summary>
206         /// <remarks>
207         ///   They all create new declaration spaces.  This
208         ///   provides the common foundation for managing those name
209         ///   spaces.
210         /// </remarks>
211         public abstract class DeclSpace : MemberCore {
212                 /// <summary>
213                 ///   this points to the actual definition that is being
214                 ///   created with System.Reflection.Emit
215                 /// </summary>
216                 public TypeBuilder TypeBuilder;
217
218                 /// <summary>
219                 ///   This variable tracks whether we have Closed the type
220                 /// </summary>
221                 public bool Created = false;
222                 
223                 //
224                 // This is the namespace in which this typecontainer
225                 // was declared.  We use this to resolve names.
226                 //
227                 public Namespace Namespace;
228
229                 public Hashtable Cache = new Hashtable ();
230                 
231                 public string Basename;
232                 
233                 /// <summary>
234                 ///   defined_names is used for toplevel objects
235                 /// </summary>
236                 protected Hashtable defined_names;
237
238                 TypeContainer parent;           
239
240                 public DeclSpace (TypeContainer parent, string name, Location l)
241                         : base (name, l)
242                 {
243                         Basename = name.Substring (1 + name.LastIndexOf ('.'));
244                         defined_names = new Hashtable ();
245                         this.parent = parent;
246                 }
247
248                 /// <summary>
249                 ///   Returns a status code based purely on the name
250                 ///   of the member being added
251                 /// </summary>
252                 protected AdditionResult IsValid (string name)
253                 {
254                         if (name == Basename)
255                                 return AdditionResult.EnclosingClash;
256
257                         if (defined_names.Contains (name))
258                                 return AdditionResult.NameExists;
259
260                         return AdditionResult.Success;
261                 }
262
263                 /// <summary>
264                 ///   Introduce @name into this declaration space and
265                 ///   associates it with the object @o.  Note that for
266                 ///   methods this will just point to the first method. o
267                 /// </summary>
268                 protected void DefineName (string name, object o)
269                 {
270                         defined_names.Add (name, o);
271                 }
272
273                 /// <summary>
274                 ///   Returns the object associated with a given name in the declaration
275                 ///   space.  This is the inverse operation of `DefineName'
276                 /// </summary>
277                 public object GetDefinition (string name)
278                 {
279                         return defined_names [name];
280                 }
281                 
282                 bool in_transit = false;
283                 
284                 /// <summary>
285                 ///   This function is used to catch recursive definitions
286                 ///   in declarations.
287                 /// </summary>
288                 public bool InTransit {
289                         get {
290                                 return in_transit;
291                         }
292
293                         set {
294                                 in_transit = value;
295                         }
296                 }
297
298                 public TypeContainer Parent {
299                         get {
300                                 return parent;
301                         }
302                 }
303
304                 /// <summary>
305                 ///   Looks up the alias for the name
306                 /// </summary>
307                 public string LookupAlias (string name)
308                 {
309                         if (Namespace != null)
310                                 return Namespace.LookupAlias (name);
311                         else
312                                 return null;
313                 }
314                 
315                 // 
316                 // root_types contains all the types.  All TopLevel types
317                 // hence have a parent that points to `root_types', that is
318                 // why there is a non-obvious test down here.
319                 //
320                 public bool IsTopLevel {
321                         get {
322                                 if (parent != null){
323                                         if (parent.parent == null)
324                                                 return true;
325                                 }
326                                 return false;
327                         }
328                 }
329
330                 public virtual void CloseType ()
331                 {
332                         if (!Created){
333                                 try {
334                                         TypeBuilder.CreateType ();
335                                 } catch {
336                                         //
337                                         // The try/catch is needed because
338                                         // nested enumerations fail to load when they
339                                         // are defined.
340                                         //
341                                         // Even if this is the right order (enumerations
342                                         // declared after types).
343                                         //
344                                         // Note that this still creates the type and
345                                         // it is possible to save it
346                                 }
347                                 Created = true;
348                         }
349                 }
350
351                 /// <remarks>
352                 ///  Should be overriten by the appropriate declaration space
353                 /// <remarks>
354                 public abstract TypeBuilder DefineType ();
355                 
356                 /// <summary>
357                 ///   Define all members, but don't apply any attributes or do anything which may
358                 ///   access not-yet-defined classes.  This method also creates the MemberCache.
359                 /// </summary>
360                 public abstract bool DefineMembers (TypeContainer parent);
361
362                 //
363                 // Whether this is an `unsafe context'
364                 //
365                 public bool UnsafeContext {
366                         get {
367                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
368                                         return true;
369                                 if (parent != null)
370                                         return parent.UnsafeContext;
371                                 return false;
372                         }
373                 }
374
375                 public static string MakeFQN (string nsn, string name)
376                 {
377                         string prefix = (nsn == "" ? "" : nsn + ".");
378
379                         return prefix + name;
380                 }
381
382                 EmitContext type_resolve_ec;
383                 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
384                 {
385                         type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
386                         type_resolve_ec.ResolvingTypeTree = true;
387
388                         return type_resolve_ec;
389                 }
390
391                 // <summary>
392                 //    Looks up the type, as parsed into the expression `e' 
393                 // </summary>
394                 public Type ResolveType (Expression e, bool silent, Location loc)
395                 {
396                         if (type_resolve_ec == null)
397                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
398                         type_resolve_ec.loc = loc;
399                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
400                         if (d == null || d.eclass != ExprClass.Type){
401                                 if (!silent){
402                                         Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
403                                 }
404                                 return null;
405                         }
406
407                         return d.Type;
408                 }
409
410                 // <summary>
411                 //    Resolves the expression `e' for a type, and will recursively define
412                 //    types. 
413                 // </summary>
414                 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
415                 {
416                         if (type_resolve_ec == null)
417                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
418
419                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
420                         if (d == null || d.eclass != ExprClass.Type){
421                                 if (!silent){
422                                         Report.Error (246, loc, "Cannot find type `"+ e +"'");
423                                 }
424                                 return null;
425                         }
426
427                         return d;
428                 }
429                 
430                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
431                 {
432                         DeclSpace parent;
433                         Type t;
434
435                         error = false;
436                         name = MakeFQN (ns, name);
437                         
438                         t  = TypeManager.LookupType (name);
439                         if (t != null)
440                                 return t;
441
442                         parent = (DeclSpace) RootContext.Tree.Decls [name];
443                         if (parent == null)
444                                 return null;
445                         
446                         t = parent.DefineType ();
447                         if (t == null){
448                                 Report.Error (146, "Class definition is circular: `"+name+"'");
449                                 error = true;
450                                 return null;
451                         }
452                         return t;
453                 }
454                 
455                 /// <summary>
456                 ///   GetType is used to resolve type names at the DeclSpace level.
457                 ///   Use this to lookup class/struct bases, interface bases or 
458                 ///   delegate type references
459                 /// </summary>
460                 ///
461                 /// <remarks>
462                 ///   Contrast this to LookupType which is used inside method bodies to 
463                 ///   lookup types that have already been defined.  GetType is used
464                 ///   during the tree resolution process and potentially define
465                 ///   recursively the type
466                 /// </remarks>
467                 public Type FindType (string name)
468                 {
469                         Type t;
470                         bool error;
471
472                         //
473                         // For the case the type we are looking for is nested within this one
474                         // or is in any base class
475                         //
476                         DeclSpace containing_ds = this;
477
478                         while (containing_ds != null){
479                                 Type current_type = containing_ds.TypeBuilder;
480
481                                 while (current_type != null) {
482                                         string pre = current_type.FullName;
483                                         
484                                         t = LookupInterfaceOrClass (pre, name, out error);
485                                         if (error)
486                                                 return null;
487                                 
488                                         if (t != null) 
489                                                 return t;
490
491                                         current_type = current_type.BaseType;
492                                 }
493                                 containing_ds = containing_ds.Parent;
494                         }
495                         
496                         //
497                         // Attempt to lookup the class on our namespace and all it's implicit parents
498                         //
499                         for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
500
501                                 t = LookupInterfaceOrClass (ns, name, out error);
502                                 if (error)
503                                         return null;
504                                 
505                                 if (t != null) 
506                                         return t;
507                         }
508                         
509                         //
510                         // Attempt to do a direct unqualified lookup
511                         //
512                         t = LookupInterfaceOrClass ("", name, out error);
513                         if (error)
514                                 return null;
515                         
516                         if (t != null)
517                                 return t;
518                         
519                         //
520                         // Attempt to lookup the class on any of the `using'
521                         // namespaces
522                         //
523
524                         for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
525
526                                 t = LookupInterfaceOrClass (ns.Name, name, out error);
527                                 if (error)
528                                         return null;
529
530                                 if (t != null)
531                                         return t;
532
533                                 //
534                                 // Now check the using clause list
535                                 //
536                                 ArrayList using_list = ns.UsingTable;
537                                 
538                                 if (using_list == null)
539                                         continue;
540
541                                 foreach (string n in using_list){
542                                         t = LookupInterfaceOrClass (n, name, out error);
543                                         if (error)
544                                                 return null;
545
546                                         if (t != null)
547                                                 return t;
548                                 }
549                                 
550                         }
551
552                         //Report.Error (246, Location, "Can not find type `"+name+"'");
553                         return null;
554                 }
555
556                 /// <remarks>
557                 ///   This function is broken and not what you're looking for.  It should only
558                 ///   be used while the type is still being created since it doesn't use the cache
559                 ///   and relies on the filter doing the member name check.
560                 /// </remarks>
561                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
562                                                         MemberFilter filter, object criteria);
563
564                 /// <remarks>
565                 ///   If we have a MemberCache, return it.  This property may return null if the
566                 ///   class doesn't have a member cache or while it's still being created.
567                 /// </remarks>
568                 public abstract MemberCache MemberCache {
569                         get;
570                 }
571         }
572
573         /// <summary>
574         ///   This is a readonly list of MemberInfo's.      
575         /// </summary>
576         public class MemberList : IList {
577                 public readonly IList List;
578                 int count;
579
580                 /// <summary>
581                 ///   Create a new MemberList from the given IList.
582                 /// </summary>
583                 public MemberList (IList list)
584                 {
585                         if (list != null)
586                                 this.List = list;
587                         else
588                                 this.List = new ArrayList ();
589                         count = List.Count;
590                 }
591
592                 /// <summary>
593                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
594                 /// </summary>
595                 public MemberList (IList first, IList second)
596                 {
597                         ArrayList list = new ArrayList ();
598                         list.AddRange (first);
599                         list.AddRange (second);
600                         count = list.Count;
601                         List = list;
602                 }
603
604                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
605
606                 /// <summary>
607                 ///   Cast the MemberList into a MemberInfo[] array.
608                 /// </summary>
609                 /// <remarks>
610                 ///   This is an expensive operation, only use it if it's really necessary.
611                 /// </remarks>
612                 public static explicit operator MemberInfo [] (MemberList list)
613                 {
614                         Timer.StartTimer (TimerType.MiscTimer);
615                         MemberInfo [] result = new MemberInfo [list.Count];
616                         list.CopyTo (result, 0);
617                         Timer.StopTimer (TimerType.MiscTimer);
618                         return result;
619                 }
620
621                 // ICollection
622
623                 public int Count {
624                         get {
625                                 return count;
626                         }
627                 }
628
629                 public bool IsSynchronized {
630                         get {
631                                 return List.IsSynchronized;
632                         }
633                 }
634
635                 public object SyncRoot {
636                         get {
637                                 return List.SyncRoot;
638                         }
639                 }
640
641                 public void CopyTo (Array array, int index)
642                 {
643                         List.CopyTo (array, index);
644                 }
645
646                 // IEnumerable
647
648                 public IEnumerator GetEnumerator ()
649                 {
650                         return List.GetEnumerator ();
651                 }
652
653                 // IList
654
655                 public bool IsFixedSize {
656                         get {
657                                 return true;
658                         }
659                 }
660
661                 public bool IsReadOnly {
662                         get {
663                                 return true;
664                         }
665                 }
666
667                 object IList.this [int index] {
668                         get {
669                                 return List [index];
670                         }
671
672                         set {
673                                 throw new NotSupportedException ();
674                         }
675                 }
676
677                 // FIXME: try to find out whether we can avoid the cast in this indexer.
678                 public MemberInfo this [int index] {
679                         get {
680                                 return (MemberInfo) List [index];
681                         }
682                 }
683
684                 public int Add (object value)
685                 {
686                         throw new NotSupportedException ();
687                 }
688
689                 public void Clear ()
690                 {
691                         throw new NotSupportedException ();
692                 }
693
694                 public bool Contains (object value)
695                 {
696                         return List.Contains (value);
697                 }
698
699                 public int IndexOf (object value)
700                 {
701                         return List.IndexOf (value);
702                 }
703
704                 public void Insert (int index, object value)
705                 {
706                         throw new NotSupportedException ();
707                 }
708
709                 public void Remove (object value)
710                 {
711                         throw new NotSupportedException ();
712                 }
713
714                 public void RemoveAt (int index)
715                 {
716                         throw new NotSupportedException ();
717                 }
718         }
719
720         /// <summary>
721         ///   This interface is used to get all members of a class when creating the
722         ///   member cache.  It must be implemented by all DeclSpace derivatives which
723         ///   want to support the member cache and by TypeHandle to get caching of
724         ///   non-dynamic types.
725         /// </summary>
726         public interface IMemberContainer {
727                 /// <summary>
728                 ///   The name of the IMemberContainer.  This is only used for
729                 ///   debugging purposes.
730                 /// </summary>
731                 string Name {
732                         get;
733                 }
734
735                 /// <summary>
736                 ///   The type of this IMemberContainer.
737                 /// </summary>
738                 Type Type {
739                         get;
740                 }
741
742                 /// <summary>
743                 ///   Returns the IMemberContainer of the parent class or null if this
744                 ///   is an interface or TypeManger.object_type.
745                 ///   This is used when creating the member cache for a class to get all
746                 ///   members from the parent class.
747                 /// </summary>
748                 IMemberContainer Parent {
749                         get;
750                 }
751
752                 /// <summary>
753                 ///   Whether this is an interface.
754                 /// </summary>
755                 bool IsInterface {
756                         get;
757                 }
758
759                 /// <summary>
760                 ///   Returns all members of this class with the corresponding MemberTypes
761                 ///   and BindingFlags.
762                 /// </summary>
763                 /// <remarks>
764                 ///   When implementing this method, make sure not to return any inherited
765                 ///   members and check the MemberTypes and BindingFlags properly.
766                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
767                 ///   get the BindingFlags (static/non-static,public/non-public) in the
768                 ///   MemberInfo class, but the cache needs this information.  That's why
769                 ///   this method is called multiple times with different BindingFlags.
770                 /// </remarks>
771                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
772
773                 /// <summary>
774                 ///   Return the container's member cache.
775                 /// </summary>
776                 MemberCache MemberCache {
777                         get;
778                 }
779         }
780
781         /// <summary>
782         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
783         ///   member lookups.  It has a member name based hash table; it maps each member
784         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
785         ///   and the BindingFlags that were initially used to get it.  The cache contains
786         ///   all members of the current class and all inherited members.  If this cache is
787         ///   for an interface types, it also contains all inherited members.
788         ///
789         ///   There are two ways to get a MemberCache:
790         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
791         ///     use the DeclSpace.MemberCache property.
792         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
793         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
794         /// </summary>
795         public class MemberCache {
796                 public readonly IMemberContainer Container;
797                 protected Hashtable member_hash;
798                 protected Hashtable method_hash;
799
800                 /// <summary>
801                 ///   Create a new MemberCache for the given IMemberContainer `container'.
802                 /// </summary>
803                 public MemberCache (IMemberContainer container)
804                 {
805                         this.Container = container;
806
807                         Timer.IncrementCounter (CounterType.MemberCache);
808                         Timer.StartTimer (TimerType.CacheInit);
809
810                         // If we have a parent class (we have a parent class unless we're
811                         // TypeManager.object_type), we deep-copy its MemberCache here.
812                         if (Container.Parent != null)
813                                 member_hash = SetupCache (Container.Parent.MemberCache);
814                         else if (Container.IsInterface)
815                                 member_hash = SetupCacheForInterface ();
816                         else
817                                 member_hash = new Hashtable ();
818
819                         // If this is neither a dynamic type nor an interface, create a special
820                         // method cache with all declared and inherited methods.
821                         Type type = container.Type;
822                         if (!(type is TypeBuilder) && !type.IsInterface) {
823                                 method_hash = new Hashtable ();
824                                 AddMethods (type);
825                         }
826
827                         // Add all members from the current class.
828                         AddMembers (Container);
829
830                         Timer.StopTimer (TimerType.CacheInit);
831                 }
832
833                 /// <summary>
834                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
835                 /// </summary>
836                 Hashtable SetupCache (MemberCache parent)
837                 {
838                         Hashtable hash = new Hashtable ();
839
840                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
841                         while (it.MoveNext ()) {
842                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
843                         }
844
845                         return hash;
846                 }
847
848                 /// <summary>
849                 ///   Add the contents of `new_hash' to `hash'.
850                 /// </summary>
851                 void AddHashtable (Hashtable hash, Hashtable new_hash)
852                 {
853                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
854                         while (it.MoveNext ()) {
855                                 ArrayList list = (ArrayList) hash [it.Key];
856                                 if (list != null)
857                                         list.AddRange ((ArrayList) it.Value);
858                                 else
859                                         hash [it.Key] = ((ArrayList) it.Value).Clone ();
860                         }
861                 }
862
863                 /// <summary>
864                 ///   Bootstrap the member cache for an interface type.
865                 ///   Type.GetMembers() won't return any inherited members for interface types,
866                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
867                 /// </summary>
868                 Hashtable SetupCacheForInterface ()
869                 {
870                         Hashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
871                         Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
872
873                         foreach (Type iface in ifaces) {
874                                 IMemberContainer iface_container =
875                                         TypeManager.LookupMemberContainer (iface);
876
877                                 MemberCache iface_cache = iface_container.MemberCache;
878                                 AddHashtable (hash, iface_cache.member_hash);
879                         }
880
881                         return hash;
882                 }
883
884                 /// <summary>
885                 ///   Add all members from class `container' to the cache.
886                 /// </summary>
887                 void AddMembers (IMemberContainer container)
888                 {
889                         // We need to call AddMembers() with a single member type at a time
890                         // to get the member type part of CacheEntry.EntryType right.
891                         AddMembers (MemberTypes.Constructor, container);
892                         AddMembers (MemberTypes.Field, container);
893                         AddMembers (MemberTypes.Method, container);
894                         AddMembers (MemberTypes.Property, container);
895                         AddMembers (MemberTypes.Event, container);
896                         // Nested types are returned by both Static and Instance searches.
897                         AddMembers (MemberTypes.NestedType,
898                                     BindingFlags.Static | BindingFlags.Public, container);
899                         AddMembers (MemberTypes.NestedType,
900                                     BindingFlags.Static | BindingFlags.NonPublic, container);
901                 }
902
903                 void AddMembers (MemberTypes mt, IMemberContainer container)
904                 {
905                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
906                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
907                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
908                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
909                 }
910
911                 /// <summary>
912                 ///   Add all members from class `container' with the requested MemberTypes and
913                 ///   BindingFlags to the cache.  This method is called multiple times with different
914                 ///   MemberTypes and BindingFlags.
915                 /// </summary>
916                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
917                 {
918                         MemberList members = container.GetMembers (mt, bf);
919                         BindingFlags new_bf = (container == Container) ?
920                                 bf | BindingFlags.DeclaredOnly : bf;
921
922                         foreach (MemberInfo member in members) {
923                                 string name = member.Name;
924
925                                 // We use a name-based hash table of ArrayList's.
926                                 ArrayList list = (ArrayList) member_hash [name];
927                                 if (list == null) {
928                                         list = new ArrayList ();
929                                         member_hash.Add (name, list);
930                                 }
931
932                                 // When this method is called for the current class, the list will
933                                 // already contain all inherited members from our parent classes.
934                                 // We cannot add new members in front of the list since this'd be an
935                                 // expensive operation, that's why the list is sorted in reverse order
936                                 // (ie. members from the current class are coming last).
937                                 list.Add (new CacheEntry (container, member, mt, bf));
938                         }
939                 }
940
941                 /// <summary>
942                 ///   Add all declared and inherited methods from class `type' to the method cache.
943                 /// </summary>
944                 void AddMethods (Type type)
945                 {
946                         AddMethods (BindingFlags.Static | BindingFlags.Public, type);
947                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic, type);
948                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
949                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
950                 }
951
952                 void AddMethods (BindingFlags bf, Type type)
953                 {
954                         MemberInfo [] members = type.GetMethods (bf);
955
956                         foreach (MethodBase member in members) {
957                                 string name = member.Name;
958
959                                 // Varargs methods aren't allowed in C# code.
960                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
961                                         continue;
962
963                                 // We use a name-based hash table of ArrayList's.
964                                 ArrayList list = (ArrayList) method_hash [name];
965                                 if (list == null) {
966                                         list = new ArrayList ();
967                                         method_hash.Add (name, list);
968                                 }
969
970                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
971                                 // sorted so we need to do this check for every member.
972                                 BindingFlags new_bf = bf;
973                                 if (member.DeclaringType == type)
974                                         new_bf |= BindingFlags.DeclaredOnly;
975
976                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
977                         }
978                 }
979
980                 /// <summary>
981                 ///   Compute and return a appropriate `EntryType' magic number for the given
982                 ///   MemberTypes and BindingFlags.
983                 /// </summary>
984                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
985                 {
986                         EntryType type = EntryType.None;
987
988                         if ((mt & MemberTypes.Constructor) != 0)
989                                 type |= EntryType.Constructor;
990                         if ((mt & MemberTypes.Event) != 0)
991                                 type |= EntryType.Event;
992                         if ((mt & MemberTypes.Field) != 0)
993                                 type |= EntryType.Field;
994                         if ((mt & MemberTypes.Method) != 0)
995                                 type |= EntryType.Method;
996                         if ((mt & MemberTypes.Property) != 0)
997                                 type |= EntryType.Property;
998                         // Nested types are returned by static and instance searches.
999                         if ((mt & MemberTypes.NestedType) != 0)
1000                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1001
1002                         if ((bf & BindingFlags.Instance) != 0)
1003                                 type |= EntryType.Instance;
1004                         if ((bf & BindingFlags.Static) != 0)
1005                                 type |= EntryType.Static;
1006                         if ((bf & BindingFlags.Public) != 0)
1007                                 type |= EntryType.Public;
1008                         if ((bf & BindingFlags.NonPublic) != 0)
1009                                 type |= EntryType.NonPublic;
1010                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1011                                 type |= EntryType.Declared;
1012
1013                         return type;
1014                 }
1015
1016                 /// <summary>
1017                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1018                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1019                 ///   single member types.
1020                 /// </summary>
1021                 public static bool IsSingleMemberType (MemberTypes mt)
1022                 {
1023                         switch (mt) {
1024                         case MemberTypes.Constructor:
1025                         case MemberTypes.Event:
1026                         case MemberTypes.Field:
1027                         case MemberTypes.Method:
1028                         case MemberTypes.Property:
1029                         case MemberTypes.NestedType:
1030                                 return true;
1031
1032                         default:
1033                                 return false;
1034                         }
1035                 }
1036
1037                 /// <summary>
1038                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1039                 ///   number to speed up the searching process.
1040                 /// </summary>
1041                 [Flags]
1042                 protected enum EntryType {
1043                         None            = 0x000,
1044
1045                         Instance        = 0x001,
1046                         Static          = 0x002,
1047                         MaskStatic      = Instance|Static,
1048
1049                         Public          = 0x004,
1050                         NonPublic       = 0x008,
1051                         MaskProtection  = Public|NonPublic,
1052
1053                         Declared        = 0x010,
1054
1055                         Constructor     = 0x020,
1056                         Event           = 0x040,
1057                         Field           = 0x080,
1058                         Method          = 0x100,
1059                         Property        = 0x200,
1060                         NestedType      = 0x400,
1061
1062                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1063                 }
1064
1065                 protected struct CacheEntry {
1066                         public readonly IMemberContainer Container;
1067                         public readonly EntryType EntryType;
1068                         public readonly MemberInfo Member;
1069
1070                         public CacheEntry (IMemberContainer container, MemberInfo member,
1071                                            MemberTypes mt, BindingFlags bf)
1072                         {
1073                                 this.Container = container;
1074                                 this.Member = member;
1075                                 this.EntryType = GetEntryType (mt, bf);
1076                         }
1077                 }
1078
1079                 /// <summary>
1080                 ///   This is called each time we're walking up one level in the class hierarchy
1081                 ///   and checks whether we can abort the search since we've already found what
1082                 ///   we were looking for.
1083                 /// </summary>
1084                 protected bool DoneSearching (ArrayList list)
1085                 {
1086                         //
1087                         // We've found exactly one member in the current class and it's not
1088                         // a method or constructor.
1089                         //
1090                         if (list.Count == 1 && !(list [0] is MethodBase))
1091                                 return true;
1092
1093                         //
1094                         // Multiple properties: we query those just to find out the indexer
1095                         // name
1096                         //
1097                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1098                                 return true;
1099
1100                         return false;
1101                 }
1102
1103                 /// <summary>
1104                 ///   Looks up members with name `name'.  If you provide an optional
1105                 ///   filter function, it'll only be called with members matching the
1106                 ///   requested member name.
1107                 ///
1108                 ///   This method will try to use the cache to do the lookup if possible.
1109                 ///
1110                 ///   Unlike other FindMembers implementations, this method will always
1111                 ///   check all inherited members - even when called on an interface type.
1112                 ///
1113                 ///   If you know that you're only looking for methods, you should use
1114                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1115                 ///   When doing a method-only search, it'll try to use a special method
1116                 ///   cache (unless it's a dynamic type or an interface) and the returned
1117                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1118                 ///   The lookup process will automatically restart itself in method-only
1119                 ///   search mode if it discovers that it's about to return methods.
1120                 /// </summary>
1121                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1122                                                MemberFilter filter, object criteria)
1123                 {
1124                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1125                         bool method_search = mt == MemberTypes.Method;
1126                         // If we have a method cache and we aren't already doing a method-only search,
1127                         // then we restart a method search if the first match is a method.
1128                         bool do_method_search = !method_search && (method_hash != null);
1129
1130                         ArrayList applicable;
1131
1132                         // If this is a method-only search, we try to use the method cache if
1133                         // possible; a lookup in the method cache will return a MemberInfo with
1134                         // the correct ReflectedType for inherited methods.
1135                         if (method_search && (method_hash != null))
1136                                 applicable = (ArrayList) method_hash [name];
1137                         else
1138                                 applicable = (ArrayList) member_hash [name];
1139
1140                         if (applicable == null)
1141                                 return MemberList.Empty;
1142
1143                         ArrayList list = new ArrayList ();
1144
1145                         Timer.StartTimer (TimerType.CachedLookup);
1146
1147                         EntryType type = GetEntryType (mt, bf);
1148
1149                         IMemberContainer current = Container;
1150
1151                         // `applicable' is a list of all members with the given member name `name'
1152                         // in the current class and all its parent classes.  The list is sorted in
1153                         // reverse order due to the way how the cache is initialy created (to speed
1154                         // things up, we're doing a deep-copy of our parent).
1155
1156                         for (int i = applicable.Count-1; i >= 0; i--) {
1157                                 CacheEntry entry = (CacheEntry) applicable [i];
1158
1159                                 // This happens each time we're walking one level up in the class
1160                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1161                                 // the first time this happens (this may already happen in the first
1162                                 // iteration of this loop if there are no members with the name we're
1163                                 // looking for in the current class).
1164                                 if (entry.Container != current) {
1165                                         if (declared_only || DoneSearching (list))
1166                                                 break;
1167
1168                                         current = entry.Container;
1169                                 }
1170
1171                                 // Is the member of the correct type ?
1172                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1173                                         continue;
1174
1175                                 // Is the member static/non-static ?
1176                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1177                                         continue;
1178
1179                                 // Apply the filter to it.
1180                                 if (filter (entry.Member, criteria)) {
1181                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1182                                                 do_method_search = false;
1183                                         list.Add (entry.Member);
1184                                 }
1185                         }
1186
1187                         Timer.StopTimer (TimerType.CachedLookup);
1188
1189                         // If we have a method cache and we aren't already doing a method-only
1190                         // search, we restart in method-only search mode if the first match is
1191                         // a method.  This ensures that we return a MemberInfo with the correct
1192                         // ReflectedType for inherited methods.
1193                         if (do_method_search && (list.Count > 0))
1194                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1195
1196                         return new MemberList (list);
1197                 }
1198         }
1199 }