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