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