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