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