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 short_type;
51 static public Type decimal_type;
52 static public Type bool_type;
53 static public Type sbyte_type;
54 static public Type byte_type;
55 static public Type ushort_type;
56 static public Type enum_type;
57 static public Type delegate_type;
58 static public Type multicast_delegate_type;
59 static public Type void_type;
60 static public Type null_type;
61 static public Type array_type;
62 static public Type runtime_handle_type;
63 static public Type type_type;
64 static public Type ienumerator_type;
65 static public Type ienumerable_type;
66 static public Type idisposable_type;
67 static public Type iasyncresult_type;
68 static public Type asynccallback_type;
69 static public Type intptr_type;
70 static public Type uintptr_type;
71 static public Type runtime_field_handle_type;
72 static public Type runtime_argument_handle_type;
73 static public Type attribute_type;
74 static public Type void_ptr_type;
75 static public Type exception_type;
77 static public Type anonymous_method_type;
78 static public Type typed_reference_type;
79 static public Type arg_iterator_type;
80 static public Type mbr_type;
81 public static Type runtime_helpers_type;
86 static internal Type isvolatile_type;
87 static public Type generic_ilist_type;
88 static public Type generic_icollection_type;
89 static public Type generic_ienumerator_type;
90 static public Type generic_ienumerable_type;
91 static public Type generic_nullable_type;
96 static internal Type expression_type;
97 public static Type parameter_expression_type;
100 // Expressions representing the internal types. Used during declaration
103 static public TypeExpr system_object_expr, system_string_expr;
104 static public TypeExpr system_boolean_expr, system_decimal_expr;
105 static public TypeExpr system_single_expr, system_double_expr;
106 static public TypeExpr system_sbyte_expr, system_byte_expr;
107 static public TypeExpr system_int16_expr, system_uint16_expr;
108 static public TypeExpr system_int32_expr, system_uint32_expr;
109 static public TypeExpr system_int64_expr, system_uint64_expr;
110 static public TypeExpr system_char_expr, system_void_expr;
111 static public TypeExpr system_valuetype_expr;
112 static public TypeExpr system_intptr_expr;
113 public static TypeExpr expression_type_expr;
117 // These methods are called by code generated by the compiler
119 static public FieldInfo string_empty;
120 static public MethodInfo system_type_get_type_from_handle;
121 static public MethodInfo bool_movenext_void;
122 static public MethodInfo void_dispose_void;
123 static public MethodInfo void_monitor_enter_object;
124 static public MethodInfo void_monitor_exit_object;
125 static public MethodInfo void_initializearray_array_fieldhandle;
126 static public MethodInfo delegate_combine_delegate_delegate;
127 static public MethodInfo delegate_remove_delegate_delegate;
128 static public PropertyInfo int_get_offset_to_string_data;
129 static public MethodInfo int_interlocked_compare_exchange;
130 static public PropertyInfo ienumerator_getcurrent;
131 public static MethodInfo methodbase_get_type_from_handle;
132 public static MethodInfo methodbase_get_type_from_handle_generic;
133 public static MethodInfo fieldinfo_get_field_from_handle;
134 static public MethodInfo activator_create_instance;
139 static public ConstructorInfo void_decimal_ctor_five_args;
140 static public ConstructorInfo void_decimal_ctor_int_arg;
142 static PtrHashtable builder_to_declspace;
144 static PtrHashtable builder_to_member_cache;
147 // Tracks the interfaces implemented by typebuilders. We only
148 // enter those who do implement or or more interfaces
150 static PtrHashtable builder_to_ifaces;
153 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
155 static Hashtable method_params;
158 // A hash table from override methods to their base virtual method.
160 static Hashtable method_overrides;
163 // Keeps track of methods
166 static Hashtable builder_to_method;
169 // Contains all public types from referenced assemblies.
170 // This member is used only if CLS Compliance verification is required.
172 public static Hashtable AllClsTopLevelTypes;
174 static Hashtable fieldbuilders_to_fields;
175 static Hashtable propertybuilder_to_property;
176 static Hashtable fields;
177 static Hashtable events;
178 static PtrHashtable assembly_internals_vis_attrs;
180 public static void CleanUp ()
182 // Lets get everything clean so that we can collect before generating code
183 builder_to_declspace = null;
184 builder_to_member_cache = null;
185 builder_to_ifaces = null;
186 builder_to_type_param = null;
187 method_params = null;
188 builder_to_method = null;
193 propertybuilder_to_property = null;
195 TypeHandle.CleanUp ();
199 // These are expressions that represent some of the internal data types, used
202 static void InitExpressionTypes ()
204 system_object_expr = new TypeLookupExpression ("System", "Object");
205 system_string_expr = new TypeLookupExpression ("System", "String");
206 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
207 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
208 system_single_expr = new TypeLookupExpression ("System", "Single");
209 system_double_expr = new TypeLookupExpression ("System", "Double");
210 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
211 system_byte_expr = new TypeLookupExpression ("System", "Byte");
212 system_int16_expr = new TypeLookupExpression ("System", "Int16");
213 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
214 system_int32_expr = new TypeLookupExpression ("System", "Int32");
215 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
216 system_int64_expr = new TypeLookupExpression ("System", "Int64");
217 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
218 system_char_expr = new TypeLookupExpression ("System", "Char");
219 system_void_expr = new TypeLookupExpression ("System", "Void");
220 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
221 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
224 static TypeManager ()
229 static public void Reset ()
231 InitExpressionTypes ();
233 builder_to_declspace = new PtrHashtable ();
234 builder_to_member_cache = new PtrHashtable ();
235 builder_to_method = new PtrHashtable ();
236 builder_to_type_param = new PtrHashtable ();
237 method_params = new PtrHashtable ();
238 method_overrides = new PtrHashtable ();
239 builder_to_ifaces = new PtrHashtable ();
241 fieldbuilders_to_fields = new Hashtable ();
242 propertybuilder_to_property = new Hashtable ();
243 fields = new Hashtable ();
244 type_hash = new DoubleHash ();
245 assembly_internals_vis_attrs = new PtrHashtable ();
246 iface_cache = new PtrHashtable ();
248 closure = new Closure ();
249 FilterWithClosure_delegate = new MemberFilter (closure.Filter);
251 // TODO: I am really bored by all this static stuff
252 system_type_get_type_from_handle =
255 void_monitor_enter_object =
256 void_monitor_exit_object =
257 void_initializearray_array_fieldhandle =
258 delegate_combine_delegate_delegate =
259 delegate_remove_delegate_delegate =
260 int_interlocked_compare_exchange =
261 methodbase_get_type_from_handle =
262 methodbase_get_type_from_handle_generic =
263 fieldinfo_get_field_from_handle =
264 activator_create_instance = null;
266 int_get_offset_to_string_data =
267 ienumerator_getcurrent = null;
269 void_decimal_ctor_five_args =
270 void_decimal_ctor_int_arg = null;
272 isvolatile_type = null;
274 // to uncover regressions
275 AllClsTopLevelTypes = null;
278 public static void AddUserType (DeclSpace ds)
280 builder_to_declspace.Add (ds.TypeBuilder, ds);
284 // This entry point is used by types that we define under the covers
286 public static void RegisterBuilder (Type tb, Type [] ifaces)
289 builder_to_ifaces [tb] = ifaces;
292 public static void AddMethod (MethodBase builder, IMethodData method)
294 builder_to_method.Add (builder, method);
295 method_params.Add (builder, method.ParameterInfo);
298 public static IMethodData GetMethod (MethodBase builder)
300 return (IMethodData) builder_to_method [builder];
304 /// Returns the DeclSpace whose Type is `t' or null if there is no
305 /// DeclSpace for `t' (ie, the Type comes from a library)
307 public static DeclSpace LookupDeclSpace (Type t)
309 return builder_to_declspace [t] as DeclSpace;
313 /// Returns the TypeContainer whose Type is `t' or null if there is no
314 /// TypeContainer for `t' (ie, the Type comes from a library)
316 public static TypeContainer LookupTypeContainer (Type t)
318 return builder_to_declspace [t] as TypeContainer;
321 public static MemberCache LookupMemberCache (Type t)
323 if (t.Module == RootContext.ToplevelTypes.Builder) {
324 DeclSpace container = (DeclSpace)builder_to_declspace [t];
325 if (container != null)
326 return container.MemberCache;
330 if (t is GenericTypeParameterBuilder) {
331 TypeParameter container = builder_to_type_param [t] as TypeParameter;
333 if (container != null)
334 return container.MemberCache;
338 return TypeHandle.GetMemberCache (t);
341 public static MemberCache LookupBaseInterfacesCache (Type t)
343 Type [] ifaces = GetInterfaces (t);
345 if (ifaces != null && ifaces.Length == 1)
346 return LookupMemberCache (ifaces [0]);
348 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
349 MemberCache cache = builder_to_member_cache [t] as MemberCache;
353 cache = new MemberCache (ifaces);
354 builder_to_member_cache.Add (t, cache);
358 public static TypeContainer LookupInterface (Type t)
360 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
361 if ((tc == null) || (tc.Kind != Kind.Interface))
367 public static Delegate LookupDelegate (Type t)
369 return builder_to_declspace [t] as Delegate;
372 public static Class LookupClass (Type t)
374 return (Class) builder_to_declspace [t];
378 // We use this hash for multiple kinds of constructed types:
380 // (T, "&") Given T, get T &
381 // (T, "*") Given T, get T *
382 // (T, "[]") Given T and a array dimension, get T []
383 // (T, X) Given a type T and a simple name X, get the type T+X
385 // Accessibility tests, if necessary, should be done by the user
387 static DoubleHash type_hash = new DoubleHash ();
390 // Gets the reference to T version of the Type (T&)
392 public static Type GetReferenceType (Type t)
395 return t.MakeByRefType ();
397 return GetConstructedType (t, "&");
402 // Gets the pointer to T version of the Type (T*)
404 public static Type GetPointerType (Type t)
406 return GetConstructedType (t, "*");
409 public static Type GetConstructedType (Type t, string dim)
412 if (type_hash.Lookup (t, dim, out ret))
415 ret = t.Module.GetType (t.ToString () + dim);
417 type_hash.Insert (t, dim, ret);
422 ret = GetReferenceType (t);
423 type_hash.Insert (t, dim, ret);
428 if (t.IsGenericParameter || t.IsGenericType) {
431 while ((pos < dim.Length) && (dim [pos] == '[')) {
434 if (dim [pos] == ']') {
435 result = result.MakeArrayType ();
438 if (pos < dim.Length)
441 type_hash.Insert (t, dim, result);
446 while (dim [pos] == ',') {
450 if ((dim [pos] != ']') || (pos != dim.Length-1))
453 result = result.MakeArrayType (rank + 1);
454 type_hash.Insert (t, dim, result);
460 type_hash.Insert (t, dim, null);
464 public static Type GetNestedType (Type t, string name)
467 if (!type_hash.Lookup (t, name, out ret)) {
468 ret = t.GetNestedType (name,
469 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
470 type_hash.Insert (t, name, ret);
476 /// Fills static table with exported types from all referenced assemblies.
477 /// This information is required for CLS Compliance tests.
479 public static void LoadAllImportedTypes ()
481 AllClsTopLevelTypes = new Hashtable (1500);
482 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
483 foreach (Type t in a.GetExportedTypes ()) {
484 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
489 public static bool NamespaceClash (string name, Location loc)
491 if (!GlobalRootNamespace.Instance.IsNamespace (name))
494 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
499 /// Returns the C# name of a type if possible, or the full type name otherwise
501 static public string CSharpName (Type t)
506 if (t == typeof (ArglistParameter))
509 if (t == typeof (AnonymousMethodBody))
510 return "anonymous method";
512 if (t == typeof (MethodGroupExpr))
513 return "method group";
516 return "internal error";
518 return CSharpName (GetFullName (t), t);
521 static readonly char [] elements = new char [] { '*', '[' };
523 public static string CSharpName (string name, Type type)
525 if (name.Length > 10) {
528 case "System.Int32": s = "int"; break;
529 case "System.Int64": s = "long"; break;
530 case "System.String": s = "string"; break;
531 case "System.Boolean": s = "bool"; break;
532 case "System.Void": s = "void"; break;
533 case "System.Object": s = "object"; break;
534 case "System.UInt32": s = "uint"; break;
535 case "System.Int16": s = "short"; break;
536 case "System.UInt16": s = "ushort"; break;
537 case "System.UInt64": s = "ulong"; break;
538 case "System.Single": s = "float"; break;
539 case "System.Double": s = "double"; break;
540 case "System.Decimal": s = "decimal"; break;
541 case "System.Char": s = "char"; break;
542 case "System.Byte": s = "byte"; break;
543 case "System.SByte": s = "sbyte"; break;
544 default: s = null; break;
549 // Predefined names can come from mscorlib only
551 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
557 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
558 return AnonymousTypeClass.SignatureForError;
560 int idx = name.IndexOfAny (elements, 10);
562 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
565 return name.Replace ('+', '.');
568 static public string CSharpName (Type[] types)
570 if (types.Length == 0)
573 StringBuilder sb = new StringBuilder ();
574 for (int i = 0; i < types.Length; ++i) {
578 sb.Append (CSharpName (types [i]));
580 return sb.ToString ();
584 /// Returns the signature of the method with full namespace classification
586 static public string GetFullNameSignature (MemberInfo mi)
588 PropertyInfo pi = mi as PropertyInfo;
590 MethodBase pmi = pi.GetGetMethod (true);
592 pmi = pi.GetSetMethod (true);
593 if (GetParameterData (pmi).Count > 0)
596 return (mi is MethodBase)
597 ? CSharpSignature (mi as MethodBase)
598 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
602 private static int GetFullName (Type t, StringBuilder sb)
606 if (!t.IsGenericType) {
607 sb.Append (t.FullName);
611 if (t.DeclaringType != null) {
612 pos = GetFullName (t.DeclaringType, sb);
614 } else if (t.Namespace != null && t.Namespace.Length != 0) {
615 sb.Append (t.Namespace);
618 sb.Append (RemoveGenericArity (t.Name));
620 Type[] this_args = GetTypeArguments (t);
622 if (this_args.Length < pos)
623 throw new InternalErrorException (
624 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
625 if (this_args.Length == pos)
630 sb.Append (CSharpName (this_args [pos++]));
631 if (pos == this_args.Length)
639 static string GetFullName (Type t)
642 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
643 return GetFullName (GetElementType (t)) + dimension;
646 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
647 t = GetTypeArguments (t)[0];
648 return CSharpName (t) + "?";
651 if (t.IsGenericParameter)
653 if (!t.IsGenericType)
656 StringBuilder sb = new StringBuilder ();
657 int pos = GetFullName (t, sb);
659 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
660 return sb.ToString ();
663 public static string GetFullName (Type t)
669 public static string RemoveGenericArity (string from)
671 int i = from.IndexOf ('`');
673 return from.Substring (0, i);
678 /// When we need to report accessors as well
680 static public string CSharpSignature (MethodBase mb)
682 return CSharpSignature (mb, false);
686 /// Returns the signature of the method
688 static public string CSharpSignature (MethodBase mb, bool show_accessor)
690 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
693 AParametersCollection iparams = GetParameterData (mb);
694 string parameters = iparams.GetSignatureForError ();
695 int accessor_end = 0;
697 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
698 string op_name = Operator.GetName (mb.Name);
699 if (op_name != null) {
700 if (op_name == "explicit" || op_name == "implicit") {
701 sig.Append (op_name);
702 sig.Append (" operator ");
703 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
705 sig.Append ("operator ");
706 sig.Append (op_name);
708 sig.Append (parameters);
709 return sig.ToString ();
712 bool is_getter = mb.Name.StartsWith ("get_");
713 bool is_setter = mb.Name.StartsWith ("set_");
714 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
716 } else if (mb.Name.StartsWith ("remove_")) {
721 if (iparams.Count > (is_getter ? 0 : 1)) {
722 sig.Append ("this[");
724 sig.Append (parameters.Substring (1, parameters.Length - 2));
726 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
729 sig.Append (mb.Name.Substring (accessor_end + 1));
732 if (mb.Name == ".ctor")
733 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
735 sig.Append (mb.Name);
737 if (IsGenericMethod (mb)) {
738 Type[] args = GetGenericArguments (mb);
740 for (int i = 0; i < args.Length; i++) {
743 sig.Append (CSharpName (args [i]));
749 sig.Append (parameters);
752 if (show_accessor && accessor_end > 0) {
754 sig.Append (mb.Name.Substring (0, accessor_end));
757 return sig.ToString ();
760 public static string GetMethodName (MethodInfo m)
762 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
765 return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
768 static public string CSharpSignature (EventInfo ei)
770 return CSharpName (ei.DeclaringType) + "." + ei.Name;
774 // Looks up a type, and aborts if it is not found. This is used
775 // by predefined types required by the compiler
777 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
779 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
780 Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
784 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
791 if (RootContext.StdLib || t == null || !required)
794 // TODO: All predefined imported types have to have correct signature
795 if (t.Module != RootContext.ToplevelTypes.Builder)
798 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
799 if (ds is Delegate) {
800 if (type_kind == Kind.Delegate)
803 TypeContainer tc = (TypeContainer)ds;
804 if (tc.Kind == type_kind)
808 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
813 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
815 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
817 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
818 if (members != null) {
819 for (int i = 0; i < members.Length; ++i) {
820 MemberInfo member = members [i];
821 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
822 MethodBase mb = member as MethodBase;
826 AParametersCollection pd = TypeManager.GetParameterData (mb);
827 if (IsEqual (pd.Types, args))
830 if (mt == MemberTypes.Field) {
831 FieldInfo fi = member as FieldInfo;
835 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
841 if (mt == MemberTypes.Property) {
842 PropertyInfo pi = member as PropertyInfo;
846 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
854 string method_args = null;
855 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
856 method_args = "(" + TypeManager.CSharpName (args) + ")";
858 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
859 TypeManager.CSharpName (t), name, method_args);
865 // Returns the ConstructorInfo for "args"
867 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
869 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
873 // Returns the MethodInfo for a method named `name' defined
874 // in type `t' which takes arguments of types `args'
876 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
878 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
881 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
883 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
886 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
888 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
892 /// The types have to be initialized after the initial
893 /// population of the type has happened (for example, to
894 /// bootstrap the corlib.dll
896 public static bool InitCoreTypes ()
898 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
899 system_object_expr.Type = object_type;
900 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
901 system_valuetype_expr.Type = value_type;
902 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
904 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
905 system_int32_expr.Type = int32_type;
906 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
907 system_int64_expr.Type = int64_type;
908 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
909 system_uint32_expr.Type = uint32_type;
910 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
911 system_uint64_expr.Type = uint64_type;
912 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
913 system_byte_expr.Type = byte_type;
914 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
915 system_sbyte_expr.Type = sbyte_type;
916 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
917 system_int16_expr.Type = short_type;
918 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
919 system_uint16_expr.Type = ushort_type;
921 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
922 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
923 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
925 // HACK: DefineType immediately resolves iterators (very wrong)
926 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
928 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
929 system_char_expr.Type = char_type;
930 string_type = CoreLookupType ("System", "String", Kind.Class, true);
931 system_string_expr.Type = string_type;
932 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
933 system_single_expr.Type = float_type;
934 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
935 system_double_expr.Type = double_type;
936 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
937 system_decimal_expr.Type = decimal_type;
938 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
939 system_boolean_expr.Type = bool_type;
940 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
941 system_intptr_expr.Type = intptr_type;
942 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
944 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
945 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
947 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
948 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
949 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
950 system_void_expr.Type = void_type;
951 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
952 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
954 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
955 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
957 PredefinedAttributes.Get.ParamArray.Resolve (false);
958 PredefinedAttributes.Get.Out.Resolve (false);
960 return Report.Errors == 0;
964 // Initializes optional core types
966 public static void InitOptionalCoreTypes ()
969 // These are only used for compare purposes
971 anonymous_method_type = typeof (AnonymousMethodBody);
972 null_type = typeof (NullLiteral);
974 void_ptr_type = GetPointerType (void_type);
977 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
978 // types cache with incorrect accessiblity when any of optional types is internal.
980 PredefinedAttributes.Get.Initialize ();
982 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
983 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
984 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
985 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
986 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
987 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
990 // Optional attributes, used for error reporting only
992 //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
993 // Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
998 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
999 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1000 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1001 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1004 // Optional types which are used as types and for member lookup
1006 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1009 // Note: extension_attribute_type is already loaded
1010 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1012 if (!RootContext.StdLib) {
1014 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1015 // has different predefined types and this method sets mscorlib types
1016 // to be same to avoid any type check errors.
1019 Type type = typeof (Type);
1020 Type [] system_4_type_arg = { type, type, type, type };
1022 MethodInfo set_corlib_type_builders =
1023 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1024 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1025 system_4_type_arg, null);
1027 if (set_corlib_type_builders != null) {
1028 object[] args = new object [4];
1029 args [0] = object_type;
1030 args [1] = value_type;
1031 args [2] = enum_type;
1032 args [3] = void_type;
1034 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1036 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1037 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1038 TypeManager.CSharpName (system_4_type_arg));
1043 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1046 /// This is the "old", non-cache based FindMembers() function. We cannot use
1047 /// the cache here because there is no member name argument.
1049 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1050 MemberFilter filter, object criteria)
1052 #if MS_COMPATIBLE && GMCS_SOURCE
1053 if (t.IsGenericType)
1054 t = t.GetGenericTypeDefinition ();
1057 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1060 // `builder_to_declspace' contains all dynamic types.
1064 Timer.StartTimer (TimerType.FindMembers);
1065 list = decl.FindMembers (mt, bf, filter, criteria);
1066 Timer.StopTimer (TimerType.FindMembers);
1071 // We have to take care of arrays specially, because GetType on
1072 // a TypeBuilder array will return a Type, not a TypeBuilder,
1073 // and we can not call FindMembers on this type.
1076 #if MS_COMPATIBLE && GMCS_SOURCE
1079 t.IsSubclassOf (TypeManager.array_type))
1080 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1083 if (t is GenericTypeParameterBuilder) {
1084 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1086 Timer.StartTimer (TimerType.FindMembers);
1087 MemberList list = tparam.FindMembers (
1088 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1089 Timer.StopTimer (TimerType.FindMembers);
1095 // Since FindMembers will not lookup both static and instance
1096 // members, we emulate this behaviour here.
1098 if ((bf & instance_and_static) == instance_and_static){
1099 MemberInfo [] i_members = t.FindMembers (
1100 mt, bf & ~BindingFlags.Static, filter, criteria);
1102 int i_len = i_members.Length;
1104 MemberInfo one = i_members [0];
1107 // If any of these are present, we are done!
1109 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1110 return new MemberList (i_members);
1113 MemberInfo [] s_members = t.FindMembers (
1114 mt, bf & ~BindingFlags.Instance, filter, criteria);
1116 int s_len = s_members.Length;
1117 if (i_len > 0 || s_len > 0)
1118 return new MemberList (i_members, s_members);
1121 return new MemberList (i_members);
1123 return new MemberList (s_members);
1127 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1132 /// This method is only called from within MemberLookup. It tries to use the member
1133 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1134 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1135 /// our return value will already contain all inherited members and the caller don't need
1136 /// to check base classes and interfaces anymore.
1138 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1139 string name, out bool used_cache)
1144 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1145 // and we can ask the DeclSpace for the MemberCache.
1148 if (t.Assembly == CodeGen.Assembly.Builder) {
1149 if (t.IsGenericParameter) {
1150 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1153 if (tparam.MemberCache == null)
1154 return new MemberInfo[0];
1156 return tparam.MemberCache.FindMembers (
1157 mt, bf, name, FilterWithClosure_delegate, null);
1161 // We have to take care of arrays specially, because GetType on
1162 // a TypeBuilder array will return a Type, not a TypeBuilder,
1163 // and we can not call FindMembers on this type.
1167 return TypeHandle.ArrayType.MemberCache.FindMembers (
1168 mt, bf, name, FilterWithClosure_delegate, null);
1171 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1172 t = t.GetGenericTypeDefinition ();
1174 if (t is TypeBuilder) {
1176 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1177 cache = decl.MemberCache;
1180 // If this DeclSpace has a MemberCache, use it.
1183 if (cache != null) {
1185 return cache.FindMembers (
1186 mt, bf, name, FilterWithClosure_delegate, null);
1189 // If there is no MemberCache, we need to use the "normal" FindMembers.
1190 // Note, this is a VERY uncommon route!
1193 Timer.StartTimer (TimerType.FindMembers);
1194 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1195 FilterWithClosure_delegate, name);
1196 Timer.StopTimer (TimerType.FindMembers);
1198 return (MemberInfo []) list;
1202 // We have to take care of arrays specially, because GetType on
1203 // a TypeBuilder array will return a Type, not a TypeBuilder,
1204 // and we can not call FindMembers on this type.
1208 return TypeHandle.ArrayType.MemberCache.FindMembers (
1209 mt, bf, name, FilterWithClosure_delegate, null);
1213 if (t is GenericTypeParameterBuilder) {
1214 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1217 if (tparam.MemberCache == null)
1218 return new MemberInfo [0];
1220 return tparam.MemberCache.FindMembers (
1221 mt, bf, name, FilterWithClosure_delegate, null);
1225 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1227 // This happens if we're resolving a class'es base class and interfaces
1228 // in TypeContainer.DefineType(). At this time, the types aren't
1229 // populated yet, so we can't use the cache.
1231 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1232 FilterWithClosure_delegate, name);
1238 // This call will always succeed. There is exactly one TypeHandle instance per
1239 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1240 // the corresponding MemberCache.
1242 cache = TypeHandle.GetMemberCache (t);
1245 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1248 public static bool IsBuiltinType (Type t)
1250 t = TypeToCoreType (t);
1251 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1252 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1253 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1254 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1261 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1262 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1264 public static bool IsPrimitiveType (Type t)
1266 return (t == int32_type || t == uint32_type ||
1267 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1268 t == char_type || t == short_type || t == bool_type ||
1269 t == sbyte_type || t == byte_type || t == ushort_type);
1272 public static bool IsDelegateType (Type t)
1274 if (TypeManager.IsGenericParameter (t))
1277 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1280 t = DropGenericTypeArguments (t);
1281 return IsSubclassOf (t, TypeManager.delegate_type);
1284 public static bool IsEnumType (Type t)
1286 t = DropGenericTypeArguments (t);
1287 return t.BaseType == TypeManager.enum_type;
1290 public static bool IsBuiltinOrEnum (Type t)
1292 if (IsBuiltinType (t))
1301 public static bool IsAttributeType (Type t)
1303 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1307 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1309 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1310 public static bool IsUnmanagedType (Type t)
1312 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1314 return ds.IsUnmanagedType ();
1316 // builtins that are not unmanaged types
1317 if (t == TypeManager.object_type || t == TypeManager.string_type)
1320 if (IsGenericType (t) || IsGenericParameter (t))
1323 if (IsBuiltinOrEnum (t))
1326 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1328 return IsUnmanagedType (GetElementType (t));
1330 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1334 if (!IsValueType (t))
1337 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1338 if (IsGenericTypeDefinition (p))
1344 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1346 foreach (FieldInfo f in fields){
1347 if (!IsUnmanagedType (f.FieldType)){
1357 // Null is considered to be a reference type
1359 public static bool IsReferenceType (Type t)
1361 if (TypeManager.IsGenericParameter (t)) {
1362 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1363 if (constraints == null)
1366 return constraints.IsReferenceType;
1369 return !IsStruct (t) && !IsEnumType (t);
1372 public static bool IsValueType (Type t)
1374 if (TypeManager.IsGenericParameter (t)) {
1375 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1376 if (constraints == null)
1379 return constraints.IsValueType;
1382 return IsStruct (t) || IsEnumType (t);
1385 public static bool IsStruct (Type t)
1387 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1390 public static bool IsInterfaceType (Type t)
1392 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1396 return tc.Kind == Kind.Interface;
1399 public static bool IsSubclassOf (Type type, Type base_type)
1401 TypeParameter tparam = LookupTypeParameter (type);
1402 TypeParameter pparam = LookupTypeParameter (base_type);
1404 if ((tparam != null) && (pparam != null)) {
1405 if (tparam == pparam)
1408 return tparam.IsSubclassOf (base_type);
1411 #if MS_COMPATIBLE && GMCS_SOURCE
1412 if (type.IsGenericType)
1413 type = type.GetGenericTypeDefinition ();
1416 if (type.IsSubclassOf (base_type))
1420 if (IsEqual (type, base_type))
1423 type = type.BaseType;
1424 } while (type != null);
1429 public static bool IsPrivateAccessible (Type type, Type parent)
1434 if (type.Equals (parent))
1437 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1440 public static bool IsFamilyAccessible (Type type, Type parent)
1442 TypeParameter tparam = LookupTypeParameter (type);
1443 TypeParameter pparam = LookupTypeParameter (parent);
1445 if ((tparam != null) && (pparam != null)) {
1446 if (tparam == pparam)
1449 return tparam.IsSubclassOf (parent);
1453 if (IsInstantiationOfSameGenericType (type, parent))
1456 type = type.BaseType;
1457 } while (type != null);
1463 // Checks whether `type' is a subclass or nested child of `base_type'.
1465 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1468 if (IsFamilyAccessible (type, base_type))
1471 // Handle nested types.
1472 type = type.DeclaringType;
1473 } while (type != null);
1479 // Checks whether `type' is a nested child of `parent'.
1481 public static bool IsNestedChildOf (Type type, Type parent)
1486 type = DropGenericTypeArguments (type);
1487 parent = DropGenericTypeArguments (parent);
1489 if (IsEqual (type, parent))
1492 type = type.DeclaringType;
1493 while (type != null) {
1494 if (IsEqual (type, parent))
1497 type = type.DeclaringType;
1503 public static bool IsSpecialType (Type t)
1505 return t == arg_iterator_type || t == typed_reference_type;
1509 // Checks whether `extern_type' is friend of the output assembly
1511 public static bool IsThisOrFriendAssembly (Assembly assembly)
1513 if (assembly == CodeGen.Assembly.Builder)
1516 if (assembly_internals_vis_attrs.Contains (assembly))
1517 return (bool)(assembly_internals_vis_attrs [assembly]);
1519 PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
1520 // HACK: Do very early resolve of SRE type checking
1521 if (pa.Type == null)
1527 object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
1528 if (attrs.Length == 0) {
1529 assembly_internals_vis_attrs.Add (assembly, false);
1533 bool is_friend = false;
1535 AssemblyName this_name = CodeGen.Assembly.Name;
1536 byte [] this_token = this_name.GetPublicKeyToken ();
1537 foreach (InternalsVisibleToAttribute attr in attrs) {
1538 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1541 AssemblyName aname = null;
1544 aname = new AssemblyName (attr.AssemblyName);
1546 throw new NotSupportedException ();
1548 } catch (FileLoadException) {
1549 } catch (ArgumentException) {
1552 if (aname == null || aname.Name != this_name.Name)
1555 byte [] key_token = aname.GetPublicKeyToken ();
1556 if (key_token != null) {
1557 if (this_token.Length == 0) {
1558 // Same name, but assembly is not strongnamed
1559 Error_FriendAccessNameNotMatching (aname.FullName);
1563 if (!CompareKeyTokens (this_token, key_token))
1571 assembly_internals_vis_attrs.Add (assembly, is_friend);
1575 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1577 for (int i = 0; i < token1.Length; i++)
1578 if (token1 [i] != token2 [i])
1584 static void Error_FriendAccessNameNotMatching (string other_name)
1587 "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",
1588 other_name, CodeGen.Assembly.Name.FullName);
1592 // Do the right thing when returning the element type of an
1593 // array type based on whether we are compiling corlib or not
1595 public static Type GetElementType (Type t)
1597 if (RootContext.StdLib)
1598 return t.GetElementType ();
1600 return TypeToCoreType (t.GetElementType ());
1604 /// This method is not implemented by MS runtime for dynamic types
1606 public static bool HasElementType (Type t)
1608 return t.IsArray || t.IsPointer || t.IsByRef;
1611 public static Type GetEnumUnderlyingType (Type t)
1613 t = DropGenericTypeArguments (t);
1614 Enum e = LookupTypeContainer (t) as Enum;
1616 return e.UnderlyingType;
1619 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1621 return TypeManager.int32_type;
1623 return TypeToCoreType (fi.FieldType);
1627 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1631 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1632 /// for anything which is dynamic, and we need this in a number of places,
1633 /// we register this information here, and use it afterwards.
1635 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1637 method_params.Add (mb, ip);
1640 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1642 method_params.Add (pb, p);
1645 static public AParametersCollection GetParameterData (MethodBase mb)
1647 AParametersCollection pd = (AParametersCollection) method_params [mb];
1650 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1651 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1652 pd = GetParameterData (mi);
1654 if (mi.IsGenericMethod)
1655 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1657 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1659 method_params.Add (mb, pd);
1663 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1664 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1665 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1668 pd = ParametersImported.Create (mb);
1670 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1671 if (generic != mb) {
1672 pd = TypeManager.GetParameterData (generic);
1673 pd = ParametersImported.Create (pd, mb);
1675 pd = ParametersImported.Create (mb);
1678 method_params.Add (mb, pd);
1683 public static AParametersCollection GetParameterData (PropertyInfo pi)
1685 AParametersCollection pd = (AParametersCollection)method_params [pi];
1687 if (pi is PropertyBuilder)
1688 return ParametersCompiled.EmptyReadOnlyParameters;
1690 ParameterInfo [] p = pi.GetIndexParameters ();
1692 return ParametersCompiled.EmptyReadOnlyParameters;
1694 pd = ParametersImported.Create (p, null);
1695 method_params.Add (pi, pd);
1701 public static AParametersCollection GetDelegateParameters (Type t)
1703 Delegate d = builder_to_declspace [t] as Delegate;
1705 return d.Parameters;
1707 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1708 return GetParameterData (invoke_mb);
1711 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1713 if (!method_overrides.Contains (override_method))
1714 method_overrides [override_method] = base_method;
1715 if (method_overrides [override_method] != base_method)
1716 throw new InternalErrorException ("Override mismatch: " + override_method);
1719 static public bool IsOverride (MethodBase m)
1721 m = DropGenericMethodArguments (m);
1723 return m.IsVirtual &&
1724 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1725 (m is MethodBuilder || method_overrides.Contains (m));
1728 static public MethodBase TryGetBaseDefinition (MethodBase m)
1730 m = DropGenericMethodArguments (m);
1732 return (MethodBase) method_overrides [m];
1735 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1737 fields.Add (fb, ic);
1740 public static IConstant GetConstant (FieldInfo fb)
1745 return (IConstant)fields [fb];
1748 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1750 propertybuilder_to_property.Add (pi, pb);
1753 public static PropertyBase GetProperty (PropertyInfo pi)
1755 return (PropertyBase)propertybuilder_to_property [pi];
1758 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1760 fieldbuilders_to_fields.Add (fb, f);
1764 // The return value can be null; This will be the case for
1765 // auxiliary FieldBuilders created by the compiler that have no
1766 // real field being declared on the source code
1768 static public FieldBase GetField (FieldInfo fb)
1771 fb = GetGenericFieldDefinition (fb);
1773 return (FieldBase) fieldbuilders_to_fields [fb];
1776 static public MethodInfo GetAddMethod (EventInfo ei)
1778 if (ei is MyEventBuilder) {
1779 return ((MyEventBuilder)ei).GetAddMethod (true);
1781 return ei.GetAddMethod (true);
1784 static public MethodInfo GetRemoveMethod (EventInfo ei)
1786 if (ei is MyEventBuilder) {
1787 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1789 return ei.GetRemoveMethod (true);
1792 static public void RegisterEventField (EventInfo einfo, EventField e)
1795 events = new Hashtable ();
1797 events.Add (einfo, e);
1800 static public EventField GetEventField (EventInfo ei)
1805 return (EventField) events [ei];
1808 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1810 Hashtable hash = new Hashtable ();
1811 return CheckStructCycles (tc, seen, hash);
1814 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1817 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1821 // `seen' contains all types we've already visited.
1823 if (seen.Contains (tc))
1825 seen.Add (tc, null);
1827 if (tc.Fields == null)
1830 foreach (FieldBase field in tc.Fields) {
1831 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1834 Type ftype = field.FieldBuilder.FieldType;
1835 TypeContainer ftc = LookupTypeContainer (ftype);
1839 if (hash.Contains (ftc)) {
1840 Report.Error (523, tc.Location,
1841 "Struct member `{0}.{1}' of type `{2}' " +
1842 "causes a cycle in the struct layout",
1843 tc.Name, field.Name, ftc.Name);
1848 // `hash' contains all types in the current path.
1850 hash.Add (tc, null);
1852 bool ok = CheckStructCycles (ftc, seen, hash);
1859 if (!seen.Contains (ftc))
1860 seen.Add (ftc, null);
1867 /// Given an array of interface types, expand and eliminate repeated ocurrences
1868 /// of an interface.
1872 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1875 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1877 ArrayList new_ifaces = new ArrayList ();
1879 foreach (TypeExpr iface in base_interfaces){
1880 Type itype = iface.Type;
1882 if (new_ifaces.Contains (itype))
1885 new_ifaces.Add (itype);
1887 Type [] implementing = GetInterfaces (itype);
1889 foreach (Type imp in implementing){
1890 if (!new_ifaces.Contains (imp))
1891 new_ifaces.Add (imp);
1894 Type [] ret = new Type [new_ifaces.Count];
1895 new_ifaces.CopyTo (ret, 0);
1899 public static Type[] ExpandInterfaces (Type [] base_interfaces)
1901 ArrayList new_ifaces = new ArrayList ();
1903 foreach (Type itype in base_interfaces){
1904 if (new_ifaces.Contains (itype))
1907 new_ifaces.Add (itype);
1909 Type [] implementing = GetInterfaces (itype);
1911 foreach (Type imp in implementing){
1912 if (!new_ifaces.Contains (imp))
1913 new_ifaces.Add (imp);
1916 Type [] ret = new Type [new_ifaces.Count];
1917 new_ifaces.CopyTo (ret, 0);
1921 static PtrHashtable iface_cache;
1924 /// This function returns the interfaces in the type `t'. Works with
1925 /// both types and TypeBuilders.
1927 public static Type [] GetInterfaces (Type t)
1929 Type [] cached = iface_cache [t] as Type [];
1934 // The reason for catching the Array case is that Reflection.Emit
1935 // will not return a TypeBuilder for Array types of TypeBuilder types,
1936 // but will still throw an exception if we try to call GetInterfaces
1939 // Since the array interfaces are always constant, we return those for
1944 t = TypeManager.array_type;
1946 if ((t is TypeBuilder) || IsGenericType (t)) {
1947 Type [] base_ifaces;
1949 if (t.BaseType == null)
1950 base_ifaces = Type.EmptyTypes;
1952 base_ifaces = GetInterfaces (t.BaseType);
1954 if (IsGenericType (t))
1955 #if MS_COMPATIBLE && GMCS_SOURCE
1956 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
1958 type_ifaces = t.GetInterfaces ();
1961 type_ifaces = (Type []) builder_to_ifaces [t];
1962 if (type_ifaces == null || type_ifaces.Length == 0)
1963 type_ifaces = Type.EmptyTypes;
1965 int base_count = base_ifaces.Length;
1966 Type [] result = new Type [base_count + type_ifaces.Length];
1967 base_ifaces.CopyTo (result, 0);
1968 type_ifaces.CopyTo (result, base_count);
1970 iface_cache [t] = result;
1972 } else if (t is GenericTypeParameterBuilder){
1973 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
1974 if (type_ifaces == null || type_ifaces.Length == 0)
1975 type_ifaces = Type.EmptyTypes;
1977 iface_cache [t] = type_ifaces;
1980 Type[] ifaces = t.GetInterfaces ();
1981 iface_cache [t] = ifaces;
1987 // gets the interfaces that are declared explicitly on t
1989 public static Type [] GetExplicitInterfaces (TypeBuilder t)
1991 return (Type []) builder_to_ifaces [t];
1995 /// The following is used to check if a given type implements an interface.
1996 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1998 public static bool ImplementsInterface (Type t, Type iface)
2003 // FIXME OPTIMIZATION:
2004 // as soon as we hit a non-TypeBuiler in the interface
2005 // chain, we could return, as the `Type.GetInterfaces'
2006 // will return all the interfaces implement by the type
2010 interfaces = GetInterfaces (t);
2012 if (interfaces != null){
2013 foreach (Type i in interfaces){
2014 if (i == iface || IsVariantOf (i, iface))
2020 } while (t != null);
2025 public static bool IsVariantOf (Type type1, Type type2)
2028 if (type1.IsGenericType && type2.IsGenericType) {
2029 Type generic_target_type = type2.GetGenericTypeDefinition ();
2030 if (type1.GetGenericTypeDefinition () == generic_target_type) {
2031 Type [] t1 = type1.GetGenericArguments ();
2032 Type [] t2 = type2.GetGenericArguments ();
2034 foreach (Type t in generic_target_type.GetGenericArguments ()) {
2035 if ((t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0) {
2036 // FIXME this is not right
2037 if (IsValueType (t1[i]) || IsValueType (t2[i])) {
2040 if ((t.GenericParameterAttributes & GenericParameterAttributes.Covariant) != 0 && !t2[i].IsAssignableFrom (t1[i])) {
2043 if ((t.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0 && !t1[i].IsAssignableFrom (t2[i])) {
2046 } else if (t1[i] != t2[i]) {
2058 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2060 // This is a custom version of Convert.ChangeType() which works
2061 // with the TypeBuilder defined types when compiling corlib.
2062 public static object ChangeType (object value, Type conversionType, out bool error)
2064 IConvertible convert_value = value as IConvertible;
2066 if (convert_value == null){
2073 // We must use Type.Equals() here since `conversionType' is
2074 // the TypeBuilder created version of a system type and not
2075 // the system type itself. You cannot use Type.GetTypeCode()
2076 // on such a type - it'd always return TypeCode.Object.
2079 // We cannot rely on build-in type conversions as they are
2080 // more limited than what C# supports.
2081 // See char -> float/decimal/double conversion
2086 if (conversionType.Equals (typeof (Boolean)))
2087 return (object)(convert_value.ToBoolean (nf_provider));
2088 if (conversionType.Equals (typeof (Byte)))
2089 return (object)(convert_value.ToByte (nf_provider));
2090 if (conversionType.Equals (typeof (Char)))
2091 return (object)(convert_value.ToChar (nf_provider));
2092 if (conversionType.Equals (typeof (DateTime)))
2093 return (object)(convert_value.ToDateTime (nf_provider));
2095 if (conversionType.Equals (decimal_type)) {
2096 if (convert_value.GetType () == TypeManager.char_type)
2097 return (decimal)convert_value.ToInt32 (nf_provider);
2098 return convert_value.ToDecimal (nf_provider);
2101 if (conversionType.Equals (typeof (Double))) {
2102 if (convert_value.GetType () == TypeManager.char_type)
2103 return (double)convert_value.ToInt32 (nf_provider);
2104 return convert_value.ToDouble (nf_provider);
2107 if (conversionType.Equals (typeof (Int16)))
2108 return (object)(convert_value.ToInt16 (nf_provider));
2109 if (conversionType.Equals (int32_type))
2110 return (object)(convert_value.ToInt32 (nf_provider));
2111 if (conversionType.Equals (int64_type))
2112 return (object)(convert_value.ToInt64 (nf_provider));
2113 if (conversionType.Equals (typeof (SByte)))
2114 return (object)(convert_value.ToSByte (nf_provider));
2116 if (conversionType.Equals (typeof (Single))) {
2117 if (convert_value.GetType () == TypeManager.char_type)
2118 return (float)convert_value.ToInt32 (nf_provider);
2119 return convert_value.ToSingle (nf_provider);
2122 if (conversionType.Equals (typeof (String)))
2123 return (object)(convert_value.ToString (nf_provider));
2124 if (conversionType.Equals (typeof (UInt16)))
2125 return (object)(convert_value.ToUInt16 (nf_provider));
2126 if (conversionType.Equals (typeof (UInt32)))
2127 return (object)(convert_value.ToUInt32 (nf_provider));
2128 if (conversionType.Equals (typeof (UInt64)))
2129 return (object)(convert_value.ToUInt64 (nf_provider));
2130 if (conversionType.Equals (typeof (Object)))
2131 return (object)(value);
2141 // When compiling with -nostdlib and the type is imported from an external assembly
2142 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2144 public static Type TypeToCoreType (Type t)
2146 if (RootContext.StdLib || t.Module != typeof (object).Module)
2149 TypeCode tc = Type.GetTypeCode (t);
2152 case TypeCode.Boolean:
2153 return TypeManager.bool_type;
2155 return TypeManager.byte_type;
2156 case TypeCode.SByte:
2157 return TypeManager.sbyte_type;
2159 return TypeManager.char_type;
2160 case TypeCode.Int16:
2161 return TypeManager.short_type;
2162 case TypeCode.UInt16:
2163 return TypeManager.ushort_type;
2164 case TypeCode.Int32:
2165 return TypeManager.int32_type;
2166 case TypeCode.UInt32:
2167 return TypeManager.uint32_type;
2168 case TypeCode.Int64:
2169 return TypeManager.int64_type;
2170 case TypeCode.UInt64:
2171 return TypeManager.uint64_type;
2172 case TypeCode.Single:
2173 return TypeManager.float_type;
2174 case TypeCode.Double:
2175 return TypeManager.double_type;
2176 case TypeCode.String:
2177 return TypeManager.string_type;
2178 case TypeCode.Decimal:
2179 return TypeManager.decimal_type;
2182 if (t == typeof (void))
2183 return TypeManager.void_type;
2184 if (t == typeof (object))
2185 return TypeManager.object_type;
2186 if (t == typeof (System.Type))
2187 return TypeManager.type_type;
2188 if (t == typeof (System.IntPtr))
2189 return TypeManager.intptr_type;
2190 if (t == typeof (System.UIntPtr))
2191 return TypeManager.uintptr_type;
2194 int dim = t.GetArrayRank ();
2195 t = GetElementType (t);
2196 return t.MakeArrayType (dim);
2199 t = GetElementType (t);
2200 return t.MakeByRefType ();
2203 t = GetElementType (t);
2204 return t.MakePointerType ();
2211 /// Utility function that can be used to probe whether a type
2212 /// is managed or not.
2214 public static bool VerifyUnManaged (Type t, Location loc)
2216 if (IsUnmanagedType (t))
2220 t = GetElementType (t);
2222 Report.SymbolRelatedToPreviousError (t);
2223 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2230 /// Returns the name of the indexer in a given type.
2233 /// The default is not always `Item'. The user can change this behaviour by
2234 /// using the IndexerNameAttribute in the container.
2235 /// For example, the String class indexer is named `Chars' not `Item'
2237 public static string IndexerPropertyName (Type t)
2239 t = DropGenericTypeArguments (t);
2240 if (t is TypeBuilder) {
2241 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2242 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2245 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
2247 System.Attribute attr = System.Attribute.GetCustomAttribute (
2250 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2251 return dma.MemberName;
2255 return TypeContainer.DefaultIndexerName;
2258 static MethodInfo declare_local_method = null;
2260 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2262 if (declare_local_method == null){
2263 declare_local_method = typeof (ILGenerator).GetMethod (
2265 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2267 new Type [] { typeof (Type), typeof (bool)},
2269 if (declare_local_method == null){
2270 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2271 return ig.DeclareLocal (t);
2274 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2277 private static bool IsSignatureEqual (Type a, Type b)
2280 /// Consider the following example (bug #77674):
2282 /// public abstract class A
2284 /// public abstract T Foo<T> ();
2287 /// public abstract class B : A
2289 /// public override U Foo<T> ()
2290 /// { return default (U); }
2293 /// Here, `T' and `U' are method type parameters from different methods
2294 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2296 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2297 /// we need to do a signature based comparision and consider them equal.
2303 if (a.IsGenericParameter && b.IsGenericParameter &&
2304 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2305 return a.GenericParameterPosition == b.GenericParameterPosition;
2309 if (a.IsArray && b.IsArray) {
2310 if (a.GetArrayRank () != b.GetArrayRank ())
2313 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2316 if (a.IsByRef && b.IsByRef)
2317 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2319 if (IsGenericType (a) && IsGenericType (b)) {
2320 if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
2323 Type[] aargs = GetTypeArguments (a);
2324 Type[] bargs = GetTypeArguments (b);
2326 if (aargs.Length != bargs.Length)
2329 for (int i = 0; i < aargs.Length; i++) {
2330 if (!IsSignatureEqual (aargs [i], bargs [i]))
2341 // Returns whether the array of memberinfos contains the given method
2343 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2345 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2347 foreach (MethodBase method in array) {
2348 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2351 if (method.Name != new_method.Name)
2354 if (method is MethodInfo && new_method is MethodInfo &&
2356 TypeToCoreType (((MethodInfo) method).ReturnType),
2357 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2360 Type [] old_args = TypeManager.GetParameterData (method).Types;
2361 int old_count = old_args.Length;
2364 if (new_args.Length != old_count)
2367 for (i = 0; i < old_count; i++){
2368 if (!IsSignatureEqual (old_args [i], new_args [i]))
2381 // We copy methods from `new_members' into `target_list' if the signature
2382 // for the method from in the new list does not exist in the target_list
2384 // The name is assumed to be the same.
2386 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2388 if (target_list == null){
2389 target_list = new ArrayList ();
2391 foreach (MemberInfo mi in new_members){
2392 if (mi is MethodBase)
2393 target_list.Add (mi);
2398 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2399 target_list.CopyTo (target_array, 0);
2401 foreach (MemberInfo mi in new_members){
2402 MethodBase new_method = (MethodBase) mi;
2404 if (!ArrayContainsMethod (target_array, new_method, true))
2405 target_list.Add (new_method);
2412 // Tracks the generic parameters.
2414 static PtrHashtable builder_to_type_param;
2416 public static void AddTypeParameter (Type t, TypeParameter tparam)
2418 if (!builder_to_type_param.Contains (t))
2419 builder_to_type_param.Add (t, tparam);
2422 public static TypeParameter LookupTypeParameter (Type t)
2424 return (TypeParameter) builder_to_type_param [t];
2427 // This method always return false for non-generic compiler,
2428 // while Type.IsGenericParameter is returned if it is supported.
2429 public static bool IsGenericParameter (Type type)
2432 return type.IsGenericParameter;
2438 public static int GenericParameterPosition (Type type)
2441 return type.GenericParameterPosition;
2443 throw new InternalErrorException ("should not be called");
2447 public static bool IsGenericType (Type type)
2450 return type.IsGenericType;
2456 public static bool IsGenericTypeDefinition (Type type)
2459 return type.IsGenericTypeDefinition;
2465 public static bool ContainsGenericParameters (Type type)
2468 return type.ContainsGenericParameters;
2474 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2477 if (fi.DeclaringType.IsGenericTypeDefinition ||
2478 !fi.DeclaringType.IsGenericType)
2481 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2482 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2483 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2485 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2486 foreach (FieldInfo f in t.GetFields (bf))
2487 if (f.MetadataToken == fi.MetadataToken)
2494 public static bool IsEqual (Type a, Type b)
2497 // MS BCL returns true even if enum types are different
2498 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2499 return a.FullName == b.FullName;
2501 // Some types are never equal
2502 if (a == TypeManager.null_type || a == TypeManager.anonymous_method_type)
2508 if (IsGenericParameter (a) && IsGenericParameter (b)) {
2509 // TODO: needs more testing before cleaning up
2510 //if (a.DeclaringMethod != b.DeclaringMethod &&
2511 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2514 return a.GenericParameterPosition == b.GenericParameterPosition;
2516 throw new NotSupportedException ();
2520 if (a.IsArray && b.IsArray) {
2521 if (a.GetArrayRank () != b.GetArrayRank ())
2523 return IsEqual (GetElementType (a), GetElementType (b));
2526 if (a.IsByRef && b.IsByRef)
2527 return IsEqual (a.GetElementType (), b.GetElementType ());
2529 if (IsGenericType (a) && IsGenericType (b)) {
2530 Type adef = DropGenericTypeArguments (a);
2531 Type bdef = DropGenericTypeArguments (b);
2536 if (adef.IsEnum && bdef.IsEnum)
2539 Type[] aargs = GetTypeArguments (a);
2540 Type[] bargs = GetTypeArguments (b);
2542 if (aargs.Length != bargs.Length)
2545 for (int i = 0; i < aargs.Length; i++) {
2546 if (!IsEqual (aargs [i], bargs [i]))
2556 public static bool IsEqual (Type[] a, Type[] b)
2558 if (a == null || b == null || a.Length != b.Length)
2561 for (int i = 0; i < a.Length; ++i) {
2562 if (a [i] == null || b [i] == null) {
2569 if (!IsEqual (a [i], b [i]))
2576 public static Type DropGenericTypeArguments (Type t)
2579 if (!t.IsGenericType)
2581 // Micro-optimization: a generic typebuilder is always a generic type definition
2582 if (t is TypeBuilder)
2584 return t.GetGenericTypeDefinition ();
2590 public static MethodBase DropGenericMethodArguments (MethodBase m)
2593 if (m.IsGenericMethod)
2594 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2596 Type t = m.DeclaringType;
2597 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2600 t = t.GetGenericTypeDefinition ();
2601 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2602 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2605 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2609 if (m is ConstructorInfo) {
2610 foreach (ConstructorInfo c in t.GetConstructors (bf))
2611 if (c.MetadataToken == m.MetadataToken)
2614 foreach (MethodBase mb in t.GetMethods (bf))
2615 if (mb.MetadataToken == m.MetadataToken)
2623 public static Type[] GetGenericArguments (MethodBase mi)
2626 return mi.GetGenericArguments ();
2628 return Type.EmptyTypes;
2632 public static Type[] GetTypeArguments (Type t)
2635 DeclSpace tc = LookupDeclSpace (t);
2638 return Type.EmptyTypes;
2640 TypeParameter[] tparam = tc.TypeParameters;
2641 Type[] ret = new Type [tparam.Length];
2642 for (int i = 0; i < tparam.Length; i++) {
2643 ret [i] = tparam [i].Type;
2644 if (ret [i] == null)
2645 throw new InternalErrorException ();
2650 return t.GetGenericArguments ();
2652 throw new InternalErrorException ();
2656 public static GenericConstraints GetTypeParameterConstraints (Type t)
2659 if (!t.IsGenericParameter)
2660 throw new InvalidOperationException ();
2662 TypeParameter tparam = LookupTypeParameter (t);
2664 return tparam.GenericConstraints;
2666 return ReflectionConstraints.GetConstraints (t);
2668 throw new InternalErrorException ();
2672 public static bool HasGenericArguments (Type t)
2674 return GetNumberOfTypeArguments (t) > 0;
2677 public static int GetNumberOfTypeArguments (Type t)
2680 if (t.IsGenericParameter)
2682 DeclSpace tc = LookupDeclSpace (t);
2684 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2686 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2693 /// Check whether `type' and `parent' are both instantiations of the same
2694 /// generic type. Note that we do not check the type parameters here.
2696 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2698 int tcount = GetNumberOfTypeArguments (type);
2699 int pcount = GetNumberOfTypeArguments (parent);
2701 if (tcount != pcount)
2704 type = DropGenericTypeArguments (type);
2705 parent = DropGenericTypeArguments (parent);
2707 return type.Equals (parent);
2711 /// Whether `mb' is a generic method definition.
2713 public static bool IsGenericMethodDefinition (MethodBase mb)
2716 if (mb.DeclaringType is TypeBuilder) {
2717 IMethodData method = (IMethodData) builder_to_method [mb];
2721 return method.GenericMethod != null;
2724 return mb.IsGenericMethodDefinition;
2731 /// Whether `mb' is a generic method.
2733 public static bool IsGenericMethod (MethodBase mb)
2736 return mb.IsGenericMethod;
2742 public static bool IsNullableType (Type t)
2745 return generic_nullable_type == DropGenericTypeArguments (t);
2752 #region MemberLookup implementation
2755 // Whether we allow private members in the result (since FindMembers
2756 // uses NonPublic for both protected and private), we need to distinguish.
2759 internal class Closure {
2760 internal bool private_ok;
2762 // Who is invoking us and which type is being queried currently.
2763 internal Type invocation_type;
2764 internal Type qualifier_type;
2766 // The assembly that defines the type is that is calling us
2767 internal Assembly invocation_assembly;
2768 internal IList almost_match;
2770 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2772 if (invocation_type == null)
2775 if (is_static && qualifier_type == null)
2776 // It resolved from a simple name, so it should be visible.
2779 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2782 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2783 if (!IsFamilyAccessible (t, m.DeclaringType))
2786 // Although a derived class can access protected members of its base class
2787 // it cannot do so through an instance of the base class (CS1540).
2788 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2789 if (is_static || qualifier_type == null ||
2790 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2791 IsFamilyAccessible (qualifier_type, t))
2795 if (almost_match != null)
2796 almost_match.Add (m);
2802 // This filter filters by name + whether it is ok to include private
2803 // members in the search
2805 internal bool Filter (MemberInfo m, object filter_criteria)
2808 // Hack: we know that the filter criteria will always be in the
2809 // `closure' // fields.
2812 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2815 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2816 (invocation_type != null) &&
2817 IsPrivateAccessible (m.DeclaringType, invocation_type))
2821 // Ugly: we need to find out the type of `m', and depending
2822 // on this, tell whether we accept or not
2824 if (m is MethodBase){
2825 MethodBase mb = (MethodBase) m;
2826 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2828 if (ma == MethodAttributes.Public)
2831 if (ma == MethodAttributes.PrivateScope)
2834 if (ma == MethodAttributes.Private)
2835 return private_ok ||
2836 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2837 IsNestedChildOf (invocation_type, m.DeclaringType);
2839 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2840 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2843 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2847 // Family, FamORAssem or FamANDAssem
2848 return CheckValidFamilyAccess (mb.IsStatic, m);
2851 if (m is FieldInfo){
2852 FieldInfo fi = (FieldInfo) m;
2853 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2855 if (fa == FieldAttributes.Public)
2858 if (fa == FieldAttributes.PrivateScope)
2861 if (fa == FieldAttributes.Private)
2862 return private_ok ||
2863 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2864 IsNestedChildOf (invocation_type, m.DeclaringType);
2866 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2867 if ((fa == FieldAttributes.Assembly) ||
2868 (fa == FieldAttributes.FamORAssem))
2871 if ((fa == FieldAttributes.Assembly) ||
2872 (fa == FieldAttributes.FamANDAssem))
2876 // Family, FamORAssem or FamANDAssem
2877 return CheckValidFamilyAccess (fi.IsStatic, m);
2881 // EventInfos and PropertyInfos, return true because they lack
2882 // permission information, so we need to check later on the methods.
2888 static Closure closure;
2889 static MemberFilter FilterWithClosure_delegate;
2892 // Looks up a member called `name' in the `queried_type'. This lookup
2893 // is done by code that is contained in the definition for `invocation_type'
2894 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2896 // `invocation_type' is used to check whether we're allowed to access the requested
2897 // member wrt its protection level.
2899 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2900 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2901 // is B and qualifier_type is A). This is used to do the CS1540 check.
2903 // When resolving a SimpleName, `qualifier_type' is null.
2905 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2906 // the same than `queried_type' - except when we're being called from BaseAccess;
2907 // in this case, `invocation_type' is the current type and `queried_type' the base
2908 // type, so this'd normally trigger a CS1540.
2910 // The binding flags are `bf' and the kind of members being looked up are `mt'
2912 // The return value always includes private members which code in `invocation_type'
2913 // is allowed to access (using the specified `qualifier_type' if given); only use
2914 // BindingFlags.NonPublic to bypass the permission check.
2916 // The 'almost_match' argument is used for reporting error CS1540.
2918 // Returns an array of a single element for everything but Methods/Constructors
2919 // that might return multiple matches.
2921 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2922 Type queried_type, MemberTypes mt,
2923 BindingFlags original_bf, string name, IList almost_match)
2925 Timer.StartTimer (TimerType.MemberLookup);
2927 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2928 queried_type, mt, original_bf, name, almost_match);
2930 Timer.StopTimer (TimerType.MemberLookup);
2935 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2936 Type queried_type, MemberTypes mt,
2937 BindingFlags original_bf, string name, IList almost_match)
2939 BindingFlags bf = original_bf;
2941 ArrayList method_list = null;
2942 Type current_type = queried_type;
2943 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2944 bool skip_iface_check = true, used_cache = false;
2945 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2947 closure.invocation_type = invocation_type;
2948 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2949 closure.qualifier_type = qualifier_type;
2950 closure.almost_match = almost_match;
2952 // This is from the first time we find a method
2953 // in most cases, we do not actually find a method in the base class
2954 // so we can just ignore it, and save the arraylist allocation
2955 MemberInfo [] first_members_list = null;
2956 bool use_first_members_list = false;
2962 // `NonPublic' is lame, because it includes both protected and
2963 // private methods, so we need to control this behavior by
2964 // explicitly tracking if a private method is ok or not.
2966 // The possible cases are:
2967 // public, private and protected (internal does not come into the
2970 if ((invocation_type != null) &&
2971 ((invocation_type == current_type) ||
2972 IsNestedChildOf (invocation_type, current_type)) ||
2974 bf = original_bf | BindingFlags.NonPublic;
2978 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2980 Timer.StopTimer (TimerType.MemberLookup);
2982 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2984 Timer.StartTimer (TimerType.MemberLookup);
2987 // When queried for an interface type, the cache will automatically check all
2988 // inherited members, so we don't need to do this here. However, this only
2989 // works if we already used the cache in the first iteration of this loop.
2991 // If we used the cache in any further iteration, we can still terminate the
2992 // loop since the cache always looks in all base classes.
2998 skip_iface_check = false;
3000 if (current_type == TypeManager.object_type)
3003 current_type = current_type.BaseType;
3006 // This happens with interfaces, they have a null
3007 // basetype. Look members up in the Object class.
3009 if (current_type == null) {
3010 current_type = TypeManager.object_type;
3015 if (list.Length == 0)
3019 // Events and types are returned by both `static' and `instance'
3020 // searches, which means that our above FindMembers will
3021 // return two copies of the same.
3023 if (list.Length == 1 && !(list [0] is MethodBase)){
3028 // Multiple properties: we query those just to find out the indexer
3031 if (list [0] is PropertyInfo)
3035 // We found an event: the cache lookup returns both the event and
3036 // its private field.
3038 if (list [0] is EventInfo) {
3039 if ((list.Length == 2) && (list [1] is FieldInfo))
3040 return new MemberInfo [] { list [0] };
3046 // We found methods, turn the search into "method scan"
3050 if (first_members_list != null) {
3051 if (use_first_members_list) {
3052 method_list = CopyNewMethods (method_list, first_members_list);
3053 use_first_members_list = false;
3056 method_list = CopyNewMethods (method_list, list);
3058 first_members_list = list;
3059 use_first_members_list = true;
3060 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3062 } while (searching);
3064 if (use_first_members_list)
3065 return first_members_list;
3067 if (method_list != null && method_list.Count > 0) {
3068 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3071 // This happens if we already used the cache in the first iteration, in this case
3072 // the cache already looked in all interfaces.
3074 if (skip_iface_check)
3078 // Interfaces do not list members they inherit, so we have to
3081 if (!queried_type.IsInterface)
3084 if (queried_type.IsArray)
3085 queried_type = TypeManager.array_type;
3087 Type [] ifaces = GetInterfaces (queried_type);
3091 foreach (Type itype in ifaces){
3094 x = MemberLookup (null, null, itype, mt, bf, name, null);
3102 const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3103 BindingFlags.Static | BindingFlags.Instance |
3104 BindingFlags.DeclaredOnly;
3106 // Currently is designed to work with external types only
3107 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3109 if (!mb.IsSpecialName)
3112 string name = mb.Name;
3113 if (name.Length < 5)
3116 if (name [3] != '_')
3119 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3120 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3121 Type.FilterName, name.Substring (4));
3126 // This can happen when property is indexer (it can have same name but different parameters)
3127 foreach (PropertyInfo p in pi) {
3128 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3129 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3138 // Currently is designed to work with external types only
3139 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3141 if (!mb.IsSpecialName)
3144 string name = mb.Name;
3145 if (name.Length < 5)
3148 if (name.StartsWith ("add_"))
3149 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3151 if (name.StartsWith ("remove_"))
3152 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3157 // Tests whether external method is really special
3158 public static bool IsSpecialMethod (MethodBase mb)
3160 if (!mb.IsSpecialName)
3163 IMethodData md = TypeManager.GetMethod (mb);
3165 return (md is AbstractPropertyEventMethod || md is Operator);
3167 PropertyInfo pi = GetPropertyFromAccessor (mb);
3169 return IsValidProperty (pi);
3171 if (GetEventFromAccessor (mb) != null)
3174 string name = mb.Name;
3175 if (name.StartsWith ("op_"))
3176 return Operator.GetName (name) != null;
3181 // Tests whether imported property is valid C# property.
3182 // TODO: It seems to me that we should do a lot of sanity tests before
3183 // we accept property as C# property
3184 static bool IsValidProperty (PropertyInfo pi)
3186 MethodInfo get_method = pi.GetGetMethod (true);
3187 MethodInfo set_method = pi.GetSetMethod (true);
3190 if (get_method != null && set_method != null) {
3191 g_count = get_method.GetParameters ().Length;
3192 s_count = set_method.GetParameters ().Length;
3193 if (g_count + 1 != s_count)
3195 } else if (get_method != null) {
3196 g_count = get_method.GetParameters ().Length;
3197 } else if (set_method != null) {
3198 s_count = set_method.GetParameters ().Length;
3202 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3204 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
3205 if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
3206 object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
3210 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3211 if (dma.MemberName != pi.Name)
3213 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3215 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3227 /// There is exactly one instance of this class per type.
3229 public sealed class TypeHandle : IMemberContainer {
3230 public readonly IMemberContainer BaseType;
3232 readonly int id = ++next_id;
3233 static int next_id = 0;
3235 static TypeHandle ()
3241 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3242 /// a TypeHandle yet, a new instance of it is created. This static method
3243 /// ensures that we'll only have one TypeHandle instance per type.
3245 private static TypeHandle GetTypeHandle (Type t)
3247 TypeHandle handle = (TypeHandle) type_hash [t];
3251 handle = new TypeHandle (t);
3252 type_hash.Add (t, handle);
3256 public static MemberCache GetMemberCache (Type t)
3258 return GetTypeHandle (t).MemberCache;
3261 public static void CleanUp ()
3266 public static void Reset ()
3268 type_hash = new PtrHashtable ();
3272 /// Returns the TypeHandle for TypeManager.object_type.
3274 public static IMemberContainer ObjectType {
3276 if (object_type != null)
3279 object_type = GetTypeHandle (TypeManager.object_type);
3286 /// Returns the TypeHandle for TypeManager.array_type.
3288 public static TypeHandle ArrayType {
3290 if (array_type != null)
3293 array_type = GetTypeHandle (TypeManager.array_type);
3299 private static PtrHashtable type_hash;
3301 private static TypeHandle object_type = null;
3302 private static TypeHandle array_type = null;
3305 private string full_name;
3306 private bool is_interface;
3307 private MemberCache member_cache;
3308 private MemberCache base_cache;
3310 private TypeHandle (Type type)
3313 full_name = type.FullName != null ? type.FullName : type.Name;
3314 if (type.BaseType != null) {
3315 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3316 BaseType = base_cache.Container;
3317 } else if (type.IsInterface)
3318 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3319 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3320 this.member_cache = new MemberCache (this);
3323 // IMemberContainer methods
3325 public string Name {
3337 public MemberCache BaseCache {
3343 public bool IsInterface {
3345 return is_interface;
3349 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3351 MemberInfo [] members;
3353 if (type is GenericTypeParameterBuilder)
3354 return MemberList.Empty;
3357 type = TypeManager.DropGenericTypeArguments (type);
3359 if (mt == MemberTypes.Event)
3360 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3362 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3365 if (members.Length == 0)
3366 return MemberList.Empty;
3368 Array.Reverse (members);
3369 return new MemberList (members);
3372 // IMemberFinder methods
3374 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3375 MemberFilter filter, object criteria)
3377 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3380 public MemberCache MemberCache {
3382 return member_cache;
3386 public override string ToString ()
3388 if (BaseType != null)
3389 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3391 return "TypeHandle (" + id + "," + Name + ")";