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
16 using System.Collections.Generic;
17 using System.Globalization;
18 using System.Reflection.Emit;
19 using System.Reflection;
22 using XmlElement = System.Object;
27 namespace Mono.CSharp {
30 // Better name would be DottenName
32 public class MemberName {
33 public readonly string Name;
34 public TypeArguments TypeArguments;
36 public readonly MemberName Left;
37 public readonly Location Location;
39 public static readonly MemberName Null = new MemberName ("");
43 private MemberName (MemberName left, string name, bool is_double_colon,
48 this.is_double_colon = is_double_colon;
52 private MemberName (MemberName left, string name, bool is_double_colon,
53 TypeArguments args, Location loc)
54 : this (left, name, is_double_colon, loc)
56 if (args != null && args.Count > 0)
57 this.TypeArguments = args;
60 public MemberName (string name)
61 : this (name, Location.Null)
64 public MemberName (string name, Location loc)
65 : this (null, name, false, loc)
68 public MemberName (string name, TypeArguments args, Location loc)
69 : this (null, name, false, args, loc)
72 public MemberName (MemberName left, string name)
73 : this (left, name, left != null ? left.Location : Location.Null)
76 public MemberName (MemberName left, string name, Location loc)
77 : this (left, name, false, loc)
80 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
81 : this (left, name, false, args, loc)
84 public MemberName (string alias, string name, TypeArguments args, Location loc)
85 : this (new MemberName (alias, loc), name, true, args, loc)
88 public MemberName (MemberName left, MemberName right)
89 : this (left, right, right.Location)
92 public MemberName (MemberName left, MemberName right, Location loc)
93 : this (null, right.Name, false, right.TypeArguments, loc)
95 if (right.is_double_colon)
96 throw new InternalErrorException ("Cannot append double_colon member name");
97 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
101 public string GetName ()
103 return GetName (false);
108 return TypeArguments == null ? 0 : TypeArguments.Count;
112 public bool IsGeneric {
114 if (TypeArguments != null)
116 else if (Left != null)
117 return Left.IsGeneric;
123 public string GetName (bool is_generic)
125 string name = is_generic ? Basename : Name;
127 return Left.GetName (is_generic) + (is_double_colon ? "::" : ".") + name;
132 public ATypeNameExpression GetTypeExpression ()
135 if (TypeArguments != null)
136 return new SimpleName (Name, TypeArguments, Location);
138 return new SimpleName (Name, Location);
141 if (is_double_colon) {
142 if (Left.Left != null)
143 throw new InternalErrorException ("The left side of a :: should be an identifier");
144 return new QualifiedAliasMember (Left.Name, Name, TypeArguments, Location);
147 Expression lexpr = Left.GetTypeExpression ();
148 return new MemberAccess (lexpr, Name, TypeArguments, Location);
151 public MemberName Clone ()
153 MemberName left_clone = Left == null ? null : Left.Clone ();
154 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
157 public string Basename {
159 if (TypeArguments != null)
160 return MakeName (Name, TypeArguments);
165 public string GetSignatureForError ()
167 string append = TypeArguments == null ? "" : "<" + TypeArguments.GetSignatureForError () + ">";
169 return Name + append;
170 string connect = is_double_colon ? "::" : ".";
171 return Left.GetSignatureForError () + connect + Name + append;
174 public override bool Equals (object other)
176 return Equals (other as MemberName);
179 public bool Equals (MemberName other)
183 if (other == null || Name != other.Name)
185 if (is_double_colon != other.is_double_colon)
188 if ((TypeArguments != null) &&
189 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
192 if ((TypeArguments == null) && (other.TypeArguments != null))
196 return other.Left == null;
198 return Left.Equals (other.Left);
201 public override int GetHashCode ()
203 int hash = Name.GetHashCode ();
204 for (MemberName n = Left; n != null; n = n.Left)
205 hash ^= n.Name.GetHashCode ();
209 if (TypeArguments != null)
210 hash ^= TypeArguments.Count << 5;
212 return hash & 0x7FFFFFFF;
215 public int CountTypeArguments {
217 if (TypeArguments != null)
218 return TypeArguments.Count;
219 else if (Left != null)
220 return Left.CountTypeArguments;
226 public static string MakeName (string name, TypeArguments args)
231 return name + "`" + args.Count;
234 public static string MakeName (string name, int count)
236 return name + "`" + count;
240 public class SimpleMemberName
243 public Location Location;
245 public SimpleMemberName (string name, Location loc)
253 /// Base representation for members. This is used to keep track
254 /// of Name, Location and Modifier flags, and handling Attributes.
256 [System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
257 public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
263 protected string cached_name;
264 // TODO: Remove in favor of MemberName
267 if (cached_name == null)
268 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
273 string IMemberDefinition.Name {
275 return member_name.Name;
279 // Is not readonly because of IndexerName attribute
280 private MemberName member_name;
281 public MemberName MemberName {
282 get { return member_name; }
286 /// Modifier flags that the user specified in the source code
288 private Modifiers mod_flags;
289 public Modifiers ModFlags {
292 if ((value & Modifiers.COMPILER_GENERATED) != 0)
293 caching_flags = Flags.IsUsed | Flags.IsAssigned;
300 public /*readonly*/ TypeContainer Parent;
303 /// Location where this declaration happens
305 public Location Location {
306 get { return member_name.Location; }
310 /// XML documentation comment
312 protected string comment;
315 /// Represents header string for documentation comment
316 /// for each member types.
318 public abstract string DocCommentHeader { get; }
322 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
323 Obsolete = 1 << 1, // Type has obsolete attribute
324 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
325 ClsCompliant = 1 << 3, // Type is CLS Compliant
326 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
327 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
328 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
329 ClsCompliantAttributeFalse = 1 << 7, // Member has CLSCompliant(false)
330 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
331 Excluded = 1 << 9, // Method is conditional
332 MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
334 IsAssigned = 1 << 12, // Field is assigned
335 HasExplicitLayout = 1 << 13,
336 PartialDefinitionExists = 1 << 14, // Set when corresponding partial method definition exists
337 HasStructLayout = 1 << 15 // Has StructLayoutAttribute
341 /// MemberCore flags at first detected then cached
343 internal Flags caching_flags;
345 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
347 this.Parent = parent as TypeContainer;
349 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
350 AddAttributes (attrs, this);
353 public virtual Assembly Assembly {
354 get { return Parent.Module.Assembly; }
357 protected virtual void SetMemberName (MemberName new_name)
359 member_name = new_name;
363 protected bool CheckAbstractAndExtern (bool has_block)
365 if (Parent.PartialContainer.Kind == MemberKind.Interface)
369 if ((ModFlags & Modifiers.EXTERN) != 0) {
370 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
371 GetSignatureForError ());
375 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
376 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
377 GetSignatureForError ());
381 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
382 if (RootContext.Version >= LanguageVersion.V_3) {
383 Property.PropertyMethod pm = this as Property.PropertyMethod;
384 if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
387 if (pm != null && pm.Property.AccessorSecond == null) {
388 Report.Error (840, Location,
389 "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
390 GetSignatureForError ());
395 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
396 GetSignatureForError ());
404 protected void CheckProtectedModifier ()
406 if ((ModFlags & Modifiers.PROTECTED) == 0)
409 if (Parent.PartialContainer.Kind == MemberKind.Struct) {
410 Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
411 GetSignatureForError ());
415 if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
416 Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
417 GetSignatureForError ());
421 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
422 !(this is Destructor)) {
423 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
424 GetSignatureForError ());
429 public abstract bool Define ();
431 public virtual string DocComment {
441 // Returns full member name for error message
443 public virtual string GetSignatureForError ()
445 if (Parent == null || Parent.Parent == null)
446 return member_name.GetSignatureForError ();
448 return Parent.GetSignatureForError () + "." + member_name.GetSignatureForError ();
452 /// Base Emit method. This is also entry point for CLS-Compliant verification.
454 public virtual void Emit ()
456 if (!RootContext.VerifyClsCompliance)
459 VerifyClsCompliance ();
462 public bool IsCompilerGenerated {
464 if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
467 return Parent == null ? false : Parent.IsCompilerGenerated;
471 public bool IsImported {
477 public virtual bool IsUsed {
479 return (caching_flags & Flags.IsUsed) != 0;
483 protected Report Report {
485 return Compiler.Report;
489 public void SetIsUsed ()
491 caching_flags |= Flags.IsUsed;
494 public void SetIsAssigned ()
496 caching_flags |= Flags.IsAssigned;
500 /// Returns instance of ObsoleteAttribute for this MemberCore
502 public virtual ObsoleteAttribute GetAttributeObsolete ()
504 if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
507 caching_flags &= ~Flags.Obsolete_Undetected;
509 if (OptAttributes == null)
512 Attribute obsolete_attr = OptAttributes.Search (PredefinedAttributes.Get.Obsolete);
513 if (obsolete_attr == null)
516 caching_flags |= Flags.Obsolete;
518 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
519 if (obsolete == null)
526 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
528 public virtual void CheckObsoleteness (Location loc)
530 ObsoleteAttribute oa = GetAttributeObsolete ();
532 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
536 // Checks whether the type P is as accessible as this member
538 public bool IsAccessibleAs (TypeSpec p)
541 // if M is private, its accessibility is the same as this declspace.
542 // we already know that P is accessible to T before this method, so we
545 if ((mod_flags & Modifiers.PRIVATE) != 0)
548 while (TypeManager.HasElementType (p))
549 p = TypeManager.GetElementType (p);
551 if (p.IsGenericParameter)
554 for (TypeSpec p_parent; p != null; p = p_parent) {
555 p_parent = p.DeclaringType;
558 foreach (TypeSpec t in p.TypeArguments) {
559 if (!IsAccessibleAs (t))
564 var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
565 if (pAccess == Modifiers.PUBLIC)
568 bool same_access_restrictions = false;
569 for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
570 var al = mc.ModFlags & Modifiers.AccessibilityMask;
572 case Modifiers.INTERNAL:
573 if (al == Modifiers.PRIVATE || al == Modifiers.INTERNAL)
574 same_access_restrictions = TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, p.Assembly);
578 case Modifiers.PROTECTED:
579 if (al == Modifiers.PROTECTED) {
580 same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
584 if (al == Modifiers.PRIVATE) {
586 // When type is private and any of its parents derives from
587 // protected type then the type is accessible
589 while (mc.Parent != null) {
590 if (mc.Parent.IsBaseTypeDefinition (p_parent))
591 same_access_restrictions = true;
598 case Modifiers.PROTECTED | Modifiers.INTERNAL:
599 if (al == Modifiers.INTERNAL)
600 same_access_restrictions = TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, p.Assembly);
601 else if (al == Modifiers.PROTECTED)
602 same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
603 else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
604 same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent) &&
605 TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, p.Assembly);
608 case Modifiers.PRIVATE:
610 // Both are private and share same parent
612 if (al == Modifiers.PRIVATE) {
613 var decl = mc.Parent;
615 same_access_restrictions = decl.CurrentType == p_parent;
616 } while (!same_access_restrictions && !decl.IsTopLevel && (decl = decl.Parent) != null);
622 throw new InternalErrorException (al.ToString ());
626 if (!same_access_restrictions)
634 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
636 public override bool IsClsComplianceRequired ()
638 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
639 return (caching_flags & Flags.ClsCompliant) != 0;
641 caching_flags &= ~Flags.ClsCompliance_Undetected;
643 if (HasClsCompliantAttribute) {
644 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
647 caching_flags |= Flags.ClsCompliant;
651 if (Parent.PartialContainer.IsClsComplianceRequired ()) {
652 caching_flags |= Flags.ClsCompliant;
659 public virtual string[] ConditionalConditions ()
665 /// Returns true when MemberCore is exposed from assembly.
667 public bool IsExposedFromAssembly ()
669 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
672 DeclSpace parentContainer = Parent.PartialContainer;
673 while (parentContainer != null && parentContainer.ModFlags != 0) {
674 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
676 parentContainer = parentContainer.Parent;
681 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
683 return Parent.LookupExtensionMethod (extensionType, name, arity, loc);
686 public virtual FullNamedExpression LookupNamespaceAlias (string name)
688 return Parent.NamespaceEntry.LookupNamespaceAlias (name);
691 public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
693 return Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
697 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
698 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
700 public bool IsNotCLSCompliant ()
702 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
703 return (caching_flags & Flags.ClsCompliantAttributeFalse) != 0;
705 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
707 if (OptAttributes != null) {
708 Attribute cls_attribute = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
709 if (cls_attribute != null) {
710 caching_flags |= Flags.HasClsCompliantAttribute;
711 if (cls_attribute.GetClsCompliantAttributeValue ())
714 caching_flags |= Flags.ClsCompliantAttributeFalse;
723 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
725 protected bool HasClsCompliantAttribute {
727 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) != 0)
728 IsNotCLSCompliant ();
730 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
735 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
737 public virtual bool EnableOverloadChecks (MemberCore overload)
743 /// The main virtual method for CLS-Compliant verifications.
744 /// The method returns true if member is CLS-Compliant and false if member is not
745 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
746 /// and add their extra verifications.
748 protected virtual bool VerifyClsCompliance ()
750 if (HasClsCompliantAttribute) {
751 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
752 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
753 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
754 Report.Warning (3021, 2, a.Location,
755 "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
756 GetSignatureForError ());
758 Report.Warning (3014, 1, a.Location,
759 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
760 GetSignatureForError ());
765 if (!IsExposedFromAssembly ()) {
766 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
767 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 ());
771 if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
772 if (Parent.Kind == MemberKind.Interface && Parent.IsClsComplianceRequired ()) {
773 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
774 } else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
775 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
781 if (Parent.Parent != null && !Parent.IsClsComplianceRequired ()) {
782 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
783 Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
784 GetSignatureForError (), Parent.GetSignatureForError ());
788 if (!IsExposedFromAssembly ())
791 if (!Parent.PartialContainer.IsClsComplianceRequired ())
795 if (member_name.Name [0] == '_') {
796 Report.Warning (3008, 1, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
803 // Raised (and passed an XmlElement that contains the comment)
804 // when GenerateDocComment is writing documentation expectedly.
806 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
811 // Returns a string that represents the signature for this
812 // member which should be used in XML documentation.
814 public virtual string GetDocCommentName (DeclSpace ds)
816 if (ds == null || this is DeclSpace)
817 return DocCommentHeader + Name;
819 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
823 // Generates xml doc comments (if any), and if required,
824 // handle warning report.
826 internal virtual void GenerateDocComment (DeclSpace ds)
829 DocUtil.GenerateDocComment (this, ds, Report);
830 } catch (Exception e) {
831 throw new InternalErrorException (this, e);
835 #region IMemberContext Members
837 public virtual CompilerContext Compiler {
838 get { return Parent.Compiler; }
841 public virtual TypeSpec CurrentType {
842 get { return Parent.CurrentType; }
845 public MemberCore CurrentMemberDefinition {
849 public virtual TypeParameter[] CurrentTypeParameters {
853 public virtual bool HasUnresolvedConstraints {
854 get { return false; }
857 public bool IsObsolete {
859 if (GetAttributeObsolete () != null)
862 return Parent == null ? false : Parent.IsObsolete;
866 public bool IsUnsafe {
868 if ((ModFlags & Modifiers.UNSAFE) != 0)
871 return Parent == null ? false : Parent.IsUnsafe;
875 public bool IsStatic {
877 return (ModFlags & Modifiers.STATIC) != 0;
885 // Base member specification. A member specification contains
886 // member details which can alter in the context (e.g. generic instances)
888 public abstract class MemberSpec
891 protected enum StateFlags
893 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
894 Obsolete = 1 << 1, // Member has obsolete attribute
895 CLSCompliant_Undetected = 1 << 3, // CLSCompliant attribute has not been detected yet
896 CLSCompliant = 1 << 4, // Member is CLS Compliant
898 IsAccessor = 1 << 9, // Method is an accessor
899 IsGeneric = 1 << 10, // Member contains type arguments
901 PendingMetaInflate = 1 << 12,
902 PendingMakeMethod = 1 << 13,
903 PendingMemberCacheMembers = 1 << 14,
904 PendingBaseTypeInflate = 1 << 15,
905 InterfacesExpanded = 1 << 16,
906 IsNotRealProperty = 1 << 17,
909 protected Modifiers modifiers;
910 protected StateFlags state;
911 protected IMemberDefinition definition;
912 public readonly MemberKind Kind;
913 protected TypeSpec declaringType;
917 public int ID = counter++;
920 protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
923 this.declaringType = declaringType;
924 this.definition = definition;
925 this.modifiers = modifiers;
927 state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected;
932 public Assembly Assembly {
934 return definition.Assembly;
938 public virtual int Arity {
944 public TypeSpec DeclaringType {
946 return declaringType;
949 declaringType = value;
953 public IMemberDefinition MemberDefinition {
959 public Modifiers Modifiers {
968 public virtual string Name {
970 return definition.Name;
974 public bool IsAbstract {
975 get { return (modifiers & Modifiers.ABSTRACT) != 0; }
978 public bool IsAccessor {
980 return (state & StateFlags.IsAccessor) != 0;
983 state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
988 // Return true when this member is a generic in C# terms
989 // A nested non-generic type of generic type will return false
991 public bool IsGeneric {
993 return (state & StateFlags.IsGeneric) != 0;
996 state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
1000 public bool IsPrivate {
1001 get { return (modifiers & Modifiers.PRIVATE) != 0; }
1004 public bool IsPublic {
1005 get { return (modifiers & Modifiers.PUBLIC) != 0; }
1008 public bool IsStatic {
1010 return (modifiers & Modifiers.STATIC) != 0;
1016 public virtual ObsoleteAttribute GetAttributeObsolete ()
1018 if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
1021 state &= ~StateFlags.Obsolete_Undetected;
1023 var oa = definition.GetAttributeObsolete ();
1025 state |= StateFlags.Obsolete;
1030 protected virtual bool IsNotCLSCompliant ()
1032 return MemberDefinition.IsNotCLSCompliant ();
1035 public virtual string GetSignatureForError ()
1037 var bf = MemberDefinition as Property.BackingField;
1038 var name = bf == null ? Name : bf.OriginalName;
1039 return DeclaringType.GetSignatureForError () + "." + name;
1042 public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
1044 var inflated = (MemberSpec) MemberwiseClone ();
1045 inflated.declaringType = inflator.TypeInstance;
1046 inflated.state |= StateFlags.PendingMetaInflate;
1048 if (inflated.ID > 0)
1049 inflated.ID = -inflated.ID;
1055 // Is this member accessible from invocationType
1057 public bool IsAccessible (TypeSpec invocationType)
1059 var ma = Modifiers & Modifiers.AccessibilityMask;
1060 if (ma == Modifiers.PUBLIC)
1063 var parentType = /* this as TypeSpec ?? */ DeclaringType;
1066 // If only accessible to the current class or children
1068 if (ma == Modifiers.PRIVATE)
1069 return invocationType.MemberDefinition == parentType.MemberDefinition ||
1070 TypeManager.IsNestedChildOf (invocationType, parentType);
1072 if ((ma & Modifiers.INTERNAL) != 0) {
1073 var b = TypeManager.IsThisOrFriendAssembly (invocationType == InternalType.FakeInternalType ?
1074 CodeGen.Assembly.Builder : invocationType.Assembly, parentType.Assembly);
1075 if (b || ma == Modifiers.INTERNAL)
1080 if (!TypeManager.IsNestedFamilyAccessible (invocationType, parentType))
1087 // Returns member CLS compliance based on full member hierarchy
1089 public bool IsCLSCompliant ()
1091 if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
1092 state &= ~StateFlags.CLSCompliant_Undetected;
1094 if (IsNotCLSCompliant ())
1098 if (DeclaringType != null) {
1099 compliant = DeclaringType.IsCLSCompliant ();
1101 // TODO: NEED AssemblySpec
1102 if (MemberDefinition.IsImported) {
1103 var attr = MemberDefinition.Assembly.GetCustomAttributes (typeof (CLSCompliantAttribute), false);
1104 compliant = attr.Length > 0 && ((CLSCompliantAttribute) attr[0]).IsCompliant;
1106 compliant = CodeGen.Assembly.IsClsCompliant;
1111 state |= StateFlags.CLSCompliant;
1114 return (state & StateFlags.CLSCompliant) != 0;
1117 public bool IsConditionallyExcluded (Location loc)
1119 if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
1122 var conditions = MemberDefinition.ConditionalConditions ();
1123 if (conditions == null)
1126 foreach (var condition in conditions) {
1127 if (loc.CompilationUnit.IsConditionalDefined (condition))
1134 public override string ToString ()
1136 return GetSignatureForError ();
1141 // Member details which are same between all member
1144 public interface IMemberDefinition
1146 Assembly Assembly { get; }
1147 string Name { get; }
1148 bool IsImported { get; }
1150 string[] ConditionalConditions ();
1151 ObsoleteAttribute GetAttributeObsolete ();
1152 bool IsNotCLSCompliant ();
1153 void SetIsAssigned ();
1157 public interface IParametersMember : IInterfaceMemberSpec
1159 AParametersCollection Parameters { get; }
1162 public interface IInterfaceMemberSpec
1164 TypeSpec MemberType { get; }
1168 // Base type container declaration. It exists to handle partial types
1169 // which share same definition (PartialContainer) but have different
1172 public abstract class DeclSpace : MemberCore {
1174 /// This points to the actual definition that is being
1175 /// created with System.Reflection.Emit
1177 public TypeBuilder TypeBuilder;
1180 // This is the namespace in which this typecontainer
1181 // was declared. We use this to resolve names.
1183 public NamespaceEntry NamespaceEntry;
1185 private Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
1187 public readonly string Basename;
1189 protected Dictionary<string, MemberCore> defined_names;
1191 public TypeContainer PartialContainer;
1193 protected readonly bool is_generic;
1194 readonly int count_type_params;
1195 protected TypeParameter[] type_params;
1196 TypeParameter[] type_param_list;
1199 // Whether we are Generic
1201 public bool IsGeneric {
1205 else if (Parent != null)
1206 return Parent.IsGeneric;
1212 static string[] attribute_targets = new string [] { "type" };
1214 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
1216 : base (parent, name, attrs)
1218 NamespaceEntry = ns;
1219 Basename = name.Basename;
1220 defined_names = new Dictionary<string, MemberCore> ();
1221 PartialContainer = null;
1222 if (name.TypeArguments != null) {
1224 count_type_params = name.TypeArguments.Count;
1227 count_type_params += parent.count_type_params;
1231 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
1233 protected virtual bool AddToContainer (MemberCore symbol, string name)
1236 if (!defined_names.TryGetValue (name, out mc)) {
1237 defined_names.Add (name, symbol);
1241 if (((mc.ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
1244 if (symbol.EnableOverloadChecks (mc))
1247 InterfaceMemberBase im = mc as InterfaceMemberBase;
1248 if (im != null && im.IsExplicitImpl)
1251 Report.SymbolRelatedToPreviousError (mc);
1252 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
1253 Error_MissingPartialModifier (symbol);
1257 if (this is ModuleContainer) {
1258 Report.Error (101, symbol.Location,
1259 "The namespace `{0}' already contains a definition for `{1}'",
1260 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
1261 } else if (symbol is TypeParameter) {
1262 Report.Error (692, symbol.Location,
1263 "Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
1265 Report.Error (102, symbol.Location,
1266 "The type `{0}' already contains a definition for `{1}'",
1267 GetSignatureForError (), symbol.MemberName.Name);
1273 protected void RemoveFromContainer (string name)
1275 defined_names.Remove (name);
1279 /// Returns the MemberCore associated with a given name in the declaration
1280 /// space. It doesn't return method based symbols !!
1283 public MemberCore GetDefinition (string name)
1285 MemberCore mc = null;
1286 defined_names.TryGetValue (name, out mc);
1291 // root_types contains all the types. All TopLevel types
1292 // hence have a parent that points to `root_types', that is
1293 // why there is a non-obvious test down here.
1295 public bool IsTopLevel {
1296 get { return (Parent != null && Parent.Parent == null); }
1299 public virtual bool IsUnmanagedType ()
1304 protected virtual TypeAttributes TypeAttr {
1305 get { return Module.DefaultCharSetType; }
1309 /// Should be overriten by the appropriate declaration space
1311 public abstract TypeBuilder DefineType ();
1313 protected void Error_MissingPartialModifier (MemberCore type)
1315 Report.Error (260, type.Location,
1316 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
1317 type.GetSignatureForError ());
1320 public override string GetSignatureForError ()
1322 return MemberName.GetSignatureForError ();
1325 public bool CheckAccessLevel (TypeSpec check_type)
1327 // TODO: Use this instead
1328 // return PartialContainer.Definition.IsAccessible (check_type);
1330 TypeSpec tb = PartialContainer.Definition;
1331 check_type = check_type.GetDefinition ();
1333 var check_attr = check_type.Modifiers & Modifiers.AccessibilityMask;
1335 switch (check_attr){
1336 case Modifiers.PUBLIC:
1339 case Modifiers.INTERNAL:
1340 return TypeManager.IsThisOrFriendAssembly (Assembly, check_type.Assembly);
1342 case Modifiers.PRIVATE:
1343 TypeSpec declaring = check_type.DeclaringType;
1344 return tb == declaring.GetDefinition () || TypeManager.IsNestedChildOf (tb, declaring);
1346 case Modifiers.PROTECTED:
1348 // Only accessible to methods in current type or any subtypes
1350 return TypeManager.IsNestedFamilyAccessible (tb, check_type.DeclaringType);
1352 case Modifiers.PROTECTED | Modifiers.INTERNAL:
1353 if (TypeManager.IsThisOrFriendAssembly (Assembly, check_type.Assembly))
1356 goto case Modifiers.PROTECTED;
1359 throw new NotImplementedException (check_attr.ToString ());
1362 private TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
1364 // TODO: GenericMethod only
1365 if (PartialContainer == null)
1368 // Has any nested type
1369 // Does not work, because base type can have
1370 //if (PartialContainer.Types == null)
1373 var container = PartialContainer.CurrentType;
1375 // Is not Root container
1376 if (container == null)
1379 var t = MemberCache.FindNestedType (container, name, arity);
1383 // FIXME: Breaks error reporting
1384 if (!t.IsAccessible (CurrentType))
1391 // Public function used to locate types.
1393 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1395 // Returns: Type or null if they type can not be found.
1397 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
1399 FullNamedExpression e;
1400 if (arity == 0 && Cache.TryGetValue (name, out e))
1404 int errors = Report.Errors;
1407 TypeParameter[] tp = CurrentTypeParameters;
1409 TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
1411 e = new TypeParameterExpr (tparam, Location.Null);
1416 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
1419 e = new TypeExpression (t, Location.Null);
1420 else if (Parent != null)
1421 e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
1423 e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
1426 // TODO MemberCache: How to cache arity stuff ?
1427 if (errors == Report.Errors && arity == 0)
1433 public override Assembly Assembly {
1434 get { return Module.Assembly; }
1437 public virtual ModuleContainer Module {
1438 get { return Parent.Module; }
1441 TypeParameter[] initialize_type_params ()
1443 if (type_param_list != null)
1444 return type_param_list;
1446 DeclSpace the_parent = Parent;
1447 if (this is GenericMethod)
1450 var list = new List<TypeParameter> ();
1451 if (the_parent != null && the_parent.IsGeneric) {
1452 // FIXME: move generics info out of DeclSpace
1453 TypeParameter[] parent_params = the_parent.TypeParameters;
1454 list.AddRange (parent_params);
1457 int count = type_params != null ? type_params.Length : 0;
1458 for (int i = 0; i < count; i++) {
1459 TypeParameter param = type_params [i];
1461 if (Parent.CurrentTypeParameters != null) {
1462 foreach (TypeParameter tp in Parent.CurrentTypeParameters) {
1463 if (tp.Name != param.Name)
1466 Report.SymbolRelatedToPreviousError (tp.Location, null);
1467 Report.Warning (693, 3, param.Location,
1468 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1469 param.Name, Parent.GetSignatureForError ());
1474 type_param_list = new TypeParameter [list.Count];
1475 list.CopyTo (type_param_list, 0);
1476 return type_param_list;
1479 public virtual void SetParameterInfo (List<Constraints> constraints_list)
1482 if (constraints_list != null) {
1484 80, Location, "Constraints are not allowed " +
1485 "on non-generic declarations");
1491 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1492 type_params = new TypeParameter [names.Length];
1495 // Register all the names
1497 for (int i = 0; i < type_params.Length; i++) {
1498 TypeParameterName name = names [i];
1500 Constraints constraints = null;
1501 if (constraints_list != null) {
1502 int total = constraints_list.Count;
1503 for (int ii = 0; ii < total; ++ii) {
1504 Constraints constraints_at = (Constraints)constraints_list[ii];
1505 // TODO: it is used by iterators only
1506 if (constraints_at == null) {
1507 constraints_list.RemoveAt (ii);
1511 if (constraints_at.TypeParameter.Value == name.Name) {
1512 constraints = constraints_at;
1513 constraints_list.RemoveAt(ii);
1519 Variance variance = name.Variance;
1520 if (name.Variance != Variance.None && !(this is Delegate || this is Interface)) {
1521 Report.Error (1960, name.Location, "Variant type parameters can only be used with interfaces and delegates");
1522 variance = Variance.None;
1525 type_params [i] = new TypeParameter (
1526 Parent, i, new MemberName (name.Name, Location), constraints, name.OptAttributes, variance);
1528 AddToContainer (type_params [i], name.Name);
1531 if (constraints_list != null && constraints_list.Count > 0) {
1532 foreach (Constraints constraint in constraints_list) {
1533 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1534 GetSignatureForError (), constraint.TypeParameter.Value);
1539 protected TypeParameter[] TypeParameters {
1542 throw new InvalidOperationException ();
1543 if ((PartialContainer != null) && (PartialContainer != this))
1544 return PartialContainer.TypeParameters;
1545 if (type_param_list == null)
1546 initialize_type_params ();
1548 return type_param_list;
1552 public int CountTypeParameters {
1554 return count_type_params;
1558 public override string[] ValidAttributeTargets {
1559 get { return attribute_targets; }
1562 protected override bool VerifyClsCompliance ()
1564 if (!base.VerifyClsCompliance ()) {
1568 if (type_params != null) {
1569 foreach (TypeParameter tp in type_params) {
1570 tp.VerifyClsCompliance ();