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