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