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