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