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