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