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