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 GetFullName ()
93 if (TypeArguments != null)
94 full_name = Name + "<" + TypeArguments + ">";
98 return Left.GetFullName () + "." + full_name;
103 public static string MakeName (string name, TypeArguments args)
108 return name + "`" + args.Count;
111 public static string MakeName (string name, int count)
113 return name + "`" + count;
116 public string GetTypeName ()
120 return Left.GetTypeName () + "." +
121 MakeName (Name, TypeArguments);
123 return MakeName (Name, TypeArguments);
126 protected bool IsUnbound {
128 if ((Left != null) && Left.IsUnbound)
130 else if (TypeArguments == null)
133 return TypeArguments.IsUnbound;
137 protected bool CheckUnbound (Location loc)
139 if ((Left != null) && !Left.CheckUnbound (loc))
141 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
142 Report.Error (1031, loc, "Type expected");
149 public Expression GetTypeExpression (Location loc)
152 if (!CheckUnbound (loc))
155 return new UnboundTypeExpression (GetTypeName ());
159 Expression lexpr = Left.GetTypeExpression (loc);
161 return new MemberAccess (lexpr, Name, TypeArguments, loc);
163 if (TypeArguments != null)
164 return new ConstructedType (Name, TypeArguments, loc);
166 return new SimpleName (Name, loc);
170 public string Basename {
172 if (TypeArguments != null)
173 return MakeName (Name, TypeArguments);
179 public override string ToString ()
182 if (TypeArguments != null)
183 full_name = Name + "<" + TypeArguments + ">";
188 return Left + "." + full_name;
195 /// Base representation for members. This is used to keep track
196 /// of Name, Location and Modifier flags, and handling Attributes.
198 public abstract class MemberCore : Attributable {
204 public readonly MemberName MemberName;
207 /// Modifier flags that the user specified in the source code
211 public readonly TypeContainer Parent;
214 /// Location where this declaration happens
216 public readonly Location Location;
220 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
221 Obsolete = 1 << 1, // Type has obsolete attribute
222 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
223 ClsCompliant = 1 << 3, // Type is CLS Compliant
224 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
225 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
226 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
227 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
228 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
229 Excluded = 1 << 9 // Method is conditional
234 /// MemberCore flags at first detected then cached
236 protected Flags caching_flags;
238 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
243 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
246 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
250 /// Tests presence of ObsoleteAttribute and report proper error
252 protected void CheckUsageOfObsoleteAttribute (Type type)
257 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
258 if (obsolete_attr == null)
261 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
264 public abstract bool Define ();
267 // Returns full member name for error message
269 public virtual string GetSignatureForError ()
275 /// Base Emit method. This is also entry point for CLS-Compliant verification.
277 public virtual void Emit ()
279 VerifyObsoleteAttribute ();
281 if (!RootContext.VerifyClsCompliance)
284 VerifyClsCompliance (Parent);
288 // Whehter is it ok to use an unsafe pointer in this type container
290 public bool UnsafeOK (DeclSpace parent)
293 // First check if this MemberCore modifier flags has unsafe set
295 if ((ModFlags & Modifiers.UNSAFE) != 0)
298 if (parent.UnsafeContext)
301 Expression.UnsafeError (Location);
306 /// Returns instance of ObsoleteAttribute for this MemberCore
308 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
310 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
311 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
315 caching_flags &= ~Flags.Obsolete_Undetected;
317 if (OptAttributes == null)
320 // TODO: remove this allocation
321 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
322 null, null, ds.ModFlags, false);
324 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
325 if (obsolete_attr == null)
328 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
329 if (obsolete == null)
332 caching_flags |= Flags.Obsolete;
337 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
339 public override bool IsClsCompliaceRequired (DeclSpace container)
341 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
342 return (caching_flags & Flags.ClsCompliant) != 0;
344 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
345 caching_flags &= ~Flags.ClsCompliance_Undetected;
346 caching_flags |= Flags.ClsCompliant;
350 caching_flags &= ~Flags.ClsCompliance_Undetected;
355 /// Returns true when MemberCore is exposed from assembly.
357 protected bool IsExposedFromAssembly (DeclSpace ds)
359 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
362 DeclSpace parentContainer = ds;
363 while (parentContainer != null && parentContainer.ModFlags != 0) {
364 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
366 parentContainer = parentContainer.Parent;
372 /// Resolve CLSCompliantAttribute value or gets cached value.
374 bool GetClsCompliantAttributeValue (DeclSpace ds)
376 if (OptAttributes != null) {
377 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
378 null, null, ds.ModFlags, false);
379 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
380 if (cls_attribute != null) {
381 caching_flags |= Flags.HasClsCompliantAttribute;
382 return cls_attribute.GetClsCompliantAttributeValue (ds);
385 return ds.GetClsCompliantAttributeValue ();
389 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
391 protected bool HasClsCompliantAttribute {
393 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
398 /// This method is used to testing error 3005 (Method or parameter name collision).
400 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
403 /// Common helper method for identifier and parameters CLS-Compliant testing.
404 /// When return false error 3005 is reported. True means no violation.
405 /// And error 3006 tests are peformed here because of speed.
407 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
409 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
410 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
415 bool error3006 = false;
416 for (int i = 0; i < ml.Count; ++i) {
417 MemberInfo mi = ml [i];
418 if (name == mi.Name) {
419 MethodBase method = mi as MethodBase;
420 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
423 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
431 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
432 // because BindingFlags.Public returns internal types too
433 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
435 // Type is external, we can get attribute directly
436 if (temp_ds == null) {
437 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
438 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
441 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
443 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
444 if (!mc.IsClsCompliaceRequired (ds))
448 for (int ii = 0; ii < ml.Count; ++ii) {
452 Report.SymbolRelatedToPreviousError (mi);
456 Report.Error_T (3006, Location, GetSignatureForError ());
465 /// The main virtual method for CLS-Compliant verifications.
466 /// The method returns true if member is CLS-Compliant and false if member is not
467 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
468 /// and add their extra verifications.
470 protected virtual bool VerifyClsCompliance (DeclSpace ds)
472 if (!IsClsCompliaceRequired (ds)) {
473 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
474 Report.Warning_T (3019, Location, GetSignatureForError ());
479 if (!CodeGen.Assembly.IsClsCompliant) {
480 if (HasClsCompliantAttribute) {
481 Report.Error_T (3014, Location, GetSignatureForError ());
485 int index = Name.LastIndexOf ('.');
486 if (Name [index > 0 ? index + 1 : 0] == '_') {
487 Report.Error_T (3008, Location, GetSignatureForError () );
490 if (!IsIdentifierClsCompliant (ds)) {
491 Report.Error_T (3005, Location, GetSignatureForError ());
497 protected abstract void VerifyObsoleteAttribute ();
502 /// Base class for structs, classes, enumerations and interfaces.
505 /// They all create new declaration spaces. This
506 /// provides the common foundation for managing those name
509 public abstract class DeclSpace : MemberCore, IAlias {
511 /// This points to the actual definition that is being
512 /// created with System.Reflection.Emit
514 public TypeBuilder TypeBuilder;
517 /// If we are a generic type, this is the type we are
518 /// currently defining. We need to lookup members on this
519 /// instead of the TypeBuilder.
521 public TypeExpr CurrentType;
524 // This is the namespace in which this typecontainer
525 // was declared. We use this to resolve names.
527 public NamespaceEntry NamespaceEntry;
529 public Hashtable Cache = new Hashtable ();
531 public string Basename;
534 /// defined_names is used for toplevel objects
536 protected Hashtable defined_names;
538 readonly bool is_generic;
539 readonly int count_type_params;
542 // Whether we are Generic
544 public bool IsGeneric {
548 else if (Parent != null)
549 return Parent.IsGeneric;
555 static string[] attribute_targets = new string [] { "type" };
557 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
558 Attributes attrs, Location l)
559 : base (parent, name, attrs, l)
562 Basename = name.Name;
563 defined_names = new Hashtable ();
564 if (name.TypeArguments != null) {
566 count_type_params = name.TypeArguments.Count;
569 count_type_params += parent.count_type_params;
572 public void RecordDecl ()
574 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
575 NamespaceEntry.DefineName (MemberName.Basename, this);
579 /// The result value from adding an declaration into
580 /// a struct or a class
582 public enum AdditionResult {
584 /// The declaration has been successfully
585 /// added to the declation space.
590 /// The symbol has already been defined.
595 /// Returned if the declation being added to the
596 /// name space clashes with its container name.
598 /// The only exceptions for this are constructors
599 /// and static constructors
604 /// Returned if a constructor was created (because syntactically
605 /// it looked like a constructor) but was not (because the name
606 /// of the method is not the same as the container class
611 /// This is only used by static constructors to emit the
612 /// error 111, but this error for other things really
613 /// happens at another level for other functions.
618 /// Some other error.
624 /// Returns a status code based purely on the name
625 /// of the member being added
627 protected AdditionResult IsValid (string basename, string name)
629 if (basename == Basename)
630 return AdditionResult.EnclosingClash;
632 if (defined_names.Contains (name))
633 return AdditionResult.NameExists;
635 return AdditionResult.Success;
638 public static int length;
639 public static int small;
642 /// Introduce @name into this declaration space and
643 /// associates it with the object @o. Note that for
644 /// methods this will just point to the first method. o
646 public void DefineName (string name, object o)
648 defined_names.Add (name, o);
651 int p = name.LastIndexOf ('.');
659 /// Returns the object associated with a given name in the declaration
660 /// space. This is the inverse operation of `DefineName'
662 public object GetDefinition (string name)
664 return defined_names [name];
667 bool in_transit = false;
670 /// This function is used to catch recursive definitions
673 public bool InTransit {
684 /// Looks up the alias for the name
686 public IAlias LookupAlias (string name)
688 if (NamespaceEntry != null)
689 return NamespaceEntry.LookupAlias (name);
695 // root_types contains all the types. All TopLevel types
696 // hence have a parent that points to `root_types', that is
697 // why there is a non-obvious test down here.
699 public bool IsTopLevel {
702 if (Parent.Parent == null)
709 public virtual void CloseType ()
711 if ((caching_flags & Flags.CloseTypeCreated) == 0){
713 TypeBuilder.CreateType ();
716 // The try/catch is needed because
717 // nested enumerations fail to load when they
720 // Even if this is the right order (enumerations
721 // declared after types).
723 // Note that this still creates the type and
724 // it is possible to save it
726 caching_flags |= Flags.CloseTypeCreated;
731 /// Should be overriten by the appropriate declaration space
733 public abstract TypeBuilder DefineType ();
736 /// Define all members, but don't apply any attributes or do anything which may
737 /// access not-yet-defined classes. This method also creates the MemberCache.
739 public abstract bool DefineMembers (TypeContainer parent);
742 // Whether this is an `unsafe context'
744 public bool UnsafeContext {
746 if ((ModFlags & Modifiers.UNSAFE) != 0)
749 return Parent.UnsafeContext;
754 public static string MakeFQN (string nsn, string name)
758 return String.Concat (nsn, ".", name);
761 EmitContext type_resolve_ec;
762 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
764 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
765 type_resolve_ec.ResolvingTypeTree = true;
767 return type_resolve_ec;
771 // Looks up the type, as parsed into the expression `e'
773 public Type ResolveType (Expression e, bool silent, Location loc)
775 TypeExpr d = ResolveTypeExpr (e, silent, loc);
779 return ResolveType (d, loc);
782 public Type ResolveType (TypeExpr d, Location loc)
784 if (!d.CheckAccessLevel (this)) {
785 Report.Error_T (122, loc, d.Name);
789 Type t = d.ResolveType (type_resolve_ec);
793 if (d is UnboundTypeExpression)
796 TypeContainer tc = TypeManager.LookupTypeContainer (t);
797 if ((tc != null) && tc.IsGeneric) {
799 int tnum = TypeManager.GetNumberOfTypeArguments (t);
800 Report.Error (305, loc,
801 "Using the generic type `{0}' " +
802 "requires {1} type arguments",
803 TypeManager.GetFullName (t), tnum);
807 ConstructedType ctype = new ConstructedType (
808 t, TypeParameters, loc);
810 t = ctype.ResolveType (type_resolve_ec);
817 // Resolves the expression `e' for a type, and will recursively define
820 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
822 if (type_resolve_ec == null)
823 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
824 type_resolve_ec.loc = loc;
825 if (this is GenericMethod)
826 type_resolve_ec.ContainerType = Parent.TypeBuilder;
828 type_resolve_ec.ContainerType = TypeBuilder;
830 int errors = Report.Errors;
832 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
834 if ((d != null) && (d.eclass == ExprClass.Type))
837 if (silent || (Report.Errors != errors))
840 if (e is SimpleName){
841 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
842 d = s.ResolveAsTypeTerminal (type_resolve_ec);
844 if ((d == null) || (d.Type == null)) {
845 Report.Error (246, loc, "Cannot find type `{0}'", e);
849 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
852 Report.Error (308, loc,
853 "The non-generic type `{0}' cannot " +
854 "be used with type arguments.",
855 TypeManager.CSharpName (d.Type));
859 Report.Error (305, loc,
860 "Using the generic type `{0}' " +
861 "requires {1} type arguments",
862 TypeManager.GetFullName (d.Type), num_args);
866 Report.Error (246, loc, "Cannot find type `{0}'", e);
870 public bool CheckAccessLevel (Type check_type)
873 if (this is GenericMethod)
874 tb = Parent.TypeBuilder;
878 if (check_type.IsGenericInstance)
879 check_type = check_type.GetGenericTypeDefinition ();
881 if (check_type == tb)
884 if (check_type.IsGenericParameter)
885 return true; // FIXME
887 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
890 // Broken Microsoft runtime, return public for arrays, no matter what
891 // the accessibility is for their underlying class, and they return
892 // NonPublic visibility for pointers
894 if (check_type.IsArray || check_type.IsPointer)
895 return CheckAccessLevel (TypeManager.GetElementType (check_type));
898 case TypeAttributes.Public:
901 case TypeAttributes.NotPublic:
903 // In same cases is null.
904 if (TypeBuilder == null)
908 // This test should probably use the declaringtype.
910 return check_type.Assembly == TypeBuilder.Assembly;
912 case TypeAttributes.NestedPublic:
915 case TypeAttributes.NestedPrivate:
916 string check_type_name = check_type.FullName;
917 string type_name = tb.FullName;
919 int cio = check_type_name.LastIndexOf ('+');
920 string container = check_type_name.Substring (0, cio);
923 // Check if the check_type is a nested class of the current type
925 if (check_type_name.StartsWith (type_name + "+")){
929 if (type_name.StartsWith (container)){
935 case TypeAttributes.NestedFamily:
937 // Only accessible to methods in current type or any subtypes
939 return FamilyAccessible (tb, check_type);
941 case TypeAttributes.NestedFamANDAssem:
942 return (check_type.Assembly == tb.Assembly) &&
943 FamilyAccessible (tb, check_type);
945 case TypeAttributes.NestedFamORAssem:
946 return (check_type.Assembly == tb.Assembly) ||
947 FamilyAccessible (tb, check_type);
949 case TypeAttributes.NestedAssembly:
950 return check_type.Assembly == tb.Assembly;
953 Console.WriteLine ("HERE: " + check_attr);
958 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
960 Type declaring = check_type.DeclaringType;
961 if (tb.IsSubclassOf (declaring))
964 string check_type_name = check_type.FullName;
966 int cio = check_type_name.LastIndexOf ('+');
967 string container = check_type_name.Substring (0, cio);
970 // Check if the check_type is a nested class of the current type
972 if (check_type_name.StartsWith (container + "+"))
978 // Access level of a type.
980 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
981 // Public Assembly Protected
982 Protected = (0 << 0) | (0 << 1) | (X << 2),
983 Public = (X << 0) | (X << 1) | (X << 2),
984 Private = (0 << 0) | (0 << 1) | (0 << 2),
985 Internal = (0 << 0) | (X << 1) | (0 << 2),
986 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
989 static AccessLevel GetAccessLevelFromModifiers (int flags)
991 if ((flags & Modifiers.INTERNAL) != 0) {
993 if ((flags & Modifiers.PROTECTED) != 0)
994 return AccessLevel.ProtectedOrInternal;
996 return AccessLevel.Internal;
998 } else if ((flags & Modifiers.PROTECTED) != 0)
999 return AccessLevel.Protected;
1000 else if ((flags & Modifiers.PRIVATE) != 0)
1001 return AccessLevel.Private;
1003 return AccessLevel.Public;
1006 // What is the effective access level of this?
1007 // TODO: Cache this?
1008 AccessLevel EffectiveAccessLevel {
1010 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1011 if (!IsTopLevel && (Parent != null))
1012 return myAccess & Parent.EffectiveAccessLevel;
1017 // Return the access level for type `t'
1018 static AccessLevel TypeEffectiveAccessLevel (Type t)
1021 return AccessLevel.Public;
1022 if (t.IsNestedPrivate)
1023 return AccessLevel.Private;
1025 return AccessLevel.Internal;
1027 // By now, it must be nested
1028 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1030 if (t.IsNestedPublic)
1032 if (t.IsNestedAssembly)
1033 return parentLevel & AccessLevel.Internal;
1034 if (t.IsNestedFamily)
1035 return parentLevel & AccessLevel.Protected;
1036 if (t.IsNestedFamORAssem)
1037 return parentLevel & AccessLevel.ProtectedOrInternal;
1038 if (t.IsNestedFamANDAssem)
1039 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1041 // nested private is taken care of
1043 throw new Exception ("I give up, what are you?");
1047 // This answers `is the type P, as accessible as a member M which has the
1048 // accessability @flags which is declared as a nested member of the type T, this declspace'
1050 public bool AsAccessible (Type p, int flags)
1052 if (p.IsGenericParameter)
1053 return true; // FIXME
1056 // 1) if M is private, its accessability is the same as this declspace.
1057 // we already know that P is accessible to T before this method, so we
1061 if ((flags & Modifiers.PRIVATE) != 0)
1064 while (p.IsArray || p.IsPointer || p.IsByRef)
1065 p = TypeManager.GetElementType (p);
1067 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1068 AccessLevel mAccess = this.EffectiveAccessLevel &
1069 GetAccessLevelFromModifiers (flags);
1071 // for every place from which we can access M, we must
1072 // be able to access P as well. So, we want
1073 // For every bit in M and P, M_i -> P_1 == true
1074 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1076 return ~ (~ mAccess | pAccess) == 0;
1079 static DoubleHash dh = new DoubleHash (1000);
1081 Type DefineTypeAndParents (DeclSpace tc)
1083 DeclSpace container = tc.Parent;
1085 if (container.TypeBuilder == null && container.Name != "")
1086 DefineTypeAndParents (container);
1088 return tc.DefineType ();
1091 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1099 if (dh.Lookup (ns, name, out r))
1103 if (Namespace.IsNamespace (ns)){
1104 string fullname = (ns != "") ? ns + "." + name : name;
1105 t = TypeManager.LookupType (fullname);
1109 t = TypeManager.LookupType (name);
1113 dh.Insert (ns, name, t);
1118 // In case we are fed a composite name, normalize it.
1120 int p = name.LastIndexOf ('.');
1122 ns = MakeFQN (ns, name.Substring (0, p));
1123 name = name.Substring (p+1);
1126 parent = RootContext.Tree.LookupByNamespace (ns, name);
1127 if (parent == null) {
1128 dh.Insert (ns, name, null);
1132 t = DefineTypeAndParents (parent);
1138 dh.Insert (ns, name, t);
1142 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1144 Report.Error (104, loc,
1145 "`{0}' is an ambiguous reference ({1} or {2})",
1149 public Type FindNestedType (Location loc, string name,
1150 out DeclSpace containing_ds)
1155 containing_ds = this;
1156 while (containing_ds != null){
1157 Type container_type = containing_ds.TypeBuilder;
1158 Type current_type = container_type;
1160 while (current_type != null && current_type != TypeManager.object_type) {
1161 string pre = current_type.FullName;
1163 t = LookupInterfaceOrClass (pre, name, out error);
1167 if ((t != null) && containing_ds.CheckAccessLevel (t))
1170 current_type = current_type.BaseType;
1172 containing_ds = containing_ds.Parent;
1179 /// GetType is used to resolve type names at the DeclSpace level.
1180 /// Use this to lookup class/struct bases, interface bases or
1181 /// delegate type references
1185 /// Contrast this to LookupType which is used inside method bodies to
1186 /// lookup types that have already been defined. GetType is used
1187 /// during the tree resolution process and potentially define
1188 /// recursively the type
1190 public Type FindType (Location loc, string name)
1196 // For the case the type we are looking for is nested within this one
1197 // or is in any base class
1199 DeclSpace containing_ds = this;
1201 while (containing_ds != null){
1202 Type container_type = containing_ds.TypeBuilder;
1203 Type current_type = container_type;
1205 while (current_type != null && current_type != TypeManager.object_type) {
1206 string pre = current_type.FullName;
1208 t = LookupInterfaceOrClass (pre, name, out error);
1212 if ((t != null) && containing_ds.CheckAccessLevel (t))
1215 current_type = current_type.BaseType;
1217 containing_ds = containing_ds.Parent;
1221 // Attempt to lookup the class on our namespace and all it's implicit parents
1223 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1224 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1233 // Attempt to do a direct unqualified lookup
1235 t = LookupInterfaceOrClass ("", name, out error);
1243 // Attempt to lookup the class on any of the `using'
1247 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1249 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1256 if (name.IndexOf ('.') > 0)
1259 IAlias alias_value = ns.LookupAlias (name);
1260 if (alias_value != null) {
1261 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1270 // Now check the using clause list
1273 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1274 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1278 if (match != null) {
1280 if (CheckAccessLevel (match)) {
1281 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1294 //Report.Error (246, Location, "Can not find type `"+name+"'");
1299 /// This function is broken and not what you're looking for. It should only
1300 /// be used while the type is still being created since it doesn't use the cache
1301 /// and relies on the filter doing the member name check.
1303 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1304 MemberFilter filter, object criteria);
1307 /// If we have a MemberCache, return it. This property may return null if the
1308 /// class doesn't have a member cache or while it's still being created.
1310 public abstract MemberCache MemberCache {
1314 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1317 TypeBuilder.SetCustomAttribute (cb);
1318 } catch (System.ArgumentException e) {
1319 Report.Warning (-21, a.Location,
1320 "The CharSet named property on StructLayout\n"+
1321 "\tdoes not work correctly on Microsoft.NET\n"+
1322 "\tYou might want to remove the CharSet declaration\n"+
1323 "\tor compile using the Mono runtime instead of the\n"+
1324 "\tMicrosoft .NET runtime\n"+
1325 "\tThe runtime gave the error: " + e);
1330 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1331 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1333 public bool GetClsCompliantAttributeValue ()
1335 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1336 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1338 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1340 if (OptAttributes != null) {
1341 EmitContext ec = new EmitContext (Parent, this, Location,
1342 null, null, ModFlags, false);
1343 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1344 if (cls_attribute != null) {
1345 caching_flags |= Flags.HasClsCompliantAttribute;
1346 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1347 caching_flags |= Flags.ClsCompliantAttributeTrue;
1354 if (Parent == null) {
1355 if (CodeGen.Assembly.IsClsCompliant) {
1356 caching_flags |= Flags.ClsCompliantAttributeTrue;
1362 if (Parent.GetClsCompliantAttributeValue ()) {
1363 caching_flags |= Flags.ClsCompliantAttributeTrue;
1370 // Tests container name for CLS-Compliant name (differing only in case)
1371 // Possible optimalization: search in same namespace only
1372 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1374 int l = Name.Length;
1376 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1377 // Seek through all imported types
1378 foreach (string type_name in TypeManager.all_imported_types.Keys)
1380 if (l != type_name.Length)
1383 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1384 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1385 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1391 // Seek through generated types
1392 foreach (string name in RootContext.Tree.Decls.Keys) {
1393 if (l != name.Length)
1396 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1401 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1402 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1403 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1413 // Extensions for generics
1415 TypeParameter[] type_params;
1416 TypeParameter[] type_param_list;
1418 protected string GetInstantiationName ()
1420 StringBuilder sb = new StringBuilder (Name);
1422 for (int i = 0; i < type_param_list.Length; i++) {
1425 sb.Append (type_param_list [i].Name);
1428 return sb.ToString ();
1431 bool check_type_parameter (ArrayList list, int start, string name)
1433 for (int i = 0; i < start; i++) {
1434 TypeParameter param = (TypeParameter) list [i];
1436 if (param.Name != name)
1439 if (RootContext.WarningLevel >= 3)
1442 "Type parameter `{0}' has same name " +
1443 "as type parameter from outer type `{1}'",
1444 name, Parent.GetInstantiationName ());
1452 TypeParameter[] initialize_type_params ()
1454 if (type_param_list != null)
1455 return type_param_list;
1457 DeclSpace the_parent = Parent;
1458 if (this is GenericMethod)
1462 TypeParameter[] parent_params = null;
1463 if ((the_parent != null) && the_parent.IsGeneric) {
1464 parent_params = the_parent.initialize_type_params ();
1465 start = parent_params != null ? parent_params.Length : 0;
1468 ArrayList list = new ArrayList ();
1469 if (parent_params != null)
1470 list.AddRange (parent_params);
1472 int count = type_params != null ? type_params.Length : 0;
1473 for (int i = 0; i < count; i++) {
1474 TypeParameter param = type_params [i];
1475 check_type_parameter (list, start, param.Name);
1479 type_param_list = new TypeParameter [list.Count];
1480 list.CopyTo (type_param_list, 0);
1481 return type_param_list;
1484 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1487 if (constraints_list != null) {
1489 80, Location, "Contraints are not allowed " +
1490 "on non-generic declarations");
1491 return AdditionResult.Error;
1494 return AdditionResult.Success;
1497 string[] names = MemberName.TypeArguments.GetDeclarations ();
1498 type_params = new TypeParameter [names.Length];
1501 // Register all the names
1503 for (int i = 0; i < type_params.Length; i++) {
1504 string name = names [i];
1506 AdditionResult res = IsValid (name, name);
1508 if (res != AdditionResult.Success)
1511 Constraints constraints = null;
1512 if (constraints_list != null) {
1513 foreach (Constraints constraint in constraints_list) {
1514 if (constraint.TypeParameter == name) {
1515 constraints = constraint;
1521 type_params [i] = new TypeParameter (name, constraints, Location);
1523 DefineName (name, type_params [i]);
1526 return AdditionResult.Success;
1529 public TypeParameter[] TypeParameters {
1532 throw new InvalidOperationException ();
1533 if (type_param_list == null)
1534 initialize_type_params ();
1536 return type_param_list;
1540 protected TypeParameter[] CurrentTypeParameters {
1543 throw new InvalidOperationException ();
1544 if (type_params != null)
1547 return new TypeParameter [0];
1551 public int CountTypeParameters {
1553 return count_type_params;
1557 public TypeParameterExpr LookupGeneric (string name, Location loc)
1562 foreach (TypeParameter type_param in CurrentTypeParameters) {
1563 if (type_param.Name != name)
1566 return new TypeParameterExpr (type_param, loc);
1570 return Parent.LookupGeneric (name, loc);
1575 bool IAlias.IsType {
1576 get { return true; }
1579 string IAlias.Name {
1580 get { return Name; }
1583 TypeExpr IAlias.Type
1586 if (TypeBuilder == null)
1587 throw new InvalidOperationException ();
1589 if (CurrentType != null)
1592 return new TypeExpression (TypeBuilder, Location);
1596 protected override string[] ValidAttributeTargets {
1598 return attribute_targets;
1604 /// This is a readonly list of MemberInfo's.
1606 public class MemberList : IList {
1607 public readonly IList List;
1611 /// Create a new MemberList from the given IList.
1613 public MemberList (IList list)
1618 this.List = new ArrayList ();
1623 /// Concatenate the ILists `first' and `second' to a new MemberList.
1625 public MemberList (IList first, IList second)
1627 ArrayList list = new ArrayList ();
1628 list.AddRange (first);
1629 list.AddRange (second);
1634 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1637 /// Cast the MemberList into a MemberInfo[] array.
1640 /// This is an expensive operation, only use it if it's really necessary.
1642 public static explicit operator MemberInfo [] (MemberList list)
1644 Timer.StartTimer (TimerType.MiscTimer);
1645 MemberInfo [] result = new MemberInfo [list.Count];
1646 list.CopyTo (result, 0);
1647 Timer.StopTimer (TimerType.MiscTimer);
1659 public bool IsSynchronized {
1661 return List.IsSynchronized;
1665 public object SyncRoot {
1667 return List.SyncRoot;
1671 public void CopyTo (Array array, int index)
1673 List.CopyTo (array, index);
1678 public IEnumerator GetEnumerator ()
1680 return List.GetEnumerator ();
1685 public bool IsFixedSize {
1691 public bool IsReadOnly {
1697 object IList.this [int index] {
1699 return List [index];
1703 throw new NotSupportedException ();
1707 // FIXME: try to find out whether we can avoid the cast in this indexer.
1708 public MemberInfo this [int index] {
1710 return (MemberInfo) List [index];
1714 public int Add (object value)
1716 throw new NotSupportedException ();
1719 public void Clear ()
1721 throw new NotSupportedException ();
1724 public bool Contains (object value)
1726 return List.Contains (value);
1729 public int IndexOf (object value)
1731 return List.IndexOf (value);
1734 public void Insert (int index, object value)
1736 throw new NotSupportedException ();
1739 public void Remove (object value)
1741 throw new NotSupportedException ();
1744 public void RemoveAt (int index)
1746 throw new NotSupportedException ();
1751 /// This interface is used to get all members of a class when creating the
1752 /// member cache. It must be implemented by all DeclSpace derivatives which
1753 /// want to support the member cache and by TypeHandle to get caching of
1754 /// non-dynamic types.
1756 public interface IMemberContainer {
1758 /// The name of the IMemberContainer. This is only used for
1759 /// debugging purposes.
1766 /// The type of this IMemberContainer.
1773 /// Returns the IMemberContainer of the parent class or null if this
1774 /// is an interface or TypeManger.object_type.
1775 /// This is used when creating the member cache for a class to get all
1776 /// members from the parent class.
1778 IMemberContainer Parent {
1783 /// Whether this is an interface.
1790 /// Returns all members of this class with the corresponding MemberTypes
1791 /// and BindingFlags.
1794 /// When implementing this method, make sure not to return any inherited
1795 /// members and check the MemberTypes and BindingFlags properly.
1796 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1797 /// get the BindingFlags (static/non-static,public/non-public) in the
1798 /// MemberInfo class, but the cache needs this information. That's why
1799 /// this method is called multiple times with different BindingFlags.
1801 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1804 /// Return the container's member cache.
1806 MemberCache MemberCache {
1812 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1813 /// member lookups. It has a member name based hash table; it maps each member
1814 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1815 /// and the BindingFlags that were initially used to get it. The cache contains
1816 /// all members of the current class and all inherited members. If this cache is
1817 /// for an interface types, it also contains all inherited members.
1819 /// There are two ways to get a MemberCache:
1820 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1821 /// use the DeclSpace.MemberCache property.
1822 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1823 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1825 public class MemberCache {
1826 public readonly IMemberContainer Container;
1827 protected Hashtable member_hash;
1828 protected Hashtable method_hash;
1831 /// Create a new MemberCache for the given IMemberContainer `container'.
1833 public MemberCache (IMemberContainer container)
1835 this.Container = container;
1837 Timer.IncrementCounter (CounterType.MemberCache);
1838 Timer.StartTimer (TimerType.CacheInit);
1842 // If we have a parent class (we have a parent class unless we're
1843 // TypeManager.object_type), we deep-copy its MemberCache here.
1844 if (Container.IsInterface) {
1847 if (Container.Parent != null)
1848 parent = Container.Parent.MemberCache;
1850 parent = TypeHandle.ObjectType.MemberCache;
1851 member_hash = SetupCacheForInterface (parent);
1852 } else if (Container.Parent != null)
1853 member_hash = SetupCache (Container.Parent.MemberCache);
1855 member_hash = new Hashtable ();
1857 // If this is neither a dynamic type nor an interface, create a special
1858 // method cache with all declared and inherited methods.
1859 Type type = container.Type;
1860 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1861 method_hash = new Hashtable ();
1865 // Add all members from the current class.
1866 AddMembers (Container);
1868 Timer.StopTimer (TimerType.CacheInit);
1872 /// Bootstrap this member cache by doing a deep-copy of our parent.
1874 Hashtable SetupCache (MemberCache parent)
1876 Hashtable hash = new Hashtable ();
1878 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1879 while (it.MoveNext ()) {
1880 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1888 /// Add the contents of `new_hash' to `hash'.
1890 void AddHashtable (Hashtable hash, MemberCache cache)
1892 Hashtable new_hash = cache.member_hash;
1893 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1894 while (it.MoveNext ()) {
1895 ArrayList list = (ArrayList) hash [it.Key];
1897 hash [it.Key] = list = new ArrayList ();
1899 foreach (CacheEntry entry in (ArrayList) it.Value) {
1900 if (entry.Container != cache.Container)
1908 /// Bootstrap the member cache for an interface type.
1909 /// Type.GetMembers() won't return any inherited members for interface types,
1910 /// so we need to do this manually. Interfaces also inherit from System.Object.
1912 Hashtable SetupCacheForInterface (MemberCache parent)
1914 Hashtable hash = SetupCache (parent);
1915 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1917 foreach (Type itype in ifaces) {
1918 IMemberContainer iface_container =
1919 TypeManager.LookupMemberContainer (itype);
1921 MemberCache iface_cache = iface_container.MemberCache;
1923 AddHashtable (hash, iface_cache);
1930 /// Add all members from class `container' to the cache.
1932 void AddMembers (IMemberContainer container)
1934 // We need to call AddMembers() with a single member type at a time
1935 // to get the member type part of CacheEntry.EntryType right.
1936 AddMembers (MemberTypes.Constructor, container);
1937 AddMembers (MemberTypes.Field, container);
1938 AddMembers (MemberTypes.Method, container);
1939 AddMembers (MemberTypes.Property, container);
1940 AddMembers (MemberTypes.Event, container);
1941 // Nested types are returned by both Static and Instance searches.
1942 AddMembers (MemberTypes.NestedType,
1943 BindingFlags.Static | BindingFlags.Public, container);
1944 AddMembers (MemberTypes.NestedType,
1945 BindingFlags.Static | BindingFlags.NonPublic, container);
1948 void AddMembers (MemberTypes mt, IMemberContainer container)
1950 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1951 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1952 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1953 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1957 /// Add all members from class `container' with the requested MemberTypes and
1958 /// BindingFlags to the cache. This method is called multiple times with different
1959 /// MemberTypes and BindingFlags.
1961 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1963 MemberList members = container.GetMembers (mt, bf);
1965 foreach (MemberInfo member in members) {
1966 string name = member.Name;
1968 int pos = name.IndexOf ('<');
1970 name = name.Substring (0, pos);
1972 // We use a name-based hash table of ArrayList's.
1973 ArrayList list = (ArrayList) member_hash [name];
1975 list = new ArrayList ();
1976 member_hash.Add (name, list);
1979 // When this method is called for the current class, the list will
1980 // already contain all inherited members from our parent classes.
1981 // We cannot add new members in front of the list since this'd be an
1982 // expensive operation, that's why the list is sorted in reverse order
1983 // (ie. members from the current class are coming last).
1984 list.Add (new CacheEntry (container, member, mt, bf));
1989 /// Add all declared and inherited methods from class `type' to the method cache.
1991 void AddMethods (Type type)
1993 AddMethods (BindingFlags.Static | BindingFlags.Public |
1994 BindingFlags.FlattenHierarchy, type);
1995 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1996 BindingFlags.FlattenHierarchy, type);
1997 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1998 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
2001 void AddMethods (BindingFlags bf, Type type)
2003 MemberInfo [] members = type.GetMethods (bf);
2005 Array.Reverse (members);
2007 foreach (MethodBase member in members) {
2008 string name = member.Name;
2010 // We use a name-based hash table of ArrayList's.
2011 ArrayList list = (ArrayList) method_hash [name];
2013 list = new ArrayList ();
2014 method_hash.Add (name, list);
2017 // Unfortunately, the elements returned by Type.GetMethods() aren't
2018 // sorted so we need to do this check for every member.
2019 BindingFlags new_bf = bf;
2020 if (member.DeclaringType == type)
2021 new_bf |= BindingFlags.DeclaredOnly;
2023 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
2028 /// Compute and return a appropriate `EntryType' magic number for the given
2029 /// MemberTypes and BindingFlags.
2031 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
2033 EntryType type = EntryType.None;
2035 if ((mt & MemberTypes.Constructor) != 0)
2036 type |= EntryType.Constructor;
2037 if ((mt & MemberTypes.Event) != 0)
2038 type |= EntryType.Event;
2039 if ((mt & MemberTypes.Field) != 0)
2040 type |= EntryType.Field;
2041 if ((mt & MemberTypes.Method) != 0)
2042 type |= EntryType.Method;
2043 if ((mt & MemberTypes.Property) != 0)
2044 type |= EntryType.Property;
2045 // Nested types are returned by static and instance searches.
2046 if ((mt & MemberTypes.NestedType) != 0)
2047 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
2049 if ((bf & BindingFlags.Instance) != 0)
2050 type |= EntryType.Instance;
2051 if ((bf & BindingFlags.Static) != 0)
2052 type |= EntryType.Static;
2053 if ((bf & BindingFlags.Public) != 0)
2054 type |= EntryType.Public;
2055 if ((bf & BindingFlags.NonPublic) != 0)
2056 type |= EntryType.NonPublic;
2057 if ((bf & BindingFlags.DeclaredOnly) != 0)
2058 type |= EntryType.Declared;
2064 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2065 /// denote multiple member types. Returns true if the given flags value denotes a
2066 /// single member types.
2068 public static bool IsSingleMemberType (MemberTypes mt)
2071 case MemberTypes.Constructor:
2072 case MemberTypes.Event:
2073 case MemberTypes.Field:
2074 case MemberTypes.Method:
2075 case MemberTypes.Property:
2076 case MemberTypes.NestedType:
2085 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2086 /// number to speed up the searching process.
2089 protected enum EntryType {
2094 MaskStatic = Instance|Static,
2098 MaskProtection = Public|NonPublic,
2102 Constructor = 0x020,
2109 MaskType = Constructor|Event|Field|Method|Property|NestedType
2112 protected struct CacheEntry {
2113 public readonly IMemberContainer Container;
2114 public readonly EntryType EntryType;
2115 public readonly MemberInfo Member;
2117 public CacheEntry (IMemberContainer container, MemberInfo member,
2118 MemberTypes mt, BindingFlags bf)
2120 this.Container = container;
2121 this.Member = member;
2122 this.EntryType = GetEntryType (mt, bf);
2127 /// This is called each time we're walking up one level in the class hierarchy
2128 /// and checks whether we can abort the search since we've already found what
2129 /// we were looking for.
2131 protected bool DoneSearching (ArrayList list)
2134 // We've found exactly one member in the current class and it's not
2135 // a method or constructor.
2137 if (list.Count == 1 && !(list [0] is MethodBase))
2141 // Multiple properties: we query those just to find out the indexer
2144 if ((list.Count > 0) && (list [0] is PropertyInfo))
2151 /// Looks up members with name `name'. If you provide an optional
2152 /// filter function, it'll only be called with members matching the
2153 /// requested member name.
2155 /// This method will try to use the cache to do the lookup if possible.
2157 /// Unlike other FindMembers implementations, this method will always
2158 /// check all inherited members - even when called on an interface type.
2160 /// If you know that you're only looking for methods, you should use
2161 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2162 /// When doing a method-only search, it'll try to use a special method
2163 /// cache (unless it's a dynamic type or an interface) and the returned
2164 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2165 /// The lookup process will automatically restart itself in method-only
2166 /// search mode if it discovers that it's about to return methods.
2168 ArrayList global = new ArrayList ();
2169 bool using_global = false;
2171 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2173 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2174 MemberFilter filter, object criteria)
2177 throw new Exception ();
2179 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2180 bool method_search = mt == MemberTypes.Method;
2181 // If we have a method cache and we aren't already doing a method-only search,
2182 // then we restart a method search if the first match is a method.
2183 bool do_method_search = !method_search && (method_hash != null);
2185 ArrayList applicable;
2187 // If this is a method-only search, we try to use the method cache if
2188 // possible; a lookup in the method cache will return a MemberInfo with
2189 // the correct ReflectedType for inherited methods.
2191 if (method_search && (method_hash != null))
2192 applicable = (ArrayList) method_hash [name];
2194 applicable = (ArrayList) member_hash [name];
2196 if (applicable == null)
2197 return emptyMemberInfo;
2200 // 32 slots gives 53 rss/54 size
2201 // 2/4 slots gives 55 rss
2203 // Strange: from 25,000 calls, only 1,800
2204 // are above 2. Why does this impact it?
2207 using_global = true;
2209 Timer.StartTimer (TimerType.CachedLookup);
2211 EntryType type = GetEntryType (mt, bf);
2213 IMemberContainer current = Container;
2216 // `applicable' is a list of all members with the given member name `name'
2217 // in the current class and all its parent classes. The list is sorted in
2218 // reverse order due to the way how the cache is initialy created (to speed
2219 // things up, we're doing a deep-copy of our parent).
2221 for (int i = applicable.Count-1; i >= 0; i--) {
2222 CacheEntry entry = (CacheEntry) applicable [i];
2224 // This happens each time we're walking one level up in the class
2225 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2226 // the first time this happens (this may already happen in the first
2227 // iteration of this loop if there are no members with the name we're
2228 // looking for in the current class).
2229 if (entry.Container != current) {
2230 if (declared_only || DoneSearching (global))
2233 current = entry.Container;
2236 // Is the member of the correct type ?
2237 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2240 // Is the member static/non-static ?
2241 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2244 // Apply the filter to it.
2245 if (filter (entry.Member, criteria)) {
2246 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2247 do_method_search = false;
2248 global.Add (entry.Member);
2252 Timer.StopTimer (TimerType.CachedLookup);
2254 // If we have a method cache and we aren't already doing a method-only
2255 // search, we restart in method-only search mode if the first match is
2256 // a method. This ensures that we return a MemberInfo with the correct
2257 // ReflectedType for inherited methods.
2258 if (do_method_search && (global.Count > 0)){
2259 using_global = false;
2261 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2264 using_global = false;
2265 MemberInfo [] copy = new MemberInfo [global.Count];
2266 global.CopyTo (copy);
2271 // This finds the method or property for us to override. invocationType is the type where
2272 // the override is going to be declared, name is the name of the method/property, and
2273 // paramTypes is the parameters, if any to the method or property
2275 // Because the MemberCache holds members from this class and all the base classes,
2276 // we can avoid tons of reflection stuff.
2278 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2280 ArrayList applicable;
2281 if (method_hash != null && !is_property)
2282 applicable = (ArrayList) method_hash [name];
2284 applicable = (ArrayList) member_hash [name];
2286 if (applicable == null)
2289 // Walk the chain of methods, starting from the top.
2291 for (int i = applicable.Count - 1; i >= 0; i--) {
2292 CacheEntry entry = (CacheEntry) applicable [i];
2294 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2297 PropertyInfo pi = null;
2298 MethodInfo mi = null;
2299 FieldInfo fi = null;
2300 Type [] cmpAttrs = null;
2303 if ((entry.EntryType & EntryType.Field) != 0) {
2304 fi = (FieldInfo)entry.Member;
2306 // TODO: For this case we ignore member type
2307 //fb = TypeManager.GetField (fi);
2308 //cmpAttrs = new Type[] { fb.MemberType };
2310 pi = (PropertyInfo) entry.Member;
2311 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2314 mi = (MethodInfo) entry.Member;
2315 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2319 // TODO: Almost duplicate !
2321 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2322 case FieldAttributes.Private:
2324 // A private method is Ok if we are a nested subtype.
2325 // The spec actually is not very clear about this, see bug 52458.
2327 if (invocationType != entry.Container.Type &
2328 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2332 case FieldAttributes.FamANDAssem:
2333 case FieldAttributes.Assembly:
2335 // Check for assembly methods
2337 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2341 return entry.Member;
2345 // Check the arguments
2347 if (cmpAttrs.Length != paramTypes.Length)
2350 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2351 if (!paramTypes [j].Equals (cmpAttrs [j]))
2356 // get one of the methods because this has the visibility info.
2359 mi = pi.GetGetMethod (true);
2361 mi = pi.GetSetMethod (true);
2367 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2368 case MethodAttributes.Private:
2370 // A private method is Ok if we are a nested subtype.
2371 // The spec actually is not very clear about this, see bug 52458.
2373 if (invocationType == entry.Container.Type ||
2374 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2375 return entry.Member;
2378 case MethodAttributes.FamANDAssem:
2379 case MethodAttributes.Assembly:
2381 // Check for assembly methods
2383 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2384 return entry.Member;
2389 // A protected method is ok, because we are overriding.
2390 // public is always ok.
2392 return entry.Member;