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