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