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 runtime_field_handle_type;
75 static public Type runtime_argument_handle_type;
76 static public Type attribute_type;
77 static public Type attribute_usage_type;
78 static public Type decimal_constant_attribute_type;
79 static public Type dllimport_type;
80 static public Type unverifiable_code_type;
81 static public Type methodimpl_attr_type;
82 static public Type marshal_as_attr_type;
83 static public Type param_array_type;
84 static public Type void_ptr_type;
85 static public Type indexer_name_type;
86 static public Type exception_type;
87 static public Type invalid_operation_exception_type;
88 static public Type not_supported_exception_type;
89 static public Type obsolete_attribute_type;
90 static public Type conditional_attribute_type;
91 static public Type in_attribute_type;
92 static public Type out_attribute_type;
93 static public Type anonymous_method_type;
94 static public Type cls_compliant_attribute_type;
95 static public Type typed_reference_type;
96 static public Type arg_iterator_type;
97 static public Type mbr_type;
98 static public Type struct_layout_attribute_type;
99 static public Type field_offset_attribute_type;
100 static public Type security_attr_type;
101 static public Type required_attr_type;
102 static public Type guid_attr_type;
103 static public Type assembly_culture_attribute_type;
104 static public Type coclass_attr_type;
105 static public Type comimport_attr_type;
110 static internal Type runtime_compatibility_attr_type;
111 static internal Type compiler_generated_attr_type;
112 static internal Type fixed_buffer_attr_type;
113 static internal Type default_charset_type;
114 static internal Type internals_visible_attr_type;
117 // An empty array of types
119 static public Type [] NoTypes;
120 static public TypeExpr [] NoTypeExprs;
124 // Expressions representing the internal types. Used during declaration
127 static public TypeExpr system_object_expr, system_string_expr;
128 static public TypeExpr system_boolean_expr, system_decimal_expr;
129 static public TypeExpr system_single_expr, system_double_expr;
130 static public TypeExpr system_sbyte_expr, system_byte_expr;
131 static public TypeExpr system_int16_expr, system_uint16_expr;
132 static public TypeExpr system_int32_expr, system_uint32_expr;
133 static public TypeExpr system_int64_expr, system_uint64_expr;
134 static public TypeExpr system_char_expr, system_void_expr;
135 static public TypeExpr system_asynccallback_expr;
136 static public TypeExpr system_iasyncresult_expr;
137 static public TypeExpr system_valuetype_expr;
138 static public TypeExpr system_intptr_expr;
141 // This is only used when compiling corlib
143 static public Type system_int32_type;
144 static public Type system_array_type;
145 static public Type system_type_type;
146 static public Type system_assemblybuilder_type;
147 static public MethodInfo system_int_array_get_length;
148 static public MethodInfo system_int_array_get_rank;
149 static public MethodInfo system_object_array_clone;
150 static public MethodInfo system_int_array_get_length_int;
151 static public MethodInfo system_int_array_get_lower_bound_int;
152 static public MethodInfo system_int_array_get_upper_bound_int;
153 static public MethodInfo system_void_array_copyto_array_int;
157 // Internal, not really used outside
159 static Type runtime_helpers_type;
162 // These methods are called by code generated by the compiler
164 static public MethodInfo string_concat_string_string;
165 static public MethodInfo string_concat_string_string_string;
166 static public MethodInfo string_concat_string_string_string_string;
167 static public MethodInfo string_concat_string_dot_dot_dot;
168 static public MethodInfo string_concat_object_object;
169 static public MethodInfo string_concat_object_object_object;
170 static public MethodInfo string_concat_object_dot_dot_dot;
171 static public MethodInfo string_isinterneted_string;
172 static public MethodInfo system_type_get_type_from_handle;
173 static public MethodInfo bool_movenext_void;
174 static public MethodInfo ienumerable_getenumerator_void;
175 static public MethodInfo void_reset_void;
176 static public MethodInfo void_dispose_void;
177 static public MethodInfo void_monitor_enter_object;
178 static public MethodInfo void_monitor_exit_object;
179 static public MethodInfo void_initializearray_array_fieldhandle;
180 static public MethodInfo int_getlength_int;
181 static public MethodInfo delegate_combine_delegate_delegate;
182 static public MethodInfo delegate_remove_delegate_delegate;
183 static public MethodInfo int_get_offset_to_string_data;
184 static public MethodInfo int_array_get_length;
185 static public MethodInfo int_array_get_rank;
186 static public MethodInfo object_array_clone;
187 static public MethodInfo int_array_get_length_int;
188 static public MethodInfo int_array_get_lower_bound_int;
189 static public MethodInfo int_array_get_upper_bound_int;
190 static public MethodInfo void_array_copyto_array_int;
191 static public PropertyInfo ienumerator_getcurrent;
194 // The attribute constructors.
196 static public ConstructorInfo object_ctor;
197 static public 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;
209 static internal CustomAttributeBuilder compiler_generated_attr;
210 static internal ConstructorInfo fixed_buffer_attr_ctor;
212 static PtrHashtable builder_to_declspace;
214 static PtrHashtable builder_to_member_cache;
217 // Tracks the interfaces implemented by typebuilders. We only
218 // enter those who do implement or or more interfaces
220 static PtrHashtable builder_to_ifaces;
223 // Maps PropertyBuilder to a Type array that contains
224 // the arguments to the indexer
226 static Hashtable indexer_arguments;
229 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
231 static Hashtable method_params;
234 // A hash table from override methods to their base virtual method.
236 static Hashtable method_overrides;
239 // Keeps track of methods
242 static Hashtable builder_to_method;
245 // Contains all public types from referenced assemblies.
246 // This member is used only if CLS Compliance verification is required.
248 public static Hashtable AllClsTopLevelTypes;
250 static Hashtable fieldbuilders_to_fields;
251 static Hashtable fields;
253 static PtrHashtable assembly_internals_vis_attrs;
260 public static void CleanUp ()
262 // Lets get everything clean so that we can collect before generating code
263 builder_to_declspace = null;
264 builder_to_member_cache = null;
265 builder_to_ifaces = null;
266 indexer_arguments = null;
267 method_params = null;
268 builder_to_method = null;
271 fieldbuilders_to_fields = null;
273 priv_fields_events = null;
277 assembly_internals_vis_attrs = null;
280 TypeHandle.CleanUp ();
284 /// A filter for Findmembers that uses the Signature object to
287 static bool SignatureFilter (MemberInfo mi, object criteria)
289 Signature sig = (Signature) criteria;
291 if (!(mi is MethodBase))
294 if (mi.Name != sig.name)
297 int count = sig.args.Length;
299 if (mi is MethodBuilder || mi is ConstructorBuilder){
300 Type [] candidate_args = GetParameterData ((MethodBase) mi).Types;
302 if (candidate_args.Length != count)
305 for (int i = 0; i < count; i++)
306 if (candidate_args [i] != sig.args [i])
311 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
313 if (pars.Length != count)
316 for (int i = 0; i < count; i++)
317 if (pars [i].ParameterType != sig.args [i])
323 // A delegate that points to the filter above.
324 static MemberFilter signature_filter;
327 // These are expressions that represent some of the internal data types, used
330 static void InitExpressionTypes ()
332 system_object_expr = new TypeLookupExpression ("System.Object");
333 system_string_expr = new TypeLookupExpression ("System.String");
334 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
335 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
336 system_single_expr = new TypeLookupExpression ("System.Single");
337 system_double_expr = new TypeLookupExpression ("System.Double");
338 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
339 system_byte_expr = new TypeLookupExpression ("System.Byte");
340 system_int16_expr = new TypeLookupExpression ("System.Int16");
341 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
342 system_int32_expr = new TypeLookupExpression ("System.Int32");
343 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
344 system_int64_expr = new TypeLookupExpression ("System.Int64");
345 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
346 system_char_expr = new TypeLookupExpression ("System.Char");
347 system_void_expr = new TypeLookupExpression ("System.Void");
348 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
349 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
350 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
351 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
354 static TypeManager ()
358 signature_filter = new MemberFilter (SignatureFilter);
359 InitExpressionTypes ();
362 static public void Reset ()
364 builder_to_declspace = new PtrHashtable ();
365 builder_to_member_cache = new PtrHashtable ();
366 builder_to_method = new PtrHashtable ();
367 method_params = new PtrHashtable ();
368 method_overrides = new PtrHashtable ();
369 indexer_arguments = new PtrHashtable ();
370 builder_to_ifaces = new PtrHashtable ();
372 NoTypes = new Type [0];
373 NoTypeExprs = new TypeExpr [0];
375 fieldbuilders_to_fields = new Hashtable ();
376 fields = new Hashtable ();
377 type_hash = new DoubleHash ();
379 assembly_internals_vis_attrs = new PtrHashtable ();
384 public static void AddUserType (DeclSpace ds)
386 builder_to_declspace.Add (ds.TypeBuilder, ds);
390 // This entry point is used by types that we define under the covers
392 public static void RegisterBuilder (Type tb, Type [] ifaces)
395 builder_to_ifaces [tb] = ifaces;
398 public static void AddMethod (MethodBase builder, IMethodData method)
400 builder_to_method.Add (builder, method);
401 method_params.Add (builder, method.ParameterInfo);
404 public static IMethodData GetMethod (MethodBase builder)
406 return (IMethodData) builder_to_method [builder];
410 /// Returns the DeclSpace whose Type is `t' or null if there is no
411 /// DeclSpace for `t' (ie, the Type comes from a library)
413 public static DeclSpace LookupDeclSpace (Type t)
415 return builder_to_declspace [t] as DeclSpace;
419 /// Returns the TypeContainer whose Type is `t' or null if there is no
420 /// TypeContainer for `t' (ie, the Type comes from a library)
422 public static TypeContainer LookupTypeContainer (Type t)
424 return builder_to_declspace [t] as TypeContainer;
427 public static MemberCache LookupMemberCache (Type t)
429 if (t is TypeBuilder) {
430 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
431 if (container != null)
432 return container.MemberCache;
435 if (t is GenericTypeParameterBuilder) {
436 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
438 if (container != null)
439 return container.MemberCache;
442 return TypeHandle.GetMemberCache (t);
445 public static MemberCache LookupBaseInterfacesCache (Type t)
447 Type [] ifaces = t.GetInterfaces ();
449 if (ifaces != null && ifaces.Length == 1)
450 return LookupMemberCache (ifaces [0]);
452 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
453 MemberCache cache = builder_to_member_cache [t] as MemberCache;
457 cache = new MemberCache (ifaces);
458 builder_to_member_cache.Add (t, cache);
462 public static TypeContainer LookupInterface (Type t)
464 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
465 if ((tc == null) || (tc.Kind != Kind.Interface))
471 public static Delegate LookupDelegate (Type t)
473 return builder_to_declspace [t] as Delegate;
476 public static Class LookupClass (Type t)
478 return (Class) builder_to_declspace [t];
482 // We use this hash for multiple kinds of constructed types:
484 // (T, "&") Given T, get T &
485 // (T, "*") Given T, get T *
486 // (T, "[]") Given T and a array dimension, get T []
487 // (T, X) Given a type T and a simple name X, get the type T+X
489 // Accessibility tests, if necessary, should be done by the user
491 static DoubleHash type_hash = new DoubleHash ();
494 // Gets the reference to T version of the Type (T&)
496 public static Type GetReferenceType (Type t)
498 return t.MakeByRefType ();
502 // Gets the pointer to T version of the Type (T*)
504 public static Type GetPointerType (Type t)
506 return GetConstructedType (t, "*");
509 public static Type GetConstructedType (Type t, string dim)
512 if (type_hash.Lookup (t, dim, out ret))
515 ret = t.Module.GetType (t.ToString () + dim);
517 type_hash.Insert (t, dim, ret);
522 ret = GetReferenceType (t);
523 type_hash.Insert (t, dim, ret);
527 if (t.IsGenericParameter || t.IsGenericInstance) {
530 while ((pos < dim.Length) && (dim [pos] == '[')) {
533 if (dim [pos] == ']') {
534 result = result.MakeArrayType ();
537 if (pos < dim.Length)
540 type_hash.Insert (t, dim, result);
545 while (dim [pos] == ',') {
549 if ((dim [pos] != ']') || (pos != dim.Length-1))
552 result = result.MakeArrayType (rank + 1);
553 type_hash.Insert (t, dim, result);
558 type_hash.Insert (t, dim, null);
562 public static Type GetNestedType (Type t, string name)
565 if (!type_hash.Lookup (t, name, out ret)) {
566 ret = t.GetNestedType (name,
567 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
568 type_hash.Insert (t, name, ret);
574 /// Fills static table with exported types from all referenced assemblies.
575 /// This information is required for CLS Compliance tests.
577 public static void LoadAllImportedTypes ()
579 AllClsTopLevelTypes = new Hashtable (1500);
580 foreach (Assembly a in RootNamespace.Global.Assemblies) {
581 foreach (Type t in a.GetExportedTypes ()) {
582 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
587 public static bool NamespaceClash (string name, Location loc)
589 if (! RootNamespace.Global.IsNamespace (name))
592 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
597 /// Returns the C# name of a type if possible, or the full type name otherwise
599 static public string CSharpName (Type t)
601 string name = GetFullName (t);
603 return Regex.Replace (name,
605 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
606 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
607 @"Boolean|String|Void|Null)" +
609 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
612 static public string CSharpName (Type[] types)
614 StringBuilder sb = new StringBuilder ();
615 foreach (Type t in types) {
616 sb.Append (CSharpName (t));
619 sb.Remove (sb.Length - 1, 1);
620 return sb.ToString ();
623 static String CSharpNameMatch (Match match)
625 string s = match.Groups [1].Captures [0].Value;
627 Replace ("int32", "int").
628 Replace ("uint32", "uint").
629 Replace ("int16", "short").
630 Replace ("uint16", "ushort").
631 Replace ("int64", "long").
632 Replace ("uint64", "ulong").
633 Replace ("single", "float").
634 Replace ("boolean", "bool")
635 + match.Groups [2].Captures [0].Value;
639 /// Returns the signature of the method with full namespace classification
641 static public string GetFullNameSignature (MemberInfo mi)
643 PropertyInfo pi = mi as PropertyInfo;
645 MethodBase pmi = pi.GetGetMethod ();
647 pmi = pi.GetSetMethod ();
648 if (GetParameterData (pmi).Count > 0)
651 return (mi is MethodBase)
652 ? CSharpSignature (mi as MethodBase)
653 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
656 private static int GetFullName (Type t, StringBuilder sb)
660 if (!t.IsGenericType) {
661 sb.Append (t.FullName);
665 if (t.DeclaringType != null) {
666 pos = GetFullName (t.DeclaringType, sb);
668 sb.Append (RemoveGenericArity (t.Name));
670 sb.Append (RemoveGenericArity (t.FullName));
673 Type[] this_args = GetTypeArguments (t);
675 if (this_args.Length < pos)
676 throw new InternalErrorException (
677 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
678 if (this_args.Length == pos)
683 sb.Append (CSharpName (this_args [pos++]));
684 if (pos == this_args.Length)
692 public static string GetFullName (Type t)
694 if (t.IsGenericParameter)
696 if (!t.IsGenericType)
699 StringBuilder sb = new StringBuilder ();
700 int pos = GetFullName (t, sb);
702 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
703 return sb.ToString ();
706 static string RemoveGenericArity (string from)
708 int i = from.IndexOf ('`');
710 return from.Substring (0, i);
715 /// When we need to report accessors as well
717 static public string CSharpSignature (MethodBase mb)
719 return CSharpSignature (mb, false);
723 /// Returns the signature of the method
725 static public string CSharpSignature (MethodBase mb, bool show_accessor)
727 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
730 ParameterData iparams = GetParameterData (mb);
731 string parameters = iparams.GetSignatureForError ();
732 string accessor = "";
735 if (mb.IsSpecialName) {
736 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
737 if (ot != Operator.OpType.TOP) {
738 sig.Append ("operator ");
739 sig.Append (Operator.GetName (ot));
740 sig.Append (parameters);
741 return sig.ToString ();
744 if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
745 accessor = mb.Name.Substring (0, 3);
750 if (mb.IsSpecialName && !mb.IsConstructor) {
751 if (iparams.Count > (mb.Name.StartsWith ("get_") ? 0 : 1)) {
752 sig.Append ("this[");
754 sig.Append (parameters.Substring (1, parameters.Length - 2));
757 int before_ret_val = parameters.LastIndexOf (',');
758 if (before_ret_val < 0)
759 sig.Append (parameters.Substring (1, parameters.Length - 2));
761 sig.Append (parameters.Substring (1, before_ret_val - 1));
765 sig.Append (mb.Name.Substring (4));
768 if (mb.Name == ".ctor")
769 sig.Append (mb.DeclaringType.Name);
771 sig.Append (mb.Name);
773 if (mb.Mono_IsInflatedMethod || TypeManager.IsGenericMethod (mb)) {
774 Type[] args = mb.GetGenericArguments ();
776 for (int i = 0; i < args.Length; i++) {
779 sig.Append (args [i].Name);
784 sig.Append (parameters);
787 if (show_accessor && accessor.Length > 0) {
789 sig.Append (accessor);
792 return sig.ToString ();
795 public static string GetMethodName (MethodInfo m)
797 if (!IsGenericMethod (m))
800 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
803 static public string CSharpSignature (EventInfo ei)
805 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
809 /// Looks up a type, and aborts if it is not found. This is used
810 /// by types required by the compiler
812 static Type CoreLookupType (string ns_name, string name)
814 Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
815 FullNamedExpression fne = ns.Lookup (RootContext.Tree.Types, name, Location.Null);
816 Type t = fne == null ? null : fne.Type;
818 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
823 /// Returns the MethodInfo for a method named `name' defined
824 /// in type `t' which takes arguments of types `args'
826 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
830 BindingFlags flags = instance_and_static | BindingFlags.Public;
836 flags |= BindingFlags.NonPublic;
838 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
839 if (list.Count == 0) {
841 Report.Error (-19, "Can not find the core function `" + name + "'");
845 MethodInfo mi = list [0] as MethodInfo;
848 Report.Error (-19, "Can not find the core function `" + name + "'");
855 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
857 return GetMethod (t, name, args, false, report_errors);
860 static MethodInfo GetMethod (Type t, string name, Type [] args)
862 return GetMethod (t, name, args, true);
866 /// Returns the PropertyInfo for a property named `name' defined
869 public static PropertyInfo GetProperty (Type t, string name)
871 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
872 BindingFlags.Instance, Type.FilterName, name);
873 if (list.Count == 0) {
874 Report.Error (-19, "Can not find the core property `" + name + "'");
878 PropertyInfo pi = list [0] as PropertyInfo;
880 Report.Error (-19, "Can not find the core function `" + name + "'");
888 /// Returns the ConstructorInfo for "args"
890 public static ConstructorInfo GetConstructor (Type t, Type [] args)
898 list = FindMembers (t, MemberTypes.Constructor,
899 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
900 signature_filter, sig);
901 if (list.Count == 0){
902 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
906 ConstructorInfo ci = list [0] as ConstructorInfo;
908 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
915 public static void InitEnumUnderlyingTypes ()
918 int32_type = CoreLookupType ("System", "Int32");
919 int64_type = CoreLookupType ("System", "Int64");
920 uint32_type = CoreLookupType ("System", "UInt32");
921 uint64_type = CoreLookupType ("System", "UInt64");
922 byte_type = CoreLookupType ("System", "Byte");
923 sbyte_type = CoreLookupType ("System", "SByte");
924 short_type = CoreLookupType ("System", "Int16");
925 ushort_type = CoreLookupType ("System", "UInt16");
929 /// The types have to be initialized after the initial
930 /// population of the type has happened (for example, to
931 /// bootstrap the corlib.dll
933 public static void InitCoreTypes ()
935 object_type = CoreLookupType ("System", "Object");
936 value_type = CoreLookupType ("System", "ValueType");
938 InitEnumUnderlyingTypes ();
940 char_type = CoreLookupType ("System", "Char");
941 string_type = CoreLookupType ("System", "String");
942 float_type = CoreLookupType ("System", "Single");
943 double_type = CoreLookupType ("System", "Double");
944 char_ptr_type = GetPointerType (char_type);
945 decimal_type = CoreLookupType ("System", "Decimal");
946 bool_type = CoreLookupType ("System", "Boolean");
947 enum_type = CoreLookupType ("System", "Enum");
949 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
950 delegate_type = CoreLookupType ("System", "Delegate");
952 array_type = CoreLookupType ("System", "Array");
953 void_type = CoreLookupType ("System", "Void");
954 type_type = CoreLookupType ("System", "Type");
956 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
957 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
958 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
959 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
960 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle");
961 asynccallback_type = CoreLookupType ("System", "AsyncCallback");
962 iasyncresult_type = CoreLookupType ("System", "IAsyncResult");
963 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator");
964 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable");
965 idisposable_type = CoreLookupType ("System", "IDisposable");
966 icloneable_type = CoreLookupType ("System", "ICloneable");
967 iconvertible_type = CoreLookupType ("System", "IConvertible");
968 monitor_type = CoreLookupType ("System.Threading", "Monitor");
969 intptr_type = CoreLookupType ("System", "IntPtr");
971 attribute_type = CoreLookupType ("System", "Attribute");
972 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
973 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
974 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
975 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
976 param_array_type = CoreLookupType ("System", "ParamArrayAttribute");
977 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
978 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
979 typed_reference_type = CoreLookupType ("System", "TypedReference");
980 arg_iterator_type = CoreLookupType ("System", "ArgIterator");
981 mbr_type = CoreLookupType ("System", "MarshalByRefObject");
982 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
984 unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
986 void_ptr_type = GetPointerType (void_type);
988 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
990 exception_type = CoreLookupType ("System", "Exception");
991 invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
992 not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
997 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
998 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
999 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
1000 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
1001 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
1002 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
1003 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1004 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
1005 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
1006 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
1007 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
1009 InitGenericCoreTypes ();
1014 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1015 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1016 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1017 internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1018 runtime_compatibility_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1020 // When compiling corlib, store the "real" types here.
1022 if (!RootContext.StdLib) {
1023 system_int32_type = typeof (System.Int32);
1024 system_array_type = typeof (System.Array);
1025 system_type_type = typeof (System.Type);
1026 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1028 Type [] void_arg = { };
1029 system_int_array_get_length = GetMethod (
1030 system_array_type, "get_Length", void_arg);
1031 system_int_array_get_rank = GetMethod (
1032 system_array_type, "get_Rank", void_arg);
1033 system_object_array_clone = GetMethod (
1034 system_array_type, "Clone", void_arg);
1036 Type [] system_int_arg = { system_int32_type };
1037 system_int_array_get_length_int = GetMethod (
1038 system_array_type, "GetLength", system_int_arg);
1039 system_int_array_get_upper_bound_int = GetMethod (
1040 system_array_type, "GetUpperBound", system_int_arg);
1041 system_int_array_get_lower_bound_int = GetMethod (
1042 system_array_type, "GetLowerBound", system_int_arg);
1044 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1045 system_void_array_copyto_array_int = GetMethod (
1046 system_array_type, "CopyTo", system_array_int_arg);
1048 Type [] system_3_type_arg = {
1049 system_type_type, system_type_type, system_type_type };
1050 Type [] system_4_type_arg = {
1051 system_type_type, system_type_type, system_type_type, system_type_type };
1053 MethodInfo set_corlib_type_builders = GetMethod (
1054 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1055 system_4_type_arg, true, false);
1057 if (set_corlib_type_builders != null) {
1058 object[] args = new object [4];
1059 args [0] = object_type;
1060 args [1] = value_type;
1061 args [2] = enum_type;
1062 args [3] = void_type;
1064 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1066 // Compatibility for an older version of the class libs.
1067 set_corlib_type_builders = GetMethod (
1068 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1069 system_3_type_arg, true, true);
1071 if (set_corlib_type_builders == null) {
1072 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1076 object[] args = new object [3];
1077 args [0] = object_type;
1078 args [1] = value_type;
1079 args [2] = enum_type;
1081 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1085 system_object_expr.Type = object_type;
1086 system_string_expr.Type = string_type;
1087 system_boolean_expr.Type = bool_type;
1088 system_decimal_expr.Type = decimal_type;
1089 system_single_expr.Type = float_type;
1090 system_double_expr.Type = double_type;
1091 system_sbyte_expr.Type = sbyte_type;
1092 system_byte_expr.Type = byte_type;
1093 system_int16_expr.Type = short_type;
1094 system_uint16_expr.Type = ushort_type;
1095 system_int32_expr.Type = int32_type;
1096 system_uint32_expr.Type = uint32_type;
1097 system_int64_expr.Type = int64_type;
1098 system_uint64_expr.Type = uint64_type;
1099 system_char_expr.Type = char_type;
1100 system_void_expr.Type = void_type;
1101 system_asynccallback_expr.Type = asynccallback_type;
1102 system_iasyncresult_expr.Type = iasyncresult_type;
1103 system_valuetype_expr.Type = value_type;
1106 // These are only used for compare purposes
1108 anonymous_method_type = typeof (AnonymousMethod);
1109 null_type = typeof (NullType);
1113 // The helper methods that are used by the compiler
1115 public static void InitCodeHelpers ()
1118 // Now load the default methods that we use.
1120 Type [] string_string = { string_type, string_type };
1121 string_concat_string_string = GetMethod (
1122 string_type, "Concat", string_string);
1123 Type [] string_string_string = { string_type, string_type, string_type };
1124 string_concat_string_string_string = GetMethod (
1125 string_type, "Concat", string_string_string);
1126 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1127 string_concat_string_string_string_string = GetMethod (
1128 string_type, "Concat", string_string_string_string);
1129 Type[] params_string = { GetConstructedType (string_type, "[]") };
1130 string_concat_string_dot_dot_dot = GetMethod (
1131 string_type, "Concat", params_string);
1133 Type [] object_object = { object_type, object_type };
1134 string_concat_object_object = GetMethod (
1135 string_type, "Concat", object_object);
1136 Type [] object_object_object = { object_type, object_type, object_type };
1137 string_concat_object_object_object = GetMethod (
1138 string_type, "Concat", object_object_object);
1139 Type[] params_object = { GetConstructedType (object_type, "[]") };
1140 string_concat_object_dot_dot_dot = GetMethod (
1141 string_type, "Concat", params_object);
1143 Type [] string_ = { string_type };
1144 string_isinterneted_string = GetMethod (
1145 string_type, "IsInterned", string_);
1147 Type [] runtime_type_handle = { runtime_handle_type };
1148 system_type_get_type_from_handle = GetMethod (
1149 type_type, "GetTypeFromHandle", runtime_type_handle);
1151 Type [] delegate_delegate = { delegate_type, delegate_type };
1152 delegate_combine_delegate_delegate = GetMethod (
1153 delegate_type, "Combine", delegate_delegate);
1155 delegate_remove_delegate_delegate = GetMethod (
1156 delegate_type, "Remove", delegate_delegate);
1161 Type [] void_arg = { };
1162 ienumerator_getcurrent = GetProperty (
1163 ienumerator_type, "Current");
1164 bool_movenext_void = GetMethod (
1165 ienumerator_type, "MoveNext", void_arg);
1166 void_reset_void = GetMethod (
1167 ienumerator_type, "Reset", void_arg);
1168 void_dispose_void = GetMethod (
1169 idisposable_type, "Dispose", void_arg);
1170 int_get_offset_to_string_data = GetMethod (
1171 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1172 int_array_get_length = GetMethod (
1173 array_type, "get_Length", void_arg);
1174 int_array_get_rank = GetMethod (
1175 array_type, "get_Rank", void_arg);
1176 ienumerable_getenumerator_void = GetMethod (
1177 ienumerable_type, "GetEnumerator", void_arg);
1182 Type [] int_arg = { int32_type };
1183 int_array_get_length_int = GetMethod (
1184 array_type, "GetLength", int_arg);
1185 int_array_get_upper_bound_int = GetMethod (
1186 array_type, "GetUpperBound", int_arg);
1187 int_array_get_lower_bound_int = GetMethod (
1188 array_type, "GetLowerBound", int_arg);
1191 // System.Array methods
1193 object_array_clone = GetMethod (
1194 array_type, "Clone", void_arg);
1195 Type [] array_int_arg = { array_type, int32_type };
1196 void_array_copyto_array_int = GetMethod (
1197 array_type, "CopyTo", array_int_arg);
1202 Type [] object_arg = { object_type };
1203 void_monitor_enter_object = GetMethod (
1204 monitor_type, "Enter", object_arg);
1205 void_monitor_exit_object = GetMethod (
1206 monitor_type, "Exit", object_arg);
1208 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1210 void_initializearray_array_fieldhandle = GetMethod (
1211 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1216 int_getlength_int = GetMethod (
1217 array_type, "GetLength", int_arg);
1220 // Decimal constructors
1222 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1223 void_decimal_ctor_five_args = GetConstructor (
1224 decimal_type, dec_arg);
1226 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1231 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1232 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1233 default_member_ctor = GetConstructor (default_member_type, string_);
1235 Type[] short_arg = { short_type };
1236 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1238 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1239 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1241 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1247 compiler_generated_attr = new CustomAttributeBuilder (
1248 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1250 Type[] type_int_arg = { type_type, int32_type };
1251 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1254 object_ctor = GetConstructor (object_type, void_arg);
1256 InitGenericCodeHelpers ();
1259 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1262 /// This is the "old", non-cache based FindMembers() function. We cannot use
1263 /// the cache here because there is no member name argument.
1265 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1266 MemberFilter filter, object criteria)
1268 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1271 // `builder_to_declspace' contains all dynamic types.
1275 Timer.StartTimer (TimerType.FindMembers);
1276 list = decl.FindMembers (mt, bf, filter, criteria);
1277 Timer.StopTimer (TimerType.FindMembers);
1282 // We have to take care of arrays specially, because GetType on
1283 // a TypeBuilder array will return a Type, not a TypeBuilder,
1284 // and we can not call FindMembers on this type.
1286 if (t.IsSubclassOf (TypeManager.array_type))
1287 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1289 if (t is GenericTypeParameterBuilder) {
1290 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1292 Timer.StartTimer (TimerType.FindMembers);
1293 MemberList list = tparam.FindMembers (
1294 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1295 Timer.StopTimer (TimerType.FindMembers);
1300 // Since FindMembers will not lookup both static and instance
1301 // members, we emulate this behaviour here.
1303 if ((bf & instance_and_static) == instance_and_static){
1304 MemberInfo [] i_members = t.FindMembers (
1305 mt, bf & ~BindingFlags.Static, filter, criteria);
1307 int i_len = i_members.Length;
1309 MemberInfo one = i_members [0];
1312 // If any of these are present, we are done!
1314 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1315 return new MemberList (i_members);
1318 MemberInfo [] s_members = t.FindMembers (
1319 mt, bf & ~BindingFlags.Instance, filter, criteria);
1321 int s_len = s_members.Length;
1322 if (i_len > 0 || s_len > 0)
1323 return new MemberList (i_members, s_members);
1326 return new MemberList (i_members);
1328 return new MemberList (s_members);
1332 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1337 /// This method is only called from within MemberLookup. It tries to use the member
1338 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1339 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1340 /// our return value will already contain all inherited members and the caller don't need
1341 /// to check base classes and interfaces anymore.
1343 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1344 string name, out bool used_cache)
1349 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1350 // and we can ask the DeclSpace for the MemberCache.
1352 if (t is TypeBuilder) {
1353 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1354 cache = decl.MemberCache;
1357 // If this DeclSpace has a MemberCache, use it.
1360 if (cache != null) {
1362 return cache.FindMembers (
1363 mt, bf, name, FilterWithClosure_delegate, null);
1366 // If there is no MemberCache, we need to use the "normal" FindMembers.
1367 // Note, this is a VERY uncommon route!
1370 Timer.StartTimer (TimerType.FindMembers);
1371 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1372 FilterWithClosure_delegate, name);
1373 Timer.StopTimer (TimerType.FindMembers);
1375 return (MemberInfo []) list;
1379 // We have to take care of arrays specially, because GetType on
1380 // a TypeBuilder array will return a Type, not a TypeBuilder,
1381 // and we can not call FindMembers on this type.
1383 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1385 return TypeHandle.ArrayType.MemberCache.FindMembers (
1386 mt, bf, name, FilterWithClosure_delegate, null);
1389 if (t is GenericTypeParameterBuilder) {
1390 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1393 Timer.StartTimer (TimerType.FindMembers);
1394 list = tparam.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1395 FilterWithClosure_delegate, name);
1396 Timer.StopTimer (TimerType.FindMembers);
1398 return (MemberInfo []) list;
1401 if (t.IsGenericInstance && (mt == MemberTypes.NestedType)) {
1403 // This happens if we're resolving a class'es base class and interfaces
1404 // in TypeContainer.DefineType(). At this time, the types aren't
1405 // populated yet, so we can't use the cache.
1407 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1408 FilterWithClosure_delegate, name);
1414 // This call will always succeed. There is exactly one TypeHandle instance per
1415 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1416 // the corresponding MemberCache.
1418 cache = TypeHandle.GetMemberCache (t);
1421 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1424 public static bool IsBuiltinType (Type t)
1426 t = TypeToCoreType (t);
1427 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1428 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1429 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1430 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1436 public static bool IsBuiltinType (TypeContainer tc)
1438 return IsBuiltinType (tc.TypeBuilder);
1442 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1443 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1445 public static bool IsPrimitiveType (Type t)
1447 return (t == int32_type || t == uint32_type ||
1448 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1449 t == char_type || t == short_type || t == bool_type ||
1450 t == sbyte_type || t == byte_type || t == ushort_type);
1453 public static bool IsDelegateType (Type t)
1455 t = DropGenericTypeArguments (t);
1456 if (t.IsSubclassOf (TypeManager.delegate_type))
1462 public static bool IsEnumType (Type t)
1464 if (builder_to_declspace [t] is Enum)
1470 public static bool IsBuiltinOrEnum (Type t)
1472 if (IsBuiltinType (t))
1481 public static bool IsNullType (Type t)
1483 return t == null_type;
1486 public static bool IsAttributeType (Type t)
1488 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1491 static Stack unmanaged_enclosing_types = new Stack (4);
1494 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1496 public static bool IsUnmanagedType (Type t)
1498 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1499 if (unmanaged_enclosing_types.Contains (t))
1502 // builtins that are not unmanaged types
1503 if (t == TypeManager.object_type || t == TypeManager.string_type)
1506 if (IsBuiltinOrEnum (t))
1509 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1513 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1517 if (!IsValueType (t))
1520 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1521 if (p.IsGenericTypeDefinition)
1525 unmanaged_enclosing_types.Push (t);
1529 if (t is TypeBuilder) {
1530 TypeContainer tc = LookupTypeContainer (t);
1531 if (tc.Fields != null){
1532 foreach (FieldMember f in tc.Fields){
1533 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1534 if ((f.ModFlags & Modifiers.STATIC) != 0)
1536 if (f.MemberType == null)
1538 if (!IsUnmanagedType (f.MemberType)){
1539 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1545 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1547 foreach (FieldInfo f in fields){
1548 if (!IsUnmanagedType (f.FieldType)){
1549 Report.SymbolRelatedToPreviousError (f);
1555 unmanaged_enclosing_types.Pop ();
1560 public static bool IsValueType (Type t)
1562 return t.IsGenericParameter || t.IsValueType;
1565 public static bool IsInterfaceType (Type t)
1567 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1571 return tc.Kind == Kind.Interface;
1574 public static bool IsSubclassOf (Type type, Type base_type)
1576 TypeParameter tparam = LookupTypeParameter (type);
1577 TypeParameter pparam = LookupTypeParameter (base_type);
1579 if ((tparam != null) && (pparam != null)) {
1580 if (tparam == pparam)
1583 return tparam.IsSubclassOf (base_type);
1587 if (IsEqual (type, base_type))
1590 type = type.BaseType;
1591 } while (type != null);
1596 public static bool IsPrivateAccessible (Type type, Type parent)
1598 if (type.Equals (parent))
1600 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1603 public static bool IsFamilyAccessible (Type type, Type parent)
1605 TypeParameter tparam = LookupTypeParameter (type);
1606 TypeParameter pparam = LookupTypeParameter (parent);
1608 if ((tparam != null) && (pparam != null)) {
1609 if (tparam == pparam)
1612 return tparam.IsSubclassOf (parent);
1616 if (IsInstantiationOfSameGenericType (type, parent))
1619 type = type.BaseType;
1620 } while (type != null);
1626 // Checks whether `type' is a subclass or nested child of `base_type'.
1628 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1631 if (IsFamilyAccessible (type, base_type))
1634 // Handle nested types.
1635 type = type.DeclaringType;
1636 } while (type != null);
1642 // Checks whether `type' is a nested child of `parent'.
1644 public static bool IsNestedChildOf (Type type, Type parent)
1646 if (IsEqual (type, parent))
1649 type = type.DeclaringType;
1650 while (type != null) {
1651 if (IsEqual (type, parent))
1654 type = type.DeclaringType;
1661 // Checks whether `extern_type' is friend of the output assembly
1663 public static bool IsFriendAssembly (Assembly assembly)
1665 if (assembly_internals_vis_attrs.Contains (assembly))
1666 return (bool)(assembly_internals_vis_attrs [assembly]);
1668 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1669 if (attrs.Length == 0) {
1670 assembly_internals_vis_attrs.Add (assembly, false);
1674 AssemblyName this_name = CodeGen.Assembly.Name;
1675 byte [] this_token = this_name.GetPublicKeyToken ();
1676 bool is_friend = false;
1677 foreach (InternalsVisibleToAttribute attr in attrs) {
1678 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1681 AssemblyName aname = null;
1683 aname = new AssemblyName (attr.AssemblyName);
1684 } catch (FileLoadException) {
1685 } catch (ArgumentException) {
1688 if (aname == null || aname.Name != this_name.Name)
1691 byte [] key_token = aname.GetPublicKeyToken ();
1692 if (key_token != null) {
1693 if (this_token == null) {
1694 // Same name, but key token is null
1695 Error_FriendAccessNameNotMatching (aname.FullName);
1699 if (!CompareKeyTokens (this_token, key_token))
1707 assembly_internals_vis_attrs.Add (assembly, is_friend);
1711 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1713 for (int i = 0; i < token1.Length; i++)
1714 if (token1 [i] != token2 [i])
1720 static void Error_FriendAccessNameNotMatching (string other_name)
1722 Report.Error (281, "Friend access was granted to `" + other_name +
1723 "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
1724 "'. Try adding a reference to `" + other_name +
1725 "' or change the output assembly name to match it");
1729 // Do the right thing when returning the element type of an
1730 // array type based on whether we are compiling corlib or not
1732 public static Type GetElementType (Type t)
1734 if (RootContext.StdLib)
1735 return t.GetElementType ();
1737 return TypeToCoreType (t.GetElementType ());
1741 /// This method is not implemented by MS runtime for dynamic types
1743 public static bool HasElementType (Type t)
1745 return t.IsArray || t.IsPointer || t.IsByRef;
1749 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1753 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1754 /// for anything which is dynamic, and we need this in a number of places,
1755 /// we register this information here, and use it afterwards.
1757 static public void RegisterMethod (MethodBase mb, Parameters ip)
1759 method_params.Add (mb, ip);
1762 static public ParameterData GetParameterData (MethodBase mb)
1764 ParameterData pd = (ParameterData)method_params [mb];
1766 if (mb is MethodBuilder || mb is ConstructorBuilder)
1767 throw new InternalErrorException ("Argument for Method not registered" + mb);
1769 pd = new ReflectionParameters (mb);
1770 method_params.Add (mb, pd);
1775 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1777 if (!method_overrides.Contains (override_method))
1778 method_overrides [override_method] = base_method;
1779 if (method_overrides [override_method] != base_method)
1780 throw new InternalErrorException ("Override mismatch: " + override_method);
1783 static public bool IsOverride (MethodBase m)
1785 return m.IsVirtual &&
1786 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1787 (m is MethodBuilder || method_overrides.Contains (m));
1790 static public MethodBase TryGetBaseDefinition (MethodBase m)
1792 return (MethodBase) method_overrides [m];
1796 /// Returns the argument types for an indexer based on its PropertyInfo
1798 /// For dynamic indexers, we use the compiler provided types, for
1799 /// indexers from existing assemblies we load them from GetParameters,
1800 /// and insert them into the cache
1802 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1804 if (indexer_arguments.Contains (indexer))
1805 return (Type []) indexer_arguments [indexer];
1806 else if (indexer is PropertyBuilder)
1807 // If we're a PropertyBuilder and not in the
1808 // `indexer_arguments' hash, then we're a property and
1812 ParameterInfo [] pi = indexer.GetIndexParameters ();
1813 // Property, not an indexer.
1817 Type [] types = new Type [c];
1819 for (int i = 0; i < c; i++)
1820 types [i] = pi [i].ParameterType;
1822 indexer_arguments.Add (indexer, types);
1827 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1829 fields.Add (fb, ic);
1832 public static IConstant GetConstant (FieldInfo fb)
1837 return (IConstant)fields [fb];
1840 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1842 if (fieldbuilders_to_fields.Contains (fb))
1845 fieldbuilders_to_fields.Add (fb, f);
1850 // The return value can be null; This will be the case for
1851 // auxiliary FieldBuilders created by the compiler that have no
1852 // real field being declared on the source code
1854 static public FieldBase GetField (FieldInfo fb)
1856 if (fb.DeclaringType.IsGenericInstance)
1857 fb = fb.Mono_GetGenericFieldDefinition ();
1859 return (FieldBase) fieldbuilders_to_fields [fb];
1862 static Hashtable events;
1864 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1867 events = new Hashtable ();
1869 if (!events.Contains (eb)) {
1870 events.Add (eb, new Pair (add, remove));
1874 static public MethodInfo GetAddMethod (EventInfo ei)
1876 if (ei is MyEventBuilder) {
1877 Pair pair = (Pair) events [ei];
1879 return (MethodInfo) pair.First;
1881 return ei.GetAddMethod (true);
1884 static public MethodInfo GetRemoveMethod (EventInfo ei)
1886 if (ei is MyEventBuilder) {
1887 Pair pair = (Pair) events [ei];
1889 return (MethodInfo) pair.Second;
1891 return ei.GetRemoveMethod (true);
1894 static Hashtable priv_fields_events;
1896 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1898 if (priv_fields_events == null)
1899 priv_fields_events = new Hashtable ();
1901 if (priv_fields_events.Contains (einfo))
1904 priv_fields_events.Add (einfo, builder);
1909 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1911 if (priv_fields_events == null)
1914 return (MemberInfo) priv_fields_events [ei];
1917 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1918 MethodBase set, Type[] args)
1920 indexer_arguments.Add (pb, args);
1925 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1927 Hashtable hash = new Hashtable ();
1928 return CheckStructCycles (tc, seen, hash);
1931 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1934 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1938 // `seen' contains all types we've already visited.
1940 if (seen.Contains (tc))
1942 seen.Add (tc, null);
1944 if (tc.Fields == null)
1947 foreach (FieldMember field in tc.Fields) {
1948 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1951 Type ftype = field.FieldBuilder.FieldType;
1952 TypeContainer ftc = LookupTypeContainer (ftype);
1956 if (hash.Contains (ftc)) {
1957 Report.Error (523, tc.Location,
1958 "Struct member `{0}.{1}' of type `{2}' " +
1959 "causes a cycle in the struct layout",
1960 tc.Name, field.Name, ftc.Name);
1965 // `hash' contains all types in the current path.
1967 hash.Add (tc, null);
1969 bool ok = CheckStructCycles (ftc, seen, hash);
1976 if (!seen.Contains (ftc))
1977 seen.Add (ftc, null);
1984 /// Given an array of interface types, expand and eliminate repeated ocurrences
1985 /// of an interface.
1989 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1992 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1994 ArrayList new_ifaces = new ArrayList ();
1996 foreach (TypeExpr iface in base_interfaces){
1997 TypeExpr texpr = iface.ResolveAsTypeTerminal (ec);
2001 Type itype = texpr.ResolveType (ec);
2003 if (new_ifaces.Contains (itype))
2006 new_ifaces.Add (itype);
2008 Type [] implementing = itype.GetInterfaces ();
2010 foreach (Type imp in implementing){
2011 if (!new_ifaces.Contains (imp))
2012 new_ifaces.Add (imp);
2015 Type [] ret = new Type [new_ifaces.Count];
2016 new_ifaces.CopyTo (ret, 0);
2020 public static Type[] ExpandInterfaces (Type [] base_interfaces)
2022 ArrayList new_ifaces = new ArrayList ();
2024 foreach (Type itype in base_interfaces){
2025 if (new_ifaces.Contains (itype))
2028 new_ifaces.Add (itype);
2030 Type [] implementing = itype.GetInterfaces ();
2032 foreach (Type imp in implementing){
2033 if (!new_ifaces.Contains (imp))
2034 new_ifaces.Add (imp);
2037 Type [] ret = new Type [new_ifaces.Count];
2038 new_ifaces.CopyTo (ret, 0);
2042 static PtrHashtable iface_cache = new PtrHashtable ();
2045 /// This function returns the interfaces in the type `t'. Works with
2046 /// both types and TypeBuilders.
2048 public static Type [] GetInterfaces (Type t)
2050 Type [] cached = iface_cache [t] as Type [];
2055 // The reason for catching the Array case is that Reflection.Emit
2056 // will not return a TypeBuilder for Array types of TypeBuilder types,
2057 // but will still throw an exception if we try to call GetInterfaces
2060 // Since the array interfaces are always constant, we return those for
2065 t = TypeManager.array_type;
2067 if ((t is TypeBuilder) || t.IsGenericInstance) {
2068 Type [] base_ifaces;
2070 if (t.BaseType == null)
2071 base_ifaces = NoTypes;
2073 base_ifaces = GetInterfaces (t.BaseType);
2075 if (t.IsGenericInstance)
2076 type_ifaces = t.GetInterfaces ();
2078 type_ifaces = (Type []) builder_to_ifaces [t];
2079 if (type_ifaces == null)
2080 type_ifaces = NoTypes;
2082 int base_count = base_ifaces.Length;
2083 Type [] result = new Type [base_count + type_ifaces.Length];
2084 base_ifaces.CopyTo (result, 0);
2085 type_ifaces.CopyTo (result, base_count);
2087 iface_cache [t] = result;
2089 } else if (t is GenericTypeParameterBuilder){
2090 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2091 if (type_ifaces == null)
2092 type_ifaces = NoTypes;
2094 iface_cache [t] = type_ifaces;
2097 Type[] ifaces = t.GetInterfaces ();
2098 iface_cache [t] = ifaces;
2104 // gets the interfaces that are declared explicitly on t
2106 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2108 return (Type []) builder_to_ifaces [t];
2112 /// The following is used to check if a given type implements an interface.
2113 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2115 public static bool ImplementsInterface (Type t, Type iface)
2120 // FIXME OPTIMIZATION:
2121 // as soon as we hit a non-TypeBuiler in the interface
2122 // chain, we could return, as the `Type.GetInterfaces'
2123 // will return all the interfaces implement by the type
2127 interfaces = GetInterfaces (t);
2129 if (interfaces != null){
2130 foreach (Type i in interfaces){
2137 } while (t != null);
2142 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2144 // This is a custom version of Convert.ChangeType() which works
2145 // with the TypeBuilder defined types when compiling corlib.
2146 public static object ChangeType (object value, Type conversionType, out bool error)
2148 IConvertible convert_value = value as IConvertible;
2150 if (convert_value == null){
2156 // We must use Type.Equals() here since `conversionType' is
2157 // the TypeBuilder created version of a system type and not
2158 // the system type itself. You cannot use Type.GetTypeCode()
2159 // on such a type - it'd always return TypeCode.Object.
2163 if (conversionType.Equals (typeof (Boolean)))
2164 return (object)(convert_value.ToBoolean (nf_provider));
2165 else if (conversionType.Equals (typeof (Byte)))
2166 return (object)(convert_value.ToByte (nf_provider));
2167 else if (conversionType.Equals (typeof (Char)))
2168 return (object)(convert_value.ToChar (nf_provider));
2169 else if (conversionType.Equals (typeof (DateTime)))
2170 return (object)(convert_value.ToDateTime (nf_provider));
2171 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2172 return (object)(convert_value.ToDecimal (nf_provider));
2173 else if (conversionType.Equals (typeof (Double)))
2174 return (object)(convert_value.ToDouble (nf_provider));
2175 else if (conversionType.Equals (typeof (Int16)))
2176 return (object)(convert_value.ToInt16 (nf_provider));
2177 else if (conversionType.Equals (typeof (Int32)))
2178 return (object)(convert_value.ToInt32 (nf_provider));
2179 else if (conversionType.Equals (typeof (Int64)))
2180 return (object)(convert_value.ToInt64 (nf_provider));
2181 else if (conversionType.Equals (typeof (SByte)))
2182 return (object)(convert_value.ToSByte (nf_provider));
2183 else if (conversionType.Equals (typeof (Single)))
2184 return (object)(convert_value.ToSingle (nf_provider));
2185 else if (conversionType.Equals (typeof (String)))
2186 return (object)(convert_value.ToString (nf_provider));
2187 else if (conversionType.Equals (typeof (UInt16)))
2188 return (object)(convert_value.ToUInt16 (nf_provider));
2189 else if (conversionType.Equals (typeof (UInt32)))
2190 return (object)(convert_value.ToUInt32 (nf_provider));
2191 else if (conversionType.Equals (typeof (UInt64)))
2192 return (object)(convert_value.ToUInt64 (nf_provider));
2193 else if (conversionType.Equals (typeof (Object)))
2194 return (object)(value);
2204 // This is needed, because enumerations from assemblies
2205 // do not report their underlyingtype, but they report
2208 public static Type EnumToUnderlying (Type t)
2210 if (t == TypeManager.enum_type)
2213 t = t.UnderlyingSystemType;
2214 if (!TypeManager.IsEnumType (t))
2217 if (t is TypeBuilder) {
2218 // slow path needed to compile corlib
2219 if (t == TypeManager.bool_type ||
2220 t == TypeManager.byte_type ||
2221 t == TypeManager.sbyte_type ||
2222 t == TypeManager.char_type ||
2223 t == TypeManager.short_type ||
2224 t == TypeManager.ushort_type ||
2225 t == TypeManager.int32_type ||
2226 t == TypeManager.uint32_type ||
2227 t == TypeManager.int64_type ||
2228 t == TypeManager.uint64_type)
2231 TypeCode tc = Type.GetTypeCode (t);
2234 case TypeCode.Boolean:
2235 return TypeManager.bool_type;
2237 return TypeManager.byte_type;
2238 case TypeCode.SByte:
2239 return TypeManager.sbyte_type;
2241 return TypeManager.char_type;
2242 case TypeCode.Int16:
2243 return TypeManager.short_type;
2244 case TypeCode.UInt16:
2245 return TypeManager.ushort_type;
2246 case TypeCode.Int32:
2247 return TypeManager.int32_type;
2248 case TypeCode.UInt32:
2249 return TypeManager.uint32_type;
2250 case TypeCode.Int64:
2251 return TypeManager.int64_type;
2252 case TypeCode.UInt64:
2253 return TypeManager.uint64_type;
2255 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2259 // When compiling corlib and called with one of the core types, return
2260 // the corresponding typebuilder for that type.
2262 public static Type TypeToCoreType (Type t)
2264 if (RootContext.StdLib || (t is TypeBuilder))
2267 TypeCode tc = Type.GetTypeCode (t);
2270 case TypeCode.Boolean:
2271 return TypeManager.bool_type;
2273 return TypeManager.byte_type;
2274 case TypeCode.SByte:
2275 return TypeManager.sbyte_type;
2277 return TypeManager.char_type;
2278 case TypeCode.Int16:
2279 return TypeManager.short_type;
2280 case TypeCode.UInt16:
2281 return TypeManager.ushort_type;
2282 case TypeCode.Int32:
2283 return TypeManager.int32_type;
2284 case TypeCode.UInt32:
2285 return TypeManager.uint32_type;
2286 case TypeCode.Int64:
2287 return TypeManager.int64_type;
2288 case TypeCode.UInt64:
2289 return TypeManager.uint64_type;
2290 case TypeCode.Single:
2291 return TypeManager.float_type;
2292 case TypeCode.Double:
2293 return TypeManager.double_type;
2294 case TypeCode.String:
2295 return TypeManager.string_type;
2296 case TypeCode.Decimal:
2297 return TypeManager.decimal_type;
2299 if (t == typeof (void))
2300 return TypeManager.void_type;
2301 if (t == typeof (object))
2302 return TypeManager.object_type;
2303 if (t == typeof (System.Type))
2304 return TypeManager.type_type;
2305 if (t == typeof (System.IntPtr))
2306 return TypeManager.intptr_type;
2312 /// Utility function that can be used to probe whether a type
2313 /// is managed or not.
2315 public static bool VerifyUnManaged (Type t, Location loc)
2317 if (IsUnmanagedType (t))
2320 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2327 /// Returns the name of the indexer in a given type.
2330 /// The default is not always `Item'. The user can change this behaviour by
2331 /// using the IndexerNameAttribute in the container.
2333 /// For example, the String class indexer is named `Chars' not `Item'
2335 public static string IndexerPropertyName (Type t)
2337 t = DropGenericTypeArguments (t);
2338 if (t is TypeBuilder) {
2339 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2340 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2343 System.Attribute attr = System.Attribute.GetCustomAttribute (
2344 t, TypeManager.default_member_type);
2346 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2347 return dma.MemberName;
2350 return TypeContainer.DefaultIndexerName;
2353 static MethodInfo declare_local_method = null;
2355 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2357 if (declare_local_method == null){
2358 declare_local_method = typeof (ILGenerator).GetMethod (
2360 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2362 new Type [] { typeof (Type), typeof (bool)},
2364 if (declare_local_method == null){
2365 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2366 return ig.DeclareLocal (t);
2369 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2373 // Returns whether the array of memberinfos contains the given method
2375 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2377 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2379 foreach (MethodBase method in array) {
2380 if (method.Name != new_method.Name)
2383 if (method is MethodInfo && new_method is MethodInfo)
2384 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2388 Type [] old_args = TypeManager.GetParameterData (method).Types;
2389 int old_count = old_args.Length;
2392 if (new_args.Length != old_count)
2395 for (i = 0; i < old_count; i++){
2396 if (old_args [i] != new_args [i])
2409 // We copy methods from `new_members' into `target_list' if the signature
2410 // for the method from in the new list does not exist in the target_list
2412 // The name is assumed to be the same.
2414 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2416 if (target_list == null){
2417 target_list = new ArrayList ();
2419 foreach (MemberInfo mi in new_members){
2420 if (mi is MethodBase)
2421 target_list.Add (mi);
2426 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2427 target_list.CopyTo (target_array, 0);
2429 foreach (MemberInfo mi in new_members){
2430 MethodBase new_method = (MethodBase) mi;
2432 if (!ArrayContainsMethod (target_array, new_method))
2433 target_list.Add (new_method);
2438 #region MemberLookup implementation
2441 // Whether we allow private members in the result (since FindMembers
2442 // uses NonPublic for both protected and private), we need to distinguish.
2445 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2450 internal class Closure {
2451 internal bool private_ok;
2453 // Who is invoking us and which type is being queried currently.
2454 internal Type invocation_type;
2455 internal Type qualifier_type;
2457 // The assembly that defines the type is that is calling us
2458 internal Assembly invocation_assembly;
2459 internal IList almost_match;
2461 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2463 if (invocation_type == null)
2466 if (is_static && qualifier_type == null)
2467 // It resolved from a simple name, so it should be visible.
2470 // A nested class has access to all the protected members visible to its parent.
2471 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2474 if (IsNestedFamilyAccessible (invocation_type, m.DeclaringType)) {
2475 // Although a derived class can access protected members of its base class
2476 // it cannot do so through an instance of the base class (CS1540).
2477 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2479 qualifier_type == null ||
2480 IsInstantiationOfSameGenericType (invocation_type, qualifier_type) ||
2481 !IsFamilyAccessible (invocation_type, qualifier_type) ||
2482 IsNestedChildOf (invocation_type, qualifier_type))
2486 if (almost_match != null)
2487 almost_match.Add (m);
2493 // This filter filters by name + whether it is ok to include private
2494 // members in the search
2496 internal bool Filter (MemberInfo m, object filter_criteria)
2499 // Hack: we know that the filter criteria will always be in the
2500 // `closure' // fields.
2503 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2506 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2507 (invocation_type != null) &&
2508 IsPrivateAccessible (m.DeclaringType, invocation_type))
2512 // Ugly: we need to find out the type of `m', and depending
2513 // on this, tell whether we accept or not
2515 if (m is MethodBase){
2516 MethodBase mb = (MethodBase) m;
2517 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2519 if (ma == MethodAttributes.Public)
2522 if (ma == MethodAttributes.Private)
2523 return private_ok ||
2524 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2525 IsNestedChildOf (invocation_type, m.DeclaringType);
2527 if (invocation_assembly == mb.DeclaringType.Assembly ||
2528 TypeManager.IsFriendAssembly (mb.DeclaringType.Assembly)) {
2529 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2532 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2536 // Family, FamORAssem or FamANDAssem
2537 return CheckValidFamilyAccess (mb.IsStatic, m);
2540 if (m is FieldInfo){
2541 FieldInfo fi = (FieldInfo) m;
2542 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2544 if (fa == FieldAttributes.Public)
2547 if (fa == FieldAttributes.Private)
2548 return private_ok ||
2549 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2550 IsNestedChildOf (invocation_type, m.DeclaringType);
2552 if (invocation_assembly == fi.DeclaringType.Assembly ||
2553 TypeManager.IsFriendAssembly (fi.DeclaringType.Assembly)) {
2554 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2557 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2561 // Family, FamORAssem or FamANDAssem
2562 return CheckValidFamilyAccess (fi.IsStatic, m);
2566 // EventInfos and PropertyInfos, return true because they lack
2567 // permission information, so we need to check later on the methods.
2573 static Closure closure = new Closure ();
2574 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2577 // Looks up a member called `name' in the `queried_type'. This lookup
2578 // is done by code that is contained in the definition for `invocation_type'
2579 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2581 // `invocation_type' is used to check whether we're allowed to access the requested
2582 // member wrt its protection level.
2584 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2585 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2586 // is B and qualifier_type is A). This is used to do the CS1540 check.
2588 // When resolving a SimpleName, `qualifier_type' is null.
2590 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2591 // the same than `queried_type' - except when we're being called from BaseAccess;
2592 // in this case, `invocation_type' is the current type and `queried_type' the base
2593 // type, so this'd normally trigger a CS1540.
2595 // The binding flags are `bf' and the kind of members being looked up are `mt'
2597 // The return value always includes private members which code in `invocation_type'
2598 // is allowed to access (using the specified `qualifier_type' if given); only use
2599 // BindingFlags.NonPublic to bypass the permission check.
2601 // The 'almost_match' argument is used for reporting error CS1540.
2603 // Returns an array of a single element for everything but Methods/Constructors
2604 // that might return multiple matches.
2606 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2607 Type queried_type, MemberTypes mt,
2608 BindingFlags original_bf, string name, IList almost_match)
2610 Timer.StartTimer (TimerType.MemberLookup);
2612 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2613 queried_type, mt, original_bf, name, almost_match);
2615 Timer.StopTimer (TimerType.MemberLookup);
2620 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2621 Type queried_type, MemberTypes mt,
2622 BindingFlags original_bf, string name, IList almost_match)
2624 BindingFlags bf = original_bf;
2626 ArrayList method_list = null;
2627 Type current_type = queried_type;
2628 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2629 bool skip_iface_check = true, used_cache = false;
2630 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2632 closure.invocation_type = invocation_type;
2633 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2634 closure.qualifier_type = qualifier_type;
2635 closure.almost_match = almost_match;
2637 // This is from the first time we find a method
2638 // in most cases, we do not actually find a method in the base class
2639 // so we can just ignore it, and save the arraylist allocation
2640 MemberInfo [] first_members_list = null;
2641 bool use_first_members_list = false;
2647 // `NonPublic' is lame, because it includes both protected and
2648 // private methods, so we need to control this behavior by
2649 // explicitly tracking if a private method is ok or not.
2651 // The possible cases are:
2652 // public, private and protected (internal does not come into the
2655 if ((invocation_type != null) &&
2656 ((invocation_type == current_type) ||
2657 IsNestedChildOf (invocation_type, current_type)) ||
2659 bf = original_bf | BindingFlags.NonPublic;
2663 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2665 Timer.StopTimer (TimerType.MemberLookup);
2667 list = MemberLookup_FindMembers (
2668 current_type, mt, bf, name, out used_cache);
2670 Timer.StartTimer (TimerType.MemberLookup);
2673 // When queried for an interface type, the cache will automatically check all
2674 // inherited members, so we don't need to do this here. However, this only
2675 // works if we already used the cache in the first iteration of this loop.
2677 // If we used the cache in any further iteration, we can still terminate the
2678 // loop since the cache always looks in all base classes.
2684 skip_iface_check = false;
2686 if (current_type == TypeManager.object_type)
2689 current_type = current_type.BaseType;
2692 // This happens with interfaces, they have a null
2693 // basetype. Look members up in the Object class.
2695 if (current_type == null) {
2696 current_type = TypeManager.object_type;
2701 if (list.Length == 0)
2705 // Events and types are returned by both `static' and `instance'
2706 // searches, which means that our above FindMembers will
2707 // return two copies of the same.
2709 if (list.Length == 1 && !(list [0] is MethodBase)){
2714 // Multiple properties: we query those just to find out the indexer
2717 if (list [0] is PropertyInfo)
2721 // We found an event: the cache lookup returns both the event and
2722 // its private field.
2724 if (list [0] is EventInfo) {
2725 if ((list.Length == 2) && (list [1] is FieldInfo))
2726 return new MemberInfo [] { list [0] };
2733 // We found methods, turn the search into "method scan"
2737 if (first_members_list != null) {
2738 if (use_first_members_list) {
2739 method_list = CopyNewMethods (method_list, first_members_list);
2740 use_first_members_list = false;
2743 method_list = CopyNewMethods (method_list, list);
2745 first_members_list = list;
2746 use_first_members_list = true;
2748 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2750 } while (searching);
2752 if (use_first_members_list) {
2753 foreach (MemberInfo mi in first_members_list) {
2754 if (! (mi is MethodBase)) {
2755 method_list = CopyNewMethods (method_list, first_members_list);
2756 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2759 return (MemberInfo []) first_members_list;
2762 if (method_list != null && method_list.Count > 0) {
2763 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2766 // This happens if we already used the cache in the first iteration, in this case
2767 // the cache already looked in all interfaces.
2769 if (skip_iface_check)
2773 // Interfaces do not list members they inherit, so we have to
2776 if (!queried_type.IsInterface)
2779 if (queried_type.IsArray)
2780 queried_type = TypeManager.array_type;
2782 Type [] ifaces = GetInterfaces (queried_type);
2786 foreach (Type itype in ifaces){
2789 x = MemberLookup (null, null, itype, mt, bf, name, null);
2797 // Tests whether external method is really special
2798 public static bool IsSpecialMethod (MethodBase mb)
2800 string name = mb.Name;
2801 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2802 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2804 if (name.StartsWith ("add_"))
2805 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2807 if (name.StartsWith ("remove_"))
2808 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2810 if (name.StartsWith ("op_")){
2811 foreach (string oname in Unary.oper_names) {
2816 foreach (string oname in Binary.oper_names) {
2829 /// There is exactly one instance of this class per type.
2831 public sealed class TypeHandle : IMemberContainer {
2832 public readonly IMemberContainer BaseType;
2834 readonly int id = ++next_id;
2835 static int next_id = 0;
2837 static TypeHandle ()
2843 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2844 /// a TypeHandle yet, a new instance of it is created. This static method
2845 /// ensures that we'll only have one TypeHandle instance per type.
2847 private static TypeHandle GetTypeHandle (Type t)
2849 TypeHandle handle = (TypeHandle) type_hash [t];
2853 handle = new TypeHandle (t);
2854 type_hash.Add (t, handle);
2858 public static MemberCache GetMemberCache (Type t)
2860 return GetTypeHandle (t).MemberCache;
2863 public static void CleanUp ()
2868 public static void Reset ()
2870 type_hash = new PtrHashtable ();
2874 /// Returns the TypeHandle for TypeManager.object_type.
2876 public static IMemberContainer ObjectType {
2878 if (object_type != null)
2881 object_type = GetTypeHandle (TypeManager.object_type);
2888 /// Returns the TypeHandle for TypeManager.array_type.
2890 public static IMemberContainer ArrayType {
2892 if (array_type != null)
2895 array_type = GetTypeHandle (TypeManager.array_type);
2901 private static PtrHashtable type_hash;
2903 private static TypeHandle object_type = null;
2904 private static TypeHandle array_type = null;
2907 private string full_name;
2908 private bool is_interface;
2909 private MemberCache member_cache;
2910 private MemberCache base_cache;
2912 private TypeHandle (Type type)
2915 full_name = type.FullName != null ? type.FullName : type.Name;
2916 if (type.BaseType != null) {
2917 base_cache = TypeManager.LookupMemberCache (type.BaseType);
2918 BaseType = base_cache.Container;
2919 } else if (type.IsInterface)
2920 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2921 this.is_interface = type.IsInterface || type.IsGenericParameter;
2922 this.member_cache = new MemberCache (this);
2925 // IMemberContainer methods
2927 public string Name {
2939 public MemberCache BaseCache {
2945 public bool IsInterface {
2947 return is_interface;
2951 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2953 MemberInfo [] members;
2954 if (type is GenericTypeParameterBuilder)
2955 return MemberList.Empty;
2956 if (mt == MemberTypes.Event)
2957 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2959 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2961 Array.Reverse (members);
2963 return new MemberList (members);
2966 // IMemberFinder methods
2968 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2969 MemberFilter filter, object criteria)
2971 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2974 public MemberCache MemberCache {
2976 return member_cache;
2980 public override string ToString ()
2982 if (BaseType != null)
2983 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2985 return "TypeHandle (" + id + "," + Name + ")";