2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004-2008 Novell, Inc
15 using System.Collections.Generic;
18 using XmlElement = System.Object;
24 using IKVM.Reflection;
25 using IKVM.Reflection.Emit;
27 using System.Reflection;
28 using System.Reflection.Emit;
31 namespace Mono.CSharp {
34 // Better name would be DottenName
36 public class MemberName {
37 public readonly string Name;
38 public TypeArguments TypeArguments;
40 public readonly MemberName Left;
41 public readonly Location Location;
43 public static readonly MemberName Null = new MemberName ("");
47 private MemberName (MemberName left, string name, bool is_double_colon,
52 this.is_double_colon = is_double_colon;
56 private MemberName (MemberName left, string name, bool is_double_colon,
57 TypeArguments args, Location loc)
58 : this (left, name, is_double_colon, loc)
60 if (args != null && args.Count > 0)
61 this.TypeArguments = args;
64 public MemberName (string name)
65 : this (name, Location.Null)
68 public MemberName (string name, Location loc)
69 : this (null, name, false, loc)
72 public MemberName (string name, TypeArguments args, Location loc)
73 : this (null, name, false, args, loc)
76 public MemberName (MemberName left, string name)
77 : this (left, name, left != null ? left.Location : Location.Null)
80 public MemberName (MemberName left, string name, Location loc)
81 : this (left, name, false, loc)
84 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
85 : this (left, name, false, args, loc)
88 public MemberName (string alias, string name, TypeArguments args, Location loc)
89 : this (new MemberName (alias, loc), name, true, args, loc)
92 public MemberName (MemberName left, MemberName right)
93 : this (left, right, right.Location)
96 public MemberName (MemberName left, MemberName right, Location loc)
97 : this (null, right.Name, false, right.TypeArguments, loc)
99 if (right.is_double_colon)
100 throw new InternalErrorException ("Cannot append double_colon member name");
101 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
105 public string GetName ()
107 return GetName (false);
112 return TypeArguments == null ? 0 : TypeArguments.Count;
116 public bool IsGeneric {
118 if (TypeArguments != null)
120 else if (Left != null)
121 return Left.IsGeneric;
127 public string GetName (bool is_generic)
129 string name = is_generic ? Basename : Name;
131 return Left.GetName (is_generic) + (is_double_colon ? "::" : ".") + name;
136 public ATypeNameExpression GetTypeExpression ()
139 if (TypeArguments != null)
140 return new SimpleName (Name, TypeArguments, Location);
142 return new SimpleName (Name, Location);
145 if (is_double_colon) {
146 if (Left.Left != null)
147 throw new InternalErrorException ("The left side of a :: should be an identifier");
148 return new QualifiedAliasMember (Left.Name, Name, TypeArguments, Location);
151 Expression lexpr = Left.GetTypeExpression ();
152 return new MemberAccess (lexpr, Name, TypeArguments, Location);
155 public MemberName Clone ()
157 MemberName left_clone = Left == null ? null : Left.Clone ();
158 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
161 public string Basename {
163 if (TypeArguments != null)
164 return MakeName (Name, TypeArguments);
169 public string GetSignatureForError ()
171 string append = TypeArguments == null ? "" : "<" + TypeArguments.GetSignatureForError () + ">";
173 return Name + append;
174 string connect = is_double_colon ? "::" : ".";
175 return Left.GetSignatureForError () + connect + Name + append;
178 public override bool Equals (object other)
180 return Equals (other as MemberName);
183 public bool Equals (MemberName other)
187 if (other == null || Name != other.Name)
189 if (is_double_colon != other.is_double_colon)
192 if ((TypeArguments != null) &&
193 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
196 if ((TypeArguments == null) && (other.TypeArguments != null))
200 return other.Left == null;
202 return Left.Equals (other.Left);
205 public override int GetHashCode ()
207 int hash = Name.GetHashCode ();
208 for (MemberName n = Left; n != null; n = n.Left)
209 hash ^= n.Name.GetHashCode ();
213 if (TypeArguments != null)
214 hash ^= TypeArguments.Count << 5;
216 return hash & 0x7FFFFFFF;
219 public int CountTypeArguments {
221 if (TypeArguments != null)
222 return TypeArguments.Count;
223 else if (Left != null)
224 return Left.CountTypeArguments;
230 public static string MakeName (string name, TypeArguments args)
235 return name + "`" + args.Count;
238 public static string MakeName (string name, int count)
240 return name + "`" + count;
244 public class SimpleMemberName
247 public Location Location;
249 public SimpleMemberName (string name, Location loc)
257 /// Base representation for members. This is used to keep track
258 /// of Name, Location and Modifier flags, and handling Attributes.
260 [System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
261 public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
267 protected string cached_name;
268 // TODO: Remove in favor of MemberName
271 if (cached_name == null)
272 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
277 string IMemberDefinition.Name {
279 return member_name.Name;
283 // Is not readonly because of IndexerName attribute
284 private MemberName member_name;
285 public MemberName MemberName {
286 get { return member_name; }
290 /// Modifier flags that the user specified in the source code
292 private Modifiers mod_flags;
293 public Modifiers ModFlags {
296 if ((value & Modifiers.COMPILER_GENERATED) != 0)
297 caching_flags = Flags.IsUsed | Flags.IsAssigned;
304 public virtual ModuleContainer Module {
306 return Parent.Module;
310 public /*readonly*/ TypeContainer Parent;
313 /// Location where this declaration happens
315 public Location Location {
316 get { return member_name.Location; }
320 /// XML documentation comment
322 protected string comment;
325 /// Represents header string for documentation comment
326 /// for each member types.
328 public abstract string DocCommentHeader { get; }
332 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
333 Obsolete = 1 << 1, // Type has obsolete attribute
334 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
335 ClsCompliant = 1 << 3, // Type is CLS Compliant
336 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
337 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
338 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
339 ClsCompliantAttributeFalse = 1 << 7, // Member has CLSCompliant(false)
340 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
341 Excluded = 1 << 9, // Method is conditional
342 MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
344 IsAssigned = 1 << 12, // Field is assigned
345 HasExplicitLayout = 1 << 13,
346 PartialDefinitionExists = 1 << 14, // Set when corresponding partial method definition exists
347 HasStructLayout = 1 << 15 // Has StructLayoutAttribute
351 /// MemberCore flags at first detected then cached
353 internal Flags caching_flags;
355 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
357 this.Parent = parent as TypeContainer;
359 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
360 AddAttributes (attrs, this);
363 protected virtual void SetMemberName (MemberName new_name)
365 member_name = new_name;
369 protected bool CheckAbstractAndExtern (bool has_block)
371 if (Parent.PartialContainer.Kind == MemberKind.Interface)
375 if ((ModFlags & Modifiers.EXTERN) != 0) {
376 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
377 GetSignatureForError ());
381 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
382 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
383 GetSignatureForError ());
387 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
388 if (Compiler.Settings.Version >= LanguageVersion.V_3) {
389 Property.PropertyMethod pm = this as Property.PropertyMethod;
390 if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
393 if (pm != null && pm.Property.AccessorSecond == null) {
394 Report.Error (840, Location,
395 "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
396 GetSignatureForError ());
401 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
402 GetSignatureForError ());
410 protected void CheckProtectedModifier ()
412 if ((ModFlags & Modifiers.PROTECTED) == 0)
415 if (Parent.PartialContainer.Kind == MemberKind.Struct) {
416 Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
417 GetSignatureForError ());
421 if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
422 Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
423 GetSignatureForError ());
427 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
428 !(this is Destructor)) {
429 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
430 GetSignatureForError ());
435 public abstract bool Define ();
437 public virtual string DocComment {
447 // Returns full member name for error message
449 public virtual string GetSignatureForError ()
451 if (Parent == null || Parent.Parent == null)
452 return member_name.GetSignatureForError ();
454 return Parent.GetSignatureForError () + "." + member_name.GetSignatureForError ();
458 /// Base Emit method. This is also entry point for CLS-Compliant verification.
460 public virtual void Emit ()
462 if (!Compiler.Settings.VerifyClsCompliance)
465 VerifyClsCompliance ();
468 public bool IsCompilerGenerated {
470 if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
473 return Parent == null ? false : Parent.IsCompilerGenerated;
477 public bool IsImported {
483 public virtual bool IsUsed {
485 return (caching_flags & Flags.IsUsed) != 0;
489 protected Report Report {
491 return Compiler.Report;
495 public void SetIsUsed ()
497 caching_flags |= Flags.IsUsed;
500 public void SetIsAssigned ()
502 caching_flags |= Flags.IsAssigned;
506 /// Returns instance of ObsoleteAttribute for this MemberCore
508 public virtual ObsoleteAttribute GetAttributeObsolete ()
510 if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
513 caching_flags &= ~Flags.Obsolete_Undetected;
515 if (OptAttributes == null)
518 Attribute obsolete_attr = OptAttributes.Search (Module.PredefinedAttributes.Obsolete);
519 if (obsolete_attr == null)
522 caching_flags |= Flags.Obsolete;
524 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
525 if (obsolete == null)
532 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
534 public virtual void CheckObsoleteness (Location loc)
536 ObsoleteAttribute oa = GetAttributeObsolete ();
538 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
542 // Checks whether the type P is as accessible as this member
544 public bool IsAccessibleAs (TypeSpec p)
547 // if M is private, its accessibility is the same as this declspace.
548 // we already know that P is accessible to T before this method, so we
551 if ((mod_flags & Modifiers.PRIVATE) != 0)
554 while (TypeManager.HasElementType (p))
555 p = TypeManager.GetElementType (p);
557 if (p.IsGenericParameter)
560 for (TypeSpec p_parent; p != null; p = p_parent) {
561 p_parent = p.DeclaringType;
564 foreach (TypeSpec t in p.TypeArguments) {
565 if (!IsAccessibleAs (t))
570 var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
571 if (pAccess == Modifiers.PUBLIC)
574 bool same_access_restrictions = false;
575 for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
576 var al = mc.ModFlags & Modifiers.AccessibilityMask;
578 case Modifiers.INTERNAL:
579 if (al == Modifiers.PRIVATE || al == Modifiers.INTERNAL)
580 same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
584 case Modifiers.PROTECTED:
585 if (al == Modifiers.PROTECTED) {
586 same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
590 if (al == Modifiers.PRIVATE) {
592 // When type is private and any of its parents derives from
593 // protected type then the type is accessible
595 while (mc.Parent != null) {
596 if (mc.Parent.IsBaseTypeDefinition (p_parent))
597 same_access_restrictions = true;
604 case Modifiers.PROTECTED | Modifiers.INTERNAL:
605 if (al == Modifiers.INTERNAL)
606 same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
607 else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
608 same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
610 goto case Modifiers.PROTECTED;
614 case Modifiers.PRIVATE:
616 // Both are private and share same parent
618 if (al == Modifiers.PRIVATE) {
619 var decl = mc.Parent;
621 same_access_restrictions = decl.CurrentType == p_parent;
622 } while (!same_access_restrictions && !decl.IsTopLevel && (decl = decl.Parent) != null);
628 throw new InternalErrorException (al.ToString ());
632 if (!same_access_restrictions)
640 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
642 public override bool IsClsComplianceRequired ()
644 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
645 return (caching_flags & Flags.ClsCompliant) != 0;
647 caching_flags &= ~Flags.ClsCompliance_Undetected;
649 if (HasClsCompliantAttribute) {
650 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
653 caching_flags |= Flags.ClsCompliant;
657 if (Parent.PartialContainer.IsClsComplianceRequired ()) {
658 caching_flags |= Flags.ClsCompliant;
665 public virtual string[] ConditionalConditions ()
671 /// Returns true when MemberCore is exposed from assembly.
673 public bool IsExposedFromAssembly ()
675 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
678 DeclSpace parentContainer = Parent.PartialContainer;
679 while (parentContainer != null && parentContainer.ModFlags != 0) {
680 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
682 parentContainer = parentContainer.Parent;
687 public virtual IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
689 return Parent.LookupExtensionMethod (extensionType, name, arity, ref scope);
692 public virtual FullNamedExpression LookupNamespaceAlias (string name)
694 return Parent.NamespaceEntry.LookupNamespaceAlias (name);
697 public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
699 return Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
703 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
704 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
706 public bool? CLSAttributeValue {
708 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0) {
709 if ((caching_flags & Flags.HasClsCompliantAttribute) == 0)
712 return (caching_flags & Flags.ClsCompliantAttributeFalse) == 0;
715 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
717 if (OptAttributes != null) {
718 Attribute cls_attribute = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
719 if (cls_attribute != null) {
720 caching_flags |= Flags.HasClsCompliantAttribute;
721 if (cls_attribute.GetClsCompliantAttributeValue ())
724 caching_flags |= Flags.ClsCompliantAttributeFalse;
734 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
736 protected bool HasClsCompliantAttribute {
738 return CLSAttributeValue.HasValue;
743 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
745 public virtual bool EnableOverloadChecks (MemberCore overload)
751 /// The main virtual method for CLS-Compliant verifications.
752 /// The method returns true if member is CLS-Compliant and false if member is not
753 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
754 /// and add their extra verifications.
756 protected virtual bool VerifyClsCompliance ()
758 if (HasClsCompliantAttribute) {
759 if (!Module.DeclaringAssembly.HasCLSCompliantAttribute) {
760 Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
761 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
762 Report.Warning (3021, 2, a.Location,
763 "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
764 GetSignatureForError ());
766 Report.Warning (3014, 1, a.Location,
767 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
768 GetSignatureForError ());
773 if (!IsExposedFromAssembly ()) {
774 Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
775 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 ());
779 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
780 if (Parent.Kind == MemberKind.Interface && Parent.IsClsComplianceRequired ()) {
781 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
782 } else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
783 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
789 if (Parent.Parent != null && !Parent.IsClsComplianceRequired ()) {
790 Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
791 Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
792 GetSignatureForError (), Parent.GetSignatureForError ());
796 if (!IsExposedFromAssembly ())
799 if (!Parent.PartialContainer.IsClsComplianceRequired ())
803 if (member_name.Name [0] == '_') {
804 Report.Warning (3008, 1, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
811 // Raised (and passed an XmlElement that contains the comment)
812 // when GenerateDocComment is writing documentation expectedly.
814 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
819 // Returns a string that represents the signature for this
820 // member which should be used in XML documentation.
822 public virtual string GetDocCommentName (DeclSpace ds)
824 if (ds == null || this is DeclSpace)
825 return DocCommentHeader + Name;
827 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
831 // Generates xml doc comments (if any), and if required,
832 // handle warning report.
834 internal virtual void GenerateDocComment (DeclSpace ds)
837 DocUtil.GenerateDocComment (this, ds, Report);
838 } catch (Exception e) {
839 throw new InternalErrorException (this, e);
843 #region IMemberContext Members
845 public virtual CompilerContext Compiler {
846 get { return Parent.Compiler; }
849 public virtual TypeSpec CurrentType {
850 get { return Parent.CurrentType; }
853 public MemberCore CurrentMemberDefinition {
857 public virtual TypeParameter[] CurrentTypeParameters {
861 public virtual bool HasUnresolvedConstraints {
862 get { return false; }
865 public bool IsObsolete {
867 if (GetAttributeObsolete () != null)
870 return Parent == null ? false : Parent.IsObsolete;
874 public bool IsUnsafe {
876 if ((ModFlags & Modifiers.UNSAFE) != 0)
879 return Parent == null ? false : Parent.IsUnsafe;
883 public bool IsStatic {
885 return (ModFlags & Modifiers.STATIC) != 0;
893 // Base member specification. A member specification contains
894 // member details which can alter in the context (e.g. generic instances)
896 public abstract class MemberSpec
899 public enum StateFlags
901 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
902 Obsolete = 1 << 1, // Member has obsolete attribute
903 CLSCompliant_Undetected = 1 << 2, // CLSCompliant attribute has not been detected yet
904 CLSCompliant = 1 << 3, // Member is CLS Compliant
905 MissingDependency_Undetected = 1 << 4,
906 MissingDependency = 1 << 5,
907 HasDynamicElement = 1 << 6,
909 IsAccessor = 1 << 9, // Method is an accessor
910 IsGeneric = 1 << 10, // Member contains type arguments
912 PendingMetaInflate = 1 << 12,
913 PendingMakeMethod = 1 << 13,
914 PendingMemberCacheMembers = 1 << 14,
915 PendingBaseTypeInflate = 1 << 15,
916 InterfacesExpanded = 1 << 16,
917 IsNotRealProperty = 1 << 17,
920 protected Modifiers modifiers;
921 public StateFlags state;
922 protected IMemberDefinition definition;
923 public readonly MemberKind Kind;
924 protected TypeSpec declaringType;
928 public int ID = counter++;
931 protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
934 this.declaringType = declaringType;
935 this.definition = definition;
936 this.modifiers = modifiers;
938 state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected | StateFlags.MissingDependency_Undetected;
943 public virtual int Arity {
949 public TypeSpec DeclaringType {
951 return declaringType;
954 declaringType = value;
958 public IMemberDefinition MemberDefinition {
964 public Modifiers Modifiers {
973 public virtual string Name {
975 return definition.Name;
979 public bool IsAbstract {
980 get { return (modifiers & Modifiers.ABSTRACT) != 0; }
983 public bool IsAccessor {
985 return (state & StateFlags.IsAccessor) != 0;
988 state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
993 // Return true when this member is a generic in C# terms
994 // A nested non-generic type of generic type will return false
996 public bool IsGeneric {
998 return (state & StateFlags.IsGeneric) != 0;
1001 state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
1005 public bool IsPrivate {
1006 get { return (modifiers & Modifiers.PRIVATE) != 0; }
1009 public bool IsPublic {
1010 get { return (modifiers & Modifiers.PUBLIC) != 0; }
1013 public bool IsStatic {
1015 return (modifiers & Modifiers.STATIC) != 0;
1021 public virtual ObsoleteAttribute GetAttributeObsolete ()
1023 if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
1026 state &= ~StateFlags.Obsolete_Undetected;
1028 var oa = definition.GetAttributeObsolete ();
1030 state |= StateFlags.Obsolete;
1036 // Returns a list of missing dependencies of this member. The list
1037 // will contain types only but it can have numerous values for members
1038 // like methods where both return type and all parameters are checked
1040 public List<TypeSpec> GetMissingDependencies ()
1042 if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0)
1045 state &= ~StateFlags.MissingDependency_Undetected;
1047 var imported = definition as ImportedDefinition;
1048 List<TypeSpec> missing;
1049 if (imported != null) {
1050 missing = ResolveMissingDependencies ();
1051 } else if (this is ElementTypeSpec) {
1052 missing = ((ElementTypeSpec) this).Element.GetMissingDependencies ();
1057 if (missing != null) {
1058 state |= StateFlags.MissingDependency;
1064 public abstract List<TypeSpec> ResolveMissingDependencies ();
1066 protected virtual bool IsNotCLSCompliant (out bool attrValue)
1068 var cls = MemberDefinition.CLSAttributeValue;
1069 attrValue = cls ?? false;
1070 return cls == false;
1073 public virtual string GetSignatureForError ()
1075 var bf = MemberDefinition as Property.BackingField;
1076 var name = bf == null ? Name : bf.OriginalName;
1077 return DeclaringType.GetSignatureForError () + "." + name;
1080 public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
1082 var inflated = (MemberSpec) MemberwiseClone ();
1083 inflated.declaringType = inflator.TypeInstance;
1084 if (DeclaringType.IsGenericOrParentIsGeneric)
1085 inflated.state |= StateFlags.PendingMetaInflate;
1087 inflated.ID += 1000000;
1093 // Is this member accessible from invocationType
1095 public bool IsAccessible (TypeSpec invocationType)
1097 var ma = Modifiers & Modifiers.AccessibilityMask;
1098 if (ma == Modifiers.PUBLIC)
1101 var parentType = /* this as TypeSpec ?? */ DeclaringType;
1103 // It's null for module context
1104 if (invocationType == null)
1105 invocationType = InternalType.FakeInternalType;
1108 // If only accessible to the current class or children
1110 if (ma == Modifiers.PRIVATE)
1111 return invocationType.MemberDefinition == parentType.MemberDefinition ||
1112 TypeManager.IsNestedChildOf (invocationType, parentType.MemberDefinition);
1114 if ((ma & Modifiers.INTERNAL) != 0) {
1116 var assembly = invocationType == InternalType.FakeInternalType ?
1117 RootContext.ToplevelTypes.DeclaringAssembly :
1118 invocationType.MemberDefinition.DeclaringAssembly;
1120 if (parentType == null) {
1121 b = ((ITypeDefinition) MemberDefinition).IsInternalAsPublic (assembly);
1123 b = DeclaringType.MemberDefinition.IsInternalAsPublic (assembly);
1126 if (b || ma == Modifiers.INTERNAL)
1131 if (!TypeManager.IsNestedFamilyAccessible (invocationType, parentType))
1138 // Returns member CLS compliance based on full member hierarchy
1140 public bool IsCLSCompliant ()
1142 if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
1143 state &= ~StateFlags.CLSCompliant_Undetected;
1146 if (IsNotCLSCompliant (out compliant))
1150 if (DeclaringType != null) {
1151 compliant = DeclaringType.IsCLSCompliant ();
1153 compliant = ((ITypeDefinition) MemberDefinition).DeclaringAssembly.IsCLSCompliant;
1158 state |= StateFlags.CLSCompliant;
1161 return (state & StateFlags.CLSCompliant) != 0;
1164 public bool IsConditionallyExcluded (Location loc)
1166 if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
1169 var conditions = MemberDefinition.ConditionalConditions ();
1170 if (conditions == null)
1173 foreach (var condition in conditions) {
1174 if (loc.CompilationUnit.IsConditionalDefined (condition))
1181 public override string ToString ()
1183 return GetSignatureForError ();
1188 // Member details which are same between all member
1191 public interface IMemberDefinition
1193 bool? CLSAttributeValue { get; }
1194 string Name { get; }
1195 bool IsImported { get; }
1197 string[] ConditionalConditions ();
1198 ObsoleteAttribute GetAttributeObsolete ();
1199 void SetIsAssigned ();
1203 public interface IParametersMember : IInterfaceMemberSpec
1205 AParametersCollection Parameters { get; }
1208 public interface IInterfaceMemberSpec
1210 TypeSpec MemberType { get; }
1214 // Base type container declaration. It exists to handle partial types
1215 // which share same definition (PartialContainer) but have different
1218 public abstract class DeclSpace : MemberCore {
1220 /// This points to the actual definition that is being
1221 /// created with System.Reflection.Emit
1223 public TypeBuilder TypeBuilder;
1226 // This is the namespace in which this typecontainer
1227 // was declared. We use this to resolve names.
1229 public NamespaceEntry NamespaceEntry;
1231 public readonly string Basename;
1233 protected Dictionary<string, MemberCore> defined_names;
1235 public TypeContainer PartialContainer;
1237 protected readonly bool is_generic;
1238 readonly int count_type_params;
1239 protected TypeParameter[] type_params;
1240 TypeParameter[] type_param_list;
1243 // Whether we are Generic
1245 public bool IsGeneric {
1249 else if (Parent != null)
1250 return Parent.IsGeneric;
1256 static string[] attribute_targets = new string [] { "type" };
1258 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
1260 : base (parent, name, attrs)
1262 NamespaceEntry = ns;
1263 Basename = name.Basename;
1264 defined_names = new Dictionary<string, MemberCore> ();
1265 PartialContainer = null;
1266 if (name.TypeArguments != null) {
1268 count_type_params = name.TypeArguments.Count;
1271 count_type_params += parent.count_type_params;
1275 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
1277 protected virtual bool AddToContainer (MemberCore symbol, string name)
1280 if (!defined_names.TryGetValue (name, out mc)) {
1281 defined_names.Add (name, symbol);
1285 if (((mc.ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
1288 if (symbol.EnableOverloadChecks (mc))
1291 InterfaceMemberBase im = mc as InterfaceMemberBase;
1292 if (im != null && im.IsExplicitImpl)
1295 Report.SymbolRelatedToPreviousError (mc);
1296 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
1297 Error_MissingPartialModifier (symbol);
1301 if (this is ModuleContainer) {
1302 Report.Error (101, symbol.Location,
1303 "The namespace `{0}' already contains a definition for `{1}'",
1304 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
1305 } else if (symbol is TypeParameter) {
1306 Report.Error (692, symbol.Location,
1307 "Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
1309 Report.Error (102, symbol.Location,
1310 "The type `{0}' already contains a definition for `{1}'",
1311 GetSignatureForError (), symbol.MemberName.Name);
1317 protected void RemoveFromContainer (string name)
1319 defined_names.Remove (name);
1323 /// Returns the MemberCore associated with a given name in the declaration
1324 /// space. It doesn't return method based symbols !!
1327 public MemberCore GetDefinition (string name)
1329 MemberCore mc = null;
1330 defined_names.TryGetValue (name, out mc);
1335 // root_types contains all the types. All TopLevel types
1336 // hence have a parent that points to `root_types', that is
1337 // why there is a non-obvious test down here.
1339 public bool IsTopLevel {
1340 get { return (Parent != null && Parent.Parent == null); }
1343 public virtual bool IsUnmanagedType ()
1348 protected abstract TypeAttributes TypeAttr { get; }
1351 /// Should be overriten by the appropriate declaration space
1353 public abstract void DefineType ();
1355 protected void Error_MissingPartialModifier (MemberCore type)
1357 Report.Error (260, type.Location,
1358 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
1359 type.GetSignatureForError ());
1362 public override string GetSignatureForError ()
1364 return MemberName.GetSignatureForError ();
1367 TypeParameter[] initialize_type_params ()
1369 if (type_param_list != null)
1370 return type_param_list;
1372 DeclSpace the_parent = Parent;
1373 if (this is GenericMethod)
1376 var list = new List<TypeParameter> ();
1377 if (the_parent != null && the_parent.IsGeneric) {
1378 // FIXME: move generics info out of DeclSpace
1379 TypeParameter[] parent_params = the_parent.TypeParameters;
1380 list.AddRange (parent_params);
1383 int count = type_params != null ? type_params.Length : 0;
1384 for (int i = 0; i < count; i++) {
1385 TypeParameter param = type_params [i];
1387 if (Parent.CurrentTypeParameters != null) {
1388 foreach (TypeParameter tp in Parent.CurrentTypeParameters) {
1389 if (tp.Name != param.Name)
1392 Report.SymbolRelatedToPreviousError (tp.Location, null);
1393 Report.Warning (693, 3, param.Location,
1394 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1395 param.Name, Parent.GetSignatureForError ());
1400 type_param_list = new TypeParameter [list.Count];
1401 list.CopyTo (type_param_list, 0);
1402 return type_param_list;
1405 public virtual void SetParameterInfo (List<Constraints> constraints_list)
1408 if (constraints_list != null) {
1410 80, Location, "Constraints are not allowed " +
1411 "on non-generic declarations");
1417 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1418 type_params = new TypeParameter [names.Length];
1421 // Register all the names
1423 for (int i = 0; i < type_params.Length; i++) {
1424 TypeParameterName name = names [i];
1426 Constraints constraints = null;
1427 if (constraints_list != null) {
1428 int total = constraints_list.Count;
1429 for (int ii = 0; ii < total; ++ii) {
1430 Constraints constraints_at = (Constraints)constraints_list[ii];
1431 // TODO: it is used by iterators only
1432 if (constraints_at == null) {
1433 constraints_list.RemoveAt (ii);
1437 if (constraints_at.TypeParameter.Value == name.Name) {
1438 constraints = constraints_at;
1439 constraints_list.RemoveAt(ii);
1445 Variance variance = name.Variance;
1446 if (name.Variance != Variance.None && !(this is Delegate || this is Interface)) {
1447 Report.Error (1960, name.Location, "Variant type parameters can only be used with interfaces and delegates");
1448 variance = Variance.None;
1451 type_params [i] = new TypeParameter (
1452 Parent, i, new MemberName (name.Name, Location), constraints, name.OptAttributes, variance);
1454 AddToContainer (type_params [i], name.Name);
1457 if (constraints_list != null && constraints_list.Count > 0) {
1458 foreach (Constraints constraint in constraints_list) {
1459 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1460 GetSignatureForError (), constraint.TypeParameter.Value);
1465 protected TypeParameter[] TypeParameters {
1468 throw new InvalidOperationException ();
1469 if ((PartialContainer != null) && (PartialContainer != this))
1470 return PartialContainer.TypeParameters;
1471 if (type_param_list == null)
1472 initialize_type_params ();
1474 return type_param_list;
1478 public int CountTypeParameters {
1480 return count_type_params;
1484 public override string[] ValidAttributeTargets {
1485 get { return attribute_targets; }
1488 protected override bool VerifyClsCompliance ()
1490 if (!base.VerifyClsCompliance ()) {
1494 if (type_params != null) {
1495 foreach (TypeParameter tp in type_params) {
1496 tp.VerifyClsCompliance ();