2003-11-04 cesar lopez nataren <cesar@ciencias.unam.mx>
[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.Collections;
15 using System.Reflection.Emit;
16 using System.Reflection;
17
18 namespace Mono.CSharp {
19
20         /// <summary>
21         ///   Base representation for members.  This is only used to keep track
22         ///   of Name, Location and Modifier flags.
23         /// </summary>
24         public abstract class MemberCore {
25                 /// <summary>
26                 ///   Public name
27                 /// </summary>
28                 public string Name;
29
30                 /// <summary>
31                 ///   Modifier flags that the user specified in the source code
32                 /// </summary>
33                 public int ModFlags;
34
35                 /// <summary>
36                 ///   Location where this declaration happens
37                 /// </summary>
38                 public readonly Location Location;
39
40                 public MemberCore (string name, Location loc)
41                 {
42                         Name = name;
43                         Location = loc;
44                 }
45
46                 public abstract bool Define (TypeContainer parent);
47
48                 // 
49                 // Whehter is it ok to use an unsafe pointer in this type container
50                 //
51                 public bool UnsafeOK (DeclSpace parent)
52                 {
53                         //
54                         // First check if this MemberCore modifier flags has unsafe set
55                         //
56                         if ((ModFlags & Modifiers.UNSAFE) != 0)
57                                 return true;
58
59                         if (parent.UnsafeContext)
60                                 return true;
61
62                         Expression.UnsafeError (Location);
63                         return false;
64                 }
65         }
66
67         /// <summary>
68         ///   Base class for structs, classes, enumerations and interfaces.  
69         /// </summary>
70         /// <remarks>
71         ///   They all create new declaration spaces.  This
72         ///   provides the common foundation for managing those name
73         ///   spaces.
74         /// </remarks>
75         public abstract class DeclSpace : MemberCore {
76                 /// <summary>
77                 ///   this points to the actual definition that is being
78                 ///   created with System.Reflection.Emit
79                 /// </summary>
80                 public TypeBuilder TypeBuilder;
81
82                 /// <summary>
83                 ///   This variable tracks whether we have Closed the type
84                 /// </summary>
85                 public bool Created = false;
86                 
87                 //
88                 // This is the namespace in which this typecontainer
89                 // was declared.  We use this to resolve names.
90                 //
91                 public NamespaceEntry NamespaceEntry;
92
93                 public Hashtable Cache = new Hashtable ();
94                 
95                 public string Basename;
96                 
97                 /// <summary>
98                 ///   defined_names is used for toplevel objects
99                 /// </summary>
100                 protected Hashtable defined_names;
101
102                 //
103                 // Whether we are Generic
104                 //
105                 public bool IsGeneric;
106
107                 TypeContainer parent;
108
109                 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Location l)
110                         : base (name, l)
111                 {
112                         NamespaceEntry = ns;
113                         Basename = name.Substring (1 + name.LastIndexOf ('.'));
114                         defined_names = new Hashtable ();
115                         this.parent = parent;
116                 }
117
118                 public void RecordDecl ()
119                 {
120                         if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
121                                 NamespaceEntry.DefineName (Basename, this);
122                 }
123
124                 /// <summary>
125                 ///   The result value from adding an declaration into
126                 ///   a struct or a class
127                 /// </summary>
128                 public enum AdditionResult {
129                         /// <summary>
130                         /// The declaration has been successfully
131                         /// added to the declation space.
132                         /// </summary>
133                         Success,
134
135                         /// <summary>
136                         ///   The symbol has already been defined.
137                         /// </summary>
138                         NameExists,
139
140                         /// <summary>
141                         ///   Returned if the declation being added to the
142                         ///   name space clashes with its container name.
143                         ///
144                         ///   The only exceptions for this are constructors
145                         ///   and static constructors
146                         /// </summary>
147                         EnclosingClash,
148
149                         /// <summary>
150                         ///   Returned if a constructor was created (because syntactically
151                         ///   it looked like a constructor) but was not (because the name
152                         ///   of the method is not the same as the container class
153                         /// </summary>
154                         NotAConstructor,
155
156                         /// <summary>
157                         ///   This is only used by static constructors to emit the
158                         ///   error 111, but this error for other things really
159                         ///   happens at another level for other functions.
160                         /// </summary>
161                         MethodExists,
162
163                         /// <summary>
164                         ///   Some other error.
165                         /// </summary>
166                         Error
167                 }
168
169                 /// <summary>
170                 ///   Returns a status code based purely on the name
171                 ///   of the member being added
172                 /// </summary>
173                 protected AdditionResult IsValid (string basename, string name)
174                 {
175                         if (basename == Basename)
176                                 return AdditionResult.EnclosingClash;
177
178                         if (defined_names.Contains (name))
179                                 return AdditionResult.NameExists;
180
181                         return AdditionResult.Success;
182                 }
183
184                 public static int length;
185                 public static int small;
186                 
187                 /// <summary>
188                 ///   Introduce @name into this declaration space and
189                 ///   associates it with the object @o.  Note that for
190                 ///   methods this will just point to the first method. o
191                 /// </summary>
192                 protected void DefineName (string name, object o)
193                 {
194                         defined_names.Add (name, o);
195
196 #if DEBUGME
197                         int p = name.LastIndexOf (".");
198                         int l = name.Length;
199                         length += l;
200                         small += l -p;
201 #endif
202                 }
203
204                 /// <summary>
205                 ///   Returns the object associated with a given name in the declaration
206                 ///   space.  This is the inverse operation of `DefineName'
207                 /// </summary>
208                 public object GetDefinition (string name)
209                 {
210                         return defined_names [name];
211                 }
212                 
213                 bool in_transit = false;
214                 
215                 /// <summary>
216                 ///   This function is used to catch recursive definitions
217                 ///   in declarations.
218                 /// </summary>
219                 public bool InTransit {
220                         get {
221                                 return in_transit;
222                         }
223
224                         set {
225                                 in_transit = value;
226                         }
227                 }
228
229                 public TypeContainer Parent {
230                         get {
231                                 return parent;
232                         }
233                 }
234
235                 /// <summary>
236                 ///   Looks up the alias for the name
237                 /// </summary>
238                 public string LookupAlias (string name)
239                 {
240                         if (NamespaceEntry != null)
241                                 return NamespaceEntry.LookupAlias (name);
242                         else
243                                 return null;
244                 }
245                 
246                 // 
247                 // root_types contains all the types.  All TopLevel types
248                 // hence have a parent that points to `root_types', that is
249                 // why there is a non-obvious test down here.
250                 //
251                 public bool IsTopLevel {
252                         get {
253                                 if (parent != null){
254                                         if (parent.parent == null)
255                                                 return true;
256                                 }
257                                 return false;
258                         }
259                 }
260
261                 public virtual void CloseType ()
262                 {
263                         if (!Created){
264                                 try {
265                                         TypeBuilder.CreateType ();
266                                 } catch {
267                                         //
268                                         // The try/catch is needed because
269                                         // nested enumerations fail to load when they
270                                         // are defined.
271                                         //
272                                         // Even if this is the right order (enumerations
273                                         // declared after types).
274                                         //
275                                         // Note that this still creates the type and
276                                         // it is possible to save it
277                                 }
278                                 Created = true;
279                         }
280                 }
281
282                 /// <remarks>
283                 ///  Should be overriten by the appropriate declaration space
284                 /// </remarks>
285                 public abstract TypeBuilder DefineType ();
286                 
287                 /// <summary>
288                 ///   Define all members, but don't apply any attributes or do anything which may
289                 ///   access not-yet-defined classes.  This method also creates the MemberCache.
290                 /// </summary>
291                 public abstract bool DefineMembers (TypeContainer parent);
292
293                 //
294                 // Whether this is an `unsafe context'
295                 //
296                 public bool UnsafeContext {
297                         get {
298                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
299                                         return true;
300                                 if (parent != null)
301                                         return parent.UnsafeContext;
302                                 return false;
303                         }
304                 }
305
306                 public static string MakeFQN (string nsn, string name)
307                 {
308                         if (nsn == "")
309                                 return name;
310                         return String.Concat (nsn, ".", name);
311                 }
312
313                 EmitContext type_resolve_ec;
314                 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
315                 {
316                         type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
317                         type_resolve_ec.ResolvingTypeTree = true;
318
319                         return type_resolve_ec;
320                 }
321
322                 // <summary>
323                 //    Looks up the type, as parsed into the expression `e' 
324                 // </summary>
325                 public Type ResolveType (Expression e, bool silent, Location loc)
326                 {
327                         if (type_resolve_ec == null)
328                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
329                         type_resolve_ec.loc = loc;
330                         type_resolve_ec.ContainerType = TypeBuilder;
331
332                         int errors = Report.Errors;
333                         Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
334
335                         if (d == null || d.eclass != ExprClass.Type){
336                                 if (!silent && errors == Report.Errors){
337                                         Console.WriteLine ("Type is: " + e.GetType().ToString ());
338                                         Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
339                                 }
340                                 return null;
341                         }
342
343                         if (d is ConstructedType)
344                                 ((ConstructedType) d).ResolveType (type_resolve_ec);
345
346                         if (!CheckAccessLevel (d.Type)) {
347                                 Report. Error (122, loc,  "`" + d.Type + "' " +
348                                        "is inaccessible because of its protection level");
349                                 return null;
350                         }
351
352                         return d.Type;
353                 }
354
355                 // <summary>
356                 //    Resolves the expression `e' for a type, and will recursively define
357                 //    types. 
358                 // </summary>
359                 public Expression ResolveTypeExpr (Expression e, bool silent, Location loc)
360                 {
361                         if (type_resolve_ec == null)
362                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
363                         type_resolve_ec.loc = loc;
364                         type_resolve_ec.ContainerType = TypeBuilder;
365
366                         Expression d = e.ResolveAsTypeTerminal (type_resolve_ec);
367                          
368                         if (d == null || d.eclass != ExprClass.Type){
369                                 if (!silent){
370                                         Report.Error (246, loc, "Cannot find type `"+ e +"'");
371                                 }
372                                 return null;
373                         }
374
375                         return d;
376                 }
377                 
378                 public bool CheckAccessLevel (Type check_type) 
379                 {
380                         if (check_type == TypeBuilder)
381                                 return true;
382
383                         if (check_type.IsGenericParameter)
384                                 return true; // FIXME
385                         
386                         TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
387                         
388                         //
389                         // Broken Microsoft runtime, return public for arrays, no matter what 
390                         // the accessibility is for their underlying class, and they return 
391                         // NonPublic visibility for pointers
392                         //
393                         if (check_type.IsArray || check_type.IsPointer)
394                                 return CheckAccessLevel (TypeManager.GetElementType (check_type));
395
396                         switch (check_attr){
397                         case TypeAttributes.Public:
398                                 return true;
399
400                         case TypeAttributes.NotPublic:
401                                 //
402                                 // This test should probably use the declaringtype.
403                                 //
404                                 if (check_type.Assembly == TypeBuilder.Assembly){
405                                         return true;
406                                 }
407                                 return false;
408                                 
409                         case TypeAttributes.NestedPublic:
410                                 return true;
411
412                         case TypeAttributes.NestedPrivate:
413                                 string check_type_name = check_type.FullName;
414                                 string type_name = TypeBuilder.FullName;
415                                 
416                                 int cio = check_type_name.LastIndexOf ("+");
417                                 string container = check_type_name.Substring (0, cio);
418
419                                 //
420                                 // Check if the check_type is a nested class of the current type
421                                 //
422                                 if (check_type_name.StartsWith (type_name + "+")){
423                                         return true;
424                                 }
425                                 
426                                 if (type_name.StartsWith (container)){
427                                         return true;
428                                 }
429
430                                 return false;
431
432                         case TypeAttributes.NestedFamily:
433                                 //
434                                 // Only accessible to methods in current type or any subtypes
435                                 //
436                                 return FamilyAccessible (check_type);
437
438                         case TypeAttributes.NestedFamANDAssem:
439                                 return (check_type.Assembly == TypeBuilder.Assembly) &&
440                                         FamilyAccessible (check_type);
441
442                         case TypeAttributes.NestedFamORAssem:
443                                 return (check_type.Assembly == TypeBuilder.Assembly) ||
444                                         FamilyAccessible (check_type);
445
446                         case TypeAttributes.NestedAssembly:
447                                 return check_type.Assembly == TypeBuilder.Assembly;
448                         }
449
450                         Console.WriteLine ("HERE: " + check_attr);
451                         return false;
452
453                 }
454
455                 protected bool FamilyAccessible (Type check_type)
456                 {
457                         Type declaring = check_type.DeclaringType;
458                         if (TypeBuilder.IsSubclassOf (declaring))
459                                 return true;
460
461                         string check_type_name = check_type.FullName;
462                         string type_name = TypeBuilder.FullName;
463                         
464                         int cio = check_type_name.LastIndexOf ("+");
465                         string container = check_type_name.Substring (0, cio);
466                         
467                         //
468                         // Check if the check_type is a nested class of the current type
469                         //
470                         if (check_type_name.StartsWith (container + "+"))
471                                 return true;
472
473                         return false;
474                 }
475
476                 // Access level of a type.
477                 enum AccessLevel {
478                         Public                  = 0,
479                         ProtectedInternal       = 1,
480                         Internal                = 2,
481                         Protected               = 3,
482                         Private                 = 4
483                 }
484
485                 // Check whether `flags' denotes a more restricted access than `level'
486                 // and return the new level.
487                 static AccessLevel CheckAccessLevel (AccessLevel level, int flags)
488                 {
489                         AccessLevel old_level = level;
490
491                         if ((flags & Modifiers.INTERNAL) != 0) {
492                                 if ((flags & Modifiers.PROTECTED) != 0) {
493                                         if ((int) level < (int) AccessLevel.ProtectedInternal)
494                                                 level = AccessLevel.ProtectedInternal;
495                                 } else {
496                                         if ((int) level < (int) AccessLevel.Internal)
497                                                 level = AccessLevel.Internal;
498                                 }
499                         } else if ((flags & Modifiers.PROTECTED) != 0) {
500                                 if ((int) level < (int) AccessLevel.Protected)
501                                         level = AccessLevel.Protected;
502                         } else if ((flags & Modifiers.PRIVATE) != 0)
503                                 level = AccessLevel.Private;
504
505                         return level;
506                 }
507
508                 // Return the access level for a new member which is defined in the current
509                 // TypeContainer with access modifiers `flags'.
510                 AccessLevel GetAccessLevel (int flags)
511                 {
512                         if ((flags & Modifiers.PRIVATE) != 0)
513                                 return AccessLevel.Private;
514
515                         AccessLevel level;
516                         if (!IsTopLevel && (Parent != null))
517                                 level = Parent.GetAccessLevel (flags);
518                         else
519                                 level = AccessLevel.Public;
520
521                         return CheckAccessLevel (CheckAccessLevel (level, flags), ModFlags);
522                 }
523
524                 // Return the access level for type `t', but don't give more access than `flags'.
525                 static AccessLevel GetAccessLevel (Type t, int flags)
526                 {
527                         if (((flags & Modifiers.PRIVATE) != 0) || t.IsNestedPrivate)
528                                 return AccessLevel.Private;
529
530                         AccessLevel level;
531                         if (TypeManager.IsBuiltinType (t))
532                                 return AccessLevel.Public;
533                         else if ((t.DeclaringType != null) && (t != t.DeclaringType))
534                                 level = GetAccessLevel (t.DeclaringType, flags);
535                         else {
536                                 level = CheckAccessLevel (AccessLevel.Public, flags);
537                         }
538
539                         if (t.IsNestedPublic)
540                                 return level;
541
542                         if (t.IsNestedAssembly || t.IsNotPublic) {
543                                 if ((int) level < (int) AccessLevel.Internal)
544                                         level = AccessLevel.Internal;
545                         }
546
547                         if (t.IsNestedFamily) {
548                                 if ((int) level < (int) AccessLevel.Protected)
549                                         level = AccessLevel.Protected;
550                         }
551
552                         if (t.IsNestedFamORAssem) {
553                                 if ((int) level < (int) AccessLevel.ProtectedInternal)
554                                         level = AccessLevel.ProtectedInternal;
555                         }
556
557                         return level;
558                 }
559
560                 //
561                 // Returns true if `parent' is as accessible as the flags `flags'
562                 // given for this member.
563                 //
564                 public bool AsAccessible (Type parent, int flags)
565                 {
566                         if (parent.IsGenericParameter)
567                                 return true; // FIXME
568
569                         while (parent.IsArray || parent.IsPointer || parent.IsByRef)
570                                 parent = TypeManager.GetElementType (parent);
571
572                         AccessLevel level = GetAccessLevel (flags);
573                         AccessLevel level2 = GetAccessLevel (parent, flags);
574
575                         return (int) level >= (int) level2;
576                 }
577                 
578                 static DoubleHash dh = new DoubleHash ();
579
580                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
581                 {
582                         DeclSpace parent;
583                         Type t;
584                         object r;
585                         
586                         error = false;
587
588                         if (dh.Lookup (ns, name, out r))
589                                 t = (Type) r;
590                         else {
591                                 if (ns != ""){
592                                         if (Namespace.IsNamespace (ns)){
593                                                 string fullname = (ns != "") ? ns + "." + name : name;
594                                                 t = TypeManager.LookupType (fullname);
595                                         } else
596                                                 t = null;
597                                 } else
598                                         t = TypeManager.LookupType (name);
599                         }
600                         
601                         if (t != null)
602                                 return t;
603
604                         //
605                         // In case we are fed a composite name, normalize it.
606                         //
607                         int p = name.LastIndexOf ('.');
608                         if (p != -1){
609                                 ns = MakeFQN (ns, name.Substring (0, p));
610                                 name = name.Substring (p+1);
611                         }
612                         
613                         parent = RootContext.Tree.LookupByNamespace (ns, name);
614                         if (parent == null)
615                                 return null;
616
617                         t = parent.DefineType ();
618                         dh.Insert (ns, name, t);
619                         if (t == null){
620                                 error = true;
621                                 return null;
622                         }
623                         return t;
624                 }
625
626                 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
627                 {
628                         Report.Error (104, loc,
629                                       String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
630                                                      t1.FullName, t2.FullName));
631                 }
632
633                 /// <summary>
634                 ///   GetType is used to resolve type names at the DeclSpace level.
635                 ///   Use this to lookup class/struct bases, interface bases or 
636                 ///   delegate type references
637                 /// </summary>
638                 ///
639                 /// <remarks>
640                 ///   Contrast this to LookupType which is used inside method bodies to 
641                 ///   lookup types that have already been defined.  GetType is used
642                 ///   during the tree resolution process and potentially define
643                 ///   recursively the type
644                 /// </remarks>
645                 public Type FindType (Location loc, string name)
646                 {
647                         Type t;
648                         bool error;
649
650                         //
651                         // For the case the type we are looking for is nested within this one
652                         // or is in any base class
653                         //
654                         DeclSpace containing_ds = this;
655
656                         while (containing_ds != null){
657                                 Type container_type = containing_ds.TypeBuilder;
658                                 Type current_type = container_type;
659
660                                 while (current_type != null) {
661                                         string pre = current_type.FullName;
662
663                                         t = LookupInterfaceOrClass (pre, name, out error);
664                                         if (error)
665                                                 return null;
666                                 
667                                         if ((t != null) && containing_ds.CheckAccessLevel (t))
668                                                 return t;
669
670                                         current_type = current_type.BaseType;
671                                 }
672                                 containing_ds = containing_ds.Parent;
673                         }
674
675                         //
676                         // Attempt to lookup the class on our namespace and all it's implicit parents
677                         //
678                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
679                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
680                                 if (error)
681                                         return null;
682                                 
683                                 if (t != null) 
684                                         return t;
685                         }
686                         
687                         //
688                         // Attempt to do a direct unqualified lookup
689                         //
690                         t = LookupInterfaceOrClass ("", name, out error);
691                         if (error)
692                                 return null;
693                         
694                         if (t != null)
695                                 return t;
696                         
697                         //
698                         // Attempt to lookup the class on any of the `using'
699                         // namespaces
700                         //
701
702                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
703
704                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
705                                 if (error)
706                                         return null;
707
708                                 if (t != null)
709                                         return t;
710
711                                 //
712                                 // Now check the using clause list
713                                 //
714                                 Type match = null;
715                                 foreach (Namespace using_ns in ns.GetUsingTable ()) {
716                                         match = LookupInterfaceOrClass (using_ns.Name, name, out error);
717                                         if (error)
718                                                 return null;
719
720                                         if (match != null){
721                                                 if (t != null){
722                                                         if (CheckAccessLevel (match)) {
723                                                                 Error_AmbiguousTypeReference (loc, name, t, match);
724                                                                 return null;
725                                                         }
726                                                         continue;
727                                                 }
728                                                 
729                                                 t = match;
730                                         }
731                                 }
732                                 if (t != null)
733                                         return t;
734                         }
735
736                         //Report.Error (246, Location, "Can not find type `"+name+"'");
737                         return null;
738                 }
739
740                 /// <remarks>
741                 ///   This function is broken and not what you're looking for.  It should only
742                 ///   be used while the type is still being created since it doesn't use the cache
743                 ///   and relies on the filter doing the member name check.
744                 /// </remarks>
745                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
746                                                         MemberFilter filter, object criteria);
747
748                 /// <remarks>
749                 ///   If we have a MemberCache, return it.  This property may return null if the
750                 ///   class doesn't have a member cache or while it's still being created.
751                 /// </remarks>
752                 public abstract MemberCache MemberCache {
753                         get;
754                 }
755
756                 //
757                 // Extensions for generics
758                 //
759                 TypeParameter[] type_params;
760
761                 ///
762                 /// Called by the parser to configure the type_parameter_list for this
763                 /// declaration space
764                 ///
765                 public AdditionResult SetParameterInfo (ArrayList type_parameter_list, ArrayList constraints_list)
766                 {
767                         type_params = new TypeParameter [type_parameter_list.Count];
768
769                         //
770                         // Mark this type as Generic
771                         //
772                         IsGeneric = true;
773                         
774                         //
775                         // Register all the names
776                         //
777                         for (int i = 0; i < type_parameter_list.Count; i++) {
778                                 string name = (string) type_parameter_list [i];
779
780                                 AdditionResult res = IsValid (name, name);
781
782                                 if (res != AdditionResult.Success)
783                                         return res;
784
785                                 Constraints constraints = null;
786                                 if (constraints_list != null) {
787                                         foreach (Constraints constraint in constraints_list) {
788                                                 if (constraint.TypeParameter == name) {
789                                                         constraints = constraint;
790                                                         break;
791                                                 }
792                                         }
793                                 }
794
795                                 type_params [i] = new TypeParameter (name, constraints, Location);
796
797                                 DefineName (name, type_params [i]);
798                         }
799
800                         return AdditionResult.Success;
801                 }
802
803                 public TypeParameter[] TypeParameters {
804                         get {
805                                 return type_params;
806                         }
807                 }
808
809                 public TypeParameterExpr LookupGeneric (string name, Location loc)
810                 {
811                         if (TypeParameters != null) {
812                                 foreach (TypeParameter type_param in TypeParameters) {
813                                         if (type_param.Name != name)
814                                                 continue;
815
816                                         return new TypeParameterExpr (type_param, loc);
817                                 }
818                         }
819
820                         if (parent != null)
821                                 return parent.LookupGeneric (name, loc);
822
823                         return null;
824                 }
825         }
826
827         /// <summary>
828         ///   This is a readonly list of MemberInfo's.      
829         /// </summary>
830         public class MemberList : IList {
831                 public readonly IList List;
832                 int count;
833
834                 /// <summary>
835                 ///   Create a new MemberList from the given IList.
836                 /// </summary>
837                 public MemberList (IList list)
838                 {
839                         if (list != null)
840                                 this.List = list;
841                         else
842                                 this.List = new ArrayList ();
843                         count = List.Count;
844                 }
845
846                 /// <summary>
847                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
848                 /// </summary>
849                 public MemberList (IList first, IList second)
850                 {
851                         ArrayList list = new ArrayList ();
852                         list.AddRange (first);
853                         list.AddRange (second);
854                         count = list.Count;
855                         List = list;
856                 }
857
858                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
859
860                 /// <summary>
861                 ///   Cast the MemberList into a MemberInfo[] array.
862                 /// </summary>
863                 /// <remarks>
864                 ///   This is an expensive operation, only use it if it's really necessary.
865                 /// </remarks>
866                 public static explicit operator MemberInfo [] (MemberList list)
867                 {
868                         Timer.StartTimer (TimerType.MiscTimer);
869                         MemberInfo [] result = new MemberInfo [list.Count];
870                         list.CopyTo (result, 0);
871                         Timer.StopTimer (TimerType.MiscTimer);
872                         return result;
873                 }
874
875                 // ICollection
876
877                 public int Count {
878                         get {
879                                 return count;
880                         }
881                 }
882
883                 public bool IsSynchronized {
884                         get {
885                                 return List.IsSynchronized;
886                         }
887                 }
888
889                 public object SyncRoot {
890                         get {
891                                 return List.SyncRoot;
892                         }
893                 }
894
895                 public void CopyTo (Array array, int index)
896                 {
897                         List.CopyTo (array, index);
898                 }
899
900                 // IEnumerable
901
902                 public IEnumerator GetEnumerator ()
903                 {
904                         return List.GetEnumerator ();
905                 }
906
907                 // IList
908
909                 public bool IsFixedSize {
910                         get {
911                                 return true;
912                         }
913                 }
914
915                 public bool IsReadOnly {
916                         get {
917                                 return true;
918                         }
919                 }
920
921                 object IList.this [int index] {
922                         get {
923                                 return List [index];
924                         }
925
926                         set {
927                                 throw new NotSupportedException ();
928                         }
929                 }
930
931                 // FIXME: try to find out whether we can avoid the cast in this indexer.
932                 public MemberInfo this [int index] {
933                         get {
934                                 return (MemberInfo) List [index];
935                         }
936                 }
937
938                 public int Add (object value)
939                 {
940                         throw new NotSupportedException ();
941                 }
942
943                 public void Clear ()
944                 {
945                         throw new NotSupportedException ();
946                 }
947
948                 public bool Contains (object value)
949                 {
950                         return List.Contains (value);
951                 }
952
953                 public int IndexOf (object value)
954                 {
955                         return List.IndexOf (value);
956                 }
957
958                 public void Insert (int index, object value)
959                 {
960                         throw new NotSupportedException ();
961                 }
962
963                 public void Remove (object value)
964                 {
965                         throw new NotSupportedException ();
966                 }
967
968                 public void RemoveAt (int index)
969                 {
970                         throw new NotSupportedException ();
971                 }
972         }
973
974         /// <summary>
975         ///   This interface is used to get all members of a class when creating the
976         ///   member cache.  It must be implemented by all DeclSpace derivatives which
977         ///   want to support the member cache and by TypeHandle to get caching of
978         ///   non-dynamic types.
979         /// </summary>
980         public interface IMemberContainer {
981                 /// <summary>
982                 ///   The name of the IMemberContainer.  This is only used for
983                 ///   debugging purposes.
984                 /// </summary>
985                 string Name {
986                         get;
987                 }
988
989                 /// <summary>
990                 ///   The type of this IMemberContainer.
991                 /// </summary>
992                 Type Type {
993                         get;
994                 }
995
996                 /// <summary>
997                 ///   Returns the IMemberContainer of the parent class or null if this
998                 ///   is an interface or TypeManger.object_type.
999                 ///   This is used when creating the member cache for a class to get all
1000                 ///   members from the parent class.
1001                 /// </summary>
1002                 IMemberContainer Parent {
1003                         get;
1004                 }
1005
1006                 /// <summary>
1007                 ///   Whether this is an interface.
1008                 /// </summary>
1009                 bool IsInterface {
1010                         get;
1011                 }
1012
1013                 /// <summary>
1014                 ///   Returns all members of this class with the corresponding MemberTypes
1015                 ///   and BindingFlags.
1016                 /// </summary>
1017                 /// <remarks>
1018                 ///   When implementing this method, make sure not to return any inherited
1019                 ///   members and check the MemberTypes and BindingFlags properly.
1020                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
1021                 ///   get the BindingFlags (static/non-static,public/non-public) in the
1022                 ///   MemberInfo class, but the cache needs this information.  That's why
1023                 ///   this method is called multiple times with different BindingFlags.
1024                 /// </remarks>
1025                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1026
1027                 /// <summary>
1028                 ///   Return the container's member cache.
1029                 /// </summary>
1030                 MemberCache MemberCache {
1031                         get;
1032                 }
1033         }
1034
1035         /// <summary>
1036         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
1037         ///   member lookups.  It has a member name based hash table; it maps each member
1038         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
1039         ///   and the BindingFlags that were initially used to get it.  The cache contains
1040         ///   all members of the current class and all inherited members.  If this cache is
1041         ///   for an interface types, it also contains all inherited members.
1042         ///
1043         ///   There are two ways to get a MemberCache:
1044         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
1045         ///     use the DeclSpace.MemberCache property.
1046         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1047         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
1048         /// </summary>
1049         public class MemberCache {
1050                 public readonly IMemberContainer Container;
1051                 protected Hashtable member_hash;
1052                 protected Hashtable method_hash;
1053                 protected Hashtable interface_hash;
1054
1055                 /// <summary>
1056                 ///   Create a new MemberCache for the given IMemberContainer `container'.
1057                 /// </summary>
1058                 public MemberCache (IMemberContainer container)
1059                 {
1060                         this.Container = container;
1061
1062                         Timer.IncrementCounter (CounterType.MemberCache);
1063                         Timer.StartTimer (TimerType.CacheInit);
1064
1065                         interface_hash = new Hashtable ();
1066
1067                         // If we have a parent class (we have a parent class unless we're
1068                         // TypeManager.object_type), we deep-copy its MemberCache here.
1069                         if (Container.IsInterface) {
1070                                 MemberCache parent;
1071                                 if (Container.Parent != null)
1072                                         parent = Container.Parent.MemberCache;
1073                                 else
1074                                         parent = TypeHandle.ObjectType.MemberCache;
1075                                 member_hash = SetupCacheForInterface (parent);
1076                         } else if (Container.Parent != null)
1077                                 member_hash = SetupCache (Container.Parent.MemberCache);
1078                         else
1079                                 member_hash = new Hashtable ();
1080
1081                         // If this is neither a dynamic type nor an interface, create a special
1082                         // method cache with all declared and inherited methods.
1083                         Type type = container.Type;
1084                         if (!(type is TypeBuilder) && !type.IsInterface) {
1085                                 method_hash = new Hashtable ();
1086                                 AddMethods (type);
1087                         }
1088
1089                         // Add all members from the current class.
1090                         AddMembers (Container);
1091
1092                         Timer.StopTimer (TimerType.CacheInit);
1093                 }
1094
1095                 /// <summary>
1096                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
1097                 /// </summary>
1098                 Hashtable SetupCache (MemberCache parent)
1099                 {
1100                         Hashtable hash = new Hashtable ();
1101
1102                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1103                         while (it.MoveNext ()) {
1104                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1105                         }
1106                                 
1107                         return hash;
1108                 }
1109
1110                 void AddInterfaces (MemberCache parent)
1111                 {
1112                         foreach (Type iface in parent.interface_hash.Keys) {
1113                                 if (!interface_hash.Contains (iface))
1114                                         interface_hash.Add (iface, true);
1115                         }
1116                 }
1117
1118                 /// <summary>
1119                 ///   Add the contents of `new_hash' to `hash'.
1120                 /// </summary>
1121                 void AddHashtable (Hashtable hash, Hashtable new_hash)
1122                 {
1123                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
1124                         while (it.MoveNext ()) {
1125                                 ArrayList list = (ArrayList) hash [it.Key];
1126                                 if (list != null)
1127                                         list.AddRange ((ArrayList) it.Value);
1128                                 else
1129                                         hash [it.Key] = ((ArrayList) it.Value).Clone ();
1130                         }
1131                 }
1132
1133                 /// <summary>
1134                 ///   Bootstrap the member cache for an interface type.
1135                 ///   Type.GetMembers() won't return any inherited members for interface types,
1136                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
1137                 /// </summary>
1138                 Hashtable SetupCacheForInterface (MemberCache parent)
1139                 {
1140                         Hashtable hash = SetupCache (parent);
1141                         Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1142
1143                         foreach (Type iface in ifaces) {
1144                                 if (interface_hash.Contains (iface))
1145                                         continue;
1146                                 interface_hash.Add (iface, true);
1147
1148                                 IMemberContainer iface_container =
1149                                         TypeManager.LookupMemberContainer (iface);
1150
1151                                 MemberCache iface_cache = iface_container.MemberCache;
1152
1153                                 AddHashtable (hash, iface_cache.member_hash);
1154                                 AddInterfaces (iface_cache);
1155                         }
1156
1157                         return hash;
1158                 }
1159
1160                 /// <summary>
1161                 ///   Add all members from class `container' to the cache.
1162                 /// </summary>
1163                 void AddMembers (IMemberContainer container)
1164                 {
1165                         // We need to call AddMembers() with a single member type at a time
1166                         // to get the member type part of CacheEntry.EntryType right.
1167                         AddMembers (MemberTypes.Constructor, container);
1168                         AddMembers (MemberTypes.Field, container);
1169                         AddMembers (MemberTypes.Method, container);
1170                         AddMembers (MemberTypes.Property, container);
1171                         AddMembers (MemberTypes.Event, container);
1172                         // Nested types are returned by both Static and Instance searches.
1173                         AddMembers (MemberTypes.NestedType,
1174                                     BindingFlags.Static | BindingFlags.Public, container);
1175                         AddMembers (MemberTypes.NestedType,
1176                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1177                 }
1178
1179                 void AddMembers (MemberTypes mt, IMemberContainer container)
1180                 {
1181                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1182                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1183                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1184                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1185                 }
1186
1187                 /// <summary>
1188                 ///   Add all members from class `container' with the requested MemberTypes and
1189                 ///   BindingFlags to the cache.  This method is called multiple times with different
1190                 ///   MemberTypes and BindingFlags.
1191                 /// </summary>
1192                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1193                 {
1194                         MemberList members = container.GetMembers (mt, bf);
1195                         BindingFlags new_bf = (container == Container) ?
1196                                 bf | BindingFlags.DeclaredOnly : bf;
1197
1198                         foreach (MemberInfo member in members) {
1199                                 string name = member.Name;
1200
1201                                 // We use a name-based hash table of ArrayList's.
1202                                 ArrayList list = (ArrayList) member_hash [name];
1203                                 if (list == null) {
1204                                         list = new ArrayList ();
1205                                         member_hash.Add (name, list);
1206                                 }
1207
1208                                 // When this method is called for the current class, the list will
1209                                 // already contain all inherited members from our parent classes.
1210                                 // We cannot add new members in front of the list since this'd be an
1211                                 // expensive operation, that's why the list is sorted in reverse order
1212                                 // (ie. members from the current class are coming last).
1213                                 list.Add (new CacheEntry (container, member, mt, bf));
1214                         }
1215                 }
1216
1217                 /// <summary>
1218                 ///   Add all declared and inherited methods from class `type' to the method cache.
1219                 /// </summary>
1220                 void AddMethods (Type type)
1221                 {
1222                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1223                                     BindingFlags.FlattenHierarchy, type);
1224                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1225                                     BindingFlags.FlattenHierarchy, type);
1226                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1227                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1228                 }
1229
1230                 void AddMethods (BindingFlags bf, Type type)
1231                 {
1232                         MemberInfo [] members = type.GetMethods (bf);
1233
1234                         foreach (MethodBase member in members) {
1235                                 string name = member.Name;
1236
1237                                 // Varargs methods aren't allowed in C# code.
1238                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1239                                         continue;
1240
1241                                 // We use a name-based hash table of ArrayList's.
1242                                 ArrayList list = (ArrayList) method_hash [name];
1243                                 if (list == null) {
1244                                         list = new ArrayList ();
1245                                         method_hash.Add (name, list);
1246                                 }
1247
1248                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1249                                 // sorted so we need to do this check for every member.
1250                                 BindingFlags new_bf = bf;
1251                                 if (member.DeclaringType == type)
1252                                         new_bf |= BindingFlags.DeclaredOnly;
1253
1254                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1255                         }
1256                 }
1257
1258                 /// <summary>
1259                 ///   Compute and return a appropriate `EntryType' magic number for the given
1260                 ///   MemberTypes and BindingFlags.
1261                 /// </summary>
1262                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1263                 {
1264                         EntryType type = EntryType.None;
1265
1266                         if ((mt & MemberTypes.Constructor) != 0)
1267                                 type |= EntryType.Constructor;
1268                         if ((mt & MemberTypes.Event) != 0)
1269                                 type |= EntryType.Event;
1270                         if ((mt & MemberTypes.Field) != 0)
1271                                 type |= EntryType.Field;
1272                         if ((mt & MemberTypes.Method) != 0)
1273                                 type |= EntryType.Method;
1274                         if ((mt & MemberTypes.Property) != 0)
1275                                 type |= EntryType.Property;
1276                         // Nested types are returned by static and instance searches.
1277                         if ((mt & MemberTypes.NestedType) != 0)
1278                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1279
1280                         if ((bf & BindingFlags.Instance) != 0)
1281                                 type |= EntryType.Instance;
1282                         if ((bf & BindingFlags.Static) != 0)
1283                                 type |= EntryType.Static;
1284                         if ((bf & BindingFlags.Public) != 0)
1285                                 type |= EntryType.Public;
1286                         if ((bf & BindingFlags.NonPublic) != 0)
1287                                 type |= EntryType.NonPublic;
1288                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1289                                 type |= EntryType.Declared;
1290
1291                         return type;
1292                 }
1293
1294                 /// <summary>
1295                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1296                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1297                 ///   single member types.
1298                 /// </summary>
1299                 public static bool IsSingleMemberType (MemberTypes mt)
1300                 {
1301                         switch (mt) {
1302                         case MemberTypes.Constructor:
1303                         case MemberTypes.Event:
1304                         case MemberTypes.Field:
1305                         case MemberTypes.Method:
1306                         case MemberTypes.Property:
1307                         case MemberTypes.NestedType:
1308                                 return true;
1309
1310                         default:
1311                                 return false;
1312                         }
1313                 }
1314
1315                 /// <summary>
1316                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1317                 ///   number to speed up the searching process.
1318                 /// </summary>
1319                 [Flags]
1320                 protected enum EntryType {
1321                         None            = 0x000,
1322
1323                         Instance        = 0x001,
1324                         Static          = 0x002,
1325                         MaskStatic      = Instance|Static,
1326
1327                         Public          = 0x004,
1328                         NonPublic       = 0x008,
1329                         MaskProtection  = Public|NonPublic,
1330
1331                         Declared        = 0x010,
1332
1333                         Constructor     = 0x020,
1334                         Event           = 0x040,
1335                         Field           = 0x080,
1336                         Method          = 0x100,
1337                         Property        = 0x200,
1338                         NestedType      = 0x400,
1339
1340                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1341                 }
1342
1343                 protected struct CacheEntry {
1344                         public readonly IMemberContainer Container;
1345                         public readonly EntryType EntryType;
1346                         public readonly MemberInfo Member;
1347
1348                         public CacheEntry (IMemberContainer container, MemberInfo member,
1349                                            MemberTypes mt, BindingFlags bf)
1350                         {
1351                                 this.Container = container;
1352                                 this.Member = member;
1353                                 this.EntryType = GetEntryType (mt, bf);
1354                         }
1355                 }
1356
1357                 /// <summary>
1358                 ///   This is called each time we're walking up one level in the class hierarchy
1359                 ///   and checks whether we can abort the search since we've already found what
1360                 ///   we were looking for.
1361                 /// </summary>
1362                 protected bool DoneSearching (ArrayList list)
1363                 {
1364                         //
1365                         // We've found exactly one member in the current class and it's not
1366                         // a method or constructor.
1367                         //
1368                         if (list.Count == 1 && !(list [0] is MethodBase))
1369                                 return true;
1370
1371                         //
1372                         // Multiple properties: we query those just to find out the indexer
1373                         // name
1374                         //
1375                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1376                                 return true;
1377
1378                         return false;
1379                 }
1380
1381                 /// <summary>
1382                 ///   Looks up members with name `name'.  If you provide an optional
1383                 ///   filter function, it'll only be called with members matching the
1384                 ///   requested member name.
1385                 ///
1386                 ///   This method will try to use the cache to do the lookup if possible.
1387                 ///
1388                 ///   Unlike other FindMembers implementations, this method will always
1389                 ///   check all inherited members - even when called on an interface type.
1390                 ///
1391                 ///   If you know that you're only looking for methods, you should use
1392                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1393                 ///   When doing a method-only search, it'll try to use a special method
1394                 ///   cache (unless it's a dynamic type or an interface) and the returned
1395                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1396                 ///   The lookup process will automatically restart itself in method-only
1397                 ///   search mode if it discovers that it's about to return methods.
1398                 /// </summary>
1399                 ArrayList global = new ArrayList ();
1400                 bool using_global = false;
1401                 
1402                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1403                                                MemberFilter filter, object criteria)
1404                 {
1405                         if (using_global)
1406                                 throw new Exception ();
1407                         
1408                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1409                         bool method_search = mt == MemberTypes.Method;
1410                         // If we have a method cache and we aren't already doing a method-only search,
1411                         // then we restart a method search if the first match is a method.
1412                         bool do_method_search = !method_search && (method_hash != null);
1413
1414                         ArrayList applicable;
1415
1416                         // If this is a method-only search, we try to use the method cache if
1417                         // possible; a lookup in the method cache will return a MemberInfo with
1418                         // the correct ReflectedType for inherited methods.
1419                         
1420                         if (method_search && (method_hash != null))
1421                                 applicable = (ArrayList) method_hash [name];
1422                         else
1423                                 applicable = (ArrayList) member_hash [name];
1424                         
1425                         if (applicable == null)
1426                                 return MemberList.Empty;
1427
1428                         //
1429                         // 32  slots gives 53 rss/54 size
1430                         // 2/4 slots gives 55 rss
1431                         //
1432                         // Strange: from 25,000 calls, only 1,800
1433                         // are above 2.  Why does this impact it?
1434                         //
1435                         global.Clear ();
1436                         using_global = true;
1437
1438                         Timer.StartTimer (TimerType.CachedLookup);
1439
1440                         EntryType type = GetEntryType (mt, bf);
1441
1442                         IMemberContainer current = Container;
1443
1444                         // `applicable' is a list of all members with the given member name `name'
1445                         // in the current class and all its parent classes.  The list is sorted in
1446                         // reverse order due to the way how the cache is initialy created (to speed
1447                         // things up, we're doing a deep-copy of our parent).
1448
1449                         for (int i = applicable.Count-1; i >= 0; i--) {
1450                                 CacheEntry entry = (CacheEntry) applicable [i];
1451
1452                                 // This happens each time we're walking one level up in the class
1453                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1454                                 // the first time this happens (this may already happen in the first
1455                                 // iteration of this loop if there are no members with the name we're
1456                                 // looking for in the current class).
1457                                 if (entry.Container != current) {
1458                                         if (declared_only || DoneSearching (global))
1459                                                 break;
1460
1461                                         current = entry.Container;
1462                                 }
1463
1464                                 // Is the member of the correct type ?
1465                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1466                                         continue;
1467
1468                                 // Is the member static/non-static ?
1469                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1470                                         continue;
1471
1472                                 // Apply the filter to it.
1473                                 if (filter (entry.Member, criteria)) {
1474                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1475                                                 do_method_search = false;
1476                                         global.Add (entry.Member);
1477                                 }
1478                         }
1479
1480                         Timer.StopTimer (TimerType.CachedLookup);
1481
1482                         // If we have a method cache and we aren't already doing a method-only
1483                         // search, we restart in method-only search mode if the first match is
1484                         // a method.  This ensures that we return a MemberInfo with the correct
1485                         // ReflectedType for inherited methods.
1486                         if (do_method_search && (global.Count > 0)){
1487                                 using_global = false;
1488
1489                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1490                         }
1491
1492                         using_global = false;
1493                         MemberInfo [] copy = new MemberInfo [global.Count];
1494                         global.CopyTo (copy);
1495                         return new MemberList (copy);
1496                 }
1497         }
1498 }