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