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 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
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.Text.RegularExpressions;
29 using System.Runtime.CompilerServices;
30 using System.Diagnostics;
32 namespace Mono.CSharp {
34 public partial class TypeManager {
36 // A list of core types that the compiler requires or uses
38 static public Type object_type;
39 static public Type value_type;
40 static public Type string_type;
41 static public Type int32_type;
42 static public Type uint32_type;
43 static public Type int64_type;
44 static public Type uint64_type;
45 static public Type float_type;
46 static public Type double_type;
47 static public Type char_type;
48 static public Type char_ptr_type;
49 static public Type short_type;
50 static public Type decimal_type;
51 static public Type bool_type;
52 static public Type sbyte_type;
53 static public Type byte_type;
54 static public Type ushort_type;
55 static public Type enum_type;
56 static public Type delegate_type;
57 static public Type multicast_delegate_type;
58 static public Type void_type;
59 static public Type null_type;
60 static public Type enumeration_type;
61 static public Type array_type;
62 static public Type runtime_handle_type;
63 static public Type icloneable_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 iconvertible_type;
69 static public Type default_member_type;
70 static public Type iasyncresult_type;
71 static public Type asynccallback_type;
72 static public Type intptr_type;
73 static public Type monitor_type;
74 static public Type interlocked_type;
75 static public Type runtime_field_handle_type;
76 static public Type runtime_argument_handle_type;
77 static public Type attribute_type;
78 static public Type attribute_usage_type;
79 static public Type decimal_constant_attribute_type;
80 static public Type dllimport_type;
81 static public Type unverifiable_code_type;
82 static public Type methodimpl_attr_type;
83 static public Type marshal_as_attr_type;
84 static public Type param_array_type;
85 static public Type void_ptr_type;
86 static public Type indexer_name_type;
87 static public Type exception_type;
88 static public Type invalid_operation_exception_type;
89 static public Type not_supported_exception_type;
90 static public Type obsolete_attribute_type;
91 static public Type conditional_attribute_type;
92 static public Type in_attribute_type;
93 static public Type out_attribute_type;
94 static public Type default_parameter_value_attribute_type;
96 static public Type anonymous_method_type;
97 static public Type cls_compliant_attribute_type;
98 static public Type typed_reference_type;
99 static public Type arg_iterator_type;
100 static public Type mbr_type;
101 static public Type struct_layout_attribute_type;
102 static public Type field_offset_attribute_type;
103 static public Type security_attr_type;
104 static public Type required_attr_type;
105 static public Type guid_attr_type;
106 static public Type assembly_culture_attribute_type;
107 static public Type coclass_attr_type;
108 static public Type comimport_attr_type;
114 static internal Type runtime_compatibility_attr_type;
115 static internal Type compiler_generated_attr_type;
116 static internal Type fixed_buffer_attr_type;
117 static internal Type default_charset_type;
118 static internal Type internals_visible_attr_type;
119 static internal Type type_forwarder_attr_type;
123 // Expressions representing the internal types. Used during declaration
126 static public TypeExpr system_object_expr, system_string_expr;
127 static public TypeExpr system_boolean_expr, system_decimal_expr;
128 static public TypeExpr system_single_expr, system_double_expr;
129 static public TypeExpr system_sbyte_expr, system_byte_expr;
130 static public TypeExpr system_int16_expr, system_uint16_expr;
131 static public TypeExpr system_int32_expr, system_uint32_expr;
132 static public TypeExpr system_int64_expr, system_uint64_expr;
133 static public TypeExpr system_char_expr, system_void_expr;
134 static public TypeExpr system_asynccallback_expr;
135 static public TypeExpr system_iasyncresult_expr;
136 static public TypeExpr system_valuetype_expr;
137 static public TypeExpr system_intptr_expr;
140 // This is only used when compiling corlib
142 static public Type system_int32_type;
143 static public Type system_array_type;
144 static public Type system_type_type;
145 static public Type system_assemblybuilder_type;
146 static public MethodInfo system_int_array_get_length;
147 static public MethodInfo system_int_array_get_rank;
148 static public MethodInfo system_object_array_clone;
149 static public MethodInfo system_int_array_get_length_int;
150 static public MethodInfo system_int_array_get_lower_bound_int;
151 static public MethodInfo system_int_array_get_upper_bound_int;
152 static public MethodInfo system_void_array_copyto_array_int;
156 // Internal, not really used outside
158 static Type runtime_helpers_type;
161 // These methods are called by code generated by the compiler
163 static public MethodInfo string_concat_string_string;
164 static public MethodInfo string_concat_string_string_string;
165 static public MethodInfo string_concat_string_string_string_string;
166 static public MethodInfo string_concat_string_dot_dot_dot;
167 static public MethodInfo string_concat_object_object;
168 static public MethodInfo string_concat_object_object_object;
169 static public MethodInfo string_concat_object_dot_dot_dot;
170 static public MethodInfo string_isinterneted_string;
171 static public MethodInfo system_type_get_type_from_handle;
172 static public MethodInfo bool_movenext_void;
173 static public MethodInfo ienumerable_getenumerator_void;
174 static public MethodInfo void_reset_void;
175 static public MethodInfo void_dispose_void;
176 static public MethodInfo void_monitor_enter_object;
177 static public MethodInfo void_monitor_exit_object;
178 static public MethodInfo void_initializearray_array_fieldhandle;
179 static public MethodInfo int_getlength_int;
180 static public MethodInfo delegate_combine_delegate_delegate;
181 static public MethodInfo delegate_remove_delegate_delegate;
182 static public MethodInfo int_get_offset_to_string_data;
183 static public MethodInfo int_array_get_length;
184 static public MethodInfo int_array_get_rank;
185 static public MethodInfo object_array_clone;
186 static public MethodInfo int_array_get_length_int;
187 static public MethodInfo int_array_get_lower_bound_int;
188 static public MethodInfo int_array_get_upper_bound_int;
189 static public MethodInfo void_array_copyto_array_int;
190 static public MethodInfo int_interlocked_compare_exchange;
191 static public PropertyInfo ienumerator_getcurrent;
194 // The attribute constructors.
196 static public ConstructorInfo object_ctor;
197 static private ConstructorInfo cons_param_array_attribute;
198 static public ConstructorInfo void_decimal_ctor_five_args;
199 static public ConstructorInfo void_decimal_ctor_int_arg;
200 static public ConstructorInfo unverifiable_code_ctor;
201 static public ConstructorInfo default_member_ctor;
202 static public ConstructorInfo decimal_constant_attribute_ctor;
203 static internal ConstructorInfo struct_layout_attribute_ctor;
204 static public ConstructorInfo field_offset_attribute_ctor;
210 static internal CustomAttributeBuilder compiler_generated_attr;
211 static internal ConstructorInfo fixed_buffer_attr_ctor;
214 static PtrHashtable builder_to_declspace;
216 static PtrHashtable builder_to_member_cache;
219 // Tracks the interfaces implemented by typebuilders. We only
220 // enter those who do implement or or more interfaces
222 static PtrHashtable builder_to_ifaces;
225 // Maps PropertyBuilder to a Type array that contains
226 // the arguments to the indexer
228 static Hashtable indexer_arguments;
231 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
233 static Hashtable method_params;
236 // A hash table from override methods to their base virtual method.
238 static Hashtable method_overrides;
241 // Keeps track of methods
244 static Hashtable builder_to_method;
247 // Contains all public types from referenced assemblies.
248 // This member is used only if CLS Compliance verification is required.
250 public static Hashtable AllClsTopLevelTypes;
252 static Hashtable fieldbuilders_to_fields;
253 static Hashtable propertybuilder_to_property;
254 static Hashtable fields;
255 static Hashtable events;
258 static PtrHashtable assembly_internals_vis_attrs;
266 public static void CleanUp ()
268 // Lets get everything clean so that we can collect before generating code
269 builder_to_declspace = null;
270 builder_to_member_cache = null;
271 builder_to_ifaces = null;
272 indexer_arguments = null;
273 method_params = null;
274 builder_to_method = null;
277 fieldbuilders_to_fields = null;
279 priv_fields_events = null;
281 propertybuilder_to_property = null;
284 assembly_internals_vis_attrs = null;
289 TypeHandle.CleanUp ();
293 /// A filter for Findmembers that uses the Signature object to
296 static bool SignatureFilter (MemberInfo mi, object criteria)
298 Signature sig = (Signature) criteria;
300 if (!(mi is MethodBase))
303 if (mi.Name != sig.name)
306 int count = sig.args.Length;
308 if (mi is MethodBuilder || mi is ConstructorBuilder){
309 Type [] candidate_args = GetParameterData ((MethodBase) mi).Types;
311 if (candidate_args.Length != count)
314 for (int i = 0; i < count; i++)
315 if (candidate_args [i] != sig.args [i])
320 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
322 if (pars.Length != count)
325 for (int i = 0; i < count; i++)
326 if (pars [i].ParameterType != sig.args [i])
332 // A delegate that points to the filter above.
333 static MemberFilter signature_filter;
336 // These are expressions that represent some of the internal data types, used
339 static void InitExpressionTypes ()
341 system_object_expr = new TypeLookupExpression ("System.Object");
342 system_string_expr = new TypeLookupExpression ("System.String");
343 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
344 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
345 system_single_expr = new TypeLookupExpression ("System.Single");
346 system_double_expr = new TypeLookupExpression ("System.Double");
347 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
348 system_byte_expr = new TypeLookupExpression ("System.Byte");
349 system_int16_expr = new TypeLookupExpression ("System.Int16");
350 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
351 system_int32_expr = new TypeLookupExpression ("System.Int32");
352 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
353 system_int64_expr = new TypeLookupExpression ("System.Int64");
354 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
355 system_char_expr = new TypeLookupExpression ("System.Char");
356 system_void_expr = new TypeLookupExpression ("System.Void");
357 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
358 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
359 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
360 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
363 static TypeManager ()
367 signature_filter = new MemberFilter (SignatureFilter);
368 InitExpressionTypes ();
371 static public void Reset ()
373 builder_to_declspace = new PtrHashtable ();
374 builder_to_member_cache = new PtrHashtable ();
375 builder_to_method = new PtrHashtable ();
376 method_params = new PtrHashtable ();
377 method_overrides = new PtrHashtable ();
378 indexer_arguments = new PtrHashtable ();
379 builder_to_ifaces = new PtrHashtable ();
381 fieldbuilders_to_fields = new Hashtable ();
382 propertybuilder_to_property = new Hashtable ();
383 fields = new Hashtable ();
384 type_hash = new DoubleHash ();
387 assembly_internals_vis_attrs = new PtrHashtable ();
392 // to uncover regressions
393 cons_param_array_attribute = null;
396 public static void AddUserType (DeclSpace ds)
398 builder_to_declspace.Add (ds.TypeBuilder, ds);
402 // This entry point is used by types that we define under the covers
404 public static void RegisterBuilder (Type tb, Type [] ifaces)
407 builder_to_ifaces [tb] = ifaces;
410 public static void AddMethod (MethodBase builder, IMethodData method)
412 builder_to_method.Add (builder, method);
413 method_params.Add (builder, method.ParameterInfo);
416 public static IMethodData GetMethod (MethodBase builder)
418 return (IMethodData) builder_to_method [builder];
422 /// Returns the DeclSpace whose Type is `t' or null if there is no
423 /// DeclSpace for `t' (ie, the Type comes from a library)
425 public static DeclSpace LookupDeclSpace (Type t)
427 return builder_to_declspace [t] as DeclSpace;
431 /// Returns the TypeContainer whose Type is `t' or null if there is no
432 /// TypeContainer for `t' (ie, the Type comes from a library)
434 public static TypeContainer LookupTypeContainer (Type t)
436 return builder_to_declspace [t] as TypeContainer;
439 public static MemberCache LookupMemberCache (Type t)
441 if (t is TypeBuilder) {
442 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
443 if (container != null)
444 return container.MemberCache;
448 if (t is GenericTypeParameterBuilder) {
449 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
451 if (container != null)
452 return container.MemberCache;
456 return TypeHandle.GetMemberCache (t);
459 public static MemberCache LookupBaseInterfacesCache (Type t)
461 Type [] ifaces = GetInterfaces (t);
463 if (ifaces != null && ifaces.Length == 1)
464 return LookupMemberCache (ifaces [0]);
466 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
467 MemberCache cache = builder_to_member_cache [t] as MemberCache;
471 cache = new MemberCache (ifaces);
472 builder_to_member_cache.Add (t, cache);
476 public static TypeContainer LookupInterface (Type t)
478 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
479 if ((tc == null) || (tc.Kind != Kind.Interface))
485 public static Delegate LookupDelegate (Type t)
487 return builder_to_declspace [t] as Delegate;
490 public static Class LookupClass (Type t)
492 return (Class) builder_to_declspace [t];
496 // We use this hash for multiple kinds of constructed types:
498 // (T, "&") Given T, get T &
499 // (T, "*") Given T, get T *
500 // (T, "[]") Given T and a array dimension, get T []
501 // (T, X) Given a type T and a simple name X, get the type T+X
503 // Accessibility tests, if necessary, should be done by the user
505 static DoubleHash type_hash = new DoubleHash ();
508 // Gets the reference to T version of the Type (T&)
510 public static Type GetReferenceType (Type t)
513 return t.MakeByRefType ();
515 return GetConstructedType (t, "&");
520 // Gets the pointer to T version of the Type (T*)
522 public static Type GetPointerType (Type t)
524 return GetConstructedType (t, "*");
527 public static Type GetConstructedType (Type t, string dim)
530 if (type_hash.Lookup (t, dim, out ret))
533 ret = t.Module.GetType (t.ToString () + dim);
535 type_hash.Insert (t, dim, ret);
540 ret = GetReferenceType (t);
541 type_hash.Insert (t, dim, ret);
546 if (t.IsGenericParameter || t.IsGenericType) {
549 while ((pos < dim.Length) && (dim [pos] == '[')) {
552 if (dim [pos] == ']') {
553 result = result.MakeArrayType ();
556 if (pos < dim.Length)
559 type_hash.Insert (t, dim, result);
564 while (dim [pos] == ',') {
568 if ((dim [pos] != ']') || (pos != dim.Length-1))
571 result = result.MakeArrayType (rank + 1);
572 type_hash.Insert (t, dim, result);
578 type_hash.Insert (t, dim, null);
582 public static Type GetNestedType (Type t, string name)
585 if (!type_hash.Lookup (t, name, out ret)) {
586 ret = t.GetNestedType (name,
587 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
588 type_hash.Insert (t, name, ret);
594 /// Fills static table with exported types from all referenced assemblies.
595 /// This information is required for CLS Compliance tests.
597 public static void LoadAllImportedTypes ()
599 AllClsTopLevelTypes = new Hashtable (1500);
600 foreach (Assembly a in RootNamespace.Global.Assemblies) {
601 foreach (Type t in a.GetExportedTypes ()) {
602 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
607 public static bool NamespaceClash (string name, Location loc)
609 if (! RootNamespace.Global.IsNamespace (name))
612 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
617 /// Returns the C# name of a type if possible, or the full type name otherwise
619 static public string CSharpName (Type t)
621 if (t == typeof(NullType))
625 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
626 t = GetTypeArguments (t) [0];
627 return CSharpName (t) + "?";
631 string name = GetFullName (t);
633 return Regex.Replace (name,
635 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
636 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
637 @"Boolean|String|Void|Null)" +
639 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
642 static public string CSharpName (Type[] types)
644 StringBuilder sb = new StringBuilder ();
645 foreach (Type t in types) {
646 sb.Append (CSharpName (t));
649 sb.Remove (sb.Length - 1, 1);
650 return sb.ToString ();
653 static String CSharpNameMatch (Match match)
655 string s = match.Groups [1].Captures [0].Value;
657 Replace ("int32", "int").
658 Replace ("uint32", "uint").
659 Replace ("int16", "short").
660 Replace ("uint16", "ushort").
661 Replace ("int64", "long").
662 Replace ("uint64", "ulong").
663 Replace ("single", "float").
664 Replace ("boolean", "bool")
665 + match.Groups [2].Captures [0].Value;
669 /// Returns the signature of the method with full namespace classification
671 static public string GetFullNameSignature (MemberInfo mi)
673 PropertyInfo pi = mi as PropertyInfo;
675 MethodBase pmi = pi.GetGetMethod (true);
677 pmi = pi.GetSetMethod (true);
678 if (GetParameterData (pmi).Count > 0)
681 return (mi is MethodBase)
682 ? CSharpSignature (mi as MethodBase)
683 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
687 private static int GetFullName (Type t, StringBuilder sb)
691 if (!t.IsGenericType) {
692 sb.Append (t.FullName);
696 if (t.DeclaringType != null) {
697 pos = GetFullName (t.DeclaringType, sb);
699 sb.Append (RemoveGenericArity (t.Name));
701 sb.Append (RemoveGenericArity (t.FullName));
704 Type[] this_args = GetTypeArguments (t);
706 if (this_args.Length < pos)
707 throw new InternalErrorException (
708 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
709 if (this_args.Length == pos)
714 sb.Append (CSharpName (this_args [pos++]));
715 if (pos == this_args.Length)
723 public static string GetFullName (Type t)
725 if (t.IsGenericParameter)
727 if (!t.IsGenericType)
730 StringBuilder sb = new StringBuilder ();
731 int pos = GetFullName (t, sb);
733 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
734 return sb.ToString ();
737 public static string GetFullName (Type t)
743 public static string RemoveGenericArity (string from)
745 int i = from.IndexOf ('`');
747 return from.Substring (0, i);
752 /// When we need to report accessors as well
754 static public string CSharpSignature (MethodBase mb)
756 return CSharpSignature (mb, false);
760 /// Returns the signature of the method
762 static public string CSharpSignature (MethodBase mb, bool show_accessor)
764 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
767 ParameterData iparams = GetParameterData (mb);
768 string parameters = iparams.GetSignatureForError ();
769 string accessor = "";
772 if (mb.IsSpecialName) {
773 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
774 if (ot != Operator.OpType.TOP) {
775 sig.Append ("operator ");
776 sig.Append (Operator.GetName (ot));
777 sig.Append (parameters);
778 return sig.ToString ();
781 if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
782 accessor = mb.Name.Substring (0, 3);
787 if (mb.IsSpecialName && !mb.IsConstructor) {
788 if (iparams.Count > (mb.Name.StartsWith ("get_") ? 0 : 1)) {
789 sig.Append ("this[");
791 sig.Append (parameters.Substring (1, parameters.Length - 2));
794 int before_ret_val = parameters.LastIndexOf (',');
795 if (before_ret_val < 0)
796 sig.Append (parameters.Substring (1, parameters.Length - 2));
798 sig.Append (parameters.Substring (1, before_ret_val - 1));
802 sig.Append (mb.Name.Substring (4));
805 if (mb.Name == ".ctor")
806 sig.Append (mb.DeclaringType.Name);
808 sig.Append (mb.Name);
811 if (TypeManager.IsGenericMethod (mb)) {
812 Type[] args = mb.GetGenericArguments ();
814 for (int i = 0; i < args.Length; i++) {
817 sig.Append (args [i].Name);
824 sig.Append (parameters);
827 if (show_accessor && accessor.Length > 0) {
829 sig.Append (accessor);
832 return sig.ToString ();
835 public static string GetMethodName (MethodInfo m)
838 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
841 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
847 static public string CSharpSignature (EventInfo ei)
849 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
853 /// Looks up a type, and aborts if it is not found. This is used
854 /// by types required by the compiler
856 static Type CoreLookupType (string ns_name, string name)
858 Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
859 FullNamedExpression fne = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
860 Type t = fne == null ? null : fne.Type;
862 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
867 /// Returns the MethodInfo for a method named `name' defined
868 /// in type `t' which takes arguments of types `args'
870 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
874 BindingFlags flags = instance_and_static | BindingFlags.Public;
880 flags |= BindingFlags.NonPublic;
882 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
883 if (list.Count == 0) {
885 Report.Error (-19, "Can not find the core function `" + name + "'");
889 MethodInfo mi = list [0] as MethodInfo;
892 Report.Error (-19, "Can not find the core function `" + name + "'");
899 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
901 return GetMethod (t, name, args, false, report_errors);
904 static MethodInfo GetMethod (Type t, string name, Type [] args)
906 return GetMethod (t, name, args, true);
910 /// Returns the PropertyInfo for a property named `name' defined
913 public static PropertyInfo GetProperty (Type t, string name)
915 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
916 BindingFlags.Instance, Type.FilterName, name);
917 if (list.Count == 0) {
918 Report.Error (-19, "Can not find the core property `" + name + "'");
922 PropertyInfo pi = list [0] as PropertyInfo;
924 Report.Error (-19, "Can not find the core function `" + name + "'");
932 /// Returns the ConstructorInfo for "args"
934 public static ConstructorInfo GetConstructor (Type t, Type [] args)
943 throw new InternalErrorException ("Core types haven't been initialized yet?");
945 list = FindMembers (t, MemberTypes.Constructor,
946 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
947 signature_filter, sig);
948 if (list.Count == 0){
949 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
953 ConstructorInfo ci = list [0] as ConstructorInfo;
955 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
962 public static void InitEnumUnderlyingTypes ()
964 int32_type = CoreLookupType ("System", "Int32");
965 int64_type = CoreLookupType ("System", "Int64");
966 uint32_type = CoreLookupType ("System", "UInt32");
967 uint64_type = CoreLookupType ("System", "UInt64");
968 byte_type = CoreLookupType ("System", "Byte");
969 sbyte_type = CoreLookupType ("System", "SByte");
970 short_type = CoreLookupType ("System", "Int16");
971 ushort_type = CoreLookupType ("System", "UInt16");
973 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator");
974 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable");
976 idisposable_type = CoreLookupType ("System", "IDisposable");
979 InitGenericCoreTypes ();
984 /// The types have to be initialized after the initial
985 /// population of the type has happened (for example, to
986 /// bootstrap the corlib.dll
988 public static void InitCoreTypes ()
990 object_type = CoreLookupType ("System", "Object");
991 value_type = CoreLookupType ("System", "ValueType");
993 InitEnumUnderlyingTypes ();
995 char_type = CoreLookupType ("System", "Char");
996 string_type = CoreLookupType ("System", "String");
997 float_type = CoreLookupType ("System", "Single");
998 double_type = CoreLookupType ("System", "Double");
999 char_ptr_type = GetPointerType (char_type);
1000 decimal_type = CoreLookupType ("System", "Decimal");
1001 bool_type = CoreLookupType ("System", "Boolean");
1002 enum_type = CoreLookupType ("System", "Enum");
1004 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
1005 delegate_type = CoreLookupType ("System", "Delegate");
1007 array_type = CoreLookupType ("System", "Array");
1008 void_type = CoreLookupType ("System", "Void");
1009 type_type = CoreLookupType ("System", "Type");
1011 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
1012 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
1013 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
1014 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
1015 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle");
1016 asynccallback_type = CoreLookupType ("System", "AsyncCallback");
1017 iasyncresult_type = CoreLookupType ("System", "IAsyncResult");
1018 icloneable_type = CoreLookupType ("System", "ICloneable");
1019 iconvertible_type = CoreLookupType ("System", "IConvertible");
1020 interlocked_type = CoreLookupType ("System.Threading", "Interlocked");
1021 monitor_type = CoreLookupType ("System.Threading", "Monitor");
1022 intptr_type = CoreLookupType ("System", "IntPtr");
1024 attribute_type = CoreLookupType ("System", "Attribute");
1025 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
1026 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
1027 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
1028 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
1029 param_array_type = CoreLookupType ("System", "ParamArrayAttribute");
1030 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
1031 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
1033 default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1035 typed_reference_type = CoreLookupType ("System", "TypedReference");
1036 arg_iterator_type = CoreLookupType ("System", "ArgIterator");
1037 mbr_type = CoreLookupType ("System", "MarshalByRefObject");
1038 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
1040 unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
1042 void_ptr_type = GetPointerType (void_type);
1044 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
1046 exception_type = CoreLookupType ("System", "Exception");
1047 invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
1048 not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
1053 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
1054 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
1055 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
1056 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
1057 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
1058 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
1059 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1060 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
1061 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
1062 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
1063 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
1069 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1070 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1071 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1072 internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1073 runtime_compatibility_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1074 type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1077 // When compiling corlib, store the "real" types here.
1079 if (!RootContext.StdLib) {
1080 system_int32_type = typeof (System.Int32);
1081 system_array_type = typeof (System.Array);
1082 system_type_type = typeof (System.Type);
1083 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1085 system_int_array_get_length = GetMethod (
1086 system_array_type, "get_Length", Type.EmptyTypes);
1087 system_int_array_get_rank = GetMethod (
1088 system_array_type, "get_Rank", Type.EmptyTypes);
1089 system_object_array_clone = GetMethod (
1090 system_array_type, "Clone", Type.EmptyTypes);
1092 Type [] system_int_arg = { system_int32_type };
1093 system_int_array_get_length_int = GetMethod (
1094 system_array_type, "GetLength", system_int_arg);
1095 system_int_array_get_upper_bound_int = GetMethod (
1096 system_array_type, "GetUpperBound", system_int_arg);
1097 system_int_array_get_lower_bound_int = GetMethod (
1098 system_array_type, "GetLowerBound", system_int_arg);
1100 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1101 system_void_array_copyto_array_int = GetMethod (
1102 system_array_type, "CopyTo", system_array_int_arg);
1104 Type [] system_3_type_arg = {
1105 system_type_type, system_type_type, system_type_type };
1106 Type [] system_4_type_arg = {
1107 system_type_type, system_type_type, system_type_type, system_type_type };
1109 MethodInfo set_corlib_type_builders = GetMethod (
1110 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1111 system_4_type_arg, true, false);
1113 if (set_corlib_type_builders != null) {
1114 object[] args = new object [4];
1115 args [0] = object_type;
1116 args [1] = value_type;
1117 args [2] = enum_type;
1118 args [3] = void_type;
1120 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1122 // Compatibility for an older version of the class libs.
1123 set_corlib_type_builders = GetMethod (
1124 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1125 system_3_type_arg, true, true);
1127 if (set_corlib_type_builders == null) {
1128 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1132 object[] args = new object [3];
1133 args [0] = object_type;
1134 args [1] = value_type;
1135 args [2] = enum_type;
1137 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1141 system_object_expr.Type = object_type;
1142 system_string_expr.Type = string_type;
1143 system_boolean_expr.Type = bool_type;
1144 system_decimal_expr.Type = decimal_type;
1145 system_single_expr.Type = float_type;
1146 system_double_expr.Type = double_type;
1147 system_sbyte_expr.Type = sbyte_type;
1148 system_byte_expr.Type = byte_type;
1149 system_int16_expr.Type = short_type;
1150 system_uint16_expr.Type = ushort_type;
1151 system_int32_expr.Type = int32_type;
1152 system_uint32_expr.Type = uint32_type;
1153 system_int64_expr.Type = int64_type;
1154 system_uint64_expr.Type = uint64_type;
1155 system_char_expr.Type = char_type;
1156 system_void_expr.Type = void_type;
1157 system_asynccallback_expr.Type = asynccallback_type;
1158 system_iasyncresult_expr.Type = iasyncresult_type;
1159 system_valuetype_expr.Type = value_type;
1162 // These are only used for compare purposes
1164 anonymous_method_type = typeof (AnonymousMethod);
1165 null_type = typeof (NullType);
1169 // The helper methods that are used by the compiler
1171 public static void InitCodeHelpers ()
1174 // Now load the default methods that we use.
1176 Type [] string_string = { string_type, string_type };
1177 string_concat_string_string = GetMethod (
1178 string_type, "Concat", string_string);
1179 Type [] string_string_string = { string_type, string_type, string_type };
1180 string_concat_string_string_string = GetMethod (
1181 string_type, "Concat", string_string_string);
1182 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1183 string_concat_string_string_string_string = GetMethod (
1184 string_type, "Concat", string_string_string_string);
1185 Type[] params_string = { GetConstructedType (string_type, "[]") };
1186 string_concat_string_dot_dot_dot = GetMethod (
1187 string_type, "Concat", params_string);
1189 Type [] object_object = { object_type, object_type };
1190 string_concat_object_object = GetMethod (
1191 string_type, "Concat", object_object);
1192 Type [] object_object_object = { object_type, object_type, object_type };
1193 string_concat_object_object_object = GetMethod (
1194 string_type, "Concat", object_object_object);
1195 Type[] params_object = { GetConstructedType (object_type, "[]") };
1196 string_concat_object_dot_dot_dot = GetMethod (
1197 string_type, "Concat", params_object);
1199 Type [] string_ = { string_type };
1200 string_isinterneted_string = GetMethod (
1201 string_type, "IsInterned", string_);
1203 Type [] runtime_type_handle = { runtime_handle_type };
1204 system_type_get_type_from_handle = GetMethod (
1205 type_type, "GetTypeFromHandle", runtime_type_handle);
1207 Type [] delegate_delegate = { delegate_type, delegate_type };
1208 delegate_combine_delegate_delegate = GetMethod (
1209 delegate_type, "Combine", delegate_delegate);
1211 delegate_remove_delegate_delegate = GetMethod (
1212 delegate_type, "Remove", delegate_delegate);
1217 ienumerator_getcurrent = GetProperty (
1218 ienumerator_type, "Current");
1219 bool_movenext_void = GetMethod (
1220 ienumerator_type, "MoveNext", Type.EmptyTypes);
1221 void_reset_void = GetMethod (
1222 ienumerator_type, "Reset", Type.EmptyTypes);
1223 void_dispose_void = GetMethod (
1224 idisposable_type, "Dispose", Type.EmptyTypes);
1225 int_get_offset_to_string_data = GetMethod (
1226 runtime_helpers_type, "get_OffsetToStringData", Type.EmptyTypes);
1227 int_array_get_length = GetMethod (
1228 array_type, "get_Length", Type.EmptyTypes);
1229 int_array_get_rank = GetMethod (
1230 array_type, "get_Rank", Type.EmptyTypes);
1231 ienumerable_getenumerator_void = GetMethod (
1232 ienumerable_type, "GetEnumerator", Type.EmptyTypes);
1237 Type [] int_arg = { int32_type };
1238 int_array_get_length_int = GetMethod (
1239 array_type, "GetLength", int_arg);
1240 int_array_get_upper_bound_int = GetMethod (
1241 array_type, "GetUpperBound", int_arg);
1242 int_array_get_lower_bound_int = GetMethod (
1243 array_type, "GetLowerBound", int_arg);
1246 // System.Array methods
1248 object_array_clone = GetMethod (
1249 array_type, "Clone", Type.EmptyTypes);
1250 Type [] array_int_arg = { array_type, int32_type };
1251 void_array_copyto_array_int = GetMethod (
1252 array_type, "CopyTo", array_int_arg);
1257 Type [] object_arg = { object_type };
1258 void_monitor_enter_object = GetMethod (
1259 monitor_type, "Enter", object_arg);
1260 void_monitor_exit_object = GetMethod (
1261 monitor_type, "Exit", object_arg);
1263 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1265 void_initializearray_array_fieldhandle = GetMethod (
1266 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1271 int_getlength_int = GetMethod (
1272 array_type, "GetLength", int_arg);
1275 // Decimal constructors
1277 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1278 void_decimal_ctor_five_args = GetConstructor (
1279 decimal_type, dec_arg);
1281 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1286 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, Type.EmptyTypes);
1287 default_member_ctor = GetConstructor (default_member_type, string_);
1289 Type[] short_arg = { short_type };
1290 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1292 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1293 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1295 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1299 // System.Threading.CompareExchange
1301 Type[] compare_exchange_types = {
1302 GetReferenceType (int32_type), int32_type, int32_type };
1303 int_interlocked_compare_exchange = GetMethod (
1304 interlocked_type, "CompareExchange", compare_exchange_types);
1310 compiler_generated_attr = new CustomAttributeBuilder (
1311 GetConstructor (compiler_generated_attr_type, Type.EmptyTypes), new object[0]);
1313 Type[] type_int_arg = { type_type, int32_type };
1314 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1318 object_ctor = GetConstructor (object_type, Type.EmptyTypes);
1321 InitGenericCodeHelpers ();
1325 static public ConstructorInfo ConsParamArrayAttribute {
1327 if (cons_param_array_attribute == null)
1328 cons_param_array_attribute = GetConstructor (param_array_type, Type.EmptyTypes);
1329 return cons_param_array_attribute;
1333 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1336 /// This is the "old", non-cache based FindMembers() function. We cannot use
1337 /// the cache here because there is no member name argument.
1339 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1340 MemberFilter filter, object criteria)
1342 #if MS_COMPATIBLE && GMCS_SOURCE
1343 if (t.IsGenericType)
1344 t = t.GetGenericTypeDefinition ();
1347 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1350 // `builder_to_declspace' contains all dynamic types.
1354 Timer.StartTimer (TimerType.FindMembers);
1355 list = decl.FindMembers (mt, bf, filter, criteria);
1356 Timer.StopTimer (TimerType.FindMembers);
1361 // We have to take care of arrays specially, because GetType on
1362 // a TypeBuilder array will return a Type, not a TypeBuilder,
1363 // and we can not call FindMembers on this type.
1366 #if MS_COMPATIBLE && GMCS_SOURCE
1369 t.IsSubclassOf (TypeManager.array_type))
1370 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1373 if (t is GenericTypeParameterBuilder) {
1374 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1376 Timer.StartTimer (TimerType.FindMembers);
1377 MemberList list = tparam.FindMembers (
1378 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1379 Timer.StopTimer (TimerType.FindMembers);
1385 // Since FindMembers will not lookup both static and instance
1386 // members, we emulate this behaviour here.
1388 if ((bf & instance_and_static) == instance_and_static){
1389 MemberInfo [] i_members = t.FindMembers (
1390 mt, bf & ~BindingFlags.Static, filter, criteria);
1392 int i_len = i_members.Length;
1394 MemberInfo one = i_members [0];
1397 // If any of these are present, we are done!
1399 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1400 return new MemberList (i_members);
1403 MemberInfo [] s_members = t.FindMembers (
1404 mt, bf & ~BindingFlags.Instance, filter, criteria);
1406 int s_len = s_members.Length;
1407 if (i_len > 0 || s_len > 0)
1408 return new MemberList (i_members, s_members);
1411 return new MemberList (i_members);
1413 return new MemberList (s_members);
1417 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1422 /// This method is only called from within MemberLookup. It tries to use the member
1423 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1424 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1425 /// our return value will already contain all inherited members and the caller don't need
1426 /// to check base classes and interfaces anymore.
1428 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1429 string name, out bool used_cache)
1434 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1435 // and we can ask the DeclSpace for the MemberCache.
1437 if (t is TypeBuilder) {
1438 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1439 cache = decl.MemberCache;
1442 // If this DeclSpace has a MemberCache, use it.
1445 if (cache != null) {
1447 return cache.FindMembers (
1448 mt, bf, name, FilterWithClosure_delegate, null);
1451 // If there is no MemberCache, we need to use the "normal" FindMembers.
1452 // Note, this is a VERY uncommon route!
1455 Timer.StartTimer (TimerType.FindMembers);
1456 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1457 FilterWithClosure_delegate, name);
1458 Timer.StopTimer (TimerType.FindMembers);
1460 return (MemberInfo []) list;
1464 // We have to take care of arrays specially, because GetType on
1465 // a TypeBuilder array will return a Type, not a TypeBuilder,
1466 // and we can not call FindMembers on this type.
1468 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1470 return TypeHandle.ArrayType.MemberCache.FindMembers (
1471 mt, bf, name, FilterWithClosure_delegate, null);
1475 if (t is GenericTypeParameterBuilder) {
1476 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1479 Timer.StartTimer (TimerType.FindMembers);
1480 list = tparam.FindMembers (mt, bf & ~BindingFlags.DeclaredOnly,
1481 FilterWithClosure_delegate, name);
1482 Timer.StopTimer (TimerType.FindMembers);
1484 return (MemberInfo []) list;
1487 if (t.IsGenericType && (mt == MemberTypes.NestedType)) {
1489 // This happens if we're resolving a class'es base class and interfaces
1490 // in TypeContainer.DefineType(). At this time, the types aren't
1491 // populated yet, so we can't use the cache.
1493 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1494 FilterWithClosure_delegate, name);
1501 // This call will always succeed. There is exactly one TypeHandle instance per
1502 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1503 // the corresponding MemberCache.
1505 cache = TypeHandle.GetMemberCache (t);
1508 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1511 public static bool IsBuiltinType (Type t)
1513 t = TypeToCoreType (t);
1514 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1515 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1516 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1517 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1523 public static bool IsBuiltinType (TypeContainer tc)
1525 return IsBuiltinType (tc.TypeBuilder);
1529 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1530 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1532 public static bool IsPrimitiveType (Type t)
1534 return (t == int32_type || t == uint32_type ||
1535 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1536 t == char_type || t == short_type || t == bool_type ||
1537 t == sbyte_type || t == byte_type || t == ushort_type);
1540 public static bool IsDelegateType (Type t)
1542 t = DropGenericTypeArguments (t);
1543 if (t.IsSubclassOf (TypeManager.delegate_type))
1549 public static bool IsEnumType (Type t)
1551 if (builder_to_declspace [t] is Enum)
1554 #if MS_COMPATIBLE && GMCS_SOURCE
1555 if (t.IsGenericParameter)
1561 public static bool IsBuiltinOrEnum (Type t)
1563 if (IsBuiltinType (t))
1572 public static bool IsNullType (Type t)
1574 return t == null_type;
1577 public static bool IsAttributeType (Type t)
1579 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1582 static Stack unmanaged_enclosing_types = new Stack (4);
1585 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1587 public static bool IsUnmanagedType (Type t)
1589 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1590 if (unmanaged_enclosing_types.Contains (t))
1593 // builtins that are not unmanaged types
1594 if (t == TypeManager.object_type || t == TypeManager.string_type)
1597 if (IsGenericType (t) || IsGenericParameter (t))
1600 if (IsBuiltinOrEnum (t))
1603 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1607 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1611 if (!IsValueType (t))
1615 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1616 if (p.IsGenericTypeDefinition)
1621 unmanaged_enclosing_types.Push (t);
1625 if (t is TypeBuilder) {
1626 TypeContainer tc = LookupTypeContainer (t);
1627 if (tc.Fields != null){
1628 foreach (FieldMember f in tc.Fields){
1629 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1630 if ((f.ModFlags & Modifiers.STATIC) != 0)
1632 if (f.MemberType == null)
1634 if (!IsUnmanagedType (f.MemberType)){
1635 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1641 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1643 foreach (FieldInfo f in fields){
1644 if (!IsUnmanagedType (f.FieldType)){
1645 Report.SymbolRelatedToPreviousError (f);
1651 unmanaged_enclosing_types.Pop ();
1656 public static bool IsValueType (Type t)
1658 return t.IsValueType || IsGenericParameter (t);
1661 public static bool IsInterfaceType (Type t)
1663 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1667 return tc.Kind == Kind.Interface;
1670 public static bool IsSubclassOf (Type type, Type base_type)
1673 TypeParameter tparam = LookupTypeParameter (type);
1674 TypeParameter pparam = LookupTypeParameter (base_type);
1676 if ((tparam != null) && (pparam != null)) {
1677 if (tparam == pparam)
1680 return tparam.IsSubclassOf (base_type);
1684 if (type.IsGenericType)
1685 type = type.GetGenericTypeDefinition ();
1689 if (type.IsSubclassOf (base_type))
1693 if (IsEqual (type, base_type))
1696 type = type.BaseType;
1697 } while (type != null);
1702 public static bool IsPrivateAccessible (Type type, Type parent)
1707 if (type.Equals (parent))
1710 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1713 public static bool IsFamilyAccessible (Type type, Type parent)
1716 TypeParameter tparam = LookupTypeParameter (type);
1717 TypeParameter pparam = LookupTypeParameter (parent);
1719 if ((tparam != null) && (pparam != null)) {
1720 if (tparam == pparam)
1723 return tparam.IsSubclassOf (parent);
1728 if (IsInstantiationOfSameGenericType (type, parent))
1731 type = type.BaseType;
1732 } while (type != null);
1738 // Checks whether `type' is a subclass or nested child of `base_type'.
1740 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1743 if (IsFamilyAccessible (type, base_type))
1746 // Handle nested types.
1747 type = type.DeclaringType;
1748 } while (type != null);
1754 // Checks whether `type' is a nested child of `parent'.
1756 public static bool IsNestedChildOf (Type type, Type parent)
1761 type = DropGenericTypeArguments (type);
1762 parent = DropGenericTypeArguments (parent);
1764 if (IsEqual (type, parent))
1767 type = type.DeclaringType;
1768 while (type != null) {
1769 if (IsEqual (type, parent))
1772 type = type.DeclaringType;
1780 // Checks whether `extern_type' is friend of the output assembly
1782 public static bool IsFriendAssembly (Assembly assembly)
1784 if (assembly_internals_vis_attrs.Contains (assembly))
1785 return (bool)(assembly_internals_vis_attrs [assembly]);
1787 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1788 if (attrs.Length == 0) {
1789 assembly_internals_vis_attrs.Add (assembly, false);
1793 AssemblyName this_name = CodeGen.Assembly.Name;
1794 byte [] this_token = this_name.GetPublicKeyToken ();
1795 bool is_friend = false;
1796 foreach (InternalsVisibleToAttribute attr in attrs) {
1797 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1800 AssemblyName aname = null;
1802 aname = new AssemblyName (attr.AssemblyName);
1803 } catch (FileLoadException) {
1804 } catch (ArgumentException) {
1807 if (aname == null || aname.Name != this_name.Name)
1810 byte [] key_token = aname.GetPublicKeyToken ();
1811 if (key_token != null) {
1812 if (this_token == null) {
1813 // Same name, but key token is null
1814 Error_FriendAccessNameNotMatching (aname.FullName);
1818 if (!CompareKeyTokens (this_token, key_token))
1826 assembly_internals_vis_attrs.Add (assembly, is_friend);
1830 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1832 for (int i = 0; i < token1.Length; i++)
1833 if (token1 [i] != token2 [i])
1839 static void Error_FriendAccessNameNotMatching (string other_name)
1841 Report.Error (281, "Friend access was granted to `" + other_name +
1842 "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
1843 "'. Try adding a reference to `" + other_name +
1844 "' or change the output assembly name to match it");
1847 public static bool IsFriendAssembly (Assembly assembly)
1854 // Do the right thing when returning the element type of an
1855 // array type based on whether we are compiling corlib or not
1857 public static Type GetElementType (Type t)
1859 if (RootContext.StdLib)
1860 return t.GetElementType ();
1862 return TypeToCoreType (t.GetElementType ());
1866 /// This method is not implemented by MS runtime for dynamic types
1868 public static bool HasElementType (Type t)
1870 return t.IsArray || t.IsPointer || t.IsByRef;
1874 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1878 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1879 /// for anything which is dynamic, and we need this in a number of places,
1880 /// we register this information here, and use it afterwards.
1882 static public void RegisterMethod (MethodBase mb, Parameters ip)
1884 method_params.Add (mb, ip);
1887 static public ParameterData GetParameterData (MethodBase mb)
1889 ParameterData pd = (ParameterData)method_params [mb];
1891 if (mb is MethodBuilder || mb is ConstructorBuilder)
1892 throw new InternalErrorException ("Argument for Method not registered" + mb);
1894 pd = new ReflectionParameters (mb);
1895 method_params.Add (mb, pd);
1900 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1902 if (!method_overrides.Contains (override_method))
1903 method_overrides [override_method] = base_method;
1904 if (method_overrides [override_method] != base_method)
1905 throw new InternalErrorException ("Override mismatch: " + override_method);
1908 static public bool IsOverride (MethodBase m)
1910 m = DropGenericMethodArguments (m);
1912 return m.IsVirtual &&
1913 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1914 (m is MethodBuilder || method_overrides.Contains (m));
1917 static public MethodBase TryGetBaseDefinition (MethodBase m)
1919 m = DropGenericMethodArguments (m);
1921 return (MethodBase) method_overrides [m];
1925 /// Returns the argument types for an indexer based on its PropertyInfo
1927 /// For dynamic indexers, we use the compiler provided types, for
1928 /// indexers from existing assemblies we load them from GetParameters,
1929 /// and insert them into the cache
1931 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1933 if (indexer_arguments.Contains (indexer))
1934 return (Type []) indexer_arguments [indexer];
1935 else if (indexer is PropertyBuilder)
1936 // If we're a PropertyBuilder and not in the
1937 // `indexer_arguments' hash, then we're a property and
1939 return Type.EmptyTypes;
1941 ParameterInfo [] pi = indexer.GetIndexParameters ();
1942 // Property, not an indexer.
1944 return Type.EmptyTypes;
1946 Type [] types = new Type [c];
1948 for (int i = 0; i < c; i++)
1949 types [i] = pi [i].ParameterType;
1951 indexer_arguments.Add (indexer, types);
1956 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1958 fields.Add (fb, ic);
1961 public static IConstant GetConstant (FieldInfo fb)
1966 return (IConstant)fields [fb];
1969 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1971 propertybuilder_to_property.Add (pi, pb);
1974 public static PropertyBase GetProperty (PropertyInfo pi)
1976 return (PropertyBase)propertybuilder_to_property [pi];
1979 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1981 if (fieldbuilders_to_fields.Contains (fb))
1984 fieldbuilders_to_fields.Add (fb, f);
1989 // The return value can be null; This will be the case for
1990 // auxiliary FieldBuilders created by the compiler that have no
1991 // real field being declared on the source code
1993 static public FieldBase GetField (FieldInfo fb)
1996 fb = GetGenericFieldDefinition (fb);
1998 return (FieldBase) fieldbuilders_to_fields [fb];
2001 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
2004 events = new Hashtable ();
2006 if (!events.Contains (eb)) {
2007 events.Add (eb, new Pair (add, remove));
2011 static public MethodInfo GetAddMethod (EventInfo ei)
2013 if (ei is MyEventBuilder) {
2014 Pair pair = (Pair) events [ei];
2016 return (MethodInfo) pair.First;
2018 return ei.GetAddMethod (true);
2021 static public MethodInfo GetRemoveMethod (EventInfo ei)
2023 if (ei is MyEventBuilder) {
2024 Pair pair = (Pair) events [ei];
2026 return (MethodInfo) pair.Second;
2028 return ei.GetRemoveMethod (true);
2031 static Hashtable priv_fields_events;
2033 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
2035 if (priv_fields_events == null)
2036 priv_fields_events = new Hashtable ();
2038 if (priv_fields_events.Contains (einfo))
2041 priv_fields_events.Add (einfo, builder);
2046 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
2048 if (priv_fields_events == null)
2051 return (MemberInfo) priv_fields_events [ei];
2054 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2055 MethodBase set, Type[] args)
2057 indexer_arguments.Add (pb, args);
2062 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2064 Hashtable hash = new Hashtable ();
2065 return CheckStructCycles (tc, seen, hash);
2068 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2071 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2075 // `seen' contains all types we've already visited.
2077 if (seen.Contains (tc))
2079 seen.Add (tc, null);
2081 if (tc.Fields == null)
2084 foreach (FieldMember field in tc.Fields) {
2085 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
2088 Type ftype = field.FieldBuilder.FieldType;
2089 TypeContainer ftc = LookupTypeContainer (ftype);
2093 if (hash.Contains (ftc)) {
2094 Report.Error (523, tc.Location,
2095 "Struct member `{0}.{1}' of type `{2}' " +
2096 "causes a cycle in the struct layout",
2097 tc.Name, field.Name, ftc.Name);
2102 // `hash' contains all types in the current path.
2104 hash.Add (tc, null);
2106 bool ok = CheckStructCycles (ftc, seen, hash);
2113 if (!seen.Contains (ftc))
2114 seen.Add (ftc, null);
2121 /// Given an array of interface types, expand and eliminate repeated ocurrences
2122 /// of an interface.
2126 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2129 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
2131 ArrayList new_ifaces = new ArrayList ();
2133 foreach (TypeExpr iface in base_interfaces){
2134 Type itype = iface.Type;
2136 if (new_ifaces.Contains (itype))
2139 new_ifaces.Add (itype);
2141 Type [] implementing = GetInterfaces (itype);
2143 foreach (Type imp in implementing){
2144 if (!new_ifaces.Contains (imp))
2145 new_ifaces.Add (imp);
2148 Type [] ret = new Type [new_ifaces.Count];
2149 new_ifaces.CopyTo (ret, 0);
2153 public static Type[] ExpandInterfaces (Type [] base_interfaces)
2155 ArrayList new_ifaces = new ArrayList ();
2157 foreach (Type itype in base_interfaces){
2158 if (new_ifaces.Contains (itype))
2161 new_ifaces.Add (itype);
2163 Type [] implementing = GetInterfaces (itype);
2165 foreach (Type imp in implementing){
2166 if (!new_ifaces.Contains (imp))
2167 new_ifaces.Add (imp);
2170 Type [] ret = new Type [new_ifaces.Count];
2171 new_ifaces.CopyTo (ret, 0);
2175 static PtrHashtable iface_cache = new PtrHashtable ();
2178 /// This function returns the interfaces in the type `t'. Works with
2179 /// both types and TypeBuilders.
2181 public static Type [] GetInterfaces (Type t)
2183 Type [] cached = iface_cache [t] as Type [];
2188 // The reason for catching the Array case is that Reflection.Emit
2189 // will not return a TypeBuilder for Array types of TypeBuilder types,
2190 // but will still throw an exception if we try to call GetInterfaces
2193 // Since the array interfaces are always constant, we return those for
2198 t = TypeManager.array_type;
2200 if ((t is TypeBuilder) || IsGenericType (t)) {
2201 Type [] base_ifaces;
2203 if (t.BaseType == null)
2204 base_ifaces = Type.EmptyTypes;
2206 base_ifaces = GetInterfaces (t.BaseType);
2208 if (IsGenericType (t))
2209 #if MS_COMPATIBLE && GMCS_SOURCE
2210 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
2212 type_ifaces = t.GetInterfaces ();
2215 type_ifaces = (Type []) builder_to_ifaces [t];
2216 if (type_ifaces == null || type_ifaces.Length == 0)
2217 type_ifaces = Type.EmptyTypes;
2219 int base_count = base_ifaces.Length;
2220 Type [] result = new Type [base_count + type_ifaces.Length];
2221 base_ifaces.CopyTo (result, 0);
2222 type_ifaces.CopyTo (result, base_count);
2224 iface_cache [t] = result;
2227 } else if (t is GenericTypeParameterBuilder){
2228 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2229 if (type_ifaces == null || type_ifaces.Length == 0)
2230 type_ifaces = Type.EmptyTypes;
2232 iface_cache [t] = type_ifaces;
2236 Type[] ifaces = t.GetInterfaces ();
2237 iface_cache [t] = ifaces;
2243 // gets the interfaces that are declared explicitly on t
2245 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2247 return (Type []) builder_to_ifaces [t];
2251 /// The following is used to check if a given type implements an interface.
2252 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2254 public static bool ImplementsInterface (Type t, Type iface)
2259 // FIXME OPTIMIZATION:
2260 // as soon as we hit a non-TypeBuiler in the interface
2261 // chain, we could return, as the `Type.GetInterfaces'
2262 // will return all the interfaces implement by the type
2266 interfaces = GetInterfaces (t);
2268 if (interfaces != null){
2269 foreach (Type i in interfaces){
2276 } while (t != null);
2281 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2283 // This is a custom version of Convert.ChangeType() which works
2284 // with the TypeBuilder defined types when compiling corlib.
2285 public static object ChangeType (object value, Type conversionType, out bool error)
2287 IConvertible convert_value = value as IConvertible;
2289 if (convert_value == null){
2295 // We must use Type.Equals() here since `conversionType' is
2296 // the TypeBuilder created version of a system type and not
2297 // the system type itself. You cannot use Type.GetTypeCode()
2298 // on such a type - it'd always return TypeCode.Object.
2302 if (conversionType.Equals (typeof (Boolean)))
2303 return (object)(convert_value.ToBoolean (nf_provider));
2304 else if (conversionType.Equals (typeof (Byte)))
2305 return (object)(convert_value.ToByte (nf_provider));
2306 else if (conversionType.Equals (typeof (Char)))
2307 return (object)(convert_value.ToChar (nf_provider));
2308 else if (conversionType.Equals (typeof (DateTime)))
2309 return (object)(convert_value.ToDateTime (nf_provider));
2310 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2311 return (object)(convert_value.ToDecimal (nf_provider));
2312 else if (conversionType.Equals (typeof (Double)))
2313 return (object)(convert_value.ToDouble (nf_provider));
2314 else if (conversionType.Equals (typeof (Int16)))
2315 return (object)(convert_value.ToInt16 (nf_provider));
2316 else if (conversionType.Equals (typeof (Int32)))
2317 return (object)(convert_value.ToInt32 (nf_provider));
2318 else if (conversionType.Equals (typeof (Int64)))
2319 return (object)(convert_value.ToInt64 (nf_provider));
2320 else if (conversionType.Equals (typeof (SByte)))
2321 return (object)(convert_value.ToSByte (nf_provider));
2322 else if (conversionType.Equals (typeof (Single)))
2323 return (object)(convert_value.ToSingle (nf_provider));
2324 else if (conversionType.Equals (typeof (String)))
2325 return (object)(convert_value.ToString (nf_provider));
2326 else if (conversionType.Equals (typeof (UInt16)))
2327 return (object)(convert_value.ToUInt16 (nf_provider));
2328 else if (conversionType.Equals (typeof (UInt32)))
2329 return (object)(convert_value.ToUInt32 (nf_provider));
2330 else if (conversionType.Equals (typeof (UInt64)))
2331 return (object)(convert_value.ToUInt64 (nf_provider));
2332 else if (conversionType.Equals (typeof (Object)))
2333 return (object)(value);
2343 // This is needed, because enumerations from assemblies
2344 // do not report their underlyingtype, but they report
2347 public static Type EnumToUnderlying (Type t)
2349 if (t == TypeManager.enum_type)
2352 t = t.UnderlyingSystemType;
2353 if (!TypeManager.IsEnumType (t))
2356 if (t is TypeBuilder) {
2357 // slow path needed to compile corlib
2358 if (t == TypeManager.bool_type ||
2359 t == TypeManager.byte_type ||
2360 t == TypeManager.sbyte_type ||
2361 t == TypeManager.char_type ||
2362 t == TypeManager.short_type ||
2363 t == TypeManager.ushort_type ||
2364 t == TypeManager.int32_type ||
2365 t == TypeManager.uint32_type ||
2366 t == TypeManager.int64_type ||
2367 t == TypeManager.uint64_type)
2370 TypeCode tc = Type.GetTypeCode (t);
2373 case TypeCode.Boolean:
2374 return TypeManager.bool_type;
2376 return TypeManager.byte_type;
2377 case TypeCode.SByte:
2378 return TypeManager.sbyte_type;
2380 return TypeManager.char_type;
2381 case TypeCode.Int16:
2382 return TypeManager.short_type;
2383 case TypeCode.UInt16:
2384 return TypeManager.ushort_type;
2385 case TypeCode.Int32:
2386 return TypeManager.int32_type;
2387 case TypeCode.UInt32:
2388 return TypeManager.uint32_type;
2389 case TypeCode.Int64:
2390 return TypeManager.int64_type;
2391 case TypeCode.UInt64:
2392 return TypeManager.uint64_type;
2394 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2398 // When compiling corlib and called with one of the core types, return
2399 // the corresponding typebuilder for that type.
2401 public static Type TypeToCoreType (Type t)
2403 if (RootContext.StdLib || (t is TypeBuilder))
2406 TypeCode tc = Type.GetTypeCode (t);
2409 case TypeCode.Boolean:
2410 return TypeManager.bool_type;
2412 return TypeManager.byte_type;
2413 case TypeCode.SByte:
2414 return TypeManager.sbyte_type;
2416 return TypeManager.char_type;
2417 case TypeCode.Int16:
2418 return TypeManager.short_type;
2419 case TypeCode.UInt16:
2420 return TypeManager.ushort_type;
2421 case TypeCode.Int32:
2422 return TypeManager.int32_type;
2423 case TypeCode.UInt32:
2424 return TypeManager.uint32_type;
2425 case TypeCode.Int64:
2426 return TypeManager.int64_type;
2427 case TypeCode.UInt64:
2428 return TypeManager.uint64_type;
2429 case TypeCode.Single:
2430 return TypeManager.float_type;
2431 case TypeCode.Double:
2432 return TypeManager.double_type;
2433 case TypeCode.String:
2434 return TypeManager.string_type;
2435 case TypeCode.Decimal:
2436 return TypeManager.decimal_type;
2438 if (t == typeof (void))
2439 return TypeManager.void_type;
2440 if (t == typeof (object))
2441 return TypeManager.object_type;
2442 if (t == typeof (System.Type))
2443 return TypeManager.type_type;
2444 if (t == typeof (System.IntPtr))
2445 return TypeManager.intptr_type;
2451 /// Utility function that can be used to probe whether a type
2452 /// is managed or not.
2454 public static bool VerifyUnManaged (Type t, Location loc)
2456 if (IsUnmanagedType (t))
2459 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2466 /// Returns the name of the indexer in a given type.
2469 /// The default is not always `Item'. The user can change this behaviour by
2470 /// using the IndexerNameAttribute in the container.
2471 /// For example, the String class indexer is named `Chars' not `Item'
2473 public static string IndexerPropertyName (Type t)
2475 t = DropGenericTypeArguments (t);
2476 if (t is TypeBuilder) {
2477 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2478 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2481 System.Attribute attr = System.Attribute.GetCustomAttribute (
2482 t, TypeManager.default_member_type);
2484 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2485 return dma.MemberName;
2488 return TypeContainer.DefaultIndexerName;
2491 static MethodInfo declare_local_method = null;
2493 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2495 if (declare_local_method == null){
2496 declare_local_method = typeof (ILGenerator).GetMethod (
2498 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2500 new Type [] { typeof (Type), typeof (bool)},
2502 if (declare_local_method == null){
2503 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2504 return ig.DeclareLocal (t);
2507 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2510 private static bool IsSignatureEqual (Type a, Type b)
2513 /// Consider the following example (bug #77674):
2515 /// public abstract class A
2517 /// public abstract T Foo<T> ();
2520 /// public abstract class B : A
2522 /// public override U Foo<T> ()
2523 /// { return default (U); }
2526 /// Here, `T' and `U' are method type parameters from different methods
2527 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2529 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2530 /// we need to do a signature based comparision and consider them equal.
2536 if (a.IsGenericParameter && b.IsGenericParameter &&
2537 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2538 return a.GenericParameterPosition == b.GenericParameterPosition;
2542 if (a.IsArray && b.IsArray) {
2543 if (a.GetArrayRank () != b.GetArrayRank ())
2546 return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2549 if (a.IsByRef && b.IsByRef)
2550 return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2553 if (a.IsGenericType && b.IsGenericType) {
2554 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2557 Type[] aargs = a.GetGenericArguments ();
2558 Type[] bargs = b.GetGenericArguments ();
2560 if (aargs.Length != bargs.Length)
2563 for (int i = 0; i < aargs.Length; i++) {
2564 if (!IsSignatureEqual (aargs [i], bargs [i]))
2576 // Returns whether the array of memberinfos contains the given method
2578 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2580 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2582 foreach (MethodBase method in array) {
2583 if (method.Name != new_method.Name)
2586 if (method is MethodInfo && new_method is MethodInfo)
2587 if (!IsSignatureEqual (((MethodInfo) method).ReturnType,
2588 ((MethodInfo) new_method).ReturnType))
2592 Type [] old_args = TypeManager.GetParameterData (method).Types;
2593 int old_count = old_args.Length;
2596 if (new_args.Length != old_count)
2599 for (i = 0; i < old_count; i++){
2600 if (!IsSignatureEqual (old_args [i], new_args [i]))
2613 // We copy methods from `new_members' into `target_list' if the signature
2614 // for the method from in the new list does not exist in the target_list
2616 // The name is assumed to be the same.
2618 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2620 if (target_list == null){
2621 target_list = new ArrayList ();
2623 foreach (MemberInfo mi in new_members){
2624 if (mi is MethodBase)
2625 target_list.Add (mi);
2630 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2631 target_list.CopyTo (target_array, 0);
2633 foreach (MemberInfo mi in new_members){
2634 MethodBase new_method = (MethodBase) mi;
2636 if (!ArrayContainsMethod (target_array, new_method))
2637 target_list.Add (new_method);
2642 // This method always return false for non-generic compiler,
2643 // while Type.IsGenericParameter is returned if it is supported.
2644 public static bool IsGenericParameter (Type type)
2647 return type.IsGenericParameter;
2653 public static int GenericParameterPosition (Type type)
2656 return type.GenericParameterPosition;
2658 throw new InternalErrorException ("should not be called");
2662 public static bool IsGenericType (Type type)
2665 return type.IsGenericType;
2672 public static bool IsEqual (Type a, Type b)
2674 return a.Equals (b);
2677 public static Type DropGenericTypeArguments (Type t)
2682 public static MethodBase DropGenericMethodArguments (MethodBase m)
2688 public static int GetNumberOfTypeArguments (Type t)
2691 if (t.IsGenericParameter)
2693 DeclSpace tc = LookupDeclSpace (t);
2695 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2697 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2704 /// Check whether `type' and `parent' are both instantiations of the same
2705 /// generic type. Note that we do not check the type parameters here.
2707 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2709 int tcount = GetNumberOfTypeArguments (type);
2710 int pcount = GetNumberOfTypeArguments (parent);
2712 if (tcount != pcount)
2715 type = DropGenericTypeArguments (type);
2716 parent = DropGenericTypeArguments (parent);
2718 return type.Equals (parent);
2721 #region MemberLookup implementation
2724 // Whether we allow private members in the result (since FindMembers
2725 // uses NonPublic for both protected and private), we need to distinguish.
2728 internal class Closure {
2729 internal bool private_ok;
2731 // Who is invoking us and which type is being queried currently.
2732 internal Type invocation_type;
2733 internal Type qualifier_type;
2735 // The assembly that defines the type is that is calling us
2736 internal Assembly invocation_assembly;
2737 internal IList almost_match;
2739 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2741 if (invocation_type == null)
2744 if (is_static && qualifier_type == null)
2745 // It resolved from a simple name, so it should be visible.
2748 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2751 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2752 if (!IsFamilyAccessible (t, m.DeclaringType))
2755 // Although a derived class can access protected members of its base class
2756 // it cannot do so through an instance of the base class (CS1540).
2757 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2758 if (is_static || qualifier_type == null ||
2759 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2760 IsFamilyAccessible (qualifier_type, t))
2764 if (almost_match != null)
2765 almost_match.Add (m);
2771 // This filter filters by name + whether it is ok to include private
2772 // members in the search
2774 internal bool Filter (MemberInfo m, object filter_criteria)
2777 // Hack: we know that the filter criteria will always be in the
2778 // `closure' // fields.
2781 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2784 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2785 (invocation_type != null) &&
2786 IsPrivateAccessible (m.DeclaringType, invocation_type))
2790 // Ugly: we need to find out the type of `m', and depending
2791 // on this, tell whether we accept or not
2793 if (m is MethodBase){
2794 MethodBase mb = (MethodBase) m;
2795 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2797 if (ma == MethodAttributes.Public)
2800 if (ma == MethodAttributes.Private)
2801 return private_ok ||
2802 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2803 IsNestedChildOf (invocation_type, m.DeclaringType);
2805 if (invocation_assembly == mb.DeclaringType.Assembly ||
2806 TypeManager.IsFriendAssembly (mb.DeclaringType.Assembly)) {
2807 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2810 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2814 // Family, FamORAssem or FamANDAssem
2815 return CheckValidFamilyAccess (mb.IsStatic, m);
2818 if (m is FieldInfo){
2819 FieldInfo fi = (FieldInfo) m;
2820 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2822 if (fa == FieldAttributes.Public)
2825 if (fa == FieldAttributes.Private)
2826 return private_ok ||
2827 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2828 IsNestedChildOf (invocation_type, m.DeclaringType);
2830 if ((invocation_assembly == fi.DeclaringType.Assembly) ||
2831 (invocation_assembly == null) ||
2832 TypeManager.IsFriendAssembly (fi.DeclaringType.Assembly)) {
2833 if ((fa == FieldAttributes.Assembly) ||
2834 (fa == FieldAttributes.FamORAssem))
2837 if ((fa == FieldAttributes.Assembly) ||
2838 (fa == FieldAttributes.FamANDAssem))
2842 // Family, FamORAssem or FamANDAssem
2843 return CheckValidFamilyAccess (fi.IsStatic, m);
2847 // EventInfos and PropertyInfos, return true because they lack
2848 // permission information, so we need to check later on the methods.
2854 static Closure closure = new Closure ();
2855 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2858 // Looks up a member called `name' in the `queried_type'. This lookup
2859 // is done by code that is contained in the definition for `invocation_type'
2860 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2862 // `invocation_type' is used to check whether we're allowed to access the requested
2863 // member wrt its protection level.
2865 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2866 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2867 // is B and qualifier_type is A). This is used to do the CS1540 check.
2869 // When resolving a SimpleName, `qualifier_type' is null.
2871 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2872 // the same than `queried_type' - except when we're being called from BaseAccess;
2873 // in this case, `invocation_type' is the current type and `queried_type' the base
2874 // type, so this'd normally trigger a CS1540.
2876 // The binding flags are `bf' and the kind of members being looked up are `mt'
2878 // The return value always includes private members which code in `invocation_type'
2879 // is allowed to access (using the specified `qualifier_type' if given); only use
2880 // BindingFlags.NonPublic to bypass the permission check.
2882 // The 'almost_match' argument is used for reporting error CS1540.
2884 // Returns an array of a single element for everything but Methods/Constructors
2885 // that might return multiple matches.
2887 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2888 Type queried_type, MemberTypes mt,
2889 BindingFlags original_bf, string name, IList almost_match)
2891 Timer.StartTimer (TimerType.MemberLookup);
2893 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2894 queried_type, mt, original_bf, name, almost_match);
2896 Timer.StopTimer (TimerType.MemberLookup);
2901 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2902 Type queried_type, MemberTypes mt,
2903 BindingFlags original_bf, string name, IList almost_match)
2905 BindingFlags bf = original_bf;
2907 ArrayList method_list = null;
2908 Type current_type = queried_type;
2909 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2910 bool skip_iface_check = true, used_cache = false;
2911 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2913 closure.invocation_type = invocation_type;
2914 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2915 closure.qualifier_type = qualifier_type;
2916 closure.almost_match = almost_match;
2918 // This is from the first time we find a method
2919 // in most cases, we do not actually find a method in the base class
2920 // so we can just ignore it, and save the arraylist allocation
2921 MemberInfo [] first_members_list = null;
2922 bool use_first_members_list = false;
2928 // `NonPublic' is lame, because it includes both protected and
2929 // private methods, so we need to control this behavior by
2930 // explicitly tracking if a private method is ok or not.
2932 // The possible cases are:
2933 // public, private and protected (internal does not come into the
2936 if ((invocation_type != null) &&
2937 ((invocation_type == current_type) ||
2938 IsNestedChildOf (invocation_type, current_type)) ||
2940 bf = original_bf | BindingFlags.NonPublic;
2944 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2946 Timer.StopTimer (TimerType.MemberLookup);
2948 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2950 Timer.StartTimer (TimerType.MemberLookup);
2953 // When queried for an interface type, the cache will automatically check all
2954 // inherited members, so we don't need to do this here. However, this only
2955 // works if we already used the cache in the first iteration of this loop.
2957 // If we used the cache in any further iteration, we can still terminate the
2958 // loop since the cache always looks in all base classes.
2964 skip_iface_check = false;
2966 if (current_type == TypeManager.object_type)
2969 current_type = current_type.BaseType;
2972 // This happens with interfaces, they have a null
2973 // basetype. Look members up in the Object class.
2975 if (current_type == null) {
2976 current_type = TypeManager.object_type;
2981 if (list.Length == 0)
2985 // Events and types are returned by both `static' and `instance'
2986 // searches, which means that our above FindMembers will
2987 // return two copies of the same.
2989 if (list.Length == 1 && !(list [0] is MethodBase)){
2994 // Multiple properties: we query those just to find out the indexer
2997 if (list [0] is PropertyInfo)
3001 // We found an event: the cache lookup returns both the event and
3002 // its private field.
3004 if (list [0] is EventInfo) {
3005 if ((list.Length == 2) && (list [1] is FieldInfo))
3006 return new MemberInfo [] { list [0] };
3012 // We found methods, turn the search into "method scan"
3016 if (first_members_list != null) {
3017 if (use_first_members_list) {
3018 method_list = CopyNewMethods (method_list, first_members_list);
3019 use_first_members_list = false;
3022 method_list = CopyNewMethods (method_list, list);
3024 first_members_list = list;
3025 use_first_members_list = true;
3026 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3028 } while (searching);
3030 if (use_first_members_list)
3031 return first_members_list;
3033 if (method_list != null && method_list.Count > 0) {
3034 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3037 // This happens if we already used the cache in the first iteration, in this case
3038 // the cache already looked in all interfaces.
3040 if (skip_iface_check)
3044 // Interfaces do not list members they inherit, so we have to
3047 if (!queried_type.IsInterface)
3050 if (queried_type.IsArray)
3051 queried_type = TypeManager.array_type;
3053 Type [] ifaces = GetInterfaces (queried_type);
3057 foreach (Type itype in ifaces){
3060 x = MemberLookup (null, null, itype, mt, bf, name, null);
3068 // Tests whether external method is really special
3069 public static bool IsSpecialMethod (MethodBase mb)
3071 string name = mb.Name;
3072 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
3073 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
3075 if (name.StartsWith ("add_"))
3076 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
3078 if (name.StartsWith ("remove_"))
3079 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
3081 if (name.StartsWith ("op_")){
3082 foreach (string oname in Unary.oper_names) {
3087 foreach (string oname in Binary.oper_names) {
3100 /// There is exactly one instance of this class per type.
3102 public sealed class TypeHandle : IMemberContainer {
3103 public readonly IMemberContainer BaseType;
3105 readonly int id = ++next_id;
3106 static int next_id = 0;
3108 static TypeHandle ()
3114 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3115 /// a TypeHandle yet, a new instance of it is created. This static method
3116 /// ensures that we'll only have one TypeHandle instance per type.
3118 private static TypeHandle GetTypeHandle (Type t)
3120 TypeHandle handle = (TypeHandle) type_hash [t];
3124 handle = new TypeHandle (t);
3125 type_hash.Add (t, handle);
3129 public static MemberCache GetMemberCache (Type t)
3131 return GetTypeHandle (t).MemberCache;
3134 public static void CleanUp ()
3139 public static void Reset ()
3141 type_hash = new PtrHashtable ();
3145 /// Returns the TypeHandle for TypeManager.object_type.
3147 public static IMemberContainer ObjectType {
3149 if (object_type != null)
3152 object_type = GetTypeHandle (TypeManager.object_type);
3159 /// Returns the TypeHandle for TypeManager.array_type.
3161 public static IMemberContainer ArrayType {
3163 if (array_type != null)
3166 array_type = GetTypeHandle (TypeManager.array_type);
3172 private static PtrHashtable type_hash;
3174 private static TypeHandle object_type = null;
3175 private static TypeHandle array_type = null;
3178 private string full_name;
3179 private bool is_interface;
3180 private MemberCache member_cache;
3181 private MemberCache base_cache;
3183 private TypeHandle (Type type)
3186 #if MS_COMPATIBLE && GMCS_SOURCE
3187 if (type.IsGenericType)
3188 this.type = this.type.GetGenericTypeDefinition ();
3190 full_name = type.FullName != null ? type.FullName : type.Name;
3191 if (type.BaseType != null) {
3192 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3193 BaseType = base_cache.Container;
3194 } else if (type.IsInterface)
3195 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3196 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3197 this.member_cache = new MemberCache (this);
3200 // IMemberContainer methods
3202 public string Name {
3214 public MemberCache BaseCache {
3220 public bool IsInterface {
3222 return is_interface;
3226 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3228 MemberInfo [] members;
3230 if (type is GenericTypeParameterBuilder)
3231 return MemberList.Empty;
3233 if (mt == MemberTypes.Event)
3234 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3236 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3238 Array.Reverse (members);
3240 return new MemberList (members);
3243 // IMemberFinder methods
3245 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3246 MemberFilter filter, object criteria)
3248 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3251 public MemberCache MemberCache {
3253 return member_cache;
3257 public override string ToString ()
3259 if (BaseType != null)
3260 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3262 return "TypeHandle (" + id + "," + Name + ")";