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