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 TypeName {
22 public readonly string Name;
23 public readonly TypeArguments TypeArguments;
25 public readonly TypeName Left;
27 public static readonly TypeName Null = new TypeName ("");
29 public TypeName (string name)
34 public TypeName (string name, TypeArguments args)
37 this.TypeArguments = args;
40 public TypeName (TypeName 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 GetTypeName ()
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 MemberName GetMemberName ()
104 if (TypeArguments != null) {
105 string[] type_params = TypeArguments.GetDeclarations ();
106 return new MemberName (Left, Name, type_params);
108 return new MemberName (Left, Name);
111 public override string ToString ()
114 if (TypeArguments != null)
115 full_name = Name + "<" + TypeArguments + ">";
120 return Left + "." + full_name;
126 public class MemberName {
127 public readonly TypeName TypeName;
128 public readonly string Name;
129 public readonly string[] TypeParameters;
131 public MemberName (string name)
136 public MemberName (TypeName type, string name)
138 this.TypeName = type;
142 public MemberName (string type, MemberName name)
144 this.TypeName = new TypeName (type);
145 this.Name = name.Name;
146 this.TypeParameters = name.TypeParameters;
149 public MemberName (TypeName type, string name, ArrayList type_params)
152 if (type_params != null) {
153 TypeParameters = new string [type_params.Count];
154 type_params.CopyTo (TypeParameters, 0);
158 public MemberName (TypeName type, string name, string[] type_params)
161 this.TypeParameters = type_params;
164 public static readonly MemberName Null = new MemberName ("");
166 public string GetMemberName ()
169 if (TypeName != null)
170 return TypeName.GetFullName () + "." + Name;
175 public static explicit operator string (MemberName name)
177 if (name.TypeName != null)
178 return name.TypeName + "." + name.Name;
183 public override string ToString ()
186 if (TypeParameters != null) {
187 StringBuilder sb = new StringBuilder ();
190 for (int i = 0; i < TypeParameters.Length; i++) {
193 sb.Append (TypeParameters [i]);
196 full_name = sb.ToString ();
200 if (TypeName != null)
201 return TypeName + "." + full_name;
208 /// Base representation for members. This is only used to keep track
209 /// of Name, Location and Modifier flags.
211 public abstract class MemberCore {
217 public readonly MemberName MemberName;
220 /// Modifier flags that the user specified in the source code
225 /// Location where this declaration happens
227 public readonly Location Location;
230 /// Attributes for this type
232 Attributes attributes;
234 public MemberCore (MemberName name, Attributes attrs, Location loc)
236 Name = (string) name;
242 public abstract bool Define (TypeContainer parent);
245 // Returns full member name for error message
247 public virtual string GetSignatureForError () {
251 public Attributes OptAttributes
262 // Whehter is it ok to use an unsafe pointer in this type container
264 public bool UnsafeOK (DeclSpace parent)
267 // First check if this MemberCore modifier flags has unsafe set
269 if ((ModFlags & Modifiers.UNSAFE) != 0)
272 if (parent.UnsafeContext)
275 Expression.UnsafeError (Location);
281 /// Base class for structs, classes, enumerations and interfaces.
284 /// They all create new declaration spaces. This
285 /// provides the common foundation for managing those name
288 public abstract class DeclSpace : MemberCore, IAlias {
290 /// This points to the actual definition that is being
291 /// created with System.Reflection.Emit
293 public TypeBuilder TypeBuilder;
296 /// If we are a generic type, this is the type we are
297 /// currently defining. We need to lookup members on this
298 /// instead of the TypeBuilder.
300 public TypeExpr CurrentType;
303 /// This variable tracks whether we have Closed the type
305 public bool Created = false;
308 // This is the namespace in which this typecontainer
309 // was declared. We use this to resolve names.
311 public NamespaceEntry NamespaceEntry;
313 public Hashtable Cache = new Hashtable ();
315 public string Basename;
318 /// defined_names is used for toplevel objects
320 protected Hashtable defined_names;
322 readonly bool is_generic;
325 // Whether we are Generic
327 public bool IsGeneric {
331 else if (parent != null)
332 return parent.IsGeneric;
338 TypeContainer parent;
340 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
341 Attributes attrs, Location l)
342 : base (name, attrs, l)
345 Basename = name.Name;
346 defined_names = new Hashtable ();
347 if (name.TypeParameters != null)
349 this.parent = parent;
352 public void RecordDecl ()
354 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
355 NamespaceEntry.DefineName (Basename, this);
359 /// The result value from adding an declaration into
360 /// a struct or a class
362 public enum AdditionResult {
364 /// The declaration has been successfully
365 /// added to the declation space.
370 /// The symbol has already been defined.
375 /// Returned if the declation being added to the
376 /// name space clashes with its container name.
378 /// The only exceptions for this are constructors
379 /// and static constructors
384 /// Returned if a constructor was created (because syntactically
385 /// it looked like a constructor) but was not (because the name
386 /// of the method is not the same as the container class
391 /// This is only used by static constructors to emit the
392 /// error 111, but this error for other things really
393 /// happens at another level for other functions.
398 /// Some other error.
404 /// Returns a status code based purely on the name
405 /// of the member being added
407 protected AdditionResult IsValid (string basename, string name)
409 if (basename == Basename)
410 return AdditionResult.EnclosingClash;
412 if (defined_names.Contains (name))
413 return AdditionResult.NameExists;
415 return AdditionResult.Success;
418 public static int length;
419 public static int small;
422 /// Introduce @name into this declaration space and
423 /// associates it with the object @o. Note that for
424 /// methods this will just point to the first method. o
426 public void DefineName (string name, object o)
428 defined_names.Add (name, o);
431 int p = name.LastIndexOf ('.');
439 /// Returns the object associated with a given name in the declaration
440 /// space. This is the inverse operation of `DefineName'
442 public object GetDefinition (string name)
444 return defined_names [name];
447 bool in_transit = false;
450 /// This function is used to catch recursive definitions
453 public bool InTransit {
463 public TypeContainer Parent {
470 /// Looks up the alias for the name
472 public IAlias LookupAlias (string name)
474 if (NamespaceEntry != null)
475 return NamespaceEntry.LookupAlias (name);
481 // root_types contains all the types. All TopLevel types
482 // hence have a parent that points to `root_types', that is
483 // why there is a non-obvious test down here.
485 public bool IsTopLevel {
488 if (parent.parent == null)
495 public virtual void CloseType ()
499 TypeBuilder.CreateType ();
502 // The try/catch is needed because
503 // nested enumerations fail to load when they
506 // Even if this is the right order (enumerations
507 // declared after types).
509 // Note that this still creates the type and
510 // it is possible to save it
517 /// Should be overriten by the appropriate declaration space
519 public abstract TypeBuilder DefineType ();
522 /// Define all members, but don't apply any attributes or do anything which may
523 /// access not-yet-defined classes. This method also creates the MemberCache.
525 public abstract bool DefineMembers (TypeContainer parent);
528 // Whether this is an `unsafe context'
530 public bool UnsafeContext {
532 if ((ModFlags & Modifiers.UNSAFE) != 0)
535 return parent.UnsafeContext;
540 public static string MakeFQN (string nsn, string name)
544 return String.Concat (nsn, ".", name);
547 EmitContext type_resolve_ec;
548 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
550 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
551 type_resolve_ec.ResolvingTypeTree = true;
553 return type_resolve_ec;
557 // Looks up the type, as parsed into the expression `e'
559 public Type ResolveType (Expression e, bool silent, Location loc)
561 TypeExpr d = ResolveTypeExpr (e, silent, loc);
565 return ResolveType (d, loc);
568 public Type ResolveType (TypeExpr d, Location loc)
570 if (!d.CheckAccessLevel (this)) {
571 Report. Error (122, loc, "`" + d.Name + "' " +
572 "is inaccessible because of its protection level");
576 Type t = d.ResolveType (type_resolve_ec);
580 TypeContainer tc = TypeManager.LookupTypeContainer (t);
581 if ((tc != null) && tc.IsGeneric) {
583 int tnum = TypeManager.GetNumberOfTypeArguments (t);
584 Report.Error (305, loc,
585 "Using the generic type `{0}' " +
586 "requires {1} type arguments",
587 TypeManager.GetFullName (t), tnum);
591 ConstructedType ctype = new ConstructedType (
592 t, TypeParameters, loc);
594 t = ctype.ResolveType (type_resolve_ec);
601 // Resolves the expression `e' for a type, and will recursively define
604 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
606 if (type_resolve_ec == null)
607 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
608 type_resolve_ec.loc = loc;
609 if (this is GenericMethod)
610 type_resolve_ec.ContainerType = Parent.TypeBuilder;
612 type_resolve_ec.ContainerType = TypeBuilder;
614 int errors = Report.Errors;
616 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
618 if ((d != null) && (d.eclass == ExprClass.Type))
621 if (silent || (Report.Errors != errors))
624 if (e is SimpleName){
625 SimpleName s = new SimpleName (((SimpleName) e).Name, -1, loc);
626 d = s.ResolveAsTypeTerminal (type_resolve_ec);
628 if ((d == null) || (d.Type == null)) {
629 Report.Error (246, loc, "Cannot find type `{0}'", e);
633 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
636 Report.Error (308, loc,
637 "The non-generic type `{0}' cannot " +
638 "be used with type arguments.",
639 TypeManager.CSharpName (d.Type));
643 Report.Error (305, loc,
644 "Using the generic type `{0}' " +
645 "requires {1} type arguments",
646 TypeManager.GetFullName (d.Type), num_args);
650 Report.Error (246, loc, "Cannot find type `{0}'", e);
654 public bool CheckAccessLevel (Type check_type)
657 if (this is GenericMethod)
658 tb = Parent.TypeBuilder;
662 if (check_type.IsGenericInstance)
663 check_type = check_type.GetGenericTypeDefinition ();
665 if (check_type == tb)
668 if (check_type.IsGenericParameter)
669 return true; // FIXME
671 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
674 // Broken Microsoft runtime, return public for arrays, no matter what
675 // the accessibility is for their underlying class, and they return
676 // NonPublic visibility for pointers
678 if (check_type.IsArray || check_type.IsPointer)
679 return CheckAccessLevel (TypeManager.GetElementType (check_type));
682 case TypeAttributes.Public:
685 case TypeAttributes.NotPublic:
687 // This test should probably use the declaringtype.
689 if (check_type.Assembly == tb.Assembly){
694 case TypeAttributes.NestedPublic:
697 case TypeAttributes.NestedPrivate:
698 string check_type_name = check_type.FullName;
699 string type_name = CurrentType != null ?
700 CurrentType.Name : tb.FullName;
702 int cio = check_type_name.LastIndexOf ('+');
703 string container = check_type_name.Substring (0, cio);
706 // Check if the check_type is a nested class of the current type
708 if (check_type_name.StartsWith (type_name + "+")){
712 if (type_name.StartsWith (container)){
718 case TypeAttributes.NestedFamily:
720 // Only accessible to methods in current type or any subtypes
722 return FamilyAccessible (tb, check_type);
724 case TypeAttributes.NestedFamANDAssem:
725 return (check_type.Assembly == tb.Assembly) &&
726 FamilyAccessible (tb, check_type);
728 case TypeAttributes.NestedFamORAssem:
729 return (check_type.Assembly == tb.Assembly) ||
730 FamilyAccessible (tb, check_type);
732 case TypeAttributes.NestedAssembly:
733 return check_type.Assembly == tb.Assembly;
736 Console.WriteLine ("HERE: " + check_attr);
741 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
743 Type declaring = check_type.DeclaringType;
744 if (tb.IsSubclassOf (declaring))
747 string check_type_name = check_type.FullName;
749 int cio = check_type_name.LastIndexOf ('+');
750 string container = check_type_name.Substring (0, cio);
753 // Check if the check_type is a nested class of the current type
755 if (check_type_name.StartsWith (container + "+"))
761 // Access level of a type.
763 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
764 // Public Assembly Protected
765 Protected = (0 << 0) | (0 << 1) | (X << 2),
766 Public = (X << 0) | (X << 1) | (X << 2),
767 Private = (0 << 0) | (0 << 1) | (0 << 2),
768 Internal = (0 << 0) | (X << 1) | (0 << 2),
769 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
772 static AccessLevel GetAccessLevelFromModifiers (int flags)
774 if ((flags & Modifiers.INTERNAL) != 0) {
776 if ((flags & Modifiers.PROTECTED) != 0)
777 return AccessLevel.ProtectedOrInternal;
779 return AccessLevel.Internal;
781 } else if ((flags & Modifiers.PROTECTED) != 0)
782 return AccessLevel.Protected;
783 else if ((flags & Modifiers.PRIVATE) != 0)
784 return AccessLevel.Private;
786 return AccessLevel.Public;
789 // What is the effective access level of this?
791 AccessLevel EffectiveAccessLevel {
793 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
794 if (!IsTopLevel && (Parent != null))
795 return myAccess & Parent.EffectiveAccessLevel;
800 // Return the access level for type `t'
801 static AccessLevel TypeEffectiveAccessLevel (Type t)
804 return AccessLevel.Public;
805 if (t.IsNestedPrivate)
806 return AccessLevel.Private;
808 return AccessLevel.Internal;
810 // By now, it must be nested
811 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
813 if (t.IsNestedPublic)
815 if (t.IsNestedAssembly)
816 return parentLevel & AccessLevel.Internal;
817 if (t.IsNestedFamily)
818 return parentLevel & AccessLevel.Protected;
819 if (t.IsNestedFamORAssem)
820 return parentLevel & AccessLevel.ProtectedOrInternal;
821 if (t.IsNestedFamANDAssem)
822 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
824 // nested private is taken care of
826 throw new Exception ("I give up, what are you?");
830 // This answers `is the type P, as accessible as a member M which has the
831 // accessability @flags which is declared as a nested member of the type T, this declspace'
833 public bool AsAccessible (Type p, int flags)
835 if (p.IsGenericParameter)
836 return true; // FIXME
839 // 1) if M is private, its accessability is the same as this declspace.
840 // we already know that P is accessible to T before this method, so we
844 if ((flags & Modifiers.PRIVATE) != 0)
847 while (p.IsArray || p.IsPointer || p.IsByRef)
848 p = TypeManager.GetElementType (p);
850 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
851 AccessLevel mAccess = this.EffectiveAccessLevel &
852 GetAccessLevelFromModifiers (flags);
854 // for every place from which we can access M, we must
855 // be able to access P as well. So, we want
856 // For every bit in M and P, M_i -> P_1 == true
857 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
859 return ~ (~ mAccess | pAccess) == 0;
862 static DoubleHash dh = new DoubleHash (1000);
864 Type DefineTypeAndParents (DeclSpace tc)
866 DeclSpace container = tc.Parent;
868 if (container.TypeBuilder == null && container.Name != "")
869 DefineTypeAndParents (container);
871 return tc.DefineType ();
874 Type LookupInterfaceOrClass (string ns, string name, out bool error)
882 if (dh.Lookup (ns, name, out r))
886 if (Namespace.IsNamespace (ns)){
887 string fullname = (ns != "") ? ns + "." + name : name;
888 t = TypeManager.LookupType (fullname);
892 t = TypeManager.LookupType (name);
896 dh.Insert (ns, name, t);
901 // In case we are fed a composite name, normalize it.
903 int p = name.LastIndexOf ('.');
905 ns = MakeFQN (ns, name.Substring (0, p));
906 name = name.Substring (p+1);
909 parent = RootContext.Tree.LookupByNamespace (ns, name);
910 if (parent == null) {
911 dh.Insert (ns, name, null);
915 t = DefineTypeAndParents (parent);
921 dh.Insert (ns, name, t);
925 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
927 Report.Error (104, loc,
928 "`{0}' is an ambiguous reference ({1} or {2})",
932 public Type FindNestedType (Location loc, string name,
933 out DeclSpace containing_ds)
938 containing_ds = this;
939 while (containing_ds != null){
940 Type container_type = containing_ds.TypeBuilder;
941 Type current_type = container_type;
943 while (current_type != null && current_type != TypeManager.object_type) {
944 string pre = current_type.FullName;
946 t = LookupInterfaceOrClass (pre, name, out error);
950 if ((t != null) && containing_ds.CheckAccessLevel (t))
953 current_type = current_type.BaseType;
955 containing_ds = containing_ds.Parent;
962 /// GetType is used to resolve type names at the DeclSpace level.
963 /// Use this to lookup class/struct bases, interface bases or
964 /// delegate type references
968 /// Contrast this to LookupType which is used inside method bodies to
969 /// lookup types that have already been defined. GetType is used
970 /// during the tree resolution process and potentially define
971 /// recursively the type
973 public Type FindType (Location loc, string name, int num_type_args)
979 // For the case the type we are looking for is nested within this one
980 // or is in any base class
982 DeclSpace containing_ds = this;
984 while (containing_ds != null){
985 Type container_type = containing_ds.TypeBuilder;
986 Type current_type = container_type;
988 while (current_type != null && current_type != TypeManager.object_type) {
989 string pre = current_type.FullName;
991 t = LookupInterfaceOrClass (pre, name, out error);
996 containing_ds.CheckAccessLevel (t) &&
997 TypeManager.CheckGeneric (t, num_type_args))
1000 current_type = current_type.BaseType;
1002 containing_ds = containing_ds.Parent;
1006 // Attempt to lookup the class on our namespace and all it's implicit parents
1008 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1009 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1013 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
1018 // Attempt to do a direct unqualified lookup
1020 t = LookupInterfaceOrClass ("", name, out error);
1024 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
1028 // Attempt to lookup the class on any of the `using'
1032 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1034 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1038 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
1042 // Now check the using clause list
1045 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1046 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1050 if ((match != null) &&
1051 TypeManager.CheckGeneric (match, num_type_args)) {
1053 if (CheckAccessLevel (match)) {
1054 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1063 if ((t != null) && TypeManager.CheckGeneric (t, num_type_args))
1067 //Report.Error (246, Location, "Can not find type `"+name+"'");
1072 /// This function is broken and not what you're looking for. It should only
1073 /// be used while the type is still being created since it doesn't use the cache
1074 /// and relies on the filter doing the member name check.
1076 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1077 MemberFilter filter, object criteria);
1080 /// If we have a MemberCache, return it. This property may return null if the
1081 /// class doesn't have a member cache or while it's still being created.
1083 public abstract MemberCache MemberCache {
1088 // Extensions for generics
1090 TypeParameter[] type_params;
1091 TypeParameter[] type_param_list;
1093 protected string GetInstantiationName ()
1095 StringBuilder sb = new StringBuilder (Name);
1097 for (int i = 0; i < type_param_list.Length; i++) {
1100 sb.Append (type_param_list [i].Name);
1103 return sb.ToString ();
1106 bool check_type_parameter (ArrayList list, int start, string name)
1108 for (int i = 0; i < start; i++) {
1109 TypeParameter param = (TypeParameter) list [i];
1111 if (param.Name != name)
1114 if (RootContext.WarningLevel >= 3)
1117 "Type parameter `{0}' has same name " +
1118 "as type parameter from outer type `{1}'",
1119 name, parent.GetInstantiationName ());
1127 TypeParameter[] initialize_type_params ()
1129 if (type_param_list != null)
1130 return type_param_list;
1132 DeclSpace the_parent = parent;
1133 if (this is GenericMethod)
1134 the_parent = the_parent.Parent;
1137 TypeParameter[] parent_params = null;
1138 if ((the_parent != null) && the_parent.IsGeneric) {
1139 parent_params = the_parent.initialize_type_params ();
1140 start = parent_params != null ? parent_params.Length : 0;
1143 ArrayList list = new ArrayList ();
1144 if (parent_params != null)
1145 list.AddRange (parent_params);
1147 int count = type_params != null ? type_params.Length : 0;
1148 for (int i = 0; i < count; i++) {
1149 TypeParameter param = type_params [i];
1150 check_type_parameter (list, start, param.Name);
1154 type_param_list = new TypeParameter [list.Count];
1155 list.CopyTo (type_param_list, 0);
1156 return type_param_list;
1159 public AdditionResult SetParameterInfo (ArrayList constraints_list)
1162 if (constraints_list != null) {
1164 80, Location, "Contraints are not allowed " +
1165 "on non-generic declarations");
1166 return AdditionResult.Error;
1169 return AdditionResult.Success;
1172 type_params = new TypeParameter [MemberName.TypeParameters.Length];
1175 // Register all the names
1177 for (int i = 0; i < MemberName.TypeParameters.Length; i++) {
1178 string name = MemberName.TypeParameters [i];
1180 AdditionResult res = IsValid (name, name);
1182 if (res != AdditionResult.Success)
1185 Constraints constraints = null;
1186 if (constraints_list != null) {
1187 foreach (Constraints constraint in constraints_list) {
1188 if (constraint.TypeParameter == name) {
1189 constraints = constraint;
1195 type_params [i] = new TypeParameter (name, constraints, Location);
1197 DefineName (name, type_params [i]);
1200 return AdditionResult.Success;
1203 public TypeParameter[] TypeParameters {
1206 throw new InvalidOperationException ();
1207 if (type_param_list == null)
1208 initialize_type_params ();
1210 return type_param_list;
1214 protected TypeParameter[] CurrentTypeParameters {
1217 throw new InvalidOperationException ();
1218 if (type_params != null)
1221 return new TypeParameter [0];
1225 public int CountTypeParameters {
1229 if (type_param_list == null)
1230 initialize_type_params ();
1232 return type_param_list.Length;
1236 public TypeParameterExpr LookupGeneric (string name, Location loc)
1241 foreach (TypeParameter type_param in CurrentTypeParameters) {
1242 if (type_param.Name != name)
1245 return new TypeParameterExpr (type_param, loc);
1249 return parent.LookupGeneric (name, loc);
1254 bool IAlias.IsType {
1255 get { return true; }
1258 string IAlias.Name {
1259 get { return Name; }
1262 TypeExpr IAlias.Type
1265 if (TypeBuilder == null)
1266 throw new InvalidOperationException ();
1268 if (CurrentType != null)
1271 return new TypeExpression (TypeBuilder, Location);
1277 /// This is a readonly list of MemberInfo's.
1279 public class MemberList : IList {
1280 public readonly IList List;
1284 /// Create a new MemberList from the given IList.
1286 public MemberList (IList list)
1291 this.List = new ArrayList ();
1296 /// Concatenate the ILists `first' and `second' to a new MemberList.
1298 public MemberList (IList first, IList second)
1300 ArrayList list = new ArrayList ();
1301 list.AddRange (first);
1302 list.AddRange (second);
1307 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1310 /// Cast the MemberList into a MemberInfo[] array.
1313 /// This is an expensive operation, only use it if it's really necessary.
1315 public static explicit operator MemberInfo [] (MemberList list)
1317 Timer.StartTimer (TimerType.MiscTimer);
1318 MemberInfo [] result = new MemberInfo [list.Count];
1319 list.CopyTo (result, 0);
1320 Timer.StopTimer (TimerType.MiscTimer);
1332 public bool IsSynchronized {
1334 return List.IsSynchronized;
1338 public object SyncRoot {
1340 return List.SyncRoot;
1344 public void CopyTo (Array array, int index)
1346 List.CopyTo (array, index);
1351 public IEnumerator GetEnumerator ()
1353 return List.GetEnumerator ();
1358 public bool IsFixedSize {
1364 public bool IsReadOnly {
1370 object IList.this [int index] {
1372 return List [index];
1376 throw new NotSupportedException ();
1380 // FIXME: try to find out whether we can avoid the cast in this indexer.
1381 public MemberInfo this [int index] {
1383 return (MemberInfo) List [index];
1387 public int Add (object value)
1389 throw new NotSupportedException ();
1392 public void Clear ()
1394 throw new NotSupportedException ();
1397 public bool Contains (object value)
1399 return List.Contains (value);
1402 public int IndexOf (object value)
1404 return List.IndexOf (value);
1407 public void Insert (int index, object value)
1409 throw new NotSupportedException ();
1412 public void Remove (object value)
1414 throw new NotSupportedException ();
1417 public void RemoveAt (int index)
1419 throw new NotSupportedException ();
1424 /// This interface is used to get all members of a class when creating the
1425 /// member cache. It must be implemented by all DeclSpace derivatives which
1426 /// want to support the member cache and by TypeHandle to get caching of
1427 /// non-dynamic types.
1429 public interface IMemberContainer {
1431 /// The name of the IMemberContainer. This is only used for
1432 /// debugging purposes.
1439 /// The type of this IMemberContainer.
1446 /// Returns the IMemberContainer of the parent class or null if this
1447 /// is an interface or TypeManger.object_type.
1448 /// This is used when creating the member cache for a class to get all
1449 /// members from the parent class.
1451 IMemberContainer Parent {
1456 /// Whether this is an interface.
1463 /// Returns all members of this class with the corresponding MemberTypes
1464 /// and BindingFlags.
1467 /// When implementing this method, make sure not to return any inherited
1468 /// members and check the MemberTypes and BindingFlags properly.
1469 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1470 /// get the BindingFlags (static/non-static,public/non-public) in the
1471 /// MemberInfo class, but the cache needs this information. That's why
1472 /// this method is called multiple times with different BindingFlags.
1474 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1477 /// Return the container's member cache.
1479 MemberCache MemberCache {
1485 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1486 /// member lookups. It has a member name based hash table; it maps each member
1487 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1488 /// and the BindingFlags that were initially used to get it. The cache contains
1489 /// all members of the current class and all inherited members. If this cache is
1490 /// for an interface types, it also contains all inherited members.
1492 /// There are two ways to get a MemberCache:
1493 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1494 /// use the DeclSpace.MemberCache property.
1495 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1496 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1498 public class MemberCache {
1499 public readonly IMemberContainer Container;
1500 protected Hashtable member_hash;
1501 protected Hashtable method_hash;
1503 Hashtable interface_hash;
1506 /// Create a new MemberCache for the given IMemberContainer `container'.
1508 public MemberCache (IMemberContainer container)
1510 this.Container = container;
1512 Timer.IncrementCounter (CounterType.MemberCache);
1513 Timer.StartTimer (TimerType.CacheInit);
1517 // If we have a parent class (we have a parent class unless we're
1518 // TypeManager.object_type), we deep-copy its MemberCache here.
1519 if (Container.IsInterface) {
1521 interface_hash = new Hashtable ();
1523 if (Container.Parent != null)
1524 parent = Container.Parent.MemberCache;
1526 parent = TypeHandle.ObjectType.MemberCache;
1527 member_hash = SetupCacheForInterface (parent);
1528 } else if (Container.Parent != null)
1529 member_hash = SetupCache (Container.Parent.MemberCache);
1531 member_hash = new Hashtable ();
1533 // If this is neither a dynamic type nor an interface, create a special
1534 // method cache with all declared and inherited methods.
1535 Type type = container.Type;
1536 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1537 method_hash = new Hashtable ();
1541 // Add all members from the current class.
1542 AddMembers (Container);
1544 Timer.StopTimer (TimerType.CacheInit);
1548 /// Bootstrap this member cache by doing a deep-copy of our parent.
1550 Hashtable SetupCache (MemberCache parent)
1552 Hashtable hash = new Hashtable ();
1554 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1555 while (it.MoveNext ()) {
1556 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1564 /// Add the contents of `new_hash' to `hash'.
1566 void AddHashtable (Hashtable hash, Hashtable new_hash)
1568 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1569 while (it.MoveNext ()) {
1570 ArrayList list = (ArrayList) hash [it.Key];
1572 list.AddRange ((ArrayList) it.Value);
1574 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1579 /// Bootstrap the member cache for an interface type.
1580 /// Type.GetMembers() won't return any inherited members for interface types,
1581 /// so we need to do this manually. Interfaces also inherit from System.Object.
1583 Hashtable SetupCacheForInterface (MemberCache parent)
1585 Hashtable hash = SetupCache (parent);
1586 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1588 foreach (TypeExpr iface in ifaces) {
1589 Type itype = iface.Type;
1591 if (interface_hash.Contains (itype))
1594 interface_hash [itype] = null;
1596 IMemberContainer iface_container =
1597 TypeManager.LookupMemberContainer (itype);
1599 MemberCache iface_cache = iface_container.MemberCache;
1601 AddHashtable (hash, iface_cache.member_hash);
1603 if (iface_cache.interface_hash == null)
1606 foreach (Type parent_contains in iface_cache.interface_hash.Keys)
1607 interface_hash [parent_contains] = null;
1614 /// Add all members from class `container' to the cache.
1616 void AddMembers (IMemberContainer container)
1618 // We need to call AddMembers() with a single member type at a time
1619 // to get the member type part of CacheEntry.EntryType right.
1620 AddMembers (MemberTypes.Constructor, container);
1621 AddMembers (MemberTypes.Field, container);
1622 AddMembers (MemberTypes.Method, container);
1623 AddMembers (MemberTypes.Property, container);
1624 AddMembers (MemberTypes.Event, container);
1625 // Nested types are returned by both Static and Instance searches.
1626 AddMembers (MemberTypes.NestedType,
1627 BindingFlags.Static | BindingFlags.Public, container);
1628 AddMembers (MemberTypes.NestedType,
1629 BindingFlags.Static | BindingFlags.NonPublic, container);
1632 void AddMembers (MemberTypes mt, IMemberContainer container)
1634 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1635 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1636 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1637 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1641 /// Add all members from class `container' with the requested MemberTypes and
1642 /// BindingFlags to the cache. This method is called multiple times with different
1643 /// MemberTypes and BindingFlags.
1645 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1647 MemberList members = container.GetMembers (mt, bf);
1649 foreach (MemberInfo member in members) {
1650 string name = member.Name;
1652 int pos = name.IndexOf ('<');
1654 name = name.Substring (0, pos);
1656 // We use a name-based hash table of ArrayList's.
1657 ArrayList list = (ArrayList) member_hash [name];
1659 list = new ArrayList ();
1660 member_hash.Add (name, list);
1663 // When this method is called for the current class, the list will
1664 // already contain all inherited members from our parent classes.
1665 // We cannot add new members in front of the list since this'd be an
1666 // expensive operation, that's why the list is sorted in reverse order
1667 // (ie. members from the current class are coming last).
1668 list.Add (new CacheEntry (container, member, mt, bf));
1673 /// Add all declared and inherited methods from class `type' to the method cache.
1675 void AddMethods (Type type)
1677 AddMethods (BindingFlags.Static | BindingFlags.Public |
1678 BindingFlags.FlattenHierarchy, type);
1679 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1680 BindingFlags.FlattenHierarchy, type);
1681 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1682 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1685 void AddMethods (BindingFlags bf, Type type)
1687 MemberInfo [] members = type.GetMethods (bf);
1689 Array.Reverse (members);
1691 foreach (MethodBase member in members) {
1692 string name = member.Name;
1694 // Varargs methods aren't allowed in C# code.
1695 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1698 // We use a name-based hash table of ArrayList's.
1699 ArrayList list = (ArrayList) method_hash [name];
1701 list = new ArrayList ();
1702 method_hash.Add (name, list);
1705 // Unfortunately, the elements returned by Type.GetMethods() aren't
1706 // sorted so we need to do this check for every member.
1707 BindingFlags new_bf = bf;
1708 if (member.DeclaringType == type)
1709 new_bf |= BindingFlags.DeclaredOnly;
1711 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1716 /// Compute and return a appropriate `EntryType' magic number for the given
1717 /// MemberTypes and BindingFlags.
1719 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1721 EntryType type = EntryType.None;
1723 if ((mt & MemberTypes.Constructor) != 0)
1724 type |= EntryType.Constructor;
1725 if ((mt & MemberTypes.Event) != 0)
1726 type |= EntryType.Event;
1727 if ((mt & MemberTypes.Field) != 0)
1728 type |= EntryType.Field;
1729 if ((mt & MemberTypes.Method) != 0)
1730 type |= EntryType.Method;
1731 if ((mt & MemberTypes.Property) != 0)
1732 type |= EntryType.Property;
1733 // Nested types are returned by static and instance searches.
1734 if ((mt & MemberTypes.NestedType) != 0)
1735 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1737 if ((bf & BindingFlags.Instance) != 0)
1738 type |= EntryType.Instance;
1739 if ((bf & BindingFlags.Static) != 0)
1740 type |= EntryType.Static;
1741 if ((bf & BindingFlags.Public) != 0)
1742 type |= EntryType.Public;
1743 if ((bf & BindingFlags.NonPublic) != 0)
1744 type |= EntryType.NonPublic;
1745 if ((bf & BindingFlags.DeclaredOnly) != 0)
1746 type |= EntryType.Declared;
1752 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1753 /// denote multiple member types. Returns true if the given flags value denotes a
1754 /// single member types.
1756 public static bool IsSingleMemberType (MemberTypes mt)
1759 case MemberTypes.Constructor:
1760 case MemberTypes.Event:
1761 case MemberTypes.Field:
1762 case MemberTypes.Method:
1763 case MemberTypes.Property:
1764 case MemberTypes.NestedType:
1773 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1774 /// number to speed up the searching process.
1777 protected enum EntryType {
1782 MaskStatic = Instance|Static,
1786 MaskProtection = Public|NonPublic,
1790 Constructor = 0x020,
1797 MaskType = Constructor|Event|Field|Method|Property|NestedType
1800 protected struct CacheEntry {
1801 public readonly IMemberContainer Container;
1802 public readonly EntryType EntryType;
1803 public readonly MemberInfo Member;
1805 public CacheEntry (IMemberContainer container, MemberInfo member,
1806 MemberTypes mt, BindingFlags bf)
1808 this.Container = container;
1809 this.Member = member;
1810 this.EntryType = GetEntryType (mt, bf);
1815 /// This is called each time we're walking up one level in the class hierarchy
1816 /// and checks whether we can abort the search since we've already found what
1817 /// we were looking for.
1819 protected bool DoneSearching (ArrayList list)
1822 // We've found exactly one member in the current class and it's not
1823 // a method or constructor.
1825 if (list.Count == 1 && !(list [0] is MethodBase))
1829 // Multiple properties: we query those just to find out the indexer
1832 if ((list.Count > 0) && (list [0] is PropertyInfo))
1839 /// Looks up members with name `name'. If you provide an optional
1840 /// filter function, it'll only be called with members matching the
1841 /// requested member name.
1843 /// This method will try to use the cache to do the lookup if possible.
1845 /// Unlike other FindMembers implementations, this method will always
1846 /// check all inherited members - even when called on an interface type.
1848 /// If you know that you're only looking for methods, you should use
1849 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1850 /// When doing a method-only search, it'll try to use a special method
1851 /// cache (unless it's a dynamic type or an interface) and the returned
1852 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1853 /// The lookup process will automatically restart itself in method-only
1854 /// search mode if it discovers that it's about to return methods.
1856 ArrayList global = new ArrayList ();
1857 bool using_global = false;
1859 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
1860 MemberFilter filter, object criteria)
1863 throw new Exception ();
1865 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1866 bool method_search = mt == MemberTypes.Method;
1867 // If we have a method cache and we aren't already doing a method-only search,
1868 // then we restart a method search if the first match is a method.
1869 bool do_method_search = !method_search && (method_hash != null);
1871 ArrayList applicable;
1873 // If this is a method-only search, we try to use the method cache if
1874 // possible; a lookup in the method cache will return a MemberInfo with
1875 // the correct ReflectedType for inherited methods.
1877 if (method_search && (method_hash != null))
1878 applicable = (ArrayList) method_hash [name];
1880 applicable = (ArrayList) member_hash [name];
1882 if (applicable == null)
1883 return MemberList.Empty;
1886 // 32 slots gives 53 rss/54 size
1887 // 2/4 slots gives 55 rss
1889 // Strange: from 25,000 calls, only 1,800
1890 // are above 2. Why does this impact it?
1893 using_global = true;
1895 Timer.StartTimer (TimerType.CachedLookup);
1897 EntryType type = GetEntryType (mt, bf);
1899 IMemberContainer current = Container;
1901 // `applicable' is a list of all members with the given member name `name'
1902 // in the current class and all its parent classes. The list is sorted in
1903 // reverse order due to the way how the cache is initialy created (to speed
1904 // things up, we're doing a deep-copy of our parent).
1906 for (int i = applicable.Count-1; i >= 0; i--) {
1907 CacheEntry entry = (CacheEntry) applicable [i];
1909 // This happens each time we're walking one level up in the class
1910 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1911 // the first time this happens (this may already happen in the first
1912 // iteration of this loop if there are no members with the name we're
1913 // looking for in the current class).
1914 if (entry.Container != current) {
1915 if (declared_only || DoneSearching (global))
1918 current = entry.Container;
1921 // Is the member of the correct type ?
1922 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1925 // Is the member static/non-static ?
1926 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1929 // Apply the filter to it.
1930 if (filter (entry.Member, criteria)) {
1931 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1932 do_method_search = false;
1933 global.Add (entry.Member);
1937 Timer.StopTimer (TimerType.CachedLookup);
1939 // If we have a method cache and we aren't already doing a method-only
1940 // search, we restart in method-only search mode if the first match is
1941 // a method. This ensures that we return a MemberInfo with the correct
1942 // ReflectedType for inherited methods.
1943 if (do_method_search && (global.Count > 0)){
1944 using_global = false;
1946 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1949 using_global = false;
1950 MemberInfo [] copy = new MemberInfo [global.Count];
1951 global.CopyTo (copy);
1952 return new MemberList (copy);
1956 // This finds the method or property for us to override. invocationType is the type where
1957 // the override is going to be declared, name is the name of the method/property, and
1958 // paramTypes is the parameters, if any to the method or property
1960 // Because the MemberCache holds members from this class and all the base classes,
1961 // we can avoid tons of reflection stuff.
1963 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1965 ArrayList applicable;
1966 if (method_hash != null && !is_property)
1967 applicable = (ArrayList) method_hash [name];
1969 applicable = (ArrayList) member_hash [name];
1971 if (applicable == null)
1974 // Walk the chain of methods, starting from the top.
1976 for (int i = applicable.Count - 1; i >= 0; i--) {
1977 CacheEntry entry = (CacheEntry) applicable [i];
1979 if ((entry.EntryType & (is_property ? EntryType.Property : EntryType.Method)) == 0)
1982 PropertyInfo pi = null;
1983 MethodInfo mi = null;
1987 pi = (PropertyInfo) entry.Member;
1988 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1990 mi = (MethodInfo) entry.Member;
1991 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1995 // Check the arguments
1997 if (cmpAttrs.Length != paramTypes.Length)
2000 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2001 if (!paramTypes [j].Equals (cmpAttrs [j]))
2006 // get one of the methods because this has the visibility info.
2009 mi = pi.GetGetMethod (true);
2011 mi = pi.GetSetMethod (true);
2017 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2018 case MethodAttributes.Private:
2020 // A private method is Ok if we are a nested subtype.
2021 // The spec actually is not very clear about this, see bug 52458.
2023 if (invocationType == entry.Container.Type ||
2024 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2025 return entry.Member;
2028 case MethodAttributes.FamANDAssem:
2029 case MethodAttributes.Assembly:
2031 // Check for assembly methods
2033 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2034 return entry.Member;
2039 // A protected method is ok, because we are overriding.
2040 // public is always ok.
2042 return entry.Member;