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