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