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