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