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 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
12 // TODO: Move the method verification stuff from the class.cs and interface.cs here
17 using System.Collections;
18 using System.Globalization;
19 using System.Reflection.Emit;
20 using System.Reflection;
22 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
23 using XmlElement = System.Object;
28 namespace Mono.CSharp {
30 public class MemberName {
31 public readonly string Name;
32 public readonly TypeArguments TypeArguments;
34 public readonly MemberName Left;
35 public readonly Location Location;
37 public static readonly MemberName Null = new MemberName ("");
41 private MemberName (MemberName left, string name, bool is_double_colon,
46 this.is_double_colon = is_double_colon;
50 private MemberName (MemberName left, string name, bool is_double_colon,
51 TypeArguments args, Location loc)
52 : this (left, name, is_double_colon, loc)
54 if (args != null && args.Count > 0)
55 this.TypeArguments = args;
58 public MemberName (string name)
59 : this (name, Location.Null)
62 public MemberName (string name, Location loc)
63 : this (null, name, false, loc)
66 public MemberName (string name, TypeArguments args, Location loc)
67 : this (null, name, false, args, loc)
70 public MemberName (MemberName left, string name)
71 : this (left, name, left != null ? left.Location : Location.Null)
74 public MemberName (MemberName left, string name, Location loc)
75 : this (left, name, false, loc)
78 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
79 : this (left, name, false, args, loc)
82 public MemberName (string alias, string name, TypeArguments args, Location loc)
83 : this (new MemberName (alias, loc), name, true, args, loc)
86 public MemberName (MemberName left, MemberName right)
87 : this (left, right, right.Location)
90 public MemberName (MemberName left, MemberName right, Location loc)
91 : this (null, right.Name, false, right.TypeArguments, loc)
93 if (right.is_double_colon)
94 throw new InternalErrorException ("Cannot append double_colon member name");
95 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
98 public string GetName ()
100 return GetName (false);
103 public bool IsGeneric {
105 if (TypeArguments != null)
107 else if (Left != null)
108 return Left.IsGeneric;
114 public string GetName (bool is_generic)
116 string name = is_generic ? Basename : Name;
117 string connect = is_double_colon ? "::" : ".";
119 return Left.GetName (is_generic) + connect + name;
124 public string GetTypeName ()
126 string connect = is_double_colon ? "::" : ".";
128 return Left.GetTypeName () + connect + MakeName (Name, TypeArguments);
130 return MakeName (Name, TypeArguments);
133 public Expression GetTypeExpression ()
136 if (TypeArguments != null)
137 return new SimpleName (Basename, TypeArguments, Location);
139 return new SimpleName (Name, Location);
142 if (is_double_colon) {
143 if (Left.Left != null)
144 throw new InternalErrorException ("The left side of a :: should be an identifier");
145 return new QualifiedAliasMember (Left.Name, Basename, Location);
148 Expression lexpr = Left.GetTypeExpression ();
149 return new MemberAccess (lexpr, Name, TypeArguments, Location);
152 public MemberName Clone ()
154 MemberName left_clone = Left == null ? null : Left.Clone ();
155 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
158 public string Basename {
160 if (TypeArguments != null)
161 return MakeName (Name, TypeArguments);
167 public string FullName {
169 if (TypeArguments != null)
170 return Name + "<" + TypeArguments + ">";
176 public string MethodName {
178 string connect = is_double_colon ? "::" : ".";
180 return Left.FullName + connect + Name;
186 public string GetSignatureForError ()
188 if (TypeArguments != null)
189 return MethodName + "<" + TypeArguments.GetSignatureForError () + ">";
194 public override bool Equals (object other)
196 return Equals (other as MemberName);
199 public bool Equals (MemberName other)
203 if (other == null || Name != other.Name)
205 if (is_double_colon != other.is_double_colon)
208 if ((TypeArguments != null) &&
209 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
212 if ((TypeArguments == null) && (other.TypeArguments != null))
216 return other.Left == null;
218 return Left.Equals (other.Left);
221 public override int GetHashCode ()
223 int hash = Name.GetHashCode ();
224 for (MemberName n = Left; n != null; n = n.Left)
225 hash ^= n.Name.GetHashCode ();
229 if (TypeArguments != null)
230 hash ^= TypeArguments.Count << 5;
232 return hash & 0x7FFFFFFF;
235 public int CountTypeArguments {
237 if (TypeArguments != null)
238 return TypeArguments.Count;
239 else if (Left != null)
240 return Left.CountTypeArguments;
246 public static string MakeName (string name, TypeArguments args)
251 return name + "`" + args.Count;
254 public static string MakeName (string name, int count)
256 return name + "`" + count;
261 /// Base representation for members. This is used to keep track
262 /// of Name, Location and Modifier flags, and handling Attributes.
264 public abstract class MemberCore : Attributable, IResolveContext {
269 protected string cached_name;
272 if (cached_name == null)
273 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
278 // Is not readonly because of IndexerName attribute
279 private MemberName member_name;
280 public MemberName MemberName {
281 get { return member_name; }
285 /// Modifier flags that the user specified in the source code
287 private int mod_flags;
288 public int ModFlags {
291 if ((value & Modifiers.COMPILER_GENERATED) != 0)
292 caching_flags = Flags.IsUsed | Flags.IsAssigned;
299 public /*readonly*/ DeclSpace Parent;
302 /// Location where this declaration happens
304 public Location Location {
305 get { return member_name.Location; }
309 /// XML documentation comment
311 protected string comment;
314 /// Represents header string for documentation comment
315 /// for each member types.
317 public abstract string DocCommentHeader { get; }
321 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
322 Obsolete = 1 << 1, // Type has obsolete attribute
323 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
324 ClsCompliant = 1 << 3, // Type is CLS Compliant
325 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
326 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
327 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
328 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
329 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
330 Excluded = 1 << 9, // Method is conditional
331 MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
333 IsAssigned = 1 << 12, // Field is assigned
334 HasExplicitLayout = 1 << 13,
335 PartialDefinitionExists = 1 << 14 // Set when corresponding partial method definition exists
339 /// MemberCore flags at first detected then cached
341 internal Flags caching_flags;
343 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
346 this.Parent = parent;
348 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
351 protected virtual void SetMemberName (MemberName new_name)
353 member_name = new_name;
357 protected bool CheckAbstractAndExtern (bool has_block)
359 if (Parent.PartialContainer.Kind == Kind.Interface)
363 if ((ModFlags & Modifiers.EXTERN) != 0) {
364 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
365 GetSignatureForError ());
369 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
370 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
371 GetSignatureForError ());
375 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0) {
376 if (RootContext.Version >= LanguageVersion.LINQ && this is Property.PropertyMethod) {
377 Report.Error (840, Location, "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
378 GetSignatureForError ());
380 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
381 GetSignatureForError ());
390 public abstract bool Define ();
392 public virtual string DocComment {
402 // Returns full member name for error message
404 public virtual string GetSignatureForError ()
406 if (Parent == null || Parent.Parent == null)
407 return member_name.GetSignatureForError ();
409 return Parent.GetSignatureForError () + "." + member_name.GetSignatureForError ();
413 /// Base Emit method. This is also entry point for CLS-Compliant verification.
415 public virtual void Emit ()
417 if (!RootContext.VerifyClsCompliance)
420 VerifyClsCompliance ();
423 public virtual bool IsUsed {
424 get { return (caching_flags & Flags.IsUsed) != 0; }
427 public void SetMemberIsUsed ()
429 caching_flags |= Flags.IsUsed;
433 /// Returns instance of ObsoleteAttribute for this MemberCore
435 public virtual ObsoleteAttribute GetObsoleteAttribute ()
437 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
438 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
442 caching_flags &= ~Flags.Obsolete_Undetected;
444 if (OptAttributes == null)
447 Attribute obsolete_attr = OptAttributes.Search (
448 TypeManager.obsolete_attribute_type);
449 if (obsolete_attr == null)
452 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
453 if (obsolete == null)
456 caching_flags |= Flags.Obsolete;
461 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
463 public virtual void CheckObsoleteness (Location loc)
466 Parent.CheckObsoleteness (loc);
468 ObsoleteAttribute oa = GetObsoleteAttribute ();
473 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
477 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
479 public override bool IsClsComplianceRequired ()
481 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
482 return (caching_flags & Flags.ClsCompliant) != 0;
484 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
485 caching_flags &= ~Flags.ClsCompliance_Undetected;
486 caching_flags |= Flags.ClsCompliant;
490 caching_flags &= ~Flags.ClsCompliance_Undetected;
495 /// Returns true when MemberCore is exposed from assembly.
497 public bool IsExposedFromAssembly ()
499 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
502 DeclSpace parentContainer = Parent;
503 while (parentContainer != null && parentContainer.ModFlags != 0) {
504 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
506 parentContainer = parentContainer.Parent;
512 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
513 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
515 public virtual bool GetClsCompliantAttributeValue ()
517 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
518 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
520 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
522 if (OptAttributes != null) {
523 Attribute cls_attribute = OptAttributes.Search (
524 TypeManager.cls_compliant_attribute_type);
525 if (cls_attribute != null) {
526 caching_flags |= Flags.HasClsCompliantAttribute;
527 bool value = cls_attribute.GetClsCompliantAttributeValue ();
529 caching_flags |= Flags.ClsCompliantAttributeTrue;
534 // It's null for TypeParameter
538 if (Parent.GetClsCompliantAttributeValue ()) {
539 caching_flags |= Flags.ClsCompliantAttributeTrue;
546 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
548 protected bool HasClsCompliantAttribute {
550 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) != 0)
551 GetClsCompliantAttributeValue ();
553 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
558 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
560 public virtual bool EnableOverloadChecks (MemberCore overload)
566 /// The main virtual method for CLS-Compliant verifications.
567 /// The method returns true if member is CLS-Compliant and false if member is not
568 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
569 /// and add their extra verifications.
571 protected virtual bool VerifyClsCompliance ()
573 if (!IsClsComplianceRequired ()) {
574 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
575 if (!IsExposedFromAssembly ())
576 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
577 if (!CodeGen.Assembly.IsClsCompliant)
578 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
583 if (HasClsCompliantAttribute) {
584 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
585 Report.Error (3014, Location,
586 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
587 GetSignatureForError ());
591 if (!Parent.IsClsComplianceRequired ()) {
592 Report.Warning (3018, 1, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
593 GetSignatureForError (), Parent.GetSignatureForError ());
598 if (member_name.Name [0] == '_') {
599 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
605 // Raised (and passed an XmlElement that contains the comment)
606 // when GenerateDocComment is writing documentation expectedly.
608 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
613 // Returns a string that represents the signature for this
614 // member which should be used in XML documentation.
616 public virtual string GetDocCommentName (DeclSpace ds)
618 if (ds == null || this is DeclSpace)
619 return DocCommentHeader + Name;
621 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
625 // Generates xml doc comments (if any), and if required,
626 // handle warning report.
628 internal virtual void GenerateDocComment (DeclSpace ds)
631 DocUtil.GenerateDocComment (this, ds);
632 } catch (Exception e) {
633 throw new InternalErrorException (this, e);
637 public override IResolveContext ResolveContext {
641 #region IResolveContext Members
643 public DeclSpace DeclContainer {
644 get { return Parent; }
647 public virtual DeclSpace GenericDeclContainer {
648 get { return DeclContainer; }
651 public bool IsInObsoleteScope {
653 if (GetObsoleteAttribute () != null)
656 return Parent == null ? false : Parent.IsInObsoleteScope;
660 public bool IsInUnsafeScope {
662 if ((ModFlags & Modifiers.UNSAFE) != 0)
665 return Parent == null ? false : Parent.IsInUnsafeScope;
673 /// Base class for structs, classes, enumerations and interfaces.
676 /// They all create new declaration spaces. This
677 /// provides the common foundation for managing those name
680 public abstract class DeclSpace : MemberCore {
682 /// This points to the actual definition that is being
683 /// created with System.Reflection.Emit
685 public TypeBuilder TypeBuilder;
688 /// If we are a generic type, this is the type we are
689 /// currently defining. We need to lookup members on this
690 /// instead of the TypeBuilder.
692 public Type CurrentType;
695 // This is the namespace in which this typecontainer
696 // was declared. We use this to resolve names.
698 public NamespaceEntry NamespaceEntry;
700 private Hashtable Cache = new Hashtable ();
702 public readonly string Basename;
704 protected Hashtable defined_names;
706 public TypeContainer PartialContainer;
708 readonly bool is_generic;
709 readonly int count_type_params;
710 readonly int count_current_type_params;
713 // Whether we are Generic
715 public bool IsGeneric {
719 else if (Parent != null)
720 return Parent.IsGeneric;
726 static string[] attribute_targets = new string [] { "type" };
728 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
730 : base (parent, name, attrs)
733 Basename = name.Basename;
734 defined_names = new Hashtable ();
735 PartialContainer = null;
736 if (name.TypeArguments != null) {
738 count_type_params = count_current_type_params = name.TypeArguments.Count;
741 count_type_params += parent.count_type_params;
744 public override DeclSpace GenericDeclContainer {
749 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
751 protected virtual bool AddToContainer (MemberCore symbol, string name)
753 MemberCore mc = (MemberCore) defined_names [name];
756 defined_names.Add (name, symbol);
760 if (symbol.EnableOverloadChecks (mc))
763 Report.SymbolRelatedToPreviousError (mc);
764 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
765 Error_MissingPartialModifier (symbol);
769 if (this is RootTypes) {
770 Report.Error (101, symbol.Location,
771 "The namespace `{0}' already contains a definition for `{1}'",
772 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
773 } else if (symbol is TypeParameter) {
774 Report.Error (692, symbol.Location,
775 "Duplicate type parameter `{0}'", name);
777 Report.Error (102, symbol.Location,
778 "The type `{0}' already contains a definition for `{1}'",
779 GetSignatureForError (), symbol.MemberName.Name);
786 /// Returns the MemberCore associated with a given name in the declaration
787 /// space. It doesn't return method based symbols !!
790 public MemberCore GetDefinition (string name)
792 return (MemberCore)defined_names [name];
795 public bool IsStaticClass {
796 get { return (ModFlags & Modifiers.STATIC) != 0; }
800 // root_types contains all the types. All TopLevel types
801 // hence have a parent that points to `root_types', that is
802 // why there is a non-obvious test down here.
804 public bool IsTopLevel {
805 get { return (Parent != null && Parent.Parent == null); }
808 public virtual void CloseType ()
810 if ((caching_flags & Flags.CloseTypeCreated) == 0){
812 TypeBuilder.CreateType ();
815 // The try/catch is needed because
816 // nested enumerations fail to load when they
819 // Even if this is the right order (enumerations
820 // declared after types).
822 // Note that this still creates the type and
823 // it is possible to save it
825 caching_flags |= Flags.CloseTypeCreated;
829 protected virtual TypeAttributes TypeAttr {
830 get { return CodeGen.Module.DefaultCharSetType; }
834 /// Should be overriten by the appropriate declaration space
836 public abstract TypeBuilder DefineType ();
839 /// Define all members, but don't apply any attributes or do anything which may
840 /// access not-yet-defined classes. This method also creates the MemberCache.
842 public virtual bool DefineMembers ()
844 if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
845 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
851 protected void Error_MissingPartialModifier (MemberCore type)
853 Report.Error (260, type.Location,
854 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
855 type.GetSignatureForError ());
858 public override string GetSignatureForError ()
861 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
863 // Parent.GetSignatureForError
867 public bool CheckAccessLevel (Type check_type)
870 if (this is GenericMethod)
871 tb = Parent.TypeBuilder;
875 check_type = TypeManager.DropGenericTypeArguments (check_type);
876 if (check_type == tb)
879 if (TypeBuilder == null)
880 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
881 // However, this is invoked again later -- so safe to return true.
882 // May also be null when resolving top-level attributes.
886 // Broken Microsoft runtime, return public for arrays, no matter what
887 // the accessibility is for their underlying class, and they return
888 // NonPublic visibility for pointers
890 if (check_type.IsArray || check_type.IsPointer)
891 return CheckAccessLevel (TypeManager.GetElementType (check_type));
893 if (TypeManager.IsGenericParameter(check_type))
894 return true; // FIXME
896 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
899 case TypeAttributes.Public:
902 case TypeAttributes.NotPublic:
904 if (TypeBuilder == null)
905 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
906 // However, this is invoked again later -- so safe to return true.
907 // May also be null when resolving top-level attributes.
910 // This test should probably use the declaringtype.
912 return check_type.Assembly == TypeBuilder.Assembly ||
913 TypeManager.IsFriendAssembly (check_type.Assembly);
915 case TypeAttributes.NestedPublic:
918 case TypeAttributes.NestedPrivate:
919 return NestedAccessible (tb, check_type);
921 case TypeAttributes.NestedFamily:
923 // Only accessible to methods in current type or any subtypes
925 return FamilyAccessible (tb, check_type);
927 case TypeAttributes.NestedFamANDAssem:
928 return ((check_type.Assembly == tb.Assembly) ||
929 TypeManager.IsFriendAssembly (check_type.Assembly)) &&
930 FamilyAccessible (tb, check_type);
932 case TypeAttributes.NestedFamORAssem:
933 return (check_type.Assembly == tb.Assembly) ||
934 FamilyAccessible (tb, check_type) ||
935 TypeManager.IsFriendAssembly (check_type.Assembly);
937 case TypeAttributes.NestedAssembly:
938 return check_type.Assembly == tb.Assembly ||
939 TypeManager.IsFriendAssembly (check_type.Assembly);
942 Console.WriteLine ("HERE: " + check_attr);
947 protected bool NestedAccessible (Type tb, Type check_type)
949 Type declaring = check_type.DeclaringType;
950 return TypeBuilder == declaring ||
951 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
954 protected bool FamilyAccessible (Type tb, Type check_type)
956 Type declaring = check_type.DeclaringType;
957 return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
960 // Access level of a type.
962 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
963 // Public Assembly Protected
964 Protected = (0 << 0) | (0 << 1) | (X << 2),
965 Public = (X << 0) | (X << 1) | (X << 2),
966 Private = (0 << 0) | (0 << 1) | (0 << 2),
967 Internal = (0 << 0) | (X << 1) | (0 << 2),
968 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
971 static AccessLevel GetAccessLevelFromModifiers (int flags)
973 if ((flags & Modifiers.INTERNAL) != 0) {
975 if ((flags & Modifiers.PROTECTED) != 0)
976 return AccessLevel.ProtectedOrInternal;
978 return AccessLevel.Internal;
980 } else if ((flags & Modifiers.PROTECTED) != 0)
981 return AccessLevel.Protected;
982 else if ((flags & Modifiers.PRIVATE) != 0)
983 return AccessLevel.Private;
985 return AccessLevel.Public;
988 // What is the effective access level of this?
990 AccessLevel EffectiveAccessLevel {
992 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
993 if (!IsTopLevel && (Parent != null))
994 return myAccess & Parent.EffectiveAccessLevel;
999 // Return the access level for type `t'
1000 static AccessLevel TypeEffectiveAccessLevel (Type t)
1003 return AccessLevel.Public;
1004 if (t.IsNestedPrivate)
1005 return AccessLevel.Private;
1007 return AccessLevel.Internal;
1009 // By now, it must be nested
1010 AccessLevel parent_level = TypeEffectiveAccessLevel (t.DeclaringType);
1012 if (t.IsNestedPublic)
1013 return parent_level;
1014 if (t.IsNestedAssembly)
1015 return parent_level & AccessLevel.Internal;
1016 if (t.IsNestedFamily)
1017 return parent_level & AccessLevel.Protected;
1018 if (t.IsNestedFamORAssem)
1019 return parent_level & AccessLevel.ProtectedOrInternal;
1020 if (t.IsNestedFamANDAssem)
1021 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1023 // nested private is taken care of
1025 throw new Exception ("I give up, what are you?");
1029 // This answers `is the type P, as accessible as a member M which has the
1030 // accessability @flags which is declared as a nested member of the type T, this declspace'
1032 public bool AsAccessible (Type p, int flags)
1035 // 1) if M is private, its accessability is the same as this declspace.
1036 // we already know that P is accessible to T before this method, so we
1040 if ((flags & Modifiers.PRIVATE) != 0)
1043 while (p.IsArray || p.IsPointer || p.IsByRef)
1044 p = TypeManager.GetElementType (p);
1047 if (p.IsGenericParameter)
1050 if (TypeManager.IsGenericType (p)) {
1051 foreach (Type t in p.GetGenericArguments ()) {
1052 if (!AsAccessible (t, flags))
1057 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1058 AccessLevel mAccess = this.EffectiveAccessLevel &
1059 GetAccessLevelFromModifiers (flags);
1061 // for every place from which we can access M, we must
1062 // be able to access P as well. So, we want
1063 // For every bit in M and P, M_i -> P_1 == true
1064 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1066 return ~ (~ mAccess | pAccess) == 0;
1069 private Type LookupNestedTypeInHierarchy (string name)
1072 // if the member cache has been created, lets use it.
1073 // the member cache is MUCH faster.
1074 if (MemberCache != null) {
1075 t = MemberCache.FindNestedType (name);
1080 // FIXME: This hack is needed because member cache does not work
1081 // with nested base generic types, it does only type name copy and
1082 // not type construction
1089 // no member cache. Do it the hard way -- reflection
1090 for (Type current_type = TypeBuilder;
1091 current_type != null && current_type != TypeManager.object_type;
1092 current_type = current_type.BaseType) {
1094 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1095 if (ct is TypeBuilder) {
1096 TypeContainer tc = ct == TypeBuilder
1097 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1099 t = tc.FindNestedType (name);
1101 t = TypeManager.GetNestedType (ct, name);
1104 if ((t == null) || !CheckAccessLevel (t))
1108 if (!TypeManager.IsGenericType (current_type))
1111 Type[] args = TypeManager.GetTypeArguments (current_type);
1112 Type[] targs = TypeManager.GetTypeArguments (t);
1113 for (int i = 0; i < args.Length; i++)
1114 targs [i] = args [i];
1116 t = t.MakeGenericType (targs);
1125 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
1131 // Public function used to locate types.
1133 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1135 // Returns: Type or null if they type can not be found.
1137 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1139 if (Cache.Contains (name))
1140 return (FullNamedExpression) Cache [name];
1142 FullNamedExpression e;
1143 int errors = Report.Errors;
1144 Type t = LookupNestedTypeInHierarchy (name);
1146 e = new TypeExpression (t, Location.Null);
1147 else if (Parent != null)
1148 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1150 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1152 if (errors == Report.Errors)
1159 /// This function is broken and not what you're looking for. It should only
1160 /// be used while the type is still being created since it doesn't use the cache
1161 /// and relies on the filter doing the member name check.
1164 // [Obsolete ("Only MemberCache approach should be used")]
1165 public virtual MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1166 MemberFilter filter, object criteria)
1168 throw new NotSupportedException ();
1172 /// If we have a MemberCache, return it. This property may return null if the
1173 /// class doesn't have a member cache or while it's still being created.
1175 public abstract MemberCache MemberCache {
1179 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1181 if (a.Type == TypeManager.required_attr_type) {
1182 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1185 TypeBuilder.SetCustomAttribute (cb);
1189 // Extensions for generics
1191 TypeParameter[] type_params;
1192 TypeParameter[] type_param_list;
1194 protected string GetInstantiationName ()
1196 StringBuilder sb = new StringBuilder (Name);
1198 for (int i = 0; i < type_param_list.Length; i++) {
1201 sb.Append (type_param_list [i].Name);
1204 return sb.ToString ();
1207 bool check_type_parameter (ArrayList list, int start, string name)
1209 for (int i = 0; i < start; i++) {
1210 TypeParameter param = (TypeParameter) list [i];
1212 if (param.Name != name)
1215 Report.SymbolRelatedToPreviousError (Parent);
1216 // TODO: Location is wrong (parent instead of child)
1217 Report.Warning (693, 3, Location,
1218 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1219 name, Parent.GetSignatureForError ());
1227 TypeParameter[] initialize_type_params ()
1229 if (type_param_list != null)
1230 return type_param_list;
1232 DeclSpace the_parent = Parent;
1233 if (this is GenericMethod)
1237 ArrayList list = new ArrayList ();
1238 if (the_parent != null && the_parent.IsGeneric) {
1239 // FIXME: move generics info out of DeclSpace
1240 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1241 start = parent_params.Length;
1242 list.AddRange (parent_params);
1245 int count = type_params != null ? type_params.Length : 0;
1246 for (int i = 0; i < count; i++) {
1247 TypeParameter param = type_params [i];
1248 check_type_parameter (list, start, param.Name);
1252 type_param_list = new TypeParameter [list.Count];
1253 list.CopyTo (type_param_list, 0);
1254 return type_param_list;
1257 public virtual void SetParameterInfo (ArrayList constraints_list)
1260 if (constraints_list != null) {
1262 80, Location, "Constraints are not allowed " +
1263 "on non-generic declarations");
1269 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1270 type_params = new TypeParameter [names.Length];
1273 // Register all the names
1275 for (int i = 0; i < type_params.Length; i++) {
1276 TypeParameterName name = names [i];
1278 Constraints constraints = null;
1279 if (constraints_list != null) {
1280 int total = constraints_list.Count;
1281 for (int ii = 0; ii < total; ++ii) {
1282 Constraints constraints_at = (Constraints)constraints_list[ii];
1283 // TODO: it is used by iterators only
1284 if (constraints_at == null) {
1285 constraints_list.RemoveAt (ii);
1289 if (constraints_at.TypeParameter == name.Name) {
1290 constraints = constraints_at;
1291 constraints_list.RemoveAt(ii);
1297 type_params [i] = new TypeParameter (
1298 Parent, this, name.Name, constraints, name.OptAttributes,
1301 AddToContainer (type_params [i], name.Name);
1304 if (constraints_list != null && constraints_list.Count > 0) {
1305 foreach (Constraints constraint in constraints_list) {
1306 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1307 GetSignatureForError (), constraint.TypeParameter);
1312 public TypeParameter[] TypeParameters {
1315 throw new InvalidOperationException ();
1316 if ((PartialContainer != null) && (PartialContainer != this))
1317 return PartialContainer.TypeParameters;
1318 if (type_param_list == null)
1319 initialize_type_params ();
1321 return type_param_list;
1325 public TypeParameter[] CurrentTypeParameters {
1328 throw new InvalidOperationException ();
1329 if ((PartialContainer != null) && (PartialContainer != this))
1330 return PartialContainer.CurrentTypeParameters;
1331 if (type_params != null)
1334 return new TypeParameter [0];
1338 public int CountTypeParameters {
1340 return count_type_params;
1344 public int CountCurrentTypeParameters {
1346 return count_current_type_params;
1350 public TypeParameterExpr LookupGeneric (string name, Location loc)
1355 TypeParameter [] current_params;
1356 if (this is TypeContainer)
1357 current_params = PartialContainer.CurrentTypeParameters;
1359 current_params = CurrentTypeParameters;
1361 foreach (TypeParameter type_param in current_params) {
1362 if (type_param.Name == name)
1363 return new TypeParameterExpr (type_param, loc);
1367 return Parent.LookupGeneric (name, loc);
1372 // Used for error reporting only
1373 public virtual Type LookupAnyGeneric (string typeName)
1375 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1378 public override string[] ValidAttributeTargets {
1379 get { return attribute_targets; }
1382 protected override bool VerifyClsCompliance ()
1384 if (!base.VerifyClsCompliance ()) {
1388 if (type_params != null) {
1389 foreach (TypeParameter tp in type_params) {
1390 if (tp.Constraints == null)
1393 tp.Constraints.VerifyClsCompliance ();
1397 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1401 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1402 if (!cache.Contains (lcase)) {
1403 cache.Add (lcase, this);
1407 object val = cache [lcase];
1409 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1412 Report.SymbolRelatedToPreviousError (t);
1415 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1418 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1420 Report.Error (3005, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1427 /// This is a readonly list of MemberInfo's.
1429 public class MemberList : IList {
1430 public readonly IList List;
1434 /// Create a new MemberList from the given IList.
1436 public MemberList (IList list)
1441 this.List = new ArrayList ();
1446 /// Concatenate the ILists `first' and `second' to a new MemberList.
1448 public MemberList (IList first, IList second)
1450 ArrayList list = new ArrayList ();
1451 list.AddRange (first);
1452 list.AddRange (second);
1457 public static readonly MemberList Empty = new MemberList (new ArrayList (0));
1460 /// Cast the MemberList into a MemberInfo[] array.
1463 /// This is an expensive operation, only use it if it's really necessary.
1465 public static explicit operator MemberInfo [] (MemberList list)
1467 Timer.StartTimer (TimerType.MiscTimer);
1468 MemberInfo [] result = new MemberInfo [list.Count];
1469 list.CopyTo (result, 0);
1470 Timer.StopTimer (TimerType.MiscTimer);
1482 public bool IsSynchronized {
1484 return List.IsSynchronized;
1488 public object SyncRoot {
1490 return List.SyncRoot;
1494 public void CopyTo (Array array, int index)
1496 List.CopyTo (array, index);
1501 public IEnumerator GetEnumerator ()
1503 return List.GetEnumerator ();
1508 public bool IsFixedSize {
1514 public bool IsReadOnly {
1520 object IList.this [int index] {
1522 return List [index];
1526 throw new NotSupportedException ();
1530 // FIXME: try to find out whether we can avoid the cast in this indexer.
1531 public MemberInfo this [int index] {
1533 return (MemberInfo) List [index];
1537 public int Add (object value)
1539 throw new NotSupportedException ();
1542 public void Clear ()
1544 throw new NotSupportedException ();
1547 public bool Contains (object value)
1549 return List.Contains (value);
1552 public int IndexOf (object value)
1554 return List.IndexOf (value);
1557 public void Insert (int index, object value)
1559 throw new NotSupportedException ();
1562 public void Remove (object value)
1564 throw new NotSupportedException ();
1567 public void RemoveAt (int index)
1569 throw new NotSupportedException ();
1574 /// This interface is used to get all members of a class when creating the
1575 /// member cache. It must be implemented by all DeclSpace derivatives which
1576 /// want to support the member cache and by TypeHandle to get caching of
1577 /// non-dynamic types.
1579 public interface IMemberContainer {
1581 /// The name of the IMemberContainer. This is only used for
1582 /// debugging purposes.
1589 /// The type of this IMemberContainer.
1596 /// Returns the IMemberContainer of the base class or null if this
1597 /// is an interface or TypeManger.object_type.
1598 /// This is used when creating the member cache for a class to get all
1599 /// members from the base class.
1601 MemberCache BaseCache {
1606 /// Whether this is an interface.
1613 /// Returns all members of this class with the corresponding MemberTypes
1614 /// and BindingFlags.
1617 /// When implementing this method, make sure not to return any inherited
1618 /// members and check the MemberTypes and BindingFlags properly.
1619 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1620 /// get the BindingFlags (static/non-static,public/non-public) in the
1621 /// MemberInfo class, but the cache needs this information. That's why
1622 /// this method is called multiple times with different BindingFlags.
1624 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1628 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1629 /// member lookups. It has a member name based hash table; it maps each member
1630 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1631 /// and the BindingFlags that were initially used to get it. The cache contains
1632 /// all members of the current class and all inherited members. If this cache is
1633 /// for an interface types, it also contains all inherited members.
1635 /// There are two ways to get a MemberCache:
1636 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1637 /// use the DeclSpace.MemberCache property.
1638 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1639 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1641 public class MemberCache {
1642 public readonly IMemberContainer Container;
1643 protected Hashtable member_hash;
1644 protected Hashtable method_hash;
1647 /// Create a new MemberCache for the given IMemberContainer `container'.
1649 public MemberCache (IMemberContainer container)
1651 this.Container = container;
1653 Timer.IncrementCounter (CounterType.MemberCache);
1654 Timer.StartTimer (TimerType.CacheInit);
1656 // If we have a base class (we have a base class unless we're
1657 // TypeManager.object_type), we deep-copy its MemberCache here.
1658 if (Container.BaseCache != null)
1659 member_hash = SetupCache (Container.BaseCache);
1661 member_hash = new Hashtable ();
1663 // If this is neither a dynamic type nor an interface, create a special
1664 // method cache with all declared and inherited methods.
1665 Type type = container.Type;
1666 if (!(type is TypeBuilder) && !type.IsInterface &&
1667 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1668 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1669 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1670 method_hash = new Hashtable ();
1674 // Add all members from the current class.
1675 AddMembers (Container);
1677 Timer.StopTimer (TimerType.CacheInit);
1680 public MemberCache (Type baseType, IMemberContainer container)
1682 this.Container = container;
1683 if (baseType == null)
1684 this.member_hash = new Hashtable ();
1686 this.member_hash = SetupCache (TypeManager.LookupMemberCache (baseType));
1689 public MemberCache (Type[] ifaces)
1692 // The members of this cache all belong to other caches.
1693 // So, 'Container' will not be used.
1695 this.Container = null;
1697 member_hash = new Hashtable ();
1701 foreach (Type itype in ifaces)
1702 AddCacheContents (TypeManager.LookupMemberCache (itype));
1705 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1707 this.Container = container;
1709 // If we have a base class (we have a base class unless we're
1710 // TypeManager.object_type), we deep-copy its MemberCache here.
1711 if (Container.BaseCache != null)
1712 member_hash = SetupCache (Container.BaseCache);
1714 member_hash = new Hashtable ();
1716 if (base_class != null)
1717 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1718 if (ifaces != null) {
1719 foreach (Type itype in ifaces) {
1720 MemberCache cache = TypeManager.LookupMemberCache (itype);
1722 AddCacheContents (cache);
1728 /// Bootstrap this member cache by doing a deep-copy of our base.
1730 static Hashtable SetupCache (MemberCache base_class)
1732 if (base_class == null)
1733 return new Hashtable ();
1735 Hashtable hash = new Hashtable (base_class.member_hash.Count);
1736 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1737 while (it.MoveNext ()) {
1738 hash.Add (it.Key, ((ArrayList) it.Value).Clone ());
1745 // Converts ModFlags to BindingFlags
1747 static BindingFlags GetBindingFlags (int modifiers)
1750 if ((modifiers & Modifiers.STATIC) != 0)
1751 bf = BindingFlags.Static;
1753 bf = BindingFlags.Instance;
1755 if ((modifiers & Modifiers.PRIVATE) != 0)
1756 bf |= BindingFlags.NonPublic;
1758 bf |= BindingFlags.Public;
1764 /// Add the contents of `cache' to the member_hash.
1766 void AddCacheContents (MemberCache cache)
1768 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1769 while (it.MoveNext ()) {
1770 ArrayList list = (ArrayList) member_hash [it.Key];
1772 member_hash [it.Key] = list = new ArrayList ();
1774 ArrayList entries = (ArrayList) it.Value;
1775 for (int i = entries.Count-1; i >= 0; i--) {
1776 CacheEntry entry = (CacheEntry) entries [i];
1778 if (entry.Container != cache.Container)
1786 /// Add all members from class `container' to the cache.
1788 void AddMembers (IMemberContainer container)
1790 // We need to call AddMembers() with a single member type at a time
1791 // to get the member type part of CacheEntry.EntryType right.
1792 if (!container.IsInterface) {
1793 AddMembers (MemberTypes.Constructor, container);
1794 AddMembers (MemberTypes.Field, container);
1796 AddMembers (MemberTypes.Method, container);
1797 AddMembers (MemberTypes.Property, container);
1798 AddMembers (MemberTypes.Event, container);
1799 // Nested types are returned by both Static and Instance searches.
1800 AddMembers (MemberTypes.NestedType,
1801 BindingFlags.Static | BindingFlags.Public, container);
1802 AddMembers (MemberTypes.NestedType,
1803 BindingFlags.Static | BindingFlags.NonPublic, container);
1806 void AddMembers (MemberTypes mt, IMemberContainer container)
1808 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1809 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1810 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1811 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1814 public void AddMember (MemberInfo mi, MemberCore mc)
1816 AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container, mi.Name, mi);
1819 public void AddGenericMember (MemberInfo mi, MemberCore mc)
1821 AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container, mc.MemberName.Basename, mi);
1824 public void AddNestedType (DeclSpace type)
1826 AddMember (MemberTypes.NestedType, GetBindingFlags (type.ModFlags), (IMemberContainer) type.Parent,
1827 type.TypeBuilder.Name, type.TypeBuilder);
1830 public void AddInterface (MemberCache baseCache)
1832 if (baseCache.member_hash.Count > 0)
1833 AddCacheContents (baseCache);
1836 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1837 string name, MemberInfo member)
1839 // We use a name-based hash table of ArrayList's.
1840 ArrayList list = (ArrayList) member_hash [name];
1842 list = new ArrayList (1);
1843 member_hash.Add (name, list);
1846 // When this method is called for the current class, the list will
1847 // already contain all inherited members from our base classes.
1848 // We cannot add new members in front of the list since this'd be an
1849 // expensive operation, that's why the list is sorted in reverse order
1850 // (ie. members from the current class are coming last).
1851 list.Add (new CacheEntry (container, member, mt, bf));
1855 /// Add all members from class `container' with the requested MemberTypes and
1856 /// BindingFlags to the cache. This method is called multiple times with different
1857 /// MemberTypes and BindingFlags.
1859 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1861 MemberList members = container.GetMembers (mt, bf);
1863 foreach (MemberInfo member in members) {
1864 string name = member.Name;
1866 AddMember (mt, bf, container, name, member);
1868 if (member is MethodInfo) {
1869 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1871 AddMember (mt, bf, container, gname, member);
1877 /// Add all declared and inherited methods from class `type' to the method cache.
1879 void AddMethods (Type type)
1881 AddMethods (BindingFlags.Static | BindingFlags.Public |
1882 BindingFlags.FlattenHierarchy, type);
1883 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1884 BindingFlags.FlattenHierarchy, type);
1885 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1886 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1889 static ArrayList overrides = new ArrayList ();
1891 void AddMethods (BindingFlags bf, Type type)
1893 MethodBase [] members = type.GetMethods (bf);
1895 Array.Reverse (members);
1897 foreach (MethodBase member in members) {
1898 string name = member.Name;
1900 // We use a name-based hash table of ArrayList's.
1901 ArrayList list = (ArrayList) method_hash [name];
1903 list = new ArrayList (1);
1904 method_hash.Add (name, list);
1907 MethodInfo curr = (MethodInfo) member;
1908 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1909 MethodInfo base_method = curr.GetBaseDefinition ();
1911 if (base_method == curr)
1912 // Not every virtual function needs to have a NewSlot flag.
1915 overrides.Add (curr);
1916 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1920 if (overrides.Count > 0) {
1921 for (int i = 0; i < overrides.Count; ++i)
1922 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1926 // Unfortunately, the elements returned by Type.GetMethods() aren't
1927 // sorted so we need to do this check for every member.
1928 BindingFlags new_bf = bf;
1929 if (member.DeclaringType == type)
1930 new_bf |= BindingFlags.DeclaredOnly;
1932 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1937 /// Compute and return a appropriate `EntryType' magic number for the given
1938 /// MemberTypes and BindingFlags.
1940 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1942 EntryType type = EntryType.None;
1944 if ((mt & MemberTypes.Constructor) != 0)
1945 type |= EntryType.Constructor;
1946 if ((mt & MemberTypes.Event) != 0)
1947 type |= EntryType.Event;
1948 if ((mt & MemberTypes.Field) != 0)
1949 type |= EntryType.Field;
1950 if ((mt & MemberTypes.Method) != 0)
1951 type |= EntryType.Method;
1952 if ((mt & MemberTypes.Property) != 0)
1953 type |= EntryType.Property;
1954 // Nested types are returned by static and instance searches.
1955 if ((mt & MemberTypes.NestedType) != 0)
1956 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1958 if ((bf & BindingFlags.Instance) != 0)
1959 type |= EntryType.Instance;
1960 if ((bf & BindingFlags.Static) != 0)
1961 type |= EntryType.Static;
1962 if ((bf & BindingFlags.Public) != 0)
1963 type |= EntryType.Public;
1964 if ((bf & BindingFlags.NonPublic) != 0)
1965 type |= EntryType.NonPublic;
1966 if ((bf & BindingFlags.DeclaredOnly) != 0)
1967 type |= EntryType.Declared;
1973 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1974 /// denote multiple member types. Returns true if the given flags value denotes a
1975 /// single member types.
1977 public static bool IsSingleMemberType (MemberTypes mt)
1980 case MemberTypes.Constructor:
1981 case MemberTypes.Event:
1982 case MemberTypes.Field:
1983 case MemberTypes.Method:
1984 case MemberTypes.Property:
1985 case MemberTypes.NestedType:
1994 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1995 /// number to speed up the searching process.
1998 protected enum EntryType {
2003 MaskStatic = Instance|Static,
2007 MaskProtection = Public|NonPublic,
2011 Constructor = 0x020,
2018 NotExtensionMethod = 0x800,
2020 MaskType = Constructor|Event|Field|Method|Property|NestedType
2023 protected class CacheEntry {
2024 public readonly IMemberContainer Container;
2025 public EntryType EntryType;
2026 public readonly MemberInfo Member;
2028 public CacheEntry (IMemberContainer container, MemberInfo member,
2029 MemberTypes mt, BindingFlags bf)
2031 this.Container = container;
2032 this.Member = member;
2033 this.EntryType = GetEntryType (mt, bf);
2036 public override string ToString ()
2038 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
2044 /// This is called each time we're walking up one level in the class hierarchy
2045 /// and checks whether we can abort the search since we've already found what
2046 /// we were looking for.
2048 protected bool DoneSearching (ArrayList list)
2051 // We've found exactly one member in the current class and it's not
2052 // a method or constructor.
2054 if (list.Count == 1 && !(list [0] is MethodBase))
2058 // Multiple properties: we query those just to find out the indexer
2061 if ((list.Count > 0) && (list [0] is PropertyInfo))
2068 /// Looks up members with name `name'. If you provide an optional
2069 /// filter function, it'll only be called with members matching the
2070 /// requested member name.
2072 /// This method will try to use the cache to do the lookup if possible.
2074 /// Unlike other FindMembers implementations, this method will always
2075 /// check all inherited members - even when called on an interface type.
2077 /// If you know that you're only looking for methods, you should use
2078 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2079 /// When doing a method-only search, it'll try to use a special method
2080 /// cache (unless it's a dynamic type or an interface) and the returned
2081 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2082 /// The lookup process will automatically restart itself in method-only
2083 /// search mode if it discovers that it's about to return methods.
2085 ArrayList global = new ArrayList ();
2086 bool using_global = false;
2088 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2090 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2091 MemberFilter filter, object criteria)
2094 throw new Exception ();
2096 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2097 bool method_search = mt == MemberTypes.Method;
2098 // If we have a method cache and we aren't already doing a method-only search,
2099 // then we restart a method search if the first match is a method.
2100 bool do_method_search = !method_search && (method_hash != null);
2102 ArrayList applicable;
2104 // If this is a method-only search, we try to use the method cache if
2105 // possible; a lookup in the method cache will return a MemberInfo with
2106 // the correct ReflectedType for inherited methods.
2108 if (method_search && (method_hash != null))
2109 applicable = (ArrayList) method_hash [name];
2111 applicable = (ArrayList) member_hash [name];
2113 if (applicable == null)
2114 return emptyMemberInfo;
2117 // 32 slots gives 53 rss/54 size
2118 // 2/4 slots gives 55 rss
2120 // Strange: from 25,000 calls, only 1,800
2121 // are above 2. Why does this impact it?
2124 using_global = true;
2126 Timer.StartTimer (TimerType.CachedLookup);
2128 EntryType type = GetEntryType (mt, bf);
2130 IMemberContainer current = Container;
2132 bool do_interface_search = current.IsInterface;
2134 // `applicable' is a list of all members with the given member name `name'
2135 // in the current class and all its base classes. The list is sorted in
2136 // reverse order due to the way how the cache is initialy created (to speed
2137 // things up, we're doing a deep-copy of our base).
2139 for (int i = applicable.Count-1; i >= 0; i--) {
2140 CacheEntry entry = (CacheEntry) applicable [i];
2142 // This happens each time we're walking one level up in the class
2143 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2144 // the first time this happens (this may already happen in the first
2145 // iteration of this loop if there are no members with the name we're
2146 // looking for in the current class).
2147 if (entry.Container != current) {
2151 if (!do_interface_search && DoneSearching (global))
2154 current = entry.Container;
2157 // Is the member of the correct type ?
2158 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2161 // Is the member static/non-static ?
2162 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2165 // Apply the filter to it.
2166 if (filter (entry.Member, criteria)) {
2167 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2168 do_method_search = false;
2171 // Because interfaces support multiple inheritance we have to be sure that
2172 // base member is from same interface, so only top level member will be returned
2173 if (do_interface_search && global.Count > 0) {
2174 bool member_already_exists = false;
2176 foreach (MemberInfo mi in global) {
2177 if (mi is MethodBase)
2180 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2181 member_already_exists = true;
2185 if (member_already_exists)
2189 global.Add (entry.Member);
2193 Timer.StopTimer (TimerType.CachedLookup);
2195 // If we have a method cache and we aren't already doing a method-only
2196 // search, we restart in method-only search mode if the first match is
2197 // a method. This ensures that we return a MemberInfo with the correct
2198 // ReflectedType for inherited methods.
2199 if (do_method_search && (global.Count > 0)){
2200 using_global = false;
2202 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2205 using_global = false;
2206 MemberInfo [] copy = new MemberInfo [global.Count];
2207 global.CopyTo (copy);
2212 /// Returns true if iterface exists in any base interfaces (ifaces)
2214 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2216 foreach (Type iface in ifaces) {
2217 if (iface == ifaceToFind)
2220 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2221 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2227 // find the nested type @name in @this.
2228 public Type FindNestedType (string name)
2230 ArrayList applicable = (ArrayList) member_hash [name];
2231 if (applicable == null)
2234 for (int i = applicable.Count-1; i >= 0; i--) {
2235 CacheEntry entry = (CacheEntry) applicable [i];
2236 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2237 return (Type) entry.Member;
2243 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2245 ArrayList applicable = (ArrayList) member_hash [name];
2246 if (applicable == null)
2250 // Walk the chain of events, starting from the top.
2252 for (int i = applicable.Count - 1; i >= 0; i--)
2254 CacheEntry entry = (CacheEntry) applicable [i];
2255 if ((entry.EntryType & EntryType.Event) == 0)
2258 EventInfo ei = (EventInfo)entry.Member;
2259 return ei.GetAddMethod (true);
2266 // Looks for extension methods with defined name and extension type
2268 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2271 if (method_hash != null)
2272 entries = (ArrayList)method_hash [name];
2274 entries = (ArrayList)member_hash [name];
2276 if (entries == null)
2279 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2281 entry_type |= EntryType.Public;
2283 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2285 ArrayList candidates = null;
2286 foreach (CacheEntry entry in entries) {
2287 if ((entry.EntryType & entry_type) == found_entry_type) {
2288 MethodBase mb = (MethodBase)entry.Member;
2290 IMethodData md = TypeManager.GetMethod (mb);
2291 ParameterData pd = md == null ?
2292 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2294 Type ex_type = pd.ExtensionMethodType;
2295 if (ex_type == null) {
2296 entry.EntryType |= EntryType.NotExtensionMethod;
2300 //if (implicit conversion between ex_type and extensionType exist) {
2301 if (candidates == null)
2302 candidates = new ArrayList (2);
2303 candidates.Add (mb);
2312 // This finds the method or property for us to override. invocation_type is the type where
2313 // the override is going to be declared, name is the name of the method/property, and
2314 // param_types is the parameters, if any to the method or property
2316 // Because the MemberCache holds members from this class and all the base classes,
2317 // we can avoid tons of reflection stuff.
2319 public MemberInfo FindMemberToOverride (Type invocation_type, string name, Type [] param_types, GenericMethod generic_method, bool is_property)
2321 ArrayList applicable;
2322 if (method_hash != null && !is_property)
2323 applicable = (ArrayList) method_hash [name];
2325 applicable = (ArrayList) member_hash [name];
2327 if (applicable == null)
2330 // Walk the chain of methods, starting from the top.
2332 for (int i = applicable.Count - 1; i >= 0; i--) {
2333 CacheEntry entry = (CacheEntry) applicable [i];
2335 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2338 PropertyInfo pi = null;
2339 MethodInfo mi = null;
2340 FieldInfo fi = null;
2341 Type [] cmp_attrs = null;
2344 if ((entry.EntryType & EntryType.Field) != 0) {
2345 fi = (FieldInfo)entry.Member;
2347 // TODO: For this case we ignore member type
2348 //fb = TypeManager.GetField (fi);
2349 //cmp_attrs = new Type[] { fb.MemberType };
2351 pi = (PropertyInfo) entry.Member;
2352 cmp_attrs = TypeManager.GetArgumentTypes (pi);
2355 mi = (MethodInfo) entry.Member;
2356 cmp_attrs = TypeManager.GetParameterData (mi).Types;
2360 // TODO: Almost duplicate !
2362 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2363 case FieldAttributes.PrivateScope:
2365 case FieldAttributes.Private:
2367 // A private method is Ok if we are a nested subtype.
2368 // The spec actually is not very clear about this, see bug 52458.
2370 if (!invocation_type.Equals (entry.Container.Type) &&
2371 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2374 case FieldAttributes.FamANDAssem:
2375 case FieldAttributes.Assembly:
2377 // Check for assembly methods
2379 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2383 return entry.Member;
2387 // Check the arguments
2389 if (cmp_attrs.Length != param_types.Length)
2393 for (j = 0; j < cmp_attrs.Length; ++j)
2394 if (!TypeManager.IsEqual (param_types [j], cmp_attrs [j]))
2396 if (j < cmp_attrs.Length)
2400 // check generic arguments for methods
2403 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2404 if (generic_method == null && cmpGenArgs.Length != 0)
2406 if (generic_method != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2411 // get one of the methods because this has the visibility info.
2414 mi = pi.GetGetMethod (true);
2416 mi = pi.GetSetMethod (true);
2422 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2423 case MethodAttributes.PrivateScope:
2425 case MethodAttributes.Private:
2427 // A private method is Ok if we are a nested subtype.
2428 // The spec actually is not very clear about this, see bug 52458.
2430 if (!invocation_type.Equals (entry.Container.Type) &&
2431 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2434 case MethodAttributes.FamANDAssem:
2435 case MethodAttributes.Assembly:
2437 // Check for assembly methods
2439 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2443 return entry.Member;
2450 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2451 /// We handle two cases. The first is for types without parameters (events, field, properties).
2452 /// The second are methods, indexers and this is why ignore_complex_types is here.
2453 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2455 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2457 ArrayList applicable = null;
2459 if (method_hash != null)
2460 applicable = (ArrayList) method_hash [name];
2462 if (applicable != null) {
2463 for (int i = applicable.Count - 1; i >= 0; i--) {
2464 CacheEntry entry = (CacheEntry) applicable [i];
2465 if ((entry.EntryType & EntryType.Public) != 0)
2466 return entry.Member;
2470 if (member_hash == null)
2472 applicable = (ArrayList) member_hash [name];
2474 if (applicable != null) {
2475 for (int i = applicable.Count - 1; i >= 0; i--) {
2476 CacheEntry entry = (CacheEntry) applicable [i];
2477 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2478 if (ignore_complex_types) {
2479 if ((entry.EntryType & EntryType.Method) != 0)
2482 // Does exist easier way how to detect indexer ?
2483 if ((entry.EntryType & EntryType.Property) != 0) {
2484 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2485 if (arg_types.Length > 0)
2489 return entry.Member;
2496 Hashtable locase_table;
2499 /// Builds low-case table for CLS Compliance test
2501 public Hashtable GetPublicMembers ()
2503 if (locase_table != null)
2504 return locase_table;
2506 locase_table = new Hashtable ();
2507 foreach (DictionaryEntry entry in member_hash) {
2508 ArrayList members = (ArrayList)entry.Value;
2509 for (int ii = 0; ii < members.Count; ++ii) {
2510 CacheEntry member_entry = (CacheEntry) members [ii];
2512 if ((member_entry.EntryType & EntryType.Public) == 0)
2515 // TODO: Does anyone know easier way how to detect that member is internal ?
2516 switch (member_entry.EntryType & EntryType.MaskType) {
2517 case EntryType.Constructor:
2520 case EntryType.Field:
2521 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2525 case EntryType.Method:
2526 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2530 case EntryType.Property:
2531 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2532 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2536 case EntryType.Event:
2537 EventInfo ei = (EventInfo)member_entry.Member;
2538 MethodInfo mi = ei.GetAddMethod ();
2539 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2543 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2544 locase_table [lcase] = member_entry.Member;
2548 return locase_table;
2551 public Hashtable Members {
2558 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2561 // TODO: refactor as method is always 'this'
2562 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2564 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2566 for (int i = 0; i < al.Count; ++i) {
2567 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2570 if (entry.Member == this_builder)
2573 if ((entry.EntryType & tested_type) != tested_type)
2576 MethodBase method_to_compare = (MethodBase)entry.Member;
2577 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2578 method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2580 if (result == AttributeTester.Result.Ok)
2583 IMethodData md = TypeManager.GetMethod (method_to_compare);
2585 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2586 // However it is exactly what csc does.
2587 if (md != null && !md.IsClsComplianceRequired ())
2590 Report.SymbolRelatedToPreviousError (entry.Member);
2592 case AttributeTester.Result.RefOutArrayError:
2593 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2595 case AttributeTester.Result.ArrayArrayError:
2596 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2600 throw new NotImplementedException (result.ToString ());
2604 public bool CheckExistingMembersOverloads (MemberCore member, string name, Parameters parameters)
2606 ArrayList entries = (ArrayList)member_hash [name];
2607 if (entries == null)
2610 int method_param_count = parameters.Count;
2611 for (int i = entries.Count - 1; i >= 0; --i) {
2612 CacheEntry ce = (CacheEntry) entries [i];
2614 if (ce.Container != member.Parent.PartialContainer)
2618 ParameterData pd = null;
2619 if ((ce.EntryType & EntryType.Property) != 0) {
2620 p_types = TypeManager.GetArgumentTypes ((PropertyInfo) ce.Member);
2622 MethodBase mb = (MethodBase) ce.Member;
2624 // TODO: This is more like a hack, because we are adding generic methods
2625 // twice with and without arity name
2626 if (mb.IsGenericMethod && !member.MemberName.IsGeneric)
2629 pd = TypeManager.GetParameterData (mb);
2633 if (p_types.Length != method_param_count)
2636 if (method_param_count > 0) {
2637 int ii = method_param_count - 1;
2638 Type type_a, type_b;
2640 type_a = parameters.ParameterType (ii);
2641 type_b = p_types [ii];
2643 if (type_a.IsGenericParameter && type_a.DeclaringMethod != null)
2646 if (type_b.IsGenericParameter && type_b.DeclaringMethod != null)
2649 } while (type_a == type_b && ii-- != 0);
2655 // Operators can differ in return type only
2657 if (member is Operator) {
2658 Operator op = TypeManager.GetMethod ((MethodBase) ce.Member) as Operator;
2659 if (op != null && op.ReturnType != ((Operator) member).ReturnType)
2664 // Report difference in parameter modifiers only
2666 if (pd != null && !(member is AbstractPropertyEventMethod)) {
2667 ii = method_param_count;
2668 while (ii-- != 0 && parameters.ParameterModifier (ii) == pd.ParameterModifier (ii) &&
2669 parameters.ExtensionMethodType == pd.ExtensionMethodType);
2672 MethodCore mc = TypeManager.GetMethod ((MethodBase) ce.Member) as MethodCore;
2673 Report.SymbolRelatedToPreviousError (ce.Member);
2674 if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.ModFlags & Modifiers.PARTIAL) != 0) {
2675 if (parameters.HasParams || pd.HasParams) {
2676 Report.Error (758, member.Location,
2677 "A partial method declaration and partial method implementation cannot differ on use of `params' modifier");
2679 Report.Error (755, member.Location,
2680 "A partial method declaration and partial method implementation must be both an extension method or neither");
2683 Report.Error (663, member.Location,
2684 "An overloaded method `{0}' cannot differ on use of parameter modifiers only",
2685 member.GetSignatureForError ());
2692 if ((ce.EntryType & EntryType.Method) != 0) {
2693 Method method_a = member as Method;
2694 Method method_b = TypeManager.GetMethod ((MethodBase) ce.Member) as Method;
2695 if (method_a != null && method_b != null && (method_a.ModFlags & method_b.ModFlags & Modifiers.PARTIAL) != 0) {
2696 const int partial_modifiers = Modifiers.STATIC | Modifiers.UNSAFE;
2697 if (method_a.IsPartialDefinition == method_b.IsPartialImplementation) {
2698 if ((method_a.ModFlags & partial_modifiers) == (method_b.ModFlags & partial_modifiers) ||
2699 method_a.Parent.IsInUnsafeScope && method_b.Parent.IsInUnsafeScope) {
2700 if (method_a.IsPartialImplementation) {
2701 method_a.SetPartialDefinition (method_b);
2702 entries.RemoveAt (i);
2704 method_b.SetPartialDefinition (method_a);
2709 if ((method_a.ModFlags & Modifiers.STATIC) != (method_b.ModFlags & Modifiers.STATIC)) {
2710 Report.SymbolRelatedToPreviousError (ce.Member);
2711 Report.Error (763, member.Location,
2712 "A partial method declaration and partial method implementation must be both `static' or neither");
2715 Report.SymbolRelatedToPreviousError (ce.Member);
2716 Report.Error (764, member.Location,
2717 "A partial method declaration and partial method implementation must be both `unsafe' or neither");
2721 Report.SymbolRelatedToPreviousError (ce.Member);
2722 if (method_a.IsPartialDefinition) {
2723 Report.Error (756, member.Location, "A partial method `{0}' declaration is already defined",
2724 member.GetSignatureForError ());
2727 Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
2728 member.GetSignatureForError ());
2732 Report.SymbolRelatedToPreviousError (ce.Member);
2733 IMethodData duplicate_member = TypeManager.GetMethod ((MethodBase) ce.Member);
2734 if (member is Operator && duplicate_member is Operator) {
2735 Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
2736 member.Parent.GetSignatureForError ());
2740 bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
2741 bool is_reserved_b = duplicate_member is AbstractPropertyEventMethod || duplicate_member is Operator;
2743 if (is_reserved_a || is_reserved_b) {
2744 Report.Error (82, member.Location, "A member `{0}' is already reserved",
2746 TypeManager.GetFullNameSignature (ce.Member) :
2747 member.GetSignatureForError ());
2751 Report.SymbolRelatedToPreviousError (ce.Member);
2754 Report.Error (111, member.Location,
2755 "A member `{0}' is already defined. Rename this member or use different parameter types",
2756 member.GetSignatureForError ());