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)
11 // 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 namespace Mono.CSharp {
23 public class MemberName {
25 public readonly TypeArguments TypeArguments;
27 public readonly MemberName Left;
29 public static readonly MemberName Null = new MemberName ("");
31 public MemberName (string name)
36 public MemberName (string name, TypeArguments args)
39 this.TypeArguments = args;
42 public MemberName (MemberName left, string name, TypeArguments args)
48 public MemberName (MemberName left, MemberName right)
49 : this (left, right.Name, right.TypeArguments)
53 public string GetName ()
56 return Left.GetName () + "." + Name;
61 public bool IsGeneric {
63 if (TypeArguments != null)
65 else if (Left != null)
66 return Left.IsGeneric;
72 public string GetName (bool is_generic)
74 string name = is_generic ? Basename : Name;
76 return Left.GetName (is_generic) + "." + name;
81 public int CountTypeArguments {
83 if (TypeArguments == null)
86 return TypeArguments.Count;
90 public string GetMethodName ()
93 return Left.GetPartialName () + "." + Name;
99 /// This returns exclusively the name as seen on the source code
100 /// it is not the fully qualifed type after resolution
102 public string GetPartialName ()
105 if (TypeArguments != null)
106 full_name = Name + "<" + TypeArguments + ">";
110 return Left.GetPartialName () + "." + full_name;
115 public static string MakeName (string name, TypeArguments args)
120 return name + "`" + args.Count;
123 public static string MakeName (string name, int count)
125 return name + "`" + count;
128 public string GetTypeName ()
132 return Left.GetTypeName () + "." +
133 MakeName (Name, TypeArguments);
135 return MakeName (Name, TypeArguments);
138 protected bool IsUnbound {
140 if ((Left != null) && Left.IsUnbound)
142 else if (TypeArguments == null)
145 return TypeArguments.IsUnbound;
149 protected bool CheckUnbound (Location loc)
151 if ((Left != null) && !Left.CheckUnbound (loc))
153 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
154 Report.Error (1031, loc, "Type expected");
161 public Expression GetTypeExpression (Location loc)
164 if (!CheckUnbound (loc))
167 return new UnboundTypeExpression (GetTypeName ());
171 Expression lexpr = Left.GetTypeExpression (loc);
173 return new MemberAccess (lexpr, Name, TypeArguments, loc);
175 if (TypeArguments != null)
176 return new ConstructedType (Name, TypeArguments, loc);
178 return new SimpleName (Name, loc);
182 public MemberName Clone ()
185 return new MemberName (Left.Clone (), Name, TypeArguments);
187 return new MemberName (Name, TypeArguments);
190 public string Basename {
192 if (TypeArguments != null)
193 return MakeName (Name, TypeArguments);
199 public override string ToString ()
201 throw new Exception ("This exception is thrown because someone is miss-using\n" +
202 "MemberName.ToString in the compiler. Please report this bug");
205 if (TypeArguments != null)
206 full_name = Name + "<" + TypeArguments + ">";
211 return Left + "." + full_name;
218 /// Base representation for members. This is used to keep track
219 /// of Name, Location and Modifier flags, and handling Attributes.
221 public abstract class MemberCore : Attributable {
227 return MemberName.GetName (!(this is GenericMethod) && !(this is Method));
231 public readonly MemberName MemberName;
234 /// Modifier flags that the user specified in the source code
238 public readonly TypeContainer Parent;
241 /// Location where this declaration happens
243 public readonly Location Location;
247 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
248 Obsolete = 1 << 1, // Type has obsolete attribute
249 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
250 ClsCompliant = 1 << 3, // Type is CLS Compliant
251 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
252 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
253 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
254 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
255 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
256 Excluded = 1 << 9, // Method is conditional
257 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
261 /// MemberCore flags at first detected then cached
263 internal Flags caching_flags;
265 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
272 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
276 /// Tests presence of ObsoleteAttribute and report proper error
278 protected void CheckUsageOfObsoleteAttribute (Type type)
283 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
284 if (obsolete_attr == null)
287 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
290 public abstract bool Define ();
293 // Returns full member name for error message
295 public virtual string GetSignatureForError ()
301 /// Use this method when MethodBuilder is null
303 public virtual string GetSignatureForError (TypeContainer tc)
309 /// Base Emit method. This is also entry point for CLS-Compliant verification.
311 public virtual void Emit ()
313 VerifyObsoleteAttribute ();
315 if (!RootContext.VerifyClsCompliance)
318 VerifyClsCompliance (Parent);
321 public bool InUnsafe {
323 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
328 // Whehter is it ok to use an unsafe pointer in this type container
330 public bool UnsafeOK (DeclSpace parent)
333 // First check if this MemberCore modifier flags has unsafe set
335 if ((ModFlags & Modifiers.UNSAFE) != 0)
338 if (parent.UnsafeContext)
341 Expression.UnsafeError (Location);
346 /// Returns instance of ObsoleteAttribute for this MemberCore
348 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
350 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
351 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
355 caching_flags &= ~Flags.Obsolete_Undetected;
357 if (OptAttributes == null)
360 Attribute obsolete_attr = OptAttributes.Search (
361 TypeManager.obsolete_attribute_type, ds.EmitContext);
362 if (obsolete_attr == null)
365 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
366 if (obsolete == null)
369 caching_flags |= Flags.Obsolete;
374 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
376 public override bool IsClsCompliaceRequired (DeclSpace container)
378 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
379 return (caching_flags & Flags.ClsCompliant) != 0;
381 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
382 caching_flags &= ~Flags.ClsCompliance_Undetected;
383 caching_flags |= Flags.ClsCompliant;
387 caching_flags &= ~Flags.ClsCompliance_Undetected;
392 /// Returns true when MemberCore is exposed from assembly.
394 protected bool IsExposedFromAssembly (DeclSpace ds)
396 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
399 DeclSpace parentContainer = ds;
400 while (parentContainer != null && parentContainer.ModFlags != 0) {
401 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
403 parentContainer = parentContainer.Parent;
409 /// Resolve CLSCompliantAttribute value or gets cached value.
411 bool GetClsCompliantAttributeValue (DeclSpace ds)
413 if (OptAttributes != null) {
414 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ds.EmitContext);
415 if (cls_attribute != null) {
416 caching_flags |= Flags.HasClsCompliantAttribute;
417 return cls_attribute.GetClsCompliantAttributeValue (ds);
420 return ds.GetClsCompliantAttributeValue ();
424 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
426 protected bool HasClsCompliantAttribute {
428 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
433 /// The main virtual method for CLS-Compliant verifications.
434 /// The method returns true if member is CLS-Compliant and false if member is not
435 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
436 /// and add their extra verifications.
438 protected virtual bool VerifyClsCompliance (DeclSpace ds)
440 if (!IsClsCompliaceRequired (ds)) {
441 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
442 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
447 if (!CodeGen.Assembly.IsClsCompliant) {
448 if (HasClsCompliantAttribute) {
449 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
454 int index = Name.LastIndexOf ('.');
455 if (Name [index > 0 ? index + 1 : 0] == '_') {
456 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
461 protected abstract void VerifyObsoleteAttribute ();
466 /// Base class for structs, classes, enumerations and interfaces.
469 /// They all create new declaration spaces. This
470 /// provides the common foundation for managing those name
473 public abstract class DeclSpace : MemberCore, IAlias {
475 /// This points to the actual definition that is being
476 /// created with System.Reflection.Emit
478 public TypeBuilder TypeBuilder;
481 /// If we are a generic type, this is the type we are
482 /// currently defining. We need to lookup members on this
483 /// instead of the TypeBuilder.
485 public TypeExpr CurrentType;
488 // This is the namespace in which this typecontainer
489 // was declared. We use this to resolve names.
491 public NamespaceEntry NamespaceEntry;
493 public Hashtable Cache = new Hashtable ();
495 public string Basename;
497 protected Hashtable defined_names;
499 readonly bool is_generic;
500 readonly int count_type_params;
502 // The emit context for toplevel objects.
503 protected EmitContext ec;
505 public EmitContext EmitContext {
510 // Whether we are Generic
512 public bool IsGeneric {
516 else if (Parent != null)
517 return Parent.IsGeneric;
523 static string[] attribute_targets = new string [] { "type" };
525 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
526 Attributes attrs, Location l)
527 : base (parent, name, attrs, l)
530 Basename = name.Name;
531 defined_names = new Hashtable ();
532 if (name.TypeArguments != null) {
534 count_type_params = name.TypeArguments.Count;
537 count_type_params += parent.count_type_params;
541 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
543 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
545 if (basename == Basename) {
546 Report.SymbolRelatedToPreviousError (this);
547 Report.Error (542, "'{0}': member names cannot be the same as their enclosing type", symbol.Location, symbol.GetSignatureForError ());
551 MemberCore mc = (MemberCore)defined_names [fullname];
553 if (is_method && (mc is MethodCore || mc is IMethodData)) {
554 symbol.caching_flags |= Flags.TestMethodDuplication;
555 mc.caching_flags |= Flags.TestMethodDuplication;
560 Report.SymbolRelatedToPreviousError (mc);
561 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
565 defined_names.Add (fullname, symbol);
569 public void RecordDecl ()
571 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
572 NamespaceEntry.DefineName (MemberName.Basename, this);
576 /// Returns the MemberCore associated with a given name in the declaration
577 /// space. It doesn't return method based symbols !!
580 public MemberCore GetDefinition (string name)
582 return (MemberCore)defined_names [name];
585 bool in_transit = false;
588 /// This function is used to catch recursive definitions
591 public bool InTransit {
602 /// Looks up the alias for the name
604 public IAlias LookupAlias (string name)
606 if (NamespaceEntry != null)
607 return NamespaceEntry.LookupAlias (name);
613 // root_types contains all the types. All TopLevel types
614 // hence have a parent that points to `root_types', that is
615 // why there is a non-obvious test down here.
617 public bool IsTopLevel {
620 if (Parent.Parent == null)
627 public virtual void CloseType ()
629 if ((caching_flags & Flags.CloseTypeCreated) == 0){
631 TypeBuilder.CreateType ();
634 // The try/catch is needed because
635 // nested enumerations fail to load when they
638 // Even if this is the right order (enumerations
639 // declared after types).
641 // Note that this still creates the type and
642 // it is possible to save it
644 caching_flags |= Flags.CloseTypeCreated;
649 /// Should be overriten by the appropriate declaration space
651 public abstract TypeBuilder DefineType ();
654 /// Define all members, but don't apply any attributes or do anything which may
655 /// access not-yet-defined classes. This method also creates the MemberCache.
657 public abstract bool DefineMembers (TypeContainer parent);
660 // Whether this is an `unsafe context'
662 public bool UnsafeContext {
664 if ((ModFlags & Modifiers.UNSAFE) != 0)
667 return Parent.UnsafeContext;
672 public static string MakeFQN (string nsn, string name)
676 return String.Concat (nsn, ".", name);
679 EmitContext type_resolve_ec;
680 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
682 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
683 type_resolve_ec.ResolvingTypeTree = true;
685 return type_resolve_ec;
689 // Looks up the type, as parsed into the expression `e'.
691 [Obsolete ("This method is going away soon")]
692 public Type ResolveType (Expression e, bool silent, Location loc)
694 TypeExpr d = ResolveTypeExpr (e, silent, loc);
695 return d == null ? null : d.Type;
698 public Type ResolveNestedType (Type t, Location loc)
700 TypeContainer tc = TypeManager.LookupTypeContainer (t);
701 if ((tc != null) && tc.IsGeneric) {
703 int tnum = TypeManager.GetNumberOfTypeArguments (t);
704 Report.Error (305, loc,
705 "Using the generic type `{0}' " +
706 "requires {1} type arguments",
707 TypeManager.GetFullName (t), tnum);
711 TypeParameter[] args;
712 if (this is GenericMethod)
713 args = Parent.TypeParameters;
715 args = TypeParameters;
717 ConstructedType ctype = new ConstructedType (t, args, loc);
718 t = ctype.ResolveType (ec);
725 // Resolves the expression `e' for a type, and will recursively define
726 // types. This should only be used for resolving base types.
728 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
730 if (type_resolve_ec == null)
731 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
732 type_resolve_ec.loc = loc;
733 if (this is GenericMethod)
734 type_resolve_ec.ContainerType = Parent.TypeBuilder;
736 type_resolve_ec.ContainerType = TypeBuilder;
738 return e.ResolveAsTypeTerminal (type_resolve_ec, silent);
741 public bool CheckAccessLevel (Type check_type)
744 if ((this is GenericMethod) || (this is Iterator))
745 tb = Parent.TypeBuilder;
749 if (check_type.IsGenericInstance)
750 check_type = check_type.GetGenericTypeDefinition ();
752 if (check_type == tb)
755 if (check_type.IsGenericParameter)
756 return true; // FIXME
758 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
761 // Broken Microsoft runtime, return public for arrays, no matter what
762 // the accessibility is for their underlying class, and they return
763 // NonPublic visibility for pointers
765 if (check_type.IsArray || check_type.IsPointer)
766 return CheckAccessLevel (TypeManager.GetElementType (check_type));
769 case TypeAttributes.Public:
772 case TypeAttributes.NotPublic:
774 if (TypeBuilder == null)
775 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
776 // However, this is invoked again later -- so safe to return true.
777 // May also be null when resolving top-level attributes.
780 // This test should probably use the declaringtype.
782 return check_type.Assembly == TypeBuilder.Assembly;
784 case TypeAttributes.NestedPublic:
787 case TypeAttributes.NestedPrivate:
788 return NestedAccessible (tb, check_type);
790 case TypeAttributes.NestedFamily:
792 // Only accessible to methods in current type or any subtypes
794 return FamilyAccessible (tb, check_type);
796 case TypeAttributes.NestedFamANDAssem:
797 return (check_type.Assembly == tb.Assembly) &&
798 FamilyAccessible (tb, check_type);
800 case TypeAttributes.NestedFamORAssem:
801 return (check_type.Assembly == tb.Assembly) ||
802 FamilyAccessible (tb, check_type);
804 case TypeAttributes.NestedAssembly:
805 return check_type.Assembly == tb.Assembly;
808 Console.WriteLine ("HERE: " + check_attr);
813 protected bool NestedAccessible (Type tb, Type check_type)
815 string check_type_name = check_type.FullName;
817 // At this point, we already know check_type is a nested class.
818 int cio = check_type_name.LastIndexOf ('+');
820 // Ensure that the string 'container' has a '+' in it to avoid false matches
821 string container = check_type_name.Substring (0, cio + 1);
823 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
824 string type_name = tb.FullName + "+";
826 // If the current class is nested inside the container of check_type,
827 // we can access check_type even if it is private or protected.
828 return type_name.StartsWith (container);
831 protected bool FamilyAccessible (Type tb, Type check_type)
833 Type declaring = check_type.DeclaringType;
834 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
837 return NestedAccessible (tb, check_type);
840 // Access level of a type.
842 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
843 // Public Assembly Protected
844 Protected = (0 << 0) | (0 << 1) | (X << 2),
845 Public = (X << 0) | (X << 1) | (X << 2),
846 Private = (0 << 0) | (0 << 1) | (0 << 2),
847 Internal = (0 << 0) | (X << 1) | (0 << 2),
848 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
851 static AccessLevel GetAccessLevelFromModifiers (int flags)
853 if ((flags & Modifiers.INTERNAL) != 0) {
855 if ((flags & Modifiers.PROTECTED) != 0)
856 return AccessLevel.ProtectedOrInternal;
858 return AccessLevel.Internal;
860 } else if ((flags & Modifiers.PROTECTED) != 0)
861 return AccessLevel.Protected;
862 else if ((flags & Modifiers.PRIVATE) != 0)
863 return AccessLevel.Private;
865 return AccessLevel.Public;
868 // What is the effective access level of this?
870 AccessLevel EffectiveAccessLevel {
872 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
873 if (!IsTopLevel && (Parent != null))
874 return myAccess & Parent.EffectiveAccessLevel;
879 // Return the access level for type `t'
880 static AccessLevel TypeEffectiveAccessLevel (Type t)
883 return AccessLevel.Public;
884 if (t.IsNestedPrivate)
885 return AccessLevel.Private;
887 return AccessLevel.Internal;
889 // By now, it must be nested
890 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
892 if (t.IsNestedPublic)
894 if (t.IsNestedAssembly)
895 return parentLevel & AccessLevel.Internal;
896 if (t.IsNestedFamily)
897 return parentLevel & AccessLevel.Protected;
898 if (t.IsNestedFamORAssem)
899 return parentLevel & AccessLevel.ProtectedOrInternal;
900 if (t.IsNestedFamANDAssem)
901 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
903 // nested private is taken care of
905 throw new Exception ("I give up, what are you?");
909 // This answers `is the type P, as accessible as a member M which has the
910 // accessability @flags which is declared as a nested member of the type T, this declspace'
912 public bool AsAccessible (Type p, int flags)
914 if (p.IsGenericParameter)
915 return true; // FIXME
918 // 1) if M is private, its accessability is the same as this declspace.
919 // we already know that P is accessible to T before this method, so we
923 if ((flags & Modifiers.PRIVATE) != 0)
926 while (p.IsArray || p.IsPointer || p.IsByRef)
927 p = TypeManager.GetElementType (p);
929 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
930 AccessLevel mAccess = this.EffectiveAccessLevel &
931 GetAccessLevelFromModifiers (flags);
933 // for every place from which we can access M, we must
934 // be able to access P as well. So, we want
935 // For every bit in M and P, M_i -> P_1 == true
936 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
938 return ~ (~ mAccess | pAccess) == 0;
941 static DoubleHash dh = new DoubleHash (1000);
943 Type DefineTypeAndParents (DeclSpace tc)
945 DeclSpace container = tc.Parent;
947 if (container.TypeBuilder == null && container.Name != "")
948 DefineTypeAndParents (container);
950 return tc.DefineType ();
953 Type LookupInterfaceOrClass (string ns, string name, out bool error)
961 if (dh.Lookup (ns, name, out r))
965 if (Namespace.IsNamespace (ns)){
966 string fullname = (ns != "") ? ns + "." + name : name;
967 t = TypeManager.LookupType (fullname);
971 t = TypeManager.LookupType (name);
975 dh.Insert (ns, name, t);
980 // In case we are fed a composite name, normalize it.
982 int p = name.LastIndexOf ('.');
984 ns = MakeFQN (ns, name.Substring (0, p));
985 name = name.Substring (p+1);
988 parent = RootContext.Tree.LookupByNamespace (ns, name);
989 if (parent == null) {
990 dh.Insert (ns, name, null);
994 t = DefineTypeAndParents (parent);
1000 dh.Insert (ns, name, t);
1004 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1006 Report.Error (104, loc,
1007 "`{0}' is an ambiguous reference ({1} or {2})",
1011 public Type FindNestedType (Location loc, string name,
1012 out DeclSpace containing_ds)
1017 containing_ds = this;
1018 while (containing_ds != null){
1019 Type container_type = containing_ds.TypeBuilder;
1020 Type current_type = container_type;
1022 while (current_type != null && current_type != TypeManager.object_type) {
1023 string pre = current_type.FullName;
1025 t = LookupInterfaceOrClass (pre, name, out error);
1029 if ((t != null) && containing_ds.CheckAccessLevel (t))
1032 current_type = current_type.BaseType;
1034 containing_ds = containing_ds.Parent;
1041 /// GetType is used to resolve type names at the DeclSpace level.
1042 /// Use this to lookup class/struct bases, interface bases or
1043 /// delegate type references
1047 /// Contrast this to LookupType which is used inside method bodies to
1048 /// lookup types that have already been defined. GetType is used
1049 /// during the tree resolution process and potentially define
1050 /// recursively the type
1052 public Type FindType (Location loc, string name)
1058 // For the case the type we are looking for is nested within this one
1059 // or is in any base class
1061 DeclSpace containing_ds = this;
1063 while (containing_ds != null){
1064 Type container_type = containing_ds.TypeBuilder;
1065 Type current_type = container_type;
1067 while (current_type != null && current_type != TypeManager.object_type) {
1068 string pre = current_type.FullName;
1070 t = LookupInterfaceOrClass (pre, name, out error);
1074 if ((t != null) && containing_ds.CheckAccessLevel (t))
1075 return ResolveNestedType (t, loc);
1077 current_type = current_type.BaseType;
1079 containing_ds = containing_ds.Parent;
1083 // Attempt to lookup the class on our namespace and all it's implicit parents
1085 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1086 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1095 // Attempt to do a direct unqualified lookup
1097 t = LookupInterfaceOrClass ("", name, out error);
1105 // Attempt to lookup the class on any of the `using'
1109 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1111 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1118 if (name.IndexOf ('.') > 0)
1121 IAlias alias_value = ns.LookupAlias (name);
1122 if (alias_value != null) {
1123 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1132 // Now check the using clause list
1135 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1136 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1140 if (match != null) {
1142 if (CheckAccessLevel (match)) {
1143 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1156 //Report.Error (246, Location, "Can not find type `"+name+"'");
1161 /// This function is broken and not what you're looking for. It should only
1162 /// be used while the type is still being created since it doesn't use the cache
1163 /// and relies on the filter doing the member name check.
1165 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1166 MemberFilter filter, object criteria);
1169 /// If we have a MemberCache, return it. This property may return null if the
1170 /// class doesn't have a member cache or while it's still being created.
1172 public abstract MemberCache MemberCache {
1176 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1179 TypeBuilder.SetCustomAttribute (cb);
1180 } catch (System.ArgumentException e) {
1181 Report.Warning (-21, a.Location,
1182 "The CharSet named property on StructLayout\n"+
1183 "\tdoes not work correctly on Microsoft.NET\n"+
1184 "\tYou might want to remove the CharSet declaration\n"+
1185 "\tor compile using the Mono runtime instead of the\n"+
1186 "\tMicrosoft .NET runtime\n"+
1187 "\tThe runtime gave the error: " + e);
1192 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1193 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1195 public bool GetClsCompliantAttributeValue ()
1197 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1198 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1200 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1202 if (OptAttributes != null) {
1203 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1204 if (cls_attribute != null) {
1205 caching_flags |= Flags.HasClsCompliantAttribute;
1206 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1207 caching_flags |= Flags.ClsCompliantAttributeTrue;
1214 if (Parent == null) {
1215 if (CodeGen.Assembly.IsClsCompliant) {
1216 caching_flags |= Flags.ClsCompliantAttributeTrue;
1222 if (Parent.GetClsCompliantAttributeValue ()) {
1223 caching_flags |= Flags.ClsCompliantAttributeTrue;
1230 // Extensions for generics
1232 TypeParameter[] type_params;
1233 TypeParameter[] type_param_list;
1235 protected string GetInstantiationName ()
1237 StringBuilder sb = new StringBuilder (Name);
1239 for (int i = 0; i < type_param_list.Length; i++) {
1242 sb.Append (type_param_list [i].Name);
1245 return sb.ToString ();
1248 bool check_type_parameter (ArrayList list, int start, string name)
1250 for (int i = 0; i < start; i++) {
1251 TypeParameter param = (TypeParameter) list [i];
1253 if (param.Name != name)
1256 if (RootContext.WarningLevel >= 3)
1259 "Type parameter `{0}' has same name " +
1260 "as type parameter from outer type `{1}'",
1261 name, Parent.GetInstantiationName ());
1269 TypeParameter[] initialize_type_params ()
1271 if (type_param_list != null)
1272 return type_param_list;
1274 DeclSpace the_parent = Parent;
1275 if (this is GenericMethod)
1279 TypeParameter[] parent_params = null;
1280 if ((the_parent != null) && the_parent.IsGeneric) {
1281 parent_params = the_parent.initialize_type_params ();
1282 start = parent_params != null ? parent_params.Length : 0;
1285 ArrayList list = new ArrayList ();
1286 if (parent_params != null)
1287 list.AddRange (parent_params);
1289 int count = type_params != null ? type_params.Length : 0;
1290 for (int i = 0; i < count; i++) {
1291 TypeParameter param = type_params [i];
1292 check_type_parameter (list, start, param.Name);
1296 type_param_list = new TypeParameter [list.Count];
1297 list.CopyTo (type_param_list, 0);
1298 return type_param_list;
1301 public void SetParameterInfo (ArrayList constraints_list)
1304 if (constraints_list != null) {
1306 80, Location, "Contraints are not allowed " +
1307 "on non-generic declarations");
1313 string[] names = MemberName.TypeArguments.GetDeclarations ();
1314 type_params = new TypeParameter [names.Length];
1317 // Register all the names
1319 for (int i = 0; i < type_params.Length; i++) {
1320 string name = names [i];
1322 Constraints constraints = null;
1323 if (constraints_list != null) {
1324 foreach (Constraints constraint in constraints_list) {
1325 if (constraint.TypeParameter == name) {
1326 constraints = constraint;
1332 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1334 string full_name = Name + "." + name;
1335 AddToContainer (type_params [i], false, full_name, name);
1339 public TypeParameter[] TypeParameters {
1342 throw new InvalidOperationException ();
1343 if (type_param_list == null)
1344 initialize_type_params ();
1346 return type_param_list;
1350 protected TypeParameter[] CurrentTypeParameters {
1353 throw new InvalidOperationException ();
1354 if (type_params != null)
1357 return new TypeParameter [0];
1361 public int CountTypeParameters {
1363 return count_type_params;
1367 public TypeParameterExpr LookupGeneric (string name, Location loc)
1372 foreach (TypeParameter type_param in CurrentTypeParameters) {
1373 if (type_param.Name != name)
1376 return new TypeParameterExpr (type_param, loc);
1380 return Parent.LookupGeneric (name, loc);
1385 bool IAlias.IsType {
1386 get { return true; }
1389 string IAlias.Name {
1390 get { return Name; }
1393 TypeExpr IAlias.Type
1396 if (TypeBuilder == null)
1397 throw new InvalidOperationException ();
1399 if (CurrentType != null)
1402 return new TypeExpression (TypeBuilder, Location);
1406 public override string[] ValidAttributeTargets {
1408 return attribute_targets;
1414 /// This is a readonly list of MemberInfo's.
1416 public class MemberList : IList {
1417 public readonly IList List;
1421 /// Create a new MemberList from the given IList.
1423 public MemberList (IList list)
1428 this.List = new ArrayList ();
1433 /// Concatenate the ILists `first' and `second' to a new MemberList.
1435 public MemberList (IList first, IList second)
1437 ArrayList list = new ArrayList ();
1438 list.AddRange (first);
1439 list.AddRange (second);
1444 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1447 /// Cast the MemberList into a MemberInfo[] array.
1450 /// This is an expensive operation, only use it if it's really necessary.
1452 public static explicit operator MemberInfo [] (MemberList list)
1454 Timer.StartTimer (TimerType.MiscTimer);
1455 MemberInfo [] result = new MemberInfo [list.Count];
1456 list.CopyTo (result, 0);
1457 Timer.StopTimer (TimerType.MiscTimer);
1469 public bool IsSynchronized {
1471 return List.IsSynchronized;
1475 public object SyncRoot {
1477 return List.SyncRoot;
1481 public void CopyTo (Array array, int index)
1483 List.CopyTo (array, index);
1488 public IEnumerator GetEnumerator ()
1490 return List.GetEnumerator ();
1495 public bool IsFixedSize {
1501 public bool IsReadOnly {
1507 object IList.this [int index] {
1509 return List [index];
1513 throw new NotSupportedException ();
1517 // FIXME: try to find out whether we can avoid the cast in this indexer.
1518 public MemberInfo this [int index] {
1520 return (MemberInfo) List [index];
1524 public int Add (object value)
1526 throw new NotSupportedException ();
1529 public void Clear ()
1531 throw new NotSupportedException ();
1534 public bool Contains (object value)
1536 return List.Contains (value);
1539 public int IndexOf (object value)
1541 return List.IndexOf (value);
1544 public void Insert (int index, object value)
1546 throw new NotSupportedException ();
1549 public void Remove (object value)
1551 throw new NotSupportedException ();
1554 public void RemoveAt (int index)
1556 throw new NotSupportedException ();
1561 /// This interface is used to get all members of a class when creating the
1562 /// member cache. It must be implemented by all DeclSpace derivatives which
1563 /// want to support the member cache and by TypeHandle to get caching of
1564 /// non-dynamic types.
1566 public interface IMemberContainer {
1568 /// The name of the IMemberContainer. This is only used for
1569 /// debugging purposes.
1576 /// The type of this IMemberContainer.
1583 /// Returns the IMemberContainer of the parent class or null if this
1584 /// is an interface or TypeManger.object_type.
1585 /// This is used when creating the member cache for a class to get all
1586 /// members from the parent class.
1588 IMemberContainer ParentContainer {
1593 /// Whether this is an interface.
1600 /// Returns all members of this class with the corresponding MemberTypes
1601 /// and BindingFlags.
1604 /// When implementing this method, make sure not to return any inherited
1605 /// members and check the MemberTypes and BindingFlags properly.
1606 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1607 /// get the BindingFlags (static/non-static,public/non-public) in the
1608 /// MemberInfo class, but the cache needs this information. That's why
1609 /// this method is called multiple times with different BindingFlags.
1611 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1614 /// Return the container's member cache.
1616 MemberCache MemberCache {
1622 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1623 /// member lookups. It has a member name based hash table; it maps each member
1624 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1625 /// and the BindingFlags that were initially used to get it. The cache contains
1626 /// all members of the current class and all inherited members. If this cache is
1627 /// for an interface types, it also contains all inherited members.
1629 /// There are two ways to get a MemberCache:
1630 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1631 /// use the DeclSpace.MemberCache property.
1632 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1633 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1635 public class MemberCache {
1636 public readonly IMemberContainer Container;
1637 protected Hashtable member_hash;
1638 protected Hashtable method_hash;
1641 /// Create a new MemberCache for the given IMemberContainer `container'.
1643 public MemberCache (IMemberContainer container)
1645 this.Container = container;
1647 Timer.IncrementCounter (CounterType.MemberCache);
1648 Timer.StartTimer (TimerType.CacheInit);
1652 // If we have a parent class (we have a parent class unless we're
1653 // TypeManager.object_type), we deep-copy its MemberCache here.
1654 if (Container.IsInterface) {
1657 if (Container.ParentContainer != null)
1658 parent = Container.ParentContainer.MemberCache;
1660 parent = TypeHandle.ObjectType.MemberCache;
1661 member_hash = SetupCacheForInterface (parent);
1662 } else if (Container.ParentContainer != null)
1663 member_hash = SetupCache (Container.ParentContainer.MemberCache);
1665 member_hash = new Hashtable ();
1667 // If this is neither a dynamic type nor an interface, create a special
1668 // method cache with all declared and inherited methods.
1669 Type type = container.Type;
1670 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1671 method_hash = new Hashtable ();
1675 // Add all members from the current class.
1676 AddMembers (Container);
1678 Timer.StopTimer (TimerType.CacheInit);
1682 /// Bootstrap this member cache by doing a deep-copy of our parent.
1684 Hashtable SetupCache (MemberCache parent)
1686 Hashtable hash = new Hashtable ();
1688 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1689 while (it.MoveNext ()) {
1690 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1698 /// Add the contents of `new_hash' to `hash'.
1700 void AddHashtable (Hashtable hash, MemberCache cache)
1702 Hashtable new_hash = cache.member_hash;
1703 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1704 while (it.MoveNext ()) {
1705 ArrayList list = (ArrayList) hash [it.Key];
1707 hash [it.Key] = list = new ArrayList ();
1709 foreach (CacheEntry entry in (ArrayList) it.Value) {
1710 if (entry.Container != cache.Container)
1718 /// Bootstrap the member cache for an interface type.
1719 /// Type.GetMembers() won't return any inherited members for interface types,
1720 /// so we need to do this manually. Interfaces also inherit from System.Object.
1722 Hashtable SetupCacheForInterface (MemberCache parent)
1724 Hashtable hash = SetupCache (parent);
1725 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1727 foreach (Type itype in ifaces) {
1728 IMemberContainer iface_container =
1729 TypeManager.LookupMemberContainer (itype);
1731 MemberCache iface_cache = iface_container.MemberCache;
1733 AddHashtable (hash, iface_cache);
1740 /// Add all members from class `container' to the cache.
1742 void AddMembers (IMemberContainer container)
1744 // We need to call AddMembers() with a single member type at a time
1745 // to get the member type part of CacheEntry.EntryType right.
1746 AddMembers (MemberTypes.Constructor, container);
1747 AddMembers (MemberTypes.Field, container);
1748 AddMembers (MemberTypes.Method, container);
1749 AddMembers (MemberTypes.Property, container);
1750 AddMembers (MemberTypes.Event, container);
1751 // Nested types are returned by both Static and Instance searches.
1752 AddMembers (MemberTypes.NestedType,
1753 BindingFlags.Static | BindingFlags.Public, container);
1754 AddMembers (MemberTypes.NestedType,
1755 BindingFlags.Static | BindingFlags.NonPublic, container);
1758 void AddMembers (MemberTypes mt, IMemberContainer container)
1760 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1761 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1762 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1763 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1767 /// Add all members from class `container' with the requested MemberTypes and
1768 /// BindingFlags to the cache. This method is called multiple times with different
1769 /// MemberTypes and BindingFlags.
1771 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1773 MemberList members = container.GetMembers (mt, bf);
1775 foreach (MemberInfo member in members) {
1776 string name = member.Name;
1778 int pos = name.IndexOf ('<');
1780 name = name.Substring (0, pos);
1782 // We use a name-based hash table of ArrayList's.
1783 ArrayList list = (ArrayList) member_hash [name];
1785 list = new ArrayList ();
1786 member_hash.Add (name, list);
1789 // When this method is called for the current class, the list will
1790 // already contain all inherited members from our parent classes.
1791 // We cannot add new members in front of the list since this'd be an
1792 // expensive operation, that's why the list is sorted in reverse order
1793 // (ie. members from the current class are coming last).
1794 list.Add (new CacheEntry (container, member, mt, bf));
1799 /// Add all declared and inherited methods from class `type' to the method cache.
1801 void AddMethods (Type type)
1803 AddMethods (BindingFlags.Static | BindingFlags.Public |
1804 BindingFlags.FlattenHierarchy, type);
1805 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1806 BindingFlags.FlattenHierarchy, type);
1807 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1808 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1811 void AddMethods (BindingFlags bf, Type type)
1813 MemberInfo [] members = type.GetMethods (bf);
1815 Array.Reverse (members);
1817 foreach (MethodBase member in members) {
1818 string name = member.Name;
1820 // We use a name-based hash table of ArrayList's.
1821 ArrayList list = (ArrayList) method_hash [name];
1823 list = new ArrayList ();
1824 method_hash.Add (name, list);
1827 // Unfortunately, the elements returned by Type.GetMethods() aren't
1828 // sorted so we need to do this check for every member.
1829 BindingFlags new_bf = bf;
1830 if (member.DeclaringType == type)
1831 new_bf |= BindingFlags.DeclaredOnly;
1833 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1838 /// Compute and return a appropriate `EntryType' magic number for the given
1839 /// MemberTypes and BindingFlags.
1841 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1843 EntryType type = EntryType.None;
1845 if ((mt & MemberTypes.Constructor) != 0)
1846 type |= EntryType.Constructor;
1847 if ((mt & MemberTypes.Event) != 0)
1848 type |= EntryType.Event;
1849 if ((mt & MemberTypes.Field) != 0)
1850 type |= EntryType.Field;
1851 if ((mt & MemberTypes.Method) != 0)
1852 type |= EntryType.Method;
1853 if ((mt & MemberTypes.Property) != 0)
1854 type |= EntryType.Property;
1855 // Nested types are returned by static and instance searches.
1856 if ((mt & MemberTypes.NestedType) != 0)
1857 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1859 if ((bf & BindingFlags.Instance) != 0)
1860 type |= EntryType.Instance;
1861 if ((bf & BindingFlags.Static) != 0)
1862 type |= EntryType.Static;
1863 if ((bf & BindingFlags.Public) != 0)
1864 type |= EntryType.Public;
1865 if ((bf & BindingFlags.NonPublic) != 0)
1866 type |= EntryType.NonPublic;
1867 if ((bf & BindingFlags.DeclaredOnly) != 0)
1868 type |= EntryType.Declared;
1874 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1875 /// denote multiple member types. Returns true if the given flags value denotes a
1876 /// single member types.
1878 public static bool IsSingleMemberType (MemberTypes mt)
1881 case MemberTypes.Constructor:
1882 case MemberTypes.Event:
1883 case MemberTypes.Field:
1884 case MemberTypes.Method:
1885 case MemberTypes.Property:
1886 case MemberTypes.NestedType:
1895 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1896 /// number to speed up the searching process.
1899 protected enum EntryType {
1904 MaskStatic = Instance|Static,
1908 MaskProtection = Public|NonPublic,
1912 Constructor = 0x020,
1919 MaskType = Constructor|Event|Field|Method|Property|NestedType
1922 protected struct CacheEntry {
1923 public readonly IMemberContainer Container;
1924 public readonly EntryType EntryType;
1925 public readonly MemberInfo Member;
1927 public CacheEntry (IMemberContainer container, MemberInfo member,
1928 MemberTypes mt, BindingFlags bf)
1930 this.Container = container;
1931 this.Member = member;
1932 this.EntryType = GetEntryType (mt, bf);
1937 /// This is called each time we're walking up one level in the class hierarchy
1938 /// and checks whether we can abort the search since we've already found what
1939 /// we were looking for.
1941 protected bool DoneSearching (ArrayList list)
1944 // We've found exactly one member in the current class and it's not
1945 // a method or constructor.
1947 if (list.Count == 1 && !(list [0] is MethodBase))
1951 // Multiple properties: we query those just to find out the indexer
1954 if ((list.Count > 0) && (list [0] is PropertyInfo))
1961 /// Looks up members with name `name'. If you provide an optional
1962 /// filter function, it'll only be called with members matching the
1963 /// requested member name.
1965 /// This method will try to use the cache to do the lookup if possible.
1967 /// Unlike other FindMembers implementations, this method will always
1968 /// check all inherited members - even when called on an interface type.
1970 /// If you know that you're only looking for methods, you should use
1971 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1972 /// When doing a method-only search, it'll try to use a special method
1973 /// cache (unless it's a dynamic type or an interface) and the returned
1974 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1975 /// The lookup process will automatically restart itself in method-only
1976 /// search mode if it discovers that it's about to return methods.
1978 ArrayList global = new ArrayList ();
1979 bool using_global = false;
1981 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1983 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1984 MemberFilter filter, object criteria)
1987 throw new Exception ();
1989 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1990 bool method_search = mt == MemberTypes.Method;
1991 // If we have a method cache and we aren't already doing a method-only search,
1992 // then we restart a method search if the first match is a method.
1993 bool do_method_search = !method_search && (method_hash != null);
1995 ArrayList applicable;
1997 // If this is a method-only search, we try to use the method cache if
1998 // possible; a lookup in the method cache will return a MemberInfo with
1999 // the correct ReflectedType for inherited methods.
2001 if (method_search && (method_hash != null))
2002 applicable = (ArrayList) method_hash [name];
2004 applicable = (ArrayList) member_hash [name];
2006 if (applicable == null)
2007 return emptyMemberInfo;
2010 // 32 slots gives 53 rss/54 size
2011 // 2/4 slots gives 55 rss
2013 // Strange: from 25,000 calls, only 1,800
2014 // are above 2. Why does this impact it?
2017 using_global = true;
2019 Timer.StartTimer (TimerType.CachedLookup);
2021 EntryType type = GetEntryType (mt, bf);
2023 IMemberContainer current = Container;
2026 // `applicable' is a list of all members with the given member name `name'
2027 // in the current class and all its parent classes. The list is sorted in
2028 // reverse order due to the way how the cache is initialy created (to speed
2029 // things up, we're doing a deep-copy of our parent).
2031 for (int i = applicable.Count-1; i >= 0; i--) {
2032 CacheEntry entry = (CacheEntry) applicable [i];
2034 // This happens each time we're walking one level up in the class
2035 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2036 // the first time this happens (this may already happen in the first
2037 // iteration of this loop if there are no members with the name we're
2038 // looking for in the current class).
2039 if (entry.Container != current) {
2040 if (declared_only || DoneSearching (global))
2043 current = entry.Container;
2046 // Is the member of the correct type ?
2047 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2050 // Is the member static/non-static ?
2051 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2054 // Apply the filter to it.
2055 if (filter (entry.Member, criteria)) {
2056 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2057 do_method_search = false;
2058 global.Add (entry.Member);
2062 Timer.StopTimer (TimerType.CachedLookup);
2064 // If we have a method cache and we aren't already doing a method-only
2065 // search, we restart in method-only search mode if the first match is
2066 // a method. This ensures that we return a MemberInfo with the correct
2067 // ReflectedType for inherited methods.
2068 if (do_method_search && (global.Count > 0)){
2069 using_global = false;
2071 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2074 using_global = false;
2075 MemberInfo [] copy = new MemberInfo [global.Count];
2076 global.CopyTo (copy);
2081 // This finds the method or property for us to override. invocationType is the type where
2082 // the override is going to be declared, name is the name of the method/property, and
2083 // paramTypes is the parameters, if any to the method or property
2085 // Because the MemberCache holds members from this class and all the base classes,
2086 // we can avoid tons of reflection stuff.
2088 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2090 ArrayList applicable;
2091 if (method_hash != null && !is_property)
2092 applicable = (ArrayList) method_hash [name];
2094 applicable = (ArrayList) member_hash [name];
2096 if (applicable == null)
2099 // Walk the chain of methods, starting from the top.
2101 for (int i = applicable.Count - 1; i >= 0; i--) {
2102 CacheEntry entry = (CacheEntry) applicable [i];
2104 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2107 PropertyInfo pi = null;
2108 MethodInfo mi = null;
2109 FieldInfo fi = null;
2110 Type [] cmpAttrs = null;
2113 if ((entry.EntryType & EntryType.Field) != 0) {
2114 fi = (FieldInfo)entry.Member;
2116 // TODO: For this case we ignore member type
2117 //fb = TypeManager.GetField (fi);
2118 //cmpAttrs = new Type[] { fb.MemberType };
2120 pi = (PropertyInfo) entry.Member;
2121 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2124 mi = (MethodInfo) entry.Member;
2125 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2129 // TODO: Almost duplicate !
2131 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2132 case FieldAttributes.Private:
2134 // A private method is Ok if we are a nested subtype.
2135 // The spec actually is not very clear about this, see bug 52458.
2137 if (invocationType != entry.Container.Type &
2138 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2142 case FieldAttributes.FamANDAssem:
2143 case FieldAttributes.Assembly:
2145 // Check for assembly methods
2147 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2151 return entry.Member;
2155 // Check the arguments
2157 if (cmpAttrs.Length != paramTypes.Length)
2160 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2161 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2166 // get one of the methods because this has the visibility info.
2169 mi = pi.GetGetMethod (true);
2171 mi = pi.GetSetMethod (true);
2177 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2178 case MethodAttributes.Private:
2180 // A private method is Ok if we are a nested subtype.
2181 // The spec actually is not very clear about this, see bug 52458.
2183 if (invocationType.Equals (entry.Container.Type) ||
2184 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2185 return entry.Member;
2188 case MethodAttributes.FamANDAssem:
2189 case MethodAttributes.Assembly:
2191 // Check for assembly methods
2193 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2194 return entry.Member;
2199 // A protected method is ok, because we are overriding.
2200 // public is always ok.
2202 return entry.Member;
2212 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2213 /// We handle two cases. The first is for types without parameters (events, field, properties).
2214 /// The second are methods, indexers and this is why ignore_complex_types is here.
2215 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2217 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2219 ArrayList applicable = null;
2221 if (method_hash != null)
2222 applicable = (ArrayList) method_hash [name];
2224 if (applicable != null) {
2225 for (int i = applicable.Count - 1; i >= 0; i--) {
2226 CacheEntry entry = (CacheEntry) applicable [i];
2227 if ((entry.EntryType & EntryType.Public) != 0)
2228 return entry.Member;
2232 if (member_hash == null)
2234 applicable = (ArrayList) member_hash [name];
2236 if (applicable != null) {
2237 for (int i = applicable.Count - 1; i >= 0; i--) {
2238 CacheEntry entry = (CacheEntry) applicable [i];
2239 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2240 if (ignore_complex_types) {
2241 if ((entry.EntryType & EntryType.Method) != 0)
2244 // Does exist easier way how to detect indexer ?
2245 if ((entry.EntryType & EntryType.Property) != 0) {
2246 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2247 if (arg_types.Length > 0)
2251 return entry.Member;
2258 Hashtable locase_table;
2261 /// Builds low-case table for CLS Compliance test
2263 public Hashtable GetPublicMembers ()
2265 if (locase_table != null)
2266 return locase_table;
2268 locase_table = new Hashtable ();
2269 foreach (DictionaryEntry entry in member_hash) {
2270 ArrayList members = (ArrayList)entry.Value;
2271 for (int ii = 0; ii < members.Count; ++ii) {
2272 CacheEntry member_entry = (CacheEntry) members [ii];
2274 if ((member_entry.EntryType & EntryType.Public) == 0)
2277 // TODO: Does anyone know easier way how to detect that member is internal ?
2278 switch (member_entry.EntryType & EntryType.MaskType) {
2279 case EntryType.Constructor:
2282 case EntryType.Field:
2283 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2287 case EntryType.Method:
2288 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2292 case EntryType.Property:
2293 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2294 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2298 case EntryType.Event:
2299 EventInfo ei = (EventInfo)member_entry.Member;
2300 MethodInfo mi = ei.GetAddMethod ();
2301 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2305 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2306 locase_table [lcase] = member_entry.Member;
2310 return locase_table;
2313 public Hashtable Members {
2320 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2322 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2324 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2326 for (int i = 0; i < al.Count; ++i) {
2327 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2330 if (entry.Member == this_builder)
2333 if ((entry.EntryType & tested_type) != tested_type)
2336 MethodBase method_to_compare = (MethodBase)entry.Member;
2337 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2340 IMethodData md = TypeManager.GetMethod (method_to_compare);
2342 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2343 // However it is exactly what csc does.
2344 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2347 Report.SymbolRelatedToPreviousError (entry.Member);
2348 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());