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