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;
94 public static Type fieldinfo_type;
95 public static Type methodinfo_type;
96 public static Type ctorinfo_type;
101 public static Type call_site_type;
102 public static Type generic_call_site_type;
105 // Expressions representing the internal types. Used during declaration
108 static public TypeExpr system_object_expr, system_string_expr;
109 static public TypeExpr system_boolean_expr, system_decimal_expr;
110 static public TypeExpr system_single_expr, system_double_expr;
111 static public TypeExpr system_sbyte_expr, system_byte_expr;
112 static public TypeExpr system_int16_expr, system_uint16_expr;
113 static public TypeExpr system_int32_expr, system_uint32_expr;
114 static public TypeExpr system_int64_expr, system_uint64_expr;
115 static public TypeExpr system_char_expr, system_void_expr;
116 static public TypeExpr system_valuetype_expr;
117 static public TypeExpr system_intptr_expr;
118 public static TypeExpr expression_type_expr;
122 // These methods are called by code generated by the compiler
124 static public FieldInfo string_empty;
125 static public MethodInfo system_type_get_type_from_handle;
126 static public MethodInfo bool_movenext_void;
127 static public MethodInfo void_dispose_void;
128 static public MethodInfo void_monitor_enter_object;
129 static public MethodInfo void_monitor_exit_object;
130 static public MethodInfo void_initializearray_array_fieldhandle;
131 static public MethodInfo delegate_combine_delegate_delegate;
132 static public MethodInfo delegate_remove_delegate_delegate;
133 static public PropertyInfo int_get_offset_to_string_data;
134 static public MethodInfo int_interlocked_compare_exchange;
135 static public PropertyInfo ienumerator_getcurrent;
136 public static MethodInfo methodbase_get_type_from_handle;
137 public static MethodInfo methodbase_get_type_from_handle_generic;
138 public static MethodInfo fieldinfo_get_field_from_handle;
139 public static MethodInfo fieldinfo_get_field_from_handle_generic;
140 static public MethodInfo activator_create_instance;
145 static public ConstructorInfo void_decimal_ctor_five_args;
146 static public ConstructorInfo void_decimal_ctor_int_arg;
148 static PtrHashtable builder_to_declspace;
150 static PtrHashtable builder_to_member_cache;
153 // Tracks the interfaces implemented by typebuilders. We only
154 // enter those who do implement or or more interfaces
156 static PtrHashtable builder_to_ifaces;
159 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
161 static Hashtable method_params;
164 // A hash table from override methods to their base virtual method.
166 static Hashtable method_overrides;
169 // Keeps track of methods
172 static Hashtable builder_to_method;
175 // Contains all public types from referenced assemblies.
176 // This member is used only if CLS Compliance verification is required.
178 public static Hashtable AllClsTopLevelTypes;
180 static Hashtable fieldbuilders_to_fields;
181 static Hashtable propertybuilder_to_property;
182 static Hashtable fields;
183 static Hashtable events;
184 static PtrHashtable assembly_internals_vis_attrs;
186 public static void CleanUp ()
188 // Lets get everything clean so that we can collect before generating code
189 builder_to_declspace = null;
190 builder_to_member_cache = null;
191 builder_to_ifaces = null;
192 builder_to_type_param = null;
193 method_params = null;
194 builder_to_method = null;
199 propertybuilder_to_property = null;
201 TypeHandle.CleanUp ();
205 // These are expressions that represent some of the internal data types, used
208 static void InitExpressionTypes ()
210 system_object_expr = new TypeLookupExpression ("System", "Object");
211 system_string_expr = new TypeLookupExpression ("System", "String");
212 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
213 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
214 system_single_expr = new TypeLookupExpression ("System", "Single");
215 system_double_expr = new TypeLookupExpression ("System", "Double");
216 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
217 system_byte_expr = new TypeLookupExpression ("System", "Byte");
218 system_int16_expr = new TypeLookupExpression ("System", "Int16");
219 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
220 system_int32_expr = new TypeLookupExpression ("System", "Int32");
221 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
222 system_int64_expr = new TypeLookupExpression ("System", "Int64");
223 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
224 system_char_expr = new TypeLookupExpression ("System", "Char");
225 system_void_expr = new TypeLookupExpression ("System", "Void");
226 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
227 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
230 static TypeManager ()
235 static public void Reset ()
237 InitExpressionTypes ();
239 builder_to_declspace = new PtrHashtable ();
240 builder_to_member_cache = new PtrHashtable ();
241 builder_to_method = new PtrHashtable ();
242 builder_to_type_param = new PtrHashtable ();
243 method_params = new PtrHashtable ();
244 method_overrides = new PtrHashtable ();
245 builder_to_ifaces = new PtrHashtable ();
247 fieldbuilders_to_fields = new Hashtable ();
248 propertybuilder_to_property = new Hashtable ();
249 fields = new Hashtable ();
250 type_hash = new DoubleHash ();
251 assembly_internals_vis_attrs = new PtrHashtable ();
252 iface_cache = new PtrHashtable ();
254 closure = new Closure ();
255 FilterWithClosure_delegate = new MemberFilter (closure.Filter);
257 // TODO: I am really bored by all this static stuff
258 system_type_get_type_from_handle =
261 void_monitor_enter_object =
262 void_monitor_exit_object =
263 void_initializearray_array_fieldhandle =
264 delegate_combine_delegate_delegate =
265 delegate_remove_delegate_delegate =
266 int_interlocked_compare_exchange =
267 methodbase_get_type_from_handle =
268 methodbase_get_type_from_handle_generic =
269 fieldinfo_get_field_from_handle =
270 fieldinfo_get_field_from_handle_generic =
271 activator_create_instance = null;
273 int_get_offset_to_string_data =
274 ienumerator_getcurrent = null;
276 void_decimal_ctor_five_args =
277 void_decimal_ctor_int_arg = null;
279 isvolatile_type = null;
281 // to uncover regressions
282 AllClsTopLevelTypes = null;
285 public static void AddUserType (DeclSpace ds)
287 builder_to_declspace.Add (ds.TypeBuilder, ds);
291 // This entry point is used by types that we define under the covers
293 public static void RegisterBuilder (Type tb, Type [] ifaces)
296 builder_to_ifaces [tb] = ifaces;
299 public static void AddMethod (MethodBase builder, IMethodData method)
301 builder_to_method.Add (builder, method);
302 method_params.Add (builder, method.ParameterInfo);
305 public static IMethodData GetMethod (MethodBase builder)
307 return (IMethodData) builder_to_method [builder];
311 /// Returns the DeclSpace whose Type is `t' or null if there is no
312 /// DeclSpace for `t' (ie, the Type comes from a library)
314 public static DeclSpace LookupDeclSpace (Type t)
316 return builder_to_declspace [t] as DeclSpace;
320 /// Returns the TypeContainer whose Type is `t' or null if there is no
321 /// TypeContainer for `t' (ie, the Type comes from a library)
323 public static TypeContainer LookupTypeContainer (Type t)
325 return builder_to_declspace [t] as TypeContainer;
328 public static MemberCache LookupMemberCache (Type t)
330 if (t.Module == RootContext.ToplevelTypes.Builder) {
331 DeclSpace container = (DeclSpace)builder_to_declspace [t];
332 if (container != null)
333 return container.MemberCache;
337 if (t is GenericTypeParameterBuilder) {
338 TypeParameter container = builder_to_type_param [t] as TypeParameter;
340 if (container != null)
341 return container.MemberCache;
345 return TypeHandle.GetMemberCache (t);
348 public static MemberCache LookupBaseInterfacesCache (Type t)
350 Type [] ifaces = GetInterfaces (t);
352 if (ifaces != null && ifaces.Length == 1)
353 return LookupMemberCache (ifaces [0]);
355 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
356 MemberCache cache = builder_to_member_cache [t] as MemberCache;
360 cache = new MemberCache (ifaces);
361 builder_to_member_cache.Add (t, cache);
365 public static TypeContainer LookupInterface (Type t)
367 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
368 if ((tc == null) || (tc.Kind != Kind.Interface))
374 public static Delegate LookupDelegate (Type t)
376 return builder_to_declspace [t] as Delegate;
379 public static Class LookupClass (Type t)
381 return (Class) builder_to_declspace [t];
385 // We use this hash for multiple kinds of constructed types:
387 // (T, "&") Given T, get T &
388 // (T, "*") Given T, get T *
389 // (T, "[]") Given T and a array dimension, get T []
390 // (T, X) Given a type T and a simple name X, get the type T+X
392 // Accessibility tests, if necessary, should be done by the user
394 static DoubleHash type_hash = new DoubleHash ();
397 // Gets the reference to T version of the Type (T&)
399 public static Type GetReferenceType (Type t)
402 return t.MakeByRefType ();
404 return GetConstructedType (t, "&");
409 // Gets the pointer to T version of the Type (T*)
411 public static Type GetPointerType (Type t)
413 return GetConstructedType (t, "*");
416 public static Type GetConstructedType (Type t, string dim)
419 if (type_hash.Lookup (t, dim, out ret))
422 ret = t.Module.GetType (t.ToString () + dim);
424 type_hash.Insert (t, dim, ret);
429 ret = GetReferenceType (t);
430 type_hash.Insert (t, dim, ret);
435 if (t.IsGenericParameter || t.IsGenericType) {
438 while ((pos < dim.Length) && (dim [pos] == '[')) {
441 if (dim [pos] == ']') {
442 result = result.MakeArrayType ();
445 if (pos < dim.Length)
448 type_hash.Insert (t, dim, result);
453 while (dim [pos] == ',') {
457 if ((dim [pos] != ']') || (pos != dim.Length-1))
460 result = result.MakeArrayType (rank + 1);
461 type_hash.Insert (t, dim, result);
467 type_hash.Insert (t, dim, null);
471 public static Type GetNestedType (Type t, string name)
474 if (!type_hash.Lookup (t, name, out ret)) {
475 ret = t.GetNestedType (name,
476 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
477 type_hash.Insert (t, name, ret);
483 /// Fills static table with exported types from all referenced assemblies.
484 /// This information is required for CLS Compliance tests.
486 public static void LoadAllImportedTypes ()
488 AllClsTopLevelTypes = new Hashtable (1500);
489 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
490 foreach (Type t in a.GetExportedTypes ()) {
491 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
496 public static bool NamespaceClash (string name, Location loc)
498 if (!GlobalRootNamespace.Instance.IsNamespace (name))
501 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
506 /// Returns the C# name of a type if possible, or the full type name otherwise
508 static public string CSharpName (Type t)
513 if (t == typeof (ArglistAccess))
516 if (t == typeof (AnonymousMethodBody))
517 return "anonymous method";
519 if (t == typeof (MethodGroupExpr))
520 return "method group";
523 return "internal error";
525 return CSharpName (GetFullName (t), t);
528 static readonly char [] elements = new char [] { '*', '[' };
530 public static string CSharpName (string name, Type type)
532 if (name.Length > 10) {
535 case "System.Int32": s = "int"; break;
536 case "System.Int64": s = "long"; break;
537 case "System.String": s = "string"; break;
538 case "System.Boolean": s = "bool"; break;
539 case "System.Void": s = "void"; break;
540 case "System.Object": s = "object"; break;
541 case "System.UInt32": s = "uint"; break;
542 case "System.Int16": s = "short"; break;
543 case "System.UInt16": s = "ushort"; break;
544 case "System.UInt64": s = "ulong"; break;
545 case "System.Single": s = "float"; break;
546 case "System.Double": s = "double"; break;
547 case "System.Decimal": s = "decimal"; break;
548 case "System.Char": s = "char"; break;
549 case "System.Byte": s = "byte"; break;
550 case "System.SByte": s = "sbyte"; break;
551 default: s = null; break;
556 // Predefined names can come from mscorlib only
558 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
564 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
565 return AnonymousTypeClass.SignatureForError;
567 int idx = name.IndexOfAny (elements, 10);
569 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
572 return name.Replace ('+', '.');
575 static public string CSharpName (Type[] types)
577 if (types.Length == 0)
580 StringBuilder sb = new StringBuilder ();
581 for (int i = 0; i < types.Length; ++i) {
585 sb.Append (CSharpName (types [i]));
587 return sb.ToString ();
591 /// Returns the signature of the method with full namespace classification
593 static public string GetFullNameSignature (MemberInfo mi)
595 PropertyInfo pi = mi as PropertyInfo;
597 MethodBase pmi = pi.GetGetMethod (true);
599 pmi = pi.GetSetMethod (true);
600 if (GetParameterData (pmi).Count > 0)
603 return (mi is MethodBase)
604 ? CSharpSignature (mi as MethodBase)
605 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
609 private static int GetFullName (Type t, StringBuilder sb)
613 if (!t.IsGenericType) {
614 sb.Append (t.FullName);
618 if (t.DeclaringType != null) {
619 pos = GetFullName (t.DeclaringType, sb);
621 } else if (t.Namespace != null && t.Namespace.Length != 0) {
622 sb.Append (t.Namespace);
625 sb.Append (RemoveGenericArity (t.Name));
627 Type[] this_args = GetTypeArguments (t);
629 if (this_args.Length < pos)
630 throw new InternalErrorException (
631 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
632 if (this_args.Length == pos)
637 sb.Append (CSharpName (this_args [pos++]));
638 if (pos == this_args.Length)
646 static string GetFullName (Type t)
649 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
650 return GetFullName (GetElementType (t)) + dimension;
653 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
654 t = TypeToCoreType (GetTypeArguments (t)[0]);
655 return CSharpName (t) + "?";
658 if (t.IsGenericParameter)
660 if (!t.IsGenericType)
663 StringBuilder sb = new StringBuilder ();
664 int pos = GetFullName (t, sb);
666 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
667 return sb.ToString ();
670 public static string GetFullName (Type t)
676 public static string RemoveGenericArity (string from)
678 int i = from.IndexOf ('`');
680 return from.Substring (0, i);
685 /// When we need to report accessors as well
687 static public string CSharpSignature (MethodBase mb)
689 return CSharpSignature (mb, false);
693 /// Returns the signature of the method
695 static public string CSharpSignature (MethodBase mb, bool show_accessor)
697 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
700 AParametersCollection iparams = GetParameterData (mb);
701 string parameters = iparams.GetSignatureForError ();
702 int accessor_end = 0;
704 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
705 string op_name = Operator.GetName (mb.Name);
706 if (op_name != null) {
707 if (op_name == "explicit" || op_name == "implicit") {
708 sig.Append (op_name);
709 sig.Append (" operator ");
710 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
712 sig.Append ("operator ");
713 sig.Append (op_name);
715 sig.Append (parameters);
716 return sig.ToString ();
719 bool is_getter = mb.Name.StartsWith ("get_");
720 bool is_setter = mb.Name.StartsWith ("set_");
721 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
723 } else if (mb.Name.StartsWith ("remove_")) {
728 if (iparams.Count > (is_getter ? 0 : 1)) {
729 sig.Append ("this[");
731 sig.Append (parameters.Substring (1, parameters.Length - 2));
733 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
736 sig.Append (mb.Name.Substring (accessor_end + 1));
739 if (mb.Name == ".ctor")
740 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
742 sig.Append (mb.Name);
744 if (IsGenericMethod (mb)) {
745 Type[] args = GetGenericArguments (mb);
747 for (int i = 0; i < args.Length; i++) {
750 sig.Append (CSharpName (args [i]));
756 sig.Append (parameters);
759 if (show_accessor && accessor_end > 0) {
761 sig.Append (mb.Name.Substring (0, accessor_end));
764 return sig.ToString ();
767 public static string GetMethodName (MethodInfo m)
769 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
772 return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
775 static public string CSharpSignature (EventInfo ei)
777 return CSharpName (ei.DeclaringType) + "." + ei.Name;
781 // Looks up a type, and aborts if it is not found. This is used
782 // by predefined types required by the compiler
784 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
786 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
787 Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
791 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
798 if (RootContext.StdLib || t == null || !required)
801 // TODO: All predefined imported types have to have correct signature
802 if (t.Module != RootContext.ToplevelTypes.Builder)
805 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
806 if (ds is Delegate) {
807 if (type_kind == Kind.Delegate)
810 TypeContainer tc = (TypeContainer)ds;
811 if (tc.Kind == type_kind)
815 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
820 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
822 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
824 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
825 if (members != null) {
826 for (int i = 0; i < members.Length; ++i) {
827 MemberInfo member = members [i];
828 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
829 MethodBase mb = member as MethodBase;
833 AParametersCollection pd = TypeManager.GetParameterData (mb);
834 if (IsEqual (pd.Types, args))
837 if (mt == MemberTypes.Field) {
838 FieldInfo fi = member as FieldInfo;
842 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
848 if (mt == MemberTypes.Property) {
849 PropertyInfo pi = member as PropertyInfo;
853 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
861 string method_args = null;
862 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
863 method_args = "(" + TypeManager.CSharpName (args) + ")";
865 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
866 TypeManager.CSharpName (t), name, method_args);
872 // Returns the ConstructorInfo for "args"
874 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
876 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
880 // Returns the MethodInfo for a method named `name' defined
881 // in type `t' which takes arguments of types `args'
883 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
885 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
888 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
890 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
893 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
895 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
899 /// The types have to be initialized after the initial
900 /// population of the type has happened (for example, to
901 /// bootstrap the corlib.dll
903 public static bool InitCoreTypes ()
905 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
906 system_object_expr.Type = object_type;
907 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
908 system_valuetype_expr.Type = value_type;
909 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
911 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
912 system_int32_expr.Type = int32_type;
913 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
914 system_int64_expr.Type = int64_type;
915 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
916 system_uint32_expr.Type = uint32_type;
917 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
918 system_uint64_expr.Type = uint64_type;
919 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
920 system_byte_expr.Type = byte_type;
921 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
922 system_sbyte_expr.Type = sbyte_type;
923 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
924 system_int16_expr.Type = short_type;
925 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
926 system_uint16_expr.Type = ushort_type;
928 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
929 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
930 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
932 // HACK: DefineType immediately resolves iterators (very wrong)
933 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
935 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
936 system_char_expr.Type = char_type;
937 string_type = CoreLookupType ("System", "String", Kind.Class, true);
938 system_string_expr.Type = string_type;
939 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
940 system_single_expr.Type = float_type;
941 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
942 system_double_expr.Type = double_type;
943 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
944 system_decimal_expr.Type = decimal_type;
945 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
946 system_boolean_expr.Type = bool_type;
947 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
948 system_intptr_expr.Type = intptr_type;
949 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
951 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
952 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
954 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
955 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
956 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
957 system_void_expr.Type = void_type;
958 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
959 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
961 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
962 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
964 PredefinedAttributes.Get.ParamArray.Resolve (false);
965 PredefinedAttributes.Get.Out.Resolve (false);
967 return Report.Errors == 0;
971 // Initializes optional core types
973 public static void InitOptionalCoreTypes ()
976 // These are only used for compare purposes
978 null_type = typeof (NullLiteral);
980 void_ptr_type = GetPointerType (void_type);
983 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
984 // types cache with incorrect accessiblity when any of optional types is internal.
986 PredefinedAttributes.Get.Initialize ();
988 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
989 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
990 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
991 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
992 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
993 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
996 // Optional attributes, used for error reporting only
998 //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
999 // Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
1004 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1005 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1006 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1007 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1010 // Optional types which are used as types and for member lookup
1012 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1015 // Note: extension_attribute_type is already loaded
1016 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1018 if (!RootContext.StdLib) {
1020 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1021 // has different predefined types and this method sets mscorlib types
1022 // to be same to avoid any type check errors.
1025 Type type = typeof (Type);
1026 Type [] system_4_type_arg = { type, type, type, type };
1028 MethodInfo set_corlib_type_builders =
1029 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1030 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1031 system_4_type_arg, null);
1033 if (set_corlib_type_builders != null) {
1034 object[] args = new object [4];
1035 args [0] = object_type;
1036 args [1] = value_type;
1037 args [2] = enum_type;
1038 args [3] = void_type;
1040 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1042 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1043 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1044 TypeManager.CSharpName (system_4_type_arg));
1049 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1052 /// This is the "old", non-cache based FindMembers() function. We cannot use
1053 /// the cache here because there is no member name argument.
1055 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1056 MemberFilter filter, object criteria)
1058 #if MS_COMPATIBLE && GMCS_SOURCE
1059 if (t.IsGenericType)
1060 t = t.GetGenericTypeDefinition ();
1063 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1066 // `builder_to_declspace' contains all dynamic types.
1070 Timer.StartTimer (TimerType.FindMembers);
1071 list = decl.FindMembers (mt, bf, filter, criteria);
1072 Timer.StopTimer (TimerType.FindMembers);
1077 // We have to take care of arrays specially, because GetType on
1078 // a TypeBuilder array will return a Type, not a TypeBuilder,
1079 // and we can not call FindMembers on this type.
1082 #if MS_COMPATIBLE && GMCS_SOURCE
1085 t.IsSubclassOf (TypeManager.array_type))
1086 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1089 if (t is GenericTypeParameterBuilder) {
1090 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1092 Timer.StartTimer (TimerType.FindMembers);
1093 MemberList list = tparam.FindMembers (
1094 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1095 Timer.StopTimer (TimerType.FindMembers);
1101 // Since FindMembers will not lookup both static and instance
1102 // members, we emulate this behaviour here.
1104 if ((bf & instance_and_static) == instance_and_static){
1105 MemberInfo [] i_members = t.FindMembers (
1106 mt, bf & ~BindingFlags.Static, filter, criteria);
1108 int i_len = i_members.Length;
1110 MemberInfo one = i_members [0];
1113 // If any of these are present, we are done!
1115 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1116 return new MemberList (i_members);
1119 MemberInfo [] s_members = t.FindMembers (
1120 mt, bf & ~BindingFlags.Instance, filter, criteria);
1122 int s_len = s_members.Length;
1123 if (i_len > 0 || s_len > 0)
1124 return new MemberList (i_members, s_members);
1127 return new MemberList (i_members);
1129 return new MemberList (s_members);
1133 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1138 /// This method is only called from within MemberLookup. It tries to use the member
1139 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1140 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1141 /// our return value will already contain all inherited members and the caller don't need
1142 /// to check base classes and interfaces anymore.
1144 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1145 string name, out bool used_cache)
1150 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1151 // and we can ask the DeclSpace for the MemberCache.
1154 if (t.Assembly == CodeGen.Assembly.Builder) {
1155 if (t.IsGenericParameter) {
1156 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1159 if (tparam.MemberCache == null)
1160 return new MemberInfo[0];
1162 return tparam.MemberCache.FindMembers (
1163 mt, bf, name, FilterWithClosure_delegate, null);
1167 // We have to take care of arrays specially, because GetType on
1168 // a TypeBuilder array will return a Type, not a TypeBuilder,
1169 // and we can not call FindMembers on this type.
1173 return TypeHandle.ArrayType.MemberCache.FindMembers (
1174 mt, bf, name, FilterWithClosure_delegate, null);
1177 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1178 t = t.GetGenericTypeDefinition ();
1180 if (t is TypeBuilder) {
1182 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1183 cache = decl.MemberCache;
1186 // If this DeclSpace has a MemberCache, use it.
1189 if (cache != null) {
1191 return cache.FindMembers (
1192 mt, bf, name, FilterWithClosure_delegate, null);
1195 // If there is no MemberCache, we need to use the "normal" FindMembers.
1196 // Note, this is a VERY uncommon route!
1199 Timer.StartTimer (TimerType.FindMembers);
1200 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1201 FilterWithClosure_delegate, name);
1202 Timer.StopTimer (TimerType.FindMembers);
1204 return (MemberInfo []) list;
1208 // We have to take care of arrays specially, because GetType on
1209 // a TypeBuilder array will return a Type, not a TypeBuilder,
1210 // and we can not call FindMembers on this type.
1214 return TypeHandle.ArrayType.MemberCache.FindMembers (
1215 mt, bf, name, FilterWithClosure_delegate, null);
1219 if (t is GenericTypeParameterBuilder) {
1220 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1223 if (tparam.MemberCache == null)
1224 return new MemberInfo [0];
1226 return tparam.MemberCache.FindMembers (
1227 mt, bf, name, FilterWithClosure_delegate, null);
1231 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1233 // This happens if we're resolving a class'es base class and interfaces
1234 // in TypeContainer.DefineType(). At this time, the types aren't
1235 // populated yet, so we can't use the cache.
1237 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1238 FilterWithClosure_delegate, name);
1244 // This call will always succeed. There is exactly one TypeHandle instance per
1245 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1246 // the corresponding MemberCache.
1248 cache = TypeHandle.GetMemberCache (t);
1251 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1254 public static bool IsBuiltinType (Type t)
1256 t = TypeToCoreType (t);
1257 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1258 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1259 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1260 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1267 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1268 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1270 public static bool IsPrimitiveType (Type t)
1272 return (t == int32_type || t == uint32_type ||
1273 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1274 t == char_type || t == short_type || t == bool_type ||
1275 t == sbyte_type || t == byte_type || t == ushort_type);
1278 public static bool IsDelegateType (Type t)
1280 if (TypeManager.IsGenericParameter (t))
1283 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1286 t = DropGenericTypeArguments (t);
1287 return IsSubclassOf (t, TypeManager.delegate_type);
1291 // Is a type of dynamic type
1293 public static bool IsDynamicType (Type t)
1295 if (t == InternalType.Dynamic)
1298 if (t != object_type)
1301 if (t.Module == RootContext.ToplevelTypes.Builder)
1304 PredefinedAttribute pa = PredefinedAttributes.Get.Dynamic;
1308 object[] res = t.GetCustomAttributes (pa.Type, false);
1309 return res != null && res.Length != 0;
1312 public static bool IsEnumType (Type t)
1314 t = DropGenericTypeArguments (t);
1315 return t.BaseType == TypeManager.enum_type;
1318 public static bool IsBuiltinOrEnum (Type t)
1320 if (IsBuiltinType (t))
1329 public static bool IsAttributeType (Type t)
1331 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1335 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1337 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1338 public static bool IsUnmanagedType (Type t)
1340 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1342 return ds.IsUnmanagedType ();
1344 // builtins that are not unmanaged types
1345 if (t == TypeManager.object_type || t == TypeManager.string_type)
1348 if (IsGenericType (t) || IsGenericParameter (t))
1351 if (IsBuiltinOrEnum (t))
1354 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1356 return IsUnmanagedType (GetElementType (t));
1358 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1362 if (!IsValueType (t))
1365 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1366 if (IsGenericTypeDefinition (p))
1372 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1374 foreach (FieldInfo f in fields){
1375 if (!IsUnmanagedType (f.FieldType)){
1385 // Null is considered to be a reference type
1387 public static bool IsReferenceType (Type t)
1389 if (TypeManager.IsGenericParameter (t)) {
1390 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1391 if (constraints == null)
1394 return constraints.IsReferenceType;
1397 return !IsStruct (t) && !IsEnumType (t);
1400 public static bool IsValueType (Type t)
1402 if (TypeManager.IsGenericParameter (t)) {
1403 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1404 if (constraints == null)
1407 return constraints.IsValueType;
1410 return IsStruct (t) || IsEnumType (t);
1413 public static bool IsStruct (Type t)
1415 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1418 public static bool IsInterfaceType (Type t)
1420 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1424 return tc.Kind == Kind.Interface;
1427 public static bool IsSubclassOf (Type type, Type base_type)
1429 TypeParameter tparam = LookupTypeParameter (type);
1430 TypeParameter pparam = LookupTypeParameter (base_type);
1432 if ((tparam != null) && (pparam != null)) {
1433 if (tparam == pparam)
1436 return tparam.IsSubclassOf (base_type);
1439 #if MS_COMPATIBLE && GMCS_SOURCE
1440 if (type.IsGenericType)
1441 type = type.GetGenericTypeDefinition ();
1444 if (type.IsSubclassOf (base_type))
1448 if (IsEqual (type, base_type))
1451 type = type.BaseType;
1452 } while (type != null);
1457 public static bool IsPrivateAccessible (Type type, Type parent)
1462 if (type.Equals (parent))
1465 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1468 public static bool IsFamilyAccessible (Type type, Type parent)
1470 TypeParameter tparam = LookupTypeParameter (type);
1471 TypeParameter pparam = LookupTypeParameter (parent);
1473 if ((tparam != null) && (pparam != null)) {
1474 if (tparam == pparam)
1477 return tparam.IsSubclassOf (parent);
1481 if (IsInstantiationOfSameGenericType (type, parent))
1484 type = type.BaseType;
1485 } while (type != null);
1491 // Checks whether `type' is a subclass or nested child of `base_type'.
1493 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1496 if (IsFamilyAccessible (type, base_type))
1499 // Handle nested types.
1500 type = type.DeclaringType;
1501 } while (type != null);
1507 // Checks whether `type' is a nested child of `parent'.
1509 public static bool IsNestedChildOf (Type type, Type parent)
1514 type = DropGenericTypeArguments (type);
1515 parent = DropGenericTypeArguments (parent);
1517 if (IsEqual (type, parent))
1520 type = type.DeclaringType;
1521 while (type != null) {
1522 if (IsEqual (type, parent))
1525 type = type.DeclaringType;
1531 public static bool IsSpecialType (Type t)
1533 return t == arg_iterator_type || t == typed_reference_type;
1537 // Checks whether `extern_type' is friend of the output assembly
1539 public static bool IsThisOrFriendAssembly (Assembly assembly)
1541 if (assembly == CodeGen.Assembly.Builder)
1544 if (assembly_internals_vis_attrs.Contains (assembly))
1545 return (bool)(assembly_internals_vis_attrs [assembly]);
1547 PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
1548 // HACK: Do very early resolve of SRE type checking
1549 if (pa.Type == null)
1555 object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
1556 if (attrs.Length == 0) {
1557 assembly_internals_vis_attrs.Add (assembly, false);
1561 bool is_friend = false;
1563 AssemblyName this_name = CodeGen.Assembly.Name;
1564 byte [] this_token = this_name.GetPublicKeyToken ();
1565 foreach (InternalsVisibleToAttribute attr in attrs) {
1566 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1569 AssemblyName aname = null;
1572 aname = new AssemblyName (attr.AssemblyName);
1574 throw new NotSupportedException ();
1576 } catch (FileLoadException) {
1577 } catch (ArgumentException) {
1580 if (aname == null || aname.Name != this_name.Name)
1583 byte [] key_token = aname.GetPublicKeyToken ();
1584 if (key_token != null) {
1585 if (this_token.Length == 0) {
1586 // Same name, but assembly is not strongnamed
1587 Error_FriendAccessNameNotMatching (aname.FullName);
1591 if (!CompareKeyTokens (this_token, key_token))
1599 assembly_internals_vis_attrs.Add (assembly, is_friend);
1603 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1605 for (int i = 0; i < token1.Length; i++)
1606 if (token1 [i] != token2 [i])
1612 static void Error_FriendAccessNameNotMatching (string other_name)
1615 "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",
1616 other_name, CodeGen.Assembly.Name.FullName);
1620 // Do the right thing when returning the element type of an
1621 // array type based on whether we are compiling corlib or not
1623 public static Type GetElementType (Type t)
1625 if (RootContext.StdLib)
1626 return t.GetElementType ();
1628 return TypeToCoreType (t.GetElementType ());
1632 /// This method is not implemented by MS runtime for dynamic types
1634 public static bool HasElementType (Type t)
1636 return t.IsArray || t.IsPointer || t.IsByRef;
1639 public static Type GetEnumUnderlyingType (Type t)
1641 t = DropGenericTypeArguments (t);
1642 Enum e = LookupTypeContainer (t) as Enum;
1644 return e.UnderlyingType;
1647 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1649 return TypeManager.int32_type;
1651 return TypeToCoreType (fi.FieldType);
1655 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1659 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1660 /// for anything which is dynamic, and we need this in a number of places,
1661 /// we register this information here, and use it afterwards.
1663 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1665 method_params.Add (mb, ip);
1668 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1670 method_params.Add (pb, p);
1673 static public AParametersCollection GetParameterData (MethodBase mb)
1675 AParametersCollection pd = (AParametersCollection) method_params [mb];
1678 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1679 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1680 pd = GetParameterData (mi);
1682 if (mi.IsGenericMethod)
1683 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1685 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1687 method_params.Add (mb, pd);
1691 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1692 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1693 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1696 pd = ParametersImported.Create (mb);
1698 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1699 if (generic != mb) {
1700 pd = TypeManager.GetParameterData (generic);
1701 pd = ParametersImported.Create (pd, mb);
1703 pd = ParametersImported.Create (mb);
1706 method_params.Add (mb, pd);
1711 public static AParametersCollection GetParameterData (PropertyInfo pi)
1713 AParametersCollection pd = (AParametersCollection)method_params [pi];
1715 if (pi is PropertyBuilder)
1716 return ParametersCompiled.EmptyReadOnlyParameters;
1718 ParameterInfo [] p = pi.GetIndexParameters ();
1720 return ParametersCompiled.EmptyReadOnlyParameters;
1722 pd = ParametersImported.Create (p, null);
1723 method_params.Add (pi, pd);
1729 public static AParametersCollection GetDelegateParameters (Type t)
1731 Delegate d = builder_to_declspace [t] as Delegate;
1733 return d.Parameters;
1735 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1736 return GetParameterData (invoke_mb);
1739 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1741 if (!method_overrides.Contains (override_method))
1742 method_overrides [override_method] = base_method;
1743 if (method_overrides [override_method] != base_method)
1744 throw new InternalErrorException ("Override mismatch: " + override_method);
1747 static public bool IsOverride (MethodBase m)
1749 m = DropGenericMethodArguments (m);
1751 return m.IsVirtual &&
1752 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1753 (m is MethodBuilder || method_overrides.Contains (m));
1756 static public MethodBase TryGetBaseDefinition (MethodBase m)
1758 m = DropGenericMethodArguments (m);
1760 return (MethodBase) method_overrides [m];
1763 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1765 fields.Add (fb, ic);
1768 public static IConstant GetConstant (FieldInfo fb)
1773 return (IConstant)fields [fb];
1776 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1778 propertybuilder_to_property.Add (pi, pb);
1781 public static PropertyBase GetProperty (PropertyInfo pi)
1783 return (PropertyBase)propertybuilder_to_property [pi];
1786 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1788 fieldbuilders_to_fields.Add (fb, f);
1792 // The return value can be null; This will be the case for
1793 // auxiliary FieldBuilders created by the compiler that have no
1794 // real field being declared on the source code
1796 static public FieldBase GetField (FieldInfo fb)
1799 fb = GetGenericFieldDefinition (fb);
1801 return (FieldBase) fieldbuilders_to_fields [fb];
1804 static public MethodInfo GetAddMethod (EventInfo ei)
1806 if (ei is MyEventBuilder) {
1807 return ((MyEventBuilder)ei).GetAddMethod (true);
1809 return ei.GetAddMethod (true);
1812 static public MethodInfo GetRemoveMethod (EventInfo ei)
1814 if (ei is MyEventBuilder) {
1815 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1817 return ei.GetRemoveMethod (true);
1820 static public void RegisterEventField (EventInfo einfo, EventField e)
1823 events = new Hashtable ();
1825 events.Add (einfo, e);
1828 static public EventField GetEventField (EventInfo ei)
1833 return (EventField) events [ei];
1836 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1838 Hashtable hash = new Hashtable ();
1839 return CheckStructCycles (tc, seen, hash);
1842 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1845 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1849 // `seen' contains all types we've already visited.
1851 if (seen.Contains (tc))
1853 seen.Add (tc, null);
1855 if (tc.Fields == null)
1858 foreach (FieldBase field in tc.Fields) {
1859 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1862 Type ftype = field.FieldBuilder.FieldType;
1863 TypeContainer ftc = LookupTypeContainer (ftype);
1867 if (hash.Contains (ftc)) {
1868 Report.Error (523, tc.Location,
1869 "Struct member `{0}.{1}' of type `{2}' " +
1870 "causes a cycle in the struct layout",
1871 tc.Name, field.Name, ftc.Name);
1876 // `hash' contains all types in the current path.
1878 hash.Add (tc, null);
1880 bool ok = CheckStructCycles (ftc, seen, hash);
1887 if (!seen.Contains (ftc))
1888 seen.Add (ftc, null);
1895 /// Given an array of interface types, expand and eliminate repeated ocurrences
1896 /// of an interface.
1900 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1903 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1905 ArrayList new_ifaces = new ArrayList ();
1907 foreach (TypeExpr iface in base_interfaces){
1908 Type itype = iface.Type;
1910 if (new_ifaces.Contains (itype))
1913 new_ifaces.Add (itype);
1915 Type [] implementing = GetInterfaces (itype);
1917 foreach (Type imp in implementing){
1918 if (!new_ifaces.Contains (imp))
1919 new_ifaces.Add (imp);
1922 Type [] ret = new Type [new_ifaces.Count];
1923 new_ifaces.CopyTo (ret, 0);
1927 public static Type[] ExpandInterfaces (Type [] base_interfaces)
1929 ArrayList new_ifaces = new ArrayList ();
1931 foreach (Type itype in base_interfaces){
1932 if (new_ifaces.Contains (itype))
1935 new_ifaces.Add (itype);
1937 Type [] implementing = GetInterfaces (itype);
1939 foreach (Type imp in implementing){
1940 if (!new_ifaces.Contains (imp))
1941 new_ifaces.Add (imp);
1944 Type [] ret = new Type [new_ifaces.Count];
1945 new_ifaces.CopyTo (ret, 0);
1949 static PtrHashtable iface_cache;
1952 /// This function returns the interfaces in the type `t'. Works with
1953 /// both types and TypeBuilders.
1955 public static Type [] GetInterfaces (Type t)
1957 Type [] cached = iface_cache [t] as Type [];
1962 // The reason for catching the Array case is that Reflection.Emit
1963 // will not return a TypeBuilder for Array types of TypeBuilder types,
1964 // but will still throw an exception if we try to call GetInterfaces
1967 // Since the array interfaces are always constant, we return those for
1972 t = TypeManager.array_type;
1974 if ((t is TypeBuilder) || IsGenericType (t)) {
1975 Type [] base_ifaces;
1977 if (t.BaseType == null)
1978 base_ifaces = Type.EmptyTypes;
1980 base_ifaces = GetInterfaces (t.BaseType);
1982 if (IsGenericType (t))
1983 #if MS_COMPATIBLE && GMCS_SOURCE
1984 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
1986 type_ifaces = t.GetInterfaces ();
1989 type_ifaces = (Type []) builder_to_ifaces [t];
1990 if (type_ifaces == null || type_ifaces.Length == 0)
1991 type_ifaces = Type.EmptyTypes;
1993 int base_count = base_ifaces.Length;
1994 Type [] result = new Type [base_count + type_ifaces.Length];
1995 base_ifaces.CopyTo (result, 0);
1996 type_ifaces.CopyTo (result, base_count);
1998 iface_cache [t] = result;
2000 } else if (t is GenericTypeParameterBuilder){
2001 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2002 if (type_ifaces == null || type_ifaces.Length == 0)
2003 type_ifaces = Type.EmptyTypes;
2005 iface_cache [t] = type_ifaces;
2008 Type[] ifaces = t.GetInterfaces ();
2009 iface_cache [t] = ifaces;
2015 // gets the interfaces that are declared explicitly on t
2017 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2019 return (Type []) builder_to_ifaces [t];
2023 /// The following is used to check if a given type implements an interface.
2024 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2026 public static bool ImplementsInterface (Type t, Type iface)
2031 // FIXME OPTIMIZATION:
2032 // as soon as we hit a non-TypeBuiler in the interface
2033 // chain, we could return, as the `Type.GetInterfaces'
2034 // will return all the interfaces implement by the type
2038 interfaces = GetInterfaces (t);
2040 if (interfaces != null){
2041 foreach (Type i in interfaces){
2042 if (i == iface || IsVariantOf (i, iface))
2048 } while (t != null);
2053 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2055 // This is a custom version of Convert.ChangeType() which works
2056 // with the TypeBuilder defined types when compiling corlib.
2057 public static object ChangeType (object value, Type conversionType, out bool error)
2059 IConvertible convert_value = value as IConvertible;
2061 if (convert_value == null){
2068 // We must use Type.Equals() here since `conversionType' is
2069 // the TypeBuilder created version of a system type and not
2070 // the system type itself. You cannot use Type.GetTypeCode()
2071 // on such a type - it'd always return TypeCode.Object.
2074 // We cannot rely on build-in type conversions as they are
2075 // more limited than what C# supports.
2076 // See char -> float/decimal/double conversion
2081 if (conversionType.Equals (typeof (Boolean)))
2082 return (object)(convert_value.ToBoolean (nf_provider));
2083 if (conversionType.Equals (typeof (Byte)))
2084 return (object)(convert_value.ToByte (nf_provider));
2085 if (conversionType.Equals (typeof (Char)))
2086 return (object)(convert_value.ToChar (nf_provider));
2087 if (conversionType.Equals (typeof (DateTime)))
2088 return (object)(convert_value.ToDateTime (nf_provider));
2090 if (conversionType.Equals (decimal_type)) {
2091 if (convert_value.GetType () == TypeManager.char_type)
2092 return (decimal)convert_value.ToInt32 (nf_provider);
2093 return convert_value.ToDecimal (nf_provider);
2096 if (conversionType.Equals (typeof (Double))) {
2097 if (convert_value.GetType () == TypeManager.char_type)
2098 return (double)convert_value.ToInt32 (nf_provider);
2099 return convert_value.ToDouble (nf_provider);
2102 if (conversionType.Equals (typeof (Int16)))
2103 return (object)(convert_value.ToInt16 (nf_provider));
2104 if (conversionType.Equals (int32_type))
2105 return (object)(convert_value.ToInt32 (nf_provider));
2106 if (conversionType.Equals (int64_type))
2107 return (object)(convert_value.ToInt64 (nf_provider));
2108 if (conversionType.Equals (typeof (SByte)))
2109 return (object)(convert_value.ToSByte (nf_provider));
2111 if (conversionType.Equals (typeof (Single))) {
2112 if (convert_value.GetType () == TypeManager.char_type)
2113 return (float)convert_value.ToInt32 (nf_provider);
2114 return convert_value.ToSingle (nf_provider);
2117 if (conversionType.Equals (typeof (String)))
2118 return (object)(convert_value.ToString (nf_provider));
2119 if (conversionType.Equals (typeof (UInt16)))
2120 return (object)(convert_value.ToUInt16 (nf_provider));
2121 if (conversionType.Equals (typeof (UInt32)))
2122 return (object)(convert_value.ToUInt32 (nf_provider));
2123 if (conversionType.Equals (typeof (UInt64)))
2124 return (object)(convert_value.ToUInt64 (nf_provider));
2125 if (conversionType.Equals (typeof (Object)))
2126 return (object)(value);
2136 // When compiling with -nostdlib and the type is imported from an external assembly
2137 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2139 public static Type TypeToCoreType (Type t)
2141 if (RootContext.StdLib || t.Module != typeof (object).Module)
2144 TypeCode tc = Type.GetTypeCode (t);
2147 case TypeCode.Boolean:
2148 return TypeManager.bool_type;
2150 return TypeManager.byte_type;
2151 case TypeCode.SByte:
2152 return TypeManager.sbyte_type;
2154 return TypeManager.char_type;
2155 case TypeCode.Int16:
2156 return TypeManager.short_type;
2157 case TypeCode.UInt16:
2158 return TypeManager.ushort_type;
2159 case TypeCode.Int32:
2160 return TypeManager.int32_type;
2161 case TypeCode.UInt32:
2162 return TypeManager.uint32_type;
2163 case TypeCode.Int64:
2164 return TypeManager.int64_type;
2165 case TypeCode.UInt64:
2166 return TypeManager.uint64_type;
2167 case TypeCode.Single:
2168 return TypeManager.float_type;
2169 case TypeCode.Double:
2170 return TypeManager.double_type;
2171 case TypeCode.String:
2172 return TypeManager.string_type;
2173 case TypeCode.Decimal:
2174 return TypeManager.decimal_type;
2177 if (t == typeof (void))
2178 return TypeManager.void_type;
2179 if (t == typeof (object))
2180 return TypeManager.object_type;
2181 if (t == typeof (System.Type))
2182 return TypeManager.type_type;
2183 if (t == typeof (System.IntPtr))
2184 return TypeManager.intptr_type;
2185 if (t == typeof (System.UIntPtr))
2186 return TypeManager.uintptr_type;
2189 int dim = t.GetArrayRank ();
2190 t = GetElementType (t);
2191 return t.MakeArrayType (dim);
2194 t = GetElementType (t);
2195 return t.MakeByRefType ();
2198 t = GetElementType (t);
2199 return t.MakePointerType ();
2206 // Converts any type to reflection supported type
2208 public static Type TypeToReflectionType (Type type)
2210 // TODO: Very lame and painful, GetReference () is enough for mcs-cecil
2211 return IsDynamicType (type) ? object_type : type;
2215 /// Utility function that can be used to probe whether a type
2216 /// is managed or not.
2218 public static bool VerifyUnManaged (Type t, Location loc)
2220 if (IsUnmanagedType (t))
2224 t = GetElementType (t);
2226 Report.SymbolRelatedToPreviousError (t);
2227 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2234 /// Returns the name of the indexer in a given type.
2237 /// The default is not always `Item'. The user can change this behaviour by
2238 /// using the IndexerNameAttribute in the container.
2239 /// For example, the String class indexer is named `Chars' not `Item'
2241 public static string IndexerPropertyName (Type t)
2243 t = DropGenericTypeArguments (t);
2244 if (t is TypeBuilder) {
2245 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2246 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2249 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
2251 System.Attribute attr = System.Attribute.GetCustomAttribute (
2254 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2255 return dma.MemberName;
2259 return TypeContainer.DefaultIndexerName;
2262 static MethodInfo declare_local_method = null;
2264 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2266 if (declare_local_method == null){
2267 declare_local_method = typeof (ILGenerator).GetMethod (
2269 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2271 new Type [] { typeof (Type), typeof (bool)},
2273 if (declare_local_method == null){
2274 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2275 return ig.DeclareLocal (t);
2278 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2281 private static bool IsSignatureEqual (Type a, Type b)
2284 /// Consider the following example (bug #77674):
2286 /// public abstract class A
2288 /// public abstract T Foo<T> ();
2291 /// public abstract class B : A
2293 /// public override U Foo<T> ()
2294 /// { return default (U); }
2297 /// Here, `T' and `U' are method type parameters from different methods
2298 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2300 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2301 /// we need to do a signature based comparision and consider them equal.
2307 if (a.IsGenericParameter && b.IsGenericParameter &&
2308 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2309 return a.GenericParameterPosition == b.GenericParameterPosition;
2313 if (a.IsArray && b.IsArray) {
2314 if (a.GetArrayRank () != b.GetArrayRank ())
2317 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2320 if (a.IsByRef && b.IsByRef)
2321 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2323 if (IsGenericType (a) && IsGenericType (b)) {
2324 if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
2327 Type[] aargs = GetTypeArguments (a);
2328 Type[] bargs = GetTypeArguments (b);
2330 if (aargs.Length != bargs.Length)
2333 for (int i = 0; i < aargs.Length; i++) {
2334 if (!IsSignatureEqual (aargs [i], bargs [i]))
2345 // Returns whether the array of memberinfos contains the given method
2347 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2349 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2351 foreach (MethodBase method in array) {
2352 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2355 if (method.Name != new_method.Name)
2358 if (method is MethodInfo && new_method is MethodInfo &&
2360 TypeToCoreType (((MethodInfo) method).ReturnType),
2361 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2364 Type [] old_args = TypeManager.GetParameterData (method).Types;
2365 int old_count = old_args.Length;
2368 if (new_args.Length != old_count)
2371 for (i = 0; i < old_count; i++){
2372 if (!IsSignatureEqual (old_args [i], new_args [i]))
2385 // We copy methods from `new_members' into `target_list' if the signature
2386 // for the method from in the new list does not exist in the target_list
2388 // The name is assumed to be the same.
2390 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2392 if (target_list == null){
2393 target_list = new ArrayList ();
2395 foreach (MemberInfo mi in new_members){
2396 if (mi is MethodBase)
2397 target_list.Add (mi);
2402 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2403 target_list.CopyTo (target_array, 0);
2405 foreach (MemberInfo mi in new_members){
2406 MethodBase new_method = (MethodBase) mi;
2408 if (!ArrayContainsMethod (target_array, new_method, true))
2409 target_list.Add (new_method);
2416 // Tracks the generic parameters.
2418 static PtrHashtable builder_to_type_param;
2420 public static void AddTypeParameter (Type t, TypeParameter tparam)
2422 if (!builder_to_type_param.Contains (t))
2423 builder_to_type_param.Add (t, tparam);
2426 public static TypeParameter LookupTypeParameter (Type t)
2428 return (TypeParameter) builder_to_type_param [t];
2431 // This method always return false for non-generic compiler,
2432 // while Type.IsGenericParameter is returned if it is supported.
2433 public static bool IsGenericParameter (Type type)
2436 return type.IsGenericParameter;
2442 public static int GenericParameterPosition (Type type)
2445 return type.GenericParameterPosition;
2447 throw new InternalErrorException ("should not be called");
2451 public static bool IsGenericType (Type type)
2454 return type.IsGenericType;
2460 public static bool IsGenericTypeDefinition (Type type)
2463 return type.IsGenericTypeDefinition;
2469 public static bool ContainsGenericParameters (Type type)
2472 return type.ContainsGenericParameters;
2478 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2481 if (fi.DeclaringType.IsGenericTypeDefinition ||
2482 !fi.DeclaringType.IsGenericType)
2485 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2486 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2487 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2489 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2490 foreach (FieldInfo f in t.GetFields (bf))
2491 if (f.MetadataToken == fi.MetadataToken)
2498 public static bool IsEqual (Type a, Type b)
2501 // MS BCL returns true even if enum types are different
2502 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2503 return a.FullName == b.FullName;
2505 // Some types are never equal
2506 if (a == TypeManager.null_type || a == InternalType.AnonymousMethod)
2512 if (IsGenericParameter (a) && IsGenericParameter (b)) {
2513 // TODO: needs more testing before cleaning up
2514 //if (a.DeclaringMethod != b.DeclaringMethod &&
2515 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2518 return a.GenericParameterPosition == b.GenericParameterPosition;
2520 throw new NotSupportedException ();
2524 if (a.IsArray && b.IsArray) {
2525 if (a.GetArrayRank () != b.GetArrayRank ())
2527 return IsEqual (GetElementType (a), GetElementType (b));
2530 if (a.IsByRef && b.IsByRef)
2531 return IsEqual (a.GetElementType (), b.GetElementType ());
2533 if (IsGenericType (a) && IsGenericType (b)) {
2534 Type adef = DropGenericTypeArguments (a);
2535 Type bdef = DropGenericTypeArguments (b);
2540 if (adef.IsEnum && bdef.IsEnum)
2543 Type[] aargs = GetTypeArguments (a);
2544 Type[] bargs = GetTypeArguments (b);
2546 if (aargs.Length != bargs.Length)
2549 for (int i = 0; i < aargs.Length; i++) {
2550 if (!IsEqual (aargs [i], bargs [i]))
2560 public static bool IsEqual (Type[] a, Type[] b)
2562 if (a == null || b == null || a.Length != b.Length)
2565 for (int i = 0; i < a.Length; ++i) {
2566 if (a [i] == null || b [i] == null) {
2573 if (!IsEqual (a [i], b [i]))
2580 public static Type DropGenericTypeArguments (Type t)
2583 if (!t.IsGenericType)
2585 // Micro-optimization: a generic typebuilder is always a generic type definition
2586 if (t is TypeBuilder)
2588 return t.GetGenericTypeDefinition ();
2594 public static MethodBase DropGenericMethodArguments (MethodBase m)
2597 if (m.IsGenericMethod)
2598 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2600 Type t = m.DeclaringType;
2601 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2604 t = t.GetGenericTypeDefinition ();
2605 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2606 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2609 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2613 if (m is ConstructorInfo) {
2614 foreach (ConstructorInfo c in t.GetConstructors (bf))
2615 if (c.MetadataToken == m.MetadataToken)
2618 foreach (MethodBase mb in t.GetMethods (bf))
2619 if (mb.MetadataToken == m.MetadataToken)
2627 public static Type[] GetGenericArguments (MethodBase mi)
2630 return mi.GetGenericArguments ();
2632 return Type.EmptyTypes;
2636 public static Type[] GetTypeArguments (Type t)
2639 DeclSpace tc = LookupDeclSpace (t);
2642 return Type.EmptyTypes;
2644 TypeParameter[] tparam = tc.TypeParameters;
2645 Type[] ret = new Type [tparam.Length];
2646 for (int i = 0; i < tparam.Length; i++) {
2647 ret [i] = tparam [i].Type;
2648 if (ret [i] == null)
2649 throw new InternalErrorException ();
2654 return t.GetGenericArguments ();
2656 throw new InternalErrorException ();
2660 public static GenericConstraints GetTypeParameterConstraints (Type t)
2663 if (!t.IsGenericParameter)
2664 throw new InvalidOperationException ();
2666 TypeParameter tparam = LookupTypeParameter (t);
2668 return tparam.GenericConstraints;
2670 return ReflectionConstraints.GetConstraints (t);
2672 throw new InternalErrorException ();
2676 public static bool HasGenericArguments (Type t)
2678 return GetNumberOfTypeArguments (t) > 0;
2681 public static int GetNumberOfTypeArguments (Type t)
2684 if (t.IsGenericParameter)
2686 DeclSpace tc = LookupDeclSpace (t);
2688 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2690 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2697 /// Check whether `type' and `parent' are both instantiations of the same
2698 /// generic type. Note that we do not check the type parameters here.
2700 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2702 int tcount = GetNumberOfTypeArguments (type);
2703 int pcount = GetNumberOfTypeArguments (parent);
2705 if (tcount != pcount)
2708 type = DropGenericTypeArguments (type);
2709 parent = DropGenericTypeArguments (parent);
2711 return type.Equals (parent);
2715 /// Whether `mb' is a generic method definition.
2717 public static bool IsGenericMethodDefinition (MethodBase mb)
2720 if (mb.DeclaringType is TypeBuilder) {
2721 IMethodData method = (IMethodData) builder_to_method [mb];
2725 return method.GenericMethod != null;
2728 return mb.IsGenericMethodDefinition;
2735 /// Whether `mb' is a generic method.
2737 public static bool IsGenericMethod (MethodBase mb)
2740 return mb.IsGenericMethod;
2746 public static bool IsNullableType (Type t)
2749 return generic_nullable_type == DropGenericTypeArguments (t);
2756 #region MemberLookup implementation
2759 // Whether we allow private members in the result (since FindMembers
2760 // uses NonPublic for both protected and private), we need to distinguish.
2763 internal class Closure {
2764 internal bool private_ok;
2766 // Who is invoking us and which type is being queried currently.
2767 internal Type invocation_type;
2768 internal Type qualifier_type;
2770 // The assembly that defines the type is that is calling us
2771 internal Assembly invocation_assembly;
2772 internal IList almost_match;
2774 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2776 if (invocation_type == null)
2779 if (is_static && qualifier_type == null)
2780 // It resolved from a simple name, so it should be visible.
2783 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2786 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2787 if (!IsFamilyAccessible (t, m.DeclaringType))
2790 // Although a derived class can access protected members of its base class
2791 // it cannot do so through an instance of the base class (CS1540).
2792 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2793 if (is_static || qualifier_type == null ||
2794 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2795 IsFamilyAccessible (qualifier_type, t))
2799 if (almost_match != null)
2800 almost_match.Add (m);
2806 // This filter filters by name + whether it is ok to include private
2807 // members in the search
2809 internal bool Filter (MemberInfo m, object filter_criteria)
2812 // Hack: we know that the filter criteria will always be in the
2813 // `closure' // fields.
2816 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2819 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2820 (invocation_type != null) &&
2821 IsPrivateAccessible (m.DeclaringType, invocation_type))
2825 // Ugly: we need to find out the type of `m', and depending
2826 // on this, tell whether we accept or not
2828 if (m is MethodBase){
2829 MethodBase mb = (MethodBase) m;
2830 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2832 if (ma == MethodAttributes.Public)
2835 if (ma == MethodAttributes.PrivateScope)
2838 if (ma == MethodAttributes.Private)
2839 return private_ok ||
2840 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2841 IsNestedChildOf (invocation_type, m.DeclaringType);
2843 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2844 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2847 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2851 // Family, FamORAssem or FamANDAssem
2852 return CheckValidFamilyAccess (mb.IsStatic, m);
2855 if (m is FieldInfo){
2856 FieldInfo fi = (FieldInfo) m;
2857 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2859 if (fa == FieldAttributes.Public)
2862 if (fa == FieldAttributes.PrivateScope)
2865 if (fa == FieldAttributes.Private)
2866 return private_ok ||
2867 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2868 IsNestedChildOf (invocation_type, m.DeclaringType);
2870 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2871 if ((fa == FieldAttributes.Assembly) ||
2872 (fa == FieldAttributes.FamORAssem))
2875 if ((fa == FieldAttributes.Assembly) ||
2876 (fa == FieldAttributes.FamANDAssem))
2880 // Family, FamORAssem or FamANDAssem
2881 return CheckValidFamilyAccess (fi.IsStatic, m);
2885 // EventInfos and PropertyInfos, return true because they lack
2886 // permission information, so we need to check later on the methods.
2892 static Closure closure;
2893 static MemberFilter FilterWithClosure_delegate;
2896 // Looks up a member called `name' in the `queried_type'. This lookup
2897 // is done by code that is contained in the definition for `invocation_type'
2898 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2900 // `invocation_type' is used to check whether we're allowed to access the requested
2901 // member wrt its protection level.
2903 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2904 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2905 // is B and qualifier_type is A). This is used to do the CS1540 check.
2907 // When resolving a SimpleName, `qualifier_type' is null.
2909 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2910 // the same than `queried_type' - except when we're being called from BaseAccess;
2911 // in this case, `invocation_type' is the current type and `queried_type' the base
2912 // type, so this'd normally trigger a CS1540.
2914 // The binding flags are `bf' and the kind of members being looked up are `mt'
2916 // The return value always includes private members which code in `invocation_type'
2917 // is allowed to access (using the specified `qualifier_type' if given); only use
2918 // BindingFlags.NonPublic to bypass the permission check.
2920 // The 'almost_match' argument is used for reporting error CS1540.
2922 // Returns an array of a single element for everything but Methods/Constructors
2923 // that might return multiple matches.
2925 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2926 Type queried_type, MemberTypes mt,
2927 BindingFlags original_bf, string name, IList almost_match)
2929 Timer.StartTimer (TimerType.MemberLookup);
2931 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2932 queried_type, mt, original_bf, name, almost_match);
2934 Timer.StopTimer (TimerType.MemberLookup);
2939 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2940 Type queried_type, MemberTypes mt,
2941 BindingFlags original_bf, string name, IList almost_match)
2943 BindingFlags bf = original_bf;
2945 ArrayList method_list = null;
2946 Type current_type = queried_type;
2947 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2948 bool skip_iface_check = true, used_cache = false;
2949 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2951 closure.invocation_type = invocation_type;
2952 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2953 closure.qualifier_type = qualifier_type;
2954 closure.almost_match = almost_match;
2956 // This is from the first time we find a method
2957 // in most cases, we do not actually find a method in the base class
2958 // so we can just ignore it, and save the arraylist allocation
2959 MemberInfo [] first_members_list = null;
2960 bool use_first_members_list = false;
2966 // `NonPublic' is lame, because it includes both protected and
2967 // private methods, so we need to control this behavior by
2968 // explicitly tracking if a private method is ok or not.
2970 // The possible cases are:
2971 // public, private and protected (internal does not come into the
2974 if ((invocation_type != null) &&
2975 ((invocation_type == current_type) ||
2976 IsNestedChildOf (invocation_type, current_type)) ||
2978 bf = original_bf | BindingFlags.NonPublic;
2982 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2984 Timer.StopTimer (TimerType.MemberLookup);
2986 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2988 Timer.StartTimer (TimerType.MemberLookup);
2991 // When queried for an interface type, the cache will automatically check all
2992 // inherited members, so we don't need to do this here. However, this only
2993 // works if we already used the cache in the first iteration of this loop.
2995 // If we used the cache in any further iteration, we can still terminate the
2996 // loop since the cache always looks in all base classes.
3002 skip_iface_check = false;
3004 if (current_type == TypeManager.object_type)
3007 current_type = current_type.BaseType;
3010 // This happens with interfaces, they have a null
3011 // basetype. Look members up in the Object class.
3013 if (current_type == null) {
3014 current_type = TypeManager.object_type;
3019 if (list.Length == 0)
3023 // Events and types are returned by both `static' and `instance'
3024 // searches, which means that our above FindMembers will
3025 // return two copies of the same.
3027 if (list.Length == 1 && !(list [0] is MethodBase)){
3032 // Multiple properties: we query those just to find out the indexer
3035 if (list [0] is PropertyInfo)
3039 // We found an event: the cache lookup returns both the event and
3040 // its private field.
3042 if (list [0] is EventInfo) {
3043 if ((list.Length == 2) && (list [1] is FieldInfo))
3044 return new MemberInfo [] { list [0] };
3050 // We found methods, turn the search into "method scan"
3054 if (first_members_list != null) {
3055 if (use_first_members_list) {
3056 method_list = CopyNewMethods (method_list, first_members_list);
3057 use_first_members_list = false;
3060 method_list = CopyNewMethods (method_list, list);
3062 first_members_list = list;
3063 use_first_members_list = true;
3064 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3066 } while (searching);
3068 if (use_first_members_list)
3069 return first_members_list;
3071 if (method_list != null && method_list.Count > 0) {
3072 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3075 // This happens if we already used the cache in the first iteration, in this case
3076 // the cache already looked in all interfaces.
3078 if (skip_iface_check)
3082 // Interfaces do not list members they inherit, so we have to
3085 if (!queried_type.IsInterface)
3088 if (queried_type.IsArray)
3089 queried_type = TypeManager.array_type;
3091 Type [] ifaces = GetInterfaces (queried_type);
3095 foreach (Type itype in ifaces){
3098 x = MemberLookup (null, null, itype, mt, bf, name, null);
3106 public const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3107 BindingFlags.Static | BindingFlags.Instance |
3108 BindingFlags.DeclaredOnly;
3110 // Currently is designed to work with external types only
3111 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3113 if (!mb.IsSpecialName)
3116 string name = mb.Name;
3117 if (name.Length < 5)
3120 if (name [3] != '_')
3123 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3124 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3125 Type.FilterName, name.Substring (4));
3130 // This can happen when property is indexer (it can have same name but different parameters)
3131 foreach (PropertyInfo p in pi) {
3132 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3133 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3142 // Currently is designed to work with external types only
3143 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3145 if (!mb.IsSpecialName)
3148 string name = mb.Name;
3149 if (name.Length < 5)
3152 if (name.StartsWith ("add_"))
3153 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3155 if (name.StartsWith ("remove_"))
3156 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3161 // Tests whether external method is really special
3162 public static bool IsSpecialMethod (MethodBase mb)
3164 if (!mb.IsSpecialName)
3167 IMethodData md = TypeManager.GetMethod (mb);
3169 return (md is AbstractPropertyEventMethod || md is Operator);
3171 PropertyInfo pi = GetPropertyFromAccessor (mb);
3173 return IsValidProperty (pi);
3175 if (GetEventFromAccessor (mb) != null)
3178 string name = mb.Name;
3179 if (name.StartsWith ("op_"))
3180 return Operator.GetName (name) != null;
3185 // Tests whether imported property is valid C# property.
3186 // TODO: It seems to me that we should do a lot of sanity tests before
3187 // we accept property as C# property
3188 static bool IsValidProperty (PropertyInfo pi)
3190 MethodInfo get_method = pi.GetGetMethod (true);
3191 MethodInfo set_method = pi.GetSetMethod (true);
3194 if (get_method != null && set_method != null) {
3195 g_count = get_method.GetParameters ().Length;
3196 s_count = set_method.GetParameters ().Length;
3197 if (g_count + 1 != s_count)
3199 } else if (get_method != null) {
3200 g_count = get_method.GetParameters ().Length;
3201 } else if (set_method != null) {
3202 s_count = set_method.GetParameters ().Length;
3206 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3208 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
3209 if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
3210 object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
3214 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3215 if (dma.MemberName != pi.Name)
3217 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3219 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3232 public static readonly Type AnonymousMethod = typeof (AnonymousMethodBody);
3233 public static readonly Type Arglist = typeof (ArglistAccess);
3234 public static readonly Type Dynamic = new DynamicType ();
3235 public static readonly Type MethodGroup = typeof (MethodGroupExpr);
3239 /// There is exactly one instance of this class per type.
3241 public sealed class TypeHandle : IMemberContainer {
3242 public readonly IMemberContainer BaseType;
3244 readonly int id = ++next_id;
3245 static int next_id = 0;
3247 static TypeHandle ()
3253 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3254 /// a TypeHandle yet, a new instance of it is created. This static method
3255 /// ensures that we'll only have one TypeHandle instance per type.
3257 private static TypeHandle GetTypeHandle (Type t)
3259 TypeHandle handle = (TypeHandle) type_hash [t];
3263 handle = new TypeHandle (t);
3264 type_hash.Add (t, handle);
3268 public static MemberCache GetMemberCache (Type t)
3270 return GetTypeHandle (t).MemberCache;
3273 public static void CleanUp ()
3278 public static void Reset ()
3280 type_hash = new PtrHashtable ();
3284 /// Returns the TypeHandle for TypeManager.object_type.
3286 public static IMemberContainer ObjectType {
3288 if (object_type != null)
3291 object_type = GetTypeHandle (TypeManager.object_type);
3298 /// Returns the TypeHandle for TypeManager.array_type.
3300 public static TypeHandle ArrayType {
3302 if (array_type != null)
3305 array_type = GetTypeHandle (TypeManager.array_type);
3311 private static PtrHashtable type_hash;
3313 private static TypeHandle object_type = null;
3314 private static TypeHandle array_type = null;
3317 private string full_name;
3318 private bool is_interface;
3319 private MemberCache member_cache;
3320 private MemberCache base_cache;
3322 private TypeHandle (Type type)
3325 full_name = type.FullName != null ? type.FullName : type.Name;
3326 if (type.BaseType != null) {
3327 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3328 BaseType = base_cache.Container;
3329 } else if (type.IsInterface)
3330 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3331 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3332 this.member_cache = new MemberCache (this);
3335 // IMemberContainer methods
3337 public string Name {
3349 public MemberCache BaseCache {
3355 public bool IsInterface {
3357 return is_interface;
3361 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3363 MemberInfo [] members;
3365 if (type is GenericTypeParameterBuilder)
3366 return MemberList.Empty;
3369 type = TypeManager.DropGenericTypeArguments (type);
3371 if (mt == MemberTypes.Event)
3372 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3374 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3377 if (members.Length == 0)
3378 return MemberList.Empty;
3380 Array.Reverse (members);
3381 return new MemberList (members);
3384 // IMemberFinder methods
3386 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3387 MemberFilter filter, object criteria)
3389 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3392 public MemberCache MemberCache {
3394 return member_cache;
3398 public override string ToString ()
3400 if (BaseType != null)
3401 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3403 return "TypeHandle (" + id + "," + Name + ")";