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