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