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;
106 static internal Type compiler_generated_attr_type;
107 static internal Type fixed_buffer_attr_type;
111 // An empty array of types
113 static public Type [] NoTypes;
114 static public TypeExpr [] NoTypeExprs;
118 // Expressions representing the internal types. Used during declaration
121 static public TypeExpr system_object_expr, system_string_expr;
122 static public TypeExpr system_boolean_expr, system_decimal_expr;
123 static public TypeExpr system_single_expr, system_double_expr;
124 static public TypeExpr system_sbyte_expr, system_byte_expr;
125 static public TypeExpr system_int16_expr, system_uint16_expr;
126 static public TypeExpr system_int32_expr, system_uint32_expr;
127 static public TypeExpr system_int64_expr, system_uint64_expr;
128 static public TypeExpr system_char_expr, system_void_expr;
129 static public TypeExpr system_asynccallback_expr;
130 static public TypeExpr system_iasyncresult_expr;
131 static public TypeExpr system_valuetype_expr;
132 static public TypeExpr system_intptr_expr;
135 // This is only used when compiling corlib
137 static public Type system_int32_type;
138 static public Type system_array_type;
139 static public Type system_type_type;
140 static public Type system_assemblybuilder_type;
141 static public MethodInfo system_int_array_get_length;
142 static public MethodInfo system_int_array_get_rank;
143 static public MethodInfo system_object_array_clone;
144 static public MethodInfo system_int_array_get_length_int;
145 static public MethodInfo system_int_array_get_lower_bound_int;
146 static public MethodInfo system_int_array_get_upper_bound_int;
147 static public MethodInfo system_void_array_copyto_array_int;
151 // Internal, not really used outside
153 static Type runtime_helpers_type;
156 // These methods are called by code generated by the compiler
158 static public MethodInfo string_concat_string_string;
159 static public MethodInfo string_concat_string_string_string;
160 static public MethodInfo string_concat_string_string_string_string;
161 static public MethodInfo string_concat_string_dot_dot_dot;
162 static public MethodInfo string_concat_object_object;
163 static public MethodInfo string_concat_object_object_object;
164 static public MethodInfo string_concat_object_dot_dot_dot;
165 static public MethodInfo string_isinterneted_string;
166 static public MethodInfo system_type_get_type_from_handle;
167 static public MethodInfo object_getcurrent_void;
168 static public MethodInfo bool_movenext_void;
169 static public MethodInfo ienumerable_getenumerator_void;
170 static public MethodInfo void_reset_void;
171 static public MethodInfo void_dispose_void;
172 static public MethodInfo void_monitor_enter_object;
173 static public MethodInfo void_monitor_exit_object;
174 static public MethodInfo void_initializearray_array_fieldhandle;
175 static public MethodInfo int_getlength_int;
176 static public MethodInfo delegate_combine_delegate_delegate;
177 static public MethodInfo delegate_remove_delegate_delegate;
178 static public MethodInfo int_get_offset_to_string_data;
179 static public MethodInfo int_array_get_length;
180 static public MethodInfo int_array_get_rank;
181 static public MethodInfo object_array_clone;
182 static public MethodInfo int_array_get_length_int;
183 static public MethodInfo int_array_get_lower_bound_int;
184 static public MethodInfo int_array_get_upper_bound_int;
185 static public MethodInfo void_array_copyto_array_int;
188 // The attribute constructors.
190 static public ConstructorInfo object_ctor;
191 static public ConstructorInfo cons_param_array_attribute;
192 static public ConstructorInfo void_decimal_ctor_five_args;
193 static public ConstructorInfo void_decimal_ctor_int_arg;
194 static public ConstructorInfo unverifiable_code_ctor;
195 static public ConstructorInfo default_member_ctor;
196 static public ConstructorInfo decimal_constant_attribute_ctor;
197 static internal ConstructorInfo struct_layout_attribute_ctor;
203 static internal CustomAttributeBuilder compiler_generated_attr;
204 static internal ConstructorInfo fixed_buffer_attr_ctor;
208 // Holds the Array of Assemblies that have been loaded
209 // (either because it is the default or the user used the
210 // -r command line option)
212 static Assembly [] assemblies;
215 // Keeps a list of modules. We used this to do lookups
216 // on the module using GetType -- needed for arrays
218 static Module [] modules;
221 // This is the type_cache from the assemblies to avoid
222 // hitting System.Reflection on every lookup.
224 static Hashtable types;
227 // This is used to hotld the corresponding TypeContainer objects
228 // since we need this in FindMembers
230 static Hashtable typecontainers;
233 // Keeps track of those types that are defined by the
236 static ArrayList user_types;
238 static PtrHashtable builder_to_declspace;
240 static PtrHashtable builder_to_member_cache;
243 // Tracks the interfaces implemented by typebuilders. We only
244 // enter those who do implement or or more interfaces
246 static PtrHashtable builder_to_ifaces;
249 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
250 // the arguments to the method
252 static Hashtable method_arguments;
255 // Maps PropertyBuilder to a Type array that contains
256 // the arguments to the indexer
258 static Hashtable indexer_arguments;
261 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
263 static Hashtable method_params;
266 // Keeps track of methods
269 static Hashtable builder_to_method;
272 // Contains all public types from referenced assemblies.
273 // This member is used only if CLS Compliance verification is required.
275 public static Hashtable all_imported_types;
277 static Hashtable fieldbuilders_to_fields;
278 static Hashtable fields;
285 public static void CleanUp ()
287 // Lets get everything clean so that we can collect before generating code
291 typecontainers = null;
293 builder_to_declspace = null;
294 builder_to_member_cache = null;
295 builder_to_ifaces = null;
296 method_arguments = null;
297 indexer_arguments = null;
298 method_params = null;
299 builder_to_method = null;
302 builder_to_constant = null;
303 fieldbuilders_to_fields = null;
305 priv_fields_events = null;
309 TypeHandle.CleanUp ();
313 /// A filter for Findmembers that uses the Signature object to
316 static bool SignatureFilter (MemberInfo mi, object criteria)
318 Signature sig = (Signature) criteria;
320 if (!(mi is MethodBase))
323 if (mi.Name != sig.name)
326 int count = sig.args.Length;
328 if (mi is MethodBuilder || mi is ConstructorBuilder){
329 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
331 if (candidate_args.Length != count)
334 for (int i = 0; i < count; i++)
335 if (candidate_args [i] != sig.args [i])
340 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
342 if (pars.Length != count)
345 for (int i = 0; i < count; i++)
346 if (pars [i].ParameterType != sig.args [i])
352 // A delegate that points to the filter above.
353 static MemberFilter signature_filter;
356 // These are expressions that represent some of the internal data types, used
359 static void InitExpressionTypes ()
361 system_object_expr = new TypeLookupExpression ("System.Object");
362 system_string_expr = new TypeLookupExpression ("System.String");
363 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
364 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
365 system_single_expr = new TypeLookupExpression ("System.Single");
366 system_double_expr = new TypeLookupExpression ("System.Double");
367 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
368 system_byte_expr = new TypeLookupExpression ("System.Byte");
369 system_int16_expr = new TypeLookupExpression ("System.Int16");
370 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
371 system_int32_expr = new TypeLookupExpression ("System.Int32");
372 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
373 system_int64_expr = new TypeLookupExpression ("System.Int64");
374 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
375 system_char_expr = new TypeLookupExpression ("System.Char");
376 system_void_expr = new TypeLookupExpression ("System.Void");
377 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
378 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
379 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
380 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
383 static TypeManager ()
387 signature_filter = new MemberFilter (SignatureFilter);
388 InitExpressionTypes ();
391 static public void Reset ()
393 assemblies = new Assembly [0];
395 user_types = new ArrayList ();
397 types = new Hashtable ();
398 typecontainers = new Hashtable ();
400 builder_to_declspace = new PtrHashtable ();
401 builder_to_member_cache = new PtrHashtable ();
402 builder_to_method = new PtrHashtable ();
403 method_arguments = new PtrHashtable ();
404 method_params = new PtrHashtable ();
405 indexer_arguments = new PtrHashtable ();
406 builder_to_ifaces = new PtrHashtable ();
408 NoTypes = new Type [0];
409 NoTypeExprs = new TypeExpr [0];
411 fieldbuilders_to_fields = new Hashtable ();
412 fields = new Hashtable ();
413 type_hash = new DoubleHash ();
416 public static void HandleDuplicate (string name, Type t)
418 Type prev = (Type) types [name];
419 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
423 // This probably never happens, as we catch this before
425 Report.Error (-17, "The type `" + name + "' has already been defined.");
429 tc = builder_to_declspace [t] as TypeContainer;
432 1595, "The type `" + name + "' is defined in an existing assembly;"+
433 " Using the new definition from: " + tc.Location);
436 1595, "The type `" + name + "' is defined in an existing assembly;");
439 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
445 public static void AddUserType (string name, TypeBuilder t)
450 HandleDuplicate (name, t);
457 // This entry point is used by types that we define under the covers
459 public static void RegisterBuilder (Type tb, Type [] ifaces)
462 builder_to_ifaces [tb] = ifaces;
465 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
467 builder_to_declspace.Add (t, tc);
468 typecontainers.Add (name, tc);
469 AddUserType (name, t);
472 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
477 HandleDuplicate (name, t);
480 builder_to_declspace.Add (t, del);
483 public static void AddEnumType (string name, TypeBuilder t, Enum en)
488 HandleDuplicate (name, t);
490 builder_to_declspace.Add (t, en);
493 public static void AddMethod (MethodBase builder, IMethodData method)
495 builder_to_method.Add (builder, method);
498 public static IMethodData GetMethod (MethodBase builder)
500 return (IMethodData) builder_to_method [builder];
504 /// Returns the DeclSpace whose Type is `t' or null if there is no
505 /// DeclSpace for `t' (ie, the Type comes from a library)
507 public static DeclSpace LookupDeclSpace (Type t)
509 return builder_to_declspace [t] as DeclSpace;
513 /// Returns the TypeContainer whose Type is `t' or null if there is no
514 /// TypeContainer for `t' (ie, the Type comes from a library)
516 public static TypeContainer LookupTypeContainer (Type t)
518 return builder_to_declspace [t] as TypeContainer;
521 public static MemberCache LookupMemberCache (Type t)
523 if (t is TypeBuilder) {
524 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
525 if (container != null)
526 return container.MemberCache;
529 return TypeHandle.GetMemberCache (t);
532 public static MemberCache LookupBaseInterfacesCache (Type t)
534 Type [] ifaces = t.GetInterfaces ();
536 if (ifaces != null && ifaces.Length == 1)
537 return LookupMemberCache (ifaces [0]);
539 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
540 MemberCache cache = builder_to_member_cache [t] as MemberCache;
544 cache = new MemberCache (ifaces);
545 builder_to_member_cache.Add (t, cache);
549 public static TypeContainer LookupInterface (Type t)
551 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
552 if ((tc == null) || (tc.Kind != Kind.Interface))
558 public static Delegate LookupDelegate (Type t)
560 return builder_to_declspace [t] as Delegate;
563 public static Enum LookupEnum (Type t)
565 return builder_to_declspace [t] as Enum;
568 public static Class LookupClass (Type t)
570 return (Class) builder_to_declspace [t];
574 /// Registers an assembly to load types from.
576 public static void AddAssembly (Assembly a)
578 foreach (Assembly assembly in assemblies) {
583 int top = assemblies.Length;
584 Assembly [] n = new Assembly [top + 1];
586 assemblies.CopyTo (n, 0);
592 public static Assembly [] GetAssemblies ()
598 /// Registers a module builder to lookup types from
600 public static void AddModule (Module mb)
602 int top = modules != null ? modules.Length : 0;
603 Module [] n = new Module [top + 1];
606 modules.CopyTo (n, 0);
611 public static Module[] Modules {
618 // We use this hash for multiple kinds of constructed types:
620 // (T, "&") Given T, get T &
621 // (T, "*") Given T, get T *
622 // (T, "[]") Given T and a array dimension, get T []
623 // (T, X) Given a type T and a simple name X, get the type T+X
625 // Accessibility tests, if necessary, should be done by the user
627 static DoubleHash type_hash = new DoubleHash ();
630 // Gets the reference to T version of the Type (T&)
632 public static Type GetReferenceType (Type t)
634 return GetConstructedType (t, "&");
638 // Gets the pointer to T version of the Type (T*)
640 public static Type GetPointerType (Type t)
642 return GetConstructedType (t, "*");
645 public static Type GetConstructedType (Type t, string dim)
648 if (!type_hash.Lookup (t, dim, out ret)) {
649 ret = t.Module.GetType (t.ToString () + dim);
650 type_hash.Insert (t, dim, ret);
655 public static Type GetNestedType (Type t, string name)
658 if (!type_hash.Lookup (t, name, out ret)) {
659 string lookup = t.ToString () + "+" + name;
660 ret = t.Module.GetType (lookup);
661 type_hash.Insert (t, name, ret);
667 // Low-level lookup, cache-less
669 public static Type LookupTypeReflection (string name)
673 foreach (Assembly a in assemblies){
674 t = a.GetType (name);
679 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
680 if (ta == TypeAttributes.NotPublic ||
681 ta == TypeAttributes.NestedPrivate ||
682 ta == TypeAttributes.NestedAssembly ||
683 ta == TypeAttributes.NestedFamANDAssem){
686 // In .NET pointers turn out to be private, even if their
687 // element type is not
690 t = t.GetElementType ();
700 foreach (Module mb in modules) {
701 t = mb.GetType (name);
710 /// Computes the namespaces that we import from the assemblies we reference.
712 public static void ComputeNamespaces ()
714 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
716 Hashtable cache = null;
719 // First add the assembly namespaces
721 if (assembly_get_namespaces != null){
722 int count = assemblies.Length;
724 for (int i = 0; i < count; i++){
725 Assembly a = assemblies [i];
726 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
727 foreach (string ns in namespaces){
730 Namespace.LookupNamespace (ns, true);
734 cache = new Hashtable ();
735 cache.Add ("", null);
736 foreach (Assembly a in assemblies) {
737 foreach (Type t in a.GetExportedTypes ()) {
738 string ns = t.Namespace;
739 if (ns == null || cache.Contains (ns))
742 Namespace.LookupNamespace (ns, true);
743 cache.Add (ns, null);
749 // Then add module namespaces
751 foreach (Module m in modules) {
752 if (m == CodeGen.Module.Builder)
755 cache = new Hashtable ();
756 cache.Add ("", null);
758 foreach (Type t in m.GetTypes ()) {
759 string ns = t.Namespace;
760 if (ns == null || cache.Contains (ns))
762 Namespace.LookupNamespace (ns, true);
763 cache.Add (ns, null);
769 /// Fills static table with exported types from all referenced assemblies.
770 /// This information is required for CLS Compliance tests.
772 public static void LoadAllImportedTypes ()
774 all_imported_types = new Hashtable ();
775 foreach (Assembly a in assemblies) {
776 foreach (Type t in a.GetExportedTypes ()) {
777 all_imported_types [t.FullName] = t;
782 public static bool NamespaceClash (string name, Location loc)
784 if (Namespace.LookupNamespace (name, false) == null)
787 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
792 /// Returns the C# name of a type if possible, or the full type name otherwise
794 static public string CSharpName (Type t)
796 return Regex.Replace (t.FullName,
798 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
799 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
800 @"Boolean|String|Void|Null)" +
802 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
805 static public string CSharpName (Type[] types)
807 StringBuilder sb = new StringBuilder ();
808 foreach (Type t in types) {
809 sb.Append (CSharpName (t));
812 sb.Remove (sb.Length - 1, 1);
813 return sb.ToString ();
816 static String CSharpNameMatch (Match match)
818 string s = match.Groups [1].Captures [0].Value;
820 Replace ("int32", "int").
821 Replace ("uint32", "uint").
822 Replace ("int16", "short").
823 Replace ("uint16", "ushort").
824 Replace ("int64", "long").
825 Replace ("uint64", "ulong").
826 Replace ("single", "float").
827 Replace ("boolean", "bool")
828 + match.Groups [2].Captures [0].Value;
832 /// Returns the signature of the method with full namespace classification
834 static public string GetFullNameSignature (MemberInfo mi)
836 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
837 return (mi is MethodBase)
838 ? GetFullNameSignature (mi as MethodBase)
839 : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
842 static public string GetFullNameSignature (MethodBase mb)
844 string name = mb.Name;
846 name = mb.DeclaringType.Name;
848 if (mb.IsSpecialName) {
849 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
850 name = name.Remove (0, 4);
857 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
861 /// Returns the signature of the property and indexer
863 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
866 return GetFullNameSignature (pb);
869 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
870 string signature = GetFullNameSignature (mb);
871 string arg = GetParameterData (mb).ParameterDesc (0);
872 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
876 /// Returns the signature of the method
878 static public string CSharpSignature (MethodBase mb)
880 StringBuilder sig = new StringBuilder ("(");
882 ParameterData iparams = GetParameterData (mb);
885 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
886 return GetFullNameSignature (mb);
888 for (int i = 0; i < iparams.Count; i++) {
892 sig.Append (iparams.ParameterDesc (i));
897 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
898 sig.Replace ('(', '[');
899 sig.Replace (')', ']');
902 return GetFullNameSignature (mb) + sig.ToString ();
906 /// Looks up a type, and aborts if it is not found. This is used
907 /// by types required by the compiler
909 static Type CoreLookupType (string name)
912 if (types.Contains (name))
913 t = (Type) types [name];
915 t = LookupTypeReflection (name);
918 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
925 /// Returns the MethodInfo for a method named `name' defined
926 /// in type `t' which takes arguments of types `args'
928 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
932 BindingFlags flags = instance_and_static | BindingFlags.Public;
938 flags |= BindingFlags.NonPublic;
940 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
941 if (list.Count == 0) {
943 Report.Error (-19, "Can not find the core function `" + name + "'");
947 MethodInfo mi = list [0] as MethodInfo;
950 Report.Error (-19, "Can not find the core function `" + name + "'");
957 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
959 return GetMethod (t, name, args, false, report_errors);
962 static MethodInfo GetMethod (Type t, string name, Type [] args)
964 return GetMethod (t, name, args, true);
969 /// Returns the ConstructorInfo for "args"
971 public static ConstructorInfo GetConstructor (Type t, Type [] args)
979 list = FindMembers (t, MemberTypes.Constructor,
980 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
981 signature_filter, sig);
982 if (list.Count == 0){
983 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
987 ConstructorInfo ci = list [0] as ConstructorInfo;
989 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
996 public static void InitEnumUnderlyingTypes ()
999 int32_type = CoreLookupType ("System.Int32");
1000 int64_type = CoreLookupType ("System.Int64");
1001 uint32_type = CoreLookupType ("System.UInt32");
1002 uint64_type = CoreLookupType ("System.UInt64");
1003 byte_type = CoreLookupType ("System.Byte");
1004 sbyte_type = CoreLookupType ("System.SByte");
1005 short_type = CoreLookupType ("System.Int16");
1006 ushort_type = CoreLookupType ("System.UInt16");
1010 /// The types have to be initialized after the initial
1011 /// population of the type has happened (for example, to
1012 /// bootstrap the corlib.dll
1014 public static void InitCoreTypes ()
1016 object_type = CoreLookupType ("System.Object");
1017 value_type = CoreLookupType ("System.ValueType");
1019 InitEnumUnderlyingTypes ();
1021 char_type = CoreLookupType ("System.Char");
1022 string_type = CoreLookupType ("System.String");
1023 float_type = CoreLookupType ("System.Single");
1024 double_type = CoreLookupType ("System.Double");
1025 char_ptr_type = CoreLookupType ("System.Char*");
1026 decimal_type = CoreLookupType ("System.Decimal");
1027 bool_type = CoreLookupType ("System.Boolean");
1028 enum_type = CoreLookupType ("System.Enum");
1030 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1031 delegate_type = CoreLookupType ("System.Delegate");
1033 array_type = CoreLookupType ("System.Array");
1034 void_type = CoreLookupType ("System.Void");
1035 type_type = CoreLookupType ("System.Type");
1037 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1038 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1039 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1040 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1041 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1042 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1043 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1044 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1045 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1046 idisposable_type = CoreLookupType ("System.IDisposable");
1047 icloneable_type = CoreLookupType ("System.ICloneable");
1048 iconvertible_type = CoreLookupType ("System.IConvertible");
1049 monitor_type = CoreLookupType ("System.Threading.Monitor");
1050 intptr_type = CoreLookupType ("System.IntPtr");
1052 attribute_type = CoreLookupType ("System.Attribute");
1053 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1054 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1055 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1056 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1057 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1058 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1059 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1060 typed_reference_type = CoreLookupType ("System.TypedReference");
1061 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1062 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1063 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1065 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1067 void_ptr_type = CoreLookupType ("System.Void*");
1069 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1071 exception_type = CoreLookupType ("System.Exception");
1072 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1073 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1078 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1079 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1080 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1081 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1082 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1083 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1084 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1090 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1091 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1094 // When compiling corlib, store the "real" types here.
1096 if (!RootContext.StdLib) {
1097 system_int32_type = typeof (System.Int32);
1098 system_array_type = typeof (System.Array);
1099 system_type_type = typeof (System.Type);
1100 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1102 Type [] void_arg = { };
1103 system_int_array_get_length = GetMethod (
1104 system_array_type, "get_Length", void_arg);
1105 system_int_array_get_rank = GetMethod (
1106 system_array_type, "get_Rank", void_arg);
1107 system_object_array_clone = GetMethod (
1108 system_array_type, "Clone", void_arg);
1110 Type [] system_int_arg = { system_int32_type };
1111 system_int_array_get_length_int = GetMethod (
1112 system_array_type, "GetLength", system_int_arg);
1113 system_int_array_get_upper_bound_int = GetMethod (
1114 system_array_type, "GetUpperBound", system_int_arg);
1115 system_int_array_get_lower_bound_int = GetMethod (
1116 system_array_type, "GetLowerBound", system_int_arg);
1118 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1119 system_void_array_copyto_array_int = GetMethod (
1120 system_array_type, "CopyTo", system_array_int_arg);
1122 Type [] system_3_type_arg = {
1123 system_type_type, system_type_type, system_type_type };
1124 Type [] system_4_type_arg = {
1125 system_type_type, system_type_type, system_type_type, system_type_type };
1127 MethodInfo set_corlib_type_builders = GetMethod (
1128 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1129 system_4_type_arg, true, false);
1131 if (set_corlib_type_builders != null) {
1132 object[] args = new object [4];
1133 args [0] = object_type;
1134 args [1] = value_type;
1135 args [2] = enum_type;
1136 args [3] = void_type;
1138 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1140 // Compatibility for an older version of the class libs.
1141 set_corlib_type_builders = GetMethod (
1142 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1143 system_3_type_arg, true, true);
1145 if (set_corlib_type_builders == null) {
1146 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1150 object[] args = new object [3];
1151 args [0] = object_type;
1152 args [1] = value_type;
1153 args [2] = enum_type;
1155 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1159 system_object_expr.Type = object_type;
1160 system_string_expr.Type = string_type;
1161 system_boolean_expr.Type = bool_type;
1162 system_decimal_expr.Type = decimal_type;
1163 system_single_expr.Type = float_type;
1164 system_double_expr.Type = double_type;
1165 system_sbyte_expr.Type = sbyte_type;
1166 system_byte_expr.Type = byte_type;
1167 system_int16_expr.Type = short_type;
1168 system_uint16_expr.Type = ushort_type;
1169 system_int32_expr.Type = int32_type;
1170 system_uint32_expr.Type = uint32_type;
1171 system_int64_expr.Type = int64_type;
1172 system_uint64_expr.Type = uint64_type;
1173 system_char_expr.Type = char_type;
1174 system_void_expr.Type = void_type;
1175 system_asynccallback_expr.Type = asynccallback_type;
1176 system_iasyncresult_expr.Type = iasyncresult_type;
1177 system_valuetype_expr.Type = value_type;
1180 // These are only used for compare purposes
1182 anonymous_method_type = typeof (AnonymousMethod);
1183 null_type = typeof (NullType);
1187 // The helper methods that are used by the compiler
1189 public static void InitCodeHelpers ()
1192 // Now load the default methods that we use.
1194 Type [] string_string = { string_type, string_type };
1195 string_concat_string_string = GetMethod (
1196 string_type, "Concat", string_string);
1197 Type [] string_string_string = { string_type, string_type, string_type };
1198 string_concat_string_string_string = GetMethod (
1199 string_type, "Concat", string_string_string);
1200 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1201 string_concat_string_string_string_string = GetMethod (
1202 string_type, "Concat", string_string_string_string);
1203 Type[] params_string = { GetConstructedType (string_type, "[]") };
1204 string_concat_string_dot_dot_dot = GetMethod (
1205 string_type, "Concat", params_string);
1207 Type [] object_object = { object_type, object_type };
1208 string_concat_object_object = GetMethod (
1209 string_type, "Concat", object_object);
1210 Type [] object_object_object = { object_type, object_type, object_type };
1211 string_concat_object_object_object = GetMethod (
1212 string_type, "Concat", object_object_object);
1213 Type[] params_object = { GetConstructedType (object_type, "[]") };
1214 string_concat_object_dot_dot_dot = GetMethod (
1215 string_type, "Concat", params_object);
1217 Type [] string_ = { string_type };
1218 string_isinterneted_string = GetMethod (
1219 string_type, "IsInterned", string_);
1221 Type [] runtime_type_handle = { runtime_handle_type };
1222 system_type_get_type_from_handle = GetMethod (
1223 type_type, "GetTypeFromHandle", runtime_type_handle);
1225 Type [] delegate_delegate = { delegate_type, delegate_type };
1226 delegate_combine_delegate_delegate = GetMethod (
1227 delegate_type, "Combine", delegate_delegate);
1229 delegate_remove_delegate_delegate = GetMethod (
1230 delegate_type, "Remove", delegate_delegate);
1235 Type [] void_arg = { };
1236 object_getcurrent_void = GetMethod (
1237 ienumerator_type, "get_Current", void_arg);
1238 bool_movenext_void = GetMethod (
1239 ienumerator_type, "MoveNext", void_arg);
1240 void_reset_void = GetMethod (
1241 ienumerator_type, "Reset", void_arg);
1242 void_dispose_void = GetMethod (
1243 idisposable_type, "Dispose", void_arg);
1244 int_get_offset_to_string_data = GetMethod (
1245 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1246 int_array_get_length = GetMethod (
1247 array_type, "get_Length", void_arg);
1248 int_array_get_rank = GetMethod (
1249 array_type, "get_Rank", void_arg);
1250 ienumerable_getenumerator_void = GetMethod (
1251 ienumerable_type, "GetEnumerator", void_arg);
1256 Type [] int_arg = { int32_type };
1257 int_array_get_length_int = GetMethod (
1258 array_type, "GetLength", int_arg);
1259 int_array_get_upper_bound_int = GetMethod (
1260 array_type, "GetUpperBound", int_arg);
1261 int_array_get_lower_bound_int = GetMethod (
1262 array_type, "GetLowerBound", int_arg);
1265 // System.Array methods
1267 object_array_clone = GetMethod (
1268 array_type, "Clone", void_arg);
1269 Type [] array_int_arg = { array_type, int32_type };
1270 void_array_copyto_array_int = GetMethod (
1271 array_type, "CopyTo", array_int_arg);
1276 Type [] object_arg = { object_type };
1277 void_monitor_enter_object = GetMethod (
1278 monitor_type, "Enter", object_arg);
1279 void_monitor_exit_object = GetMethod (
1280 monitor_type, "Exit", object_arg);
1282 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1284 void_initializearray_array_fieldhandle = GetMethod (
1285 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1290 int_getlength_int = GetMethod (
1291 array_type, "GetLength", int_arg);
1294 // Decimal constructors
1296 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1297 void_decimal_ctor_five_args = GetConstructor (
1298 decimal_type, dec_arg);
1300 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1305 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1306 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1307 default_member_ctor = GetConstructor (default_member_type, string_);
1309 Type[] short_arg = { short_type };
1310 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1312 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1313 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1320 compiler_generated_attr = new CustomAttributeBuilder (
1321 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1323 Type[] type_int_arg = { type_type, int32_type };
1324 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1328 object_ctor = GetConstructor (object_type, void_arg);
1332 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1335 /// This is the "old", non-cache based FindMembers() function. We cannot use
1336 /// the cache here because there is no member name argument.
1338 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1339 MemberFilter filter, object criteria)
1341 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1344 // `builder_to_declspace' contains all dynamic types.
1348 Timer.StartTimer (TimerType.FindMembers);
1349 list = decl.FindMembers (mt, bf, filter, criteria);
1350 Timer.StopTimer (TimerType.FindMembers);
1355 // We have to take care of arrays specially, because GetType on
1356 // a TypeBuilder array will return a Type, not a TypeBuilder,
1357 // and we can not call FindMembers on this type.
1359 if (t.IsSubclassOf (TypeManager.array_type))
1360 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1363 // Since FindMembers will not lookup both static and instance
1364 // members, we emulate this behaviour here.
1366 if ((bf & instance_and_static) == instance_and_static){
1367 MemberInfo [] i_members = t.FindMembers (
1368 mt, bf & ~BindingFlags.Static, filter, criteria);
1370 int i_len = i_members.Length;
1372 MemberInfo one = i_members [0];
1375 // If any of these are present, we are done!
1377 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1378 return new MemberList (i_members);
1381 MemberInfo [] s_members = t.FindMembers (
1382 mt, bf & ~BindingFlags.Instance, filter, criteria);
1384 int s_len = s_members.Length;
1385 if (i_len > 0 || s_len > 0)
1386 return new MemberList (i_members, s_members);
1389 return new MemberList (i_members);
1391 return new MemberList (s_members);
1395 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1400 /// This method is only called from within MemberLookup. It tries to use the member
1401 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1402 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1403 /// our return value will already contain all inherited members and the caller don't need
1404 /// to check base classes and interfaces anymore.
1406 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1407 string name, out bool used_cache)
1412 // We have to take care of arrays specially, because GetType on
1413 // a TypeBuilder array will return a Type, not a TypeBuilder,
1414 // and we can not call FindMembers on this type.
1416 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1418 return TypeHandle.ArrayType.MemberCache.FindMembers (
1419 mt, bf, name, FilterWithClosure_delegate, null);
1423 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1424 // and we can ask the DeclSpace for the MemberCache.
1426 if (t is TypeBuilder) {
1427 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1428 cache = decl.MemberCache;
1431 // If this DeclSpace has a MemberCache, use it.
1434 if (cache != null) {
1436 return cache.FindMembers (
1437 mt, bf, name, FilterWithClosure_delegate, null);
1440 // If there is no MemberCache, we need to use the "normal" FindMembers.
1441 // Note, this is a VERY uncommon route!
1444 Timer.StartTimer (TimerType.FindMembers);
1445 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1446 FilterWithClosure_delegate, name);
1447 Timer.StopTimer (TimerType.FindMembers);
1450 return (MemberInfo []) list;
1454 // This call will always succeed. There is exactly one TypeHandle instance per
1455 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1456 // the corresponding MemberCache.
1458 cache = TypeHandle.GetMemberCache (t);
1461 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1464 public static bool IsBuiltinType (Type t)
1466 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1467 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1468 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1469 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1475 public static bool IsBuiltinType (TypeContainer tc)
1477 return IsBuiltinType (tc.TypeBuilder);
1481 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1482 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1484 public static bool IsPrimitiveType (Type t)
1486 return (t == int32_type || t == uint32_type ||
1487 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1488 t == char_type || t == short_type || t == bool_type ||
1489 t == sbyte_type || t == byte_type || t == ushort_type);
1492 public static bool IsDelegateType (Type t)
1494 if (t.IsSubclassOf (TypeManager.delegate_type))
1500 public static bool IsEnumType (Type t)
1502 if (t.IsSubclassOf (TypeManager.enum_type))
1507 public static bool IsBuiltinOrEnum (Type t)
1509 if (IsBuiltinType (t))
1519 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1521 public static bool IsUnmanagedType (Type t)
1523 // builtins that are not unmanaged types
1524 if (t == TypeManager.object_type || t == TypeManager.string_type)
1527 if (IsBuiltinOrEnum (t))
1534 return IsUnmanagedType (t.GetElementType ());
1536 if (t is TypeBuilder){
1537 TypeContainer tc = LookupTypeContainer (t);
1539 if (tc.Fields == null)
1541 foreach (Field f in tc.Fields){
1542 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1543 if ((f.ModFlags & Modifiers.STATIC) != 0)
1545 if (!IsUnmanagedType (f.MemberType))
1551 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1553 foreach (FieldInfo f in fields)
1554 if (!IsUnmanagedType (f.FieldType))
1560 public static bool IsValueType (Type t)
1562 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1568 public static bool IsInterfaceType (Type t)
1570 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1574 return tc.Kind == Kind.Interface;
1577 public static bool IsSubclassOf (Type type, Type base_type)
1580 if (type.Equals (base_type))
1583 type = type.BaseType;
1584 } while (type != null);
1589 public static bool IsFamilyAccessible (Type type, Type base_type)
1591 return IsSubclassOf (type, base_type);
1595 // Checks whether `type' is a subclass or nested child of `base_type'.
1597 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1600 if ((type == base_type) || type.IsSubclassOf (base_type))
1603 // Handle nested types.
1604 type = type.DeclaringType;
1605 } while (type != null);
1611 // Checks whether `type' is a nested child of `parent'.
1613 public static bool IsNestedChildOf (Type type, Type parent)
1618 type = type.DeclaringType;
1619 while (type != null) {
1623 type = type.DeclaringType;
1630 // Do the right thing when returning the element type of an
1631 // array type based on whether we are compiling corlib or not
1633 public static Type GetElementType (Type t)
1635 if (RootContext.StdLib)
1636 return t.GetElementType ();
1638 return TypeToCoreType (t.GetElementType ());
1642 /// This method is not implemented by MS runtime for dynamic types
1644 public static bool HasElementType (Type t)
1646 return t.IsArray || t.IsPointer || t.IsByRef;
1650 /// Returns the User Defined Types
1652 public static ArrayList UserTypes {
1658 public static Hashtable TypeContainers {
1660 return typecontainers;
1664 static Hashtable builder_to_constant;
1666 public static void RegisterConstant (FieldBuilder fb, Const c)
1668 if (builder_to_constant == null)
1669 builder_to_constant = new PtrHashtable ();
1671 if (builder_to_constant.Contains (fb))
1674 builder_to_constant.Add (fb, c);
1677 public static Const LookupConstant (FieldBuilder fb)
1679 if (builder_to_constant == null)
1682 return (Const) builder_to_constant [fb];
1686 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1690 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1691 /// for anything which is dynamic, and we need this in a number of places,
1692 /// we register this information here, and use it afterwards.
1694 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1699 method_arguments.Add (mb, args);
1700 method_params.Add (mb, ip);
1703 static public ParameterData GetParameterData (MethodBase mb)
1705 object pd = method_params [mb];
1707 if (mb is MethodBuilder || mb is ConstructorBuilder)
1708 throw new InternalErrorException ("Argument for Method not registered" + mb);
1710 method_params [mb] = pd = new ReflectionParameters (mb);
1713 return (ParameterData) pd;
1717 /// Returns the argument types for a method based on its methodbase
1719 /// For dynamic methods, we use the compiler provided types, for
1720 /// methods from existing assemblies we load them from GetParameters,
1721 /// and insert them into the cache
1723 static public Type [] GetArgumentTypes (MethodBase mb)
1725 object t = method_arguments [mb];
1729 ParameterInfo [] pi = mb.GetParameters ();
1736 types = new Type [c];
1737 for (int i = 0; i < c; i++)
1738 types [i] = pi [i].ParameterType;
1740 method_arguments.Add (mb, types);
1745 /// Returns the argument types for an indexer based on its PropertyInfo
1747 /// For dynamic indexers, we use the compiler provided types, for
1748 /// indexers from existing assemblies we load them from GetParameters,
1749 /// and insert them into the cache
1751 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1753 if (indexer_arguments.Contains (indexer))
1754 return (Type []) indexer_arguments [indexer];
1755 else if (indexer is PropertyBuilder)
1756 // If we're a PropertyBuilder and not in the
1757 // `indexer_arguments' hash, then we're a property and
1761 ParameterInfo [] pi = indexer.GetIndexParameters ();
1762 // Property, not an indexer.
1766 Type [] types = new Type [c];
1768 for (int i = 0; i < c; i++)
1769 types [i] = pi [i].ParameterType;
1771 indexer_arguments.Add (indexer, types);
1777 // This is a workaround the fact that GetValue is not
1778 // supported for dynamic types
1780 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1782 if (fields.Contains (fb))
1785 fields.Add (fb, value);
1790 static public object GetValue (FieldBuilder fb)
1795 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1797 if (fieldbuilders_to_fields.Contains (fb))
1800 fieldbuilders_to_fields.Add (fb, f);
1805 // The return value can be null; This will be the case for
1806 // auxiliary FieldBuilders created by the compiler that have no
1807 // real field being declared on the source code
1809 static public FieldBase GetField (FieldInfo fb)
1811 return (FieldBase) fieldbuilders_to_fields [fb];
1814 static Hashtable events;
1816 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1819 events = new Hashtable ();
1821 if (!events.Contains (eb)) {
1822 events.Add (eb, new Pair (add, remove));
1826 static public MethodInfo GetAddMethod (EventInfo ei)
1828 if (ei is MyEventBuilder) {
1829 Pair pair = (Pair) events [ei];
1831 return (MethodInfo) pair.First;
1833 return ei.GetAddMethod (true);
1836 static public MethodInfo GetRemoveMethod (EventInfo ei)
1838 if (ei is MyEventBuilder) {
1839 Pair pair = (Pair) events [ei];
1841 return (MethodInfo) pair.Second;
1843 return ei.GetRemoveMethod (true);
1846 static Hashtable priv_fields_events;
1848 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1850 if (priv_fields_events == null)
1851 priv_fields_events = new Hashtable ();
1853 if (priv_fields_events.Contains (einfo))
1856 priv_fields_events.Add (einfo, builder);
1861 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1863 if (priv_fields_events == null)
1866 return (MemberInfo) priv_fields_events [ei];
1869 static Hashtable properties;
1871 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1873 if (properties == null)
1874 properties = new Hashtable ();
1876 if (properties.Contains (pb))
1879 properties.Add (pb, new Pair (get, set));
1884 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1885 MethodBase set, Type[] args)
1887 if (!RegisterProperty (pb, get,set))
1890 indexer_arguments.Add (pb, args);
1895 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1897 Hashtable hash = new Hashtable ();
1898 return CheckStructCycles (tc, seen, hash);
1901 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1904 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1908 // `seen' contains all types we've already visited.
1910 if (seen.Contains (tc))
1912 seen.Add (tc, null);
1914 if (tc.Fields == null)
1917 foreach (FieldMember field in tc.Fields) {
1918 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1921 Type ftype = field.FieldBuilder.FieldType;
1922 TypeContainer ftc = LookupTypeContainer (ftype);
1926 if (hash.Contains (ftc)) {
1927 Report.Error (523, tc.Location,
1928 "Struct member `{0}.{1}' of type `{2}' " +
1929 "causes a cycle in the struct layout",
1930 tc.Name, field.Name, ftc.Name);
1935 // `hash' contains all types in the current path.
1937 hash.Add (tc, null);
1939 bool ok = CheckStructCycles (ftc, seen, hash);
1946 if (!seen.Contains (ftc))
1947 seen.Add (ftc, null);
1954 /// Given an array of interface types, expand and eliminate repeated ocurrences
1955 /// of an interface.
1959 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1962 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1964 ArrayList new_ifaces = new ArrayList ();
1966 foreach (TypeExpr iface in base_interfaces){
1967 Type itype = iface.ResolveType (ec);
1971 if (!new_ifaces.Contains (itype))
1972 new_ifaces.Add (itype);
1974 Type [] implementing = itype.GetInterfaces ();
1976 foreach (Type imp in implementing){
1977 if (!new_ifaces.Contains (imp))
1978 new_ifaces.Add (imp);
1981 Type [] ret = new Type [new_ifaces.Count];
1982 new_ifaces.CopyTo (ret, 0);
1986 static PtrHashtable iface_cache = new PtrHashtable ();
1989 /// This function returns the interfaces in the type `t'. Works with
1990 /// both types and TypeBuilders.
1992 public static Type [] GetInterfaces (Type t)
1995 Type [] cached = iface_cache [t] as Type [];
2000 // The reason for catching the Array case is that Reflection.Emit
2001 // will not return a TypeBuilder for Array types of TypeBuilder types,
2002 // but will still throw an exception if we try to call GetInterfaces
2005 // Since the array interfaces are always constant, we return those for
2010 t = TypeManager.array_type;
2012 if (t is TypeBuilder){
2013 Type [] base_ifaces;
2015 if (t.BaseType == null)
2016 base_ifaces = NoTypes;
2018 base_ifaces = GetInterfaces (t.BaseType);
2019 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
2020 if (type_ifaces == null)
2021 type_ifaces = NoTypes;
2023 int base_count = base_ifaces.Length;
2024 Type [] result = new Type [base_count + type_ifaces.Length];
2025 base_ifaces.CopyTo (result, 0);
2026 type_ifaces.CopyTo (result, base_count);
2028 iface_cache [t] = result;
2031 Type[] ifaces = t.GetInterfaces ();
2032 iface_cache [t] = ifaces;
2038 // gets the interfaces that are declared explicitly on t
2040 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2042 return (Type []) builder_to_ifaces [t];
2046 /// The following is used to check if a given type implements an interface.
2047 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2049 public static bool ImplementsInterface (Type t, Type iface)
2054 // FIXME OPTIMIZATION:
2055 // as soon as we hit a non-TypeBuiler in the interface
2056 // chain, we could return, as the `Type.GetInterfaces'
2057 // will return all the interfaces implement by the type
2061 interfaces = GetInterfaces (t);
2063 if (interfaces != null){
2064 foreach (Type i in interfaces){
2071 } while (t != null);
2076 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2078 // This is a custom version of Convert.ChangeType() which works
2079 // with the TypeBuilder defined types when compiling corlib.
2080 public static object ChangeType (object value, Type conversionType, out bool error)
2082 IConvertible convert_value = value as IConvertible;
2084 if (convert_value == null){
2090 // We must use Type.Equals() here since `conversionType' is
2091 // the TypeBuilder created version of a system type and not
2092 // the system type itself. You cannot use Type.GetTypeCode()
2093 // on such a type - it'd always return TypeCode.Object.
2097 if (conversionType.Equals (typeof (Boolean)))
2098 return (object)(convert_value.ToBoolean (nf_provider));
2099 else if (conversionType.Equals (typeof (Byte)))
2100 return (object)(convert_value.ToByte (nf_provider));
2101 else if (conversionType.Equals (typeof (Char)))
2102 return (object)(convert_value.ToChar (nf_provider));
2103 else if (conversionType.Equals (typeof (DateTime)))
2104 return (object)(convert_value.ToDateTime (nf_provider));
2105 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2106 return (object)(convert_value.ToDecimal (nf_provider));
2107 else if (conversionType.Equals (typeof (Double)))
2108 return (object)(convert_value.ToDouble (nf_provider));
2109 else if (conversionType.Equals (typeof (Int16)))
2110 return (object)(convert_value.ToInt16 (nf_provider));
2111 else if (conversionType.Equals (typeof (Int32)))
2112 return (object)(convert_value.ToInt32 (nf_provider));
2113 else if (conversionType.Equals (typeof (Int64)))
2114 return (object)(convert_value.ToInt64 (nf_provider));
2115 else if (conversionType.Equals (typeof (SByte)))
2116 return (object)(convert_value.ToSByte (nf_provider));
2117 else if (conversionType.Equals (typeof (Single)))
2118 return (object)(convert_value.ToSingle (nf_provider));
2119 else if (conversionType.Equals (typeof (String)))
2120 return (object)(convert_value.ToString (nf_provider));
2121 else if (conversionType.Equals (typeof (UInt16)))
2122 return (object)(convert_value.ToUInt16 (nf_provider));
2123 else if (conversionType.Equals (typeof (UInt32)))
2124 return (object)(convert_value.ToUInt32 (nf_provider));
2125 else if (conversionType.Equals (typeof (UInt64)))
2126 return (object)(convert_value.ToUInt64 (nf_provider));
2127 else if (conversionType.Equals (typeof (Object)))
2128 return (object)(value);
2138 // This is needed, because enumerations from assemblies
2139 // do not report their underlyingtype, but they report
2142 public static Type EnumToUnderlying (Type t)
2144 if (t == TypeManager.enum_type)
2147 t = t.UnderlyingSystemType;
2148 if (!TypeManager.IsEnumType (t))
2151 if (t is TypeBuilder) {
2152 // slow path needed to compile corlib
2153 if (t == TypeManager.bool_type ||
2154 t == TypeManager.byte_type ||
2155 t == TypeManager.sbyte_type ||
2156 t == TypeManager.char_type ||
2157 t == TypeManager.short_type ||
2158 t == TypeManager.ushort_type ||
2159 t == TypeManager.int32_type ||
2160 t == TypeManager.uint32_type ||
2161 t == TypeManager.int64_type ||
2162 t == TypeManager.uint64_type)
2164 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2166 TypeCode tc = Type.GetTypeCode (t);
2169 case TypeCode.Boolean:
2170 return TypeManager.bool_type;
2172 return TypeManager.byte_type;
2173 case TypeCode.SByte:
2174 return TypeManager.sbyte_type;
2176 return TypeManager.char_type;
2177 case TypeCode.Int16:
2178 return TypeManager.short_type;
2179 case TypeCode.UInt16:
2180 return TypeManager.ushort_type;
2181 case TypeCode.Int32:
2182 return TypeManager.int32_type;
2183 case TypeCode.UInt32:
2184 return TypeManager.uint32_type;
2185 case TypeCode.Int64:
2186 return TypeManager.int64_type;
2187 case TypeCode.UInt64:
2188 return TypeManager.uint64_type;
2190 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2194 // When compiling corlib and called with one of the core types, return
2195 // the corresponding typebuilder for that type.
2197 public static Type TypeToCoreType (Type t)
2199 if (RootContext.StdLib || (t is TypeBuilder))
2202 TypeCode tc = Type.GetTypeCode (t);
2205 case TypeCode.Boolean:
2206 return TypeManager.bool_type;
2208 return TypeManager.byte_type;
2209 case TypeCode.SByte:
2210 return TypeManager.sbyte_type;
2212 return TypeManager.char_type;
2213 case TypeCode.Int16:
2214 return TypeManager.short_type;
2215 case TypeCode.UInt16:
2216 return TypeManager.ushort_type;
2217 case TypeCode.Int32:
2218 return TypeManager.int32_type;
2219 case TypeCode.UInt32:
2220 return TypeManager.uint32_type;
2221 case TypeCode.Int64:
2222 return TypeManager.int64_type;
2223 case TypeCode.UInt64:
2224 return TypeManager.uint64_type;
2225 case TypeCode.Single:
2226 return TypeManager.float_type;
2227 case TypeCode.Double:
2228 return TypeManager.double_type;
2229 case TypeCode.String:
2230 return TypeManager.string_type;
2231 case TypeCode.Decimal:
2232 return TypeManager.decimal_type;
2234 if (t == typeof (void))
2235 return TypeManager.void_type;
2236 if (t == typeof (object))
2237 return TypeManager.object_type;
2238 if (t == typeof (System.Type))
2239 return TypeManager.type_type;
2240 if (t == typeof (System.IntPtr))
2241 return TypeManager.intptr_type;
2247 /// Utility function that can be used to probe whether a type
2248 /// is managed or not.
2250 public static bool VerifyUnManaged (Type t, Location loc)
2252 if (IsUnmanagedType (t))
2255 // We need this explicit check here to make it work when compiling corlib.
2256 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
2261 "Cannot take the address or size of a variable of a managed type ('" +
2262 CSharpName (t) + "')");
2267 /// Returns the name of the indexer in a given type.
2270 /// The default is not always `Item'. The user can change this behaviour by
2271 /// using the IndexerNameAttribute in the container.
2272 /// For example, the String class indexer is named `Chars' not `Item'
2274 public static string IndexerPropertyName (Type t)
2276 if (t is TypeBuilder) {
2277 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2278 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2281 System.Attribute attr = System.Attribute.GetCustomAttribute (
2282 t, TypeManager.default_member_type);
2284 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2285 return dma.MemberName;
2288 return TypeContainer.DefaultIndexerName;
2291 static MethodInfo declare_local_method = null;
2293 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2295 if (declare_local_method == null){
2296 declare_local_method = typeof (ILGenerator).GetMethod (
2298 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2300 new Type [] { typeof (Type), typeof (bool)},
2302 if (declare_local_method == null){
2303 Report.Warning (-24, new Location (-1),
2304 "This version of the runtime does not support making pinned local variables. " +
2305 "This code may cause errors on a runtime with a moving GC");
2306 return ig.DeclareLocal (t);
2309 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2313 // Returns whether the array of memberinfos contains the given method
2315 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2317 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2319 foreach (MethodBase method in array) {
2320 if (method.Name != new_method.Name)
2323 if (method is MethodInfo && new_method is MethodInfo)
2324 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2328 Type [] old_args = TypeManager.GetArgumentTypes (method);
2329 int old_count = old_args.Length;
2332 if (new_args.Length != old_count)
2335 for (i = 0; i < old_count; i++){
2336 if (old_args [i] != new_args [i])
2349 // We copy methods from `new_members' into `target_list' if the signature
2350 // for the method from in the new list does not exist in the target_list
2352 // The name is assumed to be the same.
2354 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2356 if (target_list == null){
2357 target_list = new ArrayList ();
2359 foreach (MemberInfo mi in new_members){
2360 if (mi is MethodBase)
2361 target_list.Add (mi);
2366 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2367 target_list.CopyTo (target_array, 0);
2369 foreach (MemberInfo mi in new_members){
2370 MethodBase new_method = (MethodBase) mi;
2372 if (!ArrayContainsMethod (target_array, new_method))
2373 target_list.Add (new_method);
2379 #region MemberLookup implementation
2382 // Whether we allow private members in the result (since FindMembers
2383 // uses NonPublic for both protected and private), we need to distinguish.
2386 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2391 internal class Closure {
2392 internal bool private_ok;
2394 // Who is invoking us and which type is being queried currently.
2395 internal Type invocation_type;
2396 internal Type qualifier_type;
2398 // The assembly that defines the type is that is calling us
2399 internal Assembly invocation_assembly;
2400 internal IList almost_match;
2402 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2404 if (invocation_type == null)
2407 Debug.Assert (IsNestedFamilyAccessible (invocation_type, m.DeclaringType));
2412 // A nested class has access to all the protected members visible to its parent.
2413 if (qualifier_type != null
2414 && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2417 if (invocation_type == m.DeclaringType
2418 || invocation_type.IsSubclassOf (m.DeclaringType)) {
2419 // Although a derived class can access protected members of its base class
2420 // it cannot do so through an instance of the base class (CS1540).
2421 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2422 if (qualifier_type == null
2423 || qualifier_type == invocation_type
2424 || qualifier_type.IsSubclassOf (invocation_type))
2428 if (almost_match != null)
2429 almost_match.Add (m);
2434 // This filter filters by name + whether it is ok to include private
2435 // members in the search
2437 internal bool Filter (MemberInfo m, object filter_criteria)
2440 // Hack: we know that the filter criteria will always be in the `closure'
2444 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2447 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2448 (m.DeclaringType == invocation_type))
2452 // Ugly: we need to find out the type of `m', and depending
2453 // on this, tell whether we accept or not
2455 if (m is MethodBase){
2456 MethodBase mb = (MethodBase) m;
2457 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2459 if (ma == MethodAttributes.Private)
2460 return private_ok || (invocation_type == m.DeclaringType) ||
2461 IsNestedChildOf (invocation_type, m.DeclaringType);
2463 // Assembly succeeds if we're in the same assembly.
2464 if (ma == MethodAttributes.Assembly)
2465 return (invocation_assembly == mb.DeclaringType.Assembly);
2467 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2468 if (ma == MethodAttributes.FamANDAssem){
2469 if (invocation_assembly != mb.DeclaringType.Assembly)
2473 // Family and FamANDAssem require that we derive.
2474 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem))
2475 return CheckValidFamilyAccess (mb.IsStatic, m);
2481 if (m is FieldInfo){
2482 FieldInfo fi = (FieldInfo) m;
2483 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2485 if (fa == FieldAttributes.Private)
2486 return private_ok || (invocation_type == m.DeclaringType) ||
2487 IsNestedChildOf (invocation_type, m.DeclaringType);
2489 // Assembly succeeds if we're in the same assembly.
2490 if (fa == FieldAttributes.Assembly)
2491 return (invocation_assembly == fi.DeclaringType.Assembly);
2493 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2494 if (fa == FieldAttributes.FamANDAssem){
2495 if (invocation_assembly != fi.DeclaringType.Assembly)
2499 // Family and FamANDAssem require that we derive.
2500 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem))
2501 return CheckValidFamilyAccess (fi.IsStatic, m);
2508 // EventInfos and PropertyInfos, return true because they lack permission
2509 // information, so we need to check later on the methods.
2515 static Closure closure = new Closure ();
2516 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2519 // Looks up a member called `name' in the `queried_type'. This lookup
2520 // is done by code that is contained in the definition for `invocation_type'
2521 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2523 // `invocation_type' is used to check whether we're allowed to access the requested
2524 // member wrt its protection level.
2526 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2527 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2528 // is B and qualifier_type is A). This is used to do the CS1540 check.
2530 // When resolving a SimpleName, `qualifier_type' is null.
2532 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2533 // the same than `queried_type' - except when we're being called from BaseAccess;
2534 // in this case, `invocation_type' is the current type and `queried_type' the base
2535 // type, so this'd normally trigger a CS1540.
2537 // The binding flags are `bf' and the kind of members being looked up are `mt'
2539 // The return value always includes private members which code in `invocation_type'
2540 // is allowed to access (using the specified `qualifier_type' if given); only use
2541 // BindingFlags.NonPublic to bypass the permission check.
2543 // The 'almost_match' argument is used for reporting error CS1540.
2545 // Returns an array of a single element for everything but Methods/Constructors
2546 // that might return multiple matches.
2548 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2549 Type queried_type, MemberTypes mt,
2550 BindingFlags original_bf, string name, IList almost_match)
2552 Timer.StartTimer (TimerType.MemberLookup);
2554 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2555 queried_type, mt, original_bf, name, almost_match);
2557 Timer.StopTimer (TimerType.MemberLookup);
2562 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2563 Type queried_type, MemberTypes mt,
2564 BindingFlags original_bf, string name, IList almost_match)
2566 BindingFlags bf = original_bf;
2568 ArrayList method_list = null;
2569 Type current_type = queried_type;
2570 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2571 bool skip_iface_check = true, used_cache = false;
2572 bool always_ok_flag = false;
2574 closure.invocation_type = invocation_type;
2575 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2576 closure.qualifier_type = qualifier_type;
2577 closure.almost_match = almost_match;
2580 // If we are a nested class, we always have access to our container
2583 if (invocation_type != null){
2584 string invocation_name = invocation_type.FullName;
2585 if (invocation_name.IndexOf ('+') != -1){
2586 string container = queried_type.FullName + "+";
2587 int container_length = container.Length;
2589 if (invocation_name.Length > container_length){
2590 string shared = invocation_name.Substring (0, container_length);
2592 if (shared == container)
2593 always_ok_flag = true;
2598 // This is from the first time we find a method
2599 // in most cases, we do not actually find a method in the base class
2600 // so we can just ignore it, and save the arraylist allocation
2601 MemberInfo [] first_members_list = null;
2602 bool use_first_members_list = false;
2608 // `NonPublic' is lame, because it includes both protected and
2609 // private methods, so we need to control this behavior by
2610 // explicitly tracking if a private method is ok or not.
2612 // The possible cases are:
2613 // public, private and protected (internal does not come into the
2616 if ((invocation_type != null) &&
2617 ((invocation_type == current_type) ||
2618 IsNestedChildOf (invocation_type, current_type)) ||
2620 bf = original_bf | BindingFlags.NonPublic;
2624 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2626 Timer.StopTimer (TimerType.MemberLookup);
2628 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2630 Timer.StartTimer (TimerType.MemberLookup);
2633 // When queried for an interface type, the cache will automatically check all
2634 // inherited members, so we don't need to do this here. However, this only
2635 // works if we already used the cache in the first iteration of this loop.
2637 // If we used the cache in any further iteration, we can still terminate the
2638 // loop since the cache always looks in all base classes.
2644 skip_iface_check = false;
2646 if (current_type == TypeManager.object_type)
2649 current_type = current_type.BaseType;
2652 // This happens with interfaces, they have a null
2653 // basetype. Look members up in the Object class.
2655 if (current_type == null) {
2656 current_type = TypeManager.object_type;
2661 if (list.Length == 0)
2665 // Events and types are returned by both `static' and `instance'
2666 // searches, which means that our above FindMembers will
2667 // return two copies of the same.
2669 if (list.Length == 1 && !(list [0] is MethodBase)){
2674 // Multiple properties: we query those just to find out the indexer
2677 if (list [0] is PropertyInfo)
2681 // We found an event: the cache lookup returns both the event and
2682 // its private field.
2684 if (list [0] is EventInfo) {
2685 if ((list.Length == 2) && (list [1] is FieldInfo))
2686 return new MemberInfo [] { list [0] };
2693 // We found methods, turn the search into "method scan"
2697 if (first_members_list != null) {
2698 if (use_first_members_list) {
2699 method_list = CopyNewMethods (method_list, first_members_list);
2700 use_first_members_list = false;
2703 method_list = CopyNewMethods (method_list, list);
2705 first_members_list = list;
2706 use_first_members_list = true;
2707 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2709 } while (searching);
2711 if (use_first_members_list) {
2712 foreach (MemberInfo mi in first_members_list) {
2713 if (! (mi is MethodBase)) {
2714 method_list = CopyNewMethods (method_list, first_members_list);
2715 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2718 return (MemberInfo []) first_members_list;
2721 if (method_list != null && method_list.Count > 0)
2722 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2725 // This happens if we already used the cache in the first iteration, in this case
2726 // the cache already looked in all interfaces.
2728 if (skip_iface_check)
2732 // Interfaces do not list members they inherit, so we have to
2735 if (!queried_type.IsInterface)
2738 if (queried_type.IsArray)
2739 queried_type = TypeManager.array_type;
2741 Type [] ifaces = GetInterfaces (queried_type);
2745 foreach (Type itype in ifaces){
2748 x = MemberLookup (null, null, itype, mt, bf, name, null);
2756 // Tests whether external method is really special
2757 public static bool IsSpecialMethod (MethodBase mb)
2759 string name = mb.Name;
2760 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2761 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2763 if (name.StartsWith ("add_"))
2764 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2766 if (name.StartsWith ("remove_"))
2767 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2769 if (name.StartsWith ("op_")){
2770 foreach (string oname in Unary.oper_names) {
2775 foreach (string oname in Binary.oper_names) {
2788 /// There is exactly one instance of this class per type.
2790 public sealed class TypeHandle : IMemberContainer {
2791 public readonly IMemberContainer BaseType;
2793 readonly int id = ++next_id;
2794 static int next_id = 0;
2796 static TypeHandle ()
2802 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2803 /// a TypeHandle yet, a new instance of it is created. This static method
2804 /// ensures that we'll only have one TypeHandle instance per type.
2806 private static TypeHandle GetTypeHandle (Type t)
2808 TypeHandle handle = (TypeHandle) type_hash [t];
2812 handle = new TypeHandle (t);
2813 type_hash.Add (t, handle);
2817 public static MemberCache GetMemberCache (Type t)
2819 return GetTypeHandle (t).MemberCache;
2822 public static void CleanUp ()
2827 public static void Reset ()
2829 type_hash = new PtrHashtable ();
2833 /// Returns the TypeHandle for TypeManager.object_type.
2835 public static IMemberContainer ObjectType {
2837 if (object_type != null)
2840 object_type = GetTypeHandle (TypeManager.object_type);
2847 /// Returns the TypeHandle for TypeManager.array_type.
2849 public static IMemberContainer ArrayType {
2851 if (array_type != null)
2854 array_type = GetTypeHandle (TypeManager.array_type);
2860 private static PtrHashtable type_hash;
2862 private static TypeHandle object_type = null;
2863 private static TypeHandle array_type = null;
2866 private bool is_interface;
2867 private MemberCache member_cache;
2868 private MemberCache base_cache;
2870 private TypeHandle (Type type)
2873 if (type.BaseType != null) {
2874 base_cache = TypeManager.LookupMemberCache (type.BaseType);
2875 BaseType = base_cache.Container;
2876 } else if (type.IsInterface)
2877 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2878 this.is_interface = type.IsInterface;
2879 this.member_cache = new MemberCache (this);
2882 // IMemberContainer methods
2884 public string Name {
2886 return type.FullName;
2896 public MemberCache BaseCache {
2902 public bool IsInterface {
2904 return is_interface;
2908 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2910 MemberInfo [] members;
2911 if (mt == MemberTypes.Event)
2912 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2914 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2916 Array.Reverse (members);
2918 return new MemberList (members);
2921 // IMemberFinder methods
2923 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2924 MemberFilter filter, object criteria)
2926 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2929 public MemberCache MemberCache {
2931 return member_cache;
2935 public override string ToString ()
2937 if (BaseType != null)
2938 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2940 return "TypeHandle (" + id + "," + Name + ")";