2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
15 // the behavior of the compilation. This can be removed if we rework
16 // the code to get a list of namespaces available.
18 #define SIMPLE_SPEEDUP
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
27 using System.Text.RegularExpressions;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
33 public class TypeManager {
35 // A list of core types that the compiler requires or uses
37 static public Type object_type;
38 static public Type value_type;
39 static public Type string_type;
40 static public Type int32_type;
41 static public Type uint32_type;
42 static public Type int64_type;
43 static public Type uint64_type;
44 static public Type float_type;
45 static public Type double_type;
46 static public Type char_type;
47 static public Type char_ptr_type;
48 static public Type short_type;
49 static public Type decimal_type;
50 static public Type bool_type;
51 static public Type sbyte_type;
52 static public Type byte_type;
53 static public Type ushort_type;
54 static public Type enum_type;
55 static public Type delegate_type;
56 static public Type multicast_delegate_type;
57 static public Type void_type;
58 static public Type null_type;
59 static public Type enumeration_type;
60 static public Type array_type;
61 static public Type runtime_handle_type;
62 static public Type icloneable_type;
63 static public Type type_type;
64 static public Type ienumerator_type;
65 static public Type ienumerable_type;
66 static public Type idisposable_type;
67 static public Type iconvertible_type;
68 static public Type default_member_type;
69 static public Type iasyncresult_type;
70 static public Type asynccallback_type;
71 static public Type intptr_type;
72 static public Type monitor_type;
73 static public Type runtime_field_handle_type;
74 static public Type runtime_argument_handle_type;
75 static public Type attribute_type;
76 static public Type attribute_usage_type;
77 static public Type decimal_constant_attribute_type;
78 static public Type dllimport_type;
79 static public Type unverifiable_code_type;
80 static public Type methodimpl_attr_type;
81 static public Type marshal_as_attr_type;
82 static public Type param_array_type;
83 static public Type void_ptr_type;
84 static public Type indexer_name_type;
85 static public Type exception_type;
86 static public Type invalid_operation_exception_type;
87 static public Type not_supported_exception_type;
88 static public Type obsolete_attribute_type;
89 static public Type conditional_attribute_type;
90 static public Type in_attribute_type;
91 static public Type out_attribute_type;
92 static public Type anonymous_method_type;
93 static public Type cls_compliant_attribute_type;
94 static public Type typed_reference_type;
95 static public Type arg_iterator_type;
96 static public Type mbr_type;
97 static public Type struct_layout_attribute_type;
98 static public Type field_offset_attribute_type;
99 static public Type security_attr_type;
100 static public Type required_attr_type;
101 static public Type guid_attr_type;
102 static public Type assembly_culture_attribute_type;
108 static internal Type compiler_generated_attr_type;
109 static internal Type fixed_buffer_attr_type;
110 static internal Type default_charset_type;
114 // An empty array of types
116 static public Type [] NoTypes;
117 static public TypeExpr [] NoTypeExprs;
121 // Expressions representing the internal types. Used during declaration
124 static public TypeExpr system_object_expr, system_string_expr;
125 static public TypeExpr system_boolean_expr, system_decimal_expr;
126 static public TypeExpr system_single_expr, system_double_expr;
127 static public TypeExpr system_sbyte_expr, system_byte_expr;
128 static public TypeExpr system_int16_expr, system_uint16_expr;
129 static public TypeExpr system_int32_expr, system_uint32_expr;
130 static public TypeExpr system_int64_expr, system_uint64_expr;
131 static public TypeExpr system_char_expr, system_void_expr;
132 static public TypeExpr system_asynccallback_expr;
133 static public TypeExpr system_iasyncresult_expr;
134 static public TypeExpr system_valuetype_expr;
135 static public TypeExpr system_intptr_expr;
138 // This is only used when compiling corlib
140 static public Type system_int32_type;
141 static public Type system_array_type;
142 static public Type system_type_type;
143 static public Type system_assemblybuilder_type;
144 static public MethodInfo system_int_array_get_length;
145 static public MethodInfo system_int_array_get_rank;
146 static public MethodInfo system_object_array_clone;
147 static public MethodInfo system_int_array_get_length_int;
148 static public MethodInfo system_int_array_get_lower_bound_int;
149 static public MethodInfo system_int_array_get_upper_bound_int;
150 static public MethodInfo system_void_array_copyto_array_int;
154 // Internal, not really used outside
156 static Type runtime_helpers_type;
159 // These methods are called by code generated by the compiler
161 static public MethodInfo string_concat_string_string;
162 static public MethodInfo string_concat_string_string_string;
163 static public MethodInfo string_concat_string_string_string_string;
164 static public MethodInfo string_concat_string_dot_dot_dot;
165 static public MethodInfo string_concat_object_object;
166 static public MethodInfo string_concat_object_object_object;
167 static public MethodInfo string_concat_object_dot_dot_dot;
168 static public MethodInfo string_isinterneted_string;
169 static public MethodInfo system_type_get_type_from_handle;
170 static public MethodInfo bool_movenext_void;
171 static public MethodInfo ienumerable_getenumerator_void;
172 static public MethodInfo void_reset_void;
173 static public MethodInfo void_dispose_void;
174 static public MethodInfo void_monitor_enter_object;
175 static public MethodInfo void_monitor_exit_object;
176 static public MethodInfo void_initializearray_array_fieldhandle;
177 static public MethodInfo int_getlength_int;
178 static public MethodInfo delegate_combine_delegate_delegate;
179 static public MethodInfo delegate_remove_delegate_delegate;
180 static public MethodInfo int_get_offset_to_string_data;
181 static public MethodInfo int_array_get_length;
182 static public MethodInfo int_array_get_rank;
183 static public MethodInfo object_array_clone;
184 static public MethodInfo int_array_get_length_int;
185 static public MethodInfo int_array_get_lower_bound_int;
186 static public MethodInfo int_array_get_upper_bound_int;
187 static public MethodInfo void_array_copyto_array_int;
188 static public PropertyInfo ienumerator_getcurrent;
191 // The attribute constructors.
193 static public ConstructorInfo object_ctor;
194 static public ConstructorInfo cons_param_array_attribute;
195 static public ConstructorInfo void_decimal_ctor_five_args;
196 static public ConstructorInfo void_decimal_ctor_int_arg;
197 static public ConstructorInfo unverifiable_code_ctor;
198 static public ConstructorInfo default_member_ctor;
199 static public ConstructorInfo decimal_constant_attribute_ctor;
200 static internal ConstructorInfo struct_layout_attribute_ctor;
201 static public ConstructorInfo field_offset_attribute_ctor;
207 static internal CustomAttributeBuilder compiler_generated_attr;
208 static internal ConstructorInfo fixed_buffer_attr_ctor;
212 // Holds the Array of Assemblies that have been loaded
213 // (either because it is the default or the user used the
214 // -r command line option)
216 static Assembly [] assemblies;
219 // Keeps a list of modules. We used this to do lookups
220 // on the module using GetType -- needed for arrays
222 static Module [] modules;
224 static PtrHashtable builder_to_declspace;
226 static PtrHashtable builder_to_member_cache;
229 // Tracks the interfaces implemented by typebuilders. We only
230 // enter those who do implement or or more interfaces
232 static PtrHashtable builder_to_ifaces;
235 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
236 // the arguments to the method
238 static Hashtable method_arguments;
241 // Maps PropertyBuilder to a Type array that contains
242 // the arguments to the indexer
244 static Hashtable indexer_arguments;
247 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
249 static Hashtable method_params;
252 // A hash table from override methods to their base virtual method.
254 static Hashtable method_overrides;
257 // Keeps track of methods
260 static Hashtable builder_to_method;
263 // Contains all public types from referenced assemblies.
264 // This member is used only if CLS Compliance verification is required.
266 public static Hashtable AllClsTopLevelTypes;
268 static Hashtable fieldbuilders_to_fields;
269 static Hashtable fields;
276 public static void CleanUp ()
278 // Lets get everything clean so that we can collect before generating code
281 builder_to_declspace = null;
282 builder_to_member_cache = null;
283 builder_to_ifaces = null;
284 method_arguments = null;
285 indexer_arguments = null;
286 method_params = null;
287 builder_to_method = null;
290 fieldbuilders_to_fields = null;
292 priv_fields_events = null;
295 TypeHandle.CleanUp ();
299 /// A filter for Findmembers that uses the Signature object to
302 static bool SignatureFilter (MemberInfo mi, object criteria)
304 Signature sig = (Signature) criteria;
306 if (!(mi is MethodBase))
309 if (mi.Name != sig.name)
312 int count = sig.args.Length;
314 if (mi is MethodBuilder || mi is ConstructorBuilder){
315 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
317 if (candidate_args.Length != count)
320 for (int i = 0; i < count; i++)
321 if (candidate_args [i] != sig.args [i])
326 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
328 if (pars.Length != count)
331 for (int i = 0; i < count; i++)
332 if (pars [i].ParameterType != sig.args [i])
338 // A delegate that points to the filter above.
339 static MemberFilter signature_filter;
342 // These are expressions that represent some of the internal data types, used
345 static void InitExpressionTypes ()
347 system_object_expr = new TypeLookupExpression ("System.Object");
348 system_string_expr = new TypeLookupExpression ("System.String");
349 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
350 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
351 system_single_expr = new TypeLookupExpression ("System.Single");
352 system_double_expr = new TypeLookupExpression ("System.Double");
353 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
354 system_byte_expr = new TypeLookupExpression ("System.Byte");
355 system_int16_expr = new TypeLookupExpression ("System.Int16");
356 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
357 system_int32_expr = new TypeLookupExpression ("System.Int32");
358 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
359 system_int64_expr = new TypeLookupExpression ("System.Int64");
360 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
361 system_char_expr = new TypeLookupExpression ("System.Char");
362 system_void_expr = new TypeLookupExpression ("System.Void");
363 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
364 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
365 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
366 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
369 static TypeManager ()
373 signature_filter = new MemberFilter (SignatureFilter);
374 InitExpressionTypes ();
377 static public void Reset ()
379 assemblies = new Assembly [0];
382 builder_to_declspace = new PtrHashtable ();
383 builder_to_member_cache = new PtrHashtable ();
384 builder_to_method = new PtrHashtable ();
385 method_arguments = new PtrHashtable ();
386 method_params = new PtrHashtable ();
387 method_overrides = new PtrHashtable ();
388 indexer_arguments = new PtrHashtable ();
389 builder_to_ifaces = new PtrHashtable ();
391 NoTypes = new Type [0];
392 NoTypeExprs = new TypeExpr [0];
394 fieldbuilders_to_fields = new Hashtable ();
395 fields = new Hashtable ();
396 type_hash = new DoubleHash ();
399 public static void AddUserType (string name, DeclSpace ds)
401 builder_to_declspace.Add (ds.TypeBuilder, ds);
405 // This entry point is used by types that we define under the covers
407 public static void RegisterBuilder (Type tb, Type [] ifaces)
410 builder_to_ifaces [tb] = ifaces;
413 public static void AddMethod (MethodBase builder, IMethodData method)
415 builder_to_method.Add (builder, method);
418 public static IMethodData GetMethod (MethodBase builder)
420 return (IMethodData) builder_to_method [builder];
424 /// Returns the DeclSpace whose Type is `t' or null if there is no
425 /// DeclSpace for `t' (ie, the Type comes from a library)
427 public static DeclSpace LookupDeclSpace (Type t)
429 return builder_to_declspace [t] as DeclSpace;
433 /// Returns the TypeContainer whose Type is `t' or null if there is no
434 /// TypeContainer for `t' (ie, the Type comes from a library)
436 public static TypeContainer LookupTypeContainer (Type t)
438 return builder_to_declspace [t] as TypeContainer;
441 public static MemberCache LookupMemberCache (Type t)
443 if (t is TypeBuilder) {
444 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
445 if (container != null)
446 return container.MemberCache;
449 return TypeHandle.GetMemberCache (t);
452 public static MemberCache LookupBaseInterfacesCache (Type t)
454 Type [] ifaces = t.GetInterfaces ();
456 if (ifaces != null && ifaces.Length == 1)
457 return LookupMemberCache (ifaces [0]);
459 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
460 MemberCache cache = builder_to_member_cache [t] as MemberCache;
464 cache = new MemberCache (ifaces);
465 builder_to_member_cache.Add (t, cache);
469 public static TypeContainer LookupInterface (Type t)
471 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
472 if ((tc == null) || (tc.Kind != Kind.Interface))
478 public static Delegate LookupDelegate (Type t)
480 return builder_to_declspace [t] as Delegate;
483 public static Class LookupClass (Type t)
485 return (Class) builder_to_declspace [t];
489 /// Registers an assembly to load types from.
491 public static void AddAssembly (Assembly a)
493 foreach (Assembly assembly in assemblies) {
498 int top = assemblies.Length;
499 Assembly [] n = new Assembly [top + 1];
501 assemblies.CopyTo (n, 0);
507 public static Assembly [] GetAssemblies ()
513 /// Registers a module builder to lookup types from
515 public static void AddModule (Module mb)
517 int top = modules != null ? modules.Length : 0;
518 Module [] n = new Module [top + 1];
521 modules.CopyTo (n, 0);
526 public static Module[] Modules {
533 // We use this hash for multiple kinds of constructed types:
535 // (T, "&") Given T, get T &
536 // (T, "*") Given T, get T *
537 // (T, "[]") Given T and a array dimension, get T []
538 // (T, X) Given a type T and a simple name X, get the type T+X
540 // Accessibility tests, if necessary, should be done by the user
542 static DoubleHash type_hash = new DoubleHash ();
545 // Gets the reference to T version of the Type (T&)
547 public static Type GetReferenceType (Type t)
549 return GetConstructedType (t, "&");
553 // Gets the pointer to T version of the Type (T*)
555 public static Type GetPointerType (Type t)
557 return GetConstructedType (t, "*");
560 public static Type GetConstructedType (Type t, string dim)
563 if (!type_hash.Lookup (t, dim, out ret)) {
564 ret = t.Module.GetType (t.ToString () + dim);
565 type_hash.Insert (t, dim, ret);
570 public static Type GetNestedType (Type t, string name)
573 if (!type_hash.Lookup (t, name, out ret)) {
574 ret = t.GetNestedType (name,
575 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
576 type_hash.Insert (t, name, ret);
581 public static Type LookupTypeReflection (string name, Location loc)
583 Type found_type = null;
585 foreach (Assembly a in assemblies) {
586 Type t = a.GetType (name);
591 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
593 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
594 if (ta != TypeAttributes.NotPublic && ta != TypeAttributes.NestedPrivate &&
595 ta != TypeAttributes.NestedAssembly && ta != TypeAttributes.NestedFamANDAssem) {
596 if (found_type == null) {
601 Report.SymbolRelatedToPreviousError (found_type);
602 Report.SymbolRelatedToPreviousError (t);
603 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
608 foreach (Module mb in modules) {
609 Type t = mb.GetType (name);
613 if (found_type == null) {
618 Report.SymbolRelatedToPreviousError (t);
619 Report.SymbolRelatedToPreviousError (found_type);
620 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
621 TypeManager.CSharpName (t));
629 /// Computes the namespaces that we import from the assemblies we reference.
631 public static void ComputeNamespaces ()
633 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
635 Hashtable cache = null;
638 // First add the assembly namespaces
640 if (assembly_get_namespaces != null){
641 int count = assemblies.Length;
643 for (int i = 0; i < count; i++){
644 Assembly a = assemblies [i];
645 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
646 foreach (string ns in namespaces){
649 Namespace.LookupNamespace (ns, true);
653 cache = new Hashtable ();
654 cache.Add ("", null);
655 foreach (Assembly a in assemblies) {
656 foreach (Type t in a.GetExportedTypes ()) {
657 string ns = t.Namespace;
658 if (ns == null || cache.Contains (ns))
661 Namespace.LookupNamespace (ns, true);
662 cache.Add (ns, null);
668 // Then add module namespaces
670 foreach (Module m in modules) {
671 if (m == CodeGen.Module.Builder)
674 cache = new Hashtable ();
675 cache.Add ("", null);
677 foreach (Type t in m.GetTypes ()) {
678 string ns = t.Namespace;
679 if (ns == null || cache.Contains (ns))
681 Namespace.LookupNamespace (ns, true);
682 cache.Add (ns, null);
688 /// Fills static table with exported types from all referenced assemblies.
689 /// This information is required for CLS Compliance tests.
691 public static void LoadAllImportedTypes ()
693 AllClsTopLevelTypes = new Hashtable (1500);
694 foreach (Assembly a in assemblies) {
695 foreach (Type t in a.GetExportedTypes ()) {
696 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
701 public static bool NamespaceClash (string name, Location loc)
703 if (Namespace.LookupNamespace (name, false) == null)
706 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
711 /// Returns the C# name of a type if possible, or the full type name otherwise
713 static public string CSharpName (Type t)
715 return Regex.Replace (t.FullName,
717 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
718 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
719 @"Boolean|String|Void|Null)" +
721 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
724 static public string CSharpName (Type[] types)
726 StringBuilder sb = new StringBuilder ();
727 foreach (Type t in types) {
728 sb.Append (CSharpName (t));
731 sb.Remove (sb.Length - 1, 1);
732 return sb.ToString ();
735 static String CSharpNameMatch (Match match)
737 string s = match.Groups [1].Captures [0].Value;
739 Replace ("int32", "int").
740 Replace ("uint32", "uint").
741 Replace ("int16", "short").
742 Replace ("uint16", "ushort").
743 Replace ("int64", "long").
744 Replace ("uint64", "ulong").
745 Replace ("single", "float").
746 Replace ("boolean", "bool")
747 + match.Groups [2].Captures [0].Value;
751 /// Returns the signature of the method with full namespace classification
753 static public string GetFullNameSignature (MemberInfo mi)
755 return (mi is MethodBase)
756 ? CSharpSignature (mi as MethodBase)
757 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
761 /// When we need to report accessors as well
763 static public string CSharpSignature (MethodBase mb)
765 return CSharpSignature (mb, false);
769 /// Returns the signature of the method
771 static public string CSharpSignature (MethodBase mb, bool show_accessor)
773 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
776 ParameterData iparams = GetParameterData (mb);
777 string parameters = iparams.GetSignatureForError ();
778 string accessor = "";
781 if (mb.IsSpecialName) {
782 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
783 if (ot != Operator.OpType.TOP) {
784 sig.Append ("operator ");
785 sig.Append (Operator.GetName (ot));
786 sig.Append (parameters);
787 return sig.ToString ();
790 if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
791 accessor = mb.Name.Substring (0, 3);
796 if (mb.IsSpecialName && !mb.IsConstructor) {
797 if (iparams.Count > 1) {
798 sig.Append ("this[");
800 sig.Append (parameters.Substring (1, parameters.Length - 2));
803 int before_ret_val = parameters.LastIndexOf (',');
804 sig.Append (parameters.Substring (1, before_ret_val - 1));
808 sig.Append (mb.Name.Substring (4));
811 if (mb.Name == ".ctor")
812 sig.Append (mb.DeclaringType.Name);
814 sig.Append (mb.Name);
816 sig.Append (parameters);
819 if (show_accessor && accessor.Length > 0) {
821 sig.Append (accessor);
824 return sig.ToString ();
827 static public string CSharpSignature (EventInfo ei)
829 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
833 /// Looks up a type, and aborts if it is not found. This is used
834 /// by types required by the compiler
836 static Type CoreLookupType (string ns_name, string name)
838 Namespace ns = Namespace.LookupNamespace (ns_name, true);
839 FullNamedExpression fne = ns.Lookup (RootContext.Tree.Types, name, Location.Null);
840 Type t = fne == null ? null : fne.Type;
842 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
847 /// Returns the MethodInfo for a method named `name' defined
848 /// in type `t' which takes arguments of types `args'
850 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
854 BindingFlags flags = instance_and_static | BindingFlags.Public;
860 flags |= BindingFlags.NonPublic;
862 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
863 if (list.Count == 0) {
865 Report.Error (-19, "Can not find the core function `" + name + "'");
869 MethodInfo mi = list [0] as MethodInfo;
872 Report.Error (-19, "Can not find the core function `" + name + "'");
879 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
881 return GetMethod (t, name, args, false, report_errors);
884 static MethodInfo GetMethod (Type t, string name, Type [] args)
886 return GetMethod (t, name, args, true);
890 /// Returns the PropertyInfo for a property named `name' defined
893 static PropertyInfo GetProperty (Type t, string name)
895 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
896 BindingFlags.Instance, Type.FilterName, name);
897 if (list.Count == 0) {
898 Report.Error (-19, "Can not find the core property `" + name + "'");
902 PropertyInfo pi = list [0] as PropertyInfo;
904 Report.Error (-19, "Can not find the core function `" + name + "'");
912 /// Returns the ConstructorInfo for "args"
914 public static ConstructorInfo GetConstructor (Type t, Type [] args)
922 list = FindMembers (t, MemberTypes.Constructor,
923 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
924 signature_filter, sig);
925 if (list.Count == 0){
926 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
930 ConstructorInfo ci = list [0] as ConstructorInfo;
932 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
939 public static void InitEnumUnderlyingTypes ()
942 int32_type = CoreLookupType ("System", "Int32");
943 int64_type = CoreLookupType ("System", "Int64");
944 uint32_type = CoreLookupType ("System", "UInt32");
945 uint64_type = CoreLookupType ("System", "UInt64");
946 byte_type = CoreLookupType ("System", "Byte");
947 sbyte_type = CoreLookupType ("System", "SByte");
948 short_type = CoreLookupType ("System", "Int16");
949 ushort_type = CoreLookupType ("System", "UInt16");
953 /// The types have to be initialized after the initial
954 /// population of the type has happened (for example, to
955 /// bootstrap the corlib.dll
957 public static void InitCoreTypes ()
959 object_type = CoreLookupType ("System", "Object");
960 value_type = CoreLookupType ("System", "ValueType");
962 InitEnumUnderlyingTypes ();
964 char_type = CoreLookupType ("System", "Char");
965 string_type = CoreLookupType ("System", "String");
966 float_type = CoreLookupType ("System", "Single");
967 double_type = CoreLookupType ("System", "Double");
968 char_ptr_type = GetPointerType (char_type);
969 decimal_type = CoreLookupType ("System", "Decimal");
970 bool_type = CoreLookupType ("System", "Boolean");
971 enum_type = CoreLookupType ("System", "Enum");
973 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
974 delegate_type = CoreLookupType ("System", "Delegate");
976 array_type = CoreLookupType ("System", "Array");
977 void_type = CoreLookupType ("System", "Void");
978 type_type = CoreLookupType ("System", "Type");
980 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
981 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
982 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
983 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
984 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle");
985 asynccallback_type = CoreLookupType ("System", "AsyncCallback");
986 iasyncresult_type = CoreLookupType ("System", "IAsyncResult");
987 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator");
988 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable");
989 idisposable_type = CoreLookupType ("System", "IDisposable");
990 icloneable_type = CoreLookupType ("System", "ICloneable");
991 iconvertible_type = CoreLookupType ("System", "IConvertible");
992 monitor_type = CoreLookupType ("System.Threading", "Monitor");
993 intptr_type = CoreLookupType ("System", "IntPtr");
995 attribute_type = CoreLookupType ("System", "Attribute");
996 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
997 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
998 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
999 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
1000 param_array_type = CoreLookupType ("System", "ParamArrayAttribute");
1001 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
1002 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
1003 typed_reference_type = CoreLookupType ("System", "TypedReference");
1004 arg_iterator_type = CoreLookupType ("System", "ArgIterator");
1005 mbr_type = CoreLookupType ("System", "MarshalByRefObject");
1006 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
1008 unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
1010 void_ptr_type = GetPointerType (void_type);
1012 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
1014 exception_type = CoreLookupType ("System", "Exception");
1015 invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
1016 not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
1021 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
1022 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
1023 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
1024 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
1025 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
1026 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
1027 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1028 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
1029 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
1035 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1036 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1037 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1040 // When compiling corlib, store the "real" types here.
1042 if (!RootContext.StdLib) {
1043 system_int32_type = typeof (System.Int32);
1044 system_array_type = typeof (System.Array);
1045 system_type_type = typeof (System.Type);
1046 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1048 Type [] void_arg = { };
1049 system_int_array_get_length = GetMethod (
1050 system_array_type, "get_Length", void_arg);
1051 system_int_array_get_rank = GetMethod (
1052 system_array_type, "get_Rank", void_arg);
1053 system_object_array_clone = GetMethod (
1054 system_array_type, "Clone", void_arg);
1056 Type [] system_int_arg = { system_int32_type };
1057 system_int_array_get_length_int = GetMethod (
1058 system_array_type, "GetLength", system_int_arg);
1059 system_int_array_get_upper_bound_int = GetMethod (
1060 system_array_type, "GetUpperBound", system_int_arg);
1061 system_int_array_get_lower_bound_int = GetMethod (
1062 system_array_type, "GetLowerBound", system_int_arg);
1064 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1065 system_void_array_copyto_array_int = GetMethod (
1066 system_array_type, "CopyTo", system_array_int_arg);
1068 Type [] system_3_type_arg = {
1069 system_type_type, system_type_type, system_type_type };
1070 Type [] system_4_type_arg = {
1071 system_type_type, system_type_type, system_type_type, system_type_type };
1073 MethodInfo set_corlib_type_builders = GetMethod (
1074 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1075 system_4_type_arg, true, false);
1077 if (set_corlib_type_builders != null) {
1078 object[] args = new object [4];
1079 args [0] = object_type;
1080 args [1] = value_type;
1081 args [2] = enum_type;
1082 args [3] = void_type;
1084 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1086 // Compatibility for an older version of the class libs.
1087 set_corlib_type_builders = GetMethod (
1088 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1089 system_3_type_arg, true, true);
1091 if (set_corlib_type_builders == null) {
1092 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1096 object[] args = new object [3];
1097 args [0] = object_type;
1098 args [1] = value_type;
1099 args [2] = enum_type;
1101 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1105 system_object_expr.Type = object_type;
1106 system_string_expr.Type = string_type;
1107 system_boolean_expr.Type = bool_type;
1108 system_decimal_expr.Type = decimal_type;
1109 system_single_expr.Type = float_type;
1110 system_double_expr.Type = double_type;
1111 system_sbyte_expr.Type = sbyte_type;
1112 system_byte_expr.Type = byte_type;
1113 system_int16_expr.Type = short_type;
1114 system_uint16_expr.Type = ushort_type;
1115 system_int32_expr.Type = int32_type;
1116 system_uint32_expr.Type = uint32_type;
1117 system_int64_expr.Type = int64_type;
1118 system_uint64_expr.Type = uint64_type;
1119 system_char_expr.Type = char_type;
1120 system_void_expr.Type = void_type;
1121 system_asynccallback_expr.Type = asynccallback_type;
1122 system_iasyncresult_expr.Type = iasyncresult_type;
1123 system_valuetype_expr.Type = value_type;
1126 // These are only used for compare purposes
1128 anonymous_method_type = typeof (AnonymousMethod);
1129 null_type = typeof (NullType);
1133 // The helper methods that are used by the compiler
1135 public static void InitCodeHelpers ()
1138 // Now load the default methods that we use.
1140 Type [] string_string = { string_type, string_type };
1141 string_concat_string_string = GetMethod (
1142 string_type, "Concat", string_string);
1143 Type [] string_string_string = { string_type, string_type, string_type };
1144 string_concat_string_string_string = GetMethod (
1145 string_type, "Concat", string_string_string);
1146 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1147 string_concat_string_string_string_string = GetMethod (
1148 string_type, "Concat", string_string_string_string);
1149 Type[] params_string = { GetConstructedType (string_type, "[]") };
1150 string_concat_string_dot_dot_dot = GetMethod (
1151 string_type, "Concat", params_string);
1153 Type [] object_object = { object_type, object_type };
1154 string_concat_object_object = GetMethod (
1155 string_type, "Concat", object_object);
1156 Type [] object_object_object = { object_type, object_type, object_type };
1157 string_concat_object_object_object = GetMethod (
1158 string_type, "Concat", object_object_object);
1159 Type[] params_object = { GetConstructedType (object_type, "[]") };
1160 string_concat_object_dot_dot_dot = GetMethod (
1161 string_type, "Concat", params_object);
1163 Type [] string_ = { string_type };
1164 string_isinterneted_string = GetMethod (
1165 string_type, "IsInterned", string_);
1167 Type [] runtime_type_handle = { runtime_handle_type };
1168 system_type_get_type_from_handle = GetMethod (
1169 type_type, "GetTypeFromHandle", runtime_type_handle);
1171 Type [] delegate_delegate = { delegate_type, delegate_type };
1172 delegate_combine_delegate_delegate = GetMethod (
1173 delegate_type, "Combine", delegate_delegate);
1175 delegate_remove_delegate_delegate = GetMethod (
1176 delegate_type, "Remove", delegate_delegate);
1181 Type [] void_arg = { };
1182 ienumerator_getcurrent = GetProperty (
1183 ienumerator_type, "Current");
1184 bool_movenext_void = GetMethod (
1185 ienumerator_type, "MoveNext", void_arg);
1186 void_reset_void = GetMethod (
1187 ienumerator_type, "Reset", void_arg);
1188 void_dispose_void = GetMethod (
1189 idisposable_type, "Dispose", void_arg);
1190 int_get_offset_to_string_data = GetMethod (
1191 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1192 int_array_get_length = GetMethod (
1193 array_type, "get_Length", void_arg);
1194 int_array_get_rank = GetMethod (
1195 array_type, "get_Rank", void_arg);
1196 ienumerable_getenumerator_void = GetMethod (
1197 ienumerable_type, "GetEnumerator", void_arg);
1202 Type [] int_arg = { int32_type };
1203 int_array_get_length_int = GetMethod (
1204 array_type, "GetLength", int_arg);
1205 int_array_get_upper_bound_int = GetMethod (
1206 array_type, "GetUpperBound", int_arg);
1207 int_array_get_lower_bound_int = GetMethod (
1208 array_type, "GetLowerBound", int_arg);
1211 // System.Array methods
1213 object_array_clone = GetMethod (
1214 array_type, "Clone", void_arg);
1215 Type [] array_int_arg = { array_type, int32_type };
1216 void_array_copyto_array_int = GetMethod (
1217 array_type, "CopyTo", array_int_arg);
1222 Type [] object_arg = { object_type };
1223 void_monitor_enter_object = GetMethod (
1224 monitor_type, "Enter", object_arg);
1225 void_monitor_exit_object = GetMethod (
1226 monitor_type, "Exit", object_arg);
1228 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1230 void_initializearray_array_fieldhandle = GetMethod (
1231 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1236 int_getlength_int = GetMethod (
1237 array_type, "GetLength", int_arg);
1240 // Decimal constructors
1242 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1243 void_decimal_ctor_five_args = GetConstructor (
1244 decimal_type, dec_arg);
1246 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1251 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1252 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1253 default_member_ctor = GetConstructor (default_member_type, string_);
1255 Type[] short_arg = { short_type };
1256 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1258 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1259 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1261 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1268 compiler_generated_attr = new CustomAttributeBuilder (
1269 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1271 Type[] type_int_arg = { type_type, int32_type };
1272 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1276 object_ctor = GetConstructor (object_type, void_arg);
1280 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1283 /// This is the "old", non-cache based FindMembers() function. We cannot use
1284 /// the cache here because there is no member name argument.
1286 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1287 MemberFilter filter, object criteria)
1289 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1292 // `builder_to_declspace' contains all dynamic types.
1296 Timer.StartTimer (TimerType.FindMembers);
1297 list = decl.FindMembers (mt, bf, filter, criteria);
1298 Timer.StopTimer (TimerType.FindMembers);
1303 // We have to take care of arrays specially, because GetType on
1304 // a TypeBuilder array will return a Type, not a TypeBuilder,
1305 // and we can not call FindMembers on this type.
1307 if (t.IsSubclassOf (TypeManager.array_type))
1308 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1311 // Since FindMembers will not lookup both static and instance
1312 // members, we emulate this behaviour here.
1314 if ((bf & instance_and_static) == instance_and_static){
1315 MemberInfo [] i_members = t.FindMembers (
1316 mt, bf & ~BindingFlags.Static, filter, criteria);
1318 int i_len = i_members.Length;
1320 MemberInfo one = i_members [0];
1323 // If any of these are present, we are done!
1325 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1326 return new MemberList (i_members);
1329 MemberInfo [] s_members = t.FindMembers (
1330 mt, bf & ~BindingFlags.Instance, filter, criteria);
1332 int s_len = s_members.Length;
1333 if (i_len > 0 || s_len > 0)
1334 return new MemberList (i_members, s_members);
1337 return new MemberList (i_members);
1339 return new MemberList (s_members);
1343 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1348 /// This method is only called from within MemberLookup. It tries to use the member
1349 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1350 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1351 /// our return value will already contain all inherited members and the caller don't need
1352 /// to check base classes and interfaces anymore.
1354 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1355 string name, out bool used_cache)
1360 // We have to take care of arrays specially, because GetType on
1361 // a TypeBuilder array will return a Type, not a TypeBuilder,
1362 // and we can not call FindMembers on this type.
1364 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1366 return TypeHandle.ArrayType.MemberCache.FindMembers (
1367 mt, bf, name, FilterWithClosure_delegate, null);
1371 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1372 // and we can ask the DeclSpace for the MemberCache.
1374 if (t is TypeBuilder) {
1375 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1376 cache = decl.MemberCache;
1379 // If this DeclSpace has a MemberCache, use it.
1382 if (cache != null) {
1384 return cache.FindMembers (
1385 mt, bf, name, FilterWithClosure_delegate, null);
1388 // If there is no MemberCache, we need to use the "normal" FindMembers.
1389 // Note, this is a VERY uncommon route!
1392 Timer.StartTimer (TimerType.FindMembers);
1393 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1394 FilterWithClosure_delegate, name);
1395 Timer.StopTimer (TimerType.FindMembers);
1398 return (MemberInfo []) list;
1402 // This call will always succeed. There is exactly one TypeHandle instance per
1403 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1404 // the corresponding MemberCache.
1406 cache = TypeHandle.GetMemberCache (t);
1409 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1412 public static bool IsBuiltinType (Type t)
1414 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1415 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1416 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1417 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1423 public static bool IsBuiltinType (TypeContainer tc)
1425 return IsBuiltinType (tc.TypeBuilder);
1429 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1430 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1432 public static bool IsPrimitiveType (Type t)
1434 return (t == int32_type || t == uint32_type ||
1435 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1436 t == char_type || t == short_type || t == bool_type ||
1437 t == sbyte_type || t == byte_type || t == ushort_type);
1440 public static bool IsDelegateType (Type t)
1442 if (t.IsSubclassOf (TypeManager.delegate_type))
1448 public static bool IsEnumType (Type t)
1450 if (builder_to_declspace [t] is Enum)
1456 public static bool IsBuiltinOrEnum (Type t)
1458 if (IsBuiltinType (t))
1467 static Stack unmanaged_enclosing_types = new Stack (4);
1470 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1472 public static bool IsUnmanagedType (Type t)
1474 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1475 if (unmanaged_enclosing_types.Contains (t))
1478 // builtins that are not unmanaged types
1479 if (t == TypeManager.object_type || t == TypeManager.string_type)
1482 if (IsBuiltinOrEnum (t))
1485 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1489 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1493 if (!IsValueType (t))
1496 unmanaged_enclosing_types.Push (t);
1500 if (t is TypeBuilder){
1501 TypeContainer tc = LookupTypeContainer (t);
1502 if (tc.Fields != null){
1503 foreach (Field f in tc.Fields){
1504 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1505 if ((f.ModFlags & Modifiers.STATIC) != 0)
1507 if (f.MemberType == null)
1509 if (!IsUnmanagedType (f.MemberType)){
1510 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1516 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1518 foreach (FieldInfo f in fields){
1519 if (!IsUnmanagedType (f.FieldType)){
1520 Report.SymbolRelatedToPreviousError (f);
1526 unmanaged_enclosing_types.Pop ();
1531 public static bool IsValueType (Type t)
1533 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1539 public static bool IsInterfaceType (Type t)
1541 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1545 return tc.Kind == Kind.Interface;
1548 public static bool IsSubclassOf (Type type, Type base_type)
1551 if (type.Equals (base_type))
1554 type = type.BaseType;
1555 } while (type != null);
1560 public static bool IsFamilyAccessible (Type type, Type base_type)
1562 return IsSubclassOf (type, base_type);
1566 // Checks whether `type' is a subclass or nested child of `base_type'.
1568 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1571 if ((type == base_type) || type.IsSubclassOf (base_type))
1574 // Handle nested types.
1575 type = type.DeclaringType;
1576 } while (type != null);
1582 // Checks whether `type' is a nested child of `parent'.
1584 public static bool IsNestedChildOf (Type type, Type parent)
1589 type = type.DeclaringType;
1590 while (type != null) {
1594 type = type.DeclaringType;
1601 // Do the right thing when returning the element type of an
1602 // array type based on whether we are compiling corlib or not
1604 public static Type GetElementType (Type t)
1606 if (RootContext.StdLib)
1607 return t.GetElementType ();
1609 return TypeToCoreType (t.GetElementType ());
1613 /// This method is not implemented by MS runtime for dynamic types
1615 public static bool HasElementType (Type t)
1617 return t.IsArray || t.IsPointer || t.IsByRef;
1621 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1625 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1626 /// for anything which is dynamic, and we need this in a number of places,
1627 /// we register this information here, and use it afterwards.
1629 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1634 method_arguments.Add (mb, args);
1635 method_params.Add (mb, ip);
1638 static public ParameterData GetParameterData (MethodBase mb)
1640 object pd = method_params [mb];
1642 if (mb is MethodBuilder || mb is ConstructorBuilder)
1643 throw new InternalErrorException ("Argument for Method not registered" + mb);
1645 method_params [mb] = pd = new ReflectionParameters (mb);
1648 return (ParameterData) pd;
1651 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1653 if (method_overrides.Contains (override_method)) {
1654 if (method_overrides [override_method] != base_method)
1655 throw new InternalErrorException ("Override mismatch: " + override_method);
1658 method_overrides [override_method] = base_method;
1661 static public bool IsOverride (MethodBase m)
1663 return m.IsVirtual &&
1664 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1665 (m is MethodBuilder || method_overrides.Contains (m));
1669 /// Returns the argument types for a method based on its methodbase
1671 /// For dynamic methods, we use the compiler provided types, for
1672 /// methods from existing assemblies we load them from GetParameters,
1673 /// and insert them into the cache
1675 static public Type [] GetArgumentTypes (MethodBase mb)
1677 object t = method_arguments [mb];
1681 ParameterInfo [] pi = mb.GetParameters ();
1688 types = new Type [c];
1689 for (int i = 0; i < c; i++)
1690 types [i] = pi [i].ParameterType;
1692 method_arguments.Add (mb, types);
1697 /// Returns the argument types for an indexer based on its PropertyInfo
1699 /// For dynamic indexers, we use the compiler provided types, for
1700 /// indexers from existing assemblies we load them from GetParameters,
1701 /// and insert them into the cache
1703 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1705 if (indexer_arguments.Contains (indexer))
1706 return (Type []) indexer_arguments [indexer];
1707 else if (indexer is PropertyBuilder)
1708 // If we're a PropertyBuilder and not in the
1709 // `indexer_arguments' hash, then we're a property and
1713 ParameterInfo [] pi = indexer.GetIndexParameters ();
1714 // Property, not an indexer.
1718 Type [] types = new Type [c];
1720 for (int i = 0; i < c; i++)
1721 types [i] = pi [i].ParameterType;
1723 indexer_arguments.Add (indexer, types);
1728 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1730 fields.Add (fb, ic);
1733 public static IConstant GetConstant (FieldInfo fb)
1738 return (IConstant)fields [fb];
1741 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1743 if (fieldbuilders_to_fields.Contains (fb))
1746 fieldbuilders_to_fields.Add (fb, f);
1751 // The return value can be null; This will be the case for
1752 // auxiliary FieldBuilders created by the compiler that have no
1753 // real field being declared on the source code
1755 static public FieldBase GetField (FieldInfo fb)
1757 return (FieldBase) fieldbuilders_to_fields [fb];
1760 static Hashtable events;
1762 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1765 events = new Hashtable ();
1767 if (!events.Contains (eb)) {
1768 events.Add (eb, new Pair (add, remove));
1772 static public MethodInfo GetAddMethod (EventInfo ei)
1774 if (ei is MyEventBuilder) {
1775 Pair pair = (Pair) events [ei];
1777 return (MethodInfo) pair.First;
1779 return ei.GetAddMethod (true);
1782 static public MethodInfo GetRemoveMethod (EventInfo ei)
1784 if (ei is MyEventBuilder) {
1785 Pair pair = (Pair) events [ei];
1787 return (MethodInfo) pair.Second;
1789 return ei.GetRemoveMethod (true);
1792 static Hashtable priv_fields_events;
1794 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1796 if (priv_fields_events == null)
1797 priv_fields_events = new Hashtable ();
1799 if (priv_fields_events.Contains (einfo))
1802 priv_fields_events.Add (einfo, builder);
1807 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1809 if (priv_fields_events == null)
1812 return (MemberInfo) priv_fields_events [ei];
1815 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1816 MethodBase set, Type[] args)
1818 indexer_arguments.Add (pb, args);
1823 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1825 Hashtable hash = new Hashtable ();
1826 return CheckStructCycles (tc, seen, hash);
1829 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1832 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1836 // `seen' contains all types we've already visited.
1838 if (seen.Contains (tc))
1840 seen.Add (tc, null);
1842 if (tc.Fields == null)
1845 foreach (FieldMember field in tc.Fields) {
1846 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1849 Type ftype = field.FieldBuilder.FieldType;
1850 TypeContainer ftc = LookupTypeContainer (ftype);
1854 if (hash.Contains (ftc)) {
1855 Report.Error (523, tc.Location,
1856 "Struct member `{0}.{1}' of type `{2}' " +
1857 "causes a cycle in the struct layout",
1858 tc.Name, field.Name, ftc.Name);
1863 // `hash' contains all types in the current path.
1865 hash.Add (tc, null);
1867 bool ok = CheckStructCycles (ftc, seen, hash);
1874 if (!seen.Contains (ftc))
1875 seen.Add (ftc, null);
1882 /// Given an array of interface types, expand and eliminate repeated ocurrences
1883 /// of an interface.
1887 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1890 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1892 ArrayList new_ifaces = new ArrayList ();
1894 foreach (TypeExpr iface in base_interfaces){
1895 Type itype = iface.ResolveType (ec);
1899 if (!new_ifaces.Contains (itype))
1900 new_ifaces.Add (itype);
1902 Type [] implementing = itype.GetInterfaces ();
1904 foreach (Type imp in implementing){
1905 if (!new_ifaces.Contains (imp))
1906 new_ifaces.Add (imp);
1909 Type [] ret = new Type [new_ifaces.Count];
1910 new_ifaces.CopyTo (ret, 0);
1914 static PtrHashtable iface_cache = new PtrHashtable ();
1917 /// This function returns the interfaces in the type `t'. Works with
1918 /// both types and TypeBuilders.
1920 public static Type [] GetInterfaces (Type t)
1923 Type [] cached = iface_cache [t] as Type [];
1928 // The reason for catching the Array case is that Reflection.Emit
1929 // will not return a TypeBuilder for Array types of TypeBuilder types,
1930 // but will still throw an exception if we try to call GetInterfaces
1933 // Since the array interfaces are always constant, we return those for
1938 t = TypeManager.array_type;
1940 if (t is TypeBuilder){
1941 Type [] base_ifaces;
1943 if (t.BaseType == null)
1944 base_ifaces = NoTypes;
1946 base_ifaces = GetInterfaces (t.BaseType);
1947 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1948 if (type_ifaces == null)
1949 type_ifaces = NoTypes;
1951 int base_count = base_ifaces.Length;
1952 Type [] result = new Type [base_count + type_ifaces.Length];
1953 base_ifaces.CopyTo (result, 0);
1954 type_ifaces.CopyTo (result, base_count);
1956 iface_cache [t] = result;
1959 Type[] ifaces = t.GetInterfaces ();
1960 iface_cache [t] = ifaces;
1966 // gets the interfaces that are declared explicitly on t
1968 public static Type [] GetExplicitInterfaces (TypeBuilder t)
1970 return (Type []) builder_to_ifaces [t];
1974 /// The following is used to check if a given type implements an interface.
1975 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1977 public static bool ImplementsInterface (Type t, Type iface)
1982 // FIXME OPTIMIZATION:
1983 // as soon as we hit a non-TypeBuiler in the interface
1984 // chain, we could return, as the `Type.GetInterfaces'
1985 // will return all the interfaces implement by the type
1989 interfaces = GetInterfaces (t);
1991 if (interfaces != null){
1992 foreach (Type i in interfaces){
1999 } while (t != null);
2004 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2006 // This is a custom version of Convert.ChangeType() which works
2007 // with the TypeBuilder defined types when compiling corlib.
2008 public static object ChangeType (object value, Type conversionType, out bool error)
2010 IConvertible convert_value = value as IConvertible;
2012 if (convert_value == null){
2018 // We must use Type.Equals() here since `conversionType' is
2019 // the TypeBuilder created version of a system type and not
2020 // the system type itself. You cannot use Type.GetTypeCode()
2021 // on such a type - it'd always return TypeCode.Object.
2025 if (conversionType.Equals (typeof (Boolean)))
2026 return (object)(convert_value.ToBoolean (nf_provider));
2027 else if (conversionType.Equals (typeof (Byte)))
2028 return (object)(convert_value.ToByte (nf_provider));
2029 else if (conversionType.Equals (typeof (Char)))
2030 return (object)(convert_value.ToChar (nf_provider));
2031 else if (conversionType.Equals (typeof (DateTime)))
2032 return (object)(convert_value.ToDateTime (nf_provider));
2033 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2034 return (object)(convert_value.ToDecimal (nf_provider));
2035 else if (conversionType.Equals (typeof (Double)))
2036 return (object)(convert_value.ToDouble (nf_provider));
2037 else if (conversionType.Equals (typeof (Int16)))
2038 return (object)(convert_value.ToInt16 (nf_provider));
2039 else if (conversionType.Equals (typeof (Int32)))
2040 return (object)(convert_value.ToInt32 (nf_provider));
2041 else if (conversionType.Equals (typeof (Int64)))
2042 return (object)(convert_value.ToInt64 (nf_provider));
2043 else if (conversionType.Equals (typeof (SByte)))
2044 return (object)(convert_value.ToSByte (nf_provider));
2045 else if (conversionType.Equals (typeof (Single)))
2046 return (object)(convert_value.ToSingle (nf_provider));
2047 else if (conversionType.Equals (typeof (String)))
2048 return (object)(convert_value.ToString (nf_provider));
2049 else if (conversionType.Equals (typeof (UInt16)))
2050 return (object)(convert_value.ToUInt16 (nf_provider));
2051 else if (conversionType.Equals (typeof (UInt32)))
2052 return (object)(convert_value.ToUInt32 (nf_provider));
2053 else if (conversionType.Equals (typeof (UInt64)))
2054 return (object)(convert_value.ToUInt64 (nf_provider));
2055 else if (conversionType.Equals (typeof (Object)))
2056 return (object)(value);
2066 // This is needed, because enumerations from assemblies
2067 // do not report their underlyingtype, but they report
2070 public static Type EnumToUnderlying (Type t)
2072 if (t == TypeManager.enum_type)
2075 t = t.UnderlyingSystemType;
2076 if (!TypeManager.IsEnumType (t))
2079 if (t is TypeBuilder) {
2080 // slow path needed to compile corlib
2081 if (t == TypeManager.bool_type ||
2082 t == TypeManager.byte_type ||
2083 t == TypeManager.sbyte_type ||
2084 t == TypeManager.char_type ||
2085 t == TypeManager.short_type ||
2086 t == TypeManager.ushort_type ||
2087 t == TypeManager.int32_type ||
2088 t == TypeManager.uint32_type ||
2089 t == TypeManager.int64_type ||
2090 t == TypeManager.uint64_type)
2093 TypeCode tc = Type.GetTypeCode (t);
2096 case TypeCode.Boolean:
2097 return TypeManager.bool_type;
2099 return TypeManager.byte_type;
2100 case TypeCode.SByte:
2101 return TypeManager.sbyte_type;
2103 return TypeManager.char_type;
2104 case TypeCode.Int16:
2105 return TypeManager.short_type;
2106 case TypeCode.UInt16:
2107 return TypeManager.ushort_type;
2108 case TypeCode.Int32:
2109 return TypeManager.int32_type;
2110 case TypeCode.UInt32:
2111 return TypeManager.uint32_type;
2112 case TypeCode.Int64:
2113 return TypeManager.int64_type;
2114 case TypeCode.UInt64:
2115 return TypeManager.uint64_type;
2117 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2121 // When compiling corlib and called with one of the core types, return
2122 // the corresponding typebuilder for that type.
2124 public static Type TypeToCoreType (Type t)
2126 if (RootContext.StdLib || (t is TypeBuilder))
2129 TypeCode tc = Type.GetTypeCode (t);
2132 case TypeCode.Boolean:
2133 return TypeManager.bool_type;
2135 return TypeManager.byte_type;
2136 case TypeCode.SByte:
2137 return TypeManager.sbyte_type;
2139 return TypeManager.char_type;
2140 case TypeCode.Int16:
2141 return TypeManager.short_type;
2142 case TypeCode.UInt16:
2143 return TypeManager.ushort_type;
2144 case TypeCode.Int32:
2145 return TypeManager.int32_type;
2146 case TypeCode.UInt32:
2147 return TypeManager.uint32_type;
2148 case TypeCode.Int64:
2149 return TypeManager.int64_type;
2150 case TypeCode.UInt64:
2151 return TypeManager.uint64_type;
2152 case TypeCode.Single:
2153 return TypeManager.float_type;
2154 case TypeCode.Double:
2155 return TypeManager.double_type;
2156 case TypeCode.String:
2157 return TypeManager.string_type;
2158 case TypeCode.Decimal:
2159 return TypeManager.decimal_type;
2161 if (t == typeof (void))
2162 return TypeManager.void_type;
2163 if (t == typeof (object))
2164 return TypeManager.object_type;
2165 if (t == typeof (System.Type))
2166 return TypeManager.type_type;
2167 if (t == typeof (System.IntPtr))
2168 return TypeManager.intptr_type;
2174 /// Utility function that can be used to probe whether a type
2175 /// is managed or not.
2177 public static bool VerifyUnManaged (Type t, Location loc)
2179 if (IsUnmanagedType (t))
2182 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2189 /// Returns the name of the indexer in a given type.
2192 /// The default is not always `Item'. The user can change this behaviour by
2193 /// using the IndexerNameAttribute in the container.
2194 /// For example, the String class indexer is named `Chars' not `Item'
2196 public static string IndexerPropertyName (Type t)
2198 if (t is TypeBuilder) {
2199 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2200 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2203 System.Attribute attr = System.Attribute.GetCustomAttribute (
2204 t, TypeManager.default_member_type);
2206 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2207 return dma.MemberName;
2210 return TypeContainer.DefaultIndexerName;
2213 static MethodInfo declare_local_method = null;
2215 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2217 if (declare_local_method == null){
2218 declare_local_method = typeof (ILGenerator).GetMethod (
2220 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2222 new Type [] { typeof (Type), typeof (bool)},
2224 if (declare_local_method == null){
2225 Report.Warning (-30, new Location (-1),
2226 "This version of the runtime does not support making pinned local variables. " +
2227 "This code may cause errors on a runtime with a moving GC");
2228 return ig.DeclareLocal (t);
2231 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2235 // Returns whether the array of memberinfos contains the given method
2237 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2239 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2241 foreach (MethodBase method in array) {
2242 if (method.Name != new_method.Name)
2245 if (method is MethodInfo && new_method is MethodInfo)
2246 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2250 Type [] old_args = TypeManager.GetArgumentTypes (method);
2251 int old_count = old_args.Length;
2254 if (new_args.Length != old_count)
2257 for (i = 0; i < old_count; i++){
2258 if (old_args [i] != new_args [i])
2271 // We copy methods from `new_members' into `target_list' if the signature
2272 // for the method from in the new list does not exist in the target_list
2274 // The name is assumed to be the same.
2276 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2278 if (target_list == null){
2279 target_list = new ArrayList ();
2281 foreach (MemberInfo mi in new_members){
2282 if (mi is MethodBase)
2283 target_list.Add (mi);
2288 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2289 target_list.CopyTo (target_array, 0);
2291 foreach (MemberInfo mi in new_members){
2292 MethodBase new_method = (MethodBase) mi;
2294 if (!ArrayContainsMethod (target_array, new_method))
2295 target_list.Add (new_method);
2301 #region MemberLookup implementation
2304 // Whether we allow private members in the result (since FindMembers
2305 // uses NonPublic for both protected and private), we need to distinguish.
2308 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2313 internal class Closure {
2314 internal bool private_ok;
2316 // Who is invoking us and which type is being queried currently.
2317 internal Type invocation_type;
2318 internal Type qualifier_type;
2320 // The assembly that defines the type is that is calling us
2321 internal Assembly invocation_assembly;
2322 internal IList almost_match;
2324 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2326 if (invocation_type == null)
2329 if (is_static && qualifier_type == null)
2330 // It resolved from a simple name, so it should be visible.
2333 // A nested class has access to all the protected members visible to its parent.
2334 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2337 if (invocation_type == m.DeclaringType || invocation_type.IsSubclassOf (m.DeclaringType)) {
2338 // Although a derived class can access protected members of its base class
2339 // it cannot do so through an instance of the base class (CS1540).
2340 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2342 qualifier_type == null ||
2343 qualifier_type == invocation_type ||
2344 qualifier_type.IsSubclassOf (invocation_type))
2348 if (almost_match != null)
2349 almost_match.Add (m);
2355 // This filter filters by name + whether it is ok to include private
2356 // members in the search
2358 internal bool Filter (MemberInfo m, object filter_criteria)
2361 // Hack: we know that the filter criteria will always be in the `closure'
2365 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2368 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2369 (m.DeclaringType == invocation_type))
2373 // Ugly: we need to find out the type of `m', and depending
2374 // on this, tell whether we accept or not
2376 if (m is MethodBase){
2377 MethodBase mb = (MethodBase) m;
2378 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2380 if (ma == MethodAttributes.Private)
2381 return private_ok || invocation_type == m.DeclaringType ||
2382 IsNestedChildOf (invocation_type, m.DeclaringType);
2384 if (invocation_assembly == mb.DeclaringType.Assembly) {
2385 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2388 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2392 if (ma == MethodAttributes.Family ||
2393 ma == MethodAttributes.FamANDAssem ||
2394 ma == MethodAttributes.FamORAssem)
2395 return CheckValidFamilyAccess (mb.IsStatic, m);
2401 if (m is FieldInfo){
2402 FieldInfo fi = (FieldInfo) m;
2403 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2405 if (fa == FieldAttributes.Private)
2406 return private_ok || (invocation_type == m.DeclaringType) ||
2407 IsNestedChildOf (invocation_type, m.DeclaringType);
2409 if (invocation_assembly == fi.DeclaringType.Assembly) {
2410 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2413 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2417 if (fa == FieldAttributes.Family ||
2418 fa == FieldAttributes.FamANDAssem ||
2419 fa == FieldAttributes.FamORAssem)
2420 return CheckValidFamilyAccess (fi.IsStatic, m);
2427 // EventInfos and PropertyInfos, return true because they lack permission
2428 // information, so we need to check later on the methods.
2434 static Closure closure = new Closure ();
2435 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2438 // Looks up a member called `name' in the `queried_type'. This lookup
2439 // is done by code that is contained in the definition for `invocation_type'
2440 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2442 // `invocation_type' is used to check whether we're allowed to access the requested
2443 // member wrt its protection level.
2445 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2446 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2447 // is B and qualifier_type is A). This is used to do the CS1540 check.
2449 // When resolving a SimpleName, `qualifier_type' is null.
2451 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2452 // the same than `queried_type' - except when we're being called from BaseAccess;
2453 // in this case, `invocation_type' is the current type and `queried_type' the base
2454 // type, so this'd normally trigger a CS1540.
2456 // The binding flags are `bf' and the kind of members being looked up are `mt'
2458 // The return value always includes private members which code in `invocation_type'
2459 // is allowed to access (using the specified `qualifier_type' if given); only use
2460 // BindingFlags.NonPublic to bypass the permission check.
2462 // The 'almost_match' argument is used for reporting error CS1540.
2464 // Returns an array of a single element for everything but Methods/Constructors
2465 // that might return multiple matches.
2467 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2468 Type queried_type, MemberTypes mt,
2469 BindingFlags original_bf, string name, IList almost_match)
2471 Timer.StartTimer (TimerType.MemberLookup);
2473 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2474 queried_type, mt, original_bf, name, almost_match);
2476 Timer.StopTimer (TimerType.MemberLookup);
2481 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2482 Type queried_type, MemberTypes mt,
2483 BindingFlags original_bf, string name, IList almost_match)
2485 BindingFlags bf = original_bf;
2487 ArrayList method_list = null;
2488 Type current_type = queried_type;
2489 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2490 bool skip_iface_check = true, used_cache = false;
2491 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2493 closure.invocation_type = invocation_type;
2494 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2495 closure.qualifier_type = qualifier_type;
2496 closure.almost_match = almost_match;
2498 // This is from the first time we find a method
2499 // in most cases, we do not actually find a method in the base class
2500 // so we can just ignore it, and save the arraylist allocation
2501 MemberInfo [] first_members_list = null;
2502 bool use_first_members_list = false;
2508 // `NonPublic' is lame, because it includes both protected and
2509 // private methods, so we need to control this behavior by
2510 // explicitly tracking if a private method is ok or not.
2512 // The possible cases are:
2513 // public, private and protected (internal does not come into the
2516 if ((invocation_type != null) &&
2517 ((invocation_type == current_type) ||
2518 IsNestedChildOf (invocation_type, current_type)) ||
2520 bf = original_bf | BindingFlags.NonPublic;
2524 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2526 Timer.StopTimer (TimerType.MemberLookup);
2528 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2530 Timer.StartTimer (TimerType.MemberLookup);
2533 // When queried for an interface type, the cache will automatically check all
2534 // inherited members, so we don't need to do this here. However, this only
2535 // works if we already used the cache in the first iteration of this loop.
2537 // If we used the cache in any further iteration, we can still terminate the
2538 // loop since the cache always looks in all base classes.
2544 skip_iface_check = false;
2546 if (current_type == TypeManager.object_type)
2549 current_type = current_type.BaseType;
2552 // This happens with interfaces, they have a null
2553 // basetype. Look members up in the Object class.
2555 if (current_type == null) {
2556 current_type = TypeManager.object_type;
2561 if (list.Length == 0)
2565 // Events and types are returned by both `static' and `instance'
2566 // searches, which means that our above FindMembers will
2567 // return two copies of the same.
2569 if (list.Length == 1 && !(list [0] is MethodBase)){
2574 // Multiple properties: we query those just to find out the indexer
2577 if (list [0] is PropertyInfo)
2581 // We found an event: the cache lookup returns both the event and
2582 // its private field.
2584 if (list [0] is EventInfo) {
2585 if ((list.Length == 2) && (list [1] is FieldInfo))
2586 return new MemberInfo [] { list [0] };
2593 // We found methods, turn the search into "method scan"
2597 if (first_members_list != null) {
2598 if (use_first_members_list) {
2599 method_list = CopyNewMethods (method_list, first_members_list);
2600 use_first_members_list = false;
2603 method_list = CopyNewMethods (method_list, list);
2605 first_members_list = list;
2606 use_first_members_list = true;
2607 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2609 } while (searching);
2611 if (use_first_members_list) {
2612 foreach (MemberInfo mi in first_members_list) {
2613 if (! (mi is MethodBase)) {
2614 method_list = CopyNewMethods (method_list, first_members_list);
2615 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2618 return (MemberInfo []) first_members_list;
2621 if (method_list != null && method_list.Count > 0)
2622 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2625 // This happens if we already used the cache in the first iteration, in this case
2626 // the cache already looked in all interfaces.
2628 if (skip_iface_check)
2632 // Interfaces do not list members they inherit, so we have to
2635 if (!queried_type.IsInterface)
2638 if (queried_type.IsArray)
2639 queried_type = TypeManager.array_type;
2641 Type [] ifaces = GetInterfaces (queried_type);
2645 foreach (Type itype in ifaces){
2648 x = MemberLookup (null, null, itype, mt, bf, name, null);
2656 // Tests whether external method is really special
2657 public static bool IsSpecialMethod (MethodBase mb)
2659 string name = mb.Name;
2660 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2661 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2663 if (name.StartsWith ("add_"))
2664 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2666 if (name.StartsWith ("remove_"))
2667 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2669 if (name.StartsWith ("op_")){
2670 foreach (string oname in Unary.oper_names) {
2675 foreach (string oname in Binary.oper_names) {
2688 /// There is exactly one instance of this class per type.
2690 public sealed class TypeHandle : IMemberContainer {
2691 public readonly IMemberContainer BaseType;
2693 readonly int id = ++next_id;
2694 static int next_id = 0;
2696 static TypeHandle ()
2702 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2703 /// a TypeHandle yet, a new instance of it is created. This static method
2704 /// ensures that we'll only have one TypeHandle instance per type.
2706 private static TypeHandle GetTypeHandle (Type t)
2708 TypeHandle handle = (TypeHandle) type_hash [t];
2712 handle = new TypeHandle (t);
2713 type_hash.Add (t, handle);
2717 public static MemberCache GetMemberCache (Type t)
2719 return GetTypeHandle (t).MemberCache;
2722 public static void CleanUp ()
2727 public static void Reset ()
2729 type_hash = new PtrHashtable ();
2733 /// Returns the TypeHandle for TypeManager.object_type.
2735 public static IMemberContainer ObjectType {
2737 if (object_type != null)
2740 object_type = GetTypeHandle (TypeManager.object_type);
2747 /// Returns the TypeHandle for TypeManager.array_type.
2749 public static IMemberContainer ArrayType {
2751 if (array_type != null)
2754 array_type = GetTypeHandle (TypeManager.array_type);
2760 private static PtrHashtable type_hash;
2762 private static TypeHandle object_type = null;
2763 private static TypeHandle array_type = null;
2766 private bool is_interface;
2767 private MemberCache member_cache;
2768 private MemberCache base_cache;
2770 private TypeHandle (Type type)
2773 if (type.BaseType != null) {
2774 base_cache = TypeManager.LookupMemberCache (type.BaseType);
2775 BaseType = base_cache.Container;
2776 } else if (type.IsInterface)
2777 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2778 this.is_interface = type.IsInterface;
2779 this.member_cache = new MemberCache (this);
2782 // IMemberContainer methods
2784 public string Name {
2786 return type.FullName;
2796 public MemberCache BaseCache {
2802 public bool IsInterface {
2804 return is_interface;
2808 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2810 MemberInfo [] members;
2811 if (mt == MemberTypes.Event)
2812 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2814 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2816 Array.Reverse (members);
2818 return new MemberList (members);
2821 // IMemberFinder methods
2823 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2824 MemberFilter filter, object criteria)
2826 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2829 public MemberCache MemberCache {
2831 return member_cache;
2835 public override string ToString ()
2837 if (BaseType != null)
2838 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2840 return "TypeHandle (" + id + "," + Name + ")";