2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
15 using System.Collections;
16 using System.Reflection.Emit;
17 using System.Reflection;
19 namespace Mono.CSharp {
21 public class MemberName {
22 public readonly string Name;
23 public readonly TypeArguments TypeArguments;
25 public readonly MemberName Left;
27 public static readonly MemberName Null = new MemberName ("");
29 public MemberName (string name)
34 public MemberName (string name, TypeArguments args)
37 this.TypeArguments = args;
40 public MemberName (MemberName left, string name, TypeArguments args)
46 public string GetName ()
49 return Left.GetName () + "." + Name;
54 public string GetFullName ()
57 if (TypeArguments != null)
58 full_name = Name + "<" + TypeArguments + ">";
62 return Left.GetFullName () + "." + full_name;
67 public string GetMemberName ()
71 return Left.GetFullName () + "." + Name;
76 public Expression GetTypeExpression (Location loc)
79 Expression lexpr = Left.GetTypeExpression (loc);
81 if (TypeArguments != null)
82 return new GenericMemberAccess (lexpr, Name, TypeArguments, loc);
84 return new MemberAccess (lexpr, Name, loc);
86 if (TypeArguments != null)
87 return new ConstructedType (Name, TypeArguments, loc);
89 return new SimpleName (Name, loc);
93 public override string ToString ()
96 if (TypeArguments != null)
97 full_name = Name + "<" + TypeArguments + ">";
102 return Left + "." + full_name;
109 /// Base representation for members. This is only used to keep track
110 /// of Name, Location and Modifier flags.
112 public abstract class MemberCore {
119 /// Modifier flags that the user specified in the source code
124 /// Location where this declaration happens
126 public readonly Location Location;
129 /// Attributes for this type
131 Attributes attributes;
133 public MemberCore (string name, Attributes attrs, Location loc)
140 public abstract bool Define (TypeContainer parent);
143 // Returns full member name for error message
145 public virtual string GetSignatureForError () {
149 public Attributes OptAttributes
160 // Whehter is it ok to use an unsafe pointer in this type container
162 public bool UnsafeOK (DeclSpace parent)
165 // First check if this MemberCore modifier flags has unsafe set
167 if ((ModFlags & Modifiers.UNSAFE) != 0)
170 if (parent.UnsafeContext)
173 Expression.UnsafeError (Location);
179 /// Base class for structs, classes, enumerations and interfaces.
182 /// They all create new declaration spaces. This
183 /// provides the common foundation for managing those name
186 public abstract class DeclSpace : MemberCore {
188 /// This points to the actual definition that is being
189 /// created with System.Reflection.Emit
191 public TypeBuilder TypeBuilder;
194 /// If we are a generic type, this is the type we are
195 /// currently defining. We need to lookup members on this
196 /// instead of the TypeBuilder.
198 public TypeExpr CurrentType;
201 /// This variable tracks whether we have Closed the type
203 public bool Created = false;
206 // This is the namespace in which this typecontainer
207 // was declared. We use this to resolve names.
209 public NamespaceEntry NamespaceEntry;
211 public Hashtable Cache = new Hashtable ();
213 public string Basename;
216 /// defined_names is used for toplevel objects
218 protected Hashtable defined_names;
223 // Whether we are Generic
225 public bool IsGeneric {
229 else if (parent != null)
230 return parent.IsGeneric;
236 TypeContainer parent;
238 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
239 : base (name, attrs, l)
242 Basename = name.Substring (1 + name.LastIndexOf ('.'));
243 defined_names = new Hashtable ();
244 this.parent = parent;
247 public void RecordDecl ()
249 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
250 NamespaceEntry.DefineName (Basename, this);
254 /// The result value from adding an declaration into
255 /// a struct or a class
257 public enum AdditionResult {
259 /// The declaration has been successfully
260 /// added to the declation space.
265 /// The symbol has already been defined.
270 /// Returned if the declation being added to the
271 /// name space clashes with its container name.
273 /// The only exceptions for this are constructors
274 /// and static constructors
279 /// Returned if a constructor was created (because syntactically
280 /// it looked like a constructor) but was not (because the name
281 /// of the method is not the same as the container class
286 /// This is only used by static constructors to emit the
287 /// error 111, but this error for other things really
288 /// happens at another level for other functions.
293 /// Some other error.
299 /// Returns a status code based purely on the name
300 /// of the member being added
302 protected AdditionResult IsValid (string basename, string name)
304 if (basename == Basename)
305 return AdditionResult.EnclosingClash;
307 if (defined_names.Contains (name))
308 return AdditionResult.NameExists;
310 return AdditionResult.Success;
313 public static int length;
314 public static int small;
317 /// Introduce @name into this declaration space and
318 /// associates it with the object @o. Note that for
319 /// methods this will just point to the first method. o
321 public void DefineName (string name, object o)
323 defined_names.Add (name, o);
326 int p = name.LastIndexOf ('.');
334 /// Returns the object associated with a given name in the declaration
335 /// space. This is the inverse operation of `DefineName'
337 public object GetDefinition (string name)
339 return defined_names [name];
342 bool in_transit = false;
345 /// This function is used to catch recursive definitions
348 public bool InTransit {
358 public TypeContainer Parent {
365 /// Looks up the alias for the name
367 public string LookupAlias (string name)
369 if (NamespaceEntry != null)
370 return NamespaceEntry.LookupAlias (name);
376 // root_types contains all the types. All TopLevel types
377 // hence have a parent that points to `root_types', that is
378 // why there is a non-obvious test down here.
380 public bool IsTopLevel {
383 if (parent.parent == null)
390 public virtual void CloseType ()
394 TypeBuilder.CreateType ();
397 // The try/catch is needed because
398 // nested enumerations fail to load when they
401 // Even if this is the right order (enumerations
402 // declared after types).
404 // Note that this still creates the type and
405 // it is possible to save it
412 /// Should be overriten by the appropriate declaration space
414 public abstract TypeBuilder DefineType ();
417 /// Define all members, but don't apply any attributes or do anything which may
418 /// access not-yet-defined classes. This method also creates the MemberCache.
420 public abstract bool DefineMembers (TypeContainer parent);
423 // Whether this is an `unsafe context'
425 public bool UnsafeContext {
427 if ((ModFlags & Modifiers.UNSAFE) != 0)
430 return parent.UnsafeContext;
435 public static string MakeFQN (string nsn, string name)
439 return String.Concat (nsn, ".", name);
442 EmitContext type_resolve_ec;
443 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
445 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
446 type_resolve_ec.ResolvingTypeTree = true;
448 return type_resolve_ec;
452 // Looks up the type, as parsed into the expression `e'
454 public Type ResolveType (Expression e, bool silent, Location loc)
456 TypeExpr d = ResolveTypeExpr (e, silent, loc);
460 return ResolveType (d, loc);
463 public Type ResolveType (TypeExpr d, Location loc)
465 if (!d.CheckAccessLevel (this)) {
466 Report. Error (122, loc, "`" + d.Name + "' " +
467 "is inaccessible because of its protection level");
471 Type t = d.ResolveType (type_resolve_ec);
475 TypeContainer tc = TypeManager.LookupTypeContainer (t);
476 if ((tc != null) && tc.IsGeneric) {
477 ConstructedType ctype = new ConstructedType (
478 t, TypeParameters, loc);
480 t = ctype.ResolveType (type_resolve_ec);
487 // Resolves the expression `e' for a type, and will recursively define
490 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
492 if (type_resolve_ec == null)
493 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
494 type_resolve_ec.loc = loc;
495 if (this is GenericMethod)
496 type_resolve_ec.ContainerType = Parent.TypeBuilder;
498 type_resolve_ec.ContainerType = TypeBuilder;
500 int errors = Report.Errors;
502 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
504 if ((d != null) && (d.eclass == ExprClass.Type))
507 if (silent || (Report.Errors != errors))
510 if (e is SimpleName){
511 SimpleName s = new SimpleName (((SimpleName) e).Name, -1, loc);
512 d = s.ResolveAsTypeTerminal (type_resolve_ec);
514 if ((d == null) || (d.Type == null)) {
515 Report.Error (246, loc, "Cannot find type `{0}'", e);
519 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
522 Report.Error (308, loc,
523 "The non-generic type `{0}' cannot " +
524 "be used with type arguments.",
525 TypeManager.CSharpName (d.Type));
529 Report.Error (305, loc,
530 "Using the generic type `{0}' " +
531 "requires {1} type arguments",
532 TypeManager.GetFullName (d.Type), num_args);
536 Report.Error (246, loc, "Cannot find type `{0}'", e);
540 public bool CheckAccessLevel (Type check_type)
543 if (this is GenericMethod)
544 tb = Parent.TypeBuilder;
548 if (check_type.IsGenericInstance)
549 check_type = check_type.GetGenericTypeDefinition ();
551 if (check_type == tb)
554 if (check_type.IsGenericParameter)
555 return true; // FIXME
557 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
560 // Broken Microsoft runtime, return public for arrays, no matter what
561 // the accessibility is for their underlying class, and they return
562 // NonPublic visibility for pointers
564 if (check_type.IsArray || check_type.IsPointer)
565 return CheckAccessLevel (TypeManager.GetElementType (check_type));
568 case TypeAttributes.Public:
571 case TypeAttributes.NotPublic:
573 // This test should probably use the declaringtype.
575 if (check_type.Assembly == tb.Assembly){
580 case TypeAttributes.NestedPublic:
583 case TypeAttributes.NestedPrivate:
584 string check_type_name = check_type.FullName;
585 string type_name = CurrentType != null ?
586 CurrentType.Name : tb.FullName;
588 int cio = check_type_name.LastIndexOf ('+');
589 string container = check_type_name.Substring (0, cio);
592 // Check if the check_type is a nested class of the current type
594 if (check_type_name.StartsWith (type_name + "+")){
598 if (type_name.StartsWith (container)){
604 case TypeAttributes.NestedFamily:
606 // Only accessible to methods in current type or any subtypes
608 return FamilyAccessible (tb, check_type);
610 case TypeAttributes.NestedFamANDAssem:
611 return (check_type.Assembly == tb.Assembly) &&
612 FamilyAccessible (tb, check_type);
614 case TypeAttributes.NestedFamORAssem:
615 return (check_type.Assembly == tb.Assembly) ||
616 FamilyAccessible (tb, check_type);
618 case TypeAttributes.NestedAssembly:
619 return check_type.Assembly == tb.Assembly;
622 Console.WriteLine ("HERE: " + check_attr);
627 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
629 Type declaring = check_type.DeclaringType;
630 if (tb.IsSubclassOf (declaring))
633 string check_type_name = check_type.FullName;
635 int cio = check_type_name.LastIndexOf ('+');
636 string container = check_type_name.Substring (0, cio);
639 // Check if the check_type is a nested class of the current type
641 if (check_type_name.StartsWith (container + "+"))
647 // Access level of a type.
649 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
650 // Public Assembly Protected
651 Protected = (0 << 0) | (0 << 1) | (X << 2),
652 Public = (X << 0) | (X << 1) | (X << 2),
653 Private = (0 << 0) | (0 << 1) | (0 << 2),
654 Internal = (0 << 0) | (X << 1) | (0 << 2),
655 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
658 static AccessLevel GetAccessLevelFromModifiers (int flags)
660 if ((flags & Modifiers.INTERNAL) != 0) {
662 if ((flags & Modifiers.PROTECTED) != 0)
663 return AccessLevel.ProtectedOrInternal;
665 return AccessLevel.Internal;
667 } else if ((flags & Modifiers.PROTECTED) != 0)
668 return AccessLevel.Protected;
669 else if ((flags & Modifiers.PRIVATE) != 0)
670 return AccessLevel.Private;
672 return AccessLevel.Public;
675 // What is the effective access level of this?
677 AccessLevel EffectiveAccessLevel {
679 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
680 if (!IsTopLevel && (Parent != null))
681 return myAccess & Parent.EffectiveAccessLevel;
686 // Return the access level for type `t'
687 static AccessLevel TypeEffectiveAccessLevel (Type t)
690 return AccessLevel.Public;
691 if (t.IsNestedPrivate)
692 return AccessLevel.Private;
694 return AccessLevel.Internal;
696 // By now, it must be nested
697 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
699 if (t.IsNestedPublic)
701 if (t.IsNestedAssembly)
702 return parentLevel & AccessLevel.Internal;
703 if (t.IsNestedFamily)
704 return parentLevel & AccessLevel.Protected;
705 if (t.IsNestedFamORAssem)
706 return parentLevel & AccessLevel.ProtectedOrInternal;
707 if (t.IsNestedFamANDAssem)
708 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
710 // nested private is taken care of
712 throw new Exception ("I give up, what are you?");
716 // This answers `is the type P, as accessible as a member M which has the
717 // accessability @flags which is declared as a nested member of the type T, this declspace'
719 public bool AsAccessible (Type p, int flags)
721 if (p.IsGenericParameter)
722 return true; // FIXME
725 // 1) if M is private, its accessability is the same as this declspace.
726 // we already know that P is accessible to T before this method, so we
730 if ((flags & Modifiers.PRIVATE) != 0)
733 while (p.IsArray || p.IsPointer || p.IsByRef)
734 p = TypeManager.GetElementType (p);
736 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
737 AccessLevel mAccess = this.EffectiveAccessLevel &
738 GetAccessLevelFromModifiers (flags);
740 // for every place from which we can access M, we must
741 // be able to access P as well. So, we want
742 // For every bit in M and P, M_i -> P_1 == true
743 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
745 return ~ (~ mAccess | pAccess) == 0;
748 static DoubleHash dh = new DoubleHash (1000);
750 Type DefineTypeAndParents (DeclSpace tc)
752 DeclSpace container = tc.Parent;
754 if (container.TypeBuilder == null && container.Name != "")
755 DefineTypeAndParents (container);
757 return tc.DefineType ();
760 Type LookupInterfaceOrClass (string ns, string name, out bool error)
768 if (dh.Lookup (ns, name, out r))
772 if (Namespace.IsNamespace (ns)){
773 string fullname = (ns != "") ? ns + "." + name : name;
774 t = TypeManager.LookupType (fullname);
778 t = TypeManager.LookupType (name);
782 dh.Insert (ns, name, t);
787 // In case we are fed a composite name, normalize it.
789 int p = name.LastIndexOf ('.');
791 ns = MakeFQN (ns, name.Substring (0, p));
792 name = name.Substring (p+1);
795 parent = RootContext.Tree.LookupByNamespace (ns, name);
796 if (parent == null) {
797 dh.Insert (ns, name, null);
801 t = DefineTypeAndParents (parent);
807 dh.Insert (ns, name, t);
811 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
813 Report.Error (104, loc,
814 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
815 t1.FullName, t2.FullName));
818 public Type FindNestedType (Location loc, string name,
819 out DeclSpace containing_ds)
824 containing_ds = this;
825 while (containing_ds != null){
826 Type container_type = containing_ds.TypeBuilder;
827 Type current_type = container_type;
829 while (current_type != null && current_type != TypeManager.object_type) {
830 string pre = current_type.FullName;
832 t = LookupInterfaceOrClass (pre, name, out error);
836 if ((t != null) && containing_ds.CheckAccessLevel (t))
839 current_type = current_type.BaseType;
841 containing_ds = containing_ds.Parent;
848 /// GetType is used to resolve type names at the DeclSpace level.
849 /// Use this to lookup class/struct bases, interface bases or
850 /// delegate type references
854 /// Contrast this to LookupType which is used inside method bodies to
855 /// lookup types that have already been defined. GetType is used
856 /// during the tree resolution process and potentially define
857 /// recursively the type
859 public Type FindType (Location loc, string name, int num_type_args)
865 // For the case the type we are looking for is nested within this one
866 // or is in any base class
868 DeclSpace containing_ds = this;
870 while (containing_ds != null){
871 Type container_type = containing_ds.TypeBuilder;
872 Type current_type = container_type;
874 while (current_type != null && current_type != TypeManager.object_type) {
875 string pre = current_type.FullName;
877 t = LookupInterfaceOrClass (pre, name, out error);
882 containing_ds.CheckAccessLevel (t) &&
883 TypeManager.CheckGeneric (t, num_type_args))
886 current_type = current_type.BaseType;
888 containing_ds = containing_ds.Parent;
892 // Attempt to lookup the class on our namespace and all it's implicit parents
894 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
895 t = LookupInterfaceOrClass (ns.FullName, name, out error);
899 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
904 // Attempt to do a direct unqualified lookup
906 t = LookupInterfaceOrClass ("", name, out error);
910 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
914 // Attempt to lookup the class on any of the `using'
918 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
920 t = LookupInterfaceOrClass (ns.FullName, name, out error);
924 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
928 // Now check the using clause list
931 foreach (Namespace using_ns in ns.GetUsingTable ()) {
932 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
936 if ((match != null) &&
937 TypeManager.CheckGeneric (match, num_type_args)) {
939 if (CheckAccessLevel (match)) {
940 Error_AmbiguousTypeReference (loc, name, t, match);
949 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
953 //Report.Error (246, Location, "Can not find type `"+name+"'");
958 /// This function is broken and not what you're looking for. It should only
959 /// be used while the type is still being created since it doesn't use the cache
960 /// and relies on the filter doing the member name check.
962 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
963 MemberFilter filter, object criteria);
966 /// If we have a MemberCache, return it. This property may return null if the
967 /// class doesn't have a member cache or while it's still being created.
969 public abstract MemberCache MemberCache {
974 // Extensions for generics
976 TypeParameter[] type_params;
977 TypeParameter[] type_param_list;
979 protected string GetInstantiationName ()
981 StringBuilder sb = new StringBuilder (Name);
983 for (int i = 0; i < type_param_list.Length; i++) {
986 sb.Append (type_param_list [i].Name);
989 return sb.ToString ();
992 bool check_type_parameter (ArrayList list, int start, string name)
994 for (int i = 0; i < start; i++) {
995 TypeParameter param = (TypeParameter) list [i];
997 if (param.Name != name)
1000 if (RootContext.WarningLevel >= 3)
1003 "Type parameter `{0}' has same name " +
1004 "as type parameter from outer type `{1}'",
1005 name, parent.GetInstantiationName ());
1013 TypeParameter[] initialize_type_params ()
1015 if (type_param_list != null)
1016 return type_param_list;
1018 DeclSpace the_parent = parent;
1019 if (this is GenericMethod)
1020 the_parent = the_parent.Parent;
1023 TypeParameter[] parent_params = null;
1024 if ((the_parent != null) && the_parent.IsGeneric) {
1025 parent_params = the_parent.initialize_type_params ();
1026 start = parent_params != null ? parent_params.Length : 0;
1029 ArrayList list = new ArrayList ();
1030 if (parent_params != null)
1031 list.AddRange (parent_params);
1033 int count = type_params != null ? type_params.Length : 0;
1034 for (int i = 0; i < count; i++) {
1035 TypeParameter param = type_params [i];
1036 check_type_parameter (list, start, param.Name);
1040 type_param_list = new TypeParameter [list.Count];
1041 list.CopyTo (type_param_list, 0);
1042 return type_param_list;
1046 /// Called by the parser to configure the type_parameter_list for this
1047 /// declaration space
1049 public AdditionResult SetParameterInfo (TypeArguments args,
1050 ArrayList constraints_list)
1052 string[] type_parameter_list = args.GetDeclarations ();
1053 if (type_parameter_list == null)
1054 return AdditionResult.Error;
1056 return SetParameterInfo (type_parameter_list, constraints_list);
1059 public AdditionResult SetParameterInfo (IList type_parameter_list,
1060 ArrayList constraints_list)
1062 type_params = new TypeParameter [type_parameter_list.Count];
1065 // Mark this type as Generic
1070 // Register all the names
1072 for (int i = 0; i < type_parameter_list.Count; i++) {
1073 string name = (string) type_parameter_list [i];
1075 AdditionResult res = IsValid (name, name);
1077 if (res != AdditionResult.Success)
1080 Constraints constraints = null;
1081 if (constraints_list != null) {
1082 foreach (Constraints constraint in constraints_list) {
1083 if (constraint.TypeParameter == name) {
1084 constraints = constraint;
1090 type_params [i] = new TypeParameter (name, constraints, Location);
1092 DefineName (name, type_params [i]);
1095 return AdditionResult.Success;
1098 public TypeParameter[] TypeParameters {
1101 throw new InvalidOperationException ();
1102 if (type_param_list == null)
1103 initialize_type_params ();
1105 return type_param_list;
1109 protected TypeParameter[] CurrentTypeParameters {
1112 throw new InvalidOperationException ();
1113 if (type_params != null)
1116 return new TypeParameter [0];
1120 public int CountTypeParameters {
1124 if (type_param_list == null)
1125 initialize_type_params ();
1127 return type_param_list.Length;
1131 public TypeParameterExpr LookupGeneric (string name, Location loc)
1136 foreach (TypeParameter type_param in CurrentTypeParameters) {
1137 if (type_param.Name != name)
1140 return new TypeParameterExpr (type_param, loc);
1144 return parent.LookupGeneric (name, loc);
1151 /// This is a readonly list of MemberInfo's.
1153 public class MemberList : IList {
1154 public readonly IList List;
1158 /// Create a new MemberList from the given IList.
1160 public MemberList (IList list)
1165 this.List = new ArrayList ();
1170 /// Concatenate the ILists `first' and `second' to a new MemberList.
1172 public MemberList (IList first, IList second)
1174 ArrayList list = new ArrayList ();
1175 list.AddRange (first);
1176 list.AddRange (second);
1181 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1184 /// Cast the MemberList into a MemberInfo[] array.
1187 /// This is an expensive operation, only use it if it's really necessary.
1189 public static explicit operator MemberInfo [] (MemberList list)
1191 Timer.StartTimer (TimerType.MiscTimer);
1192 MemberInfo [] result = new MemberInfo [list.Count];
1193 list.CopyTo (result, 0);
1194 Timer.StopTimer (TimerType.MiscTimer);
1206 public bool IsSynchronized {
1208 return List.IsSynchronized;
1212 public object SyncRoot {
1214 return List.SyncRoot;
1218 public void CopyTo (Array array, int index)
1220 List.CopyTo (array, index);
1225 public IEnumerator GetEnumerator ()
1227 return List.GetEnumerator ();
1232 public bool IsFixedSize {
1238 public bool IsReadOnly {
1244 object IList.this [int index] {
1246 return List [index];
1250 throw new NotSupportedException ();
1254 // FIXME: try to find out whether we can avoid the cast in this indexer.
1255 public MemberInfo this [int index] {
1257 return (MemberInfo) List [index];
1261 public int Add (object value)
1263 throw new NotSupportedException ();
1266 public void Clear ()
1268 throw new NotSupportedException ();
1271 public bool Contains (object value)
1273 return List.Contains (value);
1276 public int IndexOf (object value)
1278 return List.IndexOf (value);
1281 public void Insert (int index, object value)
1283 throw new NotSupportedException ();
1286 public void Remove (object value)
1288 throw new NotSupportedException ();
1291 public void RemoveAt (int index)
1293 throw new NotSupportedException ();
1298 /// This interface is used to get all members of a class when creating the
1299 /// member cache. It must be implemented by all DeclSpace derivatives which
1300 /// want to support the member cache and by TypeHandle to get caching of
1301 /// non-dynamic types.
1303 public interface IMemberContainer {
1305 /// The name of the IMemberContainer. This is only used for
1306 /// debugging purposes.
1313 /// The type of this IMemberContainer.
1320 /// Returns the IMemberContainer of the parent class or null if this
1321 /// is an interface or TypeManger.object_type.
1322 /// This is used when creating the member cache for a class to get all
1323 /// members from the parent class.
1325 IMemberContainer Parent {
1330 /// Whether this is an interface.
1337 /// Returns all members of this class with the corresponding MemberTypes
1338 /// and BindingFlags.
1341 /// When implementing this method, make sure not to return any inherited
1342 /// members and check the MemberTypes and BindingFlags properly.
1343 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1344 /// get the BindingFlags (static/non-static,public/non-public) in the
1345 /// MemberInfo class, but the cache needs this information. That's why
1346 /// this method is called multiple times with different BindingFlags.
1348 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1351 /// Return the container's member cache.
1353 MemberCache MemberCache {
1359 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1360 /// member lookups. It has a member name based hash table; it maps each member
1361 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1362 /// and the BindingFlags that were initially used to get it. The cache contains
1363 /// all members of the current class and all inherited members. If this cache is
1364 /// for an interface types, it also contains all inherited members.
1366 /// There are two ways to get a MemberCache:
1367 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1368 /// use the DeclSpace.MemberCache property.
1369 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1370 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1372 public class MemberCache {
1373 public readonly IMemberContainer Container;
1374 protected Hashtable member_hash;
1375 protected Hashtable method_hash;
1377 Hashtable interface_hash;
1380 /// Create a new MemberCache for the given IMemberContainer `container'.
1382 public MemberCache (IMemberContainer container)
1384 this.Container = container;
1386 Timer.IncrementCounter (CounterType.MemberCache);
1387 Timer.StartTimer (TimerType.CacheInit);
1391 // If we have a parent class (we have a parent class unless we're
1392 // TypeManager.object_type), we deep-copy its MemberCache here.
1393 if (Container.IsInterface) {
1395 interface_hash = new Hashtable ();
1397 if (Container.Parent != null)
1398 parent = Container.Parent.MemberCache;
1400 parent = TypeHandle.ObjectType.MemberCache;
1401 member_hash = SetupCacheForInterface (parent);
1402 } else if (Container.Parent != null)
1403 member_hash = SetupCache (Container.Parent.MemberCache);
1405 member_hash = new Hashtable ();
1407 // If this is neither a dynamic type nor an interface, create a special
1408 // method cache with all declared and inherited methods.
1409 Type type = container.Type;
1410 if (!(type is TypeBuilder) && !type.IsInterface) {
1411 method_hash = new Hashtable ();
1415 // Add all members from the current class.
1416 AddMembers (Container);
1418 Timer.StopTimer (TimerType.CacheInit);
1422 /// Bootstrap this member cache by doing a deep-copy of our parent.
1424 Hashtable SetupCache (MemberCache parent)
1426 Hashtable hash = new Hashtable ();
1428 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1429 while (it.MoveNext ()) {
1430 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1438 /// Add the contents of `new_hash' to `hash'.
1440 void AddHashtable (Hashtable hash, Hashtable new_hash)
1442 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1443 while (it.MoveNext ()) {
1444 ArrayList list = (ArrayList) hash [it.Key];
1446 list.AddRange ((ArrayList) it.Value);
1448 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1453 /// Bootstrap the member cache for an interface type.
1454 /// Type.GetMembers() won't return any inherited members for interface types,
1455 /// so we need to do this manually. Interfaces also inherit from System.Object.
1457 Hashtable SetupCacheForInterface (MemberCache parent)
1459 Hashtable hash = SetupCache (parent);
1460 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1462 foreach (TypeExpr iface in ifaces) {
1463 Type itype = iface.Type;
1465 if (interface_hash.Contains (itype))
1468 interface_hash [itype] = null;
1470 IMemberContainer iface_container =
1471 TypeManager.LookupMemberContainer (itype);
1473 MemberCache iface_cache = iface_container.MemberCache;
1475 AddHashtable (hash, iface_cache.member_hash);
1477 if (iface_cache.interface_hash == null)
1480 foreach (Type parent_contains in iface_cache.interface_hash.Keys)
1481 interface_hash [parent_contains] = null;
1488 /// Add all members from class `container' to the cache.
1490 void AddMembers (IMemberContainer container)
1492 // We need to call AddMembers() with a single member type at a time
1493 // to get the member type part of CacheEntry.EntryType right.
1494 AddMembers (MemberTypes.Constructor, container);
1495 AddMembers (MemberTypes.Field, container);
1496 AddMembers (MemberTypes.Method, container);
1497 AddMembers (MemberTypes.Property, container);
1498 AddMembers (MemberTypes.Event, container);
1499 // Nested types are returned by both Static and Instance searches.
1500 AddMembers (MemberTypes.NestedType,
1501 BindingFlags.Static | BindingFlags.Public, container);
1502 AddMembers (MemberTypes.NestedType,
1503 BindingFlags.Static | BindingFlags.NonPublic, container);
1506 void AddMembers (MemberTypes mt, IMemberContainer container)
1508 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1509 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1510 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1511 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1515 /// Add all members from class `container' with the requested MemberTypes and
1516 /// BindingFlags to the cache. This method is called multiple times with different
1517 /// MemberTypes and BindingFlags.
1519 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1521 MemberList members = container.GetMembers (mt, bf);
1523 foreach (MemberInfo member in members) {
1524 string name = member.Name;
1526 int pos = name.IndexOf ('<');
1528 name = name.Substring (0, pos);
1530 // We use a name-based hash table of ArrayList's.
1531 ArrayList list = (ArrayList) member_hash [name];
1533 list = new ArrayList ();
1534 member_hash.Add (name, list);
1537 // When this method is called for the current class, the list will
1538 // already contain all inherited members from our parent classes.
1539 // We cannot add new members in front of the list since this'd be an
1540 // expensive operation, that's why the list is sorted in reverse order
1541 // (ie. members from the current class are coming last).
1542 list.Add (new CacheEntry (container, member, mt, bf));
1547 /// Add all declared and inherited methods from class `type' to the method cache.
1549 void AddMethods (Type type)
1551 AddMethods (BindingFlags.Static | BindingFlags.Public |
1552 BindingFlags.FlattenHierarchy, type);
1553 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1554 BindingFlags.FlattenHierarchy, type);
1555 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1556 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1559 void AddMethods (BindingFlags bf, Type type)
1561 MemberInfo [] members = type.GetMethods (bf);
1563 Array.Reverse (members);
1565 foreach (MethodBase member in members) {
1566 string name = member.Name;
1568 // Varargs methods aren't allowed in C# code.
1569 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1572 // We use a name-based hash table of ArrayList's.
1573 ArrayList list = (ArrayList) method_hash [name];
1575 list = new ArrayList ();
1576 method_hash.Add (name, list);
1579 // Unfortunately, the elements returned by Type.GetMethods() aren't
1580 // sorted so we need to do this check for every member.
1581 BindingFlags new_bf = bf;
1582 if (member.DeclaringType == type)
1583 new_bf |= BindingFlags.DeclaredOnly;
1585 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1590 /// Compute and return a appropriate `EntryType' magic number for the given
1591 /// MemberTypes and BindingFlags.
1593 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1595 EntryType type = EntryType.None;
1597 if ((mt & MemberTypes.Constructor) != 0)
1598 type |= EntryType.Constructor;
1599 if ((mt & MemberTypes.Event) != 0)
1600 type |= EntryType.Event;
1601 if ((mt & MemberTypes.Field) != 0)
1602 type |= EntryType.Field;
1603 if ((mt & MemberTypes.Method) != 0)
1604 type |= EntryType.Method;
1605 if ((mt & MemberTypes.Property) != 0)
1606 type |= EntryType.Property;
1607 // Nested types are returned by static and instance searches.
1608 if ((mt & MemberTypes.NestedType) != 0)
1609 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1611 if ((bf & BindingFlags.Instance) != 0)
1612 type |= EntryType.Instance;
1613 if ((bf & BindingFlags.Static) != 0)
1614 type |= EntryType.Static;
1615 if ((bf & BindingFlags.Public) != 0)
1616 type |= EntryType.Public;
1617 if ((bf & BindingFlags.NonPublic) != 0)
1618 type |= EntryType.NonPublic;
1619 if ((bf & BindingFlags.DeclaredOnly) != 0)
1620 type |= EntryType.Declared;
1626 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1627 /// denote multiple member types. Returns true if the given flags value denotes a
1628 /// single member types.
1630 public static bool IsSingleMemberType (MemberTypes mt)
1633 case MemberTypes.Constructor:
1634 case MemberTypes.Event:
1635 case MemberTypes.Field:
1636 case MemberTypes.Method:
1637 case MemberTypes.Property:
1638 case MemberTypes.NestedType:
1647 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1648 /// number to speed up the searching process.
1651 protected enum EntryType {
1656 MaskStatic = Instance|Static,
1660 MaskProtection = Public|NonPublic,
1664 Constructor = 0x020,
1671 MaskType = Constructor|Event|Field|Method|Property|NestedType
1674 protected struct CacheEntry {
1675 public readonly IMemberContainer Container;
1676 public readonly EntryType EntryType;
1677 public readonly MemberInfo Member;
1679 public CacheEntry (IMemberContainer container, MemberInfo member,
1680 MemberTypes mt, BindingFlags bf)
1682 this.Container = container;
1683 this.Member = member;
1684 this.EntryType = GetEntryType (mt, bf);
1689 /// This is called each time we're walking up one level in the class hierarchy
1690 /// and checks whether we can abort the search since we've already found what
1691 /// we were looking for.
1693 protected bool DoneSearching (ArrayList list)
1696 // We've found exactly one member in the current class and it's not
1697 // a method or constructor.
1699 if (list.Count == 1 && !(list [0] is MethodBase))
1703 // Multiple properties: we query those just to find out the indexer
1706 if ((list.Count > 0) && (list [0] is PropertyInfo))
1713 /// Looks up members with name `name'. If you provide an optional
1714 /// filter function, it'll only be called with members matching the
1715 /// requested member name.
1717 /// This method will try to use the cache to do the lookup if possible.
1719 /// Unlike other FindMembers implementations, this method will always
1720 /// check all inherited members - even when called on an interface type.
1722 /// If you know that you're only looking for methods, you should use
1723 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1724 /// When doing a method-only search, it'll try to use a special method
1725 /// cache (unless it's a dynamic type or an interface) and the returned
1726 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1727 /// The lookup process will automatically restart itself in method-only
1728 /// search mode if it discovers that it's about to return methods.
1730 ArrayList global = new ArrayList ();
1731 bool using_global = false;
1733 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1734 MemberFilter filter, object criteria)
1737 throw new Exception ();
1739 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1740 bool method_search = mt == MemberTypes.Method;
1741 // If we have a method cache and we aren't already doing a method-only search,
1742 // then we restart a method search if the first match is a method.
1743 bool do_method_search = !method_search && (method_hash != null);
1745 ArrayList applicable;
1747 // If this is a method-only search, we try to use the method cache if
1748 // possible; a lookup in the method cache will return a MemberInfo with
1749 // the correct ReflectedType for inherited methods.
1751 if (method_search && (method_hash != null))
1752 applicable = (ArrayList) method_hash [name];
1754 applicable = (ArrayList) member_hash [name];
1756 if (applicable == null)
1757 return MemberList.Empty;
1760 // 32 slots gives 53 rss/54 size
1761 // 2/4 slots gives 55 rss
1763 // Strange: from 25,000 calls, only 1,800
1764 // are above 2. Why does this impact it?
1767 using_global = true;
1769 Timer.StartTimer (TimerType.CachedLookup);
1771 EntryType type = GetEntryType (mt, bf);
1773 IMemberContainer current = Container;
1775 // `applicable' is a list of all members with the given member name `name'
1776 // in the current class and all its parent classes. The list is sorted in
1777 // reverse order due to the way how the cache is initialy created (to speed
1778 // things up, we're doing a deep-copy of our parent).
1780 for (int i = applicable.Count-1; i >= 0; i--) {
1781 CacheEntry entry = (CacheEntry) applicable [i];
1783 // This happens each time we're walking one level up in the class
1784 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1785 // the first time this happens (this may already happen in the first
1786 // iteration of this loop if there are no members with the name we're
1787 // looking for in the current class).
1788 if (entry.Container != current) {
1789 if (declared_only || DoneSearching (global))
1792 current = entry.Container;
1795 // Is the member of the correct type ?
1796 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1799 // Is the member static/non-static ?
1800 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1803 // Apply the filter to it.
1804 if (filter (entry.Member, criteria)) {
1805 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1806 do_method_search = false;
1807 global.Add (entry.Member);
1811 Timer.StopTimer (TimerType.CachedLookup);
1813 // If we have a method cache and we aren't already doing a method-only
1814 // search, we restart in method-only search mode if the first match is
1815 // a method. This ensures that we return a MemberInfo with the correct
1816 // ReflectedType for inherited methods.
1817 if (do_method_search && (global.Count > 0)){
1818 using_global = false;
1820 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1823 using_global = false;
1824 MemberInfo [] copy = new MemberInfo [global.Count];
1825 global.CopyTo (copy);
1826 return new MemberList (copy);
1830 // This finds the method or property for us to override. invocationType is the type where
1831 // the override is going to be declared, name is the name of the method/property, and
1832 // paramTypes is the parameters, if any to the method or property
1834 // Because the MemberCache holds members from this class and all the base classes,
1835 // we can avoid tons of reflection stuff.
1837 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1839 ArrayList applicable;
1840 if (method_hash != null && !is_property)
1841 applicable = (ArrayList) method_hash [name];
1843 applicable = (ArrayList) member_hash [name];
1845 if (applicable == null)
1848 // Walk the chain of methods, starting from the top.
1850 for (int i = applicable.Count - 1; i >= 0; i--) {
1851 CacheEntry entry = (CacheEntry) applicable [i];
1853 if ((entry.EntryType & (is_property ? EntryType.Property : EntryType.Method)) == 0)
1856 PropertyInfo pi = null;
1857 MethodInfo mi = null;
1861 pi = (PropertyInfo) entry.Member;
1862 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1864 mi = (MethodInfo) entry.Member;
1865 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1869 // Check the arguments
1871 if (cmpAttrs.Length != paramTypes.Length)
1874 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
1875 if (!paramTypes [j].Equals (cmpAttrs [j]))
1880 // get one of the methods because this has the visibility info.
1883 mi = pi.GetGetMethod (true);
1885 mi = pi.GetSetMethod (true);
1891 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1892 case MethodAttributes.Private:
1894 // A private method is Ok if we are a nested subtype.
1895 // The spec actually is not very clear about this, see bug 52458.
1897 if (invocationType == entry.Container.Type ||
1898 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1899 return entry.Member;
1902 case MethodAttributes.FamANDAssem:
1903 case MethodAttributes.Assembly:
1905 // Check for assembly methods
1907 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1908 return entry.Member;
1913 // A protected method is ok, because we are overriding.
1914 // public is always ok.
1916 return entry.Member;