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