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