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