Merge pull request #496 from nicolas-raoul/unit-test-for-issue2907
[mono.git] / mcs / mcs / decl.cs
1 //
2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Marek Safar (marek.safar@seznam.cz)
6 //
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004-2008 Novell, Inc
11 // Copyright 2011 Xamarin Inc
12 //
13 //
14
15 using System;
16 using System.Collections.Generic;
17 using System.Diagnostics;
18 using System.Text;
19 using Mono.CompilerServices.SymbolWriter;
20
21 #if NET_2_1
22 using XmlElement = System.Object;
23 #else
24 using System.Xml;
25 #endif
26
27 #if STATIC
28 using IKVM.Reflection;
29 using IKVM.Reflection.Emit;
30 #else
31 using System.Reflection;
32 using System.Reflection.Emit;
33 #endif
34
35 namespace Mono.CSharp {
36
37         //
38         // Better name would be DottenName
39         //
40         [DebuggerDisplay ("{GetSignatureForError()}")]
41         public class MemberName
42         {
43                 public static readonly MemberName Null = new MemberName ("");
44
45                 public readonly string Name;
46                 public TypeParameters TypeParameters;
47                 public readonly FullNamedExpression ExplicitInterface;
48                 public readonly Location Location;
49
50                 public readonly MemberName Left;
51
52                 public MemberName (string name)
53                         : this (name, Location.Null)
54                 { }
55
56                 public MemberName (string name, Location loc)
57                         : this (null, name, loc)
58                 { }
59
60                 public MemberName (string name, TypeParameters tparams, Location loc)
61                 {
62                         this.Name = name;
63                         this.Location = loc;
64
65                         this.TypeParameters = tparams;
66                 }
67
68                 public MemberName (string name, TypeParameters tparams, FullNamedExpression explicitInterface, Location loc)
69                         : this (name, tparams, loc)
70                 {
71                         this.ExplicitInterface = explicitInterface;
72                 }
73
74                 public MemberName (MemberName left, string name, Location loc)
75                 {
76                         this.Name = name;
77                         this.Location = loc;
78                         this.Left = left;
79                 }
80
81                 public MemberName (MemberName left, string name, FullNamedExpression explicitInterface, Location loc)
82                         : this (left, name, loc)
83                 {
84                         this.ExplicitInterface = explicitInterface;
85                 }
86
87                 public MemberName (MemberName left, MemberName right)
88                 {
89                         this.Name = right.Name;
90                         this.Location = right.Location;
91                         this.TypeParameters = right.TypeParameters;
92                         this.Left = left;
93                 }
94
95                 public int Arity {
96                         get {
97                                 return TypeParameters == null ? 0 : TypeParameters.Count;
98                         }
99                 }
100
101                 public bool IsGeneric {
102                         get {
103                                 return TypeParameters != null;
104                         }
105                 }
106
107                 public string Basename {
108                         get {
109                                 if (TypeParameters != null)
110                                         return MakeName (Name, TypeParameters);
111                                 return Name;
112                         }
113                 }
114
115                 public void CreateMetadataName (StringBuilder sb)
116                 {
117                         if (Left != null)
118                                 Left.CreateMetadataName (sb);
119
120                         if (sb.Length != 0) {
121                                 sb.Append (".");
122                         }
123
124                         sb.Append (Basename);
125                 }
126
127                 public string GetSignatureForDocumentation ()
128                 {
129                         var s = Basename;
130
131                         if (ExplicitInterface != null)
132                                 s = ExplicitInterface.GetSignatureForError () + "." + s;
133
134                         if (Left == null)
135                                 return s;
136
137                         return Left.GetSignatureForDocumentation () + "." + s;
138                 }
139
140                 public string GetSignatureForError ()
141                 {
142                         string s = TypeParameters == null ? null : "<" + TypeParameters.GetSignatureForError () + ">";
143                         s = Name + s;
144
145                         if (ExplicitInterface != null)
146                                 s = ExplicitInterface.GetSignatureForError () + "." + s;
147
148                         if (Left == null)
149                                 return s;
150
151                         return Left.GetSignatureForError () + "." + s;
152                 }
153
154                 public override bool Equals (object other)
155                 {
156                         return Equals (other as MemberName);
157                 }
158
159                 public bool Equals (MemberName other)
160                 {
161                         if (this == other)
162                                 return true;
163                         if (other == null || Name != other.Name)
164                                 return false;
165
166                         if ((TypeParameters != null) &&
167                             (other.TypeParameters == null || TypeParameters.Count != other.TypeParameters.Count))
168                                 return false;
169
170                         if ((TypeParameters == null) && (other.TypeParameters != null))
171                                 return false;
172
173                         if (Left == null)
174                                 return other.Left == null;
175
176                         return Left.Equals (other.Left);
177                 }
178
179                 public override int GetHashCode ()
180                 {
181                         int hash = Name.GetHashCode ();
182                         for (MemberName n = Left; n != null; n = n.Left)
183                                 hash ^= n.Name.GetHashCode ();
184
185                         if (TypeParameters != null)
186                                 hash ^= TypeParameters.Count << 5;
187
188                         return hash & 0x7FFFFFFF;
189                 }
190
191                 public static string MakeName (string name, TypeParameters args)
192                 {
193                         if (args == null)
194                                 return name;
195
196                         return name + "`" + args.Count;
197                 }
198
199                 public static string MakeName (string name, int count)
200                 {
201                         return name + "`" + count;
202                 }
203         }
204
205         public class SimpleMemberName
206         {
207                 public string Value;
208                 public Location Location;
209
210                 public SimpleMemberName (string name, Location loc)
211                 {
212                         this.Value = name;
213                         this.Location = loc;
214                 }
215         }
216
217         /// <summary>
218         ///   Base representation for members.  This is used to keep track
219         ///   of Name, Location and Modifier flags, and handling Attributes.
220         /// </summary>
221         [System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
222         public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
223         {
224                 string IMemberDefinition.Name {
225                         get {
226                                 return member_name.Name;
227                         }
228                 }
229
230                 // Is not readonly because of IndexerName attribute
231                 private MemberName member_name;
232                 public MemberName MemberName {
233                         get { return member_name; }
234                 }
235
236                 /// <summary>
237                 ///   Modifier flags that the user specified in the source code
238                 /// </summary>
239                 private Modifiers mod_flags;
240                 public Modifiers ModFlags {
241                         set {
242                                 mod_flags = value;
243                                 if ((value & Modifiers.COMPILER_GENERATED) != 0)
244                                         caching_flags = Flags.IsUsed | Flags.IsAssigned;
245                         }
246                         get {
247                                 return mod_flags;
248                         }
249                 }
250
251                 public virtual ModuleContainer Module {
252                         get {
253                                 return Parent.Module;
254                         }
255                 }
256
257                 public /*readonly*/ TypeContainer Parent;
258
259                 /// <summary>
260                 ///   Location where this declaration happens
261                 /// </summary>
262                 public Location Location {
263                         get { return member_name.Location; }
264                 }
265
266                 /// <summary>
267                 ///   XML documentation comment
268                 /// </summary>
269                 protected string comment;
270
271                 /// <summary>
272                 ///   Represents header string for documentation comment 
273                 ///   for each member types.
274                 /// </summary>
275                 public abstract string DocCommentHeader { get; }
276
277                 [Flags]
278                 public enum Flags {
279                         Obsolete_Undetected = 1,                // Obsolete attribute has not been detected yet
280                         Obsolete = 1 << 1,                      // Type has obsolete attribute
281                         ClsCompliance_Undetected = 1 << 2,      // CLS Compliance has not been detected yet
282                         ClsCompliant = 1 << 3,                  // Type is CLS Compliant
283                         CloseTypeCreated = 1 << 4,              // Tracks whether we have Closed the type
284                         HasCompliantAttribute_Undetected = 1 << 5,      // Presence of CLSCompliantAttribute has not been detected
285                         HasClsCompliantAttribute = 1 << 6,                      // Type has CLSCompliantAttribute
286                         ClsCompliantAttributeFalse = 1 << 7,                    // Member has CLSCompliant(false)
287                         Excluded_Undetected = 1 << 8,           // Conditional attribute has not been detected yet
288                         Excluded = 1 << 9,                                      // Method is conditional
289                         MethodOverloadsExist = 1 << 10,         // Test for duplication must be performed
290                         IsUsed = 1 << 11,
291                         IsAssigned = 1 << 12,                           // Field is assigned
292                         HasExplicitLayout       = 1 << 13,
293                         PartialDefinitionExists = 1 << 14,      // Set when corresponding partial method definition exists
294                         HasStructLayout = 1 << 15,                      // Has StructLayoutAttribute
295                         HasInstanceConstructor = 1 << 16,
296                         HasUserOperators = 1 << 17,
297                         CanBeReused = 1 << 18
298                 }
299
300                 /// <summary>
301                 ///   MemberCore flags at first detected then cached
302                 /// </summary>
303                 internal Flags caching_flags;
304
305                 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs)
306                 {
307                         this.Parent = parent;
308                         member_name = name;
309                         caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
310                         AddAttributes (attrs, this);
311                 }
312
313                 protected virtual void SetMemberName (MemberName new_name)
314                 {
315                         member_name = new_name;
316                 }
317
318                 public virtual void Accept (StructuralVisitor visitor)
319                 {
320                         visitor.Visit (this);
321                 }
322
323                 protected bool CheckAbstractAndExtern (bool has_block)
324                 {
325                         if (Parent.PartialContainer.Kind == MemberKind.Interface)
326                                 return true;
327
328                         if (has_block) {
329                                 if ((ModFlags & Modifiers.EXTERN) != 0) {
330                                         Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
331                                                 GetSignatureForError ());
332                                         return false;
333                                 }
334
335                                 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
336                                         Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
337                                                 GetSignatureForError ());
338                                         return false;
339                                 }
340                         } else {
341                                 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
342                                         if (Compiler.Settings.Version >= LanguageVersion.V_3) {
343                                                 Property.PropertyMethod pm = this as Property.PropertyMethod;
344                                                 if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
345                                                         pm = null;
346
347                                                 if (pm != null && pm.Property.AccessorSecond == null) {
348                                                         Report.Error (840, Location,
349                                                                 "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
350                                                                 GetSignatureForError ());
351                                                         return false;
352                                                 }
353                                         }
354
355                                         Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
356                                                       GetSignatureForError ());
357                                         return false;
358                                 }
359                         }
360
361                         return true;
362                 }
363
364                 protected void CheckProtectedModifier ()
365                 {
366                         if ((ModFlags & Modifiers.PROTECTED) == 0)
367                                 return;
368
369                         if (Parent.PartialContainer.Kind == MemberKind.Struct) {
370                                 Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
371                                         GetSignatureForError ());
372                                 return;
373                         }
374
375                         if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
376                                 Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
377                                         GetSignatureForError ());
378                                 return;
379                         }
380
381                         if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
382                                 !(this is Destructor)) {
383                                 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
384                                         GetSignatureForError ());
385                                 return;
386                         }
387                 }
388
389                 public abstract bool Define ();
390
391                 public virtual string DocComment {
392                         get {
393                                 return comment;
394                         }
395                         set {
396                                 comment = value;
397                         }
398                 }
399
400                 // 
401                 // Returns full member name for error message
402                 //
403                 public virtual string GetSignatureForError ()
404                 {
405                         var parent = Parent.GetSignatureForError ();
406                         if (parent == null)
407                                 return member_name.GetSignatureForError ();
408
409                         return parent + "." + 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 (!Compiler.Settings.VerifyClsCompliance)
418                                 return;
419
420                         VerifyClsCompliance ();
421                 }
422
423                 public bool IsAvailableForReuse {
424                         get {
425                                 return (caching_flags & Flags.CanBeReused) != 0;
426                         }
427                         set {
428                                 caching_flags = value ? (caching_flags | Flags.CanBeReused) : (caching_flags & ~Flags.CanBeReused);
429                         }
430                 }
431
432                 public bool IsCompilerGenerated {
433                         get     {
434                                 if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
435                                         return true;
436
437                                 return Parent == null ? false : Parent.IsCompilerGenerated;
438                         }
439                 }
440
441                 public bool IsImported {
442                         get {
443                                 return false;
444                         }
445                 }
446
447                 public virtual bool IsUsed {
448                         get {
449                                 return (caching_flags & Flags.IsUsed) != 0;
450                         }
451                 }
452
453                 protected Report Report {
454                         get {
455                                 return Compiler.Report;
456                         }
457                 }
458
459                 public void SetIsUsed ()
460                 {
461                         caching_flags |= Flags.IsUsed;
462                 }
463
464                 public void SetIsAssigned ()
465                 {
466                         caching_flags |= Flags.IsAssigned;
467                 }
468
469                 public virtual void SetConstraints (List<Constraints> constraints_list)
470                 {
471                         var tparams = member_name.TypeParameters;
472                         if (tparams == null) {
473                                 Report.Error (80, Location, "Constraints are not allowed on non-generic declarations");
474                                 return;
475                         }
476
477                         foreach (var c in constraints_list) {
478                                 var tp = tparams.Find (c.TypeParameter.Value);
479                                 if (tp == null) {
480                                         Report.Error (699, c.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
481                                                 GetSignatureForError (), c.TypeParameter.Value);
482                                         continue;
483                                 }
484
485                                 tp.Constraints = c;
486                         }
487                 }
488
489                 /// <summary>
490                 /// Returns instance of ObsoleteAttribute for this MemberCore
491                 /// </summary>
492                 public virtual ObsoleteAttribute GetAttributeObsolete ()
493                 {
494                         if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
495                                 return null;
496
497                         caching_flags &= ~Flags.Obsolete_Undetected;
498
499                         if (OptAttributes == null)
500                                 return null;
501
502                         Attribute obsolete_attr = OptAttributes.Search (Module.PredefinedAttributes.Obsolete);
503                         if (obsolete_attr == null)
504                                 return null;
505
506                         caching_flags |= Flags.Obsolete;
507
508                         ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
509                         if (obsolete == null)
510                                 return null;
511
512                         return obsolete;
513                 }
514
515                 /// <summary>
516                 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
517                 /// </summary>
518                 public virtual void CheckObsoleteness (Location loc)
519                 {
520                         ObsoleteAttribute oa = GetAttributeObsolete ();
521                         if (oa != null)
522                                 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
523                 }
524
525                 //
526                 // Checks whether the type P is as accessible as this member
527                 //
528                 public bool IsAccessibleAs (TypeSpec p)
529                 {
530                         //
531                         // if M is private, its accessibility is the same as this declspace.
532                         // we already know that P is accessible to T before this method, so we
533                         // may return true.
534                         //
535                         if ((mod_flags & Modifiers.PRIVATE) != 0)
536                                 return true;
537
538                         while (TypeManager.HasElementType (p))
539                                 p = TypeManager.GetElementType (p);
540
541                         if (p.IsGenericParameter)
542                                 return true;
543
544                         for (TypeSpec p_parent; p != null; p = p_parent) {
545                                 p_parent = p.DeclaringType;
546
547                                 if (p.IsGeneric) {
548                                         foreach (TypeSpec t in p.TypeArguments) {
549                                                 if (!IsAccessibleAs (t))
550                                                         return false;
551                                         }
552                                 }
553
554                                 var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
555                                 if (pAccess == Modifiers.PUBLIC)
556                                         continue;
557
558                                 bool same_access_restrictions = false;
559                                 for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
560                                         var al = mc.ModFlags & Modifiers.AccessibilityMask;
561                                         switch (pAccess) {
562                                         case Modifiers.INTERNAL:
563                                                 if (al == Modifiers.PRIVATE || al == Modifiers.INTERNAL)
564                                                         same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
565                                                 
566                                                 break;
567
568                                         case Modifiers.PROTECTED:
569                                                 if (al == Modifiers.PROTECTED) {
570                                                         same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent);
571                                                         break;
572                                                 }
573
574                                                 if (al == Modifiers.PRIVATE) {
575                                                         //
576                                                         // When type is private and any of its parents derives from
577                                                         // protected type then the type is accessible
578                                                         //
579                                                         while (mc.Parent != null && mc.Parent.PartialContainer != null) {
580                                                                 if (mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent))
581                                                                         same_access_restrictions = true;
582                                                                 mc = mc.Parent; 
583                                                         }
584                                                 }
585                                                 
586                                                 break;
587
588                                         case Modifiers.PROTECTED | Modifiers.INTERNAL:
589                                                 if (al == Modifiers.INTERNAL)
590                                                         same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
591                                                 else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
592                                                         same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
593                                                 else
594                                                         goto case Modifiers.PROTECTED;
595
596                                                 break;
597
598                                         case Modifiers.PRIVATE:
599                                                 //
600                                                 // Both are private and share same parent
601                                                 //
602                                                 if (al == Modifiers.PRIVATE) {
603                                                         var decl = mc.Parent;
604                                                         do {
605                                                                 same_access_restrictions = decl.CurrentType.MemberDefinition == p_parent.MemberDefinition;
606                                                         } while (!same_access_restrictions && !decl.PartialContainer.IsTopLevel && (decl = decl.Parent) != null);
607                                                 }
608                                                 
609                                                 break;
610                                                 
611                                         default:
612                                                 throw new InternalErrorException (al.ToString ());
613                                         }
614                                 }
615                                 
616                                 if (!same_access_restrictions)
617                                         return false;
618                         }
619
620                         return true;
621                 }
622
623                 /// <summary>
624                 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
625                 /// </summary>
626                 public override bool IsClsComplianceRequired ()
627                 {
628                         if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
629                                 return (caching_flags & Flags.ClsCompliant) != 0;
630
631                         caching_flags &= ~Flags.ClsCompliance_Undetected;
632
633                         if (HasClsCompliantAttribute) {
634                                 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
635                                         return false;
636
637                                 caching_flags |= Flags.ClsCompliant;
638                                 return true;
639                         }
640
641                         if (Parent.IsClsComplianceRequired ()) {
642                                 caching_flags |= Flags.ClsCompliant;
643                                 return true;
644                         }
645
646                         return false;
647                 }
648
649                 public virtual string[] ConditionalConditions ()
650                 {
651                         return null;
652                 }
653
654                 /// <summary>
655                 /// Returns true when MemberCore is exposed from assembly.
656                 /// </summary>
657                 public bool IsExposedFromAssembly ()
658                 {
659                         if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
660                                 return this is NamespaceContainer;
661                         
662                         var parentContainer = Parent.PartialContainer;
663                         while (parentContainer != null) {
664                                 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
665                                         return false;
666
667                                 parentContainer = parentContainer.Parent.PartialContainer;
668                         }
669
670                         return true;
671                 }
672
673                 //
674                 // Does extension methods look up to find a method which matches name and extensionType.
675                 // Search starts from this namespace and continues hierarchically up to top level.
676                 //
677                 public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
678                 {
679                         var m = Parent;
680                         do {
681                                 var ns = m as NamespaceContainer;
682                                 if (ns != null)
683                                         return ns.LookupExtensionMethod (this, extensionType, name, arity, 0);
684
685                                 m = m.Parent;
686                         } while (m != null);
687
688                         return null;
689                 }
690
691                 public virtual FullNamedExpression LookupNamespaceAlias (string name)
692                 {
693                         return Parent.LookupNamespaceAlias (name);
694                 }
695
696                 public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
697                 {
698                         return Parent.LookupNamespaceOrType (name, arity, mode, loc);
699                 }
700
701                 /// <summary>
702                 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
703                 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
704                 /// </summary>
705                 public bool? CLSAttributeValue {
706                         get {
707                                 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0) {
708                                         if ((caching_flags & Flags.HasClsCompliantAttribute) == 0)
709                                                 return null;
710
711                                         return (caching_flags & Flags.ClsCompliantAttributeFalse) == 0;
712                                 }
713
714                                 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
715
716                                 if (OptAttributes != null) {
717                                         Attribute cls_attribute = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
718                                         if (cls_attribute != null) {
719                                                 caching_flags |= Flags.HasClsCompliantAttribute;
720                                                 if (cls_attribute.GetClsCompliantAttributeValue ())
721                                                         return true;
722
723                                                 caching_flags |= Flags.ClsCompliantAttributeFalse;
724                                                 return false;
725                                         }
726                                 }
727
728                                 return null;
729                         }
730                 }
731
732                 /// <summary>
733                 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
734                 /// </summary>
735                 protected bool HasClsCompliantAttribute {
736                         get {
737                                 return CLSAttributeValue.HasValue;
738                         }
739                 }
740
741                 /// <summary>
742                 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
743                 /// </summary>
744                 public virtual bool EnableOverloadChecks (MemberCore overload)
745                 {
746                         return false;
747                 }
748
749                 /// <summary>
750                 /// The main virtual method for CLS-Compliant verifications.
751                 /// The method returns true if member is CLS-Compliant and false if member is not
752                 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
753                 /// and add their extra verifications.
754                 /// </summary>
755                 protected virtual bool VerifyClsCompliance ()
756                 {
757                         if (HasClsCompliantAttribute) {
758                                 if (!Module.DeclaringAssembly.HasCLSCompliantAttribute) {
759                                         Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
760                                         if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
761                                                 Report.Warning (3021, 2, a.Location,
762                                                         "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
763                                                         GetSignatureForError ());
764                                         } else {
765                                                 Report.Warning (3014, 1, a.Location,
766                                                         "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
767                                                         GetSignatureForError ());
768                                         }
769                                         return false;
770                                 }
771
772                                 if (!IsExposedFromAssembly ()) {
773                                         Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
774                                         Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
775                                         return false;
776                                 }
777
778                                 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
779                                         if (Parent is Interface && Parent.IsClsComplianceRequired ()) {
780                                                 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
781                                         } else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
782                                                 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
783                                         }
784
785                                         return false;
786                                 }
787
788                                 if (Parent.Kind != MemberKind.Namespace && Parent.Kind != 0 && !Parent.IsClsComplianceRequired ()) {
789                                         Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
790                                         Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
791                                                 GetSignatureForError (), Parent.GetSignatureForError ());
792                                         return false;
793                                 }
794                         } else {
795                                 if (!IsExposedFromAssembly ())
796                                         return false;
797
798                                 if (!Parent.IsClsComplianceRequired ())
799                                         return false;
800                         }
801
802                         if (member_name.Name [0] == '_') {
803                                 Warning_IdentifierNotCompliant ();
804                         }
805
806                         if (member_name.TypeParameters != null)
807                                 member_name.TypeParameters.VerifyClsCompliance ();
808
809                         return true;
810                 }
811
812                 protected void Warning_IdentifierNotCompliant ()
813                 {
814                         Report.Warning (3008, 1, MemberName.Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError ());
815                 }
816
817                 public virtual string GetCallerMemberName ()
818                 {
819                         return MemberName.Name;
820                 }
821
822                 //
823                 // Returns a string that represents the signature for this 
824                 // member which should be used in XML documentation.
825                 //
826                 public abstract string GetSignatureForDocumentation ();
827
828                 public virtual void GetCompletionStartingWith (string prefix, List<string> results)
829                 {
830                         Parent.GetCompletionStartingWith (prefix, results);
831                 }
832
833                 //
834                 // Generates xml doc comments (if any), and if required,
835                 // handle warning report.
836                 //
837                 internal virtual void GenerateDocComment (DocumentationBuilder builder)
838                 {
839                         if (DocComment == null) {
840                                 if (IsExposedFromAssembly ()) {
841                                         Constructor c = this as Constructor;
842                                         if (c == null || !c.IsDefault ())
843                                                 Report.Warning (1591, 4, Location,
844                                                         "Missing XML comment for publicly visible type or member `{0}'", GetSignatureForError ());
845                                 }
846
847                                 return;
848                         }
849
850                         try {
851                                 builder.GenerateDocumentationForMember (this);
852                         } catch (Exception e) {
853                                 throw new InternalErrorException (this, e);
854                         }
855                 }
856
857                 public virtual void WriteDebugSymbol (MonoSymbolFile file)
858                 {
859                 }
860
861                 #region IMemberContext Members
862
863                 public virtual CompilerContext Compiler {
864                         get {
865                                 return Module.Compiler;
866                         }
867                 }
868
869                 public virtual TypeSpec CurrentType {
870                         get { return Parent.CurrentType; }
871                 }
872
873                 public MemberCore CurrentMemberDefinition {
874                         get { return this; }
875                 }
876
877                 public virtual TypeParameters CurrentTypeParameters {
878                         get { return null; }
879                 }
880
881                 public bool IsObsolete {
882                         get {
883                                 if (GetAttributeObsolete () != null)
884                                         return true;
885
886                                 return Parent == null ? false : Parent.IsObsolete;
887                         }
888                 }
889
890                 public bool IsUnsafe {
891                         get {
892                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
893                                         return true;
894
895                                 return Parent == null ? false : Parent.IsUnsafe;
896                         }
897                 }
898
899                 public bool IsStatic {
900                         get {
901                                 return (ModFlags & Modifiers.STATIC) != 0;
902                         }
903                 }
904
905                 #endregion
906         }
907
908         //
909         // Base member specification. A member specification contains
910         // member details which can alter in the context (e.g. generic instances)
911         //
912         public abstract class MemberSpec
913         {
914                 [Flags]
915                 public enum StateFlags
916                 {
917                         Obsolete_Undetected = 1,        // Obsolete attribute has not been detected yet
918                         Obsolete = 1 << 1,                      // Member has obsolete attribute
919                         CLSCompliant_Undetected = 1 << 2,       // CLSCompliant attribute has not been detected yet
920                         CLSCompliant = 1 << 3,          // Member is CLS Compliant
921                         MissingDependency_Undetected = 1 << 4,
922                         MissingDependency = 1 << 5,
923                         HasDynamicElement = 1 << 6,
924                         ConstraintsChecked = 1 << 7,
925
926                         IsAccessor = 1 << 9,            // Method is an accessor
927                         IsGeneric = 1 << 10,            // Member contains type arguments
928
929                         PendingMetaInflate = 1 << 12,
930                         PendingMakeMethod = 1 << 13,
931                         PendingMemberCacheMembers = 1 << 14,
932                         PendingBaseTypeInflate = 1 << 15,
933                         InterfacesExpanded = 1 << 16,
934                         IsNotCSharpCompatible = 1 << 17,
935                         SpecialRuntimeType = 1 << 18,
936                         InflatedExpressionType = 1 << 19,
937                         InflatedNullableType = 1 << 20,
938                         GenericIterateInterface = 1 << 21,
939                         GenericTask = 1 << 22
940                 }
941
942                 //
943                 // Some flags can be copied directly from other member
944                 //
945                 protected const StateFlags SharedStateFlags =
946                         StateFlags.CLSCompliant | StateFlags.CLSCompliant_Undetected |
947                         StateFlags.Obsolete | StateFlags.Obsolete_Undetected |
948                         StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected |
949                         StateFlags.HasDynamicElement;
950
951                 protected Modifiers modifiers;
952                 public StateFlags state;
953                 protected IMemberDefinition definition;
954                 public readonly MemberKind Kind;
955                 protected TypeSpec declaringType;
956
957 #if DEBUG
958                 static int counter;
959                 public int ID = counter++;
960 #endif
961
962                 protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
963                 {
964                         this.Kind = kind;
965                         this.declaringType = declaringType;
966                         this.definition = definition;
967                         this.modifiers = modifiers;
968
969                         if (kind == MemberKind.MissingType)
970                                 state = StateFlags.MissingDependency;
971                         else
972                                 state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected | StateFlags.MissingDependency_Undetected;
973                 }
974
975                 #region Properties
976
977                 public virtual int Arity {
978                         get {
979                                 return 0;
980                         }
981                 }
982
983                 public TypeSpec DeclaringType {
984                         get {
985                                 return declaringType;
986                         }
987                         set {
988                                 declaringType = value;
989                         }
990                 }
991
992                 public IMemberDefinition MemberDefinition {
993                         get {
994                                 return definition;
995                         }
996                 }
997
998                 public Modifiers Modifiers {
999                         get {
1000                                 return modifiers;
1001                         }
1002                         set {
1003                                 modifiers = value;
1004                         }
1005                 }
1006                 
1007                 public virtual string Name {
1008                         get {
1009                                 return definition.Name;
1010                         }
1011                 }
1012
1013                 public bool IsAbstract {
1014                         get { return (modifiers & Modifiers.ABSTRACT) != 0; }
1015                 }
1016
1017                 public bool IsAccessor {
1018                         get {
1019                                 return (state & StateFlags.IsAccessor) != 0;
1020                         }
1021                         set {
1022                                 state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
1023                         }
1024                 }
1025
1026                 //
1027                 // Return true when this member is a generic in C# terms
1028                 // A nested non-generic type of generic type will return false
1029                 //
1030                 public bool IsGeneric {
1031                         get {
1032                                 return (state & StateFlags.IsGeneric) != 0;
1033                         }
1034                         set {
1035                                 state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
1036                         }
1037                 }
1038
1039                 //
1040                 // Returns true for imported members which are not compatible with C# language
1041                 //
1042                 public bool IsNotCSharpCompatible {
1043                         get {
1044                                 return (state & StateFlags.IsNotCSharpCompatible) != 0;
1045                         }
1046                         set {
1047                                 state = value ? state | StateFlags.IsNotCSharpCompatible : state & ~StateFlags.IsNotCSharpCompatible;
1048                         }
1049                 }
1050
1051                 public bool IsPrivate {
1052                         get { return (modifiers & Modifiers.PRIVATE) != 0; }
1053                 }
1054
1055                 public bool IsPublic {
1056                         get { return (modifiers & Modifiers.PUBLIC) != 0; }
1057                 }
1058
1059                 public bool IsStatic {
1060                         get { 
1061                                 return (modifiers & Modifiers.STATIC) != 0;
1062                         }
1063                 }
1064
1065                 #endregion
1066
1067                 public virtual ObsoleteAttribute GetAttributeObsolete ()
1068                 {
1069                         if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
1070                                 return null;
1071
1072                         state &= ~StateFlags.Obsolete_Undetected;
1073
1074                         var oa = definition.GetAttributeObsolete ();
1075                         if (oa != null)
1076                                 state |= StateFlags.Obsolete;
1077
1078                         return oa;
1079                 }
1080
1081                 //
1082                 // Returns a list of missing dependencies of this member. The list
1083                 // will contain types only but it can have numerous values for members
1084                 // like methods where both return type and all parameters are checked
1085                 //
1086                 public List<TypeSpec> GetMissingDependencies ()
1087                 {
1088                         if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0)
1089                                 return null;
1090
1091                         state &= ~StateFlags.MissingDependency_Undetected;
1092
1093                         var imported = definition as ImportedDefinition;
1094                         List<TypeSpec> missing;
1095                         if (imported != null) {
1096                                 missing = ResolveMissingDependencies ();
1097                         } else if (this is ElementTypeSpec) {
1098                                 missing = ((ElementTypeSpec) this).Element.GetMissingDependencies ();
1099                         } else {
1100                                 missing = null;
1101                         }
1102
1103                         if (missing != null) {
1104                                 state |= StateFlags.MissingDependency;
1105                         }
1106
1107                         return missing;
1108                 }
1109
1110                 public abstract List<TypeSpec> ResolveMissingDependencies ();
1111
1112                 protected virtual bool IsNotCLSCompliant (out bool attrValue)
1113                 {
1114                         var cls = MemberDefinition.CLSAttributeValue;
1115                         attrValue = cls ?? false;
1116                         return cls == false;
1117                 }
1118
1119                 public virtual string GetSignatureForDocumentation ()
1120                 {
1121                         return DeclaringType.GetSignatureForDocumentation () + "." + Name;
1122                 }
1123
1124                 public virtual string GetSignatureForError ()
1125                 {
1126                         var bf = MemberDefinition as Property.BackingField;
1127                         string name;
1128                         if (bf == null) {
1129                                 name = Name;
1130                         } else {
1131                                 name = bf.OriginalProperty.MemberName.Name;
1132                         }
1133
1134                         return DeclaringType.GetSignatureForError () + "." + name;
1135                 }
1136
1137                 public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
1138                 {
1139                         var inflated = (MemberSpec) MemberwiseClone ();
1140                         inflated.declaringType = inflator.TypeInstance;
1141                         if (DeclaringType.IsGenericOrParentIsGeneric)
1142                                 inflated.state |= StateFlags.PendingMetaInflate;
1143 #if DEBUG
1144                         inflated.ID += 1000000;
1145 #endif
1146                         return inflated;
1147                 }
1148
1149                 //
1150                 // Is this member accessible from invocation context
1151                 //
1152                 public bool IsAccessible (IMemberContext ctx)
1153                 {
1154                         var ma = Modifiers & Modifiers.AccessibilityMask;
1155                         if (ma == Modifiers.PUBLIC)
1156                                 return true;
1157
1158                         var parentType = /* this as TypeSpec ?? */ DeclaringType;
1159                         var ctype = ctx.CurrentType;
1160
1161                         if (ma == Modifiers.PRIVATE) {
1162                                 if (ctype == null)
1163                                         return false;
1164                                 //
1165                                 // It's only accessible to the current class or children
1166                                 //
1167                                 if (parentType.MemberDefinition == ctype.MemberDefinition)
1168                                         return true;
1169
1170                                 return TypeManager.IsNestedChildOf (ctype, parentType.MemberDefinition);
1171                         }
1172
1173                         if ((ma & Modifiers.INTERNAL) != 0) {
1174                                 bool b;
1175                                 var assembly = ctype == null ? ctx.Module.DeclaringAssembly : ctype.MemberDefinition.DeclaringAssembly;
1176
1177                                 if (parentType == null) {
1178                                         b = ((ITypeDefinition) MemberDefinition).IsInternalAsPublic (assembly);
1179                                 } else {
1180                                         b = DeclaringType.MemberDefinition.IsInternalAsPublic (assembly);
1181                                 }
1182
1183                                 if (b || ma == Modifiers.INTERNAL)
1184                                         return b;
1185                         }
1186
1187                         //
1188                         // Checks whether `ctype' is a subclass or nested child of `parentType'.
1189                         //
1190                         while (ctype != null) {
1191                                 if (TypeManager.IsFamilyAccessible (ctype, parentType))
1192                                         return true;
1193
1194                                 // Handle nested types.
1195                                 ctype = ctype.DeclaringType;    // TODO: Untested ???
1196                         }
1197
1198                         return false;
1199                 }
1200
1201                 //
1202                 // Returns member CLS compliance based on full member hierarchy
1203                 //
1204                 public bool IsCLSCompliant ()
1205                 {
1206                         if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
1207                                 state &= ~StateFlags.CLSCompliant_Undetected;
1208
1209                                 bool compliant;
1210                                 if (IsNotCLSCompliant (out compliant))
1211                                         return false;
1212
1213                                 if (!compliant) {
1214                                         if (DeclaringType != null) {
1215                                                 compliant = DeclaringType.IsCLSCompliant ();
1216                                         } else {
1217                                                 compliant = ((ITypeDefinition) MemberDefinition).DeclaringAssembly.IsCLSCompliant;
1218                                         }
1219                                 }
1220
1221                                 if (compliant)
1222                                         state |= StateFlags.CLSCompliant;
1223                         }
1224
1225                         return (state & StateFlags.CLSCompliant) != 0;
1226                 }
1227
1228                 public bool IsConditionallyExcluded (IMemberContext ctx, Location loc)
1229                 {
1230                         if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
1231                                 return false;
1232
1233                         var conditions = MemberDefinition.ConditionalConditions ();
1234                         if (conditions == null)
1235                                 return false;
1236
1237                         var m = ctx.CurrentMemberDefinition;
1238                         CompilationSourceFile unit = null;
1239                         while (m != null && unit == null) {
1240                                 unit = m as CompilationSourceFile;
1241                                 m = m.Parent;
1242                         }
1243
1244                         if (unit != null) {
1245                                 foreach (var condition in conditions) {
1246                                         if (unit.IsConditionalDefined (condition))
1247                                                 return false;
1248                                 }
1249                         }
1250
1251                         return true;
1252                 }
1253
1254                 public override string ToString ()
1255                 {
1256                         return GetSignatureForError ();
1257                 }
1258         }
1259
1260         //
1261         // Member details which are same between all member
1262         // specifications
1263         //
1264         public interface IMemberDefinition
1265         {
1266                 bool? CLSAttributeValue { get; }
1267                 string Name { get; }
1268                 bool IsImported { get; }
1269
1270                 string[] ConditionalConditions ();
1271                 ObsoleteAttribute GetAttributeObsolete ();
1272                 void SetIsAssigned ();
1273                 void SetIsUsed ();
1274         }
1275
1276         public interface IParametersMember : IInterfaceMemberSpec
1277         {
1278                 AParametersCollection Parameters { get; }
1279         }
1280
1281         public interface IInterfaceMemberSpec
1282         {
1283                 TypeSpec MemberType { get; }
1284         }
1285 }