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