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