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 {
38 // A list of core types that the compiler requires or uses
40 static public Type object_type;
41 static public Type value_type;
42 static public Type string_type;
43 static public Type int32_type;
44 static public Type uint32_type;
45 static public Type int64_type;
46 static public Type uint64_type;
47 static public Type float_type;
48 static public Type double_type;
49 static public Type char_type;
50 static public Type char_ptr_type;
51 static public Type short_type;
52 static public Type decimal_type;
53 static public Type bool_type;
54 static public Type sbyte_type;
55 static public Type byte_type;
56 static public Type ushort_type;
57 static public Type enum_type;
58 static public Type delegate_type;
59 static public Type multicast_delegate_type;
60 static public Type void_type;
61 static public Type null_type;
62 static public Type array_type;
63 static public Type runtime_handle_type;
64 static public Type type_type;
65 static public Type ienumerator_type;
66 static public Type ienumerable_type;
67 static public Type idisposable_type;
68 static public Type default_member_type;
69 static public Type iasyncresult_type;
70 static public Type asynccallback_type;
71 static public Type intptr_type;
72 static public Type uintptr_type;
73 static public Type runtime_field_handle_type;
74 static public Type runtime_argument_handle_type;
75 static public Type attribute_type;
76 static public Type attribute_usage_type;
77 static public Type decimal_constant_attribute_type;
78 static public Type dllimport_type;
79 static public Type methodimpl_attr_type;
81 static public Type marshal_as_attr_type;
83 static public Type param_array_type;
84 static public Type void_ptr_type;
85 static public Type indexer_name_type;
86 static public Type exception_type;
87 static public Type obsolete_attribute_type;
88 static public Type conditional_attribute_type;
89 static public Type in_attribute_type;
90 static public Type out_attribute_type;
91 static public Type extension_attribute_type;
92 static public Type default_parameter_value_attribute_type;
94 static public Type anonymous_method_type;
95 static public Type cls_compliant_attribute_type;
96 static public Type typed_reference_type;
97 static public Type arg_iterator_type;
98 static public Type mbr_type;
99 static public Type struct_layout_attribute_type;
100 static public Type field_offset_attribute_type;
101 static public Type security_attr_type;
102 static public Type required_attr_type;
103 static public Type guid_attr_type;
104 static public Type assembly_culture_attribute_type;
105 static public Type assembly_version_attribute_type;
106 static public Type coclass_attr_type;
107 static public Type comimport_attr_type;
108 public static Type runtime_helpers_type;
109 public static Type internals_visible_attr_type;
114 static internal Type fixed_buffer_attr_type;
115 static internal Type default_charset_type;
116 static internal Type type_forwarder_attr_type;
117 static internal Type isvolatile_type;
118 static public Type generic_ilist_type;
119 static public Type generic_icollection_type;
120 static public Type generic_ienumerator_type;
121 static public Type generic_ienumerable_type;
122 static public Type generic_nullable_type;
127 static internal Type expression_type;
128 public static Type parameter_expression_type;
131 // Expressions representing the internal types. Used during declaration
134 static public TypeExpr system_object_expr, system_string_expr;
135 static public TypeExpr system_boolean_expr, system_decimal_expr;
136 static public TypeExpr system_single_expr, system_double_expr;
137 static public TypeExpr system_sbyte_expr, system_byte_expr;
138 static public TypeExpr system_int16_expr, system_uint16_expr;
139 static public TypeExpr system_int32_expr, system_uint32_expr;
140 static public TypeExpr system_int64_expr, system_uint64_expr;
141 static public TypeExpr system_char_expr, system_void_expr;
142 static public TypeExpr system_valuetype_expr;
143 static public TypeExpr system_intptr_expr;
144 public static TypeExpr expression_type_expr;
148 // These methods are called by code generated by the compiler
150 static public FieldInfo string_empty;
151 static public MethodInfo system_type_get_type_from_handle;
152 static public MethodInfo bool_movenext_void;
153 static public MethodInfo void_dispose_void;
154 static public MethodInfo void_monitor_enter_object;
155 static public MethodInfo void_monitor_exit_object;
156 static public MethodInfo void_initializearray_array_fieldhandle;
157 static public MethodInfo delegate_combine_delegate_delegate;
158 static public MethodInfo delegate_remove_delegate_delegate;
159 static public MethodInfo int_get_offset_to_string_data;
160 static public MethodInfo int_interlocked_compare_exchange;
161 static public PropertyInfo ienumerator_getcurrent;
162 public static MethodInfo methodbase_get_type_from_handle;
163 public static MethodInfo methodbase_get_type_from_handle_generic;
164 public static MethodInfo fieldinfo_get_field_from_handle;
165 static public MethodInfo activator_create_instance;
168 // The attribute constructors.
170 static public ConstructorInfo void_decimal_ctor_five_args;
171 static public ConstructorInfo void_decimal_ctor_int_arg;
172 static public ConstructorInfo default_member_ctor;
173 static public ConstructorInfo decimal_constant_attribute_ctor;
174 static internal ConstructorInfo struct_layout_attribute_ctor;
175 static public ConstructorInfo field_offset_attribute_ctor;
176 public static ConstructorInfo invalid_operation_exception_ctor;
178 static public CustomAttributeBuilder param_array_attr;
179 static CustomAttributeBuilder compiler_generated_attr;
180 static CustomAttributeBuilder debugger_hidden_attr;
183 static internal ConstructorInfo fixed_buffer_attr_ctor;
184 static internal CustomAttributeBuilder unsafe_value_type_attr;
187 static internal CustomAttributeBuilder extension_attribute_attr;
189 static PtrHashtable builder_to_declspace;
191 static PtrHashtable builder_to_member_cache;
194 // Tracks the interfaces implemented by typebuilders. We only
195 // enter those who do implement or or more interfaces
197 static PtrHashtable builder_to_ifaces;
200 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
202 static Hashtable method_params;
205 // A hash table from override methods to their base virtual method.
207 static Hashtable method_overrides;
210 // Keeps track of methods
213 static Hashtable builder_to_method;
216 // Contains all public types from referenced assemblies.
217 // This member is used only if CLS Compliance verification is required.
219 public static Hashtable AllClsTopLevelTypes;
221 static Hashtable fieldbuilders_to_fields;
222 static Hashtable propertybuilder_to_property;
223 static Hashtable fields;
224 static Hashtable events;
225 static PtrHashtable assembly_internals_vis_attrs;
227 public static void CleanUp ()
229 // Lets get everything clean so that we can collect before generating code
230 builder_to_declspace = null;
231 builder_to_member_cache = null;
232 builder_to_ifaces = null;
233 builder_to_type_param = null;
234 method_params = null;
235 builder_to_method = null;
240 propertybuilder_to_property = null;
241 assembly_internals_vis_attrs = null;
243 TypeHandle.CleanUp ();
247 // These are expressions that represent some of the internal data types, used
250 static void InitExpressionTypes ()
252 system_object_expr = new TypeLookupExpression ("System", "Object");
253 system_string_expr = new TypeLookupExpression ("System", "String");
254 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
255 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
256 system_single_expr = new TypeLookupExpression ("System", "Single");
257 system_double_expr = new TypeLookupExpression ("System", "Double");
258 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
259 system_byte_expr = new TypeLookupExpression ("System", "Byte");
260 system_int16_expr = new TypeLookupExpression ("System", "Int16");
261 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
262 system_int32_expr = new TypeLookupExpression ("System", "Int32");
263 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
264 system_int64_expr = new TypeLookupExpression ("System", "Int64");
265 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
266 system_char_expr = new TypeLookupExpression ("System", "Char");
267 system_void_expr = new TypeLookupExpression ("System", "Void");
268 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
269 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
272 static TypeManager ()
276 InitExpressionTypes ();
279 static public void Reset ()
281 builder_to_declspace = new PtrHashtable ();
282 builder_to_member_cache = new PtrHashtable ();
283 builder_to_method = new PtrHashtable ();
284 builder_to_type_param = new PtrHashtable ();
285 method_params = new PtrHashtable ();
286 method_overrides = new PtrHashtable ();
287 builder_to_ifaces = new PtrHashtable ();
289 fieldbuilders_to_fields = new Hashtable ();
290 propertybuilder_to_property = new Hashtable ();
291 fields = new Hashtable ();
292 type_hash = new DoubleHash ();
293 assembly_internals_vis_attrs = new PtrHashtable ();
294 iface_cache = new PtrHashtable ();
296 // TODO: I am really bored by all this static stuff
297 system_type_get_type_from_handle =
300 void_monitor_enter_object =
301 void_monitor_exit_object =
302 void_initializearray_array_fieldhandle =
303 delegate_combine_delegate_delegate =
304 delegate_remove_delegate_delegate =
305 int_get_offset_to_string_data =
306 int_interlocked_compare_exchange =
307 methodbase_get_type_from_handle =
308 methodbase_get_type_from_handle_generic =
309 fieldinfo_get_field_from_handle =
310 activator_create_instance = null;
312 ienumerator_getcurrent = null;
314 void_decimal_ctor_five_args =
315 void_decimal_ctor_int_arg =
316 default_member_ctor =
317 decimal_constant_attribute_ctor =
318 struct_layout_attribute_ctor =
319 field_offset_attribute_ctor =
320 invalid_operation_exception_ctor =
321 fixed_buffer_attr_ctor = null;
324 compiler_generated_attr =
325 unsafe_value_type_attr =
326 extension_attribute_attr = null;
328 isvolatile_type = null;
330 // to uncover regressions
331 AllClsTopLevelTypes = null;
334 public static void AddUserType (DeclSpace ds)
336 builder_to_declspace.Add (ds.TypeBuilder, ds);
340 // This entry point is used by types that we define under the covers
342 public static void RegisterBuilder (Type tb, Type [] ifaces)
345 builder_to_ifaces [tb] = ifaces;
348 public static void AddMethod (MethodBase builder, IMethodData method)
350 builder_to_method.Add (builder, method);
351 method_params.Add (builder, method.ParameterInfo);
354 public static IMethodData GetMethod (MethodBase builder)
356 return (IMethodData) builder_to_method [builder];
360 /// Returns the DeclSpace whose Type is `t' or null if there is no
361 /// DeclSpace for `t' (ie, the Type comes from a library)
363 public static DeclSpace LookupDeclSpace (Type t)
365 return builder_to_declspace [t] as DeclSpace;
369 /// Returns the TypeContainer whose Type is `t' or null if there is no
370 /// TypeContainer for `t' (ie, the Type comes from a library)
372 public static TypeContainer LookupTypeContainer (Type t)
374 return builder_to_declspace [t] as TypeContainer;
377 public static MemberCache LookupMemberCache (Type t)
379 if (t.Module == CodeGen.Module.Builder) {
380 DeclSpace container = (DeclSpace)builder_to_declspace [t];
381 if (container != null)
382 return container.MemberCache;
386 if (t is GenericTypeParameterBuilder) {
387 TypeParameter container = builder_to_type_param [t] as TypeParameter;
389 if (container != null)
390 return container.MemberCache;
394 return TypeHandle.GetMemberCache (t);
397 public static MemberCache LookupBaseInterfacesCache (Type t)
399 Type [] ifaces = GetInterfaces (t);
401 if (ifaces != null && ifaces.Length == 1)
402 return LookupMemberCache (ifaces [0]);
404 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
405 MemberCache cache = builder_to_member_cache [t] as MemberCache;
409 cache = new MemberCache (ifaces);
410 builder_to_member_cache.Add (t, cache);
414 public static TypeContainer LookupInterface (Type t)
416 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
417 if ((tc == null) || (tc.Kind != Kind.Interface))
423 public static Delegate LookupDelegate (Type t)
425 return builder_to_declspace [t] as Delegate;
428 public static Class LookupClass (Type t)
430 return (Class) builder_to_declspace [t];
434 // We use this hash for multiple kinds of constructed types:
436 // (T, "&") Given T, get T &
437 // (T, "*") Given T, get T *
438 // (T, "[]") Given T and a array dimension, get T []
439 // (T, X) Given a type T and a simple name X, get the type T+X
441 // Accessibility tests, if necessary, should be done by the user
443 static DoubleHash type_hash = new DoubleHash ();
446 // Gets the reference to T version of the Type (T&)
448 public static Type GetReferenceType (Type t)
451 return t.MakeByRefType ();
453 return GetConstructedType (t, "&");
458 // Gets the pointer to T version of the Type (T*)
460 public static Type GetPointerType (Type t)
462 return GetConstructedType (t, "*");
465 public static Type GetConstructedType (Type t, string dim)
468 if (type_hash.Lookup (t, dim, out ret))
471 ret = t.Module.GetType (t.ToString () + dim);
473 type_hash.Insert (t, dim, ret);
478 ret = GetReferenceType (t);
479 type_hash.Insert (t, dim, ret);
484 if (t.IsGenericParameter || t.IsGenericType) {
487 while ((pos < dim.Length) && (dim [pos] == '[')) {
490 if (dim [pos] == ']') {
491 result = result.MakeArrayType ();
494 if (pos < dim.Length)
497 type_hash.Insert (t, dim, result);
502 while (dim [pos] == ',') {
506 if ((dim [pos] != ']') || (pos != dim.Length-1))
509 result = result.MakeArrayType (rank + 1);
510 type_hash.Insert (t, dim, result);
516 type_hash.Insert (t, dim, null);
520 public static CustomAttributeBuilder GetCompilerGeneratedAttribute (Location loc)
522 if (compiler_generated_attr != null)
523 return compiler_generated_attr;
525 Type t = TypeManager.CoreLookupType (
526 "System.Runtime.CompilerServices", "CompilerGeneratedAttribute", Kind.Class, true);
528 // TODO: it cannot be null
532 compiler_generated_attr = new CustomAttributeBuilder (
533 GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
535 return compiler_generated_attr;
538 public static CustomAttributeBuilder GetDebuggerHiddenAttribute (Location loc)
540 if (debugger_hidden_attr != null)
541 return debugger_hidden_attr;
543 Type t = TypeManager.CoreLookupType (
544 "System.Diagnostics", "DebuggerHiddenAttribute", Kind.Class, true);
546 // TODO: it cannot be null
550 debugger_hidden_attr = new CustomAttributeBuilder (
551 GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
553 return debugger_hidden_attr;
556 public static Type GetNestedType (Type t, string name)
559 if (!type_hash.Lookup (t, name, out ret)) {
560 ret = t.GetNestedType (name,
561 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
562 type_hash.Insert (t, name, ret);
568 /// Fills static table with exported types from all referenced assemblies.
569 /// This information is required for CLS Compliance tests.
571 public static void LoadAllImportedTypes ()
573 AllClsTopLevelTypes = new Hashtable (1500);
574 foreach (Assembly a in RootNamespace.Global.Assemblies) {
575 foreach (Type t in a.GetExportedTypes ()) {
576 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
581 public static bool NamespaceClash (string name, Location loc)
583 if (! RootNamespace.Global.IsNamespace (name))
586 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
591 /// Returns the C# name of a type if possible, or the full type name otherwise
593 static public string CSharpName (Type t)
598 if (t == typeof (ArglistParameter))
601 if (t == typeof (AnonymousMethodBody))
602 return "anonymous method";
605 return "internal error";
607 return CSharpName (GetFullName (t), t);
610 static readonly char [] elements = new char [] { '*', '[' };
612 public static string CSharpName (string name, Type type)
614 if (name.Length > 10) {
617 case "System.Int32": s = "int"; break;
618 case "System.Int64": s = "long"; break;
619 case "System.String": s = "string"; break;
620 case "System.Boolean": s = "bool"; break;
621 case "System.Void": s = "void"; break;
622 case "System.Object": s = "object"; break;
623 case "System.UInt32": s = "uint"; break;
624 case "System.Int16": s = "short"; break;
625 case "System.UInt16": s = "ushort"; break;
626 case "System.UInt64": s = "ulong"; break;
627 case "System.Single": s = "float"; break;
628 case "System.Double": s = "double"; break;
629 case "System.Decimal": s = "decimal"; break;
630 case "System.Char": s = "char"; break;
631 case "System.Byte": s = "byte"; break;
632 case "System.SByte": s = "sbyte"; break;
633 default: s = null; break;
638 // Predefined names can come from mscorlib only
640 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
646 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
647 return AnonymousTypeClass.SignatureForError;
649 int idx = name.IndexOfAny (elements, 10);
651 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
654 return name.Replace ('+', '.');
657 static public string CSharpName (Type[] types)
659 if (types.Length == 0)
662 StringBuilder sb = new StringBuilder ();
663 for (int i = 0; i < types.Length; ++i) {
667 sb.Append (CSharpName (types [i]));
669 return sb.ToString ();
673 /// Returns the signature of the method with full namespace classification
675 static public string GetFullNameSignature (MemberInfo mi)
677 PropertyInfo pi = mi as PropertyInfo;
679 MethodBase pmi = pi.GetGetMethod (true);
681 pmi = pi.GetSetMethod (true);
682 if (GetParameterData (pmi).Count > 0)
685 return (mi is MethodBase)
686 ? CSharpSignature (mi as MethodBase)
687 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
691 private static int GetFullName (Type t, StringBuilder sb)
695 if (!t.IsGenericType) {
696 sb.Append (t.FullName);
700 if (t.DeclaringType != null) {
701 pos = GetFullName (t.DeclaringType, sb);
703 } else if (t.Namespace != null && t.Namespace.Length != 0) {
704 sb.Append (t.Namespace);
707 sb.Append (RemoveGenericArity (t.Name));
709 Type[] this_args = GetTypeArguments (t);
711 if (this_args.Length < pos)
712 throw new InternalErrorException (
713 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
714 if (this_args.Length == pos)
719 sb.Append (CSharpName (this_args [pos++]));
720 if (pos == this_args.Length)
728 static string GetFullName (Type t)
731 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
732 return GetFullName (GetElementType (t)) + dimension;
735 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
736 t = GetTypeArguments (t)[0];
737 return CSharpName (t) + "?";
740 if (t.IsGenericParameter)
742 if (!t.IsGenericType)
745 StringBuilder sb = new StringBuilder ();
746 int pos = GetFullName (t, sb);
748 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
749 return sb.ToString ();
752 public static string GetFullName (Type t)
758 public static string RemoveGenericArity (string from)
760 int i = from.IndexOf ('`');
762 return from.Substring (0, i);
767 /// When we need to report accessors as well
769 static public string CSharpSignature (MethodBase mb)
771 return CSharpSignature (mb, false);
775 /// Returns the signature of the method
777 static public string CSharpSignature (MethodBase mb, bool show_accessor)
779 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
782 AParametersCollection iparams = GetParameterData (mb);
783 string parameters = iparams.GetSignatureForError ();
784 int accessor_end = 0;
786 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
787 string op_name = Operator.GetName (mb.Name);
788 if (op_name != null) {
789 if (op_name == "explicit" || op_name == "implicit") {
790 sig.Append (op_name);
791 sig.Append (" operator ");
792 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
794 sig.Append ("operator ");
795 sig.Append (op_name);
797 sig.Append (parameters);
798 return sig.ToString ();
801 bool is_getter = mb.Name.StartsWith ("get_");
802 bool is_setter = mb.Name.StartsWith ("set_");
803 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
805 } else if (mb.Name.StartsWith ("remove_")) {
810 if (iparams.Count > (is_getter ? 0 : 1)) {
811 sig.Append ("this[");
813 sig.Append (parameters.Substring (1, parameters.Length - 2));
815 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
818 sig.Append (mb.Name.Substring (accessor_end + 1));
821 if (mb.Name == ".ctor")
822 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
824 sig.Append (mb.Name);
827 if (TypeManager.IsGenericMethod (mb)) {
828 Type[] args = mb.GetGenericArguments ();
830 for (int i = 0; i < args.Length; i++) {
833 sig.Append (CSharpName (args [i]));
840 sig.Append (parameters);
843 if (show_accessor && accessor_end > 0) {
845 sig.Append (mb.Name.Substring (0, accessor_end));
848 return sig.ToString ();
851 public static string GetMethodName (MethodInfo m)
854 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
857 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
863 static public string CSharpSignature (EventInfo ei)
865 return CSharpName (ei.DeclaringType) + "." + ei.Name;
869 // Looks up a type, and aborts if it is not found. This is used
870 // by predefined types required by the compiler
872 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
874 Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
875 Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
879 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
886 if (RootContext.StdLib || t == null || !required)
889 // TODO: All predefined imported types have to have correct signature
890 if (t.Module != CodeGen.Module.Builder)
893 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
894 if (ds is Delegate) {
895 if (type_kind == Kind.Delegate)
898 TypeContainer tc = (TypeContainer)ds;
899 if (tc.Kind == type_kind)
903 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
908 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
910 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
912 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
913 if (members != null) {
914 for (int i = 0; i < members.Length; ++i) {
915 MemberInfo member = members [i];
916 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
917 MethodBase mb = member as MethodBase;
921 AParametersCollection pd = TypeManager.GetParameterData (mb);
922 if (IsEqual (pd.Types, args))
925 if (mt == MemberTypes.Field) {
926 FieldInfo fi = member as FieldInfo;
930 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
936 if (mt == MemberTypes.Property) {
937 PropertyInfo pi = member as PropertyInfo;
941 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
949 string method_args = null;
950 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
951 method_args = "(" + TypeManager.CSharpName (args) + ")";
953 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
954 TypeManager.CSharpName (t), name, method_args);
960 // Returns the ConstructorInfo for "args"
962 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
964 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
968 // Returns the MethodInfo for a method named `name' defined
969 // in type `t' which takes arguments of types `args'
971 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
973 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
976 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
978 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
981 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
983 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
987 /// The types have to be initialized after the initial
988 /// population of the type has happened (for example, to
989 /// bootstrap the corlib.dll
991 public static bool InitCoreTypes ()
993 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
994 system_object_expr.Type = object_type;
995 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
996 system_valuetype_expr.Type = value_type;
997 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
999 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
1000 system_int32_expr.Type = int32_type;
1001 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
1002 system_int64_expr.Type = int64_type;
1003 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
1004 system_uint32_expr.Type = uint32_type;
1005 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
1006 system_uint64_expr.Type = uint64_type;
1007 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
1008 system_byte_expr.Type = byte_type;
1009 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
1010 system_sbyte_expr.Type = sbyte_type;
1011 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
1012 system_int16_expr.Type = short_type;
1013 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
1014 system_uint16_expr.Type = ushort_type;
1016 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
1017 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
1018 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
1020 // HACK: DefineType immediately resolves iterators (very wrong)
1021 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
1023 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
1024 system_char_expr.Type = char_type;
1025 string_type = CoreLookupType ("System", "String", Kind.Class, true);
1026 system_string_expr.Type = string_type;
1027 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
1028 system_single_expr.Type = float_type;
1029 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
1030 system_double_expr.Type = double_type;
1031 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
1032 system_decimal_expr.Type = decimal_type;
1033 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
1034 system_boolean_expr.Type = bool_type;
1035 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
1036 system_intptr_expr.Type = intptr_type;
1037 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
1039 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
1040 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
1042 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
1043 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
1044 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
1045 system_void_expr.Type = void_type;
1046 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
1047 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
1049 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
1050 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
1052 param_array_type = CoreLookupType ("System", "ParamArrayAttribute", Kind.Class, true);
1053 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute", Kind.Class, true);
1055 return Report.Errors == 0;
1059 // Initializes optional core types
1061 public static void InitOptionalCoreTypes ()
1064 // These are only used for compare purposes
1066 anonymous_method_type = typeof (AnonymousMethodBody);
1067 null_type = typeof (NullLiteral);
1069 void_ptr_type = GetPointerType (void_type);
1070 char_ptr_type = GetPointerType (char_type);
1073 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
1074 // types cache with incorrect accessiblity when any of optional types is internal.
1076 internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", Kind.Class, false);
1078 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
1079 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
1080 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
1081 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
1082 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
1083 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
1086 // Optional attributes, used for error reporting only
1088 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute", Kind.Class, false);
1089 if (obsolete_attribute_type != null) {
1090 Class c = TypeManager.LookupClass (obsolete_attribute_type);
1095 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute", Kind.Class, false);
1096 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute", Kind.Class, false);
1098 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute", Kind.Class, false);
1100 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute", Kind.Class, false);
1101 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute", Kind.Class, false);
1102 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute", Kind.Class, false);
1103 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute", Kind.Class, false);
1104 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute", Kind.Class, false);
1105 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", Kind.Class, false);
1106 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute", Kind.Class, false);
1107 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute", Kind.Class, false);
1108 assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute", Kind.Class, false);
1109 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute", Kind.Class, false);
1110 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute", Kind.Class, false);
1111 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute", Kind.Class, false);
1112 default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", Kind.Class, false);
1115 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute", Kind.Class, false);
1116 type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", Kind.Class, false);
1117 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1118 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1119 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1120 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1123 // Optional types which are used as types and for member lookup
1125 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute", Kind.Class, false);
1126 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1127 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute", Kind.Class, false);
1128 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, false);
1129 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, false);
1132 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, false);
1135 // Note: extension_attribute_type is already loaded
1136 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1138 if (!RootContext.StdLib) {
1140 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1141 // has different predefined types and this method sets mscorlib types
1142 // to be same to avoid any type check errors.
1145 Type type = typeof (Type);
1146 Type [] system_4_type_arg = { type, type, type, type };
1148 MethodInfo set_corlib_type_builders =
1149 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1150 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1151 system_4_type_arg, null);
1153 if (set_corlib_type_builders != null) {
1154 object[] args = new object [4];
1155 args [0] = object_type;
1156 args [1] = value_type;
1157 args [2] = enum_type;
1158 args [3] = void_type;
1160 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1162 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1163 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1164 TypeManager.CSharpName (system_4_type_arg));
1169 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1172 /// This is the "old", non-cache based FindMembers() function. We cannot use
1173 /// the cache here because there is no member name argument.
1175 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1176 MemberFilter filter, object criteria)
1178 #if MS_COMPATIBLE && GMCS_SOURCE
1179 if (t.IsGenericType)
1180 t = t.GetGenericTypeDefinition ();
1183 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1186 // `builder_to_declspace' contains all dynamic types.
1190 Timer.StartTimer (TimerType.FindMembers);
1191 list = decl.FindMembers (mt, bf, filter, criteria);
1192 Timer.StopTimer (TimerType.FindMembers);
1197 // We have to take care of arrays specially, because GetType on
1198 // a TypeBuilder array will return a Type, not a TypeBuilder,
1199 // and we can not call FindMembers on this type.
1202 #if MS_COMPATIBLE && GMCS_SOURCE
1205 t.IsSubclassOf (TypeManager.array_type))
1206 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1209 if (t is GenericTypeParameterBuilder) {
1210 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1212 Timer.StartTimer (TimerType.FindMembers);
1213 MemberList list = tparam.FindMembers (
1214 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1215 Timer.StopTimer (TimerType.FindMembers);
1221 // Since FindMembers will not lookup both static and instance
1222 // members, we emulate this behaviour here.
1224 if ((bf & instance_and_static) == instance_and_static){
1225 MemberInfo [] i_members = t.FindMembers (
1226 mt, bf & ~BindingFlags.Static, filter, criteria);
1228 int i_len = i_members.Length;
1230 MemberInfo one = i_members [0];
1233 // If any of these are present, we are done!
1235 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1236 return new MemberList (i_members);
1239 MemberInfo [] s_members = t.FindMembers (
1240 mt, bf & ~BindingFlags.Instance, filter, criteria);
1242 int s_len = s_members.Length;
1243 if (i_len > 0 || s_len > 0)
1244 return new MemberList (i_members, s_members);
1247 return new MemberList (i_members);
1249 return new MemberList (s_members);
1253 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1258 /// This method is only called from within MemberLookup. It tries to use the member
1259 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1260 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1261 /// our return value will already contain all inherited members and the caller don't need
1262 /// to check base classes and interfaces anymore.
1264 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1265 string name, out bool used_cache)
1270 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1271 // and we can ask the DeclSpace for the MemberCache.
1274 if (t.Assembly == CodeGen.Assembly.Builder) {
1275 if (t.IsGenericParameter) {
1276 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1279 if (tparam.MemberCache == null)
1280 return new MemberInfo[0];
1282 return tparam.MemberCache.FindMembers (
1283 mt, bf, name, FilterWithClosure_delegate, null);
1287 // We have to take care of arrays specially, because GetType on
1288 // a TypeBuilder array will return a Type, not a TypeBuilder,
1289 // and we can not call FindMembers on this type.
1293 return TypeHandle.ArrayType.MemberCache.FindMembers (
1294 mt, bf, name, FilterWithClosure_delegate, null);
1297 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1298 t = t.GetGenericTypeDefinition ();
1300 if (t is TypeBuilder) {
1302 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1303 cache = decl.MemberCache;
1306 // If this DeclSpace has a MemberCache, use it.
1309 if (cache != null) {
1311 return cache.FindMembers (
1312 mt, bf, name, FilterWithClosure_delegate, null);
1315 // If there is no MemberCache, we need to use the "normal" FindMembers.
1316 // Note, this is a VERY uncommon route!
1319 Timer.StartTimer (TimerType.FindMembers);
1320 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1321 FilterWithClosure_delegate, name);
1322 Timer.StopTimer (TimerType.FindMembers);
1324 return (MemberInfo []) list;
1328 // We have to take care of arrays specially, because GetType on
1329 // a TypeBuilder array will return a Type, not a TypeBuilder,
1330 // and we can not call FindMembers on this type.
1334 return TypeHandle.ArrayType.MemberCache.FindMembers (
1335 mt, bf, name, FilterWithClosure_delegate, null);
1339 if (t is GenericTypeParameterBuilder) {
1340 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1343 if (tparam.MemberCache == null)
1344 return new MemberInfo [0];
1346 return tparam.MemberCache.FindMembers (
1347 mt, bf, name, FilterWithClosure_delegate, null);
1351 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1353 // This happens if we're resolving a class'es base class and interfaces
1354 // in TypeContainer.DefineType(). At this time, the types aren't
1355 // populated yet, so we can't use the cache.
1357 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1358 FilterWithClosure_delegate, name);
1364 // This call will always succeed. There is exactly one TypeHandle instance per
1365 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1366 // the corresponding MemberCache.
1368 cache = TypeHandle.GetMemberCache (t);
1371 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1374 public static bool IsBuiltinType (Type t)
1376 t = TypeToCoreType (t);
1377 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1378 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1379 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1380 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1387 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1388 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1390 public static bool IsPrimitiveType (Type t)
1392 return (t == int32_type || t == uint32_type ||
1393 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1394 t == char_type || t == short_type || t == bool_type ||
1395 t == sbyte_type || t == byte_type || t == ushort_type);
1398 public static bool IsDelegateType (Type t)
1401 if (t.IsGenericParameter)
1405 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1408 t = DropGenericTypeArguments (t);
1409 return IsSubclassOf (t, TypeManager.delegate_type);
1412 public static bool IsEnumType (Type t)
1414 t = DropGenericTypeArguments (t);
1415 return t.BaseType == TypeManager.enum_type;
1418 public static bool IsBuiltinOrEnum (Type t)
1420 if (IsBuiltinType (t))
1429 public static bool IsAttributeType (Type t)
1431 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1435 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1437 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1438 public static bool IsUnmanagedType (Type t)
1440 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1442 return ds.IsUnmanagedType ();
1444 // builtins that are not unmanaged types
1445 if (t == TypeManager.object_type || t == TypeManager.string_type)
1448 if (IsGenericType (t) || IsGenericParameter (t))
1451 if (IsBuiltinOrEnum (t))
1454 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1456 return IsUnmanagedType (GetElementType (t));
1458 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1462 if (!IsValueType (t))
1466 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1467 if (p.IsGenericTypeDefinition)
1474 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1476 foreach (FieldInfo f in fields){
1477 if (!IsUnmanagedType (f.FieldType)){
1487 // Null is considered to be a reference type
1489 public static bool IsReferenceType (Type t)
1491 if (TypeManager.IsGenericParameter (t)) {
1492 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1493 if (constraints == null)
1496 return constraints.IsReferenceType;
1499 return !IsStruct (t) && !IsEnumType (t);
1502 public static bool IsValueType (Type t)
1504 if (TypeManager.IsGenericParameter (t)) {
1505 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1506 if (constraints == null)
1509 return constraints.IsValueType;
1512 return IsStruct (t) || IsEnumType (t);
1515 public static bool IsStruct (Type t)
1517 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1520 public static bool IsInterfaceType (Type t)
1522 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1526 return tc.Kind == Kind.Interface;
1529 public static bool IsSubclassOf (Type type, Type base_type)
1531 TypeParameter tparam = LookupTypeParameter (type);
1532 TypeParameter pparam = LookupTypeParameter (base_type);
1534 if ((tparam != null) && (pparam != null)) {
1535 if (tparam == pparam)
1538 return tparam.IsSubclassOf (base_type);
1541 #if MS_COMPATIBLE && GMCS_SOURCE
1542 if (type.IsGenericType)
1543 type = type.GetGenericTypeDefinition ();
1546 if (type.IsSubclassOf (base_type))
1550 if (IsEqual (type, base_type))
1553 type = type.BaseType;
1554 } while (type != null);
1559 public static bool IsPrivateAccessible (Type type, Type parent)
1564 if (type.Equals (parent))
1567 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1570 public static bool IsFamilyAccessible (Type type, Type parent)
1572 TypeParameter tparam = LookupTypeParameter (type);
1573 TypeParameter pparam = LookupTypeParameter (parent);
1575 if ((tparam != null) && (pparam != null)) {
1576 if (tparam == pparam)
1579 return tparam.IsSubclassOf (parent);
1583 if (IsInstantiationOfSameGenericType (type, parent))
1586 type = type.BaseType;
1587 } while (type != null);
1593 // Checks whether `type' is a subclass or nested child of `base_type'.
1595 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1598 if (IsFamilyAccessible (type, base_type))
1601 // Handle nested types.
1602 type = type.DeclaringType;
1603 } while (type != null);
1609 // Checks whether `type' is a nested child of `parent'.
1611 public static bool IsNestedChildOf (Type type, Type parent)
1616 type = DropGenericTypeArguments (type);
1617 parent = DropGenericTypeArguments (parent);
1619 if (IsEqual (type, parent))
1622 type = type.DeclaringType;
1623 while (type != null) {
1624 if (IsEqual (type, parent))
1627 type = type.DeclaringType;
1633 public static bool IsSpecialType (Type t)
1635 return t == arg_iterator_type || t == typed_reference_type;
1639 // Checks whether `extern_type' is friend of the output assembly
1641 public static bool IsThisOrFriendAssembly (Assembly assembly)
1643 if (assembly == CodeGen.Assembly.Builder)
1646 if (assembly_internals_vis_attrs.Contains (assembly))
1647 return (bool)(assembly_internals_vis_attrs [assembly]);
1649 if (internals_visible_attr_type == null)
1652 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1653 if (attrs.Length == 0) {
1654 assembly_internals_vis_attrs.Add (assembly, false);
1658 bool is_friend = false;
1660 AssemblyName this_name = CodeGen.Assembly.Name;
1661 byte [] this_token = this_name.GetPublicKeyToken ();
1662 foreach (InternalsVisibleToAttribute attr in attrs) {
1663 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1666 AssemblyName aname = null;
1668 aname = new AssemblyName (attr.AssemblyName);
1669 } catch (FileLoadException) {
1670 } catch (ArgumentException) {
1673 if (aname == null || aname.Name != this_name.Name)
1676 byte [] key_token = aname.GetPublicKeyToken ();
1677 if (key_token != null) {
1678 if (this_token.Length == 0) {
1679 // Same name, but assembly is not strongnamed
1680 Error_FriendAccessNameNotMatching (aname.FullName);
1684 if (!CompareKeyTokens (this_token, key_token))
1692 assembly_internals_vis_attrs.Add (assembly, is_friend);
1697 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1699 for (int i = 0; i < token1.Length; i++)
1700 if (token1 [i] != token2 [i])
1706 static void Error_FriendAccessNameNotMatching (string other_name)
1709 "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",
1710 other_name, CodeGen.Assembly.Name.FullName);
1715 // Do the right thing when returning the element type of an
1716 // array type based on whether we are compiling corlib or not
1718 public static Type GetElementType (Type t)
1720 if (RootContext.StdLib)
1721 return t.GetElementType ();
1723 return TypeToCoreType (t.GetElementType ());
1727 /// This method is not implemented by MS runtime for dynamic types
1729 public static bool HasElementType (Type t)
1731 return t.IsArray || t.IsPointer || t.IsByRef;
1734 public static Type GetEnumUnderlyingType (Type t)
1736 t = DropGenericTypeArguments (t);
1737 Enum e = LookupTypeContainer (t) as Enum;
1739 return e.UnderlyingType;
1742 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1744 return TypeManager.int32_type;
1746 return TypeToCoreType (fi.FieldType);
1750 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1754 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1755 /// for anything which is dynamic, and we need this in a number of places,
1756 /// we register this information here, and use it afterwards.
1758 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1760 method_params.Add (mb, ip);
1763 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1765 method_params.Add (pb, p);
1768 static public AParametersCollection GetParameterData (MethodBase mb)
1770 AParametersCollection pd = (AParametersCollection) method_params [mb];
1773 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1774 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1775 pd = GetParameterData (mi);
1777 if (mi.IsGenericMethod)
1778 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1780 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1782 method_params.Add (mb, pd);
1786 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1787 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1788 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1791 pd = ParametersImported.Create (mb);
1793 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1794 if (generic != mb) {
1795 pd = TypeManager.GetParameterData (generic);
1796 pd = ParametersImported.Create (pd, mb);
1798 pd = ParametersImported.Create (mb);
1801 method_params.Add (mb, pd);
1806 public static AParametersCollection GetParameterData (PropertyInfo pi)
1808 AParametersCollection pd = (AParametersCollection)method_params [pi];
1810 if (pi is PropertyBuilder)
1811 return ParametersCompiled.EmptyReadOnlyParameters;
1813 ParameterInfo [] p = pi.GetIndexParameters ();
1815 return ParametersCompiled.EmptyReadOnlyParameters;
1817 pd = ParametersImported.Create (p, null);
1818 method_params.Add (pi, pd);
1824 public static AParametersCollection GetDelegateParameters (Type t)
1826 Delegate d = builder_to_declspace [t] as Delegate;
1828 return d.Parameters;
1830 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1831 return GetParameterData (invoke_mb);
1834 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1836 if (!method_overrides.Contains (override_method))
1837 method_overrides [override_method] = base_method;
1838 if (method_overrides [override_method] != base_method)
1839 throw new InternalErrorException ("Override mismatch: " + override_method);
1842 static public bool IsOverride (MethodBase m)
1844 m = DropGenericMethodArguments (m);
1846 return m.IsVirtual &&
1847 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1848 (m is MethodBuilder || method_overrides.Contains (m));
1851 static public MethodBase TryGetBaseDefinition (MethodBase m)
1853 m = DropGenericMethodArguments (m);
1855 return (MethodBase) method_overrides [m];
1858 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1860 fields.Add (fb, ic);
1863 public static IConstant GetConstant (FieldInfo fb)
1868 return (IConstant)fields [fb];
1871 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1873 propertybuilder_to_property.Add (pi, pb);
1876 public static PropertyBase GetProperty (PropertyInfo pi)
1878 return (PropertyBase)propertybuilder_to_property [pi];
1881 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1883 fieldbuilders_to_fields.Add (fb, f);
1887 // The return value can be null; This will be the case for
1888 // auxiliary FieldBuilders created by the compiler that have no
1889 // real field being declared on the source code
1891 static public FieldBase GetField (FieldInfo fb)
1894 fb = GetGenericFieldDefinition (fb);
1896 return (FieldBase) fieldbuilders_to_fields [fb];
1899 static public MethodInfo GetAddMethod (EventInfo ei)
1901 if (ei is MyEventBuilder) {
1902 return ((MyEventBuilder)ei).GetAddMethod (true);
1904 return ei.GetAddMethod (true);
1907 static public MethodInfo GetRemoveMethod (EventInfo ei)
1909 if (ei is MyEventBuilder) {
1910 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1912 return ei.GetRemoveMethod (true);
1915 static public void RegisterEventField (EventInfo einfo, EventField e)
1918 events = new Hashtable ();
1920 events.Add (einfo, e);
1923 static public EventField GetEventField (EventInfo ei)
1928 return (EventField) events [ei];
1931 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1933 Hashtable hash = new Hashtable ();
1934 return CheckStructCycles (tc, seen, hash);
1937 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1940 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1944 // `seen' contains all types we've already visited.
1946 if (seen.Contains (tc))
1948 seen.Add (tc, null);
1950 if (tc.Fields == null)
1953 foreach (FieldBase field in tc.Fields) {
1954 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1957 Type ftype = field.FieldBuilder.FieldType;
1958 TypeContainer ftc = LookupTypeContainer (ftype);
1962 if (hash.Contains (ftc)) {
1963 Report.Error (523, tc.Location,
1964 "Struct member `{0}.{1}' of type `{2}' " +
1965 "causes a cycle in the struct layout",
1966 tc.Name, field.Name, ftc.Name);
1971 // `hash' contains all types in the current path.
1973 hash.Add (tc, null);
1975 bool ok = CheckStructCycles (ftc, seen, hash);
1982 if (!seen.Contains (ftc))
1983 seen.Add (ftc, null);
1990 /// Given an array of interface types, expand and eliminate repeated ocurrences
1991 /// of an interface.
1995 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1998 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
2000 ArrayList new_ifaces = new ArrayList ();
2002 foreach (TypeExpr iface in base_interfaces){
2003 Type itype = iface.Type;
2005 if (new_ifaces.Contains (itype))
2008 new_ifaces.Add (itype);
2010 Type [] implementing = GetInterfaces (itype);
2012 foreach (Type imp in implementing){
2013 if (!new_ifaces.Contains (imp))
2014 new_ifaces.Add (imp);
2017 Type [] ret = new Type [new_ifaces.Count];
2018 new_ifaces.CopyTo (ret, 0);
2022 public static Type[] ExpandInterfaces (Type [] base_interfaces)
2024 ArrayList new_ifaces = new ArrayList ();
2026 foreach (Type itype in base_interfaces){
2027 if (new_ifaces.Contains (itype))
2030 new_ifaces.Add (itype);
2032 Type [] implementing = GetInterfaces (itype);
2034 foreach (Type imp in implementing){
2035 if (!new_ifaces.Contains (imp))
2036 new_ifaces.Add (imp);
2039 Type [] ret = new Type [new_ifaces.Count];
2040 new_ifaces.CopyTo (ret, 0);
2044 static PtrHashtable iface_cache;
2047 /// This function returns the interfaces in the type `t'. Works with
2048 /// both types and TypeBuilders.
2050 public static Type [] GetInterfaces (Type t)
2052 Type [] cached = iface_cache [t] as Type [];
2057 // The reason for catching the Array case is that Reflection.Emit
2058 // will not return a TypeBuilder for Array types of TypeBuilder types,
2059 // but will still throw an exception if we try to call GetInterfaces
2062 // Since the array interfaces are always constant, we return those for
2067 t = TypeManager.array_type;
2069 if ((t is TypeBuilder) || IsGenericType (t)) {
2070 Type [] base_ifaces;
2072 if (t.BaseType == null)
2073 base_ifaces = Type.EmptyTypes;
2075 base_ifaces = GetInterfaces (t.BaseType);
2077 if (IsGenericType (t))
2078 #if MS_COMPATIBLE && GMCS_SOURCE
2079 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
2081 type_ifaces = t.GetInterfaces ();
2084 type_ifaces = (Type []) builder_to_ifaces [t];
2085 if (type_ifaces == null || type_ifaces.Length == 0)
2086 type_ifaces = Type.EmptyTypes;
2088 int base_count = base_ifaces.Length;
2089 Type [] result = new Type [base_count + type_ifaces.Length];
2090 base_ifaces.CopyTo (result, 0);
2091 type_ifaces.CopyTo (result, base_count);
2093 iface_cache [t] = result;
2096 } else if (t is GenericTypeParameterBuilder){
2097 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2098 if (type_ifaces == null || type_ifaces.Length == 0)
2099 type_ifaces = Type.EmptyTypes;
2101 iface_cache [t] = type_ifaces;
2105 Type[] ifaces = t.GetInterfaces ();
2106 iface_cache [t] = ifaces;
2112 // gets the interfaces that are declared explicitly on t
2114 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2116 return (Type []) builder_to_ifaces [t];
2120 /// The following is used to check if a given type implements an interface.
2121 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2123 public static bool ImplementsInterface (Type t, Type iface)
2128 // FIXME OPTIMIZATION:
2129 // as soon as we hit a non-TypeBuiler in the interface
2130 // chain, we could return, as the `Type.GetInterfaces'
2131 // will return all the interfaces implement by the type
2135 interfaces = GetInterfaces (t);
2137 if (interfaces != null){
2138 foreach (Type i in interfaces){
2139 if (i == iface || IsVariantOf (i, iface))
2145 } while (t != null);
2150 public static bool IsVariantOf (Type type1, Type type2)
2153 if (type1.IsGenericType && type2.IsGenericType) {
2154 Type generic_target_type = type2.GetGenericTypeDefinition ();
2155 if (type1.GetGenericTypeDefinition () == generic_target_type) {
2156 Type [] t1 = type1.GetGenericArguments ();
2157 Type [] t2 = type2.GetGenericArguments ();
2159 foreach (Type t in generic_target_type.GetGenericArguments ()) {
2160 if ((t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0) {
2161 // FIXME this is not right
2162 if (IsValueType (t1[i]) || IsValueType (t2[i])) {
2165 if ((t.GenericParameterAttributes & GenericParameterAttributes.Covariant) != 0 && !t2[i].IsAssignableFrom (t1[i])) {
2168 if ((t.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0 && !t1[i].IsAssignableFrom (t2[i])) {
2171 } else if (t1[i] != t2[i]) {
2183 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2185 // This is a custom version of Convert.ChangeType() which works
2186 // with the TypeBuilder defined types when compiling corlib.
2187 public static object ChangeType (object value, Type conversionType, out bool error)
2189 IConvertible convert_value = value as IConvertible;
2191 if (convert_value == null){
2198 // We must use Type.Equals() here since `conversionType' is
2199 // the TypeBuilder created version of a system type and not
2200 // the system type itself. You cannot use Type.GetTypeCode()
2201 // on such a type - it'd always return TypeCode.Object.
2204 // We cannot rely on build-in type conversions as they are
2205 // more limited than what C# supports.
2206 // See char -> float/decimal/double conversion
2211 if (conversionType.Equals (typeof (Boolean)))
2212 return (object)(convert_value.ToBoolean (nf_provider));
2213 if (conversionType.Equals (typeof (Byte)))
2214 return (object)(convert_value.ToByte (nf_provider));
2215 if (conversionType.Equals (typeof (Char)))
2216 return (object)(convert_value.ToChar (nf_provider));
2217 if (conversionType.Equals (typeof (DateTime)))
2218 return (object)(convert_value.ToDateTime (nf_provider));
2220 if (conversionType.Equals (decimal_type)) {
2221 if (convert_value.GetType () == TypeManager.char_type)
2222 return (decimal)convert_value.ToInt32 (nf_provider);
2223 return convert_value.ToDecimal (nf_provider);
2226 if (conversionType.Equals (typeof (Double))) {
2227 if (convert_value.GetType () == TypeManager.char_type)
2228 return (double)convert_value.ToInt32 (nf_provider);
2229 return convert_value.ToDouble (nf_provider);
2232 if (conversionType.Equals (typeof (Int16)))
2233 return (object)(convert_value.ToInt16 (nf_provider));
2234 if (conversionType.Equals (int32_type))
2235 return (object)(convert_value.ToInt32 (nf_provider));
2236 if (conversionType.Equals (int64_type))
2237 return (object)(convert_value.ToInt64 (nf_provider));
2238 if (conversionType.Equals (typeof (SByte)))
2239 return (object)(convert_value.ToSByte (nf_provider));
2241 if (conversionType.Equals (typeof (Single))) {
2242 if (convert_value.GetType () == TypeManager.char_type)
2243 return (float)convert_value.ToInt32 (nf_provider);
2244 return convert_value.ToSingle (nf_provider);
2247 if (conversionType.Equals (typeof (String)))
2248 return (object)(convert_value.ToString (nf_provider));
2249 if (conversionType.Equals (typeof (UInt16)))
2250 return (object)(convert_value.ToUInt16 (nf_provider));
2251 if (conversionType.Equals (typeof (UInt32)))
2252 return (object)(convert_value.ToUInt32 (nf_provider));
2253 if (conversionType.Equals (typeof (UInt64)))
2254 return (object)(convert_value.ToUInt64 (nf_provider));
2255 if (conversionType.Equals (typeof (Object)))
2256 return (object)(value);
2266 // When compiling with -nostdlib and the type is imported from an external assembly
2267 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2269 public static Type TypeToCoreType (Type t)
2271 if (RootContext.StdLib || t.Module != typeof (object).Module)
2274 TypeCode tc = Type.GetTypeCode (t);
2277 case TypeCode.Boolean:
2278 return TypeManager.bool_type;
2280 return TypeManager.byte_type;
2281 case TypeCode.SByte:
2282 return TypeManager.sbyte_type;
2284 return TypeManager.char_type;
2285 case TypeCode.Int16:
2286 return TypeManager.short_type;
2287 case TypeCode.UInt16:
2288 return TypeManager.ushort_type;
2289 case TypeCode.Int32:
2290 return TypeManager.int32_type;
2291 case TypeCode.UInt32:
2292 return TypeManager.uint32_type;
2293 case TypeCode.Int64:
2294 return TypeManager.int64_type;
2295 case TypeCode.UInt64:
2296 return TypeManager.uint64_type;
2297 case TypeCode.Single:
2298 return TypeManager.float_type;
2299 case TypeCode.Double:
2300 return TypeManager.double_type;
2301 case TypeCode.String:
2302 return TypeManager.string_type;
2303 case TypeCode.Decimal:
2304 return TypeManager.decimal_type;
2307 if (t == typeof (void))
2308 return TypeManager.void_type;
2309 if (t == typeof (object))
2310 return TypeManager.object_type;
2311 if (t == typeof (System.Type))
2312 return TypeManager.type_type;
2313 if (t == typeof (System.IntPtr))
2314 return TypeManager.intptr_type;
2315 if (t == typeof (System.UIntPtr))
2316 return TypeManager.uintptr_type;
2319 int dim = t.GetArrayRank ();
2320 t = GetElementType (t);
2321 return t.MakeArrayType (dim);
2324 t = GetElementType (t);
2325 return t.MakeByRefType ();
2328 t = GetElementType (t);
2329 return t.MakePointerType ();
2336 /// Utility function that can be used to probe whether a type
2337 /// is managed or not.
2339 public static bool VerifyUnManaged (Type t, Location loc)
2341 if (IsUnmanagedType (t))
2345 t = GetElementType (t);
2347 Report.SymbolRelatedToPreviousError (t);
2348 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2355 /// Returns the name of the indexer in a given type.
2358 /// The default is not always `Item'. The user can change this behaviour by
2359 /// using the IndexerNameAttribute in the container.
2360 /// For example, the String class indexer is named `Chars' not `Item'
2362 public static string IndexerPropertyName (Type t)
2364 t = DropGenericTypeArguments (t);
2365 if (t is TypeBuilder) {
2366 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2367 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2370 System.Attribute attr = System.Attribute.GetCustomAttribute (
2371 t, TypeManager.default_member_type);
2373 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2374 return dma.MemberName;
2377 return TypeContainer.DefaultIndexerName;
2380 static MethodInfo declare_local_method = null;
2382 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2384 if (declare_local_method == null){
2385 declare_local_method = typeof (ILGenerator).GetMethod (
2387 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2389 new Type [] { typeof (Type), typeof (bool)},
2391 if (declare_local_method == null){
2392 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2393 return ig.DeclareLocal (t);
2396 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2399 private static bool IsSignatureEqual (Type a, Type b)
2402 /// Consider the following example (bug #77674):
2404 /// public abstract class A
2406 /// public abstract T Foo<T> ();
2409 /// public abstract class B : A
2411 /// public override U Foo<T> ()
2412 /// { return default (U); }
2415 /// Here, `T' and `U' are method type parameters from different methods
2416 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2418 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2419 /// we need to do a signature based comparision and consider them equal.
2425 if (a.IsGenericParameter && b.IsGenericParameter &&
2426 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2427 return a.GenericParameterPosition == b.GenericParameterPosition;
2431 if (a.IsArray && b.IsArray) {
2432 if (a.GetArrayRank () != b.GetArrayRank ())
2435 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2438 if (a.IsByRef && b.IsByRef)
2439 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2442 if (a.IsGenericType && b.IsGenericType) {
2443 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2446 Type[] aargs = a.GetGenericArguments ();
2447 Type[] bargs = b.GetGenericArguments ();
2449 if (aargs.Length != bargs.Length)
2452 for (int i = 0; i < aargs.Length; i++) {
2453 if (!IsSignatureEqual (aargs [i], bargs [i]))
2465 // Returns whether the array of memberinfos contains the given method
2467 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2469 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2471 foreach (MethodBase method in array) {
2472 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2475 if (method.Name != new_method.Name)
2478 if (method is MethodInfo && new_method is MethodInfo &&
2480 TypeToCoreType (((MethodInfo) method).ReturnType),
2481 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2484 Type [] old_args = TypeManager.GetParameterData (method).Types;
2485 int old_count = old_args.Length;
2488 if (new_args.Length != old_count)
2491 for (i = 0; i < old_count; i++){
2492 if (!IsSignatureEqual (old_args [i], new_args [i]))
2505 // We copy methods from `new_members' into `target_list' if the signature
2506 // for the method from in the new list does not exist in the target_list
2508 // The name is assumed to be the same.
2510 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2512 if (target_list == null){
2513 target_list = new ArrayList ();
2515 foreach (MemberInfo mi in new_members){
2516 if (mi is MethodBase)
2517 target_list.Add (mi);
2522 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2523 target_list.CopyTo (target_array, 0);
2525 foreach (MemberInfo mi in new_members){
2526 MethodBase new_method = (MethodBase) mi;
2528 if (!ArrayContainsMethod (target_array, new_method, true))
2529 target_list.Add (new_method);
2536 // Tracks the generic parameters.
2538 static PtrHashtable builder_to_type_param;
2540 public static void AddTypeParameter (Type t, TypeParameter tparam)
2542 if (!builder_to_type_param.Contains (t))
2543 builder_to_type_param.Add (t, tparam);
2546 public static TypeParameter LookupTypeParameter (Type t)
2548 return (TypeParameter) builder_to_type_param [t];
2551 // This method always return false for non-generic compiler,
2552 // while Type.IsGenericParameter is returned if it is supported.
2553 public static bool IsGenericParameter (Type type)
2556 return type.IsGenericParameter;
2562 public static int GenericParameterPosition (Type type)
2565 return type.GenericParameterPosition;
2567 throw new InternalErrorException ("should not be called");
2571 public static bool IsGenericType (Type type)
2574 return type.IsGenericType;
2580 public static bool IsGenericTypeDefinition (Type type)
2583 return type.IsGenericTypeDefinition;
2589 public static bool ContainsGenericParameters (Type type)
2592 return type.ContainsGenericParameters;
2598 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2601 if (fi.DeclaringType.IsGenericTypeDefinition ||
2602 !fi.DeclaringType.IsGenericType)
2605 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2606 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2607 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2609 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2610 foreach (FieldInfo f in t.GetFields (bf))
2611 if (f.MetadataToken == fi.MetadataToken)
2618 public static bool IsEqual (Type a, Type b)
2621 // MS BCL returns true even if enum types are different
2622 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2623 return a.FullName == b.FullName;
2625 // Some types are never equal
2626 if (a == TypeManager.null_type || a == TypeManager.anonymous_method_type)
2633 if (a.IsGenericParameter && b.IsGenericParameter) {
2634 // TODO: needs more testing before cleaning up
2635 //if (a.DeclaringMethod != b.DeclaringMethod &&
2636 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2638 return a.GenericParameterPosition == b.GenericParameterPosition;
2641 if (a.IsArray && b.IsArray) {
2642 if (a.GetArrayRank () != b.GetArrayRank ())
2644 return IsEqual (GetElementType (a), GetElementType (b));
2647 if (a.IsByRef && b.IsByRef)
2648 return IsEqual (a.GetElementType (), b.GetElementType ());
2650 if (a.IsGenericType && b.IsGenericType) {
2651 Type adef = a.GetGenericTypeDefinition ();
2652 Type bdef = b.GetGenericTypeDefinition ();
2657 if (adef.IsEnum && bdef.IsEnum)
2660 Type[] aargs = a.GetGenericArguments ();
2661 Type[] bargs = b.GetGenericArguments ();
2663 if (aargs.Length != bargs.Length)
2666 for (int i = 0; i < aargs.Length; i++) {
2667 if (!IsEqual (aargs [i], bargs [i]))
2678 public static bool IsEqual (Type[] a, Type[] b)
2680 if (a == null || b == null || a.Length != b.Length)
2683 for (int i = 0; i < a.Length; ++i) {
2684 if (a [i] == null || b [i] == null) {
2691 if (!IsEqual (a [i], b [i]))
2698 public static Type DropGenericTypeArguments (Type t)
2701 if (!t.IsGenericType)
2703 // Micro-optimization: a generic typebuilder is always a generic type definition
2704 if (t is TypeBuilder)
2706 return t.GetGenericTypeDefinition ();
2712 public static MethodBase DropGenericMethodArguments (MethodBase m)
2715 if (m.IsGenericMethod)
2716 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2718 Type t = m.DeclaringType;
2719 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2722 t = t.GetGenericTypeDefinition ();
2723 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2724 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2727 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2731 if (m is ConstructorInfo) {
2732 foreach (ConstructorInfo c in t.GetConstructors (bf))
2733 if (c.MetadataToken == m.MetadataToken)
2736 foreach (MethodBase mb in t.GetMethods (bf))
2737 if (mb.MetadataToken == m.MetadataToken)
2745 public static Type[] GetGenericArguments (MethodBase mi)
2748 return mi.GetGenericArguments ();
2750 return Type.EmptyTypes;
2754 public static Type[] GetTypeArguments (Type t)
2757 DeclSpace tc = LookupDeclSpace (t);
2760 return Type.EmptyTypes;
2762 TypeParameter[] tparam = tc.TypeParameters;
2763 Type[] ret = new Type [tparam.Length];
2764 for (int i = 0; i < tparam.Length; i++) {
2765 ret [i] = tparam [i].Type;
2766 if (ret [i] == null)
2767 throw new InternalErrorException ();
2772 return t.GetGenericArguments ();
2774 throw new InternalErrorException ();
2778 public static GenericConstraints GetTypeParameterConstraints (Type t)
2781 if (!t.IsGenericParameter)
2782 throw new InvalidOperationException ();
2784 TypeParameter tparam = LookupTypeParameter (t);
2786 return tparam.GenericConstraints;
2788 return ReflectionConstraints.GetConstraints (t);
2790 throw new InternalErrorException ();
2794 public static bool HasGenericArguments (Type t)
2796 return GetNumberOfTypeArguments (t) > 0;
2799 public static int GetNumberOfTypeArguments (Type t)
2802 if (t.IsGenericParameter)
2804 DeclSpace tc = LookupDeclSpace (t);
2806 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2808 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2815 /// Check whether `type' and `parent' are both instantiations of the same
2816 /// generic type. Note that we do not check the type parameters here.
2818 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2820 int tcount = GetNumberOfTypeArguments (type);
2821 int pcount = GetNumberOfTypeArguments (parent);
2823 if (tcount != pcount)
2826 type = DropGenericTypeArguments (type);
2827 parent = DropGenericTypeArguments (parent);
2829 return type.Equals (parent);
2833 /// Whether `mb' is a generic method definition.
2835 public static bool IsGenericMethodDefinition (MethodBase mb)
2838 if (mb.DeclaringType is TypeBuilder) {
2839 IMethodData method = (IMethodData) builder_to_method [mb];
2843 return method.GenericMethod != null;
2846 return mb.IsGenericMethodDefinition;
2853 /// Whether `mb' is a generic method.
2855 public static bool IsGenericMethod (MethodBase mb)
2858 return mb.IsGenericMethod;
2864 public static bool IsNullableType (Type t)
2867 return generic_nullable_type == DropGenericTypeArguments (t);
2873 public static bool IsNullableTypeOf (Type t, Type nullable)
2876 if (!IsNullableType (t))
2879 return GetTypeArguments (t) [0] == nullable;
2885 public static bool IsNullableValueType (Type t)
2888 if (!IsNullableType (t))
2891 return IsValueType (GetTypeArguments (t) [0]);
2898 #region MemberLookup implementation
2901 // Whether we allow private members in the result (since FindMembers
2902 // uses NonPublic for both protected and private), we need to distinguish.
2905 internal class Closure {
2906 internal bool private_ok;
2908 // Who is invoking us and which type is being queried currently.
2909 internal Type invocation_type;
2910 internal Type qualifier_type;
2912 // The assembly that defines the type is that is calling us
2913 internal Assembly invocation_assembly;
2914 internal IList almost_match;
2916 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2918 if (invocation_type == null)
2921 if (is_static && qualifier_type == null)
2922 // It resolved from a simple name, so it should be visible.
2925 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2928 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2929 if (!IsFamilyAccessible (t, m.DeclaringType))
2932 // Although a derived class can access protected members of its base class
2933 // it cannot do so through an instance of the base class (CS1540).
2934 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2935 if (is_static || qualifier_type == null ||
2936 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2937 IsFamilyAccessible (qualifier_type, t))
2941 if (almost_match != null)
2942 almost_match.Add (m);
2948 // This filter filters by name + whether it is ok to include private
2949 // members in the search
2951 internal bool Filter (MemberInfo m, object filter_criteria)
2954 // Hack: we know that the filter criteria will always be in the
2955 // `closure' // fields.
2958 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2961 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2962 (invocation_type != null) &&
2963 IsPrivateAccessible (m.DeclaringType, invocation_type))
2967 // Ugly: we need to find out the type of `m', and depending
2968 // on this, tell whether we accept or not
2970 if (m is MethodBase){
2971 MethodBase mb = (MethodBase) m;
2972 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2974 if (ma == MethodAttributes.Public)
2977 if (ma == MethodAttributes.PrivateScope)
2980 if (ma == MethodAttributes.Private)
2981 return private_ok ||
2982 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2983 IsNestedChildOf (invocation_type, m.DeclaringType);
2985 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2986 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2989 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2993 // Family, FamORAssem or FamANDAssem
2994 return CheckValidFamilyAccess (mb.IsStatic, m);
2997 if (m is FieldInfo){
2998 FieldInfo fi = (FieldInfo) m;
2999 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
3001 if (fa == FieldAttributes.Public)
3004 if (fa == FieldAttributes.PrivateScope)
3007 if (fa == FieldAttributes.Private)
3008 return private_ok ||
3009 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
3010 IsNestedChildOf (invocation_type, m.DeclaringType);
3012 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
3013 if ((fa == FieldAttributes.Assembly) ||
3014 (fa == FieldAttributes.FamORAssem))
3017 if ((fa == FieldAttributes.Assembly) ||
3018 (fa == FieldAttributes.FamANDAssem))
3022 // Family, FamORAssem or FamANDAssem
3023 return CheckValidFamilyAccess (fi.IsStatic, m);
3027 // EventInfos and PropertyInfos, return true because they lack
3028 // permission information, so we need to check later on the methods.
3034 static Closure closure = new Closure ();
3035 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
3038 // Looks up a member called `name' in the `queried_type'. This lookup
3039 // is done by code that is contained in the definition for `invocation_type'
3040 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
3042 // `invocation_type' is used to check whether we're allowed to access the requested
3043 // member wrt its protection level.
3045 // When called from MemberAccess, `qualifier_type' is the type which is used to access
3046 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
3047 // is B and qualifier_type is A). This is used to do the CS1540 check.
3049 // When resolving a SimpleName, `qualifier_type' is null.
3051 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
3052 // the same than `queried_type' - except when we're being called from BaseAccess;
3053 // in this case, `invocation_type' is the current type and `queried_type' the base
3054 // type, so this'd normally trigger a CS1540.
3056 // The binding flags are `bf' and the kind of members being looked up are `mt'
3058 // The return value always includes private members which code in `invocation_type'
3059 // is allowed to access (using the specified `qualifier_type' if given); only use
3060 // BindingFlags.NonPublic to bypass the permission check.
3062 // The 'almost_match' argument is used for reporting error CS1540.
3064 // Returns an array of a single element for everything but Methods/Constructors
3065 // that might return multiple matches.
3067 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
3068 Type queried_type, MemberTypes mt,
3069 BindingFlags original_bf, string name, IList almost_match)
3071 Timer.StartTimer (TimerType.MemberLookup);
3073 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
3074 queried_type, mt, original_bf, name, almost_match);
3076 Timer.StopTimer (TimerType.MemberLookup);
3081 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
3082 Type queried_type, MemberTypes mt,
3083 BindingFlags original_bf, string name, IList almost_match)
3085 BindingFlags bf = original_bf;
3087 ArrayList method_list = null;
3088 Type current_type = queried_type;
3089 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
3090 bool skip_iface_check = true, used_cache = false;
3091 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
3093 closure.invocation_type = invocation_type;
3094 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
3095 closure.qualifier_type = qualifier_type;
3096 closure.almost_match = almost_match;
3098 // This is from the first time we find a method
3099 // in most cases, we do not actually find a method in the base class
3100 // so we can just ignore it, and save the arraylist allocation
3101 MemberInfo [] first_members_list = null;
3102 bool use_first_members_list = false;
3108 // `NonPublic' is lame, because it includes both protected and
3109 // private methods, so we need to control this behavior by
3110 // explicitly tracking if a private method is ok or not.
3112 // The possible cases are:
3113 // public, private and protected (internal does not come into the
3116 if ((invocation_type != null) &&
3117 ((invocation_type == current_type) ||
3118 IsNestedChildOf (invocation_type, current_type)) ||
3120 bf = original_bf | BindingFlags.NonPublic;
3124 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
3126 Timer.StopTimer (TimerType.MemberLookup);
3128 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
3130 Timer.StartTimer (TimerType.MemberLookup);
3133 // When queried for an interface type, the cache will automatically check all
3134 // inherited members, so we don't need to do this here. However, this only
3135 // works if we already used the cache in the first iteration of this loop.
3137 // If we used the cache in any further iteration, we can still terminate the
3138 // loop since the cache always looks in all base classes.
3144 skip_iface_check = false;
3146 if (current_type == TypeManager.object_type)
3149 current_type = current_type.BaseType;
3152 // This happens with interfaces, they have a null
3153 // basetype. Look members up in the Object class.
3155 if (current_type == null) {
3156 current_type = TypeManager.object_type;
3161 if (list.Length == 0)
3165 // Events and types are returned by both `static' and `instance'
3166 // searches, which means that our above FindMembers will
3167 // return two copies of the same.
3169 if (list.Length == 1 && !(list [0] is MethodBase)){
3174 // Multiple properties: we query those just to find out the indexer
3177 if (list [0] is PropertyInfo)
3181 // We found an event: the cache lookup returns both the event and
3182 // its private field.
3184 if (list [0] is EventInfo) {
3185 if ((list.Length == 2) && (list [1] is FieldInfo))
3186 return new MemberInfo [] { list [0] };
3192 // We found methods, turn the search into "method scan"
3196 if (first_members_list != null) {
3197 if (use_first_members_list) {
3198 method_list = CopyNewMethods (method_list, first_members_list);
3199 use_first_members_list = false;
3202 method_list = CopyNewMethods (method_list, list);
3204 first_members_list = list;
3205 use_first_members_list = true;
3206 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3208 } while (searching);
3210 if (use_first_members_list)
3211 return first_members_list;
3213 if (method_list != null && method_list.Count > 0) {
3214 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3217 // This happens if we already used the cache in the first iteration, in this case
3218 // the cache already looked in all interfaces.
3220 if (skip_iface_check)
3224 // Interfaces do not list members they inherit, so we have to
3227 if (!queried_type.IsInterface)
3230 if (queried_type.IsArray)
3231 queried_type = TypeManager.array_type;
3233 Type [] ifaces = GetInterfaces (queried_type);
3237 foreach (Type itype in ifaces){
3240 x = MemberLookup (null, null, itype, mt, bf, name, null);
3248 const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3249 BindingFlags.Static | BindingFlags.Instance |
3250 BindingFlags.DeclaredOnly;
3252 // Currently is designed to work with external types only
3253 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3255 if (!mb.IsSpecialName)
3258 string name = mb.Name;
3259 if (name.Length < 5)
3262 if (name [3] != '_')
3265 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3266 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3267 Type.FilterName, name.Substring (4));
3272 // This can happen when property is indexer (it can have same name but different parameters)
3273 foreach (PropertyInfo p in pi) {
3274 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3275 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3284 // Currently is designed to work with external types only
3285 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3287 if (!mb.IsSpecialName)
3290 string name = mb.Name;
3291 if (name.Length < 5)
3294 if (name.StartsWith ("add_"))
3295 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3297 if (name.StartsWith ("remove_"))
3298 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3303 // Tests whether external method is really special
3304 public static bool IsSpecialMethod (MethodBase mb)
3306 if (!mb.IsSpecialName)
3309 IMethodData md = TypeManager.GetMethod (mb);
3311 return (md is AbstractPropertyEventMethod || md is Operator);
3313 PropertyInfo pi = GetPropertyFromAccessor (mb);
3315 return IsValidProperty (pi);
3317 if (GetEventFromAccessor (mb) != null)
3320 string name = mb.Name;
3321 if (name.StartsWith ("op_"))
3322 return Operator.GetName (name) != null;
3327 // Tests whether imported property is valid C# property.
3328 // TODO: It seems to me that we should do a lot of sanity tests before
3329 // we accept property as C# property
3330 static bool IsValidProperty (PropertyInfo pi)
3332 MethodInfo get_method = pi.GetGetMethod (true);
3333 MethodInfo set_method = pi.GetSetMethod (true);
3336 if (get_method != null && set_method != null) {
3337 g_count = get_method.GetParameters ().Length;
3338 s_count = set_method.GetParameters ().Length;
3339 if (g_count + 1 != s_count)
3341 } else if (get_method != null) {
3342 g_count = get_method.GetParameters ().Length;
3343 } else if (set_method != null) {
3344 s_count = set_method.GetParameters ().Length;
3348 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3350 if ((s_count > 1 || g_count > 0) && TypeManager.default_member_type != null) {
3351 object[] o = pi.DeclaringType.GetCustomAttributes (TypeManager.default_member_type, false);
3355 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3356 if (dma.MemberName != pi.Name)
3358 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3360 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3372 /// There is exactly one instance of this class per type.
3374 public sealed class TypeHandle : IMemberContainer {
3375 public readonly IMemberContainer BaseType;
3377 readonly int id = ++next_id;
3378 static int next_id = 0;
3380 static TypeHandle ()
3386 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3387 /// a TypeHandle yet, a new instance of it is created. This static method
3388 /// ensures that we'll only have one TypeHandle instance per type.
3390 private static TypeHandle GetTypeHandle (Type t)
3392 TypeHandle handle = (TypeHandle) type_hash [t];
3396 handle = new TypeHandle (t);
3397 type_hash.Add (t, handle);
3401 public static MemberCache GetMemberCache (Type t)
3403 return GetTypeHandle (t).MemberCache;
3406 public static void CleanUp ()
3411 public static void Reset ()
3413 type_hash = new PtrHashtable ();
3417 /// Returns the TypeHandle for TypeManager.object_type.
3419 public static IMemberContainer ObjectType {
3421 if (object_type != null)
3424 object_type = GetTypeHandle (TypeManager.object_type);
3431 /// Returns the TypeHandle for TypeManager.array_type.
3433 public static TypeHandle ArrayType {
3435 if (array_type != null)
3438 array_type = GetTypeHandle (TypeManager.array_type);
3444 private static PtrHashtable type_hash;
3446 private static TypeHandle object_type = null;
3447 private static TypeHandle array_type = null;
3450 private string full_name;
3451 private bool is_interface;
3452 private MemberCache member_cache;
3453 private MemberCache base_cache;
3455 private TypeHandle (Type type)
3458 full_name = type.FullName != null ? type.FullName : type.Name;
3459 if (type.BaseType != null) {
3460 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3461 BaseType = base_cache.Container;
3462 } else if (type.IsInterface)
3463 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3464 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3465 this.member_cache = new MemberCache (this);
3468 // IMemberContainer methods
3470 public string Name {
3482 public MemberCache BaseCache {
3488 public bool IsInterface {
3490 return is_interface;
3494 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3496 MemberInfo [] members;
3499 if (type is GenericTypeParameterBuilder)
3500 return MemberList.Empty;
3504 type = TypeManager.DropGenericTypeArguments (type);
3506 if (mt == MemberTypes.Event)
3507 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3509 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3512 if (members.Length == 0)
3513 return MemberList.Empty;
3515 Array.Reverse (members);
3516 return new MemberList (members);
3519 // IMemberFinder methods
3521 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3522 MemberFilter filter, object criteria)
3524 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3527 public MemberCache MemberCache {
3529 return member_cache;
3533 public override string ToString ()
3535 if (BaseType != null)
3536 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3538 return "TypeHandle (" + id + "," + Name + ")";