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