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