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