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 public Expression GetTypeExpression (Location loc)
129 Expression lexpr = Left.GetTypeExpression (loc);
131 return new MemberAccess (lexpr, Name, TypeArguments, loc);
133 if (TypeArguments != null)
134 return new ConstructedType (Name, TypeArguments, loc);
136 return new SimpleName (Name, loc);
140 public string Basename {
142 if (TypeArguments != null)
143 return MakeName (Name, TypeArguments);
149 public override string ToString ()
152 if (TypeArguments != null)
153 full_name = Name + "<" + TypeArguments + ">";
158 return Left + "." + full_name;
165 /// Base representation for members. This is used to keep track
166 /// of Name, Location and Modifier flags, and handling Attributes.
168 public abstract class MemberCore : Attributable {
174 public readonly MemberName MemberName;
177 /// Modifier flags that the user specified in the source code
182 /// Location where this declaration happens
184 public readonly Location Location;
188 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
189 Obsolete = 1 << 1, // Type has obsolete attribute
190 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
191 ClsCompliant = 1 << 3, // Type is CLS Compliant
192 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
193 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
194 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
195 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
196 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
197 Excluded = 1 << 9 // Method is conditional
202 /// MemberCore flags at first detected then cached
204 protected Flags caching_flags;
206 public MemberCore (MemberName name, Attributes attrs, Location loc)
209 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
212 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
216 /// Tests presence of ObsoleteAttribute and report proper error
218 protected void CheckUsageOfObsoleteAttribute (Type type)
223 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
224 if (obsolete_attr == null)
227 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
230 public abstract bool Define (TypeContainer parent);
233 // Returns full member name for error message
235 public virtual string GetSignatureForError ()
241 /// Base Emit method. This is also entry point for CLS-Compliant verification.
243 public virtual void Emit (TypeContainer container)
245 VerifyObsoleteAttribute ();
247 if (!RootContext.VerifyClsCompliance)
250 VerifyClsCompliance (container);
254 // Whehter is it ok to use an unsafe pointer in this type container
256 public bool UnsafeOK (DeclSpace parent)
259 // First check if this MemberCore modifier flags has unsafe set
261 if ((ModFlags & Modifiers.UNSAFE) != 0)
264 if (parent.UnsafeContext)
267 Expression.UnsafeError (Location);
272 /// Returns instance of ObsoleteAttribute for this MemberCore
274 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
276 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
277 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
281 caching_flags &= ~Flags.Obsolete_Undetected;
283 if (OptAttributes == null)
286 // TODO: remove this allocation
287 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
288 null, null, ds.ModFlags, false);
290 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
291 if (obsolete_attr == null)
294 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
295 if (obsolete == null)
298 caching_flags |= Flags.Obsolete;
303 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
305 public override bool IsClsCompliaceRequired (DeclSpace container)
307 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
308 return (caching_flags & Flags.ClsCompliant) != 0;
310 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
311 caching_flags &= ~Flags.ClsCompliance_Undetected;
312 caching_flags |= Flags.ClsCompliant;
316 caching_flags &= ~Flags.ClsCompliance_Undetected;
321 /// Returns true when MemberCore is exposed from assembly.
323 protected bool IsExposedFromAssembly (DeclSpace ds)
325 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
328 DeclSpace parentContainer = ds;
329 while (parentContainer != null && parentContainer.ModFlags != 0) {
330 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
332 parentContainer = parentContainer.Parent;
338 /// Resolve CLSCompliantAttribute value or gets cached value.
340 bool GetClsCompliantAttributeValue (DeclSpace ds)
342 if (OptAttributes != null) {
343 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
344 null, null, ds.ModFlags, false);
345 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
346 if (cls_attribute != null) {
347 caching_flags |= Flags.HasClsCompliantAttribute;
348 return cls_attribute.GetClsCompliantAttributeValue (ds);
351 return ds.GetClsCompliantAttributeValue ();
355 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
357 protected bool HasClsCompliantAttribute {
359 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
364 /// This method is used to testing error 3005 (Method or parameter name collision).
366 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
369 /// Common helper method for identifier and parameters CLS-Compliant testing.
370 /// When return false error 3005 is reported. True means no violation.
371 /// And error 3006 tests are peformed here because of speed.
373 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
375 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
376 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
381 bool error3006 = false;
382 for (int i = 0; i < ml.Count; ++i) {
383 MemberInfo mi = ml [i];
384 if (name == mi.Name) {
385 MethodBase method = mi as MethodBase;
386 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
389 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
397 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
398 // because BindingFlags.Public returns internal types too
399 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
401 // Type is external, we can get attribute directly
402 if (temp_ds == null) {
403 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
404 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
407 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
409 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
410 if (!mc.IsClsCompliaceRequired (ds))
414 for (int ii = 0; ii < ml.Count; ++ii) {
418 Report.SymbolRelatedToPreviousError (mi);
422 Report.Error_T (3006, Location, GetSignatureForError ());
431 /// The main virtual method for CLS-Compliant verifications.
432 /// The method returns true if member is CLS-Compliant and false if member is not
433 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
434 /// and add their extra verifications.
436 protected virtual bool VerifyClsCompliance (DeclSpace ds)
438 if (!IsClsCompliaceRequired (ds)) {
439 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
440 Report.Warning_T (3019, Location, GetSignatureForError ());
445 if (!CodeGen.Assembly.IsClsCompliant) {
446 if (HasClsCompliantAttribute) {
447 Report.Error_T (3014, Location, GetSignatureForError ());
451 int index = Name.LastIndexOf ('.');
452 if (Name [index > 0 ? index + 1 : 0] == '_') {
453 Report.Error_T (3008, Location, GetSignatureForError () );
456 if (!IsIdentifierClsCompliant (ds)) {
457 Report.Error_T (3005, Location, GetSignatureForError ());
463 protected abstract void VerifyObsoleteAttribute ();
468 /// Base class for structs, classes, enumerations and interfaces.
471 /// They all create new declaration spaces. This
472 /// provides the common foundation for managing those name
475 public abstract class DeclSpace : MemberCore, IAlias {
477 /// This points to the actual definition that is being
478 /// created with System.Reflection.Emit
480 public TypeBuilder TypeBuilder;
483 /// If we are a generic type, this is the type we are
484 /// currently defining. We need to lookup members on this
485 /// instead of the TypeBuilder.
487 public TypeExpr CurrentType;
490 // This is the namespace in which this typecontainer
491 // was declared. We use this to resolve names.
493 public NamespaceEntry NamespaceEntry;
495 public Hashtable Cache = new Hashtable ();
497 public string Basename;
500 /// defined_names is used for toplevel objects
502 protected Hashtable defined_names;
504 readonly bool is_generic;
505 readonly int count_type_params;
508 // Whether we are Generic
510 public bool IsGeneric {
514 else if (parent != null)
515 return parent.IsGeneric;
521 TypeContainer parent;
523 static string[] attribute_targets = new string [] { "type" };
525 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
526 Attributes attrs, Location l)
527 : base (name, attrs, l)
530 Basename = name.Name;
531 defined_names = new Hashtable ();
532 if (name.TypeArguments != null) {
534 count_type_params = name.TypeArguments.Count;
537 count_type_params += parent.count_type_params;
538 this.parent = parent;
541 public void RecordDecl ()
543 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
544 NamespaceEntry.DefineName (MemberName.Basename, this);
548 /// The result value from adding an declaration into
549 /// a struct or a class
551 public enum AdditionResult {
553 /// The declaration has been successfully
554 /// added to the declation space.
559 /// The symbol has already been defined.
564 /// Returned if the declation being added to the
565 /// name space clashes with its container name.
567 /// The only exceptions for this are constructors
568 /// and static constructors
573 /// Returned if a constructor was created (because syntactically
574 /// it looked like a constructor) but was not (because the name
575 /// of the method is not the same as the container class
580 /// This is only used by static constructors to emit the
581 /// error 111, but this error for other things really
582 /// happens at another level for other functions.
587 /// Some other error.
593 /// Returns a status code based purely on the name
594 /// of the member being added
596 protected AdditionResult IsValid (string basename, string name)
598 if (basename == Basename)
599 return AdditionResult.EnclosingClash;
601 if (defined_names.Contains (name))
602 return AdditionResult.NameExists;
604 return AdditionResult.Success;
607 public static int length;
608 public static int small;
611 /// Introduce @name into this declaration space and
612 /// associates it with the object @o. Note that for
613 /// methods this will just point to the first method. o
615 public void DefineName (string name, object o)
617 defined_names.Add (name, o);
620 int p = name.LastIndexOf ('.');
628 /// Returns the object associated with a given name in the declaration
629 /// space. This is the inverse operation of `DefineName'
631 public object GetDefinition (string name)
633 return defined_names [name];
636 bool in_transit = false;
639 /// This function is used to catch recursive definitions
642 public bool InTransit {
652 public TypeContainer Parent {
659 /// Looks up the alias for the name
661 public IAlias LookupAlias (string name)
663 if (NamespaceEntry != null)
664 return NamespaceEntry.LookupAlias (name);
670 // root_types contains all the types. All TopLevel types
671 // hence have a parent that points to `root_types', that is
672 // why there is a non-obvious test down here.
674 public bool IsTopLevel {
677 if (parent.parent == null)
684 public virtual void CloseType ()
686 if ((caching_flags & Flags.CloseTypeCreated) == 0){
688 TypeBuilder.CreateType ();
691 // The try/catch is needed because
692 // nested enumerations fail to load when they
695 // Even if this is the right order (enumerations
696 // declared after types).
698 // Note that this still creates the type and
699 // it is possible to save it
701 caching_flags |= Flags.CloseTypeCreated;
706 /// Should be overriten by the appropriate declaration space
708 public abstract TypeBuilder DefineType ();
711 /// Define all members, but don't apply any attributes or do anything which may
712 /// access not-yet-defined classes. This method also creates the MemberCache.
714 public abstract bool DefineMembers (TypeContainer parent);
717 // Whether this is an `unsafe context'
719 public bool UnsafeContext {
721 if ((ModFlags & Modifiers.UNSAFE) != 0)
724 return parent.UnsafeContext;
729 public static string MakeFQN (string nsn, string name)
733 return String.Concat (nsn, ".", name);
736 EmitContext type_resolve_ec;
737 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
739 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
740 type_resolve_ec.ResolvingTypeTree = true;
742 return type_resolve_ec;
746 // Looks up the type, as parsed into the expression `e'
748 public Type ResolveType (Expression e, bool silent, Location loc)
750 TypeExpr d = ResolveTypeExpr (e, silent, loc);
754 return ResolveType (d, loc);
757 public Type ResolveType (TypeExpr d, Location loc)
759 if (!d.CheckAccessLevel (this)) {
760 Report.Error_T (122, loc, d.Name);
764 Type t = d.ResolveType (type_resolve_ec);
768 TypeContainer tc = TypeManager.LookupTypeContainer (t);
769 if ((tc != null) && tc.IsGeneric) {
771 int tnum = TypeManager.GetNumberOfTypeArguments (t);
772 Report.Error (305, loc,
773 "Using the generic type `{0}' " +
774 "requires {1} type arguments",
775 TypeManager.GetFullName (t), tnum);
779 ConstructedType ctype = new ConstructedType (
780 t, TypeParameters, loc);
782 t = ctype.ResolveType (type_resolve_ec);
789 // Resolves the expression `e' for a type, and will recursively define
792 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
794 if (type_resolve_ec == null)
795 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
796 type_resolve_ec.loc = loc;
797 if (this is GenericMethod)
798 type_resolve_ec.ContainerType = Parent.TypeBuilder;
800 type_resolve_ec.ContainerType = TypeBuilder;
802 int errors = Report.Errors;
804 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
806 if ((d != null) && (d.eclass == ExprClass.Type))
809 if (silent || (Report.Errors != errors))
812 if (e is SimpleName){
813 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
814 d = s.ResolveAsTypeTerminal (type_resolve_ec);
816 if ((d == null) || (d.Type == null)) {
817 Report.Error (246, loc, "Cannot find type `{0}'", e);
821 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
824 Report.Error (308, loc,
825 "The non-generic type `{0}' cannot " +
826 "be used with type arguments.",
827 TypeManager.CSharpName (d.Type));
831 Report.Error (305, loc,
832 "Using the generic type `{0}' " +
833 "requires {1} type arguments",
834 TypeManager.GetFullName (d.Type), num_args);
838 Report.Error (246, loc, "Cannot find type `{0}'", e);
842 public bool CheckAccessLevel (Type check_type)
845 if (this is GenericMethod)
846 tb = Parent.TypeBuilder;
850 if (check_type.IsGenericInstance)
851 check_type = check_type.GetGenericTypeDefinition ();
853 if (check_type == tb)
856 if (check_type.IsGenericParameter)
857 return true; // FIXME
859 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
862 // Broken Microsoft runtime, return public for arrays, no matter what
863 // the accessibility is for their underlying class, and they return
864 // NonPublic visibility for pointers
866 if (check_type.IsArray || check_type.IsPointer)
867 return CheckAccessLevel (TypeManager.GetElementType (check_type));
870 case TypeAttributes.Public:
873 case TypeAttributes.NotPublic:
875 // In same cases is null.
876 if (TypeBuilder == null)
880 // This test should probably use the declaringtype.
882 return check_type.Assembly == TypeBuilder.Assembly;
884 case TypeAttributes.NestedPublic:
887 case TypeAttributes.NestedPrivate:
888 string check_type_name = check_type.FullName;
889 string type_name = CurrentType != null ?
890 CurrentType.Name : tb.FullName;
892 int cio = check_type_name.LastIndexOf ('+');
893 string container = check_type_name.Substring (0, cio);
896 // Check if the check_type is a nested class of the current type
898 if (check_type_name.StartsWith (type_name + "+")){
902 if (type_name.StartsWith (container)){
908 case TypeAttributes.NestedFamily:
910 // Only accessible to methods in current type or any subtypes
912 return FamilyAccessible (tb, check_type);
914 case TypeAttributes.NestedFamANDAssem:
915 return (check_type.Assembly == tb.Assembly) &&
916 FamilyAccessible (tb, check_type);
918 case TypeAttributes.NestedFamORAssem:
919 return (check_type.Assembly == tb.Assembly) ||
920 FamilyAccessible (tb, check_type);
922 case TypeAttributes.NestedAssembly:
923 return check_type.Assembly == tb.Assembly;
926 Console.WriteLine ("HERE: " + check_attr);
931 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
933 Type declaring = check_type.DeclaringType;
934 if (tb.IsSubclassOf (declaring))
937 string check_type_name = check_type.FullName;
939 int cio = check_type_name.LastIndexOf ('+');
940 string container = check_type_name.Substring (0, cio);
943 // Check if the check_type is a nested class of the current type
945 if (check_type_name.StartsWith (container + "+"))
951 // Access level of a type.
953 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
954 // Public Assembly Protected
955 Protected = (0 << 0) | (0 << 1) | (X << 2),
956 Public = (X << 0) | (X << 1) | (X << 2),
957 Private = (0 << 0) | (0 << 1) | (0 << 2),
958 Internal = (0 << 0) | (X << 1) | (0 << 2),
959 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
962 static AccessLevel GetAccessLevelFromModifiers (int flags)
964 if ((flags & Modifiers.INTERNAL) != 0) {
966 if ((flags & Modifiers.PROTECTED) != 0)
967 return AccessLevel.ProtectedOrInternal;
969 return AccessLevel.Internal;
971 } else if ((flags & Modifiers.PROTECTED) != 0)
972 return AccessLevel.Protected;
973 else if ((flags & Modifiers.PRIVATE) != 0)
974 return AccessLevel.Private;
976 return AccessLevel.Public;
979 // What is the effective access level of this?
981 AccessLevel EffectiveAccessLevel {
983 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
984 if (!IsTopLevel && (Parent != null))
985 return myAccess & Parent.EffectiveAccessLevel;
990 // Return the access level for type `t'
991 static AccessLevel TypeEffectiveAccessLevel (Type t)
994 return AccessLevel.Public;
995 if (t.IsNestedPrivate)
996 return AccessLevel.Private;
998 return AccessLevel.Internal;
1000 // By now, it must be nested
1001 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1003 if (t.IsNestedPublic)
1005 if (t.IsNestedAssembly)
1006 return parentLevel & AccessLevel.Internal;
1007 if (t.IsNestedFamily)
1008 return parentLevel & AccessLevel.Protected;
1009 if (t.IsNestedFamORAssem)
1010 return parentLevel & AccessLevel.ProtectedOrInternal;
1011 if (t.IsNestedFamANDAssem)
1012 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1014 // nested private is taken care of
1016 throw new Exception ("I give up, what are you?");
1020 // This answers `is the type P, as accessible as a member M which has the
1021 // accessability @flags which is declared as a nested member of the type T, this declspace'
1023 public bool AsAccessible (Type p, int flags)
1025 if (p.IsGenericParameter)
1026 return true; // FIXME
1029 // 1) if M is private, its accessability is the same as this declspace.
1030 // we already know that P is accessible to T before this method, so we
1034 if ((flags & Modifiers.PRIVATE) != 0)
1037 while (p.IsArray || p.IsPointer || p.IsByRef)
1038 p = TypeManager.GetElementType (p);
1040 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1041 AccessLevel mAccess = this.EffectiveAccessLevel &
1042 GetAccessLevelFromModifiers (flags);
1044 // for every place from which we can access M, we must
1045 // be able to access P as well. So, we want
1046 // For every bit in M and P, M_i -> P_1 == true
1047 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1049 return ~ (~ mAccess | pAccess) == 0;
1052 static DoubleHash dh = new DoubleHash (1000);
1054 Type DefineTypeAndParents (DeclSpace tc)
1056 DeclSpace container = tc.Parent;
1058 if (container.TypeBuilder == null && container.Name != "")
1059 DefineTypeAndParents (container);
1061 return tc.DefineType ();
1064 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1072 if (dh.Lookup (ns, name, out r))
1076 if (Namespace.IsNamespace (ns)){
1077 string fullname = (ns != "") ? ns + "." + name : name;
1078 t = TypeManager.LookupType (fullname);
1082 t = TypeManager.LookupType (name);
1086 dh.Insert (ns, name, t);
1091 // In case we are fed a composite name, normalize it.
1093 int p = name.LastIndexOf ('.');
1095 ns = MakeFQN (ns, name.Substring (0, p));
1096 name = name.Substring (p+1);
1099 parent = RootContext.Tree.LookupByNamespace (ns, name);
1100 if (parent == null) {
1101 dh.Insert (ns, name, null);
1105 t = DefineTypeAndParents (parent);
1111 dh.Insert (ns, name, t);
1115 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1117 Report.Error (104, loc,
1118 "`{0}' is an ambiguous reference ({1} or {2})",
1122 public Type FindNestedType (Location loc, string name,
1123 out DeclSpace containing_ds)
1128 containing_ds = this;
1129 while (containing_ds != null){
1130 Type container_type = containing_ds.TypeBuilder;
1131 Type current_type = container_type;
1133 while (current_type != null && current_type != TypeManager.object_type) {
1134 string pre = current_type.FullName;
1136 t = LookupInterfaceOrClass (pre, name, out error);
1140 if ((t != null) && containing_ds.CheckAccessLevel (t))
1143 current_type = current_type.BaseType;
1145 containing_ds = containing_ds.Parent;
1152 /// GetType is used to resolve type names at the DeclSpace level.
1153 /// Use this to lookup class/struct bases, interface bases or
1154 /// delegate type references
1158 /// Contrast this to LookupType which is used inside method bodies to
1159 /// lookup types that have already been defined. GetType is used
1160 /// during the tree resolution process and potentially define
1161 /// recursively the type
1163 public Type FindType (Location loc, string name)
1169 // For the case the type we are looking for is nested within this one
1170 // or is in any base class
1172 DeclSpace containing_ds = this;
1174 while (containing_ds != null){
1175 Type container_type = containing_ds.TypeBuilder;
1176 Type current_type = container_type;
1178 while (current_type != null && current_type != TypeManager.object_type) {
1179 string pre = current_type.FullName;
1181 t = LookupInterfaceOrClass (pre, name, out error);
1185 if ((t != null) && containing_ds.CheckAccessLevel (t))
1188 current_type = current_type.BaseType;
1190 containing_ds = containing_ds.Parent;
1194 // Attempt to lookup the class on our namespace and all it's implicit parents
1196 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1197 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1206 // Attempt to do a direct unqualified lookup
1208 t = LookupInterfaceOrClass ("", name, out error);
1216 // Attempt to lookup the class on any of the `using'
1220 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1222 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1229 if (name.IndexOf ('.') > 0)
1232 IAlias alias_value = ns.LookupAlias (name);
1233 if (alias_value != null) {
1234 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1243 // Now check the using clause list
1246 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1247 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1251 if (match != null) {
1253 if (CheckAccessLevel (match)) {
1254 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1267 //Report.Error (246, Location, "Can not find type `"+name+"'");
1272 /// This function is broken and not what you're looking for. It should only
1273 /// be used while the type is still being created since it doesn't use the cache
1274 /// and relies on the filter doing the member name check.
1276 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1277 MemberFilter filter, object criteria);
1280 /// If we have a MemberCache, return it. This property may return null if the
1281 /// class doesn't have a member cache or while it's still being created.
1283 public abstract MemberCache MemberCache {
1287 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1290 TypeBuilder.SetCustomAttribute (cb);
1291 } catch (System.ArgumentException e) {
1292 Report.Warning (-21, a.Location,
1293 "The CharSet named property on StructLayout\n"+
1294 "\tdoes not work correctly on Microsoft.NET\n"+
1295 "\tYou might want to remove the CharSet declaration\n"+
1296 "\tor compile using the Mono runtime instead of the\n"+
1297 "\tMicrosoft .NET runtime\n"+
1298 "\tThe runtime gave the error: " + e);
1303 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1304 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1306 public bool GetClsCompliantAttributeValue ()
1308 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1309 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1311 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1313 if (OptAttributes != null) {
1314 EmitContext ec = new EmitContext (parent, this, Location,
1315 null, null, ModFlags, false);
1316 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1317 if (cls_attribute != null) {
1318 caching_flags |= Flags.HasClsCompliantAttribute;
1319 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1320 caching_flags |= Flags.ClsCompliantAttributeTrue;
1327 if (parent == null) {
1328 if (CodeGen.Assembly.IsClsCompliant) {
1329 caching_flags |= Flags.ClsCompliantAttributeTrue;
1335 if (parent.GetClsCompliantAttributeValue ()) {
1336 caching_flags |= Flags.ClsCompliantAttributeTrue;
1343 // Tests container name for CLS-Compliant name (differing only in case)
1344 // Possible optimalization: search in same namespace only
1345 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1347 int l = Name.Length;
1349 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1350 // Seek through all imported types
1351 foreach (string type_name in TypeManager.all_imported_types.Keys)
1353 if (l != type_name.Length)
1356 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1357 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1358 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1364 // Seek through generated types
1365 foreach (string name in RootContext.Tree.Decls.Keys) {
1366 if (l != name.Length)
1369 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1374 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1375 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1376 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1386 // Extensions for generics
1388 TypeParameter[] type_params;
1389 TypeParameter[] type_param_list;
1391 protected string GetInstantiationName ()
1393 StringBuilder sb = new StringBuilder (Name);
1395 for (int i = 0; i < type_param_list.Length; i++) {
1398 sb.Append (type_param_list [i].Name);
1401 return sb.ToString ();
1404 bool check_type_parameter (ArrayList list, int start, string name)
1406 for (int i = 0; i < start; i++) {
1407 TypeParameter param = (TypeParameter) list [i];
1409 if (param.Name != name)
1412 if (RootContext.WarningLevel >= 3)
1415 "Type parameter `{0}' has same name " +
1416 "as type parameter from outer type `{1}'",
1417 name, parent.GetInstantiationName ());
1425 TypeParameter[] initialize_type_params ()
1427 if (type_param_list != null)
1428 return type_param_list;
1430 DeclSpace the_parent = parent;
1431 if (this is GenericMethod)
1435 TypeParameter[] parent_params = null;
1436 if ((the_parent != null) && the_parent.IsGeneric) {
1437 parent_params = the_parent.initialize_type_params ();
1438 start = parent_params != null ? parent_params.Length : 0;
1441 ArrayList list = new ArrayList ();
1442 if (parent_params != null)
1443 list.AddRange (parent_params);
1445 int count = type_params != null ? type_params.Length : 0;
1446 for (int i = 0; i < count; i++) {
1447 TypeParameter param = type_params [i];
1448 check_type_parameter (list, start, param.Name);
1452 type_param_list = new TypeParameter [list.Count];
1453 list.CopyTo (type_param_list, 0);
1454 return type_param_list;
1457 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1460 if (constraints_list != null) {
1462 80, Location, "Contraints are not allowed " +
1463 "on non-generic declarations");
1464 return AdditionResult.Error;
1467 return AdditionResult.Success;
1470 string[] names = MemberName.TypeArguments.GetDeclarations ();
1471 type_params = new TypeParameter [names.Length];
1474 // Register all the names
1476 for (int i = 0; i < type_params.Length; i++) {
1477 string name = names [i];
1479 AdditionResult res = IsValid (name, name);
1481 if (res != AdditionResult.Success)
1484 Constraints constraints = null;
1485 if (constraints_list != null) {
1486 foreach (Constraints constraint in constraints_list) {
1487 if (constraint.TypeParameter == name) {
1488 constraints = constraint;
1494 type_params [i] = new TypeParameter (name, constraints, Location);
1496 DefineName (name, type_params [i]);
1499 return AdditionResult.Success;
1502 public TypeParameter[] TypeParameters {
1505 throw new InvalidOperationException ();
1506 if (type_param_list == null)
1507 initialize_type_params ();
1509 return type_param_list;
1513 protected TypeParameter[] CurrentTypeParameters {
1516 throw new InvalidOperationException ();
1517 if (type_params != null)
1520 return new TypeParameter [0];
1524 public int CountTypeParameters {
1526 return count_type_params;
1530 public TypeParameterExpr LookupGeneric (string name, Location loc)
1535 foreach (TypeParameter type_param in CurrentTypeParameters) {
1536 if (type_param.Name != name)
1539 return new TypeParameterExpr (type_param, loc);
1543 return parent.LookupGeneric (name, loc);
1548 bool IAlias.IsType {
1549 get { return true; }
1552 string IAlias.Name {
1553 get { return Name; }
1556 TypeExpr IAlias.Type
1559 if (TypeBuilder == null)
1560 throw new InvalidOperationException ();
1562 if (CurrentType != null)
1565 return new TypeExpression (TypeBuilder, Location);
1569 protected override string[] ValidAttributeTargets {
1571 return attribute_targets;
1577 /// This is a readonly list of MemberInfo's.
1579 public class MemberList : IList {
1580 public readonly IList List;
1584 /// Create a new MemberList from the given IList.
1586 public MemberList (IList list)
1591 this.List = new ArrayList ();
1596 /// Concatenate the ILists `first' and `second' to a new MemberList.
1598 public MemberList (IList first, IList second)
1600 ArrayList list = new ArrayList ();
1601 list.AddRange (first);
1602 list.AddRange (second);
1607 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1610 /// Cast the MemberList into a MemberInfo[] array.
1613 /// This is an expensive operation, only use it if it's really necessary.
1615 public static explicit operator MemberInfo [] (MemberList list)
1617 Timer.StartTimer (TimerType.MiscTimer);
1618 MemberInfo [] result = new MemberInfo [list.Count];
1619 list.CopyTo (result, 0);
1620 Timer.StopTimer (TimerType.MiscTimer);
1632 public bool IsSynchronized {
1634 return List.IsSynchronized;
1638 public object SyncRoot {
1640 return List.SyncRoot;
1644 public void CopyTo (Array array, int index)
1646 List.CopyTo (array, index);
1651 public IEnumerator GetEnumerator ()
1653 return List.GetEnumerator ();
1658 public bool IsFixedSize {
1664 public bool IsReadOnly {
1670 object IList.this [int index] {
1672 return List [index];
1676 throw new NotSupportedException ();
1680 // FIXME: try to find out whether we can avoid the cast in this indexer.
1681 public MemberInfo this [int index] {
1683 return (MemberInfo) List [index];
1687 public int Add (object value)
1689 throw new NotSupportedException ();
1692 public void Clear ()
1694 throw new NotSupportedException ();
1697 public bool Contains (object value)
1699 return List.Contains (value);
1702 public int IndexOf (object value)
1704 return List.IndexOf (value);
1707 public void Insert (int index, object value)
1709 throw new NotSupportedException ();
1712 public void Remove (object value)
1714 throw new NotSupportedException ();
1717 public void RemoveAt (int index)
1719 throw new NotSupportedException ();
1724 /// This interface is used to get all members of a class when creating the
1725 /// member cache. It must be implemented by all DeclSpace derivatives which
1726 /// want to support the member cache and by TypeHandle to get caching of
1727 /// non-dynamic types.
1729 public interface IMemberContainer {
1731 /// The name of the IMemberContainer. This is only used for
1732 /// debugging purposes.
1739 /// The type of this IMemberContainer.
1746 /// Returns the IMemberContainer of the parent class or null if this
1747 /// is an interface or TypeManger.object_type.
1748 /// This is used when creating the member cache for a class to get all
1749 /// members from the parent class.
1751 IMemberContainer Parent {
1756 /// Whether this is an interface.
1763 /// Returns all members of this class with the corresponding MemberTypes
1764 /// and BindingFlags.
1767 /// When implementing this method, make sure not to return any inherited
1768 /// members and check the MemberTypes and BindingFlags properly.
1769 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1770 /// get the BindingFlags (static/non-static,public/non-public) in the
1771 /// MemberInfo class, but the cache needs this information. That's why
1772 /// this method is called multiple times with different BindingFlags.
1774 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1777 /// Return the container's member cache.
1779 MemberCache MemberCache {
1785 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1786 /// member lookups. It has a member name based hash table; it maps each member
1787 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1788 /// and the BindingFlags that were initially used to get it. The cache contains
1789 /// all members of the current class and all inherited members. If this cache is
1790 /// for an interface types, it also contains all inherited members.
1792 /// There are two ways to get a MemberCache:
1793 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1794 /// use the DeclSpace.MemberCache property.
1795 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1796 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1798 public class MemberCache {
1799 public readonly IMemberContainer Container;
1800 protected Hashtable member_hash;
1801 protected Hashtable method_hash;
1804 /// Create a new MemberCache for the given IMemberContainer `container'.
1806 public MemberCache (IMemberContainer container)
1808 this.Container = container;
1810 Timer.IncrementCounter (CounterType.MemberCache);
1811 Timer.StartTimer (TimerType.CacheInit);
1815 // If we have a parent class (we have a parent class unless we're
1816 // TypeManager.object_type), we deep-copy its MemberCache here.
1817 if (Container.IsInterface) {
1820 if (Container.Parent != null)
1821 parent = Container.Parent.MemberCache;
1823 parent = TypeHandle.ObjectType.MemberCache;
1824 member_hash = SetupCacheForInterface (parent);
1825 } else if (Container.Parent != null)
1826 member_hash = SetupCache (Container.Parent.MemberCache);
1828 member_hash = new Hashtable ();
1830 // If this is neither a dynamic type nor an interface, create a special
1831 // method cache with all declared and inherited methods.
1832 Type type = container.Type;
1833 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1834 method_hash = new Hashtable ();
1838 // Add all members from the current class.
1839 AddMembers (Container);
1841 Timer.StopTimer (TimerType.CacheInit);
1845 /// Bootstrap this member cache by doing a deep-copy of our parent.
1847 Hashtable SetupCache (MemberCache parent)
1849 Hashtable hash = new Hashtable ();
1851 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1852 while (it.MoveNext ()) {
1853 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1861 /// Add the contents of `new_hash' to `hash'.
1863 void AddHashtable (Hashtable hash, MemberCache cache)
1865 Hashtable new_hash = cache.member_hash;
1866 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1867 while (it.MoveNext ()) {
1868 ArrayList list = (ArrayList) hash [it.Key];
1870 hash [it.Key] = list = new ArrayList ();
1872 foreach (CacheEntry entry in (ArrayList) it.Value) {
1873 if (entry.Container != cache.Container)
1881 /// Bootstrap the member cache for an interface type.
1882 /// Type.GetMembers() won't return any inherited members for interface types,
1883 /// so we need to do this manually. Interfaces also inherit from System.Object.
1885 Hashtable SetupCacheForInterface (MemberCache parent)
1887 Hashtable hash = SetupCache (parent);
1888 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1890 foreach (TypeExpr iface in ifaces) {
1891 Type itype = iface.Type;
1893 IMemberContainer iface_container =
1894 TypeManager.LookupMemberContainer (itype);
1896 MemberCache iface_cache = iface_container.MemberCache;
1898 AddHashtable (hash, iface_cache);
1905 /// Add all members from class `container' to the cache.
1907 void AddMembers (IMemberContainer container)
1909 // We need to call AddMembers() with a single member type at a time
1910 // to get the member type part of CacheEntry.EntryType right.
1911 AddMembers (MemberTypes.Constructor, container);
1912 AddMembers (MemberTypes.Field, container);
1913 AddMembers (MemberTypes.Method, container);
1914 AddMembers (MemberTypes.Property, container);
1915 AddMembers (MemberTypes.Event, container);
1916 // Nested types are returned by both Static and Instance searches.
1917 AddMembers (MemberTypes.NestedType,
1918 BindingFlags.Static | BindingFlags.Public, container);
1919 AddMembers (MemberTypes.NestedType,
1920 BindingFlags.Static | BindingFlags.NonPublic, container);
1923 void AddMembers (MemberTypes mt, IMemberContainer container)
1925 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1926 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1927 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1928 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1932 /// Add all members from class `container' with the requested MemberTypes and
1933 /// BindingFlags to the cache. This method is called multiple times with different
1934 /// MemberTypes and BindingFlags.
1936 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1938 MemberList members = container.GetMembers (mt, bf);
1940 foreach (MemberInfo member in members) {
1941 string name = member.Name;
1943 int pos = name.IndexOf ('<');
1945 name = name.Substring (0, pos);
1947 // We use a name-based hash table of ArrayList's.
1948 ArrayList list = (ArrayList) member_hash [name];
1950 list = new ArrayList ();
1951 member_hash.Add (name, list);
1954 // When this method is called for the current class, the list will
1955 // already contain all inherited members from our parent classes.
1956 // We cannot add new members in front of the list since this'd be an
1957 // expensive operation, that's why the list is sorted in reverse order
1958 // (ie. members from the current class are coming last).
1959 list.Add (new CacheEntry (container, member, mt, bf));
1964 /// Add all declared and inherited methods from class `type' to the method cache.
1966 void AddMethods (Type type)
1968 AddMethods (BindingFlags.Static | BindingFlags.Public |
1969 BindingFlags.FlattenHierarchy, type);
1970 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1971 BindingFlags.FlattenHierarchy, type);
1972 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1973 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1976 void AddMethods (BindingFlags bf, Type type)
1978 MemberInfo [] members = type.GetMethods (bf);
1980 Array.Reverse (members);
1982 foreach (MethodBase member in members) {
1983 string name = member.Name;
1985 // We use a name-based hash table of ArrayList's.
1986 ArrayList list = (ArrayList) method_hash [name];
1988 list = new ArrayList ();
1989 method_hash.Add (name, list);
1992 // Unfortunately, the elements returned by Type.GetMethods() aren't
1993 // sorted so we need to do this check for every member.
1994 BindingFlags new_bf = bf;
1995 if (member.DeclaringType == type)
1996 new_bf |= BindingFlags.DeclaredOnly;
1998 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
2003 /// Compute and return a appropriate `EntryType' magic number for the given
2004 /// MemberTypes and BindingFlags.
2006 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
2008 EntryType type = EntryType.None;
2010 if ((mt & MemberTypes.Constructor) != 0)
2011 type |= EntryType.Constructor;
2012 if ((mt & MemberTypes.Event) != 0)
2013 type |= EntryType.Event;
2014 if ((mt & MemberTypes.Field) != 0)
2015 type |= EntryType.Field;
2016 if ((mt & MemberTypes.Method) != 0)
2017 type |= EntryType.Method;
2018 if ((mt & MemberTypes.Property) != 0)
2019 type |= EntryType.Property;
2020 // Nested types are returned by static and instance searches.
2021 if ((mt & MemberTypes.NestedType) != 0)
2022 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
2024 if ((bf & BindingFlags.Instance) != 0)
2025 type |= EntryType.Instance;
2026 if ((bf & BindingFlags.Static) != 0)
2027 type |= EntryType.Static;
2028 if ((bf & BindingFlags.Public) != 0)
2029 type |= EntryType.Public;
2030 if ((bf & BindingFlags.NonPublic) != 0)
2031 type |= EntryType.NonPublic;
2032 if ((bf & BindingFlags.DeclaredOnly) != 0)
2033 type |= EntryType.Declared;
2039 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2040 /// denote multiple member types. Returns true if the given flags value denotes a
2041 /// single member types.
2043 public static bool IsSingleMemberType (MemberTypes mt)
2046 case MemberTypes.Constructor:
2047 case MemberTypes.Event:
2048 case MemberTypes.Field:
2049 case MemberTypes.Method:
2050 case MemberTypes.Property:
2051 case MemberTypes.NestedType:
2060 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2061 /// number to speed up the searching process.
2064 protected enum EntryType {
2069 MaskStatic = Instance|Static,
2073 MaskProtection = Public|NonPublic,
2077 Constructor = 0x020,
2084 MaskType = Constructor|Event|Field|Method|Property|NestedType
2087 protected struct CacheEntry {
2088 public readonly IMemberContainer Container;
2089 public readonly EntryType EntryType;
2090 public readonly MemberInfo Member;
2092 public CacheEntry (IMemberContainer container, MemberInfo member,
2093 MemberTypes mt, BindingFlags bf)
2095 this.Container = container;
2096 this.Member = member;
2097 this.EntryType = GetEntryType (mt, bf);
2102 /// This is called each time we're walking up one level in the class hierarchy
2103 /// and checks whether we can abort the search since we've already found what
2104 /// we were looking for.
2106 protected bool DoneSearching (ArrayList list)
2109 // We've found exactly one member in the current class and it's not
2110 // a method or constructor.
2112 if (list.Count == 1 && !(list [0] is MethodBase))
2116 // Multiple properties: we query those just to find out the indexer
2119 if ((list.Count > 0) && (list [0] is PropertyInfo))
2126 /// Looks up members with name `name'. If you provide an optional
2127 /// filter function, it'll only be called with members matching the
2128 /// requested member name.
2130 /// This method will try to use the cache to do the lookup if possible.
2132 /// Unlike other FindMembers implementations, this method will always
2133 /// check all inherited members - even when called on an interface type.
2135 /// If you know that you're only looking for methods, you should use
2136 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2137 /// When doing a method-only search, it'll try to use a special method
2138 /// cache (unless it's a dynamic type or an interface) and the returned
2139 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2140 /// The lookup process will automatically restart itself in method-only
2141 /// search mode if it discovers that it's about to return methods.
2143 ArrayList global = new ArrayList ();
2144 bool using_global = false;
2146 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2148 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2149 MemberFilter filter, object criteria)
2152 throw new Exception ();
2154 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2155 bool method_search = mt == MemberTypes.Method;
2156 // If we have a method cache and we aren't already doing a method-only search,
2157 // then we restart a method search if the first match is a method.
2158 bool do_method_search = !method_search && (method_hash != null);
2160 ArrayList applicable;
2162 // If this is a method-only search, we try to use the method cache if
2163 // possible; a lookup in the method cache will return a MemberInfo with
2164 // the correct ReflectedType for inherited methods.
2166 if (method_search && (method_hash != null))
2167 applicable = (ArrayList) method_hash [name];
2169 applicable = (ArrayList) member_hash [name];
2171 if (applicable == null)
2172 return emptyMemberInfo;
2175 // 32 slots gives 53 rss/54 size
2176 // 2/4 slots gives 55 rss
2178 // Strange: from 25,000 calls, only 1,800
2179 // are above 2. Why does this impact it?
2182 using_global = true;
2184 Timer.StartTimer (TimerType.CachedLookup);
2186 EntryType type = GetEntryType (mt, bf);
2188 IMemberContainer current = Container;
2191 // `applicable' is a list of all members with the given member name `name'
2192 // in the current class and all its parent classes. The list is sorted in
2193 // reverse order due to the way how the cache is initialy created (to speed
2194 // things up, we're doing a deep-copy of our parent).
2196 for (int i = applicable.Count-1; i >= 0; i--) {
2197 CacheEntry entry = (CacheEntry) applicable [i];
2199 // This happens each time we're walking one level up in the class
2200 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2201 // the first time this happens (this may already happen in the first
2202 // iteration of this loop if there are no members with the name we're
2203 // looking for in the current class).
2204 if (entry.Container != current) {
2205 if (declared_only || DoneSearching (global))
2208 current = entry.Container;
2211 // Is the member of the correct type ?
2212 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2215 // Is the member static/non-static ?
2216 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2219 // Apply the filter to it.
2220 if (filter (entry.Member, criteria)) {
2221 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2222 do_method_search = false;
2223 global.Add (entry.Member);
2227 Timer.StopTimer (TimerType.CachedLookup);
2229 // If we have a method cache and we aren't already doing a method-only
2230 // search, we restart in method-only search mode if the first match is
2231 // a method. This ensures that we return a MemberInfo with the correct
2232 // ReflectedType for inherited methods.
2233 if (do_method_search && (global.Count > 0)){
2234 using_global = false;
2236 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2239 using_global = false;
2240 MemberInfo [] copy = new MemberInfo [global.Count];
2241 global.CopyTo (copy);
2246 // This finds the method or property for us to override. invocationType is the type where
2247 // the override is going to be declared, name is the name of the method/property, and
2248 // paramTypes is the parameters, if any to the method or property
2250 // Because the MemberCache holds members from this class and all the base classes,
2251 // we can avoid tons of reflection stuff.
2253 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2255 ArrayList applicable;
2256 if (method_hash != null && !is_property)
2257 applicable = (ArrayList) method_hash [name];
2259 applicable = (ArrayList) member_hash [name];
2261 if (applicable == null)
2264 // Walk the chain of methods, starting from the top.
2266 for (int i = applicable.Count - 1; i >= 0; i--) {
2267 CacheEntry entry = (CacheEntry) applicable [i];
2269 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2272 PropertyInfo pi = null;
2273 MethodInfo mi = null;
2274 FieldInfo fi = null;
2275 Type [] cmpAttrs = null;
2278 if ((entry.EntryType & EntryType.Field) != 0) {
2279 fi = (FieldInfo)entry.Member;
2281 // TODO: For this case we ignore member type
2282 //fb = TypeManager.GetField (fi);
2283 //cmpAttrs = new Type[] { fb.MemberType };
2285 pi = (PropertyInfo) entry.Member;
2286 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2289 mi = (MethodInfo) entry.Member;
2290 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2294 // TODO: Almost duplicate !
2296 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2297 case FieldAttributes.Private:
2299 // A private method is Ok if we are a nested subtype.
2300 // The spec actually is not very clear about this, see bug 52458.
2302 if (invocationType != entry.Container.Type &
2303 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2307 case FieldAttributes.FamANDAssem:
2308 case FieldAttributes.Assembly:
2310 // Check for assembly methods
2312 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2316 return entry.Member;
2320 // Check the arguments
2322 if (cmpAttrs.Length != paramTypes.Length)
2325 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2326 if (!paramTypes [j].Equals (cmpAttrs [j]))
2331 // get one of the methods because this has the visibility info.
2334 mi = pi.GetGetMethod (true);
2336 mi = pi.GetSetMethod (true);
2342 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2343 case MethodAttributes.Private:
2345 // A private method is Ok if we are a nested subtype.
2346 // The spec actually is not very clear about this, see bug 52458.
2348 if (invocationType == entry.Container.Type ||
2349 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2350 return entry.Member;
2353 case MethodAttributes.FamANDAssem:
2354 case MethodAttributes.Assembly:
2356 // Check for assembly methods
2358 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2359 return entry.Member;
2364 // A protected method is ok, because we are overriding.
2365 // public is always ok.
2367 return entry.Member;