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