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