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