A type parameter is no longer an interface.
[mono.git] / mcs / gmcs / 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.Text;
15 using System.Collections;
16 using System.Reflection.Emit;
17 using System.Reflection;
18
19 namespace Mono.CSharp {
20
21         public class MemberName {
22                 public readonly string Name;
23                 public readonly TypeArguments TypeArguments;
24
25                 public readonly MemberName Left;
26
27                 public static readonly MemberName Null = new MemberName ("");
28
29                 public MemberName (string name)
30                 {
31                         this.Name = name;
32                 }
33
34                 public MemberName (string name, TypeArguments args)
35                         : this (name)
36                 {
37                         this.TypeArguments = args;
38                 }
39
40                 public MemberName (MemberName left, string name, TypeArguments args)
41                         : this (name, args)
42                 {
43                         this.Left = left;
44                 }
45
46                 public string GetName ()
47                 {
48                         if (Left != null)
49                                 return Left.GetName () + "." + Name;
50                         else
51                                 return Name;
52                 }
53
54                 public string GetFullName ()
55                 {
56                         string full_name;
57                         if (TypeArguments != null)
58                                 full_name = Name + "<" + TypeArguments + ">";
59                         else
60                                 full_name = Name;
61                         if (Left != null)
62                                 return Left.GetFullName () + "." + full_name;
63                         else
64                                 return full_name;
65                 }
66
67                 public string GetMemberName ()
68                 {
69                         string full_name;
70                         if (Left != null)
71                                 return Left.GetFullName () + "." + Name;
72                         else
73                                 return Name;
74                 }
75
76                 public Expression GetTypeExpression (Location loc)
77                 {
78                         if (Left != null) {
79                                 Expression lexpr = Left.GetTypeExpression (loc);
80
81                                 if (TypeArguments != null)
82                                         return new GenericMemberAccess (lexpr, Name, TypeArguments, loc);
83                                 else
84                                         return new MemberAccess (lexpr, Name, loc);
85                         } else {
86                                 if (TypeArguments != null)
87                                         return new ConstructedType (Name, TypeArguments, loc);
88                                 else
89                                         return new SimpleName (Name, loc);
90                         }
91                 }
92
93                 public override string ToString ()
94                 {
95                         string full_name;
96                         if (TypeArguments != null)
97                                 full_name = Name + "<" + TypeArguments + ">";
98                         else
99                                 full_name = Name;
100
101                         if (Left != null)
102                                 return Left + "." + full_name;
103                         else
104                                 return full_name;
105                 }
106         }
107
108         /// <summary>
109         ///   Base representation for members.  This is only used to keep track
110         ///   of Name, Location and Modifier flags.
111         /// </summary>
112         public abstract class MemberCore {
113                 /// <summary>
114                 ///   Public name
115                 /// </summary>
116                 public string Name;
117
118                 /// <summary>
119                 ///   Modifier flags that the user specified in the source code
120                 /// </summary>
121                 public int ModFlags;
122
123                 /// <summary>
124                 ///   Location where this declaration happens
125                 /// </summary>
126                 public readonly Location Location;
127
128                 /// <summary>
129                 ///   Attributes for this type
130                 /// </summary>
131                 Attributes attributes;
132
133                 public MemberCore (string name, Attributes attrs, Location loc)
134                 {
135                         Name = name;
136                         Location = loc;
137                         attributes = attrs;
138                 }
139
140                 public abstract bool Define (TypeContainer parent);
141
142                 // 
143                 // Returns full member name for error message
144                 //
145                 public virtual string GetSignatureForError () {
146                         return Name;
147                 }
148
149                 public Attributes OptAttributes 
150                 {
151                         get {
152                                 return attributes;
153                         }
154                         set {
155                                 attributes = value;
156                         }
157                 }
158
159                 // 
160                 // Whehter is it ok to use an unsafe pointer in this type container
161                 //
162                 public bool UnsafeOK (DeclSpace parent)
163                 {
164                         //
165                         // First check if this MemberCore modifier flags has unsafe set
166                         //
167                         if ((ModFlags & Modifiers.UNSAFE) != 0)
168                                 return true;
169
170                         if (parent.UnsafeContext)
171                                 return true;
172
173                         Expression.UnsafeError (Location);
174                         return false;
175                 }
176         }
177
178         /// <summary>
179         ///   Base class for structs, classes, enumerations and interfaces.  
180         /// </summary>
181         /// <remarks>
182         ///   They all create new declaration spaces.  This
183         ///   provides the common foundation for managing those name
184         ///   spaces.
185         /// </remarks>
186         public abstract class DeclSpace : MemberCore {
187                 /// <summary>
188                 ///   This points to the actual definition that is being
189                 ///   created with System.Reflection.Emit
190                 /// </summary>
191                 public TypeBuilder TypeBuilder;
192
193                 /// <summary>
194                 ///   If we are a generic type, this is the type we are
195                 ///   currently defining.  We need to lookup members on this
196                 ///   instead of the TypeBuilder.
197                 /// </summary>
198                 public TypeExpr CurrentType;
199
200                 /// <summary>
201                 ///   This variable tracks whether we have Closed the type
202                 /// </summary>
203                 public bool Created = false;
204                 
205                 //
206                 // This is the namespace in which this typecontainer
207                 // was declared.  We use this to resolve names.
208                 //
209                 public NamespaceEntry NamespaceEntry;
210
211                 public Hashtable Cache = new Hashtable ();
212                 
213                 public string Basename;
214                 
215                 /// <summary>
216                 ///   defined_names is used for toplevel objects
217                 /// </summary>
218                 protected Hashtable defined_names;
219
220                 bool is_generic;
221
222                 //
223                 // Whether we are Generic
224                 //
225                 public bool IsGeneric {
226                         get {
227                                 if (is_generic)
228                                         return true;
229                                 else if (parent != null)
230                                         return parent.IsGeneric;
231                                 else
232                                         return false;
233                         }
234                 }
235
236                 TypeContainer parent;
237
238                 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
239                         : base (name, attrs, l)
240                 {
241                         NamespaceEntry = ns;
242                         Basename = name.Substring (1 + name.LastIndexOf ('.'));
243                         defined_names = new Hashtable ();
244                         this.parent = parent;
245                 }
246
247                 public void RecordDecl ()
248                 {
249                         if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
250                                 NamespaceEntry.DefineName (Basename, this);
251                 }
252
253                 /// <summary>
254                 ///   The result value from adding an declaration into
255                 ///   a struct or a class
256                 /// </summary>
257                 public enum AdditionResult {
258                         /// <summary>
259                         /// The declaration has been successfully
260                         /// added to the declation space.
261                         /// </summary>
262                         Success,
263
264                         /// <summary>
265                         ///   The symbol has already been defined.
266                         /// </summary>
267                         NameExists,
268
269                         /// <summary>
270                         ///   Returned if the declation being added to the
271                         ///   name space clashes with its container name.
272                         ///
273                         ///   The only exceptions for this are constructors
274                         ///   and static constructors
275                         /// </summary>
276                         EnclosingClash,
277
278                         /// <summary>
279                         ///   Returned if a constructor was created (because syntactically
280                         ///   it looked like a constructor) but was not (because the name
281                         ///   of the method is not the same as the container class
282                         /// </summary>
283                         NotAConstructor,
284
285                         /// <summary>
286                         ///   This is only used by static constructors to emit the
287                         ///   error 111, but this error for other things really
288                         ///   happens at another level for other functions.
289                         /// </summary>
290                         MethodExists,
291
292                         /// <summary>
293                         ///   Some other error.
294                         /// </summary>
295                         Error
296                 }
297
298                 /// <summary>
299                 ///   Returns a status code based purely on the name
300                 ///   of the member being added
301                 /// </summary>
302                 protected AdditionResult IsValid (string basename, string name)
303                 {
304                         if (basename == Basename)
305                                 return AdditionResult.EnclosingClash;
306
307                         if (defined_names.Contains (name))
308                                 return AdditionResult.NameExists;
309
310                         return AdditionResult.Success;
311                 }
312
313                 public static int length;
314                 public static int small;
315                 
316                 /// <summary>
317                 ///   Introduce @name into this declaration space and
318                 ///   associates it with the object @o.  Note that for
319                 ///   methods this will just point to the first method. o
320                 /// </summary>
321                 public void DefineName (string name, object o)
322                 {
323                         defined_names.Add (name, o);
324
325 #if DEBUGME
326                         int p = name.LastIndexOf ('.');
327                         int l = name.Length;
328                         length += l;
329                         small += l -p;
330 #endif
331                 }
332
333                 /// <summary>
334                 ///   Returns the object associated with a given name in the declaration
335                 ///   space.  This is the inverse operation of `DefineName'
336                 /// </summary>
337                 public object GetDefinition (string name)
338                 {
339                         return defined_names [name];
340                 }
341                 
342                 bool in_transit = false;
343                 
344                 /// <summary>
345                 ///   This function is used to catch recursive definitions
346                 ///   in declarations.
347                 /// </summary>
348                 public bool InTransit {
349                         get {
350                                 return in_transit;
351                         }
352
353                         set {
354                                 in_transit = value;
355                         }
356                 }
357
358                 public TypeContainer Parent {
359                         get {
360                                 return parent;
361                         }
362                 }
363
364                 /// <summary>
365                 ///   Looks up the alias for the name
366                 /// </summary>
367                 public string LookupAlias (string name)
368                 {
369                         if (NamespaceEntry != null)
370                                 return NamespaceEntry.LookupAlias (name);
371                         else
372                                 return null;
373                 }
374                 
375                 // 
376                 // root_types contains all the types.  All TopLevel types
377                 // hence have a parent that points to `root_types', that is
378                 // why there is a non-obvious test down here.
379                 //
380                 public bool IsTopLevel {
381                         get {
382                                 if (parent != null){
383                                         if (parent.parent == null)
384                                                 return true;
385                                 }
386                                 return false;
387                         }
388                 }
389
390                 public virtual void CloseType ()
391                 {
392                         if (!Created){
393                                 try {
394                                         TypeBuilder.CreateType ();
395                                 } catch {
396                                         //
397                                         // The try/catch is needed because
398                                         // nested enumerations fail to load when they
399                                         // are defined.
400                                         //
401                                         // Even if this is the right order (enumerations
402                                         // declared after types).
403                                         //
404                                         // Note that this still creates the type and
405                                         // it is possible to save it
406                                 }
407                                 Created = true;
408                         }
409                 }
410
411                 /// <remarks>
412                 ///  Should be overriten by the appropriate declaration space
413                 /// </remarks>
414                 public abstract TypeBuilder DefineType ();
415                 
416                 /// <summary>
417                 ///   Define all members, but don't apply any attributes or do anything which may
418                 ///   access not-yet-defined classes.  This method also creates the MemberCache.
419                 /// </summary>
420                 public abstract bool DefineMembers (TypeContainer parent);
421
422                 //
423                 // Whether this is an `unsafe context'
424                 //
425                 public bool UnsafeContext {
426                         get {
427                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
428                                         return true;
429                                 if (parent != null)
430                                         return parent.UnsafeContext;
431                                 return false;
432                         }
433                 }
434
435                 public static string MakeFQN (string nsn, string name)
436                 {
437                         if (nsn == "")
438                                 return name;
439                         return String.Concat (nsn, ".", name);
440                 }
441
442                 EmitContext type_resolve_ec;
443                 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
444                 {
445                         type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
446                         type_resolve_ec.ResolvingTypeTree = true;
447
448                         return type_resolve_ec;
449                 }
450
451                 // <summary>
452                 //    Looks up the type, as parsed into the expression `e' 
453                 // </summary>
454                 public Type ResolveType (Expression e, bool silent, Location loc)
455                 {
456                         TypeExpr d = ResolveTypeExpr (e, silent, loc);
457                         if (d == null)
458                                 return null;
459
460                         return ResolveType (d, loc);
461                 }
462
463                 public Type ResolveType (TypeExpr d, Location loc)
464                 {
465                         if (!d.CheckAccessLevel (this)) {
466                                 Report. Error (122, loc,  "`" + d.Name + "' " +
467                                        "is inaccessible because of its protection level");
468                                 return null;
469                         }
470
471                         Type t = d.ResolveType (type_resolve_ec);
472                         if (t == null)
473                                 return null;
474
475                         TypeContainer tc = TypeManager.LookupTypeContainer (t);
476                         if ((tc != null) && tc.IsGeneric) {
477                                 ConstructedType ctype = new ConstructedType (
478                                         t, TypeParameters, loc);
479
480                                 t = ctype.ResolveType (type_resolve_ec);
481                         }
482
483                         return t;
484                 }
485
486                 // <summary>
487                 //    Resolves the expression `e' for a type, and will recursively define
488                 //    types. 
489                 // </summary>
490                 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
491                 {
492                         if (type_resolve_ec == null)
493                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
494                         type_resolve_ec.loc = loc;
495                         if (this is GenericMethod)
496                                 type_resolve_ec.ContainerType = Parent.TypeBuilder;
497                         else
498                                 type_resolve_ec.ContainerType = TypeBuilder;
499
500                         int errors = Report.Errors;
501
502                         TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
503
504                         if ((d != null) && (d.eclass == ExprClass.Type))
505                                 return d;
506
507                         if (silent || (Report.Errors != errors))
508                                 return null;
509
510                         if (e is SimpleName){
511                                 SimpleName s = new SimpleName (((SimpleName) e).Name, -1, loc);
512                                 d = s.ResolveAsTypeTerminal (type_resolve_ec);
513
514                                 if ((d == null) || (d.Type == null)) {
515                                         Report.Error (246, loc, "Cannot find type `{0}'", e);
516                                         return null;
517                                 }
518
519                                 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
520
521                                 if (num_args == 0) {
522                                         Report.Error (308, loc,
523                                                       "The non-generic type `{0}' cannot " +
524                                                       "be used with type arguments.",
525                                                       TypeManager.CSharpName (d.Type));
526                                         return null;
527                                 }
528
529                                 Report.Error (305, loc,
530                                               "Using the generic type `{0}' " +
531                                               "requires {1} type arguments",
532                                               TypeManager.GetFullName (d.Type), num_args);
533                                 return null;
534                         }
535
536                         Report.Error (246, loc, "Cannot find type `{0}'", e);
537                         return null;
538                 }
539                 
540                 public bool CheckAccessLevel (Type check_type) 
541                 {
542                         TypeBuilder tb;
543                         if (this is GenericMethod)
544                                 tb = Parent.TypeBuilder;
545                         else
546                                 tb = TypeBuilder;
547
548                         if (check_type.IsGenericInstance)
549                                 check_type = check_type.GetGenericTypeDefinition ();
550
551                         if (check_type == tb)
552                                 return true;
553
554                         if (check_type.IsGenericParameter)
555                                 return true; // FIXME
556                         
557                         TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
558                         
559                         //
560                         // Broken Microsoft runtime, return public for arrays, no matter what 
561                         // the accessibility is for their underlying class, and they return 
562                         // NonPublic visibility for pointers
563                         //
564                         if (check_type.IsArray || check_type.IsPointer)
565                                 return CheckAccessLevel (TypeManager.GetElementType (check_type));
566
567                         switch (check_attr){
568                         case TypeAttributes.Public:
569                                 return true;
570
571                         case TypeAttributes.NotPublic:
572                                 //
573                                 // This test should probably use the declaringtype.
574                                 //
575                                 if (check_type.Assembly == tb.Assembly){
576                                         return true;
577                                 }
578                                 return false;
579                                 
580                         case TypeAttributes.NestedPublic:
581                                 return true;
582
583                         case TypeAttributes.NestedPrivate:
584                                 string check_type_name = check_type.FullName;
585                                 string type_name = CurrentType != null ?
586                                         CurrentType.Name : tb.FullName;
587
588                                 int cio = check_type_name.LastIndexOf ('+');
589                                 string container = check_type_name.Substring (0, cio);
590
591                                 //
592                                 // Check if the check_type is a nested class of the current type
593                                 //
594                                 if (check_type_name.StartsWith (type_name + "+")){
595                                         return true;
596                                 }
597                                 
598                                 if (type_name.StartsWith (container)){
599                                         return true;
600                                 }
601
602                                 return false;
603
604                         case TypeAttributes.NestedFamily:
605                                 //
606                                 // Only accessible to methods in current type or any subtypes
607                                 //
608                                 return FamilyAccessible (tb, check_type);
609
610                         case TypeAttributes.NestedFamANDAssem:
611                                 return (check_type.Assembly == tb.Assembly) &&
612                                         FamilyAccessible (tb, check_type);
613
614                         case TypeAttributes.NestedFamORAssem:
615                                 return (check_type.Assembly == tb.Assembly) ||
616                                         FamilyAccessible (tb, check_type);
617
618                         case TypeAttributes.NestedAssembly:
619                                 return check_type.Assembly == tb.Assembly;
620                         }
621
622                         Console.WriteLine ("HERE: " + check_attr);
623                         return false;
624
625                 }
626
627                 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
628                 {
629                         Type declaring = check_type.DeclaringType;
630                         if (tb.IsSubclassOf (declaring))
631                                 return true;
632
633                         string check_type_name = check_type.FullName;
634                         
635                         int cio = check_type_name.LastIndexOf ('+');
636                         string container = check_type_name.Substring (0, cio);
637                         
638                         //
639                         // Check if the check_type is a nested class of the current type
640                         //
641                         if (check_type_name.StartsWith (container + "+"))
642                                 return true;
643
644                         return false;
645                 }
646
647                 // Access level of a type.
648                 const int X = 1;
649                 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
650                         // Public    Assembly   Protected
651                         Protected           = (0 << 0) | (0 << 1) | (X << 2),
652                         Public              = (X << 0) | (X << 1) | (X << 2),
653                         Private             = (0 << 0) | (0 << 1) | (0 << 2),
654                         Internal            = (0 << 0) | (X << 1) | (0 << 2),
655                         ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
656                 }
657
658                 static AccessLevel GetAccessLevelFromModifiers (int flags)
659                 {
660                         if ((flags & Modifiers.INTERNAL) != 0) {
661
662                                 if ((flags & Modifiers.PROTECTED) != 0)
663                                         return AccessLevel.ProtectedOrInternal;
664                                 else
665                                         return AccessLevel.Internal;
666
667                         } else if ((flags & Modifiers.PROTECTED) != 0)
668                                 return AccessLevel.Protected;
669                         else if ((flags & Modifiers.PRIVATE) != 0)
670                                 return AccessLevel.Private;
671                         else
672                                 return AccessLevel.Public;
673                 }
674
675                 // What is the effective access level of this?
676                 // TODO: Cache this?
677                 AccessLevel EffectiveAccessLevel {
678                         get {
679                                 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
680                                 if (!IsTopLevel && (Parent != null))
681                                         return myAccess & Parent.EffectiveAccessLevel;
682                                 return myAccess;
683                         }
684                 }
685
686                 // Return the access level for type `t'
687                 static AccessLevel TypeEffectiveAccessLevel (Type t)
688                 {
689                         if (t.IsPublic)
690                                 return AccessLevel.Public;
691                         if (t.IsNestedPrivate)
692                                 return AccessLevel.Private;
693                         if (t.IsNotPublic)
694                                 return AccessLevel.Internal;
695
696                         // By now, it must be nested
697                         AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
698
699                         if (t.IsNestedPublic)
700                                 return parentLevel;
701                         if (t.IsNestedAssembly)
702                                 return parentLevel & AccessLevel.Internal;
703                         if (t.IsNestedFamily)
704                                 return parentLevel & AccessLevel.Protected;
705                         if (t.IsNestedFamORAssem)
706                                 return parentLevel & AccessLevel.ProtectedOrInternal;
707                         if (t.IsNestedFamANDAssem)
708                                 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
709
710                         // nested private is taken care of
711
712                         throw new Exception ("I give up, what are you?");
713                 }
714
715                 //
716                 // This answers `is the type P, as accessible as a member M which has the
717                 // accessability @flags which is declared as a nested member of the type T, this declspace'
718                 //
719                 public bool AsAccessible (Type p, int flags)
720                 {
721                         if (p.IsGenericParameter)
722                                 return true; // FIXME
723
724                         //
725                         // 1) if M is private, its accessability is the same as this declspace.
726                         // we already know that P is accessible to T before this method, so we
727                         // may return true.
728                         //
729
730                         if ((flags & Modifiers.PRIVATE) != 0)
731                                 return true;
732
733                         while (p.IsArray || p.IsPointer || p.IsByRef)
734                                 p = TypeManager.GetElementType (p);
735
736                         AccessLevel pAccess = TypeEffectiveAccessLevel (p);
737                         AccessLevel mAccess = this.EffectiveAccessLevel &
738                                 GetAccessLevelFromModifiers (flags);
739
740                         // for every place from which we can access M, we must
741                         // be able to access P as well. So, we want
742                         // For every bit in M and P, M_i -> P_1 == true
743                         // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
744
745                         return ~ (~ mAccess | pAccess) == 0;
746                 }
747                 
748                 static DoubleHash dh = new DoubleHash (1000);
749
750                 Type DefineTypeAndParents (DeclSpace tc)
751                 {
752                         DeclSpace container = tc.Parent;
753
754                         if (container.TypeBuilder == null && container.Name != "")
755                                 DefineTypeAndParents (container);
756
757                         return tc.DefineType ();
758                 }
759                 
760                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
761                 {
762                         DeclSpace parent;
763                         Type t;
764                         object r;
765                         
766                         error = false;
767
768                         if (dh.Lookup (ns, name, out r))
769                                 return (Type) r;
770                         else {
771                                 if (ns != ""){
772                                         if (Namespace.IsNamespace (ns)){
773                                                 string fullname = (ns != "") ? ns + "." + name : name;
774                                                 t = TypeManager.LookupType (fullname);
775                                         } else
776                                                 t = null;
777                                 } else
778                                         t = TypeManager.LookupType (name);
779                         }
780                         
781                         if (t != null) {
782                                 dh.Insert (ns, name, t);
783                                 return t;
784                         }
785
786                         //
787                         // In case we are fed a composite name, normalize it.
788                         //
789                         int p = name.LastIndexOf ('.');
790                         if (p != -1){
791                                 ns = MakeFQN (ns, name.Substring (0, p));
792                                 name = name.Substring (p+1);
793                         }
794                         
795                         parent = RootContext.Tree.LookupByNamespace (ns, name);
796                         if (parent == null) {
797                                 dh.Insert (ns, name, null);
798                                 return null;
799                         }
800
801                         t = DefineTypeAndParents (parent);
802                         if (t == null){
803                                 error = true;
804                                 return null;
805                         }
806                         
807                         dh.Insert (ns, name, t);
808                         return t;
809                 }
810
811                 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
812                 {
813                         Report.Error (104, loc,
814                                       String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
815                                                      t1.FullName, t2.FullName));
816                 }
817
818                 public Type FindNestedType (Location loc, string name,
819                                             out DeclSpace containing_ds)
820                 {
821                         Type t;
822                         bool error;
823
824                         containing_ds = this;
825                         while (containing_ds != null){
826                                 Type container_type = containing_ds.TypeBuilder;
827                                 Type current_type = container_type;
828
829                                 while (current_type != null && current_type != TypeManager.object_type) {
830                                         string pre = current_type.FullName;
831
832                                         t = LookupInterfaceOrClass (pre, name, out error);
833                                         if (error)
834                                                 return null;
835
836                                         if ((t != null) && containing_ds.CheckAccessLevel (t))
837                                                 return t;
838
839                                         current_type = current_type.BaseType;
840                                 }
841                                 containing_ds = containing_ds.Parent;
842                         }
843
844                         return null;
845                 }
846
847                 /// <summary>
848                 ///   GetType is used to resolve type names at the DeclSpace level.
849                 ///   Use this to lookup class/struct bases, interface bases or 
850                 ///   delegate type references
851                 /// </summary>
852                 ///
853                 /// <remarks>
854                 ///   Contrast this to LookupType which is used inside method bodies to 
855                 ///   lookup types that have already been defined.  GetType is used
856                 ///   during the tree resolution process and potentially define
857                 ///   recursively the type
858                 /// </remarks>
859                 public Type FindType (Location loc, string name, int num_type_args)
860                 {
861                         Type t;
862                         bool error;
863
864                         //
865                         // For the case the type we are looking for is nested within this one
866                         // or is in any base class
867                         //
868                         DeclSpace containing_ds = this;
869
870                         while (containing_ds != null){
871                                 Type container_type = containing_ds.TypeBuilder;
872                                 Type current_type = container_type;
873
874                                 while (current_type != null && current_type != TypeManager.object_type) {
875                                         string pre = current_type.FullName;
876
877                                         t = LookupInterfaceOrClass (pre, name, out error);
878                                         if (error)
879                                                 return null;
880
881                                         if ((t != null) &&
882                                             containing_ds.CheckAccessLevel (t) &&
883                                             TypeManager.CheckGeneric (t, num_type_args))
884                                                 return t;
885
886                                         current_type = current_type.BaseType;
887                                 }
888                                 containing_ds = containing_ds.Parent;
889                         }
890
891                         //
892                         // Attempt to lookup the class on our namespace and all it's implicit parents
893                         //
894                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
895                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
896                                 if (error)
897                                         return null;
898
899                                 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
900                                         return t;
901                         }
902                         
903                         //
904                         // Attempt to do a direct unqualified lookup
905                         //
906                         t = LookupInterfaceOrClass ("", name, out error);
907                         if (error)
908                                 return null;
909                         
910                         if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
911                                 return t;
912                         
913                         //
914                         // Attempt to lookup the class on any of the `using'
915                         // namespaces
916                         //
917
918                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
919
920                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
921                                 if (error)
922                                         return null;
923
924                                 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
925                                         return t;
926
927                                 //
928                                 // Now check the using clause list
929                                 //
930                                 Type match = null;
931                                 foreach (Namespace using_ns in ns.GetUsingTable ()) {
932                                         match = LookupInterfaceOrClass (using_ns.Name, name, out error);
933                                         if (error)
934                                                 return null;
935
936                                         if ((match != null) &&
937                                             TypeManager.CheckGeneric (match, num_type_args)) {
938                                                 if (t != null){
939                                                         if (CheckAccessLevel (match)) {
940                                                                 Error_AmbiguousTypeReference (loc, name, t, match);
941                                                                 return null;
942                                                         }
943                                                         continue;
944                                                 }
945                                                 
946                                                 t = match;
947                                         }
948                                 }
949                                 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
950                                         return t;
951                         }
952
953                         //Report.Error (246, Location, "Can not find type `"+name+"'");
954                         return null;
955                 }
956
957                 /// <remarks>
958                 ///   This function is broken and not what you're looking for.  It should only
959                 ///   be used while the type is still being created since it doesn't use the cache
960                 ///   and relies on the filter doing the member name check.
961                 /// </remarks>
962                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
963                                                         MemberFilter filter, object criteria);
964
965                 /// <remarks>
966                 ///   If we have a MemberCache, return it.  This property may return null if the
967                 ///   class doesn't have a member cache or while it's still being created.
968                 /// </remarks>
969                 public abstract MemberCache MemberCache {
970                         get;
971                 }
972
973                 //
974                 // Extensions for generics
975                 //
976                 TypeParameter[] type_params;
977                 TypeParameter[] type_param_list;
978
979                 protected string GetInstantiationName ()
980                 {
981                         StringBuilder sb = new StringBuilder (Name);
982                         sb.Append ("<");
983                         for (int i = 0; i < type_param_list.Length; i++) {
984                                 if (i > 0)
985                                         sb.Append (",");
986                                 sb.Append (type_param_list [i].Name);
987                         }
988                         sb.Append (">");
989                         return sb.ToString ();
990                 }
991
992                 bool check_type_parameter (ArrayList list, int start, string name)
993                 {
994                         for (int i = 0; i < start; i++) {
995                                 TypeParameter param = (TypeParameter) list [i];
996
997                                 if (param.Name != name)
998                                         continue;
999
1000                                 if (RootContext.WarningLevel >= 3)
1001                                         Report.Warning (
1002                                                 693, Location,
1003                                                 "Type parameter `{0}' has same name " +
1004                                                 "as type parameter from outer type `{1}'",
1005                                                 name, parent.GetInstantiationName ());
1006
1007                                 return false;
1008                         }
1009
1010                         return true;
1011                 }
1012
1013                 TypeParameter[] initialize_type_params ()
1014                 {
1015                         if (type_param_list != null)
1016                                 return type_param_list;
1017
1018                         DeclSpace the_parent = parent;
1019                         if (this is GenericMethod)
1020                                 the_parent = the_parent.Parent;
1021
1022                         int start = 0;
1023                         TypeParameter[] parent_params = null;
1024                         if ((the_parent != null) && the_parent.IsGeneric) {
1025                                 parent_params = the_parent.initialize_type_params ();
1026                                 start = parent_params != null ? parent_params.Length : 0;
1027                         }
1028
1029                         ArrayList list = new ArrayList ();
1030                         if (parent_params != null)
1031                                 list.AddRange (parent_params);
1032
1033                         int count = type_params != null ? type_params.Length : 0;
1034                         for (int i = 0; i < count; i++) {
1035                                 TypeParameter param = type_params [i];
1036                                 check_type_parameter (list, start, param.Name);
1037                                 list.Add (param);
1038                         }
1039
1040                         type_param_list = new TypeParameter [list.Count];
1041                         list.CopyTo (type_param_list, 0);
1042                         return type_param_list;
1043                 }
1044
1045                 ///
1046                 /// Called by the parser to configure the type_parameter_list for this
1047                 /// declaration space
1048                 ///
1049                 public AdditionResult SetParameterInfo (TypeArguments args,
1050                                                         ArrayList constraints_list)
1051                 {
1052                         string[] type_parameter_list = args.GetDeclarations ();
1053                         if (type_parameter_list == null)
1054                                 return AdditionResult.Error;
1055
1056                         return SetParameterInfo (type_parameter_list, constraints_list);
1057                 }
1058
1059                 public AdditionResult SetParameterInfo (IList type_parameter_list,
1060                                                         ArrayList constraints_list)
1061                 {
1062                         type_params = new TypeParameter [type_parameter_list.Count];
1063
1064                         //
1065                         // Mark this type as Generic
1066                         //
1067                         is_generic = true;
1068
1069                         //
1070                         // Register all the names
1071                         //
1072                         for (int i = 0; i < type_parameter_list.Count; i++) {
1073                                 string name = (string) type_parameter_list [i];
1074
1075                                 AdditionResult res = IsValid (name, name);
1076
1077                                 if (res != AdditionResult.Success)
1078                                         return res;
1079
1080                                 Constraints constraints = null;
1081                                 if (constraints_list != null) {
1082                                         foreach (Constraints constraint in constraints_list) {
1083                                                 if (constraint.TypeParameter == name) {
1084                                                         constraints = constraint;
1085                                                         break;
1086                                                 }
1087                                         }
1088                                 }
1089
1090                                 type_params [i] = new TypeParameter (name, constraints, Location);
1091
1092                                 DefineName (name, type_params [i]);
1093                         }
1094
1095                         return AdditionResult.Success;
1096                 }
1097
1098                 public TypeParameter[] TypeParameters {
1099                         get {
1100                                 if (!IsGeneric)
1101                                         throw new InvalidOperationException ();
1102                                 if (type_param_list == null)
1103                                         initialize_type_params ();
1104
1105                                 return type_param_list;
1106                         }
1107                 }
1108
1109                 protected TypeParameter[] CurrentTypeParameters {
1110                         get {
1111                                 if (!IsGeneric)
1112                                         throw new InvalidOperationException ();
1113                                 if (type_params != null)
1114                                         return type_params;
1115                                 else
1116                                         return new TypeParameter [0];
1117                         }
1118                 }
1119
1120                 public int CountTypeParameters {
1121                         get {
1122                                 if (!IsGeneric)
1123                                         return 0;
1124                                 if (type_param_list == null)
1125                                         initialize_type_params ();
1126
1127                                 return type_param_list.Length;
1128                         }
1129                 }
1130
1131                 public TypeParameterExpr LookupGeneric (string name, Location loc)
1132                 {
1133                         if (!IsGeneric)
1134                                 return null;
1135
1136                         foreach (TypeParameter type_param in CurrentTypeParameters) {
1137                                 if (type_param.Name != name)
1138                                         continue;
1139
1140                                 return new TypeParameterExpr (type_param, loc);
1141                         }
1142
1143                         if (parent != null)
1144                                 return parent.LookupGeneric (name, loc);
1145
1146                         return null;
1147                 }
1148         }
1149
1150         /// <summary>
1151         ///   This is a readonly list of MemberInfo's.      
1152         /// </summary>
1153         public class MemberList : IList {
1154                 public readonly IList List;
1155                 int count;
1156
1157                 /// <summary>
1158                 ///   Create a new MemberList from the given IList.
1159                 /// </summary>
1160                 public MemberList (IList list)
1161                 {
1162                         if (list != null)
1163                                 this.List = list;
1164                         else
1165                                 this.List = new ArrayList ();
1166                         count = List.Count;
1167                 }
1168
1169                 /// <summary>
1170                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
1171                 /// </summary>
1172                 public MemberList (IList first, IList second)
1173                 {
1174                         ArrayList list = new ArrayList ();
1175                         list.AddRange (first);
1176                         list.AddRange (second);
1177                         count = list.Count;
1178                         List = list;
1179                 }
1180
1181                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1182
1183                 /// <summary>
1184                 ///   Cast the MemberList into a MemberInfo[] array.
1185                 /// </summary>
1186                 /// <remarks>
1187                 ///   This is an expensive operation, only use it if it's really necessary.
1188                 /// </remarks>
1189                 public static explicit operator MemberInfo [] (MemberList list)
1190                 {
1191                         Timer.StartTimer (TimerType.MiscTimer);
1192                         MemberInfo [] result = new MemberInfo [list.Count];
1193                         list.CopyTo (result, 0);
1194                         Timer.StopTimer (TimerType.MiscTimer);
1195                         return result;
1196                 }
1197
1198                 // ICollection
1199
1200                 public int Count {
1201                         get {
1202                                 return count;
1203                         }
1204                 }
1205
1206                 public bool IsSynchronized {
1207                         get {
1208                                 return List.IsSynchronized;
1209                         }
1210                 }
1211
1212                 public object SyncRoot {
1213                         get {
1214                                 return List.SyncRoot;
1215                         }
1216                 }
1217
1218                 public void CopyTo (Array array, int index)
1219                 {
1220                         List.CopyTo (array, index);
1221                 }
1222
1223                 // IEnumerable
1224
1225                 public IEnumerator GetEnumerator ()
1226                 {
1227                         return List.GetEnumerator ();
1228                 }
1229
1230                 // IList
1231
1232                 public bool IsFixedSize {
1233                         get {
1234                                 return true;
1235                         }
1236                 }
1237
1238                 public bool IsReadOnly {
1239                         get {
1240                                 return true;
1241                         }
1242                 }
1243
1244                 object IList.this [int index] {
1245                         get {
1246                                 return List [index];
1247                         }
1248
1249                         set {
1250                                 throw new NotSupportedException ();
1251                         }
1252                 }
1253
1254                 // FIXME: try to find out whether we can avoid the cast in this indexer.
1255                 public MemberInfo this [int index] {
1256                         get {
1257                                 return (MemberInfo) List [index];
1258                         }
1259                 }
1260
1261                 public int Add (object value)
1262                 {
1263                         throw new NotSupportedException ();
1264                 }
1265
1266                 public void Clear ()
1267                 {
1268                         throw new NotSupportedException ();
1269                 }
1270
1271                 public bool Contains (object value)
1272                 {
1273                         return List.Contains (value);
1274                 }
1275
1276                 public int IndexOf (object value)
1277                 {
1278                         return List.IndexOf (value);
1279                 }
1280
1281                 public void Insert (int index, object value)
1282                 {
1283                         throw new NotSupportedException ();
1284                 }
1285
1286                 public void Remove (object value)
1287                 {
1288                         throw new NotSupportedException ();
1289                 }
1290
1291                 public void RemoveAt (int index)
1292                 {
1293                         throw new NotSupportedException ();
1294                 }
1295         }
1296
1297         /// <summary>
1298         ///   This interface is used to get all members of a class when creating the
1299         ///   member cache.  It must be implemented by all DeclSpace derivatives which
1300         ///   want to support the member cache and by TypeHandle to get caching of
1301         ///   non-dynamic types.
1302         /// </summary>
1303         public interface IMemberContainer {
1304                 /// <summary>
1305                 ///   The name of the IMemberContainer.  This is only used for
1306                 ///   debugging purposes.
1307                 /// </summary>
1308                 string Name {
1309                         get;
1310                 }
1311
1312                 /// <summary>
1313                 ///   The type of this IMemberContainer.
1314                 /// </summary>
1315                 Type Type {
1316                         get;
1317                 }
1318
1319                 /// <summary>
1320                 ///   Returns the IMemberContainer of the parent class or null if this
1321                 ///   is an interface or TypeManger.object_type.
1322                 ///   This is used when creating the member cache for a class to get all
1323                 ///   members from the parent class.
1324                 /// </summary>
1325                 IMemberContainer Parent {
1326                         get;
1327                 }
1328
1329                 /// <summary>
1330                 ///   Whether this is an interface.
1331                 /// </summary>
1332                 bool IsInterface {
1333                         get;
1334                 }
1335
1336                 /// <summary>
1337                 ///   Returns all members of this class with the corresponding MemberTypes
1338                 ///   and BindingFlags.
1339                 /// </summary>
1340                 /// <remarks>
1341                 ///   When implementing this method, make sure not to return any inherited
1342                 ///   members and check the MemberTypes and BindingFlags properly.
1343                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
1344                 ///   get the BindingFlags (static/non-static,public/non-public) in the
1345                 ///   MemberInfo class, but the cache needs this information.  That's why
1346                 ///   this method is called multiple times with different BindingFlags.
1347                 /// </remarks>
1348                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1349
1350                 /// <summary>
1351                 ///   Return the container's member cache.
1352                 /// </summary>
1353                 MemberCache MemberCache {
1354                         get;
1355                 }
1356         }
1357
1358         /// <summary>
1359         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
1360         ///   member lookups.  It has a member name based hash table; it maps each member
1361         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
1362         ///   and the BindingFlags that were initially used to get it.  The cache contains
1363         ///   all members of the current class and all inherited members.  If this cache is
1364         ///   for an interface types, it also contains all inherited members.
1365         ///
1366         ///   There are two ways to get a MemberCache:
1367         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
1368         ///     use the DeclSpace.MemberCache property.
1369         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1370         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
1371         /// </summary>
1372         public class MemberCache {
1373                 public readonly IMemberContainer Container;
1374                 protected Hashtable member_hash;
1375                 protected Hashtable method_hash;
1376                 
1377                 Hashtable interface_hash;
1378
1379                 /// <summary>
1380                 ///   Create a new MemberCache for the given IMemberContainer `container'.
1381                 /// </summary>
1382                 public MemberCache (IMemberContainer container)
1383                 {
1384                         this.Container = container;
1385
1386                         Timer.IncrementCounter (CounterType.MemberCache);
1387                         Timer.StartTimer (TimerType.CacheInit);
1388
1389                         
1390
1391                         // If we have a parent class (we have a parent class unless we're
1392                         // TypeManager.object_type), we deep-copy its MemberCache here.
1393                         if (Container.IsInterface) {
1394                                 MemberCache parent;
1395                                 interface_hash = new Hashtable ();
1396                                 
1397                                 if (Container.Parent != null)
1398                                         parent = Container.Parent.MemberCache;
1399                                 else
1400                                         parent = TypeHandle.ObjectType.MemberCache;
1401                                 member_hash = SetupCacheForInterface (parent);
1402                         } else if (Container.Parent != null)
1403                                 member_hash = SetupCache (Container.Parent.MemberCache);
1404                         else
1405                                 member_hash = new Hashtable ();
1406
1407                         // If this is neither a dynamic type nor an interface, create a special
1408                         // method cache with all declared and inherited methods.
1409                         Type type = container.Type;
1410                         if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1411                                 method_hash = new Hashtable ();
1412                                 AddMethods (type);
1413                         }
1414
1415                         // Add all members from the current class.
1416                         AddMembers (Container);
1417
1418                         Timer.StopTimer (TimerType.CacheInit);
1419                 }
1420
1421                 /// <summary>
1422                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
1423                 /// </summary>
1424                 Hashtable SetupCache (MemberCache parent)
1425                 {
1426                         Hashtable hash = new Hashtable ();
1427
1428                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1429                         while (it.MoveNext ()) {
1430                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1431                         }
1432                                 
1433                         return hash;
1434                 }
1435
1436
1437                 /// <summary>
1438                 ///   Add the contents of `new_hash' to `hash'.
1439                 /// </summary>
1440                 void AddHashtable (Hashtable hash, Hashtable new_hash)
1441                 {
1442                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
1443                         while (it.MoveNext ()) {
1444                                 ArrayList list = (ArrayList) hash [it.Key];
1445                                 if (list != null)
1446                                         list.AddRange ((ArrayList) it.Value);
1447                                 else
1448                                         hash [it.Key] = ((ArrayList) it.Value).Clone ();
1449                         }
1450                 }
1451
1452                 /// <summary>
1453                 ///   Bootstrap the member cache for an interface type.
1454                 ///   Type.GetMembers() won't return any inherited members for interface types,
1455                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
1456                 /// </summary>
1457                 Hashtable SetupCacheForInterface (MemberCache parent)
1458                 {
1459                         Hashtable hash = SetupCache (parent);
1460                         TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1461
1462                         foreach (TypeExpr iface in ifaces) {
1463                                 Type itype = iface.Type;
1464
1465                                 if (interface_hash.Contains (itype))
1466                                         continue;
1467                                 
1468                                 interface_hash [itype] = null;
1469
1470                                 IMemberContainer iface_container =
1471                                         TypeManager.LookupMemberContainer (itype);
1472
1473                                 MemberCache iface_cache = iface_container.MemberCache;
1474
1475                                 AddHashtable (hash, iface_cache.member_hash);
1476                                 
1477                                 if (iface_cache.interface_hash == null)
1478                                         continue;
1479                                 
1480                                 foreach (Type parent_contains in iface_cache.interface_hash.Keys)
1481                                         interface_hash [parent_contains] = null;
1482                         }
1483
1484                         return hash;
1485                 }
1486
1487                 /// <summary>
1488                 ///   Add all members from class `container' to the cache.
1489                 /// </summary>
1490                 void AddMembers (IMemberContainer container)
1491                 {
1492                         // We need to call AddMembers() with a single member type at a time
1493                         // to get the member type part of CacheEntry.EntryType right.
1494                         AddMembers (MemberTypes.Constructor, container);
1495                         AddMembers (MemberTypes.Field, container);
1496                         AddMembers (MemberTypes.Method, container);
1497                         AddMembers (MemberTypes.Property, container);
1498                         AddMembers (MemberTypes.Event, container);
1499                         // Nested types are returned by both Static and Instance searches.
1500                         AddMembers (MemberTypes.NestedType,
1501                                     BindingFlags.Static | BindingFlags.Public, container);
1502                         AddMembers (MemberTypes.NestedType,
1503                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1504                 }
1505
1506                 void AddMembers (MemberTypes mt, IMemberContainer container)
1507                 {
1508                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1509                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1510                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1511                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1512                 }
1513
1514                 /// <summary>
1515                 ///   Add all members from class `container' with the requested MemberTypes and
1516                 ///   BindingFlags to the cache.  This method is called multiple times with different
1517                 ///   MemberTypes and BindingFlags.
1518                 /// </summary>
1519                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1520                 {
1521                         MemberList members = container.GetMembers (mt, bf);
1522
1523                         foreach (MemberInfo member in members) {
1524                                 string name = member.Name;
1525
1526                                 int pos = name.IndexOf ('<');
1527                                 if (pos > 0)
1528                                         name = name.Substring (0, pos);
1529
1530                                 // We use a name-based hash table of ArrayList's.
1531                                 ArrayList list = (ArrayList) member_hash [name];
1532                                 if (list == null) {
1533                                         list = new ArrayList ();
1534                                         member_hash.Add (name, list);
1535                                 }
1536
1537                                 // When this method is called for the current class, the list will
1538                                 // already contain all inherited members from our parent classes.
1539                                 // We cannot add new members in front of the list since this'd be an
1540                                 // expensive operation, that's why the list is sorted in reverse order
1541                                 // (ie. members from the current class are coming last).
1542                                 list.Add (new CacheEntry (container, member, mt, bf));
1543                         }
1544                 }
1545
1546                 /// <summary>
1547                 ///   Add all declared and inherited methods from class `type' to the method cache.
1548                 /// </summary>
1549                 void AddMethods (Type type)
1550                 {
1551                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1552                                     BindingFlags.FlattenHierarchy, type);
1553                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1554                                     BindingFlags.FlattenHierarchy, type);
1555                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1556                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1557                 }
1558
1559                 void AddMethods (BindingFlags bf, Type type)
1560                 {
1561                         MemberInfo [] members = type.GetMethods (bf);
1562
1563                         Array.Reverse (members);
1564
1565                         foreach (MethodBase member in members) {
1566                                 string name = member.Name;
1567
1568                                 // Varargs methods aren't allowed in C# code.
1569                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1570                                         continue;
1571
1572                                 // We use a name-based hash table of ArrayList's.
1573                                 ArrayList list = (ArrayList) method_hash [name];
1574                                 if (list == null) {
1575                                         list = new ArrayList ();
1576                                         method_hash.Add (name, list);
1577                                 }
1578
1579                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1580                                 // sorted so we need to do this check for every member.
1581                                 BindingFlags new_bf = bf;
1582                                 if (member.DeclaringType == type)
1583                                         new_bf |= BindingFlags.DeclaredOnly;
1584
1585                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1586                         }
1587                 }
1588
1589                 /// <summary>
1590                 ///   Compute and return a appropriate `EntryType' magic number for the given
1591                 ///   MemberTypes and BindingFlags.
1592                 /// </summary>
1593                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1594                 {
1595                         EntryType type = EntryType.None;
1596
1597                         if ((mt & MemberTypes.Constructor) != 0)
1598                                 type |= EntryType.Constructor;
1599                         if ((mt & MemberTypes.Event) != 0)
1600                                 type |= EntryType.Event;
1601                         if ((mt & MemberTypes.Field) != 0)
1602                                 type |= EntryType.Field;
1603                         if ((mt & MemberTypes.Method) != 0)
1604                                 type |= EntryType.Method;
1605                         if ((mt & MemberTypes.Property) != 0)
1606                                 type |= EntryType.Property;
1607                         // Nested types are returned by static and instance searches.
1608                         if ((mt & MemberTypes.NestedType) != 0)
1609                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1610
1611                         if ((bf & BindingFlags.Instance) != 0)
1612                                 type |= EntryType.Instance;
1613                         if ((bf & BindingFlags.Static) != 0)
1614                                 type |= EntryType.Static;
1615                         if ((bf & BindingFlags.Public) != 0)
1616                                 type |= EntryType.Public;
1617                         if ((bf & BindingFlags.NonPublic) != 0)
1618                                 type |= EntryType.NonPublic;
1619                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1620                                 type |= EntryType.Declared;
1621
1622                         return type;
1623                 }
1624
1625                 /// <summary>
1626                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1627                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1628                 ///   single member types.
1629                 /// </summary>
1630                 public static bool IsSingleMemberType (MemberTypes mt)
1631                 {
1632                         switch (mt) {
1633                         case MemberTypes.Constructor:
1634                         case MemberTypes.Event:
1635                         case MemberTypes.Field:
1636                         case MemberTypes.Method:
1637                         case MemberTypes.Property:
1638                         case MemberTypes.NestedType:
1639                                 return true;
1640
1641                         default:
1642                                 return false;
1643                         }
1644                 }
1645
1646                 /// <summary>
1647                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1648                 ///   number to speed up the searching process.
1649                 /// </summary>
1650                 [Flags]
1651                 protected enum EntryType {
1652                         None            = 0x000,
1653
1654                         Instance        = 0x001,
1655                         Static          = 0x002,
1656                         MaskStatic      = Instance|Static,
1657
1658                         Public          = 0x004,
1659                         NonPublic       = 0x008,
1660                         MaskProtection  = Public|NonPublic,
1661
1662                         Declared        = 0x010,
1663
1664                         Constructor     = 0x020,
1665                         Event           = 0x040,
1666                         Field           = 0x080,
1667                         Method          = 0x100,
1668                         Property        = 0x200,
1669                         NestedType      = 0x400,
1670
1671                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1672                 }
1673
1674                 protected struct CacheEntry {
1675                         public readonly IMemberContainer Container;
1676                         public readonly EntryType EntryType;
1677                         public readonly MemberInfo Member;
1678
1679                         public CacheEntry (IMemberContainer container, MemberInfo member,
1680                                            MemberTypes mt, BindingFlags bf)
1681                         {
1682                                 this.Container = container;
1683                                 this.Member = member;
1684                                 this.EntryType = GetEntryType (mt, bf);
1685                         }
1686                 }
1687
1688                 /// <summary>
1689                 ///   This is called each time we're walking up one level in the class hierarchy
1690                 ///   and checks whether we can abort the search since we've already found what
1691                 ///   we were looking for.
1692                 /// </summary>
1693                 protected bool DoneSearching (ArrayList list)
1694                 {
1695                         //
1696                         // We've found exactly one member in the current class and it's not
1697                         // a method or constructor.
1698                         //
1699                         if (list.Count == 1 && !(list [0] is MethodBase))
1700                                 return true;
1701
1702                         //
1703                         // Multiple properties: we query those just to find out the indexer
1704                         // name
1705                         //
1706                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1707                                 return true;
1708
1709                         return false;
1710                 }
1711
1712                 /// <summary>
1713                 ///   Looks up members with name `name'.  If you provide an optional
1714                 ///   filter function, it'll only be called with members matching the
1715                 ///   requested member name.
1716                 ///
1717                 ///   This method will try to use the cache to do the lookup if possible.
1718                 ///
1719                 ///   Unlike other FindMembers implementations, this method will always
1720                 ///   check all inherited members - even when called on an interface type.
1721                 ///
1722                 ///   If you know that you're only looking for methods, you should use
1723                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1724                 ///   When doing a method-only search, it'll try to use a special method
1725                 ///   cache (unless it's a dynamic type or an interface) and the returned
1726                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1727                 ///   The lookup process will automatically restart itself in method-only
1728                 ///   search mode if it discovers that it's about to return methods.
1729                 /// </summary>
1730                 ArrayList global = new ArrayList ();
1731                 bool using_global = false;
1732                 
1733                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1734                                                MemberFilter filter, object criteria)
1735                 {
1736                         if (using_global)
1737                                 throw new Exception ();
1738                         
1739                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1740                         bool method_search = mt == MemberTypes.Method;
1741                         // If we have a method cache and we aren't already doing a method-only search,
1742                         // then we restart a method search if the first match is a method.
1743                         bool do_method_search = !method_search && (method_hash != null);
1744
1745                         ArrayList applicable;
1746
1747                         // If this is a method-only search, we try to use the method cache if
1748                         // possible; a lookup in the method cache will return a MemberInfo with
1749                         // the correct ReflectedType for inherited methods.
1750                         
1751                         if (method_search && (method_hash != null))
1752                                 applicable = (ArrayList) method_hash [name];
1753                         else
1754                                 applicable = (ArrayList) member_hash [name];
1755                         
1756                         if (applicable == null)
1757                                 return MemberList.Empty;
1758
1759                         //
1760                         // 32  slots gives 53 rss/54 size
1761                         // 2/4 slots gives 55 rss
1762                         //
1763                         // Strange: from 25,000 calls, only 1,800
1764                         // are above 2.  Why does this impact it?
1765                         //
1766                         global.Clear ();
1767                         using_global = true;
1768
1769                         Timer.StartTimer (TimerType.CachedLookup);
1770
1771                         EntryType type = GetEntryType (mt, bf);
1772
1773                         IMemberContainer current = Container;
1774
1775                         // `applicable' is a list of all members with the given member name `name'
1776                         // in the current class and all its parent classes.  The list is sorted in
1777                         // reverse order due to the way how the cache is initialy created (to speed
1778                         // things up, we're doing a deep-copy of our parent).
1779
1780                         for (int i = applicable.Count-1; i >= 0; i--) {
1781                                 CacheEntry entry = (CacheEntry) applicable [i];
1782
1783                                 // This happens each time we're walking one level up in the class
1784                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1785                                 // the first time this happens (this may already happen in the first
1786                                 // iteration of this loop if there are no members with the name we're
1787                                 // looking for in the current class).
1788                                 if (entry.Container != current) {
1789                                         if (declared_only || DoneSearching (global))
1790                                                 break;
1791
1792                                         current = entry.Container;
1793                                 }
1794
1795                                 // Is the member of the correct type ?
1796                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1797                                         continue;
1798
1799                                 // Is the member static/non-static ?
1800                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1801                                         continue;
1802
1803                                 // Apply the filter to it.
1804                                 if (filter (entry.Member, criteria)) {
1805                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1806                                                 do_method_search = false;
1807                                         global.Add (entry.Member);
1808                                 }
1809                         }
1810
1811                         Timer.StopTimer (TimerType.CachedLookup);
1812
1813                         // If we have a method cache and we aren't already doing a method-only
1814                         // search, we restart in method-only search mode if the first match is
1815                         // a method.  This ensures that we return a MemberInfo with the correct
1816                         // ReflectedType for inherited methods.
1817                         if (do_method_search && (global.Count > 0)){
1818                                 using_global = false;
1819
1820                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1821                         }
1822
1823                         using_global = false;
1824                         MemberInfo [] copy = new MemberInfo [global.Count];
1825                         global.CopyTo (copy);
1826                         return new MemberList (copy);
1827                 }
1828                 
1829                 //
1830                 // This finds the method or property for us to override. invocationType is the type where
1831                 // the override is going to be declared, name is the name of the method/property, and
1832                 // paramTypes is the parameters, if any to the method or property
1833                 //
1834                 // Because the MemberCache holds members from this class and all the base classes,
1835                 // we can avoid tons of reflection stuff.
1836                 //
1837                 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1838                 {
1839                         ArrayList applicable;
1840                         if (method_hash != null && !is_property)
1841                                 applicable = (ArrayList) method_hash [name];
1842                         else
1843                                 applicable = (ArrayList) member_hash [name];
1844                         
1845                         if (applicable == null)
1846                                 return null;
1847                         //
1848                         // Walk the chain of methods, starting from the top.
1849                         //
1850                         for (int i = applicable.Count - 1; i >= 0; i--) {
1851                                 CacheEntry entry = (CacheEntry) applicable [i];
1852                                 
1853                                 if ((entry.EntryType & (is_property ? EntryType.Property : EntryType.Method)) == 0)
1854                                         continue;
1855
1856                                 PropertyInfo pi = null;
1857                                 MethodInfo mi = null;
1858                                 Type [] cmpAttrs;
1859                                 
1860                                 if (is_property) {
1861                                         pi = (PropertyInfo) entry.Member;
1862                                         cmpAttrs = TypeManager.GetArgumentTypes (pi);
1863                                 } else {
1864                                         mi = (MethodInfo) entry.Member;
1865                                         cmpAttrs = TypeManager.GetArgumentTypes (mi);
1866                                 }
1867                                 
1868                                 //
1869                                 // Check the arguments
1870                                 //
1871                                 if (cmpAttrs.Length != paramTypes.Length)
1872                                         continue;
1873
1874                                 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
1875                                         if (!paramTypes [j].Equals (cmpAttrs [j]))
1876                                                 goto next;
1877                                 }
1878                                 
1879                                 //
1880                                 // get one of the methods because this has the visibility info.
1881                                 //
1882                                 if (is_property) {
1883                                         mi = pi.GetGetMethod (true);
1884                                         if (mi == null)
1885                                                 mi = pi.GetSetMethod (true);
1886                                 }
1887                                 
1888                                 //
1889                                 // Check visibility
1890                                 //
1891                                 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1892                                 case MethodAttributes.Private:
1893                                         //
1894                                         // A private method is Ok if we are a nested subtype.
1895                                         // The spec actually is not very clear about this, see bug 52458.
1896                                         //
1897                                         if (invocationType == entry.Container.Type ||
1898                                             TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1899                                                 return entry.Member;
1900                                         
1901                                         break;
1902                                 case MethodAttributes.FamANDAssem:
1903                                 case MethodAttributes.Assembly:
1904                                         //
1905                                         // Check for assembly methods
1906                                         //
1907                                         if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1908                                                 return entry.Member;
1909                                         
1910                                         break;
1911                                 default:
1912                                         //
1913                                         // A protected method is ok, because we are overriding.
1914                                         // public is always ok.
1915                                         //
1916                                         return entry.Member;
1917                                 }
1918                         next:
1919                                 ;
1920                         }
1921                         
1922                         return null;
1923                 }
1924         }
1925 }