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