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