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