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