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