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