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