correcting a recurring typo
[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
400                         int errors = Report.Errors;
401                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
402                         if (d == null || d.eclass != ExprClass.Type){
403                                 if (!silent && errors == Report.Errors){
404                                         Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
405                                 }
406                                 return null;
407                         }
408
409                         return d.Type;
410                 }
411
412                 // <summary>
413                 //    Resolves the expression `e' for a type, and will recursively define
414                 //    types. 
415                 // </summary>
416                 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
417                 {
418                         if (type_resolve_ec == null)
419                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
420
421                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
422                         if (d == null || d.eclass != ExprClass.Type){
423                                 if (!silent){
424                                         Report.Error (246, loc, "Cannot find type '"+ e +"'");
425                                 }
426                                 return null;
427                         }
428
429                         return d;
430                 }
431                 
432                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
433                 {
434                         DeclSpace parent;
435                         Type t;
436
437                         error = false;
438                         name = MakeFQN (ns, name);
439                         
440                         t  = TypeManager.LookupType (name);
441                         if (t != null)
442                                 return t;
443
444                         parent = (DeclSpace) RootContext.Tree.Decls [name];
445                         if (parent == null)
446                                 return null;
447                                 
448                         t = parent.DefineType ();
449                         if (t == null){
450                                 Report.Error (146, Location, "Class definition is circular: `"+name+"'");
451                                 error = true;
452                                 return null;
453                         }
454                         return t;
455                 }
456
457                 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
458                 {
459                         Report.Error (104, loc,
460                                       String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
461                                                      t1.FullName, t2.FullName));
462                 }
463
464                 /// <summary>
465                 ///   GetType is used to resolve type names at the DeclSpace level.
466                 ///   Use this to lookup class/struct bases, interface bases or 
467                 ///   delegate type references
468                 /// </summary>
469                 ///
470                 /// <remarks>
471                 ///   Contrast this to LookupType which is used inside method bodies to 
472                 ///   lookup types that have already been defined.  GetType is used
473                 ///   during the tree resolution process and potentially define
474                 ///   recursively the type
475                 /// </remarks>
476                 public Type FindType (Location loc, string name)
477                 {
478                         Type t;
479                         bool error;
480
481                         //
482                         // For the case the type we are looking for is nested within this one
483                         // or is in any base class
484                         //
485                         DeclSpace containing_ds = this;
486
487                         while (containing_ds != null){
488                                 Type current_type = containing_ds.TypeBuilder;
489
490                                 while (current_type != null) {
491                                         string pre = current_type.FullName;
492                                         
493                                         t = LookupInterfaceOrClass (pre, name, out error);
494                                         if (error)
495                                                 return null;
496                                 
497                                         if (t != null) 
498                                                 return t;
499
500                                         current_type = current_type.BaseType;
501                                 }
502                                 containing_ds = containing_ds.Parent;
503                         }
504                         
505                         //
506                         // Attempt to lookup the class on our namespace and all it's implicit parents
507                         //
508                         for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
509
510                                 t = LookupInterfaceOrClass (ns, name, out error);
511                                 if (error)
512                                         return null;
513                                 
514                                 if (t != null) 
515                                         return t;
516                         }
517                         
518                         //
519                         // Attempt to do a direct unqualified lookup
520                         //
521                         t = LookupInterfaceOrClass ("", name, out error);
522                         if (error)
523                                 return null;
524                         
525                         if (t != null)
526                                 return t;
527                         
528                         //
529                         // Attempt to lookup the class on any of the `using'
530                         // namespaces
531                         //
532
533                         for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
534
535                                 t = LookupInterfaceOrClass (ns.Name, name, out error);
536                                 if (error)
537                                         return null;
538
539                                 if (t != null)
540                                         return t;
541
542                                 //
543                                 // Now check the using clause list
544                                 //
545                                 ArrayList using_list = ns.UsingTable;
546                                 
547                                 if (using_list == null)
548                                         continue;
549
550                                 Type match = null;
551                                 foreach (Namespace.UsingEntry ue in using_list){
552                                         match = LookupInterfaceOrClass (ue.Name, name, out error);
553                                         if (error)
554                                                 return null;
555
556                                         if (match != null){
557                                                 if (t != null){
558                                                         Error_AmbiguousTypeReference (loc, name, t, match);
559                                                         return null;
560                                                 }
561                                                 
562                                                 t = match;
563                                                 ue.Used = true;
564                                         }
565                                 }
566                                 if (t != null)
567                                         return t;
568                         }
569
570                         //Report.Error (246, Location, "Can not find type `"+name+"'");
571                         return null;
572                 }
573
574                 /// <remarks>
575                 ///   This function is broken and not what you're looking for.  It should only
576                 ///   be used while the type is still being created since it doesn't use the cache
577                 ///   and relies on the filter doing the member name check.
578                 /// </remarks>
579                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
580                                                         MemberFilter filter, object criteria);
581
582                 /// <remarks>
583                 ///   If we have a MemberCache, return it.  This property may return null if the
584                 ///   class doesn't have a member cache or while it's still being created.
585                 /// </remarks>
586                 public abstract MemberCache MemberCache {
587                         get;
588                 }
589         }
590
591         /// <summary>
592         ///   This is a readonly list of MemberInfo's.      
593         /// </summary>
594         public class MemberList : IList {
595                 public readonly IList List;
596                 int count;
597
598                 /// <summary>
599                 ///   Create a new MemberList from the given IList.
600                 /// </summary>
601                 public MemberList (IList list)
602                 {
603                         if (list != null)
604                                 this.List = list;
605                         else
606                                 this.List = new ArrayList ();
607                         count = List.Count;
608                 }
609
610                 /// <summary>
611                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
612                 /// </summary>
613                 public MemberList (IList first, IList second)
614                 {
615                         ArrayList list = new ArrayList ();
616                         list.AddRange (first);
617                         list.AddRange (second);
618                         count = list.Count;
619                         List = list;
620                 }
621
622                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
623
624                 /// <summary>
625                 ///   Cast the MemberList into a MemberInfo[] array.
626                 /// </summary>
627                 /// <remarks>
628                 ///   This is an expensive operation, only use it if it's really necessary.
629                 /// </remarks>
630                 public static explicit operator MemberInfo [] (MemberList list)
631                 {
632                         Timer.StartTimer (TimerType.MiscTimer);
633                         MemberInfo [] result = new MemberInfo [list.Count];
634                         list.CopyTo (result, 0);
635                         Timer.StopTimer (TimerType.MiscTimer);
636                         return result;
637                 }
638
639                 // ICollection
640
641                 public int Count {
642                         get {
643                                 return count;
644                         }
645                 }
646
647                 public bool IsSynchronized {
648                         get {
649                                 return List.IsSynchronized;
650                         }
651                 }
652
653                 public object SyncRoot {
654                         get {
655                                 return List.SyncRoot;
656                         }
657                 }
658
659                 public void CopyTo (Array array, int index)
660                 {
661                         List.CopyTo (array, index);
662                 }
663
664                 // IEnumerable
665
666                 public IEnumerator GetEnumerator ()
667                 {
668                         return List.GetEnumerator ();
669                 }
670
671                 // IList
672
673                 public bool IsFixedSize {
674                         get {
675                                 return true;
676                         }
677                 }
678
679                 public bool IsReadOnly {
680                         get {
681                                 return true;
682                         }
683                 }
684
685                 object IList.this [int index] {
686                         get {
687                                 return List [index];
688                         }
689
690                         set {
691                                 throw new NotSupportedException ();
692                         }
693                 }
694
695                 // FIXME: try to find out whether we can avoid the cast in this indexer.
696                 public MemberInfo this [int index] {
697                         get {
698                                 return (MemberInfo) List [index];
699                         }
700                 }
701
702                 public int Add (object value)
703                 {
704                         throw new NotSupportedException ();
705                 }
706
707                 public void Clear ()
708                 {
709                         throw new NotSupportedException ();
710                 }
711
712                 public bool Contains (object value)
713                 {
714                         return List.Contains (value);
715                 }
716
717                 public int IndexOf (object value)
718                 {
719                         return List.IndexOf (value);
720                 }
721
722                 public void Insert (int index, object value)
723                 {
724                         throw new NotSupportedException ();
725                 }
726
727                 public void Remove (object value)
728                 {
729                         throw new NotSupportedException ();
730                 }
731
732                 public void RemoveAt (int index)
733                 {
734                         throw new NotSupportedException ();
735                 }
736         }
737
738         /// <summary>
739         ///   This interface is used to get all members of a class when creating the
740         ///   member cache.  It must be implemented by all DeclSpace derivatives which
741         ///   want to support the member cache and by TypeHandle to get caching of
742         ///   non-dynamic types.
743         /// </summary>
744         public interface IMemberContainer {
745                 /// <summary>
746                 ///   The name of the IMemberContainer.  This is only used for
747                 ///   debugging purposes.
748                 /// </summary>
749                 string Name {
750                         get;
751                 }
752
753                 /// <summary>
754                 ///   The type of this IMemberContainer.
755                 /// </summary>
756                 Type Type {
757                         get;
758                 }
759
760                 /// <summary>
761                 ///   Returns the IMemberContainer of the parent class or null if this
762                 ///   is an interface or TypeManger.object_type.
763                 ///   This is used when creating the member cache for a class to get all
764                 ///   members from the parent class.
765                 /// </summary>
766                 IMemberContainer Parent {
767                         get;
768                 }
769
770                 /// <summary>
771                 ///   Whether this is an interface.
772                 /// </summary>
773                 bool IsInterface {
774                         get;
775                 }
776
777                 /// <summary>
778                 ///   Returns all members of this class with the corresponding MemberTypes
779                 ///   and BindingFlags.
780                 /// </summary>
781                 /// <remarks>
782                 ///   When implementing this method, make sure not to return any inherited
783                 ///   members and check the MemberTypes and BindingFlags properly.
784                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
785                 ///   get the BindingFlags (static/non-static,public/non-public) in the
786                 ///   MemberInfo class, but the cache needs this information.  That's why
787                 ///   this method is called multiple times with different BindingFlags.
788                 /// </remarks>
789                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
790
791                 /// <summary>
792                 ///   Return the container's member cache.
793                 /// </summary>
794                 MemberCache MemberCache {
795                         get;
796                 }
797         }
798
799         /// <summary>
800         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
801         ///   member lookups.  It has a member name based hash table; it maps each member
802         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
803         ///   and the BindingFlags that were initially used to get it.  The cache contains
804         ///   all members of the current class and all inherited members.  If this cache is
805         ///   for an interface types, it also contains all inherited members.
806         ///
807         ///   There are two ways to get a MemberCache:
808         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
809         ///     use the DeclSpace.MemberCache property.
810         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
811         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
812         /// </summary>
813         public class MemberCache {
814                 public readonly IMemberContainer Container;
815                 protected Hashtable member_hash;
816                 protected Hashtable method_hash;
817                 protected Hashtable interface_hash;
818
819                 /// <summary>
820                 ///   Create a new MemberCache for the given IMemberContainer `container'.
821                 /// </summary>
822                 public MemberCache (IMemberContainer container)
823                 {
824                         this.Container = container;
825
826                         Timer.IncrementCounter (CounterType.MemberCache);
827                         Timer.StartTimer (TimerType.CacheInit);
828
829                         interface_hash = new Hashtable ();
830
831                         // If we have a parent class (we have a parent class unless we're
832                         // TypeManager.object_type), we deep-copy its MemberCache here.
833                         if (Container.Parent != null)
834                                 member_hash = SetupCache (Container.Parent.MemberCache);
835                         else if (Container.IsInterface)
836                                 member_hash = SetupCacheForInterface ();
837                         else
838                                 member_hash = new Hashtable ();
839
840                         // If this is neither a dynamic type nor an interface, create a special
841                         // method cache with all declared and inherited methods.
842                         Type type = container.Type;
843                         if (!(type is TypeBuilder) && !type.IsInterface) {
844                                 method_hash = new Hashtable ();
845                                 AddMethods (type);
846                         }
847
848                         // Add all members from the current class.
849                         AddMembers (Container);
850
851                         Timer.StopTimer (TimerType.CacheInit);
852                 }
853
854                 /// <summary>
855                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
856                 /// </summary>
857                 Hashtable SetupCache (MemberCache parent)
858                 {
859                         Hashtable hash = new Hashtable ();
860
861                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
862                         while (it.MoveNext ()) {
863                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
864                         }
865
866                         return hash;
867                 }
868
869                 void AddInterfaces (MemberCache parent)
870                 {
871                         foreach (Type iface in parent.interface_hash.Keys) {
872                                 if (!interface_hash.Contains (iface))
873                                         interface_hash.Add (iface, true);
874                         }
875                 }
876
877                 /// <summary>
878                 ///   Add the contents of `new_hash' to `hash'.
879                 /// </summary>
880                 void AddHashtable (Hashtable hash, Hashtable new_hash)
881                 {
882                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
883                         while (it.MoveNext ()) {
884                                 ArrayList list = (ArrayList) hash [it.Key];
885                                 if (list != null)
886                                         list.AddRange ((ArrayList) it.Value);
887                                 else
888                                         hash [it.Key] = ((ArrayList) it.Value).Clone ();
889                         }
890                 }
891
892                 /// <summary>
893                 ///   Bootstrap the member cache for an interface type.
894                 ///   Type.GetMembers() won't return any inherited members for interface types,
895                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
896                 /// </summary>
897                 Hashtable SetupCacheForInterface ()
898                 {
899                         Hashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
900                         Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
901
902                         foreach (Type iface in ifaces) {
903                                 if (interface_hash.Contains (iface))
904                                         continue;
905                                 interface_hash.Add (iface, true);
906
907                                 IMemberContainer iface_container =
908                                         TypeManager.LookupMemberContainer (iface);
909
910                                 MemberCache iface_cache = iface_container.MemberCache;
911                                 AddHashtable (hash, iface_cache.member_hash);
912                                 AddInterfaces (iface_cache);
913                         }
914
915                         return hash;
916                 }
917
918                 /// <summary>
919                 ///   Add all members from class `container' to the cache.
920                 /// </summary>
921                 void AddMembers (IMemberContainer container)
922                 {
923                         // We need to call AddMembers() with a single member type at a time
924                         // to get the member type part of CacheEntry.EntryType right.
925                         AddMembers (MemberTypes.Constructor, container);
926                         AddMembers (MemberTypes.Field, container);
927                         AddMembers (MemberTypes.Method, container);
928                         AddMembers (MemberTypes.Property, container);
929                         AddMembers (MemberTypes.Event, container);
930                         // Nested types are returned by both Static and Instance searches.
931                         AddMembers (MemberTypes.NestedType,
932                                     BindingFlags.Static | BindingFlags.Public, container);
933                         AddMembers (MemberTypes.NestedType,
934                                     BindingFlags.Static | BindingFlags.NonPublic, container);
935                 }
936
937                 void AddMembers (MemberTypes mt, IMemberContainer container)
938                 {
939                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
940                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
941                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
942                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
943                 }
944
945                 /// <summary>
946                 ///   Add all members from class `container' with the requested MemberTypes and
947                 ///   BindingFlags to the cache.  This method is called multiple times with different
948                 ///   MemberTypes and BindingFlags.
949                 /// </summary>
950                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
951                 {
952                         MemberList members = container.GetMembers (mt, bf);
953                         BindingFlags new_bf = (container == Container) ?
954                                 bf | BindingFlags.DeclaredOnly : bf;
955
956                         foreach (MemberInfo member in members) {
957                                 string name = member.Name;
958
959                                 // We use a name-based hash table of ArrayList's.
960                                 ArrayList list = (ArrayList) member_hash [name];
961                                 if (list == null) {
962                                         list = new ArrayList ();
963                                         member_hash.Add (name, list);
964                                 }
965
966                                 // When this method is called for the current class, the list will
967                                 // already contain all inherited members from our parent classes.
968                                 // We cannot add new members in front of the list since this'd be an
969                                 // expensive operation, that's why the list is sorted in reverse order
970                                 // (ie. members from the current class are coming last).
971                                 list.Add (new CacheEntry (container, member, mt, bf));
972                         }
973                 }
974
975                 /// <summary>
976                 ///   Add all declared and inherited methods from class `type' to the method cache.
977                 /// </summary>
978                 void AddMethods (Type type)
979                 {
980                         AddMethods (BindingFlags.Static | BindingFlags.Public, type);
981                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic, type);
982                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
983                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
984                 }
985
986                 void AddMethods (BindingFlags bf, Type type)
987                 {
988                         MemberInfo [] members = type.GetMethods (bf);
989
990                         foreach (MethodBase member in members) {
991                                 string name = member.Name;
992
993                                 // Varargs methods aren't allowed in C# code.
994                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
995                                         continue;
996
997                                 // We use a name-based hash table of ArrayList's.
998                                 ArrayList list = (ArrayList) method_hash [name];
999                                 if (list == null) {
1000                                         list = new ArrayList ();
1001                                         method_hash.Add (name, list);
1002                                 }
1003
1004                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1005                                 // sorted so we need to do this check for every member.
1006                                 BindingFlags new_bf = bf;
1007                                 if (member.DeclaringType == type)
1008                                         new_bf |= BindingFlags.DeclaredOnly;
1009
1010                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1011                         }
1012                 }
1013
1014                 /// <summary>
1015                 ///   Compute and return a appropriate `EntryType' magic number for the given
1016                 ///   MemberTypes and BindingFlags.
1017                 /// </summary>
1018                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1019                 {
1020                         EntryType type = EntryType.None;
1021
1022                         if ((mt & MemberTypes.Constructor) != 0)
1023                                 type |= EntryType.Constructor;
1024                         if ((mt & MemberTypes.Event) != 0)
1025                                 type |= EntryType.Event;
1026                         if ((mt & MemberTypes.Field) != 0)
1027                                 type |= EntryType.Field;
1028                         if ((mt & MemberTypes.Method) != 0)
1029                                 type |= EntryType.Method;
1030                         if ((mt & MemberTypes.Property) != 0)
1031                                 type |= EntryType.Property;
1032                         // Nested types are returned by static and instance searches.
1033                         if ((mt & MemberTypes.NestedType) != 0)
1034                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1035
1036                         if ((bf & BindingFlags.Instance) != 0)
1037                                 type |= EntryType.Instance;
1038                         if ((bf & BindingFlags.Static) != 0)
1039                                 type |= EntryType.Static;
1040                         if ((bf & BindingFlags.Public) != 0)
1041                                 type |= EntryType.Public;
1042                         if ((bf & BindingFlags.NonPublic) != 0)
1043                                 type |= EntryType.NonPublic;
1044                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1045                                 type |= EntryType.Declared;
1046
1047                         return type;
1048                 }
1049
1050                 /// <summary>
1051                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1052                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1053                 ///   single member types.
1054                 /// </summary>
1055                 public static bool IsSingleMemberType (MemberTypes mt)
1056                 {
1057                         switch (mt) {
1058                         case MemberTypes.Constructor:
1059                         case MemberTypes.Event:
1060                         case MemberTypes.Field:
1061                         case MemberTypes.Method:
1062                         case MemberTypes.Property:
1063                         case MemberTypes.NestedType:
1064                                 return true;
1065
1066                         default:
1067                                 return false;
1068                         }
1069                 }
1070
1071                 /// <summary>
1072                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1073                 ///   number to speed up the searching process.
1074                 /// </summary>
1075                 [Flags]
1076                 protected enum EntryType {
1077                         None            = 0x000,
1078
1079                         Instance        = 0x001,
1080                         Static          = 0x002,
1081                         MaskStatic      = Instance|Static,
1082
1083                         Public          = 0x004,
1084                         NonPublic       = 0x008,
1085                         MaskProtection  = Public|NonPublic,
1086
1087                         Declared        = 0x010,
1088
1089                         Constructor     = 0x020,
1090                         Event           = 0x040,
1091                         Field           = 0x080,
1092                         Method          = 0x100,
1093                         Property        = 0x200,
1094                         NestedType      = 0x400,
1095
1096                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1097                 }
1098
1099                 protected struct CacheEntry {
1100                         public readonly IMemberContainer Container;
1101                         public readonly EntryType EntryType;
1102                         public readonly MemberInfo Member;
1103
1104                         public CacheEntry (IMemberContainer container, MemberInfo member,
1105                                            MemberTypes mt, BindingFlags bf)
1106                         {
1107                                 this.Container = container;
1108                                 this.Member = member;
1109                                 this.EntryType = GetEntryType (mt, bf);
1110                         }
1111                 }
1112
1113                 /// <summary>
1114                 ///   This is called each time we're walking up one level in the class hierarchy
1115                 ///   and checks whether we can abort the search since we've already found what
1116                 ///   we were looking for.
1117                 /// </summary>
1118                 protected bool DoneSearching (ArrayList list)
1119                 {
1120                         //
1121                         // We've found exactly one member in the current class and it's not
1122                         // a method or constructor.
1123                         //
1124                         if (list.Count == 1 && !(list [0] is MethodBase))
1125                                 return true;
1126
1127                         //
1128                         // Multiple properties: we query those just to find out the indexer
1129                         // name
1130                         //
1131                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1132                                 return true;
1133
1134                         return false;
1135                 }
1136
1137                 /// <summary>
1138                 ///   Looks up members with name `name'.  If you provide an optional
1139                 ///   filter function, it'll only be called with members matching the
1140                 ///   requested member name.
1141                 ///
1142                 ///   This method will try to use the cache to do the lookup if possible.
1143                 ///
1144                 ///   Unlike other FindMembers implementations, this method will always
1145                 ///   check all inherited members - even when called on an interface type.
1146                 ///
1147                 ///   If you know that you're only looking for methods, you should use
1148                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1149                 ///   When doing a method-only search, it'll try to use a special method
1150                 ///   cache (unless it's a dynamic type or an interface) and the returned
1151                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1152                 ///   The lookup process will automatically restart itself in method-only
1153                 ///   search mode if it discovers that it's about to return methods.
1154                 /// </summary>
1155                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1156                                                MemberFilter filter, object criteria)
1157                 {
1158                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1159                         bool method_search = mt == MemberTypes.Method;
1160                         // If we have a method cache and we aren't already doing a method-only search,
1161                         // then we restart a method search if the first match is a method.
1162                         bool do_method_search = !method_search && (method_hash != null);
1163
1164                         ArrayList applicable;
1165
1166                         // If this is a method-only search, we try to use the method cache if
1167                         // possible; a lookup in the method cache will return a MemberInfo with
1168                         // the correct ReflectedType for inherited methods.
1169                         if (method_search && (method_hash != null))
1170                                 applicable = (ArrayList) method_hash [name];
1171                         else
1172                                 applicable = (ArrayList) member_hash [name];
1173
1174                         if (applicable == null)
1175                                 return MemberList.Empty;
1176
1177                         ArrayList list = new ArrayList ();
1178
1179                         Timer.StartTimer (TimerType.CachedLookup);
1180
1181                         EntryType type = GetEntryType (mt, bf);
1182
1183                         IMemberContainer current = Container;
1184
1185                         // `applicable' is a list of all members with the given member name `name'
1186                         // in the current class and all its parent classes.  The list is sorted in
1187                         // reverse order due to the way how the cache is initialy created (to speed
1188                         // things up, we're doing a deep-copy of our parent).
1189
1190                         for (int i = applicable.Count-1; i >= 0; i--) {
1191                                 CacheEntry entry = (CacheEntry) applicable [i];
1192
1193                                 // This happens each time we're walking one level up in the class
1194                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1195                                 // the first time this happens (this may already happen in the first
1196                                 // iteration of this loop if there are no members with the name we're
1197                                 // looking for in the current class).
1198                                 if (entry.Container != current) {
1199                                         if (declared_only || DoneSearching (list))
1200                                                 break;
1201
1202                                         current = entry.Container;
1203                                 }
1204
1205                                 // Is the member of the correct type ?
1206                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1207                                         continue;
1208
1209                                 // Is the member static/non-static ?
1210                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1211                                         continue;
1212
1213                                 // Apply the filter to it.
1214                                 if (filter (entry.Member, criteria)) {
1215                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1216                                                 do_method_search = false;
1217                                         list.Add (entry.Member);
1218                                 }
1219                         }
1220
1221                         Timer.StopTimer (TimerType.CachedLookup);
1222
1223                         // If we have a method cache and we aren't already doing a method-only
1224                         // search, we restart in method-only search mode if the first match is
1225                         // a method.  This ensures that we return a MemberInfo with the correct
1226                         // ReflectedType for inherited methods.
1227                         if (do_method_search && (list.Count > 0))
1228                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1229
1230                         return new MemberList (list);
1231                 }
1232         }
1233 }