2003-03-26 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                         type_resolve_ec.ContainerType = TypeBuilder;
458
459                         int errors = Report.Errors;
460                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
461                         
462                         if (d == null || d.eclass != ExprClass.Type){
463                                 if (!silent && errors == Report.Errors){
464                                         Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
465                                 }
466                                 return null;
467                         }
468
469                         if (!CheckAccessLevel (d.Type)) {
470                                 Report. Error (122, "`" + d.Type + "' " +
471                                        "is inaccessible because of its protection level");
472                                 return null;
473                         }
474
475                         return d.Type;
476                 }
477
478                 // <summary>
479                 //    Resolves the expression `e' for a type, and will recursively define
480                 //    types. 
481                 // </summary>
482                 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
483                 {
484                         if (type_resolve_ec == null)
485                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
486
487                         Expression d = e.Resolve (type_resolve_ec, ResolveFlags.Type);
488                          
489                         if (d == null || d.eclass != ExprClass.Type){
490                                 if (!silent){
491                                         Report.Error (246, loc, "Cannot find type `"+ e +"'");
492                                 }
493                                 return null;
494                         }
495
496                         return d;
497                 }
498                 
499                 bool CheckAccessLevel (Type check_type) 
500                 {
501                         if (check_type.IsPublic || check_type.IsNestedPublic)
502                                 return true;
503                         
504                         if (check_type.Assembly == TypeBuilder.Assembly)
505                                 return true;
506
507                         return false;
508
509                 }
510
511
512                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
513                 {
514                         DeclSpace parent;
515                         Type t;
516
517                         error = false;
518                         name = MakeFQN (ns, name);
519                         
520                         t  = TypeManager.LookupType (name);
521                         if (t != null)
522                                 return t;
523
524                         parent = (DeclSpace) RootContext.Tree.Decls [name];
525                         if (parent == null)
526                                 return null;
527                         
528                         t = parent.DefineType ();
529                         if (t == null){
530                                 Report.Error (146, Location, "Class definition is circular: `"+name+"'");
531                                 error = true;
532                                 return null;
533                         }
534                         return t;
535                 }
536
537                 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
538                 {
539                         Report.Error (104, loc,
540                                       String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
541                                                      t1.FullName, t2.FullName));
542                 }
543
544                 /// <summary>
545                 ///   GetType is used to resolve type names at the DeclSpace level.
546                 ///   Use this to lookup class/struct bases, interface bases or 
547                 ///   delegate type references
548                 /// </summary>
549                 ///
550                 /// <remarks>
551                 ///   Contrast this to LookupType which is used inside method bodies to 
552                 ///   lookup types that have already been defined.  GetType is used
553                 ///   during the tree resolution process and potentially define
554                 ///   recursively the type
555                 /// </remarks>
556                 public Type FindType (Location loc, string name)
557                 {
558                         Type t;
559                         bool error;
560
561                         //
562                         // For the case the type we are looking for is nested within this one
563                         // or is in any base class
564                         //
565                         DeclSpace containing_ds = this;
566
567                         while (containing_ds != null){
568                                 Type current_type = containing_ds.TypeBuilder;
569
570                                 while (current_type != null) {
571                                         string pre = current_type.FullName;
572
573                                         t = LookupInterfaceOrClass (pre, name, out error);
574                                         if (error)
575                                                 return null;
576                                 
577                                         if (t != null) 
578                                                 return t;
579
580                                         current_type = current_type.BaseType;
581                                 }
582                                 containing_ds = containing_ds.Parent;
583                         }
584                         
585                         //
586                         // Attempt to lookup the class on our namespace and all it's implicit parents
587                         //
588                         for (string ns = Namespace.Name; ns != null; ns = RootContext.ImplicitParent (ns)) {
589
590                                 t = LookupInterfaceOrClass (ns, name, out error);
591                                 if (error)
592                                         return null;
593                                 
594                                 if (t != null) 
595                                         return t;
596                         }
597                         
598                         //
599                         // Attempt to do a direct unqualified lookup
600                         //
601                         t = LookupInterfaceOrClass ("", name, out error);
602                         if (error)
603                                 return null;
604                         
605                         if (t != null)
606                                 return t;
607                         
608                         //
609                         // Attempt to lookup the class on any of the `using'
610                         // namespaces
611                         //
612
613                         for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
614
615                                 t = LookupInterfaceOrClass (ns.Name, name, out error);
616                                 if (error)
617                                         return null;
618
619                                 if (t != null)
620                                         return t;
621
622                                 //
623                                 // Now check the using clause list
624                                 //
625                                 ArrayList using_list = ns.UsingTable;
626                                 
627                                 if (using_list == null)
628                                         continue;
629
630                                 Type match = null;
631                                 foreach (Namespace.UsingEntry ue in using_list){
632                                         match = LookupInterfaceOrClass (ue.Name, name, out error);
633                                         if (error)
634                                                 return null;
635
636                                         if (match != null){
637                                                 if (t != null){
638                                                         Error_AmbiguousTypeReference (loc, name, t, match);
639                                                         return null;
640                                                 }
641                                                 
642                                                 t = match;
643                                                 ue.Used = true;
644                                         }
645                                 }
646                                 if (t != null)
647                                         return t;
648                         }
649
650                         //Report.Error (246, Location, "Can not find type `"+name+"'");
651                         return null;
652                 }
653
654                 /// <remarks>
655                 ///   This function is broken and not what you're looking for.  It should only
656                 ///   be used while the type is still being created since it doesn't use the cache
657                 ///   and relies on the filter doing the member name check.
658                 /// </remarks>
659                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
660                                                         MemberFilter filter, object criteria);
661
662                 /// <remarks>
663                 ///   If we have a MemberCache, return it.  This property may return null if the
664                 ///   class doesn't have a member cache or while it's still being created.
665                 /// </remarks>
666                 public abstract MemberCache MemberCache {
667                         get;
668                 }
669         }
670
671         /// <summary>
672         ///   This is a readonly list of MemberInfo's.      
673         /// </summary>
674         public class MemberList : IList {
675                 public readonly IList List;
676                 int count;
677
678                 /// <summary>
679                 ///   Create a new MemberList from the given IList.
680                 /// </summary>
681                 public MemberList (IList list)
682                 {
683                         if (list != null)
684                                 this.List = list;
685                         else
686                                 this.List = new ArrayList ();
687                         count = List.Count;
688                 }
689
690                 /// <summary>
691                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
692                 /// </summary>
693                 public MemberList (IList first, IList second)
694                 {
695                         ArrayList list = new ArrayList ();
696                         list.AddRange (first);
697                         list.AddRange (second);
698                         count = list.Count;
699                         List = list;
700                 }
701
702                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
703
704                 /// <summary>
705                 ///   Cast the MemberList into a MemberInfo[] array.
706                 /// </summary>
707                 /// <remarks>
708                 ///   This is an expensive operation, only use it if it's really necessary.
709                 /// </remarks>
710                 public static explicit operator MemberInfo [] (MemberList list)
711                 {
712                         Timer.StartTimer (TimerType.MiscTimer);
713                         MemberInfo [] result = new MemberInfo [list.Count];
714                         list.CopyTo (result, 0);
715                         Timer.StopTimer (TimerType.MiscTimer);
716                         return result;
717                 }
718
719                 // ICollection
720
721                 public int Count {
722                         get {
723                                 return count;
724                         }
725                 }
726
727                 public bool IsSynchronized {
728                         get {
729                                 return List.IsSynchronized;
730                         }
731                 }
732
733                 public object SyncRoot {
734                         get {
735                                 return List.SyncRoot;
736                         }
737                 }
738
739                 public void CopyTo (Array array, int index)
740                 {
741                         List.CopyTo (array, index);
742                 }
743
744                 // IEnumerable
745
746                 public IEnumerator GetEnumerator ()
747                 {
748                         return List.GetEnumerator ();
749                 }
750
751                 // IList
752
753                 public bool IsFixedSize {
754                         get {
755                                 return true;
756                         }
757                 }
758
759                 public bool IsReadOnly {
760                         get {
761                                 return true;
762                         }
763                 }
764
765                 object IList.this [int index] {
766                         get {
767                                 return List [index];
768                         }
769
770                         set {
771                                 throw new NotSupportedException ();
772                         }
773                 }
774
775                 // FIXME: try to find out whether we can avoid the cast in this indexer.
776                 public MemberInfo this [int index] {
777                         get {
778                                 return (MemberInfo) List [index];
779                         }
780                 }
781
782                 public int Add (object value)
783                 {
784                         throw new NotSupportedException ();
785                 }
786
787                 public void Clear ()
788                 {
789                         throw new NotSupportedException ();
790                 }
791
792                 public bool Contains (object value)
793                 {
794                         return List.Contains (value);
795                 }
796
797                 public int IndexOf (object value)
798                 {
799                         return List.IndexOf (value);
800                 }
801
802                 public void Insert (int index, object value)
803                 {
804                         throw new NotSupportedException ();
805                 }
806
807                 public void Remove (object value)
808                 {
809                         throw new NotSupportedException ();
810                 }
811
812                 public void RemoveAt (int index)
813                 {
814                         throw new NotSupportedException ();
815                 }
816         }
817
818         /// <summary>
819         ///   This interface is used to get all members of a class when creating the
820         ///   member cache.  It must be implemented by all DeclSpace derivatives which
821         ///   want to support the member cache and by TypeHandle to get caching of
822         ///   non-dynamic types.
823         /// </summary>
824         public interface IMemberContainer {
825                 /// <summary>
826                 ///   The name of the IMemberContainer.  This is only used for
827                 ///   debugging purposes.
828                 /// </summary>
829                 string Name {
830                         get;
831                 }
832
833                 /// <summary>
834                 ///   The type of this IMemberContainer.
835                 /// </summary>
836                 Type Type {
837                         get;
838                 }
839
840                 /// <summary>
841                 ///   Returns the IMemberContainer of the parent class or null if this
842                 ///   is an interface or TypeManger.object_type.
843                 ///   This is used when creating the member cache for a class to get all
844                 ///   members from the parent class.
845                 /// </summary>
846                 IMemberContainer Parent {
847                         get;
848                 }
849
850                 /// <summary>
851                 ///   Whether this is an interface.
852                 /// </summary>
853                 bool IsInterface {
854                         get;
855                 }
856
857                 /// <summary>
858                 ///   Returns all members of this class with the corresponding MemberTypes
859                 ///   and BindingFlags.
860                 /// </summary>
861                 /// <remarks>
862                 ///   When implementing this method, make sure not to return any inherited
863                 ///   members and check the MemberTypes and BindingFlags properly.
864                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
865                 ///   get the BindingFlags (static/non-static,public/non-public) in the
866                 ///   MemberInfo class, but the cache needs this information.  That's why
867                 ///   this method is called multiple times with different BindingFlags.
868                 /// </remarks>
869                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
870
871                 /// <summary>
872                 ///   Return the container's member cache.
873                 /// </summary>
874                 MemberCache MemberCache {
875                         get;
876                 }
877         }
878
879         /// <summary>
880         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
881         ///   member lookups.  It has a member name based hash table; it maps each member
882         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
883         ///   and the BindingFlags that were initially used to get it.  The cache contains
884         ///   all members of the current class and all inherited members.  If this cache is
885         ///   for an interface types, it also contains all inherited members.
886         ///
887         ///   There are two ways to get a MemberCache:
888         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
889         ///     use the DeclSpace.MemberCache property.
890         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
891         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
892         /// </summary>
893         public class MemberCache {
894                 public readonly IMemberContainer Container;
895                 protected Hashtable member_hash;
896                 protected Hashtable method_hash;
897                 protected Hashtable interface_hash;
898
899                 /// <summary>
900                 ///   Create a new MemberCache for the given IMemberContainer `container'.
901                 /// </summary>
902                 public MemberCache (IMemberContainer container)
903                 {
904                         this.Container = container;
905
906                         Timer.IncrementCounter (CounterType.MemberCache);
907                         Timer.StartTimer (TimerType.CacheInit);
908
909                         interface_hash = new Hashtable ();
910
911                         // If we have a parent class (we have a parent class unless we're
912                         // TypeManager.object_type), we deep-copy its MemberCache here.
913                         if (Container.Parent != null)
914                                 member_hash = SetupCache (Container.Parent.MemberCache);
915                         else if (Container.IsInterface)
916                                 member_hash = SetupCacheForInterface ();
917                         else
918                                 member_hash = new Hashtable ();
919
920                         // If this is neither a dynamic type nor an interface, create a special
921                         // method cache with all declared and inherited methods.
922                         Type type = container.Type;
923                         if (!(type is TypeBuilder) && !type.IsInterface) {
924                                 method_hash = new Hashtable ();
925                                 AddMethods (type);
926                         }
927
928                         // Add all members from the current class.
929                         AddMembers (Container);
930
931                         Timer.StopTimer (TimerType.CacheInit);
932                 }
933
934                 /// <summary>
935                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
936                 /// </summary>
937                 Hashtable SetupCache (MemberCache parent)
938                 {
939                         Hashtable hash = new Hashtable ();
940
941                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
942                         while (it.MoveNext ()) {
943                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
944                         }
945
946                         return hash;
947                 }
948
949                 void AddInterfaces (MemberCache parent)
950                 {
951                         foreach (Type iface in parent.interface_hash.Keys) {
952                                 if (!interface_hash.Contains (iface))
953                                         interface_hash.Add (iface, true);
954                         }
955                 }
956
957                 /// <summary>
958                 ///   Add the contents of `new_hash' to `hash'.
959                 /// </summary>
960                 void AddHashtable (Hashtable hash, Hashtable new_hash)
961                 {
962                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
963                         while (it.MoveNext ()) {
964                                 ArrayList list = (ArrayList) hash [it.Key];
965                                 if (list != null)
966                                         list.AddRange ((ArrayList) it.Value);
967                                 else
968                                         hash [it.Key] = ((ArrayList) it.Value).Clone ();
969                         }
970                 }
971
972                 /// <summary>
973                 ///   Bootstrap the member cache for an interface type.
974                 ///   Type.GetMembers() won't return any inherited members for interface types,
975                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
976                 /// </summary>
977                 Hashtable SetupCacheForInterface ()
978                 {
979                         Hashtable hash = SetupCache (TypeHandle.ObjectType.MemberCache);
980                         Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
981
982                         foreach (Type iface in ifaces) {
983                                 if (interface_hash.Contains (iface))
984                                         continue;
985                                 interface_hash.Add (iface, true);
986
987                                 IMemberContainer iface_container =
988                                         TypeManager.LookupMemberContainer (iface);
989
990                                 MemberCache iface_cache = iface_container.MemberCache;
991                                 AddHashtable (hash, iface_cache.member_hash);
992                                 AddInterfaces (iface_cache);
993                         }
994
995                         return hash;
996                 }
997
998                 /// <summary>
999                 ///   Add all members from class `container' to the cache.
1000                 /// </summary>
1001                 void AddMembers (IMemberContainer container)
1002                 {
1003                         // We need to call AddMembers() with a single member type at a time
1004                         // to get the member type part of CacheEntry.EntryType right.
1005                         AddMembers (MemberTypes.Constructor, container);
1006                         AddMembers (MemberTypes.Field, container);
1007                         AddMembers (MemberTypes.Method, container);
1008                         AddMembers (MemberTypes.Property, container);
1009                         AddMembers (MemberTypes.Event, container);
1010                         // Nested types are returned by both Static and Instance searches.
1011                         AddMembers (MemberTypes.NestedType,
1012                                     BindingFlags.Static | BindingFlags.Public, container);
1013                         AddMembers (MemberTypes.NestedType,
1014                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1015                 }
1016
1017                 void AddMembers (MemberTypes mt, IMemberContainer container)
1018                 {
1019                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1020                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1021                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1022                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1023                 }
1024
1025                 /// <summary>
1026                 ///   Add all members from class `container' with the requested MemberTypes and
1027                 ///   BindingFlags to the cache.  This method is called multiple times with different
1028                 ///   MemberTypes and BindingFlags.
1029                 /// </summary>
1030                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1031                 {
1032                         MemberList members = container.GetMembers (mt, bf);
1033                         BindingFlags new_bf = (container == Container) ?
1034                                 bf | BindingFlags.DeclaredOnly : bf;
1035
1036                         foreach (MemberInfo member in members) {
1037                                 string name = member.Name;
1038
1039                                 // We use a name-based hash table of ArrayList's.
1040                                 ArrayList list = (ArrayList) member_hash [name];
1041                                 if (list == null) {
1042                                         list = new ArrayList ();
1043                                         member_hash.Add (name, list);
1044                                 }
1045
1046                                 // When this method is called for the current class, the list will
1047                                 // already contain all inherited members from our parent classes.
1048                                 // We cannot add new members in front of the list since this'd be an
1049                                 // expensive operation, that's why the list is sorted in reverse order
1050                                 // (ie. members from the current class are coming last).
1051                                 list.Add (new CacheEntry (container, member, mt, bf));
1052                         }
1053                 }
1054
1055                 /// <summary>
1056                 ///   Add all declared and inherited methods from class `type' to the method cache.
1057                 /// </summary>
1058                 void AddMethods (Type type)
1059                 {
1060                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1061                                     BindingFlags.FlattenHierarchy, type);
1062                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1063                                     BindingFlags.FlattenHierarchy, type);
1064                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1065                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1066                 }
1067
1068                 void AddMethods (BindingFlags bf, Type type)
1069                 {
1070                         MemberInfo [] members = type.GetMethods (bf);
1071
1072                         foreach (MethodBase member in members) {
1073                                 string name = member.Name;
1074
1075                                 // Varargs methods aren't allowed in C# code.
1076                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1077                                         continue;
1078
1079                                 // We use a name-based hash table of ArrayList's.
1080                                 ArrayList list = (ArrayList) method_hash [name];
1081                                 if (list == null) {
1082                                         list = new ArrayList ();
1083                                         method_hash.Add (name, list);
1084                                 }
1085
1086                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1087                                 // sorted so we need to do this check for every member.
1088                                 BindingFlags new_bf = bf;
1089                                 if (member.DeclaringType == type)
1090                                         new_bf |= BindingFlags.DeclaredOnly;
1091
1092                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1093                         }
1094                 }
1095
1096                 /// <summary>
1097                 ///   Compute and return a appropriate `EntryType' magic number for the given
1098                 ///   MemberTypes and BindingFlags.
1099                 /// </summary>
1100                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1101                 {
1102                         EntryType type = EntryType.None;
1103
1104                         if ((mt & MemberTypes.Constructor) != 0)
1105                                 type |= EntryType.Constructor;
1106                         if ((mt & MemberTypes.Event) != 0)
1107                                 type |= EntryType.Event;
1108                         if ((mt & MemberTypes.Field) != 0)
1109                                 type |= EntryType.Field;
1110                         if ((mt & MemberTypes.Method) != 0)
1111                                 type |= EntryType.Method;
1112                         if ((mt & MemberTypes.Property) != 0)
1113                                 type |= EntryType.Property;
1114                         // Nested types are returned by static and instance searches.
1115                         if ((mt & MemberTypes.NestedType) != 0)
1116                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1117
1118                         if ((bf & BindingFlags.Instance) != 0)
1119                                 type |= EntryType.Instance;
1120                         if ((bf & BindingFlags.Static) != 0)
1121                                 type |= EntryType.Static;
1122                         if ((bf & BindingFlags.Public) != 0)
1123                                 type |= EntryType.Public;
1124                         if ((bf & BindingFlags.NonPublic) != 0)
1125                                 type |= EntryType.NonPublic;
1126                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1127                                 type |= EntryType.Declared;
1128
1129                         return type;
1130                 }
1131
1132                 /// <summary>
1133                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1134                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1135                 ///   single member types.
1136                 /// </summary>
1137                 public static bool IsSingleMemberType (MemberTypes mt)
1138                 {
1139                         switch (mt) {
1140                         case MemberTypes.Constructor:
1141                         case MemberTypes.Event:
1142                         case MemberTypes.Field:
1143                         case MemberTypes.Method:
1144                         case MemberTypes.Property:
1145                         case MemberTypes.NestedType:
1146                                 return true;
1147
1148                         default:
1149                                 return false;
1150                         }
1151                 }
1152
1153                 /// <summary>
1154                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1155                 ///   number to speed up the searching process.
1156                 /// </summary>
1157                 [Flags]
1158                 protected enum EntryType {
1159                         None            = 0x000,
1160
1161                         Instance        = 0x001,
1162                         Static          = 0x002,
1163                         MaskStatic      = Instance|Static,
1164
1165                         Public          = 0x004,
1166                         NonPublic       = 0x008,
1167                         MaskProtection  = Public|NonPublic,
1168
1169                         Declared        = 0x010,
1170
1171                         Constructor     = 0x020,
1172                         Event           = 0x040,
1173                         Field           = 0x080,
1174                         Method          = 0x100,
1175                         Property        = 0x200,
1176                         NestedType      = 0x400,
1177
1178                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1179                 }
1180
1181                 protected struct CacheEntry {
1182                         public readonly IMemberContainer Container;
1183                         public readonly EntryType EntryType;
1184                         public readonly MemberInfo Member;
1185
1186                         public CacheEntry (IMemberContainer container, MemberInfo member,
1187                                            MemberTypes mt, BindingFlags bf)
1188                         {
1189                                 this.Container = container;
1190                                 this.Member = member;
1191                                 this.EntryType = GetEntryType (mt, bf);
1192                         }
1193                 }
1194
1195                 /// <summary>
1196                 ///   This is called each time we're walking up one level in the class hierarchy
1197                 ///   and checks whether we can abort the search since we've already found what
1198                 ///   we were looking for.
1199                 /// </summary>
1200                 protected bool DoneSearching (ArrayList list)
1201                 {
1202                         //
1203                         // We've found exactly one member in the current class and it's not
1204                         // a method or constructor.
1205                         //
1206                         if (list.Count == 1 && !(list [0] is MethodBase))
1207                                 return true;
1208
1209                         //
1210                         // Multiple properties: we query those just to find out the indexer
1211                         // name
1212                         //
1213                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1214                                 return true;
1215
1216                         return false;
1217                 }
1218
1219                 /// <summary>
1220                 ///   Looks up members with name `name'.  If you provide an optional
1221                 ///   filter function, it'll only be called with members matching the
1222                 ///   requested member name.
1223                 ///
1224                 ///   This method will try to use the cache to do the lookup if possible.
1225                 ///
1226                 ///   Unlike other FindMembers implementations, this method will always
1227                 ///   check all inherited members - even when called on an interface type.
1228                 ///
1229                 ///   If you know that you're only looking for methods, you should use
1230                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1231                 ///   When doing a method-only search, it'll try to use a special method
1232                 ///   cache (unless it's a dynamic type or an interface) and the returned
1233                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1234                 ///   The lookup process will automatically restart itself in method-only
1235                 ///   search mode if it discovers that it's about to return methods.
1236                 /// </summary>
1237                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1238                                                MemberFilter filter, object criteria)
1239                 {
1240                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1241                         bool method_search = mt == MemberTypes.Method;
1242                         // If we have a method cache and we aren't already doing a method-only search,
1243                         // then we restart a method search if the first match is a method.
1244                         bool do_method_search = !method_search && (method_hash != null);
1245
1246                         ArrayList applicable;
1247
1248                         // If this is a method-only search, we try to use the method cache if
1249                         // possible; a lookup in the method cache will return a MemberInfo with
1250                         // the correct ReflectedType for inherited methods.
1251                         if (method_search && (method_hash != null))
1252                                 applicable = (ArrayList) method_hash [name];
1253                         else
1254                                 applicable = (ArrayList) member_hash [name];
1255                         
1256                         if (applicable == null)
1257                                 return MemberList.Empty;
1258
1259                         ArrayList list = new ArrayList ();
1260
1261                         Timer.StartTimer (TimerType.CachedLookup);
1262
1263                         EntryType type = GetEntryType (mt, bf);
1264
1265                         IMemberContainer current = Container;
1266
1267                         // `applicable' is a list of all members with the given member name `name'
1268                         // in the current class and all its parent classes.  The list is sorted in
1269                         // reverse order due to the way how the cache is initialy created (to speed
1270                         // things up, we're doing a deep-copy of our parent).
1271
1272                         for (int i = applicable.Count-1; i >= 0; i--) {
1273                                 CacheEntry entry = (CacheEntry) applicable [i];
1274
1275                                 // This happens each time we're walking one level up in the class
1276                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1277                                 // the first time this happens (this may already happen in the first
1278                                 // iteration of this loop if there are no members with the name we're
1279                                 // looking for in the current class).
1280                                 if (entry.Container != current) {
1281                                         if (declared_only || DoneSearching (list))
1282                                                 break;
1283
1284                                         current = entry.Container;
1285                                 }
1286
1287                                 // Is the member of the correct type ?
1288                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1289                                         continue;
1290
1291                                 // Is the member static/non-static ?
1292                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1293                                         continue;
1294
1295                                 // Apply the filter to it.
1296                                 if (filter (entry.Member, criteria)) {
1297                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1298                                                 do_method_search = false;
1299                                         list.Add (entry.Member);
1300                                 }
1301                         }
1302
1303                         Timer.StopTimer (TimerType.CachedLookup);
1304
1305                         // If we have a method cache and we aren't already doing a method-only
1306                         // search, we restart in method-only search mode if the first match is
1307                         // a method.  This ensures that we return a MemberInfo with the correct
1308                         // ReflectedType for inherited methods.
1309                         if (do_method_search && (list.Count > 0))
1310                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1311
1312                         return new MemberList (list);
1313                 }
1314         }
1315 }