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 int CountTypeArguments {
56 if (TypeArguments == null)
59 return TypeArguments.Count;
63 public string GetFullName ()
66 if (TypeArguments != null)
67 full_name = Name + "<" + TypeArguments + ">";
71 return Left.GetFullName () + "." + full_name;
76 public string GetMemberName ()
80 return Left.GetFullName () + "." + Name;
85 public Expression GetTypeExpression (Location loc)
88 Expression lexpr = Left.GetTypeExpression (loc);
90 if (TypeArguments != null)
91 return new GenericMemberAccess (lexpr, Name, TypeArguments, loc);
93 return new MemberAccess (lexpr, Name, loc);
95 if (TypeArguments != null)
96 return new ConstructedType (Name, TypeArguments, loc);
98 return new SimpleName (Name, loc);
102 public override string ToString ()
105 if (TypeArguments != null)
106 full_name = Name + "<" + TypeArguments + ">";
111 return Left + "." + full_name;
118 /// Base representation for members. This is only used to keep track
119 /// of Name, Location and Modifier flags.
121 public abstract class MemberCore {
128 /// Modifier flags that the user specified in the source code
133 /// Location where this declaration happens
135 public readonly Location Location;
138 /// Attributes for this type
140 Attributes attributes;
142 public MemberCore (string name, Attributes attrs, Location loc)
149 public abstract bool Define (TypeContainer parent);
152 // Returns full member name for error message
154 public virtual string GetSignatureForError () {
158 public Attributes OptAttributes
169 // Whehter is it ok to use an unsafe pointer in this type container
171 public bool UnsafeOK (DeclSpace parent)
174 // First check if this MemberCore modifier flags has unsafe set
176 if ((ModFlags & Modifiers.UNSAFE) != 0)
179 if (parent.UnsafeContext)
182 Expression.UnsafeError (Location);
188 /// Base class for structs, classes, enumerations and interfaces.
191 /// They all create new declaration spaces. This
192 /// provides the common foundation for managing those name
195 public abstract class DeclSpace : MemberCore, IAlias {
197 /// This points to the actual definition that is being
198 /// created with System.Reflection.Emit
200 public TypeBuilder TypeBuilder;
203 /// If we are a generic type, this is the type we are
204 /// currently defining. We need to lookup members on this
205 /// instead of the TypeBuilder.
207 public TypeExpr CurrentType;
210 /// This variable tracks whether we have Closed the type
212 public bool Created = false;
215 // This is the namespace in which this typecontainer
216 // was declared. We use this to resolve names.
218 public NamespaceEntry NamespaceEntry;
220 public Hashtable Cache = new Hashtable ();
222 public string Basename;
225 /// defined_names is used for toplevel objects
227 protected Hashtable defined_names;
232 // Whether we are Generic
234 public bool IsGeneric {
238 else if (parent != null)
239 return parent.IsGeneric;
245 TypeContainer parent;
247 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
248 : base (name, attrs, l)
251 Basename = name.Substring (1 + name.LastIndexOf ('.'));
252 defined_names = new Hashtable ();
253 this.parent = parent;
256 public void RecordDecl ()
258 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
259 NamespaceEntry.DefineName (Basename, this);
263 /// The result value from adding an declaration into
264 /// a struct or a class
266 public enum AdditionResult {
268 /// The declaration has been successfully
269 /// added to the declation space.
274 /// The symbol has already been defined.
279 /// Returned if the declation being added to the
280 /// name space clashes with its container name.
282 /// The only exceptions for this are constructors
283 /// and static constructors
288 /// Returned if a constructor was created (because syntactically
289 /// it looked like a constructor) but was not (because the name
290 /// of the method is not the same as the container class
295 /// This is only used by static constructors to emit the
296 /// error 111, but this error for other things really
297 /// happens at another level for other functions.
302 /// Some other error.
308 /// Returns a status code based purely on the name
309 /// of the member being added
311 protected AdditionResult IsValid (string basename, string name)
313 if (basename == Basename)
314 return AdditionResult.EnclosingClash;
316 if (defined_names.Contains (name))
317 return AdditionResult.NameExists;
319 return AdditionResult.Success;
322 public static int length;
323 public static int small;
326 /// Introduce @name into this declaration space and
327 /// associates it with the object @o. Note that for
328 /// methods this will just point to the first method. o
330 public void DefineName (string name, object o)
332 defined_names.Add (name, o);
335 int p = name.LastIndexOf ('.');
343 /// Returns the object associated with a given name in the declaration
344 /// space. This is the inverse operation of `DefineName'
346 public object GetDefinition (string name)
348 return defined_names [name];
351 bool in_transit = false;
354 /// This function is used to catch recursive definitions
357 public bool InTransit {
367 public TypeContainer Parent {
374 /// Looks up the alias for the name
376 public IAlias LookupAlias (string name)
378 if (NamespaceEntry != null)
379 return NamespaceEntry.LookupAlias (name);
385 // root_types contains all the types. All TopLevel types
386 // hence have a parent that points to `root_types', that is
387 // why there is a non-obvious test down here.
389 public bool IsTopLevel {
392 if (parent.parent == null)
399 public virtual void CloseType ()
403 TypeBuilder.CreateType ();
406 // The try/catch is needed because
407 // nested enumerations fail to load when they
410 // Even if this is the right order (enumerations
411 // declared after types).
413 // Note that this still creates the type and
414 // it is possible to save it
421 /// Should be overriten by the appropriate declaration space
423 public abstract TypeBuilder DefineType ();
426 /// Define all members, but don't apply any attributes or do anything which may
427 /// access not-yet-defined classes. This method also creates the MemberCache.
429 public abstract bool DefineMembers (TypeContainer parent);
432 // Whether this is an `unsafe context'
434 public bool UnsafeContext {
436 if ((ModFlags & Modifiers.UNSAFE) != 0)
439 return parent.UnsafeContext;
444 public static string MakeFQN (string nsn, string name)
448 return String.Concat (nsn, ".", name);
451 EmitContext type_resolve_ec;
452 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
454 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
455 type_resolve_ec.ResolvingTypeTree = true;
457 return type_resolve_ec;
461 // Looks up the type, as parsed into the expression `e'
463 public Type ResolveType (Expression e, bool silent, Location loc)
465 TypeExpr d = ResolveTypeExpr (e, silent, loc);
469 return ResolveType (d, loc);
472 public Type ResolveType (TypeExpr d, Location loc)
474 if (!d.CheckAccessLevel (this)) {
475 Report. Error (122, loc, "`" + d.Name + "' " +
476 "is inaccessible because of its protection level");
480 Type t = d.ResolveType (type_resolve_ec);
484 TypeContainer tc = TypeManager.LookupTypeContainer (t);
485 if ((tc != null) && tc.IsGeneric) {
487 int tnum = TypeManager.GetNumberOfTypeArguments (t);
488 Report.Error (305, loc,
489 "Using the generic type `{0}' " +
490 "requires {1} type arguments",
491 TypeManager.GetFullName (t), tnum);
495 ConstructedType ctype = new ConstructedType (
496 t, TypeParameters, loc);
498 t = ctype.ResolveType (type_resolve_ec);
505 // Resolves the expression `e' for a type, and will recursively define
508 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
510 if (type_resolve_ec == null)
511 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
512 type_resolve_ec.loc = loc;
513 if (this is GenericMethod)
514 type_resolve_ec.ContainerType = Parent.TypeBuilder;
516 type_resolve_ec.ContainerType = TypeBuilder;
518 int errors = Report.Errors;
520 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
522 if ((d != null) && (d.eclass == ExprClass.Type))
525 if (silent || (Report.Errors != errors))
528 if (e is SimpleName){
529 SimpleName s = new SimpleName (((SimpleName) e).Name, -1, loc);
530 d = s.ResolveAsTypeTerminal (type_resolve_ec);
532 if ((d == null) || (d.Type == null)) {
533 Report.Error (246, loc, "Cannot find type `{0}'", e);
537 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
540 Report.Error (308, loc,
541 "The non-generic type `{0}' cannot " +
542 "be used with type arguments.",
543 TypeManager.CSharpName (d.Type));
547 Report.Error (305, loc,
548 "Using the generic type `{0}' " +
549 "requires {1} type arguments",
550 TypeManager.GetFullName (d.Type), num_args);
554 Report.Error (246, loc, "Cannot find type `{0}'", e);
558 public bool CheckAccessLevel (Type check_type)
561 if (this is GenericMethod)
562 tb = Parent.TypeBuilder;
566 if (check_type.IsGenericInstance)
567 check_type = check_type.GetGenericTypeDefinition ();
569 if (check_type == tb)
572 if (check_type.IsGenericParameter)
573 return true; // FIXME
575 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
578 // Broken Microsoft runtime, return public for arrays, no matter what
579 // the accessibility is for their underlying class, and they return
580 // NonPublic visibility for pointers
582 if (check_type.IsArray || check_type.IsPointer)
583 return CheckAccessLevel (TypeManager.GetElementType (check_type));
586 case TypeAttributes.Public:
589 case TypeAttributes.NotPublic:
591 // This test should probably use the declaringtype.
593 if (check_type.Assembly == tb.Assembly){
598 case TypeAttributes.NestedPublic:
601 case TypeAttributes.NestedPrivate:
602 string check_type_name = check_type.FullName;
603 string type_name = CurrentType != null ?
604 CurrentType.Name : tb.FullName;
606 int cio = check_type_name.LastIndexOf ('+');
607 string container = check_type_name.Substring (0, cio);
610 // Check if the check_type is a nested class of the current type
612 if (check_type_name.StartsWith (type_name + "+")){
616 if (type_name.StartsWith (container)){
622 case TypeAttributes.NestedFamily:
624 // Only accessible to methods in current type or any subtypes
626 return FamilyAccessible (tb, check_type);
628 case TypeAttributes.NestedFamANDAssem:
629 return (check_type.Assembly == tb.Assembly) &&
630 FamilyAccessible (tb, check_type);
632 case TypeAttributes.NestedFamORAssem:
633 return (check_type.Assembly == tb.Assembly) ||
634 FamilyAccessible (tb, check_type);
636 case TypeAttributes.NestedAssembly:
637 return check_type.Assembly == tb.Assembly;
640 Console.WriteLine ("HERE: " + check_attr);
645 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
647 Type declaring = check_type.DeclaringType;
648 if (tb.IsSubclassOf (declaring))
651 string check_type_name = check_type.FullName;
653 int cio = check_type_name.LastIndexOf ('+');
654 string container = check_type_name.Substring (0, cio);
657 // Check if the check_type is a nested class of the current type
659 if (check_type_name.StartsWith (container + "+"))
665 // Access level of a type.
667 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
668 // Public Assembly Protected
669 Protected = (0 << 0) | (0 << 1) | (X << 2),
670 Public = (X << 0) | (X << 1) | (X << 2),
671 Private = (0 << 0) | (0 << 1) | (0 << 2),
672 Internal = (0 << 0) | (X << 1) | (0 << 2),
673 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
676 static AccessLevel GetAccessLevelFromModifiers (int flags)
678 if ((flags & Modifiers.INTERNAL) != 0) {
680 if ((flags & Modifiers.PROTECTED) != 0)
681 return AccessLevel.ProtectedOrInternal;
683 return AccessLevel.Internal;
685 } else if ((flags & Modifiers.PROTECTED) != 0)
686 return AccessLevel.Protected;
687 else if ((flags & Modifiers.PRIVATE) != 0)
688 return AccessLevel.Private;
690 return AccessLevel.Public;
693 // What is the effective access level of this?
695 AccessLevel EffectiveAccessLevel {
697 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
698 if (!IsTopLevel && (Parent != null))
699 return myAccess & Parent.EffectiveAccessLevel;
704 // Return the access level for type `t'
705 static AccessLevel TypeEffectiveAccessLevel (Type t)
708 return AccessLevel.Public;
709 if (t.IsNestedPrivate)
710 return AccessLevel.Private;
712 return AccessLevel.Internal;
714 // By now, it must be nested
715 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
717 if (t.IsNestedPublic)
719 if (t.IsNestedAssembly)
720 return parentLevel & AccessLevel.Internal;
721 if (t.IsNestedFamily)
722 return parentLevel & AccessLevel.Protected;
723 if (t.IsNestedFamORAssem)
724 return parentLevel & AccessLevel.ProtectedOrInternal;
725 if (t.IsNestedFamANDAssem)
726 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
728 // nested private is taken care of
730 throw new Exception ("I give up, what are you?");
734 // This answers `is the type P, as accessible as a member M which has the
735 // accessability @flags which is declared as a nested member of the type T, this declspace'
737 public bool AsAccessible (Type p, int flags)
739 if (p.IsGenericParameter)
740 return true; // FIXME
743 // 1) if M is private, its accessability is the same as this declspace.
744 // we already know that P is accessible to T before this method, so we
748 if ((flags & Modifiers.PRIVATE) != 0)
751 while (p.IsArray || p.IsPointer || p.IsByRef)
752 p = TypeManager.GetElementType (p);
754 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
755 AccessLevel mAccess = this.EffectiveAccessLevel &
756 GetAccessLevelFromModifiers (flags);
758 // for every place from which we can access M, we must
759 // be able to access P as well. So, we want
760 // For every bit in M and P, M_i -> P_1 == true
761 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
763 return ~ (~ mAccess | pAccess) == 0;
766 static DoubleHash dh = new DoubleHash (1000);
768 Type DefineTypeAndParents (DeclSpace tc)
770 DeclSpace container = tc.Parent;
772 if (container.TypeBuilder == null && container.Name != "")
773 DefineTypeAndParents (container);
775 return tc.DefineType ();
778 Type LookupInterfaceOrClass (string ns, string name, out bool error)
786 if (dh.Lookup (ns, name, out r))
790 if (Namespace.IsNamespace (ns)){
791 string fullname = (ns != "") ? ns + "." + name : name;
792 t = TypeManager.LookupType (fullname);
796 t = TypeManager.LookupType (name);
800 dh.Insert (ns, name, t);
805 // In case we are fed a composite name, normalize it.
807 int p = name.LastIndexOf ('.');
809 ns = MakeFQN (ns, name.Substring (0, p));
810 name = name.Substring (p+1);
813 parent = RootContext.Tree.LookupByNamespace (ns, name);
814 if (parent == null) {
815 dh.Insert (ns, name, null);
819 t = DefineTypeAndParents (parent);
825 dh.Insert (ns, name, t);
829 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
831 Report.Error (104, loc,
832 "`{0}' is an ambiguous reference ({1} or {2})",
836 public Type FindNestedType (Location loc, string name,
837 out DeclSpace containing_ds)
842 containing_ds = this;
843 while (containing_ds != null){
844 Type container_type = containing_ds.TypeBuilder;
845 Type current_type = container_type;
847 while (current_type != null && current_type != TypeManager.object_type) {
848 string pre = current_type.FullName;
850 t = LookupInterfaceOrClass (pre, name, out error);
854 if ((t != null) && containing_ds.CheckAccessLevel (t))
857 current_type = current_type.BaseType;
859 containing_ds = containing_ds.Parent;
866 /// GetType is used to resolve type names at the DeclSpace level.
867 /// Use this to lookup class/struct bases, interface bases or
868 /// delegate type references
872 /// Contrast this to LookupType which is used inside method bodies to
873 /// lookup types that have already been defined. GetType is used
874 /// during the tree resolution process and potentially define
875 /// recursively the type
877 public Type FindType (Location loc, string name, int num_type_args)
883 // For the case the type we are looking for is nested within this one
884 // or is in any base class
886 DeclSpace containing_ds = this;
888 while (containing_ds != null){
889 Type container_type = containing_ds.TypeBuilder;
890 Type current_type = container_type;
892 while (current_type != null && current_type != TypeManager.object_type) {
893 string pre = current_type.FullName;
895 t = LookupInterfaceOrClass (pre, name, out error);
900 containing_ds.CheckAccessLevel (t) &&
901 TypeManager.CheckGeneric (t, num_type_args))
904 current_type = current_type.BaseType;
906 containing_ds = containing_ds.Parent;
910 // Attempt to lookup the class on our namespace and all it's implicit parents
912 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
913 t = LookupInterfaceOrClass (ns.FullName, name, out error);
917 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
922 // Attempt to do a direct unqualified lookup
924 t = LookupInterfaceOrClass ("", name, out error);
928 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
932 // Attempt to lookup the class on any of the `using'
936 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
938 t = LookupInterfaceOrClass (ns.FullName, name, out error);
942 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
946 // Now check the using clause list
949 foreach (Namespace using_ns in ns.GetUsingTable ()) {
950 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
954 if ((match != null) &&
955 TypeManager.CheckGeneric (match, num_type_args)) {
957 if (CheckAccessLevel (match)) {
958 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
967 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
971 //Report.Error (246, Location, "Can not find type `"+name+"'");
976 /// This function is broken and not what you're looking for. It should only
977 /// be used while the type is still being created since it doesn't use the cache
978 /// and relies on the filter doing the member name check.
980 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
981 MemberFilter filter, object criteria);
984 /// If we have a MemberCache, return it. This property may return null if the
985 /// class doesn't have a member cache or while it's still being created.
987 public abstract MemberCache MemberCache {
992 // Extensions for generics
994 TypeParameter[] type_params;
995 TypeParameter[] type_param_list;
997 protected string GetInstantiationName ()
999 StringBuilder sb = new StringBuilder (Name);
1001 for (int i = 0; i < type_param_list.Length; i++) {
1004 sb.Append (type_param_list [i].Name);
1007 return sb.ToString ();
1010 bool check_type_parameter (ArrayList list, int start, string name)
1012 for (int i = 0; i < start; i++) {
1013 TypeParameter param = (TypeParameter) list [i];
1015 if (param.Name != name)
1018 if (RootContext.WarningLevel >= 3)
1021 "Type parameter `{0}' has same name " +
1022 "as type parameter from outer type `{1}'",
1023 name, parent.GetInstantiationName ());
1031 TypeParameter[] initialize_type_params ()
1033 if (type_param_list != null)
1034 return type_param_list;
1036 DeclSpace the_parent = parent;
1037 if (this is GenericMethod)
1038 the_parent = the_parent.Parent;
1041 TypeParameter[] parent_params = null;
1042 if ((the_parent != null) && the_parent.IsGeneric) {
1043 parent_params = the_parent.initialize_type_params ();
1044 start = parent_params != null ? parent_params.Length : 0;
1047 ArrayList list = new ArrayList ();
1048 if (parent_params != null)
1049 list.AddRange (parent_params);
1051 int count = type_params != null ? type_params.Length : 0;
1052 for (int i = 0; i < count; i++) {
1053 TypeParameter param = type_params [i];
1054 check_type_parameter (list, start, param.Name);
1058 type_param_list = new TypeParameter [list.Count];
1059 list.CopyTo (type_param_list, 0);
1060 return type_param_list;
1064 /// Called by the parser to configure the type_parameter_list for this
1065 /// declaration space
1067 public AdditionResult SetParameterInfo (TypeArguments args,
1068 ArrayList constraints_list)
1070 string[] type_parameter_list = args.GetDeclarations ();
1071 if (type_parameter_list == null)
1072 return AdditionResult.Error;
1074 return SetParameterInfo (type_parameter_list, constraints_list);
1077 public AdditionResult SetParameterInfo (IList type_parameter_list,
1078 ArrayList constraints_list)
1080 type_params = new TypeParameter [type_parameter_list.Count];
1083 // Mark this type as Generic
1088 // Register all the names
1090 for (int i = 0; i < type_parameter_list.Count; i++) {
1091 string name = (string) type_parameter_list [i];
1093 AdditionResult res = IsValid (name, name);
1095 if (res != AdditionResult.Success)
1098 Constraints constraints = null;
1099 if (constraints_list != null) {
1100 foreach (Constraints constraint in constraints_list) {
1101 if (constraint.TypeParameter == name) {
1102 constraints = constraint;
1108 type_params [i] = new TypeParameter (name, constraints, Location);
1110 DefineName (name, type_params [i]);
1113 return AdditionResult.Success;
1116 public TypeParameter[] TypeParameters {
1119 throw new InvalidOperationException ();
1120 if (type_param_list == null)
1121 initialize_type_params ();
1123 return type_param_list;
1127 protected TypeParameter[] CurrentTypeParameters {
1130 throw new InvalidOperationException ();
1131 if (type_params != null)
1134 return new TypeParameter [0];
1138 public int CountTypeParameters {
1142 if (type_param_list == null)
1143 initialize_type_params ();
1145 return type_param_list.Length;
1149 public TypeParameterExpr LookupGeneric (string name, Location loc)
1154 foreach (TypeParameter type_param in CurrentTypeParameters) {
1155 if (type_param.Name != name)
1158 return new TypeParameterExpr (type_param, loc);
1162 return parent.LookupGeneric (name, loc);
1167 bool IAlias.IsType {
1168 get { return true; }
1171 string IAlias.Name {
1172 get { return Name; }
1175 TypeExpr IAlias.Type
1178 if (TypeBuilder == null)
1179 throw new InvalidOperationException ();
1181 if (CurrentType != null)
1184 return new TypeExpression (TypeBuilder, Location);
1190 /// This is a readonly list of MemberInfo's.
1192 public class MemberList : IList {
1193 public readonly IList List;
1197 /// Create a new MemberList from the given IList.
1199 public MemberList (IList list)
1204 this.List = new ArrayList ();
1209 /// Concatenate the ILists `first' and `second' to a new MemberList.
1211 public MemberList (IList first, IList second)
1213 ArrayList list = new ArrayList ();
1214 list.AddRange (first);
1215 list.AddRange (second);
1220 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1223 /// Cast the MemberList into a MemberInfo[] array.
1226 /// This is an expensive operation, only use it if it's really necessary.
1228 public static explicit operator MemberInfo [] (MemberList list)
1230 Timer.StartTimer (TimerType.MiscTimer);
1231 MemberInfo [] result = new MemberInfo [list.Count];
1232 list.CopyTo (result, 0);
1233 Timer.StopTimer (TimerType.MiscTimer);
1245 public bool IsSynchronized {
1247 return List.IsSynchronized;
1251 public object SyncRoot {
1253 return List.SyncRoot;
1257 public void CopyTo (Array array, int index)
1259 List.CopyTo (array, index);
1264 public IEnumerator GetEnumerator ()
1266 return List.GetEnumerator ();
1271 public bool IsFixedSize {
1277 public bool IsReadOnly {
1283 object IList.this [int index] {
1285 return List [index];
1289 throw new NotSupportedException ();
1293 // FIXME: try to find out whether we can avoid the cast in this indexer.
1294 public MemberInfo this [int index] {
1296 return (MemberInfo) List [index];
1300 public int Add (object value)
1302 throw new NotSupportedException ();
1305 public void Clear ()
1307 throw new NotSupportedException ();
1310 public bool Contains (object value)
1312 return List.Contains (value);
1315 public int IndexOf (object value)
1317 return List.IndexOf (value);
1320 public void Insert (int index, object value)
1322 throw new NotSupportedException ();
1325 public void Remove (object value)
1327 throw new NotSupportedException ();
1330 public void RemoveAt (int index)
1332 throw new NotSupportedException ();
1337 /// This interface is used to get all members of a class when creating the
1338 /// member cache. It must be implemented by all DeclSpace derivatives which
1339 /// want to support the member cache and by TypeHandle to get caching of
1340 /// non-dynamic types.
1342 public interface IMemberContainer {
1344 /// The name of the IMemberContainer. This is only used for
1345 /// debugging purposes.
1352 /// The type of this IMemberContainer.
1359 /// Returns the IMemberContainer of the parent class or null if this
1360 /// is an interface or TypeManger.object_type.
1361 /// This is used when creating the member cache for a class to get all
1362 /// members from the parent class.
1364 IMemberContainer Parent {
1369 /// Whether this is an interface.
1376 /// Returns all members of this class with the corresponding MemberTypes
1377 /// and BindingFlags.
1380 /// When implementing this method, make sure not to return any inherited
1381 /// members and check the MemberTypes and BindingFlags properly.
1382 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1383 /// get the BindingFlags (static/non-static,public/non-public) in the
1384 /// MemberInfo class, but the cache needs this information. That's why
1385 /// this method is called multiple times with different BindingFlags.
1387 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1390 /// Return the container's member cache.
1392 MemberCache MemberCache {
1398 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1399 /// member lookups. It has a member name based hash table; it maps each member
1400 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1401 /// and the BindingFlags that were initially used to get it. The cache contains
1402 /// all members of the current class and all inherited members. If this cache is
1403 /// for an interface types, it also contains all inherited members.
1405 /// There are two ways to get a MemberCache:
1406 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1407 /// use the DeclSpace.MemberCache property.
1408 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1409 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1411 public class MemberCache {
1412 public readonly IMemberContainer Container;
1413 protected Hashtable member_hash;
1414 protected Hashtable method_hash;
1416 Hashtable interface_hash;
1419 /// Create a new MemberCache for the given IMemberContainer `container'.
1421 public MemberCache (IMemberContainer container)
1423 this.Container = container;
1425 Timer.IncrementCounter (CounterType.MemberCache);
1426 Timer.StartTimer (TimerType.CacheInit);
1430 // If we have a parent class (we have a parent class unless we're
1431 // TypeManager.object_type), we deep-copy its MemberCache here.
1432 if (Container.IsInterface) {
1434 interface_hash = new Hashtable ();
1436 if (Container.Parent != null)
1437 parent = Container.Parent.MemberCache;
1439 parent = TypeHandle.ObjectType.MemberCache;
1440 member_hash = SetupCacheForInterface (parent);
1441 } else if (Container.Parent != null)
1442 member_hash = SetupCache (Container.Parent.MemberCache);
1444 member_hash = new Hashtable ();
1446 // If this is neither a dynamic type nor an interface, create a special
1447 // method cache with all declared and inherited methods.
1448 Type type = container.Type;
1449 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1450 method_hash = new Hashtable ();
1454 // Add all members from the current class.
1455 AddMembers (Container);
1457 Timer.StopTimer (TimerType.CacheInit);
1461 /// Bootstrap this member cache by doing a deep-copy of our parent.
1463 Hashtable SetupCache (MemberCache parent)
1465 Hashtable hash = new Hashtable ();
1467 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1468 while (it.MoveNext ()) {
1469 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1477 /// Add the contents of `new_hash' to `hash'.
1479 void AddHashtable (Hashtable hash, Hashtable new_hash)
1481 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1482 while (it.MoveNext ()) {
1483 ArrayList list = (ArrayList) hash [it.Key];
1485 list.AddRange ((ArrayList) it.Value);
1487 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1492 /// Bootstrap the member cache for an interface type.
1493 /// Type.GetMembers() won't return any inherited members for interface types,
1494 /// so we need to do this manually. Interfaces also inherit from System.Object.
1496 Hashtable SetupCacheForInterface (MemberCache parent)
1498 Hashtable hash = SetupCache (parent);
1499 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1501 foreach (TypeExpr iface in ifaces) {
1502 Type itype = iface.Type;
1504 if (interface_hash.Contains (itype))
1507 interface_hash [itype] = null;
1509 IMemberContainer iface_container =
1510 TypeManager.LookupMemberContainer (itype);
1512 MemberCache iface_cache = iface_container.MemberCache;
1514 AddHashtable (hash, iface_cache.member_hash);
1516 if (iface_cache.interface_hash == null)
1519 foreach (Type parent_contains in iface_cache.interface_hash.Keys)
1520 interface_hash [parent_contains] = null;
1527 /// Add all members from class `container' to the cache.
1529 void AddMembers (IMemberContainer container)
1531 // We need to call AddMembers() with a single member type at a time
1532 // to get the member type part of CacheEntry.EntryType right.
1533 AddMembers (MemberTypes.Constructor, container);
1534 AddMembers (MemberTypes.Field, container);
1535 AddMembers (MemberTypes.Method, container);
1536 AddMembers (MemberTypes.Property, container);
1537 AddMembers (MemberTypes.Event, container);
1538 // Nested types are returned by both Static and Instance searches.
1539 AddMembers (MemberTypes.NestedType,
1540 BindingFlags.Static | BindingFlags.Public, container);
1541 AddMembers (MemberTypes.NestedType,
1542 BindingFlags.Static | BindingFlags.NonPublic, container);
1545 void AddMembers (MemberTypes mt, IMemberContainer container)
1547 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1548 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1549 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1550 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1554 /// Add all members from class `container' with the requested MemberTypes and
1555 /// BindingFlags to the cache. This method is called multiple times with different
1556 /// MemberTypes and BindingFlags.
1558 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1560 MemberList members = container.GetMembers (mt, bf);
1562 foreach (MemberInfo member in members) {
1563 string name = member.Name;
1565 int pos = name.IndexOf ('<');
1567 name = name.Substring (0, pos);
1569 // We use a name-based hash table of ArrayList's.
1570 ArrayList list = (ArrayList) member_hash [name];
1572 list = new ArrayList ();
1573 member_hash.Add (name, list);
1576 // When this method is called for the current class, the list will
1577 // already contain all inherited members from our parent classes.
1578 // We cannot add new members in front of the list since this'd be an
1579 // expensive operation, that's why the list is sorted in reverse order
1580 // (ie. members from the current class are coming last).
1581 list.Add (new CacheEntry (container, member, mt, bf));
1586 /// Add all declared and inherited methods from class `type' to the method cache.
1588 void AddMethods (Type type)
1590 AddMethods (BindingFlags.Static | BindingFlags.Public |
1591 BindingFlags.FlattenHierarchy, type);
1592 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1593 BindingFlags.FlattenHierarchy, type);
1594 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1595 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1598 void AddMethods (BindingFlags bf, Type type)
1600 MemberInfo [] members = type.GetMethods (bf);
1602 Array.Reverse (members);
1604 foreach (MethodBase member in members) {
1605 string name = member.Name;
1607 // Varargs methods aren't allowed in C# code.
1608 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1611 // We use a name-based hash table of ArrayList's.
1612 ArrayList list = (ArrayList) method_hash [name];
1614 list = new ArrayList ();
1615 method_hash.Add (name, list);
1618 // Unfortunately, the elements returned by Type.GetMethods() aren't
1619 // sorted so we need to do this check for every member.
1620 BindingFlags new_bf = bf;
1621 if (member.DeclaringType == type)
1622 new_bf |= BindingFlags.DeclaredOnly;
1624 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1629 /// Compute and return a appropriate `EntryType' magic number for the given
1630 /// MemberTypes and BindingFlags.
1632 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1634 EntryType type = EntryType.None;
1636 if ((mt & MemberTypes.Constructor) != 0)
1637 type |= EntryType.Constructor;
1638 if ((mt & MemberTypes.Event) != 0)
1639 type |= EntryType.Event;
1640 if ((mt & MemberTypes.Field) != 0)
1641 type |= EntryType.Field;
1642 if ((mt & MemberTypes.Method) != 0)
1643 type |= EntryType.Method;
1644 if ((mt & MemberTypes.Property) != 0)
1645 type |= EntryType.Property;
1646 // Nested types are returned by static and instance searches.
1647 if ((mt & MemberTypes.NestedType) != 0)
1648 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1650 if ((bf & BindingFlags.Instance) != 0)
1651 type |= EntryType.Instance;
1652 if ((bf & BindingFlags.Static) != 0)
1653 type |= EntryType.Static;
1654 if ((bf & BindingFlags.Public) != 0)
1655 type |= EntryType.Public;
1656 if ((bf & BindingFlags.NonPublic) != 0)
1657 type |= EntryType.NonPublic;
1658 if ((bf & BindingFlags.DeclaredOnly) != 0)
1659 type |= EntryType.Declared;
1665 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1666 /// denote multiple member types. Returns true if the given flags value denotes a
1667 /// single member types.
1669 public static bool IsSingleMemberType (MemberTypes mt)
1672 case MemberTypes.Constructor:
1673 case MemberTypes.Event:
1674 case MemberTypes.Field:
1675 case MemberTypes.Method:
1676 case MemberTypes.Property:
1677 case MemberTypes.NestedType:
1686 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1687 /// number to speed up the searching process.
1690 protected enum EntryType {
1695 MaskStatic = Instance|Static,
1699 MaskProtection = Public|NonPublic,
1703 Constructor = 0x020,
1710 MaskType = Constructor|Event|Field|Method|Property|NestedType
1713 protected struct CacheEntry {
1714 public readonly IMemberContainer Container;
1715 public readonly EntryType EntryType;
1716 public readonly MemberInfo Member;
1718 public CacheEntry (IMemberContainer container, MemberInfo member,
1719 MemberTypes mt, BindingFlags bf)
1721 this.Container = container;
1722 this.Member = member;
1723 this.EntryType = GetEntryType (mt, bf);
1728 /// This is called each time we're walking up one level in the class hierarchy
1729 /// and checks whether we can abort the search since we've already found what
1730 /// we were looking for.
1732 protected bool DoneSearching (ArrayList list)
1735 // We've found exactly one member in the current class and it's not
1736 // a method or constructor.
1738 if (list.Count == 1 && !(list [0] is MethodBase))
1742 // Multiple properties: we query those just to find out the indexer
1745 if ((list.Count > 0) && (list [0] is PropertyInfo))
1752 /// Looks up members with name `name'. If you provide an optional
1753 /// filter function, it'll only be called with members matching the
1754 /// requested member name.
1756 /// This method will try to use the cache to do the lookup if possible.
1758 /// Unlike other FindMembers implementations, this method will always
1759 /// check all inherited members - even when called on an interface type.
1761 /// If you know that you're only looking for methods, you should use
1762 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1763 /// When doing a method-only search, it'll try to use a special method
1764 /// cache (unless it's a dynamic type or an interface) and the returned
1765 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1766 /// The lookup process will automatically restart itself in method-only
1767 /// search mode if it discovers that it's about to return methods.
1769 ArrayList global = new ArrayList ();
1770 bool using_global = false;
1772 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1773 MemberFilter filter, object criteria)
1776 throw new Exception ();
1778 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1779 bool method_search = mt == MemberTypes.Method;
1780 // If we have a method cache and we aren't already doing a method-only search,
1781 // then we restart a method search if the first match is a method.
1782 bool do_method_search = !method_search && (method_hash != null);
1784 ArrayList applicable;
1786 // If this is a method-only search, we try to use the method cache if
1787 // possible; a lookup in the method cache will return a MemberInfo with
1788 // the correct ReflectedType for inherited methods.
1790 if (method_search && (method_hash != null))
1791 applicable = (ArrayList) method_hash [name];
1793 applicable = (ArrayList) member_hash [name];
1795 if (applicable == null)
1796 return MemberList.Empty;
1799 // 32 slots gives 53 rss/54 size
1800 // 2/4 slots gives 55 rss
1802 // Strange: from 25,000 calls, only 1,800
1803 // are above 2. Why does this impact it?
1806 using_global = true;
1808 Timer.StartTimer (TimerType.CachedLookup);
1810 EntryType type = GetEntryType (mt, bf);
1812 IMemberContainer current = Container;
1814 // `applicable' is a list of all members with the given member name `name'
1815 // in the current class and all its parent classes. The list is sorted in
1816 // reverse order due to the way how the cache is initialy created (to speed
1817 // things up, we're doing a deep-copy of our parent).
1819 for (int i = applicable.Count-1; i >= 0; i--) {
1820 CacheEntry entry = (CacheEntry) applicable [i];
1822 // This happens each time we're walking one level up in the class
1823 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1824 // the first time this happens (this may already happen in the first
1825 // iteration of this loop if there are no members with the name we're
1826 // looking for in the current class).
1827 if (entry.Container != current) {
1828 if (declared_only || DoneSearching (global))
1831 current = entry.Container;
1834 // Is the member of the correct type ?
1835 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1838 // Is the member static/non-static ?
1839 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1842 // Apply the filter to it.
1843 if (filter (entry.Member, criteria)) {
1844 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1845 do_method_search = false;
1846 global.Add (entry.Member);
1850 Timer.StopTimer (TimerType.CachedLookup);
1852 // If we have a method cache and we aren't already doing a method-only
1853 // search, we restart in method-only search mode if the first match is
1854 // a method. This ensures that we return a MemberInfo with the correct
1855 // ReflectedType for inherited methods.
1856 if (do_method_search && (global.Count > 0)){
1857 using_global = false;
1859 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1862 using_global = false;
1863 MemberInfo [] copy = new MemberInfo [global.Count];
1864 global.CopyTo (copy);
1865 return new MemberList (copy);
1869 // This finds the method or property for us to override. invocationType is the type where
1870 // the override is going to be declared, name is the name of the method/property, and
1871 // paramTypes is the parameters, if any to the method or property
1873 // Because the MemberCache holds members from this class and all the base classes,
1874 // we can avoid tons of reflection stuff.
1876 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1878 ArrayList applicable;
1879 if (method_hash != null && !is_property)
1880 applicable = (ArrayList) method_hash [name];
1882 applicable = (ArrayList) member_hash [name];
1884 if (applicable == null)
1887 // Walk the chain of methods, starting from the top.
1889 for (int i = applicable.Count - 1; i >= 0; i--) {
1890 CacheEntry entry = (CacheEntry) applicable [i];
1892 if ((entry.EntryType & (is_property ? EntryType.Property : EntryType.Method)) == 0)
1895 PropertyInfo pi = null;
1896 MethodInfo mi = null;
1900 pi = (PropertyInfo) entry.Member;
1901 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1903 mi = (MethodInfo) entry.Member;
1904 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1908 // Check the arguments
1910 if (cmpAttrs.Length != paramTypes.Length)
1913 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
1914 if (!paramTypes [j].Equals (cmpAttrs [j]))
1919 // get one of the methods because this has the visibility info.
1922 mi = pi.GetGetMethod (true);
1924 mi = pi.GetSetMethod (true);
1930 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1931 case MethodAttributes.Private:
1933 // A private method is Ok if we are a nested subtype.
1934 // The spec actually is not very clear about this, see bug 52458.
1936 if (invocationType == entry.Container.Type ||
1937 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1938 return entry.Member;
1941 case MethodAttributes.FamANDAssem:
1942 case MethodAttributes.Assembly:
1944 // Check for assembly methods
1946 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1947 return entry.Member;
1952 // A protected method is ok, because we are overriding.
1953 // public is always ok.
1955 return entry.Member;