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