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