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 TypeName {
24 public readonly string Name;
25 public readonly TypeArguments TypeArguments;
27 public readonly TypeName Left;
29 public static readonly TypeName Null = new TypeName ("");
31 public TypeName (string name)
36 public TypeName (string name, TypeArguments args)
39 this.TypeArguments = args;
42 public TypeName (TypeName left, string name, TypeArguments args)
48 public string GetName ()
51 return Left.GetName () + "." + Name;
56 public int CountTypeArguments {
58 if (TypeArguments == null)
61 return TypeArguments.Count;
65 public string GetFullName ()
68 if (TypeArguments != null)
69 full_name = Name + "<" + TypeArguments + ">";
73 return Left.GetFullName () + "." + full_name;
78 public string GetTypeName (bool full)
81 if (full && (TypeArguments != null))
82 suffix = "!" + TypeArguments.Count;
84 return Left.GetTypeName (full) + "." + Name + suffix;
89 public Expression GetTypeExpression (Location loc)
92 Expression lexpr = Left.GetTypeExpression (loc);
94 return new MemberAccess (lexpr, Name, TypeArguments, loc);
96 if (TypeArguments != null)
97 return new ConstructedType (Name, TypeArguments, loc);
99 return new SimpleName (Name, loc);
103 public MemberName GetMemberName ()
105 if (TypeArguments != null) {
106 string[] type_params = TypeArguments.GetDeclarations ();
107 return new MemberName (Left, Name, type_params);
109 return new MemberName (Left, Name);
112 public override string ToString ()
115 if (TypeArguments != null)
116 full_name = Name + "<" + TypeArguments + ">";
121 return Left + "." + full_name;
127 public class MemberName {
128 public readonly TypeName TypeName;
129 public readonly string Name;
130 public readonly string[] TypeParameters;
132 public MemberName (string name)
137 public MemberName (TypeName type, string name)
139 this.TypeName = type;
143 public MemberName (TypeName type, MemberName name)
145 this.TypeName = type;
146 this.Name = name.Name;
147 this.TypeParameters = name.TypeParameters;
150 public MemberName (TypeName type, string name, ArrayList type_params)
153 if (type_params != null) {
154 TypeParameters = new string [type_params.Count];
155 type_params.CopyTo (TypeParameters, 0);
159 public MemberName (TypeName type, string name, string[] type_params)
162 this.TypeParameters = type_params;
165 public TypeName MakeTypeName (Location loc)
167 if (TypeParameters != null) {
168 TypeArguments args = new TypeArguments (loc);
169 foreach (string param in TypeParameters)
170 args.Add (new SimpleName (param, loc));
171 return new TypeName (TypeName, Name, args);
174 return new TypeName (TypeName, Name, null);
177 public static readonly MemberName Null = new MemberName ("");
179 public string Basename {
181 if (TypeParameters != null)
182 return Name + "!" + TypeParameters.Length;
188 public string GetName (bool is_generic)
190 string name = is_generic ? Basename : Name;
191 if (TypeName != null)
192 return TypeName.GetTypeName (is_generic) + "." + name;
197 public int CountTypeParameters {
199 if (TypeParameters != null)
202 return TypeParameters.Length;
206 protected string PrintTypeParams ()
208 if (TypeParameters != null) {
209 StringBuilder sb = new StringBuilder ();
211 for (int i = 0; i < TypeParameters.Length; i++) {
214 sb.Append (TypeParameters [i]);
217 return sb.ToString ();
223 public string FullName {
225 string full_name = Name + PrintTypeParams ();
227 if (TypeName != null)
228 return TypeName + "." + full_name;
234 public override string ToString ()
236 return String.Format ("MemberName [{0}:{1}:{2}]",
237 TypeName, Name, PrintTypeParams ());
242 /// Base representation for members. This is used to keep track
243 /// of Name, Location and Modifier flags, and handling Attributes.
245 public abstract class MemberCore : Attributable {
251 public readonly MemberName MemberName;
254 /// Modifier flags that the user specified in the source code
259 /// Location where this declaration happens
261 public readonly Location Location;
265 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
266 Obsolete = 1 << 1, // Type has obsolete attribute
267 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
268 ClsCompliant = 1 << 3, // Type is CLS Compliant
269 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
270 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
271 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
272 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
273 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
274 Excluded = 1 << 9 // Method is conditional
279 /// MemberCore flags at first detected then cached
281 protected Flags caching_flags;
283 public MemberCore (MemberName name, Attributes attrs, Location loc)
286 Name = name.GetName (!(this is GenericMethod) && !(this is Method));
289 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
293 /// Tests presence of ObsoleteAttribute and report proper error
295 protected void CheckUsageOfObsoleteAttribute (Type type)
300 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
301 if (obsolete_attr == null)
304 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
307 public abstract bool Define (TypeContainer parent);
310 // Returns full member name for error message
312 public virtual string GetSignatureForError ()
318 /// Base Emit method. This is also entry point for CLS-Compliant verification.
320 public virtual void Emit (TypeContainer container)
322 VerifyObsoleteAttribute ();
324 if (!RootContext.VerifyClsCompliance)
327 VerifyClsCompliance (container);
331 // Whehter is it ok to use an unsafe pointer in this type container
333 public bool UnsafeOK (DeclSpace parent)
336 // First check if this MemberCore modifier flags has unsafe set
338 if ((ModFlags & Modifiers.UNSAFE) != 0)
341 if (parent.UnsafeContext)
344 Expression.UnsafeError (Location);
349 /// Returns instance of ObsoleteAttribute for this MemberCore
351 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
353 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
354 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
358 caching_flags &= ~Flags.Obsolete_Undetected;
360 if (OptAttributes == null)
363 // TODO: remove this allocation
364 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
365 null, null, ds.ModFlags, false);
367 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
368 if (obsolete_attr == null)
371 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
372 if (obsolete == null)
375 caching_flags |= Flags.Obsolete;
380 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
382 public override bool IsClsCompliaceRequired (DeclSpace container)
384 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
385 return (caching_flags & Flags.ClsCompliant) != 0;
387 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
388 caching_flags &= ~Flags.ClsCompliance_Undetected;
389 caching_flags |= Flags.ClsCompliant;
393 caching_flags &= ~Flags.ClsCompliance_Undetected;
398 /// Returns true when MemberCore is exposed from assembly.
400 protected bool IsExposedFromAssembly (DeclSpace ds)
402 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
405 DeclSpace parentContainer = ds;
406 while (parentContainer != null && parentContainer.ModFlags != 0) {
407 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
409 parentContainer = parentContainer.Parent;
415 /// Resolve CLSCompliantAttribute value or gets cached value.
417 bool GetClsCompliantAttributeValue (DeclSpace ds)
419 if (OptAttributes != null) {
420 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
421 null, null, ds.ModFlags, false);
422 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
423 if (cls_attribute != null) {
424 caching_flags |= Flags.HasClsCompliantAttribute;
425 return cls_attribute.GetClsCompliantAttributeValue (ds);
428 return ds.GetClsCompliantAttributeValue ();
432 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
434 protected bool HasClsCompliantAttribute {
436 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
441 /// This method is used to testing error 3005 (Method or parameter name collision).
443 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
446 /// Common helper method for identifier and parameters CLS-Compliant testing.
447 /// When return false error 3005 is reported. True means no violation.
448 /// And error 3006 tests are peformed here because of speed.
450 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
452 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
453 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
458 bool error3006 = false;
459 for (int i = 0; i < ml.Count; ++i) {
460 MemberInfo mi = ml [i];
461 if (name == mi.Name) {
462 MethodBase method = mi as MethodBase;
463 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
466 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
474 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
475 // because BindingFlags.Public returns internal types too
476 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
478 // Type is external, we can get attribute directly
479 if (temp_ds == null) {
480 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
481 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
484 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
486 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
487 if (!mc.IsClsCompliaceRequired (ds))
491 for (int ii = 0; ii < ml.Count; ++ii) {
495 Report.SymbolRelatedToPreviousError (mi);
499 Report.Error_T (3006, Location, GetSignatureForError ());
508 /// The main virtual method for CLS-Compliant verifications.
509 /// The method returns true if member is CLS-Compliant and false if member is not
510 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
511 /// and add their extra verifications.
513 protected virtual bool VerifyClsCompliance (DeclSpace ds)
515 if (!IsClsCompliaceRequired (ds)) {
516 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
517 Report.Warning_T (3019, Location, GetSignatureForError ());
522 if (!CodeGen.Assembly.IsClsCompliant) {
523 if (HasClsCompliantAttribute) {
524 Report.Error_T (3014, Location, GetSignatureForError ());
528 int index = Name.LastIndexOf ('.');
529 if (Name [index > 0 ? index + 1 : 0] == '_') {
530 Report.Error_T (3008, Location, GetSignatureForError () );
533 if (!IsIdentifierClsCompliant (ds)) {
534 Report.Error_T (3005, Location, GetSignatureForError ());
540 protected abstract void VerifyObsoleteAttribute ();
545 /// Base class for structs, classes, enumerations and interfaces.
548 /// They all create new declaration spaces. This
549 /// provides the common foundation for managing those name
552 public abstract class DeclSpace : MemberCore, IAlias {
554 /// This points to the actual definition that is being
555 /// created with System.Reflection.Emit
557 public TypeBuilder TypeBuilder;
560 /// If we are a generic type, this is the type we are
561 /// currently defining. We need to lookup members on this
562 /// instead of the TypeBuilder.
564 public TypeExpr CurrentType;
567 // This is the namespace in which this typecontainer
568 // was declared. We use this to resolve names.
570 public NamespaceEntry NamespaceEntry;
572 public Hashtable Cache = new Hashtable ();
574 public string Basename;
577 /// defined_names is used for toplevel objects
579 protected Hashtable defined_names;
581 readonly bool is_generic;
582 readonly int count_type_params;
585 // Whether we are Generic
587 public bool IsGeneric {
591 else if (parent != null)
592 return parent.IsGeneric;
598 TypeContainer parent;
600 static string[] attribute_targets = new string [] { "type" };
602 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
603 Attributes attrs, Location l)
604 : base (name, attrs, l)
607 Basename = name.Name;
608 defined_names = new Hashtable ();
609 if (name.TypeParameters != null) {
611 count_type_params = name.TypeParameters.Length;
614 count_type_params += parent.count_type_params;
615 this.parent = parent;
618 public void RecordDecl ()
620 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
621 NamespaceEntry.DefineName (MemberName.Basename, this);
625 /// The result value from adding an declaration into
626 /// a struct or a class
628 public enum AdditionResult {
630 /// The declaration has been successfully
631 /// added to the declation space.
636 /// The symbol has already been defined.
641 /// Returned if the declation being added to the
642 /// name space clashes with its container name.
644 /// The only exceptions for this are constructors
645 /// and static constructors
650 /// Returned if a constructor was created (because syntactically
651 /// it looked like a constructor) but was not (because the name
652 /// of the method is not the same as the container class
657 /// This is only used by static constructors to emit the
658 /// error 111, but this error for other things really
659 /// happens at another level for other functions.
664 /// Some other error.
670 /// Returns a status code based purely on the name
671 /// of the member being added
673 protected AdditionResult IsValid (string basename, string name)
675 if (basename == Basename)
676 return AdditionResult.EnclosingClash;
678 if (defined_names.Contains (name))
679 return AdditionResult.NameExists;
681 return AdditionResult.Success;
684 public static int length;
685 public static int small;
688 /// Introduce @name into this declaration space and
689 /// associates it with the object @o. Note that for
690 /// methods this will just point to the first method. o
692 public void DefineName (string name, object o)
694 defined_names.Add (name, o);
697 int p = name.LastIndexOf ('.');
705 /// Returns the object associated with a given name in the declaration
706 /// space. This is the inverse operation of `DefineName'
708 public object GetDefinition (string name)
710 return defined_names [name];
713 bool in_transit = false;
716 /// This function is used to catch recursive definitions
719 public bool InTransit {
729 public TypeContainer Parent {
736 /// Looks up the alias for the name
738 public IAlias LookupAlias (string name)
740 if (NamespaceEntry != null)
741 return NamespaceEntry.LookupAlias (name);
747 // root_types contains all the types. All TopLevel types
748 // hence have a parent that points to `root_types', that is
749 // why there is a non-obvious test down here.
751 public bool IsTopLevel {
754 if (parent.parent == null)
761 public virtual void CloseType ()
763 if ((caching_flags & Flags.CloseTypeCreated) == 0){
765 TypeBuilder.CreateType ();
768 // The try/catch is needed because
769 // nested enumerations fail to load when they
772 // Even if this is the right order (enumerations
773 // declared after types).
775 // Note that this still creates the type and
776 // it is possible to save it
778 caching_flags |= Flags.CloseTypeCreated;
783 /// Should be overriten by the appropriate declaration space
785 public abstract TypeBuilder DefineType ();
788 /// Define all members, but don't apply any attributes or do anything which may
789 /// access not-yet-defined classes. This method also creates the MemberCache.
791 public abstract bool DefineMembers (TypeContainer parent);
794 // Whether this is an `unsafe context'
796 public bool UnsafeContext {
798 if ((ModFlags & Modifiers.UNSAFE) != 0)
801 return parent.UnsafeContext;
806 public static string MakeFQN (string nsn, string name)
810 return String.Concat (nsn, ".", name);
813 EmitContext type_resolve_ec;
814 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
816 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
817 type_resolve_ec.ResolvingTypeTree = true;
819 return type_resolve_ec;
823 // Looks up the type, as parsed into the expression `e'
825 public Type ResolveType (Expression e, bool silent, Location loc)
827 TypeExpr d = ResolveTypeExpr (e, silent, loc);
831 return ResolveType (d, loc);
834 public Type ResolveType (TypeExpr d, Location loc)
836 if (!d.CheckAccessLevel (this)) {
837 Report.Error_T (122, loc, d.Name);
841 Type t = d.ResolveType (type_resolve_ec);
845 TypeContainer tc = TypeManager.LookupTypeContainer (t);
846 if ((tc != null) && tc.IsGeneric) {
848 int tnum = TypeManager.GetNumberOfTypeArguments (t);
849 Report.Error (305, loc,
850 "Using the generic type `{0}' " +
851 "requires {1} type arguments",
852 TypeManager.GetFullName (t), tnum);
856 ConstructedType ctype = new ConstructedType (
857 t, TypeParameters, loc);
859 t = ctype.ResolveType (type_resolve_ec);
866 // Resolves the expression `e' for a type, and will recursively define
869 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
871 if (type_resolve_ec == null)
872 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
873 type_resolve_ec.loc = loc;
874 if (this is GenericMethod)
875 type_resolve_ec.ContainerType = Parent.TypeBuilder;
877 type_resolve_ec.ContainerType = TypeBuilder;
879 int errors = Report.Errors;
881 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
883 if ((d != null) && (d.eclass == ExprClass.Type))
886 if (silent || (Report.Errors != errors))
889 if (e is SimpleName){
890 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
891 d = s.ResolveAsTypeTerminal (type_resolve_ec);
893 if ((d == null) || (d.Type == null)) {
894 Report.Error (246, loc, "Cannot find type `{0}'", e);
898 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
901 Report.Error (308, loc,
902 "The non-generic type `{0}' cannot " +
903 "be used with type arguments.",
904 TypeManager.CSharpName (d.Type));
908 Report.Error (305, loc,
909 "Using the generic type `{0}' " +
910 "requires {1} type arguments",
911 TypeManager.GetFullName (d.Type), num_args);
915 Report.Error (246, loc, "Cannot find type `{0}'", e);
919 public bool CheckAccessLevel (Type check_type)
922 if (this is GenericMethod)
923 tb = Parent.TypeBuilder;
927 if (check_type.IsGenericInstance)
928 check_type = check_type.GetGenericTypeDefinition ();
930 if (check_type == tb)
933 if (check_type.IsGenericParameter)
934 return true; // FIXME
936 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
939 // Broken Microsoft runtime, return public for arrays, no matter what
940 // the accessibility is for their underlying class, and they return
941 // NonPublic visibility for pointers
943 if (check_type.IsArray || check_type.IsPointer)
944 return CheckAccessLevel (TypeManager.GetElementType (check_type));
947 case TypeAttributes.Public:
950 case TypeAttributes.NotPublic:
952 // In same cases is null.
953 if (TypeBuilder == null)
957 // This test should probably use the declaringtype.
959 return check_type.Assembly == TypeBuilder.Assembly;
961 case TypeAttributes.NestedPublic:
964 case TypeAttributes.NestedPrivate:
965 string check_type_name = check_type.FullName;
966 string type_name = CurrentType != null ?
967 CurrentType.Name : tb.FullName;
969 int cio = check_type_name.LastIndexOf ('+');
970 string container = check_type_name.Substring (0, cio);
973 // Check if the check_type is a nested class of the current type
975 if (check_type_name.StartsWith (type_name + "+")){
979 if (type_name.StartsWith (container)){
985 case TypeAttributes.NestedFamily:
987 // Only accessible to methods in current type or any subtypes
989 return FamilyAccessible (tb, check_type);
991 case TypeAttributes.NestedFamANDAssem:
992 return (check_type.Assembly == tb.Assembly) &&
993 FamilyAccessible (tb, check_type);
995 case TypeAttributes.NestedFamORAssem:
996 return (check_type.Assembly == tb.Assembly) ||
997 FamilyAccessible (tb, check_type);
999 case TypeAttributes.NestedAssembly:
1000 return check_type.Assembly == tb.Assembly;
1003 Console.WriteLine ("HERE: " + check_attr);
1008 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
1010 Type declaring = check_type.DeclaringType;
1011 if (tb.IsSubclassOf (declaring))
1014 string check_type_name = check_type.FullName;
1016 int cio = check_type_name.LastIndexOf ('+');
1017 string container = check_type_name.Substring (0, cio);
1020 // Check if the check_type is a nested class of the current type
1022 if (check_type_name.StartsWith (container + "+"))
1028 // Access level of a type.
1030 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
1031 // Public Assembly Protected
1032 Protected = (0 << 0) | (0 << 1) | (X << 2),
1033 Public = (X << 0) | (X << 1) | (X << 2),
1034 Private = (0 << 0) | (0 << 1) | (0 << 2),
1035 Internal = (0 << 0) | (X << 1) | (0 << 2),
1036 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
1039 static AccessLevel GetAccessLevelFromModifiers (int flags)
1041 if ((flags & Modifiers.INTERNAL) != 0) {
1043 if ((flags & Modifiers.PROTECTED) != 0)
1044 return AccessLevel.ProtectedOrInternal;
1046 return AccessLevel.Internal;
1048 } else if ((flags & Modifiers.PROTECTED) != 0)
1049 return AccessLevel.Protected;
1050 else if ((flags & Modifiers.PRIVATE) != 0)
1051 return AccessLevel.Private;
1053 return AccessLevel.Public;
1056 // What is the effective access level of this?
1057 // TODO: Cache this?
1058 AccessLevel EffectiveAccessLevel {
1060 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1061 if (!IsTopLevel && (Parent != null))
1062 return myAccess & Parent.EffectiveAccessLevel;
1067 // Return the access level for type `t'
1068 static AccessLevel TypeEffectiveAccessLevel (Type t)
1071 return AccessLevel.Public;
1072 if (t.IsNestedPrivate)
1073 return AccessLevel.Private;
1075 return AccessLevel.Internal;
1077 // By now, it must be nested
1078 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1080 if (t.IsNestedPublic)
1082 if (t.IsNestedAssembly)
1083 return parentLevel & AccessLevel.Internal;
1084 if (t.IsNestedFamily)
1085 return parentLevel & AccessLevel.Protected;
1086 if (t.IsNestedFamORAssem)
1087 return parentLevel & AccessLevel.ProtectedOrInternal;
1088 if (t.IsNestedFamANDAssem)
1089 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1091 // nested private is taken care of
1093 throw new Exception ("I give up, what are you?");
1097 // This answers `is the type P, as accessible as a member M which has the
1098 // accessability @flags which is declared as a nested member of the type T, this declspace'
1100 public bool AsAccessible (Type p, int flags)
1102 if (p.IsGenericParameter)
1103 return true; // FIXME
1106 // 1) if M is private, its accessability is the same as this declspace.
1107 // we already know that P is accessible to T before this method, so we
1111 if ((flags & Modifiers.PRIVATE) != 0)
1114 while (p.IsArray || p.IsPointer || p.IsByRef)
1115 p = TypeManager.GetElementType (p);
1117 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1118 AccessLevel mAccess = this.EffectiveAccessLevel &
1119 GetAccessLevelFromModifiers (flags);
1121 // for every place from which we can access M, we must
1122 // be able to access P as well. So, we want
1123 // For every bit in M and P, M_i -> P_1 == true
1124 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1126 return ~ (~ mAccess | pAccess) == 0;
1129 static DoubleHash dh = new DoubleHash (1000);
1131 Type DefineTypeAndParents (DeclSpace tc)
1133 DeclSpace container = tc.Parent;
1135 if (container.TypeBuilder == null && container.Name != "")
1136 DefineTypeAndParents (container);
1138 return tc.DefineType ();
1141 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1149 if (dh.Lookup (ns, name, out r))
1153 if (Namespace.IsNamespace (ns)){
1154 string fullname = (ns != "") ? ns + "." + name : name;
1155 t = TypeManager.LookupType (fullname);
1159 t = TypeManager.LookupType (name);
1163 dh.Insert (ns, name, t);
1168 // In case we are fed a composite name, normalize it.
1170 int p = name.LastIndexOf ('.');
1172 ns = MakeFQN (ns, name.Substring (0, p));
1173 name = name.Substring (p+1);
1176 parent = RootContext.Tree.LookupByNamespace (ns, name);
1177 if (parent == null) {
1178 dh.Insert (ns, name, null);
1182 t = DefineTypeAndParents (parent);
1188 dh.Insert (ns, name, t);
1192 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1194 Report.Error (104, loc,
1195 "`{0}' is an ambiguous reference ({1} or {2})",
1199 public Type FindNestedType (Location loc, string name,
1200 out DeclSpace containing_ds)
1205 containing_ds = this;
1206 while (containing_ds != null){
1207 Type container_type = containing_ds.TypeBuilder;
1208 Type current_type = container_type;
1210 while (current_type != null && current_type != TypeManager.object_type) {
1211 string pre = current_type.FullName;
1213 t = LookupInterfaceOrClass (pre, name, out error);
1217 if ((t != null) && containing_ds.CheckAccessLevel (t))
1220 current_type = current_type.BaseType;
1222 containing_ds = containing_ds.Parent;
1229 /// GetType is used to resolve type names at the DeclSpace level.
1230 /// Use this to lookup class/struct bases, interface bases or
1231 /// delegate type references
1235 /// Contrast this to LookupType which is used inside method bodies to
1236 /// lookup types that have already been defined. GetType is used
1237 /// during the tree resolution process and potentially define
1238 /// recursively the type
1240 public Type FindType (Location loc, string name)
1246 // For the case the type we are looking for is nested within this one
1247 // or is in any base class
1249 DeclSpace containing_ds = this;
1251 while (containing_ds != null){
1252 Type container_type = containing_ds.TypeBuilder;
1253 Type current_type = container_type;
1255 while (current_type != null && current_type != TypeManager.object_type) {
1256 string pre = current_type.FullName;
1258 t = LookupInterfaceOrClass (pre, name, out error);
1262 if ((t != null) && containing_ds.CheckAccessLevel (t))
1265 current_type = current_type.BaseType;
1267 containing_ds = containing_ds.Parent;
1271 // Attempt to lookup the class on our namespace and all it's implicit parents
1273 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1274 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1283 // Attempt to do a direct unqualified lookup
1285 t = LookupInterfaceOrClass ("", name, out error);
1293 // Attempt to lookup the class on any of the `using'
1297 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1299 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1306 if (name.IndexOf ('.') > 0)
1309 IAlias alias_value = ns.LookupAlias (name);
1310 if (alias_value != null) {
1311 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1320 // Now check the using clause list
1323 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1324 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1328 if (match != null) {
1330 if (CheckAccessLevel (match)) {
1331 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1344 //Report.Error (246, Location, "Can not find type `"+name+"'");
1349 /// This function is broken and not what you're looking for. It should only
1350 /// be used while the type is still being created since it doesn't use the cache
1351 /// and relies on the filter doing the member name check.
1353 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1354 MemberFilter filter, object criteria);
1357 /// If we have a MemberCache, return it. This property may return null if the
1358 /// class doesn't have a member cache or while it's still being created.
1360 public abstract MemberCache MemberCache {
1364 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1367 TypeBuilder.SetCustomAttribute (cb);
1368 } catch (System.ArgumentException e) {
1369 Report.Warning (-21, a.Location,
1370 "The CharSet named property on StructLayout\n"+
1371 "\tdoes not work correctly on Microsoft.NET\n"+
1372 "\tYou might want to remove the CharSet declaration\n"+
1373 "\tor compile using the Mono runtime instead of the\n"+
1374 "\tMicrosoft .NET runtime\n"+
1375 "\tThe runtime gave the error: " + e);
1380 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1381 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1383 public bool GetClsCompliantAttributeValue ()
1385 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1386 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1388 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1390 if (OptAttributes != null) {
1391 EmitContext ec = new EmitContext (parent, this, Location,
1392 null, null, ModFlags, false);
1393 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1394 if (cls_attribute != null) {
1395 caching_flags |= Flags.HasClsCompliantAttribute;
1396 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1397 caching_flags |= Flags.ClsCompliantAttributeTrue;
1404 if (parent == null) {
1405 if (CodeGen.Assembly.IsClsCompliant) {
1406 caching_flags |= Flags.ClsCompliantAttributeTrue;
1412 if (parent.GetClsCompliantAttributeValue ()) {
1413 caching_flags |= Flags.ClsCompliantAttributeTrue;
1420 // Tests container name for CLS-Compliant name (differing only in case)
1421 // Possible optimalization: search in same namespace only
1422 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1424 int l = Name.Length;
1426 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1427 // Seek through all imported types
1428 foreach (string type_name in TypeManager.all_imported_types.Keys)
1430 if (l != type_name.Length)
1433 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1434 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1435 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1441 // Seek through generated types
1442 foreach (string name in RootContext.Tree.Decls.Keys) {
1443 if (l != name.Length)
1446 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1451 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1452 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1453 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1463 // Extensions for generics
1465 TypeParameter[] type_params;
1466 TypeParameter[] type_param_list;
1468 protected string GetInstantiationName ()
1470 StringBuilder sb = new StringBuilder (Name);
1472 for (int i = 0; i < type_param_list.Length; i++) {
1475 sb.Append (type_param_list [i].Name);
1478 return sb.ToString ();
1481 bool check_type_parameter (ArrayList list, int start, string name)
1483 for (int i = 0; i < start; i++) {
1484 TypeParameter param = (TypeParameter) list [i];
1486 if (param.Name != name)
1489 if (RootContext.WarningLevel >= 3)
1492 "Type parameter `{0}' has same name " +
1493 "as type parameter from outer type `{1}'",
1494 name, parent.GetInstantiationName ());
1502 TypeParameter[] initialize_type_params ()
1504 if (type_param_list != null)
1505 return type_param_list;
1507 DeclSpace the_parent = parent;
1508 if (this is GenericMethod)
1512 TypeParameter[] parent_params = null;
1513 if ((the_parent != null) && the_parent.IsGeneric) {
1514 parent_params = the_parent.initialize_type_params ();
1515 start = parent_params != null ? parent_params.Length : 0;
1518 ArrayList list = new ArrayList ();
1519 if (parent_params != null)
1520 list.AddRange (parent_params);
1522 int count = type_params != null ? type_params.Length : 0;
1523 for (int i = 0; i < count; i++) {
1524 TypeParameter param = type_params [i];
1525 check_type_parameter (list, start, param.Name);
1529 type_param_list = new TypeParameter [list.Count];
1530 list.CopyTo (type_param_list, 0);
1531 return type_param_list;
1534 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1537 if (constraints_list != null) {
1539 80, Location, "Contraints are not allowed " +
1540 "on non-generic declarations");
1541 return AdditionResult.Error;
1544 return AdditionResult.Success;
1547 type_params = new TypeParameter [MemberName.TypeParameters.Length];
1550 // Register all the names
1552 for (int i = 0; i < MemberName.TypeParameters.Length; i++) {
1553 string name = MemberName.TypeParameters [i];
1555 AdditionResult res = IsValid (name, name);
1557 if (res != AdditionResult.Success)
1560 Constraints constraints = null;
1561 if (constraints_list != null) {
1562 foreach (Constraints constraint in constraints_list) {
1563 if (constraint.TypeParameter == name) {
1564 constraints = constraint;
1570 type_params [i] = new TypeParameter (name, constraints, Location);
1572 DefineName (name, type_params [i]);
1575 return AdditionResult.Success;
1578 public TypeParameter[] TypeParameters {
1581 throw new InvalidOperationException ();
1582 if (type_param_list == null)
1583 initialize_type_params ();
1585 return type_param_list;
1589 protected TypeParameter[] CurrentTypeParameters {
1592 throw new InvalidOperationException ();
1593 if (type_params != null)
1596 return new TypeParameter [0];
1600 public int CountTypeParameters {
1602 return count_type_params;
1606 public TypeParameterExpr LookupGeneric (string name, Location loc)
1611 foreach (TypeParameter type_param in CurrentTypeParameters) {
1612 if (type_param.Name != name)
1615 return new TypeParameterExpr (type_param, loc);
1619 return parent.LookupGeneric (name, loc);
1624 bool IAlias.IsType {
1625 get { return true; }
1628 string IAlias.Name {
1629 get { return Name; }
1632 TypeExpr IAlias.Type
1635 if (TypeBuilder == null)
1636 throw new InvalidOperationException ();
1638 if (CurrentType != null)
1641 return new TypeExpression (TypeBuilder, Location);
1645 protected override string[] ValidAttributeTargets {
1647 return attribute_targets;
1653 /// This is a readonly list of MemberInfo's.
1655 public class MemberList : IList {
1656 public readonly IList List;
1660 /// Create a new MemberList from the given IList.
1662 public MemberList (IList list)
1667 this.List = new ArrayList ();
1672 /// Concatenate the ILists `first' and `second' to a new MemberList.
1674 public MemberList (IList first, IList second)
1676 ArrayList list = new ArrayList ();
1677 list.AddRange (first);
1678 list.AddRange (second);
1683 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1686 /// Cast the MemberList into a MemberInfo[] array.
1689 /// This is an expensive operation, only use it if it's really necessary.
1691 public static explicit operator MemberInfo [] (MemberList list)
1693 Timer.StartTimer (TimerType.MiscTimer);
1694 MemberInfo [] result = new MemberInfo [list.Count];
1695 list.CopyTo (result, 0);
1696 Timer.StopTimer (TimerType.MiscTimer);
1708 public bool IsSynchronized {
1710 return List.IsSynchronized;
1714 public object SyncRoot {
1716 return List.SyncRoot;
1720 public void CopyTo (Array array, int index)
1722 List.CopyTo (array, index);
1727 public IEnumerator GetEnumerator ()
1729 return List.GetEnumerator ();
1734 public bool IsFixedSize {
1740 public bool IsReadOnly {
1746 object IList.this [int index] {
1748 return List [index];
1752 throw new NotSupportedException ();
1756 // FIXME: try to find out whether we can avoid the cast in this indexer.
1757 public MemberInfo this [int index] {
1759 return (MemberInfo) List [index];
1763 public int Add (object value)
1765 throw new NotSupportedException ();
1768 public void Clear ()
1770 throw new NotSupportedException ();
1773 public bool Contains (object value)
1775 return List.Contains (value);
1778 public int IndexOf (object value)
1780 return List.IndexOf (value);
1783 public void Insert (int index, object value)
1785 throw new NotSupportedException ();
1788 public void Remove (object value)
1790 throw new NotSupportedException ();
1793 public void RemoveAt (int index)
1795 throw new NotSupportedException ();
1800 /// This interface is used to get all members of a class when creating the
1801 /// member cache. It must be implemented by all DeclSpace derivatives which
1802 /// want to support the member cache and by TypeHandle to get caching of
1803 /// non-dynamic types.
1805 public interface IMemberContainer {
1807 /// The name of the IMemberContainer. This is only used for
1808 /// debugging purposes.
1815 /// The type of this IMemberContainer.
1822 /// Returns the IMemberContainer of the parent class or null if this
1823 /// is an interface or TypeManger.object_type.
1824 /// This is used when creating the member cache for a class to get all
1825 /// members from the parent class.
1827 IMemberContainer Parent {
1832 /// Whether this is an interface.
1839 /// Returns all members of this class with the corresponding MemberTypes
1840 /// and BindingFlags.
1843 /// When implementing this method, make sure not to return any inherited
1844 /// members and check the MemberTypes and BindingFlags properly.
1845 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1846 /// get the BindingFlags (static/non-static,public/non-public) in the
1847 /// MemberInfo class, but the cache needs this information. That's why
1848 /// this method is called multiple times with different BindingFlags.
1850 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1853 /// Return the container's member cache.
1855 MemberCache MemberCache {
1861 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1862 /// member lookups. It has a member name based hash table; it maps each member
1863 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1864 /// and the BindingFlags that were initially used to get it. The cache contains
1865 /// all members of the current class and all inherited members. If this cache is
1866 /// for an interface types, it also contains all inherited members.
1868 /// There are two ways to get a MemberCache:
1869 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1870 /// use the DeclSpace.MemberCache property.
1871 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1872 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1874 public class MemberCache {
1875 public readonly IMemberContainer Container;
1876 protected Hashtable member_hash;
1877 protected Hashtable method_hash;
1880 /// Create a new MemberCache for the given IMemberContainer `container'.
1882 public MemberCache (IMemberContainer container)
1884 this.Container = container;
1886 Timer.IncrementCounter (CounterType.MemberCache);
1887 Timer.StartTimer (TimerType.CacheInit);
1891 // If we have a parent class (we have a parent class unless we're
1892 // TypeManager.object_type), we deep-copy its MemberCache here.
1893 if (Container.IsInterface) {
1896 if (Container.Parent != null)
1897 parent = Container.Parent.MemberCache;
1899 parent = TypeHandle.ObjectType.MemberCache;
1900 member_hash = SetupCacheForInterface (parent);
1901 } else if (Container.Parent != null)
1902 member_hash = SetupCache (Container.Parent.MemberCache);
1904 member_hash = new Hashtable ();
1906 // If this is neither a dynamic type nor an interface, create a special
1907 // method cache with all declared and inherited methods.
1908 Type type = container.Type;
1909 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1910 method_hash = new Hashtable ();
1914 // Add all members from the current class.
1915 AddMembers (Container);
1917 Timer.StopTimer (TimerType.CacheInit);
1921 /// Bootstrap this member cache by doing a deep-copy of our parent.
1923 Hashtable SetupCache (MemberCache parent)
1925 Hashtable hash = new Hashtable ();
1927 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1928 while (it.MoveNext ()) {
1929 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1937 /// Add the contents of `new_hash' to `hash'.
1939 void AddHashtable (Hashtable hash, MemberCache cache)
1941 Hashtable new_hash = cache.member_hash;
1942 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1943 while (it.MoveNext ()) {
1944 ArrayList list = (ArrayList) hash [it.Key];
1946 hash [it.Key] = list = new ArrayList ();
1948 foreach (CacheEntry entry in (ArrayList) it.Value) {
1949 if (entry.Container != cache.Container)
1957 /// Bootstrap the member cache for an interface type.
1958 /// Type.GetMembers() won't return any inherited members for interface types,
1959 /// so we need to do this manually. Interfaces also inherit from System.Object.
1961 Hashtable SetupCacheForInterface (MemberCache parent)
1963 Hashtable hash = SetupCache (parent);
1964 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1966 foreach (TypeExpr iface in ifaces) {
1967 Type itype = iface.Type;
1969 IMemberContainer iface_container =
1970 TypeManager.LookupMemberContainer (itype);
1972 MemberCache iface_cache = iface_container.MemberCache;
1974 AddHashtable (hash, iface_cache);
1981 /// Add all members from class `container' to the cache.
1983 void AddMembers (IMemberContainer container)
1985 // We need to call AddMembers() with a single member type at a time
1986 // to get the member type part of CacheEntry.EntryType right.
1987 AddMembers (MemberTypes.Constructor, container);
1988 AddMembers (MemberTypes.Field, container);
1989 AddMembers (MemberTypes.Method, container);
1990 AddMembers (MemberTypes.Property, container);
1991 AddMembers (MemberTypes.Event, container);
1992 // Nested types are returned by both Static and Instance searches.
1993 AddMembers (MemberTypes.NestedType,
1994 BindingFlags.Static | BindingFlags.Public, container);
1995 AddMembers (MemberTypes.NestedType,
1996 BindingFlags.Static | BindingFlags.NonPublic, container);
1999 void AddMembers (MemberTypes mt, IMemberContainer container)
2001 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
2002 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
2003 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
2004 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
2008 /// Add all members from class `container' with the requested MemberTypes and
2009 /// BindingFlags to the cache. This method is called multiple times with different
2010 /// MemberTypes and BindingFlags.
2012 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
2014 MemberList members = container.GetMembers (mt, bf);
2016 foreach (MemberInfo member in members) {
2017 string name = member.Name;
2019 int pos = name.IndexOf ('<');
2021 name = name.Substring (0, pos);
2023 // We use a name-based hash table of ArrayList's.
2024 ArrayList list = (ArrayList) member_hash [name];
2026 list = new ArrayList ();
2027 member_hash.Add (name, list);
2030 // When this method is called for the current class, the list will
2031 // already contain all inherited members from our parent classes.
2032 // We cannot add new members in front of the list since this'd be an
2033 // expensive operation, that's why the list is sorted in reverse order
2034 // (ie. members from the current class are coming last).
2035 list.Add (new CacheEntry (container, member, mt, bf));
2040 /// Add all declared and inherited methods from class `type' to the method cache.
2042 void AddMethods (Type type)
2044 AddMethods (BindingFlags.Static | BindingFlags.Public |
2045 BindingFlags.FlattenHierarchy, type);
2046 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
2047 BindingFlags.FlattenHierarchy, type);
2048 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
2049 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
2052 void AddMethods (BindingFlags bf, Type type)
2054 MemberInfo [] members = type.GetMethods (bf);
2056 Array.Reverse (members);
2058 foreach (MethodBase member in members) {
2059 string name = member.Name;
2061 // Varargs methods aren't allowed in C# code.
2062 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
2065 // We use a name-based hash table of ArrayList's.
2066 ArrayList list = (ArrayList) method_hash [name];
2068 list = new ArrayList ();
2069 method_hash.Add (name, list);
2072 // Unfortunately, the elements returned by Type.GetMethods() aren't
2073 // sorted so we need to do this check for every member.
2074 BindingFlags new_bf = bf;
2075 if (member.DeclaringType == type)
2076 new_bf |= BindingFlags.DeclaredOnly;
2078 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
2083 /// Compute and return a appropriate `EntryType' magic number for the given
2084 /// MemberTypes and BindingFlags.
2086 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
2088 EntryType type = EntryType.None;
2090 if ((mt & MemberTypes.Constructor) != 0)
2091 type |= EntryType.Constructor;
2092 if ((mt & MemberTypes.Event) != 0)
2093 type |= EntryType.Event;
2094 if ((mt & MemberTypes.Field) != 0)
2095 type |= EntryType.Field;
2096 if ((mt & MemberTypes.Method) != 0)
2097 type |= EntryType.Method;
2098 if ((mt & MemberTypes.Property) != 0)
2099 type |= EntryType.Property;
2100 // Nested types are returned by static and instance searches.
2101 if ((mt & MemberTypes.NestedType) != 0)
2102 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
2104 if ((bf & BindingFlags.Instance) != 0)
2105 type |= EntryType.Instance;
2106 if ((bf & BindingFlags.Static) != 0)
2107 type |= EntryType.Static;
2108 if ((bf & BindingFlags.Public) != 0)
2109 type |= EntryType.Public;
2110 if ((bf & BindingFlags.NonPublic) != 0)
2111 type |= EntryType.NonPublic;
2112 if ((bf & BindingFlags.DeclaredOnly) != 0)
2113 type |= EntryType.Declared;
2119 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2120 /// denote multiple member types. Returns true if the given flags value denotes a
2121 /// single member types.
2123 public static bool IsSingleMemberType (MemberTypes mt)
2126 case MemberTypes.Constructor:
2127 case MemberTypes.Event:
2128 case MemberTypes.Field:
2129 case MemberTypes.Method:
2130 case MemberTypes.Property:
2131 case MemberTypes.NestedType:
2140 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2141 /// number to speed up the searching process.
2144 protected enum EntryType {
2149 MaskStatic = Instance|Static,
2153 MaskProtection = Public|NonPublic,
2157 Constructor = 0x020,
2164 MaskType = Constructor|Event|Field|Method|Property|NestedType
2167 protected struct CacheEntry {
2168 public readonly IMemberContainer Container;
2169 public readonly EntryType EntryType;
2170 public readonly MemberInfo Member;
2172 public CacheEntry (IMemberContainer container, MemberInfo member,
2173 MemberTypes mt, BindingFlags bf)
2175 this.Container = container;
2176 this.Member = member;
2177 this.EntryType = GetEntryType (mt, bf);
2182 /// This is called each time we're walking up one level in the class hierarchy
2183 /// and checks whether we can abort the search since we've already found what
2184 /// we were looking for.
2186 protected bool DoneSearching (ArrayList list)
2189 // We've found exactly one member in the current class and it's not
2190 // a method or constructor.
2192 if (list.Count == 1 && !(list [0] is MethodBase))
2196 // Multiple properties: we query those just to find out the indexer
2199 if ((list.Count > 0) && (list [0] is PropertyInfo))
2206 /// Looks up members with name `name'. If you provide an optional
2207 /// filter function, it'll only be called with members matching the
2208 /// requested member name.
2210 /// This method will try to use the cache to do the lookup if possible.
2212 /// Unlike other FindMembers implementations, this method will always
2213 /// check all inherited members - even when called on an interface type.
2215 /// If you know that you're only looking for methods, you should use
2216 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2217 /// When doing a method-only search, it'll try to use a special method
2218 /// cache (unless it's a dynamic type or an interface) and the returned
2219 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2220 /// The lookup process will automatically restart itself in method-only
2221 /// search mode if it discovers that it's about to return methods.
2223 ArrayList global = new ArrayList ();
2224 bool using_global = false;
2226 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2228 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2229 MemberFilter filter, object criteria)
2232 throw new Exception ();
2234 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2235 bool method_search = mt == MemberTypes.Method;
2236 // If we have a method cache and we aren't already doing a method-only search,
2237 // then we restart a method search if the first match is a method.
2238 bool do_method_search = !method_search && (method_hash != null);
2240 ArrayList applicable;
2242 // If this is a method-only search, we try to use the method cache if
2243 // possible; a lookup in the method cache will return a MemberInfo with
2244 // the correct ReflectedType for inherited methods.
2246 if (method_search && (method_hash != null))
2247 applicable = (ArrayList) method_hash [name];
2249 applicable = (ArrayList) member_hash [name];
2251 if (applicable == null)
2252 return emptyMemberInfo;
2255 // 32 slots gives 53 rss/54 size
2256 // 2/4 slots gives 55 rss
2258 // Strange: from 25,000 calls, only 1,800
2259 // are above 2. Why does this impact it?
2262 using_global = true;
2264 Timer.StartTimer (TimerType.CachedLookup);
2266 EntryType type = GetEntryType (mt, bf);
2268 IMemberContainer current = Container;
2271 // `applicable' is a list of all members with the given member name `name'
2272 // in the current class and all its parent classes. The list is sorted in
2273 // reverse order due to the way how the cache is initialy created (to speed
2274 // things up, we're doing a deep-copy of our parent).
2276 for (int i = applicable.Count-1; i >= 0; i--) {
2277 CacheEntry entry = (CacheEntry) applicable [i];
2279 // This happens each time we're walking one level up in the class
2280 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2281 // the first time this happens (this may already happen in the first
2282 // iteration of this loop if there are no members with the name we're
2283 // looking for in the current class).
2284 if (entry.Container != current) {
2285 if (declared_only || DoneSearching (global))
2288 current = entry.Container;
2291 // Is the member of the correct type ?
2292 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2295 // Is the member static/non-static ?
2296 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2299 // Apply the filter to it.
2300 if (filter (entry.Member, criteria)) {
2301 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2302 do_method_search = false;
2303 global.Add (entry.Member);
2307 Timer.StopTimer (TimerType.CachedLookup);
2309 // If we have a method cache and we aren't already doing a method-only
2310 // search, we restart in method-only search mode if the first match is
2311 // a method. This ensures that we return a MemberInfo with the correct
2312 // ReflectedType for inherited methods.
2313 if (do_method_search && (global.Count > 0)){
2314 using_global = false;
2316 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2319 using_global = false;
2320 MemberInfo [] copy = new MemberInfo [global.Count];
2321 global.CopyTo (copy);
2326 // This finds the method or property for us to override. invocationType is the type where
2327 // the override is going to be declared, name is the name of the method/property, and
2328 // paramTypes is the parameters, if any to the method or property
2330 // Because the MemberCache holds members from this class and all the base classes,
2331 // we can avoid tons of reflection stuff.
2333 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2335 ArrayList applicable;
2336 if (method_hash != null && !is_property)
2337 applicable = (ArrayList) method_hash [name];
2339 applicable = (ArrayList) member_hash [name];
2341 if (applicable == null)
2344 // Walk the chain of methods, starting from the top.
2346 for (int i = applicable.Count - 1; i >= 0; i--) {
2347 CacheEntry entry = (CacheEntry) applicable [i];
2349 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2352 PropertyInfo pi = null;
2353 MethodInfo mi = null;
2354 FieldInfo fi = null;
2355 Type [] cmpAttrs = null;
2358 if ((entry.EntryType & EntryType.Field) != 0) {
2359 fi = (FieldInfo)entry.Member;
2361 // TODO: For this case we ignore member type
2362 //fb = TypeManager.GetField (fi);
2363 //cmpAttrs = new Type[] { fb.MemberType };
2365 pi = (PropertyInfo) entry.Member;
2366 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2369 mi = (MethodInfo) entry.Member;
2370 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2374 // TODO: Almost duplicate !
2376 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2377 case FieldAttributes.Private:
2379 // A private method is Ok if we are a nested subtype.
2380 // The spec actually is not very clear about this, see bug 52458.
2382 if (invocationType != entry.Container.Type &
2383 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2387 case FieldAttributes.FamANDAssem:
2388 case FieldAttributes.Assembly:
2390 // Check for assembly methods
2392 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2396 return entry.Member;
2400 // Check the arguments
2402 if (cmpAttrs.Length != paramTypes.Length)
2405 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2406 if (!paramTypes [j].Equals (cmpAttrs [j]))
2411 // get one of the methods because this has the visibility info.
2414 mi = pi.GetGetMethod (true);
2416 mi = pi.GetSetMethod (true);
2422 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2423 case MethodAttributes.Private:
2425 // A private method is Ok if we are a nested subtype.
2426 // The spec actually is not very clear about this, see bug 52458.
2428 if (invocationType == entry.Container.Type ||
2429 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2430 return entry.Member;
2433 case MethodAttributes.FamANDAssem:
2434 case MethodAttributes.Assembly:
2436 // Check for assembly methods
2438 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2439 return entry.Member;
2444 // A protected method is ok, because we are overriding.
2445 // public is always ok.
2447 return entry.Member;