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