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
16 using System.Collections;
17 using System.Globalization;
18 using System.Reflection.Emit;
19 using System.Reflection;
21 #if BOOTSTRAP_WITH_OLDLIB
22 using XmlElement = System.Object;
27 namespace Mono.CSharp {
29 public class MemberName {
31 public readonly MemberName Left;
33 public static readonly MemberName Null = new MemberName ("");
35 public MemberName (string name)
40 public MemberName (MemberName left, string name)
46 public MemberName (MemberName left, MemberName right)
47 : this (left, right.Name)
51 public string GetName ()
53 return GetName (false);
56 public string GetName (bool is_generic)
58 string name = is_generic ? Basename : Name;
60 return Left.GetName (is_generic) + "." + name;
66 /// This returns exclusively the name as seen on the source code
67 /// it is not the fully qualifed type after resolution
69 public string GetPartialName ()
72 return Left.GetPartialName () + "." + Name;
77 public string GetTypeName ()
80 return Left.GetTypeName () + "." + Name;
85 public Expression GetTypeExpression (Location loc)
88 Expression lexpr = Left.GetTypeExpression (loc);
90 return new MemberAccess (lexpr, Name, loc);
92 return new SimpleName (Name, loc);
96 public MemberName Clone ()
99 return new MemberName (Left.Clone (), Name);
101 return new MemberName (Name);
104 public string Basename {
110 public override string ToString ()
113 return Left + "." + Name;
120 /// Base representation for members. This is used to keep track
121 /// of Name, Location and Modifier flags, and handling Attributes.
123 public abstract class MemberCore : Attributable {
129 // !(this is GenericMethod) && !(this is Method)
130 return MemberName.GetName (false);
134 // Is not readonly because of IndexerName attribute
135 public MemberName MemberName;
138 /// Modifier flags that the user specified in the source code
142 public /*readonly*/ TypeContainer Parent;
145 /// Location where this declaration happens
147 public readonly Location Location;
150 /// XML documentation comment
152 public string DocComment;
155 /// Represents header string for documentation comment
156 /// for each member types.
158 public abstract string DocCommentHeader { get; }
162 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
163 Obsolete = 1 << 1, // Type has obsolete attribute
164 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
165 ClsCompliant = 1 << 3, // Type is CLS Compliant
166 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
167 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
168 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
169 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
170 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
171 Excluded = 1 << 9, // Method is conditional
172 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
176 /// MemberCore flags at first detected then cached
178 internal Flags caching_flags;
180 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
187 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
191 /// Tests presence of ObsoleteAttribute and report proper error
193 protected void CheckUsageOfObsoleteAttribute (Type type)
198 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
199 if (obsolete_attr == null)
202 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
205 public abstract bool Define ();
208 // Returns full member name for error message
210 public virtual string GetSignatureForError ()
216 /// Use this method when MethodBuilder is null
218 public virtual string GetSignatureForError (TypeContainer tc)
224 /// Base Emit method. This is also entry point for CLS-Compliant verification.
226 public virtual void Emit ()
228 // Hack with Parent == null is for EnumMember
229 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
230 VerifyObsoleteAttribute ();
232 if (!RootContext.VerifyClsCompliance)
235 VerifyClsCompliance (Parent);
238 public bool InUnsafe {
240 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
245 // Whehter is it ok to use an unsafe pointer in this type container
247 public bool UnsafeOK (DeclSpace parent)
250 // First check if this MemberCore modifier flags has unsafe set
252 if ((ModFlags & Modifiers.UNSAFE) != 0)
255 if (parent.UnsafeContext)
258 Expression.UnsafeError (Location);
263 /// Returns instance of ObsoleteAttribute for this MemberCore
265 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
267 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
268 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
272 caching_flags &= ~Flags.Obsolete_Undetected;
274 if (OptAttributes == null)
277 Attribute obsolete_attr = OptAttributes.Search (
278 TypeManager.obsolete_attribute_type, ds.EmitContext);
279 if (obsolete_attr == null)
282 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds.EmitContext);
283 if (obsolete == null)
286 caching_flags |= Flags.Obsolete;
291 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
293 public override bool IsClsCompliaceRequired (DeclSpace container)
295 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
296 return (caching_flags & Flags.ClsCompliant) != 0;
298 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
299 caching_flags &= ~Flags.ClsCompliance_Undetected;
300 caching_flags |= Flags.ClsCompliant;
304 caching_flags &= ~Flags.ClsCompliance_Undetected;
309 /// Returns true when MemberCore is exposed from assembly.
311 public bool IsExposedFromAssembly (DeclSpace ds)
313 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
316 DeclSpace parentContainer = ds;
317 while (parentContainer != null && parentContainer.ModFlags != 0) {
318 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
320 parentContainer = parentContainer.Parent;
326 /// Resolve CLSCompliantAttribute value or gets cached value.
328 bool GetClsCompliantAttributeValue (DeclSpace ds)
330 if (OptAttributes != null) {
331 Attribute cls_attribute = OptAttributes.Search (
332 TypeManager.cls_compliant_attribute_type, ds.EmitContext);
333 if (cls_attribute != null) {
334 caching_flags |= Flags.HasClsCompliantAttribute;
335 return cls_attribute.GetClsCompliantAttributeValue (ds.EmitContext);
338 return ds.GetClsCompliantAttributeValue ();
342 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
344 protected bool HasClsCompliantAttribute {
346 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
351 /// It helps to handle error 102 & 111 detection
353 public virtual bool MarkForDuplicationCheck ()
359 /// The main virtual method for CLS-Compliant verifications.
360 /// The method returns true if member is CLS-Compliant and false if member is not
361 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
362 /// and add their extra verifications.
364 protected virtual bool VerifyClsCompliance (DeclSpace ds)
366 if (!IsClsCompliaceRequired (ds)) {
367 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
368 if (!IsExposedFromAssembly (ds))
369 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
370 if (!CodeGen.Assembly.IsClsCompliant)
371 Report.Warning (3021, Location, "'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
376 if (!CodeGen.Assembly.IsClsCompliant) {
377 if (HasClsCompliantAttribute) {
378 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
383 int index = Name.LastIndexOf ('.');
384 if (Name [index > 0 ? index + 1 : 0] == '_') {
385 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
390 protected abstract void VerifyObsoleteAttribute ();
393 // Raised (and passed an XmlElement that contains the comment)
394 // when GenerateDocComment is writing documentation expectedly.
396 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
401 // Returns a string that represents the signature for this
402 // member which should be used in XML documentation.
404 public virtual string GetDocCommentName (DeclSpace ds)
406 if (ds == null || this is DeclSpace)
407 return DocCommentHeader + Name;
409 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
413 // Generates xml doc comments (if any), and if required,
414 // handle warning report.
416 internal virtual void GenerateDocComment (DeclSpace ds)
418 DocUtil.GenerateDocComment (this, ds);
423 /// Base class for structs, classes, enumerations and interfaces.
426 /// They all create new declaration spaces. This
427 /// provides the common foundation for managing those name
430 public abstract class DeclSpace : MemberCore, IAlias {
432 /// This points to the actual definition that is being
433 /// created with System.Reflection.Emit
435 public TypeBuilder TypeBuilder;
438 // This is the namespace in which this typecontainer
439 // was declared. We use this to resolve names.
441 public NamespaceEntry NamespaceEntry;
443 private Hashtable Cache = new Hashtable ();
445 public string Basename;
447 protected Hashtable defined_names;
449 // The emit context for toplevel objects.
450 protected EmitContext ec;
452 public EmitContext EmitContext {
456 static string[] attribute_targets = new string [] { "type" };
458 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
459 Attributes attrs, Location l)
460 : base (parent, name, attrs, l)
463 Basename = name.Name;
464 defined_names = new Hashtable ();
468 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
470 protected bool AddToContainer (MemberCore symbol, string fullname, string basename)
472 if (basename == Basename && !(this is Interface)) {
473 Report.SymbolRelatedToPreviousError (this);
474 Report.Error (542, symbol.Location, "'{0}': member names cannot be the same as their enclosing type", symbol.GetSignatureForError ());
478 MemberCore mc = (MemberCore)defined_names [fullname];
481 defined_names.Add (fullname, symbol);
485 if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
488 Report.SymbolRelatedToPreviousError (mc);
489 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
493 public void RecordDecl ()
495 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
496 NamespaceEntry.DefineName (MemberName.Basename, this);
500 /// Returns the MemberCore associated with a given name in the declaration
501 /// space. It doesn't return method based symbols !!
504 public MemberCore GetDefinition (string name)
506 return (MemberCore)defined_names [name];
509 bool in_transit = false;
512 /// This function is used to catch recursive definitions
515 public bool InTransit {
526 // root_types contains all the types. All TopLevel types
527 // hence have a parent that points to `root_types', that is
528 // why there is a non-obvious test down here.
530 public bool IsTopLevel {
533 if (Parent.Parent == null)
540 public virtual void CloseType ()
542 if ((caching_flags & Flags.CloseTypeCreated) == 0){
544 TypeBuilder.CreateType ();
547 // The try/catch is needed because
548 // nested enumerations fail to load when they
551 // Even if this is the right order (enumerations
552 // declared after types).
554 // Note that this still creates the type and
555 // it is possible to save it
557 caching_flags |= Flags.CloseTypeCreated;
562 /// Should be overriten by the appropriate declaration space
564 public abstract TypeBuilder DefineType ();
567 /// Define all members, but don't apply any attributes or do anything which may
568 /// access not-yet-defined classes. This method also creates the MemberCache.
570 public abstract bool DefineMembers (TypeContainer parent);
573 // Whether this is an `unsafe context'
575 public bool UnsafeContext {
577 if ((ModFlags & Modifiers.UNSAFE) != 0)
580 return Parent.UnsafeContext;
585 public static string MakeFQN (string nsn, string name)
589 return String.Concat (nsn, ".", name);
592 EmitContext type_resolve_ec;
595 // Resolves the expression `e' for a type, and will recursively define
596 // types. This should only be used for resolving base types.
598 public TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
600 if (type_resolve_ec == null) {
601 // FIXME: I think this should really be one of:
603 // a. type_resolve_ec = Parent.EmitContext;
604 // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
606 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
608 type_resolve_ec = new EmitContext (Parent, this, loc, null, null, ModFlags, false);
609 type_resolve_ec.ResolvingTypeTree = true;
611 type_resolve_ec.loc = loc;
612 type_resolve_ec.ContainerType = TypeBuilder;
614 return e.ResolveAsTypeTerminal (type_resolve_ec, silent);
617 public bool CheckAccessLevel (Type check_type)
619 if (check_type == TypeBuilder)
622 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
625 // Broken Microsoft runtime, return public for arrays, no matter what
626 // the accessibility is for their underlying class, and they return
627 // NonPublic visibility for pointers
629 if (check_type.IsArray || check_type.IsPointer)
630 return CheckAccessLevel (TypeManager.GetElementType (check_type));
632 if (TypeBuilder == null)
633 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
634 // However, this is invoked again later -- so safe to return true.
635 // May also be null when resolving top-level attributes.
639 case TypeAttributes.Public:
642 case TypeAttributes.NotPublic:
644 // This test should probably use the declaringtype.
646 return check_type.Assembly == TypeBuilder.Assembly;
648 case TypeAttributes.NestedPublic:
651 case TypeAttributes.NestedPrivate:
652 return NestedAccessible (check_type);
654 case TypeAttributes.NestedFamily:
655 return FamilyAccessible (check_type);
657 case TypeAttributes.NestedFamANDAssem:
658 return (check_type.Assembly == TypeBuilder.Assembly) &&
659 FamilyAccessible (check_type);
661 case TypeAttributes.NestedFamORAssem:
662 return (check_type.Assembly == TypeBuilder.Assembly) ||
663 FamilyAccessible (check_type);
665 case TypeAttributes.NestedAssembly:
666 return check_type.Assembly == TypeBuilder.Assembly;
669 Console.WriteLine ("HERE: " + check_attr);
674 protected bool NestedAccessible (Type check_type)
676 string check_type_name = check_type.FullName;
678 // At this point, we already know check_type is a nested class.
679 int cio = check_type_name.LastIndexOf ('+');
681 // Ensure that the string 'container' has a '+' in it to avoid false matches
682 string container = check_type_name.Substring (0, cio + 1);
684 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
685 string type_name = TypeBuilder.FullName + "+";
687 // If the current class is nested inside the container of check_type,
688 // we can access check_type even if it is private or protected.
689 return type_name.StartsWith (container);
692 protected bool FamilyAccessible (Type check_type)
694 Type declaring = check_type.DeclaringType;
695 if (TypeBuilder == declaring ||
696 TypeBuilder.IsSubclassOf (declaring))
699 return NestedAccessible (check_type);
702 // Access level of a type.
704 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
705 // Public Assembly Protected
706 Protected = (0 << 0) | (0 << 1) | (X << 2),
707 Public = (X << 0) | (X << 1) | (X << 2),
708 Private = (0 << 0) | (0 << 1) | (0 << 2),
709 Internal = (0 << 0) | (X << 1) | (0 << 2),
710 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
713 static AccessLevel GetAccessLevelFromModifiers (int flags)
715 if ((flags & Modifiers.INTERNAL) != 0) {
717 if ((flags & Modifiers.PROTECTED) != 0)
718 return AccessLevel.ProtectedOrInternal;
720 return AccessLevel.Internal;
722 } else if ((flags & Modifiers.PROTECTED) != 0)
723 return AccessLevel.Protected;
725 else if ((flags & Modifiers.PRIVATE) != 0)
726 return AccessLevel.Private;
729 return AccessLevel.Public;
732 // What is the effective access level of this?
734 AccessLevel EffectiveAccessLevel {
736 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
737 if (!IsTopLevel && (Parent != null))
738 return myAccess & Parent.EffectiveAccessLevel;
744 // Return the access level for type `t'
745 static AccessLevel TypeEffectiveAccessLevel (Type t)
748 return AccessLevel.Public;
749 if (t.IsNestedPrivate)
750 return AccessLevel.Private;
752 return AccessLevel.Internal;
754 // By now, it must be nested
755 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
757 if (t.IsNestedPublic)
759 if (t.IsNestedAssembly)
760 return parentLevel & AccessLevel.Internal;
761 if (t.IsNestedFamily)
762 return parentLevel & AccessLevel.Protected;
763 if (t.IsNestedFamORAssem)
764 return parentLevel & AccessLevel.ProtectedOrInternal;
765 if (t.IsNestedFamANDAssem)
766 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
768 // nested private is taken care of
770 throw new Exception ("I give up, what are you?");
774 // This answers `is the type P, as accessible as a member M which has the
775 // accessability @flags which is declared as a nested member of the type T, this declspace'
777 public bool AsAccessible (Type p, int flags)
780 // 1) if M is private, its accessability is the same as this declspace.
781 // we already know that P is accessible to T before this method, so we
785 if ((flags & Modifiers.PRIVATE) != 0)
788 while (p.IsArray || p.IsPointer || p.IsByRef)
789 p = TypeManager.GetElementType (p);
791 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
792 AccessLevel mAccess = this.EffectiveAccessLevel &
793 GetAccessLevelFromModifiers (flags);
795 // for every place from which we can access M, we must
796 // be able to access P as well. So, we want
797 // For every bit in M and P, M_i -> P_1 == true
798 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
800 return ~ (~ mAccess | pAccess) == 0;
803 static DoubleHash dh = new DoubleHash (1000);
805 Type DefineTypeAndParents (DeclSpace tc)
807 DeclSpace container = tc.Parent;
809 if (container.TypeBuilder == null && container.Name != "")
810 DefineTypeAndParents (container);
812 return tc.DefineType ();
815 FullNamedExpression LookupInterfaceOrClass (string ns, string name, out bool error)
818 FullNamedExpression result;
823 int p = name.LastIndexOf ('.');
825 if (dh.Lookup (ns, name, out r))
826 return (FullNamedExpression) r;
829 // If the type is not a nested type, we do not need `LookupType's processing.
830 // If the @name does not have a `.' in it, this cant be a nested type.
833 if (Namespace.IsNamespace (ns)) {
835 t = TypeManager.LookupType (ns + "." + name);
837 t = TypeManager.LookupTypeDirect (ns + "." + name);
841 t = TypeManager.LookupType (name);
843 t = TypeManager.LookupTypeDirect (name);
847 result = new TypeExpression (t, Location.Null);
848 dh.Insert (ns, name, result);
852 if (ns != "" && Namespace.IsNamespace (ns)) {
853 result = Namespace.LookupNamespace (ns, false).Lookup (this, name, Location.Null);
854 if (result != null) {
855 dh.Insert (ns, name, result);
860 if (ns == "" && Namespace.IsNamespace (name)) {
861 result = Namespace.LookupNamespace (name, false);
862 dh.Insert (ns, name, result);
867 // In case we are fed a composite name, normalize it.
871 ns = MakeFQN (ns, name.Substring (0, p));
872 name = name.Substring (p+1);
875 if (ns.IndexOf ('+') != -1)
876 ns = ns.Replace ('+', '.');
878 parent = RootContext.Tree.LookupByNamespace (ns, name);
879 if (parent == null) {
880 dh.Insert (ns, name, null);
884 t = DefineTypeAndParents (parent);
890 result = new TypeExpression (t, Location.Null);
891 dh.Insert (ns, name, result);
895 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
897 Report.Error (104, loc,
898 "`{0}' is an ambiguous reference ({1} or {2})",
903 /// GetType is used to resolve type names at the DeclSpace level.
904 /// Use this to lookup class/struct bases, interface bases or
905 /// delegate type references
909 /// Contrast this to LookupType which is used inside method bodies to
910 /// lookup types that have already been defined. GetType is used
911 /// during the tree resolution process and potentially define
912 /// recursively the type
914 public FullNamedExpression FindType (Location loc, string name)
916 FullNamedExpression t;
920 // For the case the type we are looking for is nested within this one
921 // or is in any base class
924 DeclSpace containing_ds = this;
926 while (containing_ds != null){
927 Type container_type = containing_ds.TypeBuilder;
928 Type current_type = container_type;
930 while (current_type != null && current_type != TypeManager.object_type) {
931 string pre = current_type.FullName;
933 t = LookupInterfaceOrClass (pre, name, out error);
937 if ((t != null) && containing_ds.CheckAccessLevel (t.Type))
940 current_type = current_type.BaseType;
942 containing_ds = containing_ds.Parent;
946 // Attempt to lookup the class on our namespace and all it's implicit parents
948 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
949 t = LookupInterfaceOrClass (ns.FullName, name, out error);
958 // Attempt to do a direct unqualified lookup
960 t = LookupInterfaceOrClass ("", name, out error);
968 // Attempt to lookup the class on any of the `using'
972 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
974 t = LookupInterfaceOrClass (ns.FullName, name, out error);
981 if (name.IndexOf ('.') > 0)
984 t = ns.LookupAlias (name);
989 // Now check the using clause list
991 FullNamedExpression match = null;
992 foreach (Namespace using_ns in ns.GetUsingTable ()) {
993 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
997 if ((match != null) && (match is TypeExpr)) {
998 Type matched = ((TypeExpr) match).Type;
999 if (!CheckAccessLevel (matched))
1002 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1012 //Report.Error (246, Location, "Can not find type `"+name+"'");
1017 // Public function used to locate types, this can only
1018 // be used after the ResolveTree function has been invoked.
1020 // Returns: Type or null if they type can not be found.
1022 // Come to think of it, this should be a DeclSpace
1024 public FullNamedExpression LookupType (string name, bool silent, Location loc)
1026 FullNamedExpression e;
1028 if (Cache.Contains (name)) {
1029 e = (FullNamedExpression) Cache [name];
1032 // For the case the type we are looking for is nested within this one
1033 // or is in any base class
1035 DeclSpace containing_ds = this;
1036 while (containing_ds != null){
1038 // if the member cache has been created, lets use it.
1039 // the member cache is MUCH faster.
1040 if (containing_ds.MemberCache != null) {
1041 Type t = containing_ds.MemberCache.FindNestedType (name);
1043 containing_ds = containing_ds.Parent;
1047 e = new TypeExpression (t, Location.Null);
1052 // no member cache. Do it the hard way -- reflection
1053 Type current_type = containing_ds.TypeBuilder;
1055 while (current_type != null &&
1056 current_type != TypeManager.object_type) {
1060 Type t = TypeManager.LookupType (current_type.FullName + "." + name);
1062 e = new TypeExpression (t, Location.Null);
1067 current_type = current_type.BaseType;
1070 containing_ds = containing_ds.Parent;
1073 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc);
1074 if (!silent || e != null)
1078 if (e == null && !silent)
1079 Report.Error (246, loc, "Cannot find type `"+name+"'");
1085 /// This function is broken and not what you're looking for. It should only
1086 /// be used while the type is still being created since it doesn't use the cache
1087 /// and relies on the filter doing the member name check.
1089 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1090 MemberFilter filter, object criteria);
1093 /// If we have a MemberCache, return it. This property may return null if the
1094 /// class doesn't have a member cache or while it's still being created.
1096 public abstract MemberCache MemberCache {
1100 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1103 TypeBuilder.SetCustomAttribute (cb);
1104 } catch (System.ArgumentException e) {
1105 Report.Warning (-21, a.Location,
1106 "The CharSet named property on StructLayout\n"+
1107 "\tdoes not work correctly on Microsoft.NET\n"+
1108 "\tYou might want to remove the CharSet declaration\n"+
1109 "\tor compile using the Mono runtime instead of the\n"+
1110 "\tMicrosoft .NET runtime\n"+
1111 "\tThe runtime gave the error: " + e);
1116 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1117 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1119 public bool GetClsCompliantAttributeValue ()
1121 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1122 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1124 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1126 if (OptAttributes != null) {
1127 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, ec);
1128 if (cls_attribute != null) {
1129 caching_flags |= Flags.HasClsCompliantAttribute;
1130 if (cls_attribute.GetClsCompliantAttributeValue (ec)) {
1131 caching_flags |= Flags.ClsCompliantAttributeTrue;
1138 if (Parent == null) {
1139 if (CodeGen.Assembly.IsClsCompliant) {
1140 caching_flags |= Flags.ClsCompliantAttributeTrue;
1146 if (Parent.GetClsCompliantAttributeValue ()) {
1147 caching_flags |= Flags.ClsCompliantAttributeTrue;
1153 public override string[] ValidAttributeTargets {
1155 return attribute_targets;
1159 bool IAlias.IsType {
1160 get { return true; }
1163 string IAlias.Name {
1164 get { return Name; }
1167 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1169 if (TypeBuilder == null)
1170 throw new InvalidOperationException ();
1172 return new TypeExpression (TypeBuilder, Location);
1177 /// This is a readonly list of MemberInfo's.
1179 public class MemberList : IList {
1180 public readonly IList List;
1184 /// Create a new MemberList from the given IList.
1186 public MemberList (IList list)
1191 this.List = new ArrayList ();
1196 /// Concatenate the ILists `first' and `second' to a new MemberList.
1198 public MemberList (IList first, IList second)
1200 ArrayList list = new ArrayList ();
1201 list.AddRange (first);
1202 list.AddRange (second);
1207 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1210 /// Cast the MemberList into a MemberInfo[] array.
1213 /// This is an expensive operation, only use it if it's really necessary.
1215 public static explicit operator MemberInfo [] (MemberList list)
1217 Timer.StartTimer (TimerType.MiscTimer);
1218 MemberInfo [] result = new MemberInfo [list.Count];
1219 list.CopyTo (result, 0);
1220 Timer.StopTimer (TimerType.MiscTimer);
1232 public bool IsSynchronized {
1234 return List.IsSynchronized;
1238 public object SyncRoot {
1240 return List.SyncRoot;
1244 public void CopyTo (Array array, int index)
1246 List.CopyTo (array, index);
1251 public IEnumerator GetEnumerator ()
1253 return List.GetEnumerator ();
1258 public bool IsFixedSize {
1264 public bool IsReadOnly {
1270 object IList.this [int index] {
1272 return List [index];
1276 throw new NotSupportedException ();
1280 // FIXME: try to find out whether we can avoid the cast in this indexer.
1281 public MemberInfo this [int index] {
1283 return (MemberInfo) List [index];
1287 public int Add (object value)
1289 throw new NotSupportedException ();
1292 public void Clear ()
1294 throw new NotSupportedException ();
1297 public bool Contains (object value)
1299 return List.Contains (value);
1302 public int IndexOf (object value)
1304 return List.IndexOf (value);
1307 public void Insert (int index, object value)
1309 throw new NotSupportedException ();
1312 public void Remove (object value)
1314 throw new NotSupportedException ();
1317 public void RemoveAt (int index)
1319 throw new NotSupportedException ();
1324 /// This interface is used to get all members of a class when creating the
1325 /// member cache. It must be implemented by all DeclSpace derivatives which
1326 /// want to support the member cache and by TypeHandle to get caching of
1327 /// non-dynamic types.
1329 public interface IMemberContainer {
1331 /// The name of the IMemberContainer. This is only used for
1332 /// debugging purposes.
1339 /// The type of this IMemberContainer.
1346 /// Returns the IMemberContainer of the base class or null if this
1347 /// is an interface or TypeManger.object_type.
1348 /// This is used when creating the member cache for a class to get all
1349 /// members from the base class.
1351 MemberCache BaseCache {
1356 /// Whether this is an interface.
1363 /// Returns all members of this class with the corresponding MemberTypes
1364 /// and BindingFlags.
1367 /// When implementing this method, make sure not to return any inherited
1368 /// members and check the MemberTypes and BindingFlags properly.
1369 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1370 /// get the BindingFlags (static/non-static,public/non-public) in the
1371 /// MemberInfo class, but the cache needs this information. That's why
1372 /// this method is called multiple times with different BindingFlags.
1374 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1377 /// Return the container's member cache.
1379 MemberCache MemberCache {
1385 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1386 /// member lookups. It has a member name based hash table; it maps each member
1387 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1388 /// and the BindingFlags that were initially used to get it. The cache contains
1389 /// all members of the current class and all inherited members. If this cache is
1390 /// for an interface types, it also contains all inherited members.
1392 /// There are two ways to get a MemberCache:
1393 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1394 /// use the DeclSpace.MemberCache property.
1395 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1396 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1398 public class MemberCache {
1399 public readonly IMemberContainer Container;
1400 protected Hashtable member_hash;
1401 protected Hashtable method_hash;
1404 /// Create a new MemberCache for the given IMemberContainer `container'.
1406 public MemberCache (IMemberContainer container)
1408 this.Container = container;
1410 Timer.IncrementCounter (CounterType.MemberCache);
1411 Timer.StartTimer (TimerType.CacheInit);
1413 // If we have a base class (we have a base class unless we're
1414 // TypeManager.object_type), we deep-copy its MemberCache here.
1415 if (Container.BaseCache != null)
1416 member_hash = DeepCopy (Container.BaseCache.member_hash);
1418 member_hash = new Hashtable ();
1420 // If this is neither a dynamic type nor an interface, create a special
1421 // method cache with all declared and inherited methods.
1422 Type type = container.Type;
1423 if (!(type is TypeBuilder) && !type.IsInterface) {
1424 if (Container.BaseCache != null) {
1425 method_hash = DeepCopy (Container.BaseCache.method_hash);
1426 ClearDeclaredOnly (method_hash);
1429 method_hash = new Hashtable ();
1433 // Add all members from the current class.
1434 AddMembers (Container);
1436 Timer.StopTimer (TimerType.CacheInit);
1439 public MemberCache (Type[] ifaces)
1442 // The members of this cache all belong to other caches.
1443 // So, 'Container' will not be used.
1445 this.Container = null;
1447 member_hash = new Hashtable ();
1451 foreach (Type itype in ifaces)
1452 AddCacheContents (TypeManager.LookupMemberCache (itype));
1456 /// Return a a deep-copy of the hashtable @other.
1458 Hashtable DeepCopy (Hashtable other)
1460 Hashtable hash = new Hashtable ();
1465 IDictionaryEnumerator it = other.GetEnumerator ();
1466 while (it.MoveNext ()) {
1467 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1473 void ClearDeclaredOnly (Hashtable hash)
1475 IDictionaryEnumerator it = hash.GetEnumerator ();
1476 while (it.MoveNext ()) {
1477 foreach (CacheEntry ce in (ArrayList) it.Value)
1478 ce.EntryType &= ~EntryType.Declared;
1483 /// Add the contents of `cache' to the member_hash.
1485 void AddCacheContents (MemberCache cache)
1487 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1488 while (it.MoveNext ()) {
1489 ArrayList list = (ArrayList) member_hash [it.Key];
1491 member_hash [it.Key] = list = new ArrayList ();
1493 ArrayList entries = (ArrayList) it.Value;
1494 for (int i = entries.Count-1; i >= 0; i--) {
1495 CacheEntry entry = (CacheEntry) entries [i];
1497 if (entry.Container != cache.Container)
1505 /// Add all members from class `container' to the cache.
1507 void AddMembers (IMemberContainer container)
1509 // We need to call AddMembers() with a single member type at a time
1510 // to get the member type part of CacheEntry.EntryType right.
1511 if (!container.IsInterface) {
1512 AddMembers (MemberTypes.Constructor, container);
1513 AddMembers (MemberTypes.Field, container);
1515 AddMembers (MemberTypes.Method, container);
1516 AddMembers (MemberTypes.Property, container);
1517 AddMembers (MemberTypes.Event, container);
1518 // Nested types are returned by both Static and Instance searches.
1519 AddMembers (MemberTypes.NestedType,
1520 BindingFlags.Static | BindingFlags.Public, container);
1521 AddMembers (MemberTypes.NestedType,
1522 BindingFlags.Static | BindingFlags.NonPublic, container);
1525 void AddMembers (MemberTypes mt, IMemberContainer container)
1527 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1528 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1529 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1530 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1534 /// Add all members from class `container' with the requested MemberTypes and
1535 /// BindingFlags to the cache. This method is called multiple times with different
1536 /// MemberTypes and BindingFlags.
1538 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1540 MemberList members = container.GetMembers (mt, bf);
1542 foreach (MemberInfo member in members) {
1543 string name = member.Name;
1545 // We use a name-based hash table of ArrayList's.
1546 ArrayList list = (ArrayList) member_hash [name];
1548 list = new ArrayList ();
1549 member_hash.Add (name, list);
1552 // When this method is called for the current class, the list will
1553 // already contain all inherited members from our base classes.
1554 // We cannot add new members in front of the list since this'd be an
1555 // expensive operation, that's why the list is sorted in reverse order
1556 // (ie. members from the current class are coming last).
1557 list.Add (new CacheEntry (container, member, mt, bf));
1562 /// Add all declared and inherited methods from class `type' to the method cache.
1564 void AddMethods (Type type)
1566 AddMethods (BindingFlags.Static | BindingFlags.Public |
1567 BindingFlags.FlattenHierarchy, type);
1568 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1569 BindingFlags.FlattenHierarchy, type);
1570 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1571 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1574 void AddMethods (BindingFlags bf, Type type)
1577 // Consider the case:
1579 // class X { public virtual int f() {} }
1582 // When processing 'Y', the method_cache will already have a copy of 'f',
1583 // with ReflectedType == X. However, we want to ensure that its ReflectedType == Y
1585 MethodBase [] members = type.GetMethods (bf);
1587 Array.Reverse (members);
1589 foreach (MethodBase member in members) {
1590 string name = member.Name;
1592 // We use a name-based hash table of ArrayList's.
1593 ArrayList list = (ArrayList) method_hash [name];
1595 list = new ArrayList ();
1596 method_hash.Add (name, list);
1599 Type declaring_type = member.DeclaringType;
1600 if (declaring_type == type) {
1601 list.Add (new CacheEntry (Container, member, MemberTypes.Method, bf | BindingFlags.DeclaredOnly));
1607 CacheEntry entry = (CacheEntry) list [n];
1608 MethodBase old = entry.Member as MethodBase;
1610 if (member.MethodHandle.Value == old.MethodHandle.Value &&
1611 declaring_type == old.DeclaringType) {
1612 entry.Member = member;
1618 throw new InternalErrorException ("cannot find inherited member " + member + " in base classes of " + type);
1623 /// Compute and return a appropriate `EntryType' magic number for the given
1624 /// MemberTypes and BindingFlags.
1626 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1628 EntryType type = EntryType.None;
1630 if ((mt & MemberTypes.Constructor) != 0)
1631 type |= EntryType.Constructor;
1632 if ((mt & MemberTypes.Event) != 0)
1633 type |= EntryType.Event;
1634 if ((mt & MemberTypes.Field) != 0)
1635 type |= EntryType.Field;
1636 if ((mt & MemberTypes.Method) != 0)
1637 type |= EntryType.Method;
1638 if ((mt & MemberTypes.Property) != 0)
1639 type |= EntryType.Property;
1640 // Nested types are returned by static and instance searches.
1641 if ((mt & MemberTypes.NestedType) != 0)
1642 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1644 if ((bf & BindingFlags.Instance) != 0)
1645 type |= EntryType.Instance;
1646 if ((bf & BindingFlags.Static) != 0)
1647 type |= EntryType.Static;
1648 if ((bf & BindingFlags.Public) != 0)
1649 type |= EntryType.Public;
1650 if ((bf & BindingFlags.NonPublic) != 0)
1651 type |= EntryType.NonPublic;
1652 if ((bf & BindingFlags.DeclaredOnly) != 0)
1653 type |= EntryType.Declared;
1659 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1660 /// denote multiple member types. Returns true if the given flags value denotes a
1661 /// single member types.
1663 public static bool IsSingleMemberType (MemberTypes mt)
1666 case MemberTypes.Constructor:
1667 case MemberTypes.Event:
1668 case MemberTypes.Field:
1669 case MemberTypes.Method:
1670 case MemberTypes.Property:
1671 case MemberTypes.NestedType:
1680 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1681 /// number to speed up the searching process.
1684 protected enum EntryType {
1689 MaskStatic = Instance|Static,
1693 MaskProtection = Public|NonPublic,
1697 Constructor = 0x020,
1704 MaskType = Constructor|Event|Field|Method|Property|NestedType
1707 protected class CacheEntry {
1708 public readonly IMemberContainer Container;
1709 public EntryType EntryType;
1710 public MemberInfo Member;
1712 public CacheEntry (IMemberContainer container, MemberInfo member,
1713 MemberTypes mt, BindingFlags bf)
1715 this.Container = container;
1716 this.Member = member;
1717 this.EntryType = GetEntryType (mt, bf);
1720 public override string ToString ()
1722 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1728 /// This is called each time we're walking up one level in the class hierarchy
1729 /// and checks whether we can abort the search since we've already found what
1730 /// we were looking for.
1732 protected bool DoneSearching (ArrayList list)
1735 // We've found exactly one member in the current class and it's not
1736 // a method or constructor.
1738 if (list.Count == 1 && !(list [0] is MethodBase))
1742 // Multiple properties: we query those just to find out the indexer
1745 if ((list.Count > 0) && (list [0] is PropertyInfo))
1752 /// Looks up members with name `name'. If you provide an optional
1753 /// filter function, it'll only be called with members matching the
1754 /// requested member name.
1756 /// This method will try to use the cache to do the lookup if possible.
1758 /// Unlike other FindMembers implementations, this method will always
1759 /// check all inherited members - even when called on an interface type.
1761 /// If you know that you're only looking for methods, you should use
1762 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1763 /// When doing a method-only search, it'll try to use a special method
1764 /// cache (unless it's a dynamic type or an interface) and the returned
1765 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1766 /// The lookup process will automatically restart itself in method-only
1767 /// search mode if it discovers that it's about to return methods.
1769 ArrayList global = new ArrayList ();
1770 bool using_global = false;
1772 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1774 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1775 MemberFilter filter, object criteria)
1778 throw new Exception ();
1780 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1781 bool method_search = mt == MemberTypes.Method;
1782 // If we have a method cache and we aren't already doing a method-only search,
1783 // then we restart a method search if the first match is a method.
1784 bool do_method_search = !method_search && (method_hash != null);
1786 ArrayList applicable;
1788 // If this is a method-only search, we try to use the method cache if
1789 // possible; a lookup in the method cache will return a MemberInfo with
1790 // the correct ReflectedType for inherited methods.
1792 if (method_search && (method_hash != null))
1793 applicable = (ArrayList) method_hash [name];
1795 applicable = (ArrayList) member_hash [name];
1797 if (applicable == null)
1798 return emptyMemberInfo;
1801 // 32 slots gives 53 rss/54 size
1802 // 2/4 slots gives 55 rss
1804 // Strange: from 25,000 calls, only 1,800
1805 // are above 2. Why does this impact it?
1808 using_global = true;
1810 Timer.StartTimer (TimerType.CachedLookup);
1812 EntryType type = GetEntryType (mt, bf);
1814 IMemberContainer current = Container;
1817 // `applicable' is a list of all members with the given member name `name'
1818 // in the current class and all its base classes. The list is sorted in
1819 // reverse order due to the way how the cache is initialy created (to speed
1820 // things up, we're doing a deep-copy of our base).
1822 for (int i = applicable.Count-1; i >= 0; i--) {
1823 CacheEntry entry = (CacheEntry) applicable [i];
1825 // This happens each time we're walking one level up in the class
1826 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1827 // the first time this happens (this may already happen in the first
1828 // iteration of this loop if there are no members with the name we're
1829 // looking for in the current class).
1830 if (entry.Container != current) {
1831 if (declared_only || DoneSearching (global))
1834 current = entry.Container;
1837 // Is the member of the correct type ?
1838 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1841 // Is the member static/non-static ?
1842 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1845 // Apply the filter to it.
1846 if (filter (entry.Member, criteria)) {
1847 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1848 do_method_search = false;
1849 global.Add (entry.Member);
1853 Timer.StopTimer (TimerType.CachedLookup);
1855 // If we have a method cache and we aren't already doing a method-only
1856 // search, we restart in method-only search mode if the first match is
1857 // a method. This ensures that we return a MemberInfo with the correct
1858 // ReflectedType for inherited methods.
1859 if (do_method_search && (global.Count > 0)){
1860 using_global = false;
1862 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1865 using_global = false;
1866 MemberInfo [] copy = new MemberInfo [global.Count];
1867 global.CopyTo (copy);
1871 // find the nested type @name in @this.
1872 public Type FindNestedType (string name)
1874 ArrayList applicable = (ArrayList) member_hash [name];
1875 if (applicable == null)
1878 for (int i = applicable.Count-1; i >= 0; i--) {
1879 CacheEntry entry = (CacheEntry) applicable [i];
1880 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
1881 return (Type) entry.Member;
1888 // This finds the method or property for us to override. invocationType is the type where
1889 // the override is going to be declared, name is the name of the method/property, and
1890 // paramTypes is the parameters, if any to the method or property
1892 // Because the MemberCache holds members from this class and all the base classes,
1893 // we can avoid tons of reflection stuff.
1895 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1897 ArrayList applicable;
1898 if (method_hash != null && !is_property)
1899 applicable = (ArrayList) method_hash [name];
1901 applicable = (ArrayList) member_hash [name];
1903 if (applicable == null)
1906 // Walk the chain of methods, starting from the top.
1908 for (int i = applicable.Count - 1; i >= 0; i--) {
1909 CacheEntry entry = (CacheEntry) applicable [i];
1911 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1914 PropertyInfo pi = null;
1915 MethodInfo mi = null;
1916 FieldInfo fi = null;
1917 Type [] cmpAttrs = null;
1920 if ((entry.EntryType & EntryType.Field) != 0) {
1921 fi = (FieldInfo)entry.Member;
1923 // TODO: For this case we ignore member type
1924 //fb = TypeManager.GetField (fi);
1925 //cmpAttrs = new Type[] { fb.MemberType };
1927 pi = (PropertyInfo) entry.Member;
1928 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1931 mi = (MethodInfo) entry.Member;
1932 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1936 // TODO: Almost duplicate !
1938 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1939 case FieldAttributes.Private:
1941 // A private method is Ok if we are a nested subtype.
1942 // The spec actually is not very clear about this, see bug 52458.
1944 if (invocationType != entry.Container.Type &
1945 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1949 case FieldAttributes.FamANDAssem:
1950 case FieldAttributes.Assembly:
1952 // Check for assembly methods
1954 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1958 return entry.Member;
1962 // Check the arguments
1964 if (cmpAttrs.Length != paramTypes.Length)
1967 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1968 if (paramTypes [j] != cmpAttrs [j])
1972 // get one of the methods because this has the visibility info.
1975 mi = pi.GetGetMethod (true);
1977 mi = pi.GetSetMethod (true);
1983 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1984 case MethodAttributes.Private:
1986 // A private method is Ok if we are a nested subtype.
1987 // The spec actually is not very clear about this, see bug 52458.
1989 if (invocationType == entry.Container.Type ||
1990 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1991 return entry.Member;
1994 case MethodAttributes.FamANDAssem:
1995 case MethodAttributes.Assembly:
1997 // Check for assembly methods
1999 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2000 return entry.Member;
2005 // A protected method is ok, because we are overriding.
2006 // public is always ok.
2008 return entry.Member;
2018 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2019 /// We handle two cases. The first is for types without parameters (events, field, properties).
2020 /// The second are methods, indexers and this is why ignore_complex_types is here.
2021 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2023 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2025 ArrayList applicable = null;
2027 if (method_hash != null)
2028 applicable = (ArrayList) method_hash [name];
2030 if (applicable != null) {
2031 for (int i = applicable.Count - 1; i >= 0; i--) {
2032 CacheEntry entry = (CacheEntry) applicable [i];
2033 if ((entry.EntryType & EntryType.Public) != 0)
2034 return entry.Member;
2038 if (member_hash == null)
2040 applicable = (ArrayList) member_hash [name];
2042 if (applicable != null) {
2043 for (int i = applicable.Count - 1; i >= 0; i--) {
2044 CacheEntry entry = (CacheEntry) applicable [i];
2045 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2046 if (ignore_complex_types) {
2047 if ((entry.EntryType & EntryType.Method) != 0)
2050 // Does exist easier way how to detect indexer ?
2051 if ((entry.EntryType & EntryType.Property) != 0) {
2052 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2053 if (arg_types.Length > 0)
2057 return entry.Member;
2064 Hashtable locase_table;
2067 /// Builds low-case table for CLS Compliance test
2069 public Hashtable GetPublicMembers ()
2071 if (locase_table != null)
2072 return locase_table;
2074 locase_table = new Hashtable ();
2075 foreach (DictionaryEntry entry in member_hash) {
2076 ArrayList members = (ArrayList)entry.Value;
2077 for (int ii = 0; ii < members.Count; ++ii) {
2078 CacheEntry member_entry = (CacheEntry) members [ii];
2080 if ((member_entry.EntryType & EntryType.Public) == 0)
2083 // TODO: Does anyone know easier way how to detect that member is internal ?
2084 switch (member_entry.EntryType & EntryType.MaskType) {
2085 case EntryType.Constructor:
2088 case EntryType.Field:
2089 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2093 case EntryType.Method:
2094 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2098 case EntryType.Property:
2099 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2100 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2104 case EntryType.Event:
2105 EventInfo ei = (EventInfo)member_entry.Member;
2106 MethodInfo mi = ei.GetAddMethod ();
2107 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2111 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2112 locase_table [lcase] = member_entry.Member;
2116 return locase_table;
2119 public Hashtable Members {
2126 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2128 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2130 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2132 for (int i = 0; i < al.Count; ++i) {
2133 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2136 if (entry.Member == this_builder)
2139 if ((entry.EntryType & tested_type) != tested_type)
2142 MethodBase method_to_compare = (MethodBase)entry.Member;
2143 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2146 IMethodData md = TypeManager.GetMethod (method_to_compare);
2148 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2149 // However it is exactly what csc does.
2150 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2153 Report.SymbolRelatedToPreviousError (entry.Member);
2154 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());