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 {
24 public readonly string Name;
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.GetFullName () + "." + Name;
98 public string GetFullName ()
101 if (TypeArguments != null)
102 full_name = Name + "<" + TypeArguments + ">";
106 return Left.GetFullName () + "." + full_name;
111 public static string MakeName (string name, TypeArguments args)
116 return name + "`" + args.Count;
119 public static string MakeName (string name, int count)
121 return name + "`" + count;
124 public string GetTypeName ()
128 return Left.GetTypeName () + "." +
129 MakeName (Name, TypeArguments);
131 return MakeName (Name, TypeArguments);
134 protected bool IsUnbound {
136 if ((Left != null) && Left.IsUnbound)
138 else if (TypeArguments == null)
141 return TypeArguments.IsUnbound;
145 protected bool CheckUnbound (Location loc)
147 if ((Left != null) && !Left.CheckUnbound (loc))
149 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
150 Report.Error (1031, loc, "Type expected");
157 public Expression GetTypeExpression (Location loc)
160 if (!CheckUnbound (loc))
163 return new UnboundTypeExpression (GetTypeName ());
167 Expression lexpr = Left.GetTypeExpression (loc);
169 return new MemberAccess (lexpr, Name, TypeArguments, loc);
171 if (TypeArguments != null)
172 return new ConstructedType (Name, TypeArguments, loc);
174 return new SimpleName (Name, loc);
178 public string Basename {
180 if (TypeArguments != null)
181 return MakeName (Name, TypeArguments);
187 public override string ToString ()
190 if (TypeArguments != null)
191 full_name = Name + "<" + TypeArguments + ">";
196 return Left + "." + full_name;
203 /// Base representation for members. This is used to keep track
204 /// of Name, Location and Modifier flags, and handling Attributes.
206 public abstract class MemberCore : Attributable {
212 public readonly MemberName MemberName;
215 /// Modifier flags that the user specified in the source code
219 public readonly TypeContainer Parent;
222 /// Location where this declaration happens
224 public readonly Location Location;
228 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
229 Obsolete = 1 << 1, // Type has obsolete attribute
230 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
231 ClsCompliant = 1 << 3, // Type is CLS Compliant
232 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
233 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
234 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
235 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
236 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
237 Excluded = 1 << 9 // Method is conditional
242 /// MemberCore flags at first detected then cached
244 protected Flags caching_flags;
246 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
251 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
254 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
258 /// Tests presence of ObsoleteAttribute and report proper error
260 protected void CheckUsageOfObsoleteAttribute (Type type)
265 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
266 if (obsolete_attr == null)
269 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
272 public abstract bool Define ();
275 // Returns full member name for error message
277 public virtual string GetSignatureForError ()
283 /// Base Emit method. This is also entry point for CLS-Compliant verification.
285 public virtual void Emit ()
287 VerifyObsoleteAttribute ();
289 if (!RootContext.VerifyClsCompliance)
292 VerifyClsCompliance (Parent);
296 // Whehter is it ok to use an unsafe pointer in this type container
298 public bool UnsafeOK (DeclSpace parent)
301 // First check if this MemberCore modifier flags has unsafe set
303 if ((ModFlags & Modifiers.UNSAFE) != 0)
306 if (parent.UnsafeContext)
309 Expression.UnsafeError (Location);
314 /// Returns instance of ObsoleteAttribute for this MemberCore
316 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
318 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
319 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
323 caching_flags &= ~Flags.Obsolete_Undetected;
325 if (OptAttributes == null)
328 // TODO: remove this allocation
329 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
330 null, null, ds.ModFlags, false);
332 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
333 if (obsolete_attr == null)
336 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
337 if (obsolete == null)
340 caching_flags |= Flags.Obsolete;
345 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
347 public override bool IsClsCompliaceRequired (DeclSpace container)
349 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
350 return (caching_flags & Flags.ClsCompliant) != 0;
352 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
353 caching_flags &= ~Flags.ClsCompliance_Undetected;
354 caching_flags |= Flags.ClsCompliant;
358 caching_flags &= ~Flags.ClsCompliance_Undetected;
363 /// Returns true when MemberCore is exposed from assembly.
365 protected bool IsExposedFromAssembly (DeclSpace ds)
367 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
370 DeclSpace parentContainer = ds;
371 while (parentContainer != null && parentContainer.ModFlags != 0) {
372 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
374 parentContainer = parentContainer.Parent;
380 /// Resolve CLSCompliantAttribute value or gets cached value.
382 bool GetClsCompliantAttributeValue (DeclSpace ds)
384 if (OptAttributes != null) {
385 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
386 null, null, ds.ModFlags, false);
387 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
388 if (cls_attribute != null) {
389 caching_flags |= Flags.HasClsCompliantAttribute;
390 return cls_attribute.GetClsCompliantAttributeValue (ds);
393 return ds.GetClsCompliantAttributeValue ();
397 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
399 protected bool HasClsCompliantAttribute {
401 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
406 /// The main virtual method for CLS-Compliant verifications.
407 /// The method returns true if member is CLS-Compliant and false if member is not
408 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
409 /// and add their extra verifications.
411 protected virtual bool VerifyClsCompliance (DeclSpace ds)
413 if (!IsClsCompliaceRequired (ds)) {
414 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
415 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
420 if (!CodeGen.Assembly.IsClsCompliant) {
421 if (HasClsCompliantAttribute) {
422 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
426 int index = Name.LastIndexOf ('.');
427 if (Name [index > 0 ? index + 1 : 0] == '_') {
428 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
433 protected abstract void VerifyObsoleteAttribute ();
438 /// Base class for structs, classes, enumerations and interfaces.
441 /// They all create new declaration spaces. This
442 /// provides the common foundation for managing those name
445 public abstract class DeclSpace : MemberCore, IAlias {
447 /// This points to the actual definition that is being
448 /// created with System.Reflection.Emit
450 public TypeBuilder TypeBuilder;
453 /// If we are a generic type, this is the type we are
454 /// currently defining. We need to lookup members on this
455 /// instead of the TypeBuilder.
457 public TypeExpr CurrentType;
460 // This is the namespace in which this typecontainer
461 // was declared. We use this to resolve names.
463 public NamespaceEntry NamespaceEntry;
465 public Hashtable Cache = new Hashtable ();
467 public string Basename;
470 /// defined_names is used for toplevel objects
472 protected Hashtable defined_names;
474 readonly bool is_generic;
475 readonly int count_type_params;
478 // Whether we are Generic
480 public bool IsGeneric {
484 else if (Parent != null)
485 return Parent.IsGeneric;
491 static string[] attribute_targets = new string [] { "type" };
493 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
494 Attributes attrs, Location l)
495 : base (parent, name, attrs, l)
498 Basename = name.Name;
499 defined_names = new Hashtable ();
500 if (name.TypeArguments != null) {
502 count_type_params = name.TypeArguments.Count;
505 count_type_params += parent.count_type_params;
508 public void RecordDecl ()
510 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
511 NamespaceEntry.DefineName (MemberName.Basename, this);
515 /// The result value from adding an declaration into
516 /// a struct or a class
518 public enum AdditionResult {
520 /// The declaration has been successfully
521 /// added to the declation space.
526 /// The symbol has already been defined.
531 /// Returned if the declation being added to the
532 /// name space clashes with its container name.
534 /// The only exceptions for this are constructors
535 /// and static constructors
540 /// Returned if a constructor was created (because syntactically
541 /// it looked like a constructor) but was not (because the name
542 /// of the method is not the same as the container class
547 /// This is only used by static constructors to emit the
548 /// error 111, but this error for other things really
549 /// happens at another level for other functions.
554 /// Some other error.
560 /// Returns a status code based purely on the name
561 /// of the member being added
563 protected AdditionResult IsValid (string basename, string name)
565 if (basename == Basename)
566 return AdditionResult.EnclosingClash;
568 if (defined_names.Contains (name))
569 return AdditionResult.NameExists;
571 return AdditionResult.Success;
574 public static int length;
575 public static int small;
578 /// Introduce @name into this declaration space and
579 /// associates it with the object @o. Note that for
580 /// methods this will just point to the first method. o
582 public void DefineName (string name, object o)
584 defined_names.Add (name, o);
587 int p = name.LastIndexOf ('.');
595 /// Returns the object associated with a given name in the declaration
596 /// space. This is the inverse operation of `DefineName'
598 public object GetDefinition (string name)
600 return defined_names [name];
603 bool in_transit = false;
606 /// This function is used to catch recursive definitions
609 public bool InTransit {
620 /// Looks up the alias for the name
622 public IAlias LookupAlias (string name)
624 if (NamespaceEntry != null)
625 return NamespaceEntry.LookupAlias (name);
631 // root_types contains all the types. All TopLevel types
632 // hence have a parent that points to `root_types', that is
633 // why there is a non-obvious test down here.
635 public bool IsTopLevel {
638 if (Parent.Parent == null)
645 public virtual void CloseType ()
647 if ((caching_flags & Flags.CloseTypeCreated) == 0){
649 TypeBuilder.CreateType ();
652 // The try/catch is needed because
653 // nested enumerations fail to load when they
656 // Even if this is the right order (enumerations
657 // declared after types).
659 // Note that this still creates the type and
660 // it is possible to save it
662 caching_flags |= Flags.CloseTypeCreated;
667 /// Should be overriten by the appropriate declaration space
669 public abstract TypeBuilder DefineType ();
672 /// Define all members, but don't apply any attributes or do anything which may
673 /// access not-yet-defined classes. This method also creates the MemberCache.
675 public abstract bool DefineMembers (TypeContainer parent);
678 // Whether this is an `unsafe context'
680 public bool UnsafeContext {
682 if ((ModFlags & Modifiers.UNSAFE) != 0)
685 return Parent.UnsafeContext;
690 public static string MakeFQN (string nsn, string name)
694 return String.Concat (nsn, ".", name);
697 EmitContext type_resolve_ec;
698 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
700 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
701 type_resolve_ec.ResolvingTypeTree = true;
703 return type_resolve_ec;
707 // Looks up the type, as parsed into the expression `e'
709 public Type ResolveType (Expression e, bool silent, Location loc)
711 TypeExpr d = ResolveTypeExpr (e, silent, loc);
715 return ResolveType (d, loc);
718 public Type ResolveType (TypeExpr d, Location loc)
720 if (!d.CheckAccessLevel (this)) {
721 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", d.Name);
725 Type t = d.ResolveType (type_resolve_ec);
729 if (d is UnboundTypeExpression)
732 TypeContainer tc = TypeManager.LookupTypeContainer (t);
733 if ((tc != null) && tc.IsGeneric) {
735 int tnum = TypeManager.GetNumberOfTypeArguments (t);
736 Report.Error (305, loc,
737 "Using the generic type `{0}' " +
738 "requires {1} type arguments",
739 TypeManager.GetFullName (t), tnum);
743 ConstructedType ctype = new ConstructedType (
744 t, TypeParameters, loc);
746 t = ctype.ResolveType (type_resolve_ec);
753 // Resolves the expression `e' for a type, and will recursively define
756 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
758 if (type_resolve_ec == null)
759 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
760 type_resolve_ec.loc = loc;
761 if (this is GenericMethod)
762 type_resolve_ec.ContainerType = Parent.TypeBuilder;
764 type_resolve_ec.ContainerType = TypeBuilder;
766 int errors = Report.Errors;
768 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
770 if ((d != null) && (d.eclass == ExprClass.Type))
773 if (silent || (Report.Errors != errors))
776 if (e is SimpleName){
777 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
778 d = s.ResolveAsTypeTerminal (type_resolve_ec);
780 if ((d == null) || (d.Type == null)) {
781 Report.Error (246, loc, "Cannot find type `{0}'", e);
785 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
788 Report.Error (308, loc,
789 "The non-generic type `{0}' cannot " +
790 "be used with type arguments.",
791 TypeManager.CSharpName (d.Type));
795 Report.Error (305, loc,
796 "Using the generic type `{0}' " +
797 "requires {1} type arguments",
798 TypeManager.GetFullName (d.Type), num_args);
802 Report.Error (246, loc, "Cannot find type `{0}'", e);
806 public bool CheckAccessLevel (Type check_type)
809 if (this is GenericMethod)
810 tb = Parent.TypeBuilder;
814 if (check_type.IsGenericInstance)
815 check_type = check_type.GetGenericTypeDefinition ();
817 if (check_type == tb)
820 if (check_type.IsGenericParameter)
821 return true; // FIXME
823 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
826 // Broken Microsoft runtime, return public for arrays, no matter what
827 // the accessibility is for their underlying class, and they return
828 // NonPublic visibility for pointers
830 if (check_type.IsArray || check_type.IsPointer)
831 return CheckAccessLevel (TypeManager.GetElementType (check_type));
834 case TypeAttributes.Public:
837 case TypeAttributes.NotPublic:
839 // In same cases is null.
840 if (TypeBuilder == null)
844 // This test should probably use the declaringtype.
846 return check_type.Assembly == TypeBuilder.Assembly;
848 case TypeAttributes.NestedPublic:
851 case TypeAttributes.NestedPrivate:
852 string check_type_name = check_type.FullName;
853 string type_name = tb.FullName;
855 int cio = check_type_name.LastIndexOf ('+');
856 string container = check_type_name.Substring (0, cio);
859 // Check if the check_type is a nested class of the current type
861 if (check_type_name.StartsWith (type_name + "+")){
865 if (type_name.StartsWith (container)){
871 case TypeAttributes.NestedFamily:
873 // Only accessible to methods in current type or any subtypes
875 return FamilyAccessible (tb, check_type);
877 case TypeAttributes.NestedFamANDAssem:
878 return (check_type.Assembly == tb.Assembly) &&
879 FamilyAccessible (tb, check_type);
881 case TypeAttributes.NestedFamORAssem:
882 return (check_type.Assembly == tb.Assembly) ||
883 FamilyAccessible (tb, check_type);
885 case TypeAttributes.NestedAssembly:
886 return check_type.Assembly == tb.Assembly;
889 Console.WriteLine ("HERE: " + check_attr);
894 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
896 Type declaring = check_type.DeclaringType;
897 if (tb.IsSubclassOf (declaring))
900 string check_type_name = check_type.FullName;
902 int cio = check_type_name.LastIndexOf ('+');
903 string container = check_type_name.Substring (0, cio);
906 // Check if the check_type is a nested class of the current type
908 if (check_type_name.StartsWith (container + "+"))
914 // Access level of a type.
916 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
917 // Public Assembly Protected
918 Protected = (0 << 0) | (0 << 1) | (X << 2),
919 Public = (X << 0) | (X << 1) | (X << 2),
920 Private = (0 << 0) | (0 << 1) | (0 << 2),
921 Internal = (0 << 0) | (X << 1) | (0 << 2),
922 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
925 static AccessLevel GetAccessLevelFromModifiers (int flags)
927 if ((flags & Modifiers.INTERNAL) != 0) {
929 if ((flags & Modifiers.PROTECTED) != 0)
930 return AccessLevel.ProtectedOrInternal;
932 return AccessLevel.Internal;
934 } else if ((flags & Modifiers.PROTECTED) != 0)
935 return AccessLevel.Protected;
936 else if ((flags & Modifiers.PRIVATE) != 0)
937 return AccessLevel.Private;
939 return AccessLevel.Public;
942 // What is the effective access level of this?
944 AccessLevel EffectiveAccessLevel {
946 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
947 if (!IsTopLevel && (Parent != null))
948 return myAccess & Parent.EffectiveAccessLevel;
953 // Return the access level for type `t'
954 static AccessLevel TypeEffectiveAccessLevel (Type t)
957 return AccessLevel.Public;
958 if (t.IsNestedPrivate)
959 return AccessLevel.Private;
961 return AccessLevel.Internal;
963 // By now, it must be nested
964 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
966 if (t.IsNestedPublic)
968 if (t.IsNestedAssembly)
969 return parentLevel & AccessLevel.Internal;
970 if (t.IsNestedFamily)
971 return parentLevel & AccessLevel.Protected;
972 if (t.IsNestedFamORAssem)
973 return parentLevel & AccessLevel.ProtectedOrInternal;
974 if (t.IsNestedFamANDAssem)
975 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
977 // nested private is taken care of
979 throw new Exception ("I give up, what are you?");
983 // This answers `is the type P, as accessible as a member M which has the
984 // accessability @flags which is declared as a nested member of the type T, this declspace'
986 public bool AsAccessible (Type p, int flags)
988 if (p.IsGenericParameter)
989 return true; // FIXME
992 // 1) if M is private, its accessability is the same as this declspace.
993 // we already know that P is accessible to T before this method, so we
997 if ((flags & Modifiers.PRIVATE) != 0)
1000 while (p.IsArray || p.IsPointer || p.IsByRef)
1001 p = TypeManager.GetElementType (p);
1003 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1004 AccessLevel mAccess = this.EffectiveAccessLevel &
1005 GetAccessLevelFromModifiers (flags);
1007 // for every place from which we can access M, we must
1008 // be able to access P as well. So, we want
1009 // For every bit in M and P, M_i -> P_1 == true
1010 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1012 return ~ (~ mAccess | pAccess) == 0;
1015 static DoubleHash dh = new DoubleHash (1000);
1017 Type DefineTypeAndParents (DeclSpace tc)
1019 DeclSpace container = tc.Parent;
1021 if (container.TypeBuilder == null && container.Name != "")
1022 DefineTypeAndParents (container);
1024 return tc.DefineType ();
1027 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1035 if (dh.Lookup (ns, name, out r))
1039 if (Namespace.IsNamespace (ns)){
1040 string fullname = (ns != "") ? ns + "." + name : name;
1041 t = TypeManager.LookupType (fullname);
1045 t = TypeManager.LookupType (name);
1049 dh.Insert (ns, name, t);
1054 // In case we are fed a composite name, normalize it.
1056 int p = name.LastIndexOf ('.');
1058 ns = MakeFQN (ns, name.Substring (0, p));
1059 name = name.Substring (p+1);
1062 parent = RootContext.Tree.LookupByNamespace (ns, name);
1063 if (parent == null) {
1064 dh.Insert (ns, name, null);
1068 t = DefineTypeAndParents (parent);
1074 dh.Insert (ns, name, t);
1078 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1080 Report.Error (104, loc,
1081 "`{0}' is an ambiguous reference ({1} or {2})",
1085 public Type FindNestedType (Location loc, string name,
1086 out DeclSpace containing_ds)
1091 containing_ds = this;
1092 while (containing_ds != null){
1093 Type container_type = containing_ds.TypeBuilder;
1094 Type current_type = container_type;
1096 while (current_type != null && current_type != TypeManager.object_type) {
1097 string pre = current_type.FullName;
1099 t = LookupInterfaceOrClass (pre, name, out error);
1103 if ((t != null) && containing_ds.CheckAccessLevel (t))
1106 current_type = current_type.BaseType;
1108 containing_ds = containing_ds.Parent;
1115 /// GetType is used to resolve type names at the DeclSpace level.
1116 /// Use this to lookup class/struct bases, interface bases or
1117 /// delegate type references
1121 /// Contrast this to LookupType which is used inside method bodies to
1122 /// lookup types that have already been defined. GetType is used
1123 /// during the tree resolution process and potentially define
1124 /// recursively the type
1126 public Type FindType (Location loc, string name)
1132 // For the case the type we are looking for is nested within this one
1133 // or is in any base class
1135 DeclSpace containing_ds = this;
1137 while (containing_ds != null){
1138 Type container_type = containing_ds.TypeBuilder;
1139 Type current_type = container_type;
1141 while (current_type != null && current_type != TypeManager.object_type) {
1142 string pre = current_type.FullName;
1144 t = LookupInterfaceOrClass (pre, name, out error);
1148 if ((t != null) && containing_ds.CheckAccessLevel (t))
1151 current_type = current_type.BaseType;
1153 containing_ds = containing_ds.Parent;
1157 // Attempt to lookup the class on our namespace and all it's implicit parents
1159 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1160 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1169 // Attempt to do a direct unqualified lookup
1171 t = LookupInterfaceOrClass ("", name, out error);
1179 // Attempt to lookup the class on any of the `using'
1183 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1185 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1192 if (name.IndexOf ('.') > 0)
1195 IAlias alias_value = ns.LookupAlias (name);
1196 if (alias_value != null) {
1197 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1206 // Now check the using clause list
1209 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1210 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1214 if (match != null) {
1216 if (CheckAccessLevel (match)) {
1217 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1230 //Report.Error (246, Location, "Can not find type `"+name+"'");
1235 /// This function is broken and not what you're looking for. It should only
1236 /// be used while the type is still being created since it doesn't use the cache
1237 /// and relies on the filter doing the member name check.
1239 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1240 MemberFilter filter, object criteria);
1243 /// If we have a MemberCache, return it. This property may return null if the
1244 /// class doesn't have a member cache or while it's still being created.
1246 public abstract MemberCache MemberCache {
1250 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1253 TypeBuilder.SetCustomAttribute (cb);
1254 } catch (System.ArgumentException e) {
1255 Report.Warning (-21, a.Location,
1256 "The CharSet named property on StructLayout\n"+
1257 "\tdoes not work correctly on Microsoft.NET\n"+
1258 "\tYou might want to remove the CharSet declaration\n"+
1259 "\tor compile using the Mono runtime instead of the\n"+
1260 "\tMicrosoft .NET runtime\n"+
1261 "\tThe runtime gave the error: " + e);
1266 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1267 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1269 public bool GetClsCompliantAttributeValue ()
1271 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1272 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1274 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1276 if (OptAttributes != null) {
1277 EmitContext ec = new EmitContext (Parent, this, Location,
1278 null, null, ModFlags, false);
1279 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1280 if (cls_attribute != null) {
1281 caching_flags |= Flags.HasClsCompliantAttribute;
1282 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1283 caching_flags |= Flags.ClsCompliantAttributeTrue;
1290 if (Parent == null) {
1291 if (CodeGen.Assembly.IsClsCompliant) {
1292 caching_flags |= Flags.ClsCompliantAttributeTrue;
1298 if (Parent.GetClsCompliantAttributeValue ()) {
1299 caching_flags |= Flags.ClsCompliantAttributeTrue;
1306 // Extensions for generics
1308 TypeParameter[] type_params;
1309 TypeParameter[] type_param_list;
1311 protected string GetInstantiationName ()
1313 StringBuilder sb = new StringBuilder (Name);
1315 for (int i = 0; i < type_param_list.Length; i++) {
1318 sb.Append (type_param_list [i].Name);
1321 return sb.ToString ();
1324 bool check_type_parameter (ArrayList list, int start, string name)
1326 for (int i = 0; i < start; i++) {
1327 TypeParameter param = (TypeParameter) list [i];
1329 if (param.Name != name)
1332 if (RootContext.WarningLevel >= 3)
1335 "Type parameter `{0}' has same name " +
1336 "as type parameter from outer type `{1}'",
1337 name, Parent.GetInstantiationName ());
1345 TypeParameter[] initialize_type_params ()
1347 if (type_param_list != null)
1348 return type_param_list;
1350 DeclSpace the_parent = Parent;
1351 if (this is GenericMethod)
1355 TypeParameter[] parent_params = null;
1356 if ((the_parent != null) && the_parent.IsGeneric) {
1357 parent_params = the_parent.initialize_type_params ();
1358 start = parent_params != null ? parent_params.Length : 0;
1361 ArrayList list = new ArrayList ();
1362 if (parent_params != null)
1363 list.AddRange (parent_params);
1365 int count = type_params != null ? type_params.Length : 0;
1366 for (int i = 0; i < count; i++) {
1367 TypeParameter param = type_params [i];
1368 check_type_parameter (list, start, param.Name);
1372 type_param_list = new TypeParameter [list.Count];
1373 list.CopyTo (type_param_list, 0);
1374 return type_param_list;
1377 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1380 if (constraints_list != null) {
1382 80, Location, "Contraints are not allowed " +
1383 "on non-generic declarations");
1384 return AdditionResult.Error;
1387 return AdditionResult.Success;
1390 string[] names = MemberName.TypeArguments.GetDeclarations ();
1391 type_params = new TypeParameter [names.Length];
1394 // Register all the names
1396 for (int i = 0; i < type_params.Length; i++) {
1397 string name = names [i];
1399 AdditionResult res = IsValid (name, name);
1401 if (res != AdditionResult.Success)
1404 Constraints constraints = null;
1405 if (constraints_list != null) {
1406 foreach (Constraints constraint in constraints_list) {
1407 if (constraint.TypeParameter == name) {
1408 constraints = constraint;
1414 type_params [i] = new TypeParameter (name, constraints, Location);
1416 DefineName (name, type_params [i]);
1419 return AdditionResult.Success;
1422 public TypeParameter[] TypeParameters {
1425 throw new InvalidOperationException ();
1426 if (type_param_list == null)
1427 initialize_type_params ();
1429 return type_param_list;
1433 protected TypeParameter[] CurrentTypeParameters {
1436 throw new InvalidOperationException ();
1437 if (type_params != null)
1440 return new TypeParameter [0];
1444 public int CountTypeParameters {
1446 return count_type_params;
1450 public TypeParameterExpr LookupGeneric (string name, Location loc)
1455 foreach (TypeParameter type_param in CurrentTypeParameters) {
1456 if (type_param.Name != name)
1459 return new TypeParameterExpr (type_param, loc);
1463 return Parent.LookupGeneric (name, loc);
1468 bool IAlias.IsType {
1469 get { return true; }
1472 string IAlias.Name {
1473 get { return Name; }
1476 TypeExpr IAlias.Type
1479 if (TypeBuilder == null)
1480 throw new InvalidOperationException ();
1482 if (CurrentType != null)
1485 return new TypeExpression (TypeBuilder, Location);
1489 public override string[] ValidAttributeTargets {
1491 return attribute_targets;
1497 /// This is a readonly list of MemberInfo's.
1499 public class MemberList : IList {
1500 public readonly IList List;
1504 /// Create a new MemberList from the given IList.
1506 public MemberList (IList list)
1511 this.List = new ArrayList ();
1516 /// Concatenate the ILists `first' and `second' to a new MemberList.
1518 public MemberList (IList first, IList second)
1520 ArrayList list = new ArrayList ();
1521 list.AddRange (first);
1522 list.AddRange (second);
1527 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1530 /// Cast the MemberList into a MemberInfo[] array.
1533 /// This is an expensive operation, only use it if it's really necessary.
1535 public static explicit operator MemberInfo [] (MemberList list)
1537 Timer.StartTimer (TimerType.MiscTimer);
1538 MemberInfo [] result = new MemberInfo [list.Count];
1539 list.CopyTo (result, 0);
1540 Timer.StopTimer (TimerType.MiscTimer);
1552 public bool IsSynchronized {
1554 return List.IsSynchronized;
1558 public object SyncRoot {
1560 return List.SyncRoot;
1564 public void CopyTo (Array array, int index)
1566 List.CopyTo (array, index);
1571 public IEnumerator GetEnumerator ()
1573 return List.GetEnumerator ();
1578 public bool IsFixedSize {
1584 public bool IsReadOnly {
1590 object IList.this [int index] {
1592 return List [index];
1596 throw new NotSupportedException ();
1600 // FIXME: try to find out whether we can avoid the cast in this indexer.
1601 public MemberInfo this [int index] {
1603 return (MemberInfo) List [index];
1607 public int Add (object value)
1609 throw new NotSupportedException ();
1612 public void Clear ()
1614 throw new NotSupportedException ();
1617 public bool Contains (object value)
1619 return List.Contains (value);
1622 public int IndexOf (object value)
1624 return List.IndexOf (value);
1627 public void Insert (int index, object value)
1629 throw new NotSupportedException ();
1632 public void Remove (object value)
1634 throw new NotSupportedException ();
1637 public void RemoveAt (int index)
1639 throw new NotSupportedException ();
1644 /// This interface is used to get all members of a class when creating the
1645 /// member cache. It must be implemented by all DeclSpace derivatives which
1646 /// want to support the member cache and by TypeHandle to get caching of
1647 /// non-dynamic types.
1649 public interface IMemberContainer {
1651 /// The name of the IMemberContainer. This is only used for
1652 /// debugging purposes.
1659 /// The type of this IMemberContainer.
1666 /// Returns the IMemberContainer of the parent class or null if this
1667 /// is an interface or TypeManger.object_type.
1668 /// This is used when creating the member cache for a class to get all
1669 /// members from the parent class.
1671 IMemberContainer ParentContainer {
1676 /// Whether this is an interface.
1683 /// Returns all members of this class with the corresponding MemberTypes
1684 /// and BindingFlags.
1687 /// When implementing this method, make sure not to return any inherited
1688 /// members and check the MemberTypes and BindingFlags properly.
1689 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1690 /// get the BindingFlags (static/non-static,public/non-public) in the
1691 /// MemberInfo class, but the cache needs this information. That's why
1692 /// this method is called multiple times with different BindingFlags.
1694 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1697 /// Return the container's member cache.
1699 MemberCache MemberCache {
1705 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1706 /// member lookups. It has a member name based hash table; it maps each member
1707 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1708 /// and the BindingFlags that were initially used to get it. The cache contains
1709 /// all members of the current class and all inherited members. If this cache is
1710 /// for an interface types, it also contains all inherited members.
1712 /// There are two ways to get a MemberCache:
1713 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1714 /// use the DeclSpace.MemberCache property.
1715 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1716 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1718 public class MemberCache {
1719 public readonly IMemberContainer Container;
1720 protected Hashtable member_hash;
1721 protected Hashtable method_hash;
1724 /// Create a new MemberCache for the given IMemberContainer `container'.
1726 public MemberCache (IMemberContainer container)
1728 this.Container = container;
1730 Timer.IncrementCounter (CounterType.MemberCache);
1731 Timer.StartTimer (TimerType.CacheInit);
1735 // If we have a parent class (we have a parent class unless we're
1736 // TypeManager.object_type), we deep-copy its MemberCache here.
1737 if (Container.IsInterface) {
1740 if (Container.ParentContainer != null)
1741 parent = Container.ParentContainer.MemberCache;
1743 parent = TypeHandle.ObjectType.MemberCache;
1744 member_hash = SetupCacheForInterface (parent);
1745 } else if (Container.ParentContainer != null)
1746 member_hash = SetupCache (Container.ParentContainer.MemberCache);
1748 member_hash = new Hashtable ();
1750 // If this is neither a dynamic type nor an interface, create a special
1751 // method cache with all declared and inherited methods.
1752 Type type = container.Type;
1753 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1754 method_hash = new Hashtable ();
1758 // Add all members from the current class.
1759 AddMembers (Container);
1761 Timer.StopTimer (TimerType.CacheInit);
1765 /// Bootstrap this member cache by doing a deep-copy of our parent.
1767 Hashtable SetupCache (MemberCache parent)
1769 Hashtable hash = new Hashtable ();
1771 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1772 while (it.MoveNext ()) {
1773 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1781 /// Add the contents of `new_hash' to `hash'.
1783 void AddHashtable (Hashtable hash, MemberCache cache)
1785 Hashtable new_hash = cache.member_hash;
1786 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1787 while (it.MoveNext ()) {
1788 ArrayList list = (ArrayList) hash [it.Key];
1790 hash [it.Key] = list = new ArrayList ();
1792 foreach (CacheEntry entry in (ArrayList) it.Value) {
1793 if (entry.Container != cache.Container)
1801 /// Bootstrap the member cache for an interface type.
1802 /// Type.GetMembers() won't return any inherited members for interface types,
1803 /// so we need to do this manually. Interfaces also inherit from System.Object.
1805 Hashtable SetupCacheForInterface (MemberCache parent)
1807 Hashtable hash = SetupCache (parent);
1808 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1810 foreach (Type itype in ifaces) {
1811 IMemberContainer iface_container =
1812 TypeManager.LookupMemberContainer (itype);
1814 MemberCache iface_cache = iface_container.MemberCache;
1816 AddHashtable (hash, iface_cache);
1823 /// Add all members from class `container' to the cache.
1825 void AddMembers (IMemberContainer container)
1827 // We need to call AddMembers() with a single member type at a time
1828 // to get the member type part of CacheEntry.EntryType right.
1829 AddMembers (MemberTypes.Constructor, container);
1830 AddMembers (MemberTypes.Field, container);
1831 AddMembers (MemberTypes.Method, container);
1832 AddMembers (MemberTypes.Property, container);
1833 AddMembers (MemberTypes.Event, container);
1834 // Nested types are returned by both Static and Instance searches.
1835 AddMembers (MemberTypes.NestedType,
1836 BindingFlags.Static | BindingFlags.Public, container);
1837 AddMembers (MemberTypes.NestedType,
1838 BindingFlags.Static | BindingFlags.NonPublic, container);
1841 void AddMembers (MemberTypes mt, IMemberContainer container)
1843 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1844 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1845 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1846 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1850 /// Add all members from class `container' with the requested MemberTypes and
1851 /// BindingFlags to the cache. This method is called multiple times with different
1852 /// MemberTypes and BindingFlags.
1854 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1856 MemberList members = container.GetMembers (mt, bf);
1858 foreach (MemberInfo member in members) {
1859 string name = member.Name;
1861 int pos = name.IndexOf ('<');
1863 name = name.Substring (0, pos);
1865 // We use a name-based hash table of ArrayList's.
1866 ArrayList list = (ArrayList) member_hash [name];
1868 list = new ArrayList ();
1869 member_hash.Add (name, list);
1872 // When this method is called for the current class, the list will
1873 // already contain all inherited members from our parent classes.
1874 // We cannot add new members in front of the list since this'd be an
1875 // expensive operation, that's why the list is sorted in reverse order
1876 // (ie. members from the current class are coming last).
1877 list.Add (new CacheEntry (container, member, mt, bf));
1882 /// Add all declared and inherited methods from class `type' to the method cache.
1884 void AddMethods (Type type)
1886 AddMethods (BindingFlags.Static | BindingFlags.Public |
1887 BindingFlags.FlattenHierarchy, type);
1888 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1889 BindingFlags.FlattenHierarchy, type);
1890 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1891 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1894 void AddMethods (BindingFlags bf, Type type)
1896 MemberInfo [] members = type.GetMethods (bf);
1898 Array.Reverse (members);
1900 foreach (MethodBase member in members) {
1901 string name = member.Name;
1903 // We use a name-based hash table of ArrayList's.
1904 ArrayList list = (ArrayList) method_hash [name];
1906 list = new ArrayList ();
1907 method_hash.Add (name, list);
1910 // Unfortunately, the elements returned by Type.GetMethods() aren't
1911 // sorted so we need to do this check for every member.
1912 BindingFlags new_bf = bf;
1913 if (member.DeclaringType == type)
1914 new_bf |= BindingFlags.DeclaredOnly;
1916 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1921 /// Compute and return a appropriate `EntryType' magic number for the given
1922 /// MemberTypes and BindingFlags.
1924 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1926 EntryType type = EntryType.None;
1928 if ((mt & MemberTypes.Constructor) != 0)
1929 type |= EntryType.Constructor;
1930 if ((mt & MemberTypes.Event) != 0)
1931 type |= EntryType.Event;
1932 if ((mt & MemberTypes.Field) != 0)
1933 type |= EntryType.Field;
1934 if ((mt & MemberTypes.Method) != 0)
1935 type |= EntryType.Method;
1936 if ((mt & MemberTypes.Property) != 0)
1937 type |= EntryType.Property;
1938 // Nested types are returned by static and instance searches.
1939 if ((mt & MemberTypes.NestedType) != 0)
1940 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1942 if ((bf & BindingFlags.Instance) != 0)
1943 type |= EntryType.Instance;
1944 if ((bf & BindingFlags.Static) != 0)
1945 type |= EntryType.Static;
1946 if ((bf & BindingFlags.Public) != 0)
1947 type |= EntryType.Public;
1948 if ((bf & BindingFlags.NonPublic) != 0)
1949 type |= EntryType.NonPublic;
1950 if ((bf & BindingFlags.DeclaredOnly) != 0)
1951 type |= EntryType.Declared;
1957 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1958 /// denote multiple member types. Returns true if the given flags value denotes a
1959 /// single member types.
1961 public static bool IsSingleMemberType (MemberTypes mt)
1964 case MemberTypes.Constructor:
1965 case MemberTypes.Event:
1966 case MemberTypes.Field:
1967 case MemberTypes.Method:
1968 case MemberTypes.Property:
1969 case MemberTypes.NestedType:
1978 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1979 /// number to speed up the searching process.
1982 protected enum EntryType {
1987 MaskStatic = Instance|Static,
1991 MaskProtection = Public|NonPublic,
1995 Constructor = 0x020,
2002 MaskType = Constructor|Event|Field|Method|Property|NestedType
2005 protected struct CacheEntry {
2006 public readonly IMemberContainer Container;
2007 public readonly EntryType EntryType;
2008 public readonly MemberInfo Member;
2010 public CacheEntry (IMemberContainer container, MemberInfo member,
2011 MemberTypes mt, BindingFlags bf)
2013 this.Container = container;
2014 this.Member = member;
2015 this.EntryType = GetEntryType (mt, bf);
2020 /// This is called each time we're walking up one level in the class hierarchy
2021 /// and checks whether we can abort the search since we've already found what
2022 /// we were looking for.
2024 protected bool DoneSearching (ArrayList list)
2027 // We've found exactly one member in the current class and it's not
2028 // a method or constructor.
2030 if (list.Count == 1 && !(list [0] is MethodBase))
2034 // Multiple properties: we query those just to find out the indexer
2037 if ((list.Count > 0) && (list [0] is PropertyInfo))
2044 /// Looks up members with name `name'. If you provide an optional
2045 /// filter function, it'll only be called with members matching the
2046 /// requested member name.
2048 /// This method will try to use the cache to do the lookup if possible.
2050 /// Unlike other FindMembers implementations, this method will always
2051 /// check all inherited members - even when called on an interface type.
2053 /// If you know that you're only looking for methods, you should use
2054 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2055 /// When doing a method-only search, it'll try to use a special method
2056 /// cache (unless it's a dynamic type or an interface) and the returned
2057 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2058 /// The lookup process will automatically restart itself in method-only
2059 /// search mode if it discovers that it's about to return methods.
2061 ArrayList global = new ArrayList ();
2062 bool using_global = false;
2064 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2066 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2067 MemberFilter filter, object criteria)
2070 throw new Exception ();
2072 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2073 bool method_search = mt == MemberTypes.Method;
2074 // If we have a method cache and we aren't already doing a method-only search,
2075 // then we restart a method search if the first match is a method.
2076 bool do_method_search = !method_search && (method_hash != null);
2078 ArrayList applicable;
2080 // If this is a method-only search, we try to use the method cache if
2081 // possible; a lookup in the method cache will return a MemberInfo with
2082 // the correct ReflectedType for inherited methods.
2084 if (method_search && (method_hash != null))
2085 applicable = (ArrayList) method_hash [name];
2087 applicable = (ArrayList) member_hash [name];
2089 if (applicable == null)
2090 return emptyMemberInfo;
2093 // 32 slots gives 53 rss/54 size
2094 // 2/4 slots gives 55 rss
2096 // Strange: from 25,000 calls, only 1,800
2097 // are above 2. Why does this impact it?
2100 using_global = true;
2102 Timer.StartTimer (TimerType.CachedLookup);
2104 EntryType type = GetEntryType (mt, bf);
2106 IMemberContainer current = Container;
2109 // `applicable' is a list of all members with the given member name `name'
2110 // in the current class and all its parent classes. The list is sorted in
2111 // reverse order due to the way how the cache is initialy created (to speed
2112 // things up, we're doing a deep-copy of our parent).
2114 for (int i = applicable.Count-1; i >= 0; i--) {
2115 CacheEntry entry = (CacheEntry) applicable [i];
2117 // This happens each time we're walking one level up in the class
2118 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2119 // the first time this happens (this may already happen in the first
2120 // iteration of this loop if there are no members with the name we're
2121 // looking for in the current class).
2122 if (entry.Container != current) {
2123 if (declared_only || DoneSearching (global))
2126 current = entry.Container;
2129 // Is the member of the correct type ?
2130 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2133 // Is the member static/non-static ?
2134 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2137 // Apply the filter to it.
2138 if (filter (entry.Member, criteria)) {
2139 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2140 do_method_search = false;
2141 global.Add (entry.Member);
2145 Timer.StopTimer (TimerType.CachedLookup);
2147 // If we have a method cache and we aren't already doing a method-only
2148 // search, we restart in method-only search mode if the first match is
2149 // a method. This ensures that we return a MemberInfo with the correct
2150 // ReflectedType for inherited methods.
2151 if (do_method_search && (global.Count > 0)){
2152 using_global = false;
2154 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2157 using_global = false;
2158 MemberInfo [] copy = new MemberInfo [global.Count];
2159 global.CopyTo (copy);
2164 // This finds the method or property for us to override. invocationType is the type where
2165 // the override is going to be declared, name is the name of the method/property, and
2166 // paramTypes is the parameters, if any to the method or property
2168 // Because the MemberCache holds members from this class and all the base classes,
2169 // we can avoid tons of reflection stuff.
2171 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2173 ArrayList applicable;
2174 if (method_hash != null && !is_property)
2175 applicable = (ArrayList) method_hash [name];
2177 applicable = (ArrayList) member_hash [name];
2179 if (applicable == null)
2182 // Walk the chain of methods, starting from the top.
2184 for (int i = applicable.Count - 1; i >= 0; i--) {
2185 CacheEntry entry = (CacheEntry) applicable [i];
2187 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2190 PropertyInfo pi = null;
2191 MethodInfo mi = null;
2192 FieldInfo fi = null;
2193 Type [] cmpAttrs = null;
2196 if ((entry.EntryType & EntryType.Field) != 0) {
2197 fi = (FieldInfo)entry.Member;
2199 // TODO: For this case we ignore member type
2200 //fb = TypeManager.GetField (fi);
2201 //cmpAttrs = new Type[] { fb.MemberType };
2203 pi = (PropertyInfo) entry.Member;
2204 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2207 mi = (MethodInfo) entry.Member;
2208 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2212 // TODO: Almost duplicate !
2214 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2215 case FieldAttributes.Private:
2217 // A private method is Ok if we are a nested subtype.
2218 // The spec actually is not very clear about this, see bug 52458.
2220 if (invocationType != entry.Container.Type &
2221 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2225 case FieldAttributes.FamANDAssem:
2226 case FieldAttributes.Assembly:
2228 // Check for assembly methods
2230 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2234 return entry.Member;
2238 // Check the arguments
2240 if (cmpAttrs.Length != paramTypes.Length)
2243 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2244 if (!paramTypes [j].Equals (cmpAttrs [j]))
2249 // get one of the methods because this has the visibility info.
2252 mi = pi.GetGetMethod (true);
2254 mi = pi.GetSetMethod (true);
2260 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2261 case MethodAttributes.Private:
2263 // A private method is Ok if we are a nested subtype.
2264 // The spec actually is not very clear about this, see bug 52458.
2266 if (invocationType == entry.Container.Type ||
2267 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2268 return entry.Member;
2271 case MethodAttributes.FamANDAssem:
2272 case MethodAttributes.Assembly:
2274 // Check for assembly methods
2276 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2277 return entry.Member;
2282 // A protected method is ok, because we are overriding.
2283 // public is always ok.
2285 return entry.Member;
2295 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2296 /// We handle two cases. The first is for types without parameters (events, field, properties).
2297 /// The second are methods, indexers and this is why ignore_complex_types is here.
2298 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2300 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2302 ArrayList applicable = null;
2304 if (method_hash != null)
2305 applicable = (ArrayList) method_hash [name];
2307 if (applicable != null) {
2308 for (int i = applicable.Count - 1; i >= 0; i--) {
2309 CacheEntry entry = (CacheEntry) applicable [i];
2310 if ((entry.EntryType & EntryType.Public) != 0)
2311 return entry.Member;
2315 if (member_hash == null)
2317 applicable = (ArrayList) member_hash [name];
2319 if (applicable != null) {
2320 for (int i = applicable.Count - 1; i >= 0; i--) {
2321 CacheEntry entry = (CacheEntry) applicable [i];
2322 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2323 if (ignore_complex_types) {
2324 if ((entry.EntryType & EntryType.Method) != 0)
2327 // Does exist easier way how to detect indexer ?
2328 if ((entry.EntryType & EntryType.Property) != 0) {
2329 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2330 if (arg_types.Length == 1)
2334 return entry.Member;
2341 Hashtable locase_table;
2344 /// Builds low-case table for CLS Compliance test
2346 public Hashtable GetPublicMembers ()
2348 if (locase_table != null)
2349 return locase_table;
2351 locase_table = new Hashtable ();
2352 foreach (DictionaryEntry entry in member_hash) {
2353 ArrayList members = (ArrayList)entry.Value;
2354 for (int ii = 0; ii < members.Count; ++ii) {
2355 CacheEntry member_entry = (CacheEntry) members [ii];
2357 if ((member_entry.EntryType & EntryType.Public) == 0)
2360 // TODO: Does anyone know easier way how to detect that member is internal ?
2361 switch (member_entry.EntryType & EntryType.MaskType) {
2362 case EntryType.Constructor:
2365 case EntryType.Field:
2366 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2370 case EntryType.Method:
2371 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2375 case EntryType.Property:
2376 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2377 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2381 case EntryType.Event:
2382 EventInfo ei = (EventInfo)member_entry.Member;
2383 MethodInfo mi = ei.GetAddMethod ();
2384 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2388 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2389 locase_table [lcase] = member_entry.Member;
2393 return locase_table;
2396 public Hashtable Members {
2403 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2405 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2407 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2409 for (int i = 0; i < al.Count; ++i) {
2410 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2413 if (entry.Member == this_builder)
2416 if ((entry.EntryType & tested_type) != tested_type)
2419 MethodBase method_to_compare = (MethodBase)entry.Member;
2420 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2423 IMethodData md = TypeManager.GetMethod (method_to_compare);
2425 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2426 // However it is exactly what csc does.
2427 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2430 Report.SymbolRelatedToPreviousError (entry.Member);
2431 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());