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