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