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