2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2003-2008 Novell, Inc.
15 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
16 // the behavior of the compilation. This can be removed if we rework
17 // the code to get a list of namespaces available.
19 #define SIMPLE_SPEEDUP
23 using System.Globalization;
24 using System.Collections;
25 using System.Reflection;
26 using System.Reflection.Emit;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
33 partial class TypeManager {
35 // A list of core types that the compiler requires or uses
37 static public Type object_type;
38 static public Type value_type;
39 static public Type string_type;
40 static public Type int32_type;
41 static public Type uint32_type;
42 static public Type int64_type;
43 static public Type uint64_type;
44 static public Type float_type;
45 static public Type double_type;
46 static public Type char_type;
47 static public Type short_type;
48 static public Type decimal_type;
49 static public Type bool_type;
50 static public Type sbyte_type;
51 static public Type byte_type;
52 static public Type ushort_type;
53 static public Type enum_type;
54 static public Type delegate_type;
55 static public Type multicast_delegate_type;
56 static public Type void_type;
57 static public Type null_type;
58 static public Type array_type;
59 static public Type runtime_handle_type;
60 static public Type type_type;
61 static public Type ienumerator_type;
62 static public Type ienumerable_type;
63 static public Type idisposable_type;
64 static public Type iasyncresult_type;
65 static public Type asynccallback_type;
66 static public Type intptr_type;
67 static public Type uintptr_type;
68 static public Type runtime_field_handle_type;
69 static public Type runtime_argument_handle_type;
70 static public Type attribute_type;
71 static public Type void_ptr_type;
72 static public Type exception_type;
74 static public Type typed_reference_type;
75 static public Type arg_iterator_type;
76 static public Type mbr_type;
77 public static Type runtime_helpers_type;
82 static internal Type isvolatile_type;
83 static public Type generic_ilist_type;
84 static public Type generic_icollection_type;
85 static public Type generic_ienumerator_type;
86 static public Type generic_ienumerable_type;
87 static public Type generic_nullable_type;
92 static internal Type expression_type;
93 public static Type parameter_expression_type;
98 public static Type call_site_type;
99 public static Type generic_call_site_type;
102 // Expressions representing the internal types. Used during declaration
105 static public TypeExpr system_object_expr, system_string_expr;
106 static public TypeExpr system_boolean_expr, system_decimal_expr;
107 static public TypeExpr system_single_expr, system_double_expr;
108 static public TypeExpr system_sbyte_expr, system_byte_expr;
109 static public TypeExpr system_int16_expr, system_uint16_expr;
110 static public TypeExpr system_int32_expr, system_uint32_expr;
111 static public TypeExpr system_int64_expr, system_uint64_expr;
112 static public TypeExpr system_char_expr, system_void_expr;
113 static public TypeExpr system_valuetype_expr;
114 static public TypeExpr system_intptr_expr;
115 public static TypeExpr expression_type_expr;
119 // These methods are called by code generated by the compiler
121 static public FieldInfo string_empty;
122 static public MethodInfo system_type_get_type_from_handle;
123 static public MethodInfo bool_movenext_void;
124 static public MethodInfo void_dispose_void;
125 static public MethodInfo void_monitor_enter_object;
126 static public MethodInfo void_monitor_exit_object;
127 static public MethodInfo void_initializearray_array_fieldhandle;
128 static public MethodInfo delegate_combine_delegate_delegate;
129 static public MethodInfo delegate_remove_delegate_delegate;
130 static public PropertyInfo int_get_offset_to_string_data;
131 static public MethodInfo int_interlocked_compare_exchange;
132 static public PropertyInfo ienumerator_getcurrent;
133 public static MethodInfo methodbase_get_type_from_handle;
134 public static MethodInfo methodbase_get_type_from_handle_generic;
135 public static MethodInfo fieldinfo_get_field_from_handle;
136 static public MethodInfo activator_create_instance;
141 static public ConstructorInfo void_decimal_ctor_five_args;
142 static public ConstructorInfo void_decimal_ctor_int_arg;
144 static PtrHashtable builder_to_declspace;
146 static PtrHashtable builder_to_member_cache;
149 // Tracks the interfaces implemented by typebuilders. We only
150 // enter those who do implement or or more interfaces
152 static PtrHashtable builder_to_ifaces;
155 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
157 static Hashtable method_params;
160 // A hash table from override methods to their base virtual method.
162 static Hashtable method_overrides;
165 // Keeps track of methods
168 static Hashtable builder_to_method;
171 // Contains all public types from referenced assemblies.
172 // This member is used only if CLS Compliance verification is required.
174 public static Hashtable AllClsTopLevelTypes;
176 static Hashtable fieldbuilders_to_fields;
177 static Hashtable propertybuilder_to_property;
178 static Hashtable fields;
179 static Hashtable events;
180 static PtrHashtable assembly_internals_vis_attrs;
182 public static void CleanUp ()
184 // Lets get everything clean so that we can collect before generating code
185 builder_to_declspace = null;
186 builder_to_member_cache = null;
187 builder_to_ifaces = null;
188 builder_to_type_param = null;
189 method_params = null;
190 builder_to_method = null;
195 propertybuilder_to_property = null;
197 TypeHandle.CleanUp ();
201 // These are expressions that represent some of the internal data types, used
204 static void InitExpressionTypes ()
206 system_object_expr = new TypeLookupExpression ("System", "Object");
207 system_string_expr = new TypeLookupExpression ("System", "String");
208 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
209 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
210 system_single_expr = new TypeLookupExpression ("System", "Single");
211 system_double_expr = new TypeLookupExpression ("System", "Double");
212 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
213 system_byte_expr = new TypeLookupExpression ("System", "Byte");
214 system_int16_expr = new TypeLookupExpression ("System", "Int16");
215 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
216 system_int32_expr = new TypeLookupExpression ("System", "Int32");
217 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
218 system_int64_expr = new TypeLookupExpression ("System", "Int64");
219 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
220 system_char_expr = new TypeLookupExpression ("System", "Char");
221 system_void_expr = new TypeLookupExpression ("System", "Void");
222 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
223 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
226 static TypeManager ()
231 static public void Reset ()
233 InitExpressionTypes ();
235 builder_to_declspace = new PtrHashtable ();
236 builder_to_member_cache = new PtrHashtable ();
237 builder_to_method = new PtrHashtable ();
238 builder_to_type_param = new PtrHashtable ();
239 method_params = new PtrHashtable ();
240 method_overrides = new PtrHashtable ();
241 builder_to_ifaces = new PtrHashtable ();
243 fieldbuilders_to_fields = new Hashtable ();
244 propertybuilder_to_property = new Hashtable ();
245 fields = new Hashtable ();
246 type_hash = new DoubleHash ();
247 assembly_internals_vis_attrs = new PtrHashtable ();
248 iface_cache = new PtrHashtable ();
250 closure = new Closure ();
251 FilterWithClosure_delegate = new MemberFilter (closure.Filter);
253 // TODO: I am really bored by all this static stuff
254 system_type_get_type_from_handle =
257 void_monitor_enter_object =
258 void_monitor_exit_object =
259 void_initializearray_array_fieldhandle =
260 delegate_combine_delegate_delegate =
261 delegate_remove_delegate_delegate =
262 int_interlocked_compare_exchange =
263 methodbase_get_type_from_handle =
264 methodbase_get_type_from_handle_generic =
265 fieldinfo_get_field_from_handle =
266 activator_create_instance = null;
268 int_get_offset_to_string_data =
269 ienumerator_getcurrent = null;
271 void_decimal_ctor_five_args =
272 void_decimal_ctor_int_arg = null;
274 isvolatile_type = null;
276 // to uncover regressions
277 AllClsTopLevelTypes = null;
280 public static void AddUserType (DeclSpace ds)
282 builder_to_declspace.Add (ds.TypeBuilder, ds);
286 // This entry point is used by types that we define under the covers
288 public static void RegisterBuilder (Type tb, Type [] ifaces)
291 builder_to_ifaces [tb] = ifaces;
294 public static void AddMethod (MethodBase builder, IMethodData method)
296 builder_to_method.Add (builder, method);
297 method_params.Add (builder, method.ParameterInfo);
300 public static IMethodData GetMethod (MethodBase builder)
302 return (IMethodData) builder_to_method [builder];
306 /// Returns the DeclSpace whose Type is `t' or null if there is no
307 /// DeclSpace for `t' (ie, the Type comes from a library)
309 public static DeclSpace LookupDeclSpace (Type t)
311 return builder_to_declspace [t] as DeclSpace;
315 /// Returns the TypeContainer whose Type is `t' or null if there is no
316 /// TypeContainer for `t' (ie, the Type comes from a library)
318 public static TypeContainer LookupTypeContainer (Type t)
320 return builder_to_declspace [t] as TypeContainer;
323 public static MemberCache LookupMemberCache (Type t)
325 if (t.Module == RootContext.ToplevelTypes.Builder) {
326 DeclSpace container = (DeclSpace)builder_to_declspace [t];
327 if (container != null)
328 return container.MemberCache;
332 if (t is GenericTypeParameterBuilder) {
333 TypeParameter container = builder_to_type_param [t] as TypeParameter;
335 if (container != null)
336 return container.MemberCache;
340 return TypeHandle.GetMemberCache (t);
343 public static MemberCache LookupBaseInterfacesCache (Type t)
345 Type [] ifaces = GetInterfaces (t);
347 if (ifaces != null && ifaces.Length == 1)
348 return LookupMemberCache (ifaces [0]);
350 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
351 MemberCache cache = builder_to_member_cache [t] as MemberCache;
355 cache = new MemberCache (ifaces);
356 builder_to_member_cache.Add (t, cache);
360 public static TypeContainer LookupInterface (Type t)
362 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
363 if ((tc == null) || (tc.Kind != Kind.Interface))
369 public static Delegate LookupDelegate (Type t)
371 return builder_to_declspace [t] as Delegate;
374 public static Class LookupClass (Type t)
376 return (Class) builder_to_declspace [t];
380 // We use this hash for multiple kinds of constructed types:
382 // (T, "&") Given T, get T &
383 // (T, "*") Given T, get T *
384 // (T, "[]") Given T and a array dimension, get T []
385 // (T, X) Given a type T and a simple name X, get the type T+X
387 // Accessibility tests, if necessary, should be done by the user
389 static DoubleHash type_hash = new DoubleHash ();
392 // Gets the reference to T version of the Type (T&)
394 public static Type GetReferenceType (Type t)
397 return t.MakeByRefType ();
399 return GetConstructedType (t, "&");
404 // Gets the pointer to T version of the Type (T*)
406 public static Type GetPointerType (Type t)
408 return GetConstructedType (t, "*");
411 public static Type GetConstructedType (Type t, string dim)
414 if (type_hash.Lookup (t, dim, out ret))
417 ret = t.Module.GetType (t.ToString () + dim);
419 type_hash.Insert (t, dim, ret);
424 ret = GetReferenceType (t);
425 type_hash.Insert (t, dim, ret);
430 if (t.IsGenericParameter || t.IsGenericType) {
433 while ((pos < dim.Length) && (dim [pos] == '[')) {
436 if (dim [pos] == ']') {
437 result = result.MakeArrayType ();
440 if (pos < dim.Length)
443 type_hash.Insert (t, dim, result);
448 while (dim [pos] == ',') {
452 if ((dim [pos] != ']') || (pos != dim.Length-1))
455 result = result.MakeArrayType (rank + 1);
456 type_hash.Insert (t, dim, result);
462 type_hash.Insert (t, dim, null);
466 public static Type GetNestedType (Type t, string name)
469 if (!type_hash.Lookup (t, name, out ret)) {
470 ret = t.GetNestedType (name,
471 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
472 type_hash.Insert (t, name, ret);
478 /// Fills static table with exported types from all referenced assemblies.
479 /// This information is required for CLS Compliance tests.
481 public static void LoadAllImportedTypes ()
483 AllClsTopLevelTypes = new Hashtable (1500);
484 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
485 foreach (Type t in a.GetExportedTypes ()) {
486 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
491 public static bool NamespaceClash (string name, Location loc)
493 if (!GlobalRootNamespace.Instance.IsNamespace (name))
496 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
501 /// Returns the C# name of a type if possible, or the full type name otherwise
503 static public string CSharpName (Type t)
508 if (t == typeof (ArglistAccess))
511 if (t == typeof (AnonymousMethodBody))
512 return "anonymous method";
514 if (t == typeof (MethodGroupExpr))
515 return "method group";
518 return "internal error";
520 return CSharpName (GetFullName (t), t);
523 static readonly char [] elements = new char [] { '*', '[' };
525 public static string CSharpName (string name, Type type)
527 if (name.Length > 10) {
530 case "System.Int32": s = "int"; break;
531 case "System.Int64": s = "long"; break;
532 case "System.String": s = "string"; break;
533 case "System.Boolean": s = "bool"; break;
534 case "System.Void": s = "void"; break;
535 case "System.Object": s = "object"; break;
536 case "System.UInt32": s = "uint"; break;
537 case "System.Int16": s = "short"; break;
538 case "System.UInt16": s = "ushort"; break;
539 case "System.UInt64": s = "ulong"; break;
540 case "System.Single": s = "float"; break;
541 case "System.Double": s = "double"; break;
542 case "System.Decimal": s = "decimal"; break;
543 case "System.Char": s = "char"; break;
544 case "System.Byte": s = "byte"; break;
545 case "System.SByte": s = "sbyte"; break;
546 default: s = null; break;
551 // Predefined names can come from mscorlib only
553 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
559 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
560 return AnonymousTypeClass.SignatureForError;
562 int idx = name.IndexOfAny (elements, 10);
564 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
567 return name.Replace ('+', '.');
570 static public string CSharpName (Type[] types)
572 if (types.Length == 0)
575 StringBuilder sb = new StringBuilder ();
576 for (int i = 0; i < types.Length; ++i) {
580 sb.Append (CSharpName (types [i]));
582 return sb.ToString ();
586 /// Returns the signature of the method with full namespace classification
588 static public string GetFullNameSignature (MemberInfo mi)
590 PropertyInfo pi = mi as PropertyInfo;
592 MethodBase pmi = pi.GetGetMethod (true);
594 pmi = pi.GetSetMethod (true);
595 if (GetParameterData (pmi).Count > 0)
598 return (mi is MethodBase)
599 ? CSharpSignature (mi as MethodBase)
600 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
604 private static int GetFullName (Type t, StringBuilder sb)
608 if (!t.IsGenericType) {
609 sb.Append (t.FullName);
613 if (t.DeclaringType != null) {
614 pos = GetFullName (t.DeclaringType, sb);
616 } else if (t.Namespace != null && t.Namespace.Length != 0) {
617 sb.Append (t.Namespace);
620 sb.Append (RemoveGenericArity (t.Name));
622 Type[] this_args = GetTypeArguments (t);
624 if (this_args.Length < pos)
625 throw new InternalErrorException (
626 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
627 if (this_args.Length == pos)
632 sb.Append (CSharpName (this_args [pos++]));
633 if (pos == this_args.Length)
641 static string GetFullName (Type t)
644 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
645 return GetFullName (GetElementType (t)) + dimension;
648 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
649 t = GetTypeArguments (t)[0];
650 return CSharpName (t) + "?";
653 if (t.IsGenericParameter)
655 if (!t.IsGenericType)
658 StringBuilder sb = new StringBuilder ();
659 int pos = GetFullName (t, sb);
661 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
662 return sb.ToString ();
665 public static string GetFullName (Type t)
671 public static string RemoveGenericArity (string from)
673 int i = from.IndexOf ('`');
675 return from.Substring (0, i);
680 /// When we need to report accessors as well
682 static public string CSharpSignature (MethodBase mb)
684 return CSharpSignature (mb, false);
688 /// Returns the signature of the method
690 static public string CSharpSignature (MethodBase mb, bool show_accessor)
692 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
695 AParametersCollection iparams = GetParameterData (mb);
696 string parameters = iparams.GetSignatureForError ();
697 int accessor_end = 0;
699 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
700 string op_name = Operator.GetName (mb.Name);
701 if (op_name != null) {
702 if (op_name == "explicit" || op_name == "implicit") {
703 sig.Append (op_name);
704 sig.Append (" operator ");
705 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
707 sig.Append ("operator ");
708 sig.Append (op_name);
710 sig.Append (parameters);
711 return sig.ToString ();
714 bool is_getter = mb.Name.StartsWith ("get_");
715 bool is_setter = mb.Name.StartsWith ("set_");
716 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
718 } else if (mb.Name.StartsWith ("remove_")) {
723 if (iparams.Count > (is_getter ? 0 : 1)) {
724 sig.Append ("this[");
726 sig.Append (parameters.Substring (1, parameters.Length - 2));
728 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
731 sig.Append (mb.Name.Substring (accessor_end + 1));
734 if (mb.Name == ".ctor")
735 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
737 sig.Append (mb.Name);
739 if (IsGenericMethod (mb)) {
740 Type[] args = GetGenericArguments (mb);
742 for (int i = 0; i < args.Length; i++) {
745 sig.Append (CSharpName (args [i]));
751 sig.Append (parameters);
754 if (show_accessor && accessor_end > 0) {
756 sig.Append (mb.Name.Substring (0, accessor_end));
759 return sig.ToString ();
762 public static string GetMethodName (MethodInfo m)
764 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
767 return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
770 static public string CSharpSignature (EventInfo ei)
772 return CSharpName (ei.DeclaringType) + "." + ei.Name;
776 // Looks up a type, and aborts if it is not found. This is used
777 // by predefined types required by the compiler
779 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
781 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
782 Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
786 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
793 if (RootContext.StdLib || t == null || !required)
796 // TODO: All predefined imported types have to have correct signature
797 if (t.Module != RootContext.ToplevelTypes.Builder)
800 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
801 if (ds is Delegate) {
802 if (type_kind == Kind.Delegate)
805 TypeContainer tc = (TypeContainer)ds;
806 if (tc.Kind == type_kind)
810 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
815 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
817 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
819 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
820 if (members != null) {
821 for (int i = 0; i < members.Length; ++i) {
822 MemberInfo member = members [i];
823 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
824 MethodBase mb = member as MethodBase;
828 AParametersCollection pd = TypeManager.GetParameterData (mb);
829 if (IsEqual (pd.Types, args))
832 if (mt == MemberTypes.Field) {
833 FieldInfo fi = member as FieldInfo;
837 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
843 if (mt == MemberTypes.Property) {
844 PropertyInfo pi = member as PropertyInfo;
848 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
856 string method_args = null;
857 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
858 method_args = "(" + TypeManager.CSharpName (args) + ")";
860 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
861 TypeManager.CSharpName (t), name, method_args);
867 // Returns the ConstructorInfo for "args"
869 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
871 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
875 // Returns the MethodInfo for a method named `name' defined
876 // in type `t' which takes arguments of types `args'
878 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
880 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
883 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
885 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
888 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
890 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
894 /// The types have to be initialized after the initial
895 /// population of the type has happened (for example, to
896 /// bootstrap the corlib.dll
898 public static bool InitCoreTypes ()
900 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
901 system_object_expr.Type = object_type;
902 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
903 system_valuetype_expr.Type = value_type;
904 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
906 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
907 system_int32_expr.Type = int32_type;
908 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
909 system_int64_expr.Type = int64_type;
910 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
911 system_uint32_expr.Type = uint32_type;
912 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
913 system_uint64_expr.Type = uint64_type;
914 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
915 system_byte_expr.Type = byte_type;
916 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
917 system_sbyte_expr.Type = sbyte_type;
918 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
919 system_int16_expr.Type = short_type;
920 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
921 system_uint16_expr.Type = ushort_type;
923 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
924 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
925 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
927 // HACK: DefineType immediately resolves iterators (very wrong)
928 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
930 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
931 system_char_expr.Type = char_type;
932 string_type = CoreLookupType ("System", "String", Kind.Class, true);
933 system_string_expr.Type = string_type;
934 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
935 system_single_expr.Type = float_type;
936 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
937 system_double_expr.Type = double_type;
938 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
939 system_decimal_expr.Type = decimal_type;
940 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
941 system_boolean_expr.Type = bool_type;
942 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
943 system_intptr_expr.Type = intptr_type;
944 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
946 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
947 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
949 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
950 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
951 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
952 system_void_expr.Type = void_type;
953 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
954 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
956 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
957 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
959 PredefinedAttributes.Get.ParamArray.Resolve (false);
960 PredefinedAttributes.Get.Out.Resolve (false);
962 return Report.Errors == 0;
966 // Initializes optional core types
968 public static void InitOptionalCoreTypes ()
971 // These are only used for compare purposes
973 null_type = typeof (NullLiteral);
975 void_ptr_type = GetPointerType (void_type);
978 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
979 // types cache with incorrect accessiblity when any of optional types is internal.
981 PredefinedAttributes.Get.Initialize ();
983 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
984 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
985 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
986 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
987 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
988 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
991 // Optional attributes, used for error reporting only
993 //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
994 // Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
999 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1000 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1001 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1002 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1005 // Optional types which are used as types and for member lookup
1007 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1010 // Note: extension_attribute_type is already loaded
1011 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1013 if (!RootContext.StdLib) {
1015 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1016 // has different predefined types and this method sets mscorlib types
1017 // to be same to avoid any type check errors.
1020 Type type = typeof (Type);
1021 Type [] system_4_type_arg = { type, type, type, type };
1023 MethodInfo set_corlib_type_builders =
1024 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1025 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1026 system_4_type_arg, null);
1028 if (set_corlib_type_builders != null) {
1029 object[] args = new object [4];
1030 args [0] = object_type;
1031 args [1] = value_type;
1032 args [2] = enum_type;
1033 args [3] = void_type;
1035 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1037 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1038 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1039 TypeManager.CSharpName (system_4_type_arg));
1044 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1047 /// This is the "old", non-cache based FindMembers() function. We cannot use
1048 /// the cache here because there is no member name argument.
1050 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1051 MemberFilter filter, object criteria)
1053 #if MS_COMPATIBLE && GMCS_SOURCE
1054 if (t.IsGenericType)
1055 t = t.GetGenericTypeDefinition ();
1058 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1061 // `builder_to_declspace' contains all dynamic types.
1065 Timer.StartTimer (TimerType.FindMembers);
1066 list = decl.FindMembers (mt, bf, filter, criteria);
1067 Timer.StopTimer (TimerType.FindMembers);
1072 // We have to take care of arrays specially, because GetType on
1073 // a TypeBuilder array will return a Type, not a TypeBuilder,
1074 // and we can not call FindMembers on this type.
1077 #if MS_COMPATIBLE && GMCS_SOURCE
1080 t.IsSubclassOf (TypeManager.array_type))
1081 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1084 if (t is GenericTypeParameterBuilder) {
1085 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1087 Timer.StartTimer (TimerType.FindMembers);
1088 MemberList list = tparam.FindMembers (
1089 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1090 Timer.StopTimer (TimerType.FindMembers);
1096 // Since FindMembers will not lookup both static and instance
1097 // members, we emulate this behaviour here.
1099 if ((bf & instance_and_static) == instance_and_static){
1100 MemberInfo [] i_members = t.FindMembers (
1101 mt, bf & ~BindingFlags.Static, filter, criteria);
1103 int i_len = i_members.Length;
1105 MemberInfo one = i_members [0];
1108 // If any of these are present, we are done!
1110 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1111 return new MemberList (i_members);
1114 MemberInfo [] s_members = t.FindMembers (
1115 mt, bf & ~BindingFlags.Instance, filter, criteria);
1117 int s_len = s_members.Length;
1118 if (i_len > 0 || s_len > 0)
1119 return new MemberList (i_members, s_members);
1122 return new MemberList (i_members);
1124 return new MemberList (s_members);
1128 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1133 /// This method is only called from within MemberLookup. It tries to use the member
1134 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1135 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1136 /// our return value will already contain all inherited members and the caller don't need
1137 /// to check base classes and interfaces anymore.
1139 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1140 string name, out bool used_cache)
1145 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1146 // and we can ask the DeclSpace for the MemberCache.
1149 if (t.Assembly == CodeGen.Assembly.Builder) {
1150 if (t.IsGenericParameter) {
1151 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1154 if (tparam.MemberCache == null)
1155 return new MemberInfo[0];
1157 return tparam.MemberCache.FindMembers (
1158 mt, bf, name, FilterWithClosure_delegate, null);
1162 // We have to take care of arrays specially, because GetType on
1163 // a TypeBuilder array will return a Type, not a TypeBuilder,
1164 // and we can not call FindMembers on this type.
1168 return TypeHandle.ArrayType.MemberCache.FindMembers (
1169 mt, bf, name, FilterWithClosure_delegate, null);
1172 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1173 t = t.GetGenericTypeDefinition ();
1175 if (t is TypeBuilder) {
1177 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1178 cache = decl.MemberCache;
1181 // If this DeclSpace has a MemberCache, use it.
1184 if (cache != null) {
1186 return cache.FindMembers (
1187 mt, bf, name, FilterWithClosure_delegate, null);
1190 // If there is no MemberCache, we need to use the "normal" FindMembers.
1191 // Note, this is a VERY uncommon route!
1194 Timer.StartTimer (TimerType.FindMembers);
1195 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1196 FilterWithClosure_delegate, name);
1197 Timer.StopTimer (TimerType.FindMembers);
1199 return (MemberInfo []) list;
1203 // We have to take care of arrays specially, because GetType on
1204 // a TypeBuilder array will return a Type, not a TypeBuilder,
1205 // and we can not call FindMembers on this type.
1209 return TypeHandle.ArrayType.MemberCache.FindMembers (
1210 mt, bf, name, FilterWithClosure_delegate, null);
1214 if (t is GenericTypeParameterBuilder) {
1215 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1218 if (tparam.MemberCache == null)
1219 return new MemberInfo [0];
1221 return tparam.MemberCache.FindMembers (
1222 mt, bf, name, FilterWithClosure_delegate, null);
1226 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1228 // This happens if we're resolving a class'es base class and interfaces
1229 // in TypeContainer.DefineType(). At this time, the types aren't
1230 // populated yet, so we can't use the cache.
1232 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1233 FilterWithClosure_delegate, name);
1239 // This call will always succeed. There is exactly one TypeHandle instance per
1240 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1241 // the corresponding MemberCache.
1243 cache = TypeHandle.GetMemberCache (t);
1246 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1249 public static bool IsBuiltinType (Type t)
1251 t = TypeToCoreType (t);
1252 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1253 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1254 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1255 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1262 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1263 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1265 public static bool IsPrimitiveType (Type t)
1267 return (t == int32_type || t == uint32_type ||
1268 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1269 t == char_type || t == short_type || t == bool_type ||
1270 t == sbyte_type || t == byte_type || t == ushort_type);
1273 public static bool IsDelegateType (Type t)
1275 if (TypeManager.IsGenericParameter (t))
1278 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1281 t = DropGenericTypeArguments (t);
1282 return IsSubclassOf (t, TypeManager.delegate_type);
1285 public static bool IsEnumType (Type t)
1287 t = DropGenericTypeArguments (t);
1288 return t.BaseType == TypeManager.enum_type;
1291 public static bool IsBuiltinOrEnum (Type t)
1293 if (IsBuiltinType (t))
1302 public static bool IsAttributeType (Type t)
1304 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1308 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1310 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1311 public static bool IsUnmanagedType (Type t)
1313 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1315 return ds.IsUnmanagedType ();
1317 // builtins that are not unmanaged types
1318 if (t == TypeManager.object_type || t == TypeManager.string_type)
1321 if (IsGenericType (t) || IsGenericParameter (t))
1324 if (IsBuiltinOrEnum (t))
1327 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1329 return IsUnmanagedType (GetElementType (t));
1331 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1335 if (!IsValueType (t))
1338 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1339 if (IsGenericTypeDefinition (p))
1345 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1347 foreach (FieldInfo f in fields){
1348 if (!IsUnmanagedType (f.FieldType)){
1358 // Null is considered to be a reference type
1360 public static bool IsReferenceType (Type t)
1362 if (TypeManager.IsGenericParameter (t)) {
1363 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1364 if (constraints == null)
1367 return constraints.IsReferenceType;
1370 return !IsStruct (t) && !IsEnumType (t);
1373 public static bool IsValueType (Type t)
1375 if (TypeManager.IsGenericParameter (t)) {
1376 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1377 if (constraints == null)
1380 return constraints.IsValueType;
1383 return IsStruct (t) || IsEnumType (t);
1386 public static bool IsStruct (Type t)
1388 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1391 public static bool IsInterfaceType (Type t)
1393 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1397 return tc.Kind == Kind.Interface;
1400 public static bool IsSubclassOf (Type type, Type base_type)
1402 TypeParameter tparam = LookupTypeParameter (type);
1403 TypeParameter pparam = LookupTypeParameter (base_type);
1405 if ((tparam != null) && (pparam != null)) {
1406 if (tparam == pparam)
1409 return tparam.IsSubclassOf (base_type);
1412 #if MS_COMPATIBLE && GMCS_SOURCE
1413 if (type.IsGenericType)
1414 type = type.GetGenericTypeDefinition ();
1417 if (type.IsSubclassOf (base_type))
1421 if (IsEqual (type, base_type))
1424 type = type.BaseType;
1425 } while (type != null);
1430 public static bool IsPrivateAccessible (Type type, Type parent)
1435 if (type.Equals (parent))
1438 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1441 public static bool IsFamilyAccessible (Type type, Type parent)
1443 TypeParameter tparam = LookupTypeParameter (type);
1444 TypeParameter pparam = LookupTypeParameter (parent);
1446 if ((tparam != null) && (pparam != null)) {
1447 if (tparam == pparam)
1450 return tparam.IsSubclassOf (parent);
1454 if (IsInstantiationOfSameGenericType (type, parent))
1457 type = type.BaseType;
1458 } while (type != null);
1464 // Checks whether `type' is a subclass or nested child of `base_type'.
1466 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1469 if (IsFamilyAccessible (type, base_type))
1472 // Handle nested types.
1473 type = type.DeclaringType;
1474 } while (type != null);
1480 // Checks whether `type' is a nested child of `parent'.
1482 public static bool IsNestedChildOf (Type type, Type parent)
1487 type = DropGenericTypeArguments (type);
1488 parent = DropGenericTypeArguments (parent);
1490 if (IsEqual (type, parent))
1493 type = type.DeclaringType;
1494 while (type != null) {
1495 if (IsEqual (type, parent))
1498 type = type.DeclaringType;
1504 public static bool IsSpecialType (Type t)
1506 return t == arg_iterator_type || t == typed_reference_type;
1510 // Checks whether `extern_type' is friend of the output assembly
1512 public static bool IsThisOrFriendAssembly (Assembly assembly)
1514 if (assembly == CodeGen.Assembly.Builder)
1517 if (assembly_internals_vis_attrs.Contains (assembly))
1518 return (bool)(assembly_internals_vis_attrs [assembly]);
1520 PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
1521 // HACK: Do very early resolve of SRE type checking
1522 if (pa.Type == null)
1528 object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
1529 if (attrs.Length == 0) {
1530 assembly_internals_vis_attrs.Add (assembly, false);
1534 bool is_friend = false;
1536 AssemblyName this_name = CodeGen.Assembly.Name;
1537 byte [] this_token = this_name.GetPublicKeyToken ();
1538 foreach (InternalsVisibleToAttribute attr in attrs) {
1539 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1542 AssemblyName aname = null;
1545 aname = new AssemblyName (attr.AssemblyName);
1547 throw new NotSupportedException ();
1549 } catch (FileLoadException) {
1550 } catch (ArgumentException) {
1553 if (aname == null || aname.Name != this_name.Name)
1556 byte [] key_token = aname.GetPublicKeyToken ();
1557 if (key_token != null) {
1558 if (this_token.Length == 0) {
1559 // Same name, but assembly is not strongnamed
1560 Error_FriendAccessNameNotMatching (aname.FullName);
1564 if (!CompareKeyTokens (this_token, key_token))
1572 assembly_internals_vis_attrs.Add (assembly, is_friend);
1576 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1578 for (int i = 0; i < token1.Length; i++)
1579 if (token1 [i] != token2 [i])
1585 static void Error_FriendAccessNameNotMatching (string other_name)
1588 "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
1589 other_name, CodeGen.Assembly.Name.FullName);
1593 // Do the right thing when returning the element type of an
1594 // array type based on whether we are compiling corlib or not
1596 public static Type GetElementType (Type t)
1598 if (RootContext.StdLib)
1599 return t.GetElementType ();
1601 return TypeToCoreType (t.GetElementType ());
1605 /// This method is not implemented by MS runtime for dynamic types
1607 public static bool HasElementType (Type t)
1609 return t.IsArray || t.IsPointer || t.IsByRef;
1612 public static Type GetEnumUnderlyingType (Type t)
1614 t = DropGenericTypeArguments (t);
1615 Enum e = LookupTypeContainer (t) as Enum;
1617 return e.UnderlyingType;
1620 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1622 return TypeManager.int32_type;
1624 return TypeToCoreType (fi.FieldType);
1628 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1632 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1633 /// for anything which is dynamic, and we need this in a number of places,
1634 /// we register this information here, and use it afterwards.
1636 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1638 method_params.Add (mb, ip);
1641 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1643 method_params.Add (pb, p);
1646 static public AParametersCollection GetParameterData (MethodBase mb)
1648 AParametersCollection pd = (AParametersCollection) method_params [mb];
1651 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1652 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1653 pd = GetParameterData (mi);
1655 if (mi.IsGenericMethod)
1656 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1658 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1660 method_params.Add (mb, pd);
1664 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1665 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1666 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1669 pd = ParametersImported.Create (mb);
1671 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1672 if (generic != mb) {
1673 pd = TypeManager.GetParameterData (generic);
1674 pd = ParametersImported.Create (pd, mb);
1676 pd = ParametersImported.Create (mb);
1679 method_params.Add (mb, pd);
1684 public static AParametersCollection GetParameterData (PropertyInfo pi)
1686 AParametersCollection pd = (AParametersCollection)method_params [pi];
1688 if (pi is PropertyBuilder)
1689 return ParametersCompiled.EmptyReadOnlyParameters;
1691 ParameterInfo [] p = pi.GetIndexParameters ();
1693 return ParametersCompiled.EmptyReadOnlyParameters;
1695 pd = ParametersImported.Create (p, null);
1696 method_params.Add (pi, pd);
1702 public static AParametersCollection GetDelegateParameters (Type t)
1704 Delegate d = builder_to_declspace [t] as Delegate;
1706 return d.Parameters;
1708 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1709 return GetParameterData (invoke_mb);
1712 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1714 if (!method_overrides.Contains (override_method))
1715 method_overrides [override_method] = base_method;
1716 if (method_overrides [override_method] != base_method)
1717 throw new InternalErrorException ("Override mismatch: " + override_method);
1720 static public bool IsOverride (MethodBase m)
1722 m = DropGenericMethodArguments (m);
1724 return m.IsVirtual &&
1725 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1726 (m is MethodBuilder || method_overrides.Contains (m));
1729 static public MethodBase TryGetBaseDefinition (MethodBase m)
1731 m = DropGenericMethodArguments (m);
1733 return (MethodBase) method_overrides [m];
1736 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1738 fields.Add (fb, ic);
1741 public static IConstant GetConstant (FieldInfo fb)
1746 return (IConstant)fields [fb];
1749 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1751 propertybuilder_to_property.Add (pi, pb);
1754 public static PropertyBase GetProperty (PropertyInfo pi)
1756 return (PropertyBase)propertybuilder_to_property [pi];
1759 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1761 fieldbuilders_to_fields.Add (fb, f);
1765 // The return value can be null; This will be the case for
1766 // auxiliary FieldBuilders created by the compiler that have no
1767 // real field being declared on the source code
1769 static public FieldBase GetField (FieldInfo fb)
1772 fb = GetGenericFieldDefinition (fb);
1774 return (FieldBase) fieldbuilders_to_fields [fb];
1777 static public MethodInfo GetAddMethod (EventInfo ei)
1779 if (ei is MyEventBuilder) {
1780 return ((MyEventBuilder)ei).GetAddMethod (true);
1782 return ei.GetAddMethod (true);
1785 static public MethodInfo GetRemoveMethod (EventInfo ei)
1787 if (ei is MyEventBuilder) {
1788 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1790 return ei.GetRemoveMethod (true);
1793 static public void RegisterEventField (EventInfo einfo, EventField e)
1796 events = new Hashtable ();
1798 events.Add (einfo, e);
1801 static public EventField GetEventField (EventInfo ei)
1806 return (EventField) events [ei];
1809 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1811 Hashtable hash = new Hashtable ();
1812 return CheckStructCycles (tc, seen, hash);
1815 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1818 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1822 // `seen' contains all types we've already visited.
1824 if (seen.Contains (tc))
1826 seen.Add (tc, null);
1828 if (tc.Fields == null)
1831 foreach (FieldBase field in tc.Fields) {
1832 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1835 Type ftype = field.FieldBuilder.FieldType;
1836 TypeContainer ftc = LookupTypeContainer (ftype);
1840 if (hash.Contains (ftc)) {
1841 Report.Error (523, tc.Location,
1842 "Struct member `{0}.{1}' of type `{2}' " +
1843 "causes a cycle in the struct layout",
1844 tc.Name, field.Name, ftc.Name);
1849 // `hash' contains all types in the current path.
1851 hash.Add (tc, null);
1853 bool ok = CheckStructCycles (ftc, seen, hash);
1860 if (!seen.Contains (ftc))
1861 seen.Add (ftc, null);
1868 /// Given an array of interface types, expand and eliminate repeated ocurrences
1869 /// of an interface.
1873 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1876 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1878 ArrayList new_ifaces = new ArrayList ();
1880 foreach (TypeExpr iface in base_interfaces){
1881 Type itype = iface.Type;
1883 if (new_ifaces.Contains (itype))
1886 new_ifaces.Add (itype);
1888 Type [] implementing = GetInterfaces (itype);
1890 foreach (Type imp in implementing){
1891 if (!new_ifaces.Contains (imp))
1892 new_ifaces.Add (imp);
1895 Type [] ret = new Type [new_ifaces.Count];
1896 new_ifaces.CopyTo (ret, 0);
1900 public static Type[] ExpandInterfaces (Type [] base_interfaces)
1902 ArrayList new_ifaces = new ArrayList ();
1904 foreach (Type itype in base_interfaces){
1905 if (new_ifaces.Contains (itype))
1908 new_ifaces.Add (itype);
1910 Type [] implementing = GetInterfaces (itype);
1912 foreach (Type imp in implementing){
1913 if (!new_ifaces.Contains (imp))
1914 new_ifaces.Add (imp);
1917 Type [] ret = new Type [new_ifaces.Count];
1918 new_ifaces.CopyTo (ret, 0);
1922 static PtrHashtable iface_cache;
1925 /// This function returns the interfaces in the type `t'. Works with
1926 /// both types and TypeBuilders.
1928 public static Type [] GetInterfaces (Type t)
1930 Type [] cached = iface_cache [t] as Type [];
1935 // The reason for catching the Array case is that Reflection.Emit
1936 // will not return a TypeBuilder for Array types of TypeBuilder types,
1937 // but will still throw an exception if we try to call GetInterfaces
1940 // Since the array interfaces are always constant, we return those for
1945 t = TypeManager.array_type;
1947 if ((t is TypeBuilder) || IsGenericType (t)) {
1948 Type [] base_ifaces;
1950 if (t.BaseType == null)
1951 base_ifaces = Type.EmptyTypes;
1953 base_ifaces = GetInterfaces (t.BaseType);
1955 if (IsGenericType (t))
1956 #if MS_COMPATIBLE && GMCS_SOURCE
1957 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
1959 type_ifaces = t.GetInterfaces ();
1962 type_ifaces = (Type []) builder_to_ifaces [t];
1963 if (type_ifaces == null || type_ifaces.Length == 0)
1964 type_ifaces = Type.EmptyTypes;
1966 int base_count = base_ifaces.Length;
1967 Type [] result = new Type [base_count + type_ifaces.Length];
1968 base_ifaces.CopyTo (result, 0);
1969 type_ifaces.CopyTo (result, base_count);
1971 iface_cache [t] = result;
1973 } else if (t is GenericTypeParameterBuilder){
1974 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
1975 if (type_ifaces == null || type_ifaces.Length == 0)
1976 type_ifaces = Type.EmptyTypes;
1978 iface_cache [t] = type_ifaces;
1981 Type[] ifaces = t.GetInterfaces ();
1982 iface_cache [t] = ifaces;
1988 // gets the interfaces that are declared explicitly on t
1990 public static Type [] GetExplicitInterfaces (TypeBuilder t)
1992 return (Type []) builder_to_ifaces [t];
1996 /// The following is used to check if a given type implements an interface.
1997 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1999 public static bool ImplementsInterface (Type t, Type iface)
2004 // FIXME OPTIMIZATION:
2005 // as soon as we hit a non-TypeBuiler in the interface
2006 // chain, we could return, as the `Type.GetInterfaces'
2007 // will return all the interfaces implement by the type
2011 interfaces = GetInterfaces (t);
2013 if (interfaces != null){
2014 foreach (Type i in interfaces){
2015 if (i == iface || IsVariantOf (i, iface))
2021 } while (t != null);
2026 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2028 // This is a custom version of Convert.ChangeType() which works
2029 // with the TypeBuilder defined types when compiling corlib.
2030 public static object ChangeType (object value, Type conversionType, out bool error)
2032 IConvertible convert_value = value as IConvertible;
2034 if (convert_value == null){
2041 // We must use Type.Equals() here since `conversionType' is
2042 // the TypeBuilder created version of a system type and not
2043 // the system type itself. You cannot use Type.GetTypeCode()
2044 // on such a type - it'd always return TypeCode.Object.
2047 // We cannot rely on build-in type conversions as they are
2048 // more limited than what C# supports.
2049 // See char -> float/decimal/double conversion
2054 if (conversionType.Equals (typeof (Boolean)))
2055 return (object)(convert_value.ToBoolean (nf_provider));
2056 if (conversionType.Equals (typeof (Byte)))
2057 return (object)(convert_value.ToByte (nf_provider));
2058 if (conversionType.Equals (typeof (Char)))
2059 return (object)(convert_value.ToChar (nf_provider));
2060 if (conversionType.Equals (typeof (DateTime)))
2061 return (object)(convert_value.ToDateTime (nf_provider));
2063 if (conversionType.Equals (decimal_type)) {
2064 if (convert_value.GetType () == TypeManager.char_type)
2065 return (decimal)convert_value.ToInt32 (nf_provider);
2066 return convert_value.ToDecimal (nf_provider);
2069 if (conversionType.Equals (typeof (Double))) {
2070 if (convert_value.GetType () == TypeManager.char_type)
2071 return (double)convert_value.ToInt32 (nf_provider);
2072 return convert_value.ToDouble (nf_provider);
2075 if (conversionType.Equals (typeof (Int16)))
2076 return (object)(convert_value.ToInt16 (nf_provider));
2077 if (conversionType.Equals (int32_type))
2078 return (object)(convert_value.ToInt32 (nf_provider));
2079 if (conversionType.Equals (int64_type))
2080 return (object)(convert_value.ToInt64 (nf_provider));
2081 if (conversionType.Equals (typeof (SByte)))
2082 return (object)(convert_value.ToSByte (nf_provider));
2084 if (conversionType.Equals (typeof (Single))) {
2085 if (convert_value.GetType () == TypeManager.char_type)
2086 return (float)convert_value.ToInt32 (nf_provider);
2087 return convert_value.ToSingle (nf_provider);
2090 if (conversionType.Equals (typeof (String)))
2091 return (object)(convert_value.ToString (nf_provider));
2092 if (conversionType.Equals (typeof (UInt16)))
2093 return (object)(convert_value.ToUInt16 (nf_provider));
2094 if (conversionType.Equals (typeof (UInt32)))
2095 return (object)(convert_value.ToUInt32 (nf_provider));
2096 if (conversionType.Equals (typeof (UInt64)))
2097 return (object)(convert_value.ToUInt64 (nf_provider));
2098 if (conversionType.Equals (typeof (Object)))
2099 return (object)(value);
2109 // When compiling with -nostdlib and the type is imported from an external assembly
2110 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2112 public static Type TypeToCoreType (Type t)
2114 if (RootContext.StdLib || t.Module != typeof (object).Module)
2117 TypeCode tc = Type.GetTypeCode (t);
2120 case TypeCode.Boolean:
2121 return TypeManager.bool_type;
2123 return TypeManager.byte_type;
2124 case TypeCode.SByte:
2125 return TypeManager.sbyte_type;
2127 return TypeManager.char_type;
2128 case TypeCode.Int16:
2129 return TypeManager.short_type;
2130 case TypeCode.UInt16:
2131 return TypeManager.ushort_type;
2132 case TypeCode.Int32:
2133 return TypeManager.int32_type;
2134 case TypeCode.UInt32:
2135 return TypeManager.uint32_type;
2136 case TypeCode.Int64:
2137 return TypeManager.int64_type;
2138 case TypeCode.UInt64:
2139 return TypeManager.uint64_type;
2140 case TypeCode.Single:
2141 return TypeManager.float_type;
2142 case TypeCode.Double:
2143 return TypeManager.double_type;
2144 case TypeCode.String:
2145 return TypeManager.string_type;
2146 case TypeCode.Decimal:
2147 return TypeManager.decimal_type;
2150 if (t == typeof (void))
2151 return TypeManager.void_type;
2152 if (t == typeof (object))
2153 return TypeManager.object_type;
2154 if (t == typeof (System.Type))
2155 return TypeManager.type_type;
2156 if (t == typeof (System.IntPtr))
2157 return TypeManager.intptr_type;
2158 if (t == typeof (System.UIntPtr))
2159 return TypeManager.uintptr_type;
2162 int dim = t.GetArrayRank ();
2163 t = GetElementType (t);
2164 return t.MakeArrayType (dim);
2167 t = GetElementType (t);
2168 return t.MakeByRefType ();
2171 t = GetElementType (t);
2172 return t.MakePointerType ();
2179 // Converts any type to reflection supported type
2181 public static Type TypeToReflectionType (Type type)
2183 // TODO: Very lame and painful, GetReference () is enough for mcs-cecil
2184 return type == InternalType.Dynamic ? object_type : type;
2188 /// Utility function that can be used to probe whether a type
2189 /// is managed or not.
2191 public static bool VerifyUnManaged (Type t, Location loc)
2193 if (IsUnmanagedType (t))
2197 t = GetElementType (t);
2199 Report.SymbolRelatedToPreviousError (t);
2200 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2207 /// Returns the name of the indexer in a given type.
2210 /// The default is not always `Item'. The user can change this behaviour by
2211 /// using the IndexerNameAttribute in the container.
2212 /// For example, the String class indexer is named `Chars' not `Item'
2214 public static string IndexerPropertyName (Type t)
2216 t = DropGenericTypeArguments (t);
2217 if (t is TypeBuilder) {
2218 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2219 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2222 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
2224 System.Attribute attr = System.Attribute.GetCustomAttribute (
2227 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2228 return dma.MemberName;
2232 return TypeContainer.DefaultIndexerName;
2235 static MethodInfo declare_local_method = null;
2237 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2239 if (declare_local_method == null){
2240 declare_local_method = typeof (ILGenerator).GetMethod (
2242 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2244 new Type [] { typeof (Type), typeof (bool)},
2246 if (declare_local_method == null){
2247 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2248 return ig.DeclareLocal (t);
2251 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2254 private static bool IsSignatureEqual (Type a, Type b)
2257 /// Consider the following example (bug #77674):
2259 /// public abstract class A
2261 /// public abstract T Foo<T> ();
2264 /// public abstract class B : A
2266 /// public override U Foo<T> ()
2267 /// { return default (U); }
2270 /// Here, `T' and `U' are method type parameters from different methods
2271 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2273 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2274 /// we need to do a signature based comparision and consider them equal.
2280 if (a.IsGenericParameter && b.IsGenericParameter &&
2281 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2282 return a.GenericParameterPosition == b.GenericParameterPosition;
2286 if (a.IsArray && b.IsArray) {
2287 if (a.GetArrayRank () != b.GetArrayRank ())
2290 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2293 if (a.IsByRef && b.IsByRef)
2294 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2296 if (IsGenericType (a) && IsGenericType (b)) {
2297 if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
2300 Type[] aargs = GetTypeArguments (a);
2301 Type[] bargs = GetTypeArguments (b);
2303 if (aargs.Length != bargs.Length)
2306 for (int i = 0; i < aargs.Length; i++) {
2307 if (!IsSignatureEqual (aargs [i], bargs [i]))
2318 // Returns whether the array of memberinfos contains the given method
2320 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2322 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2324 foreach (MethodBase method in array) {
2325 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2328 if (method.Name != new_method.Name)
2331 if (method is MethodInfo && new_method is MethodInfo &&
2333 TypeToCoreType (((MethodInfo) method).ReturnType),
2334 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2337 Type [] old_args = TypeManager.GetParameterData (method).Types;
2338 int old_count = old_args.Length;
2341 if (new_args.Length != old_count)
2344 for (i = 0; i < old_count; i++){
2345 if (!IsSignatureEqual (old_args [i], new_args [i]))
2358 // We copy methods from `new_members' into `target_list' if the signature
2359 // for the method from in the new list does not exist in the target_list
2361 // The name is assumed to be the same.
2363 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2365 if (target_list == null){
2366 target_list = new ArrayList ();
2368 foreach (MemberInfo mi in new_members){
2369 if (mi is MethodBase)
2370 target_list.Add (mi);
2375 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2376 target_list.CopyTo (target_array, 0);
2378 foreach (MemberInfo mi in new_members){
2379 MethodBase new_method = (MethodBase) mi;
2381 if (!ArrayContainsMethod (target_array, new_method, true))
2382 target_list.Add (new_method);
2389 // Tracks the generic parameters.
2391 static PtrHashtable builder_to_type_param;
2393 public static void AddTypeParameter (Type t, TypeParameter tparam)
2395 if (!builder_to_type_param.Contains (t))
2396 builder_to_type_param.Add (t, tparam);
2399 public static TypeParameter LookupTypeParameter (Type t)
2401 return (TypeParameter) builder_to_type_param [t];
2404 // This method always return false for non-generic compiler,
2405 // while Type.IsGenericParameter is returned if it is supported.
2406 public static bool IsGenericParameter (Type type)
2409 return type.IsGenericParameter;
2415 public static int GenericParameterPosition (Type type)
2418 return type.GenericParameterPosition;
2420 throw new InternalErrorException ("should not be called");
2424 public static bool IsGenericType (Type type)
2427 return type.IsGenericType;
2433 public static bool IsGenericTypeDefinition (Type type)
2436 return type.IsGenericTypeDefinition;
2442 public static bool ContainsGenericParameters (Type type)
2445 return type.ContainsGenericParameters;
2451 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2454 if (fi.DeclaringType.IsGenericTypeDefinition ||
2455 !fi.DeclaringType.IsGenericType)
2458 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2459 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2460 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2462 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2463 foreach (FieldInfo f in t.GetFields (bf))
2464 if (f.MetadataToken == fi.MetadataToken)
2471 public static bool IsEqual (Type a, Type b)
2474 // MS BCL returns true even if enum types are different
2475 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2476 return a.FullName == b.FullName;
2478 // Some types are never equal
2479 if (a == TypeManager.null_type || a == InternalType.AnonymousMethod)
2485 if (IsGenericParameter (a) && IsGenericParameter (b)) {
2486 // TODO: needs more testing before cleaning up
2487 //if (a.DeclaringMethod != b.DeclaringMethod &&
2488 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2491 return a.GenericParameterPosition == b.GenericParameterPosition;
2493 throw new NotSupportedException ();
2497 if (a.IsArray && b.IsArray) {
2498 if (a.GetArrayRank () != b.GetArrayRank ())
2500 return IsEqual (GetElementType (a), GetElementType (b));
2503 if (a.IsByRef && b.IsByRef)
2504 return IsEqual (a.GetElementType (), b.GetElementType ());
2506 if (IsGenericType (a) && IsGenericType (b)) {
2507 Type adef = DropGenericTypeArguments (a);
2508 Type bdef = DropGenericTypeArguments (b);
2513 if (adef.IsEnum && bdef.IsEnum)
2516 Type[] aargs = GetTypeArguments (a);
2517 Type[] bargs = GetTypeArguments (b);
2519 if (aargs.Length != bargs.Length)
2522 for (int i = 0; i < aargs.Length; i++) {
2523 if (!IsEqual (aargs [i], bargs [i]))
2533 public static bool IsEqual (Type[] a, Type[] b)
2535 if (a == null || b == null || a.Length != b.Length)
2538 for (int i = 0; i < a.Length; ++i) {
2539 if (a [i] == null || b [i] == null) {
2546 if (!IsEqual (a [i], b [i]))
2553 public static Type DropGenericTypeArguments (Type t)
2556 if (!t.IsGenericType)
2558 // Micro-optimization: a generic typebuilder is always a generic type definition
2559 if (t is TypeBuilder)
2561 return t.GetGenericTypeDefinition ();
2567 public static MethodBase DropGenericMethodArguments (MethodBase m)
2570 if (m.IsGenericMethod)
2571 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2573 Type t = m.DeclaringType;
2574 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2577 t = t.GetGenericTypeDefinition ();
2578 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2579 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2582 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2586 if (m is ConstructorInfo) {
2587 foreach (ConstructorInfo c in t.GetConstructors (bf))
2588 if (c.MetadataToken == m.MetadataToken)
2591 foreach (MethodBase mb in t.GetMethods (bf))
2592 if (mb.MetadataToken == m.MetadataToken)
2600 public static Type[] GetGenericArguments (MethodBase mi)
2603 return mi.GetGenericArguments ();
2605 return Type.EmptyTypes;
2609 public static Type[] GetTypeArguments (Type t)
2612 DeclSpace tc = LookupDeclSpace (t);
2615 return Type.EmptyTypes;
2617 TypeParameter[] tparam = tc.TypeParameters;
2618 Type[] ret = new Type [tparam.Length];
2619 for (int i = 0; i < tparam.Length; i++) {
2620 ret [i] = tparam [i].Type;
2621 if (ret [i] == null)
2622 throw new InternalErrorException ();
2627 return t.GetGenericArguments ();
2629 throw new InternalErrorException ();
2633 public static GenericConstraints GetTypeParameterConstraints (Type t)
2636 if (!t.IsGenericParameter)
2637 throw new InvalidOperationException ();
2639 TypeParameter tparam = LookupTypeParameter (t);
2641 return tparam.GenericConstraints;
2643 return ReflectionConstraints.GetConstraints (t);
2645 throw new InternalErrorException ();
2649 public static bool HasGenericArguments (Type t)
2651 return GetNumberOfTypeArguments (t) > 0;
2654 public static int GetNumberOfTypeArguments (Type t)
2657 if (t.IsGenericParameter)
2659 DeclSpace tc = LookupDeclSpace (t);
2661 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2663 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2670 /// Check whether `type' and `parent' are both instantiations of the same
2671 /// generic type. Note that we do not check the type parameters here.
2673 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2675 int tcount = GetNumberOfTypeArguments (type);
2676 int pcount = GetNumberOfTypeArguments (parent);
2678 if (tcount != pcount)
2681 type = DropGenericTypeArguments (type);
2682 parent = DropGenericTypeArguments (parent);
2684 return type.Equals (parent);
2688 /// Whether `mb' is a generic method definition.
2690 public static bool IsGenericMethodDefinition (MethodBase mb)
2693 if (mb.DeclaringType is TypeBuilder) {
2694 IMethodData method = (IMethodData) builder_to_method [mb];
2698 return method.GenericMethod != null;
2701 return mb.IsGenericMethodDefinition;
2708 /// Whether `mb' is a generic method.
2710 public static bool IsGenericMethod (MethodBase mb)
2713 return mb.IsGenericMethod;
2719 public static bool IsNullableType (Type t)
2722 return generic_nullable_type == DropGenericTypeArguments (t);
2729 #region MemberLookup implementation
2732 // Whether we allow private members in the result (since FindMembers
2733 // uses NonPublic for both protected and private), we need to distinguish.
2736 internal class Closure {
2737 internal bool private_ok;
2739 // Who is invoking us and which type is being queried currently.
2740 internal Type invocation_type;
2741 internal Type qualifier_type;
2743 // The assembly that defines the type is that is calling us
2744 internal Assembly invocation_assembly;
2745 internal IList almost_match;
2747 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2749 if (invocation_type == null)
2752 if (is_static && qualifier_type == null)
2753 // It resolved from a simple name, so it should be visible.
2756 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2759 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2760 if (!IsFamilyAccessible (t, m.DeclaringType))
2763 // Although a derived class can access protected members of its base class
2764 // it cannot do so through an instance of the base class (CS1540).
2765 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2766 if (is_static || qualifier_type == null ||
2767 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2768 IsFamilyAccessible (qualifier_type, t))
2772 if (almost_match != null)
2773 almost_match.Add (m);
2779 // This filter filters by name + whether it is ok to include private
2780 // members in the search
2782 internal bool Filter (MemberInfo m, object filter_criteria)
2785 // Hack: we know that the filter criteria will always be in the
2786 // `closure' // fields.
2789 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2792 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2793 (invocation_type != null) &&
2794 IsPrivateAccessible (m.DeclaringType, invocation_type))
2798 // Ugly: we need to find out the type of `m', and depending
2799 // on this, tell whether we accept or not
2801 if (m is MethodBase){
2802 MethodBase mb = (MethodBase) m;
2803 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2805 if (ma == MethodAttributes.Public)
2808 if (ma == MethodAttributes.PrivateScope)
2811 if (ma == MethodAttributes.Private)
2812 return private_ok ||
2813 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2814 IsNestedChildOf (invocation_type, m.DeclaringType);
2816 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2817 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2820 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2824 // Family, FamORAssem or FamANDAssem
2825 return CheckValidFamilyAccess (mb.IsStatic, m);
2828 if (m is FieldInfo){
2829 FieldInfo fi = (FieldInfo) m;
2830 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2832 if (fa == FieldAttributes.Public)
2835 if (fa == FieldAttributes.PrivateScope)
2838 if (fa == FieldAttributes.Private)
2839 return private_ok ||
2840 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2841 IsNestedChildOf (invocation_type, m.DeclaringType);
2843 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2844 if ((fa == FieldAttributes.Assembly) ||
2845 (fa == FieldAttributes.FamORAssem))
2848 if ((fa == FieldAttributes.Assembly) ||
2849 (fa == FieldAttributes.FamANDAssem))
2853 // Family, FamORAssem or FamANDAssem
2854 return CheckValidFamilyAccess (fi.IsStatic, m);
2858 // EventInfos and PropertyInfos, return true because they lack
2859 // permission information, so we need to check later on the methods.
2865 static Closure closure;
2866 static MemberFilter FilterWithClosure_delegate;
2869 // Looks up a member called `name' in the `queried_type'. This lookup
2870 // is done by code that is contained in the definition for `invocation_type'
2871 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2873 // `invocation_type' is used to check whether we're allowed to access the requested
2874 // member wrt its protection level.
2876 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2877 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2878 // is B and qualifier_type is A). This is used to do the CS1540 check.
2880 // When resolving a SimpleName, `qualifier_type' is null.
2882 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2883 // the same than `queried_type' - except when we're being called from BaseAccess;
2884 // in this case, `invocation_type' is the current type and `queried_type' the base
2885 // type, so this'd normally trigger a CS1540.
2887 // The binding flags are `bf' and the kind of members being looked up are `mt'
2889 // The return value always includes private members which code in `invocation_type'
2890 // is allowed to access (using the specified `qualifier_type' if given); only use
2891 // BindingFlags.NonPublic to bypass the permission check.
2893 // The 'almost_match' argument is used for reporting error CS1540.
2895 // Returns an array of a single element for everything but Methods/Constructors
2896 // that might return multiple matches.
2898 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2899 Type queried_type, MemberTypes mt,
2900 BindingFlags original_bf, string name, IList almost_match)
2902 Timer.StartTimer (TimerType.MemberLookup);
2904 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2905 queried_type, mt, original_bf, name, almost_match);
2907 Timer.StopTimer (TimerType.MemberLookup);
2912 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2913 Type queried_type, MemberTypes mt,
2914 BindingFlags original_bf, string name, IList almost_match)
2916 BindingFlags bf = original_bf;
2918 ArrayList method_list = null;
2919 Type current_type = queried_type;
2920 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2921 bool skip_iface_check = true, used_cache = false;
2922 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2924 closure.invocation_type = invocation_type;
2925 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2926 closure.qualifier_type = qualifier_type;
2927 closure.almost_match = almost_match;
2929 // This is from the first time we find a method
2930 // in most cases, we do not actually find a method in the base class
2931 // so we can just ignore it, and save the arraylist allocation
2932 MemberInfo [] first_members_list = null;
2933 bool use_first_members_list = false;
2939 // `NonPublic' is lame, because it includes both protected and
2940 // private methods, so we need to control this behavior by
2941 // explicitly tracking if a private method is ok or not.
2943 // The possible cases are:
2944 // public, private and protected (internal does not come into the
2947 if ((invocation_type != null) &&
2948 ((invocation_type == current_type) ||
2949 IsNestedChildOf (invocation_type, current_type)) ||
2951 bf = original_bf | BindingFlags.NonPublic;
2955 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2957 Timer.StopTimer (TimerType.MemberLookup);
2959 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2961 Timer.StartTimer (TimerType.MemberLookup);
2964 // When queried for an interface type, the cache will automatically check all
2965 // inherited members, so we don't need to do this here. However, this only
2966 // works if we already used the cache in the first iteration of this loop.
2968 // If we used the cache in any further iteration, we can still terminate the
2969 // loop since the cache always looks in all base classes.
2975 skip_iface_check = false;
2977 if (current_type == TypeManager.object_type)
2980 current_type = current_type.BaseType;
2983 // This happens with interfaces, they have a null
2984 // basetype. Look members up in the Object class.
2986 if (current_type == null) {
2987 current_type = TypeManager.object_type;
2992 if (list.Length == 0)
2996 // Events and types are returned by both `static' and `instance'
2997 // searches, which means that our above FindMembers will
2998 // return two copies of the same.
3000 if (list.Length == 1 && !(list [0] is MethodBase)){
3005 // Multiple properties: we query those just to find out the indexer
3008 if (list [0] is PropertyInfo)
3012 // We found an event: the cache lookup returns both the event and
3013 // its private field.
3015 if (list [0] is EventInfo) {
3016 if ((list.Length == 2) && (list [1] is FieldInfo))
3017 return new MemberInfo [] { list [0] };
3023 // We found methods, turn the search into "method scan"
3027 if (first_members_list != null) {
3028 if (use_first_members_list) {
3029 method_list = CopyNewMethods (method_list, first_members_list);
3030 use_first_members_list = false;
3033 method_list = CopyNewMethods (method_list, list);
3035 first_members_list = list;
3036 use_first_members_list = true;
3037 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3039 } while (searching);
3041 if (use_first_members_list)
3042 return first_members_list;
3044 if (method_list != null && method_list.Count > 0) {
3045 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3048 // This happens if we already used the cache in the first iteration, in this case
3049 // the cache already looked in all interfaces.
3051 if (skip_iface_check)
3055 // Interfaces do not list members they inherit, so we have to
3058 if (!queried_type.IsInterface)
3061 if (queried_type.IsArray)
3062 queried_type = TypeManager.array_type;
3064 Type [] ifaces = GetInterfaces (queried_type);
3068 foreach (Type itype in ifaces){
3071 x = MemberLookup (null, null, itype, mt, bf, name, null);
3079 const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3080 BindingFlags.Static | BindingFlags.Instance |
3081 BindingFlags.DeclaredOnly;
3083 // Currently is designed to work with external types only
3084 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3086 if (!mb.IsSpecialName)
3089 string name = mb.Name;
3090 if (name.Length < 5)
3093 if (name [3] != '_')
3096 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3097 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3098 Type.FilterName, name.Substring (4));
3103 // This can happen when property is indexer (it can have same name but different parameters)
3104 foreach (PropertyInfo p in pi) {
3105 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3106 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3115 // Currently is designed to work with external types only
3116 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3118 if (!mb.IsSpecialName)
3121 string name = mb.Name;
3122 if (name.Length < 5)
3125 if (name.StartsWith ("add_"))
3126 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3128 if (name.StartsWith ("remove_"))
3129 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3134 // Tests whether external method is really special
3135 public static bool IsSpecialMethod (MethodBase mb)
3137 if (!mb.IsSpecialName)
3140 IMethodData md = TypeManager.GetMethod (mb);
3142 return (md is AbstractPropertyEventMethod || md is Operator);
3144 PropertyInfo pi = GetPropertyFromAccessor (mb);
3146 return IsValidProperty (pi);
3148 if (GetEventFromAccessor (mb) != null)
3151 string name = mb.Name;
3152 if (name.StartsWith ("op_"))
3153 return Operator.GetName (name) != null;
3158 // Tests whether imported property is valid C# property.
3159 // TODO: It seems to me that we should do a lot of sanity tests before
3160 // we accept property as C# property
3161 static bool IsValidProperty (PropertyInfo pi)
3163 MethodInfo get_method = pi.GetGetMethod (true);
3164 MethodInfo set_method = pi.GetSetMethod (true);
3167 if (get_method != null && set_method != null) {
3168 g_count = get_method.GetParameters ().Length;
3169 s_count = set_method.GetParameters ().Length;
3170 if (g_count + 1 != s_count)
3172 } else if (get_method != null) {
3173 g_count = get_method.GetParameters ().Length;
3174 } else if (set_method != null) {
3175 s_count = set_method.GetParameters ().Length;
3179 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3181 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
3182 if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
3183 object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
3187 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3188 if (dma.MemberName != pi.Name)
3190 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3192 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3205 public static readonly Type AnonymousMethod = typeof (AnonymousMethodBody);
3206 public static readonly Type Arglist = typeof (ArglistAccess);
3207 public static readonly Type Dynamic = new DynamicType ();
3208 public static readonly Type MethodGroup = typeof (MethodGroupExpr);
3212 /// There is exactly one instance of this class per type.
3214 public sealed class TypeHandle : IMemberContainer {
3215 public readonly IMemberContainer BaseType;
3217 readonly int id = ++next_id;
3218 static int next_id = 0;
3220 static TypeHandle ()
3226 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3227 /// a TypeHandle yet, a new instance of it is created. This static method
3228 /// ensures that we'll only have one TypeHandle instance per type.
3230 private static TypeHandle GetTypeHandle (Type t)
3232 TypeHandle handle = (TypeHandle) type_hash [t];
3236 handle = new TypeHandle (t);
3237 type_hash.Add (t, handle);
3241 public static MemberCache GetMemberCache (Type t)
3243 return GetTypeHandle (t).MemberCache;
3246 public static void CleanUp ()
3251 public static void Reset ()
3253 type_hash = new PtrHashtable ();
3257 /// Returns the TypeHandle for TypeManager.object_type.
3259 public static IMemberContainer ObjectType {
3261 if (object_type != null)
3264 object_type = GetTypeHandle (TypeManager.object_type);
3271 /// Returns the TypeHandle for TypeManager.array_type.
3273 public static TypeHandle ArrayType {
3275 if (array_type != null)
3278 array_type = GetTypeHandle (TypeManager.array_type);
3284 private static PtrHashtable type_hash;
3286 private static TypeHandle object_type = null;
3287 private static TypeHandle array_type = null;
3290 private string full_name;
3291 private bool is_interface;
3292 private MemberCache member_cache;
3293 private MemberCache base_cache;
3295 private TypeHandle (Type type)
3298 full_name = type.FullName != null ? type.FullName : type.Name;
3299 if (type.BaseType != null) {
3300 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3301 BaseType = base_cache.Container;
3302 } else if (type.IsInterface)
3303 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3304 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3305 this.member_cache = new MemberCache (this);
3308 // IMemberContainer methods
3310 public string Name {
3322 public MemberCache BaseCache {
3328 public bool IsInterface {
3330 return is_interface;
3334 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3336 MemberInfo [] members;
3338 if (type is GenericTypeParameterBuilder)
3339 return MemberList.Empty;
3342 type = TypeManager.DropGenericTypeArguments (type);
3344 if (mt == MemberTypes.Event)
3345 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3347 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3350 if (members.Length == 0)
3351 return MemberList.Empty;
3353 Array.Reverse (members);
3354 return new MemberList (members);
3357 // IMemberFinder methods
3359 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3360 MemberFilter filter, object criteria)
3362 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3365 public MemberCache MemberCache {
3367 return member_cache;
3371 public override string ToString ()
3373 if (BaseType != null)
3374 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3376 return "TypeHandle (" + id + "," + Name + ")";