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;
105 static internal Type compiler_generated_attr_type;
106 static internal Type fixed_buffer_attr_type;
110 // An empty array of types
112 static public Type [] NoTypes;
113 static public TypeExpr [] NoTypeExprs;
117 // Expressions representing the internal types. Used during declaration
120 static public TypeExpr system_object_expr, system_string_expr;
121 static public TypeExpr system_boolean_expr, system_decimal_expr;
122 static public TypeExpr system_single_expr, system_double_expr;
123 static public TypeExpr system_sbyte_expr, system_byte_expr;
124 static public TypeExpr system_int16_expr, system_uint16_expr;
125 static public TypeExpr system_int32_expr, system_uint32_expr;
126 static public TypeExpr system_int64_expr, system_uint64_expr;
127 static public TypeExpr system_char_expr, system_void_expr;
128 static public TypeExpr system_asynccallback_expr;
129 static public TypeExpr system_iasyncresult_expr;
130 static public TypeExpr system_valuetype_expr;
131 static public TypeExpr system_intptr_expr;
134 // This is only used when compiling corlib
136 static public Type system_int32_type;
137 static public Type system_array_type;
138 static public Type system_type_type;
139 static public Type system_assemblybuilder_type;
140 static public MethodInfo system_int_array_get_length;
141 static public MethodInfo system_int_array_get_rank;
142 static public MethodInfo system_object_array_clone;
143 static public MethodInfo system_int_array_get_length_int;
144 static public MethodInfo system_int_array_get_lower_bound_int;
145 static public MethodInfo system_int_array_get_upper_bound_int;
146 static public MethodInfo system_void_array_copyto_array_int;
150 // Internal, not really used outside
152 static Type runtime_helpers_type;
155 // These methods are called by code generated by the compiler
157 static public MethodInfo string_concat_string_string;
158 static public MethodInfo string_concat_string_string_string;
159 static public MethodInfo string_concat_string_string_string_string;
160 static public MethodInfo string_concat_string_dot_dot_dot;
161 static public MethodInfo string_concat_object_object;
162 static public MethodInfo string_concat_object_object_object;
163 static public MethodInfo string_concat_object_dot_dot_dot;
164 static public MethodInfo string_isinterneted_string;
165 static public MethodInfo system_type_get_type_from_handle;
166 static public MethodInfo object_getcurrent_void;
167 static public MethodInfo bool_movenext_void;
168 static public MethodInfo ienumerable_getenumerator_void;
169 static public MethodInfo void_reset_void;
170 static public MethodInfo void_dispose_void;
171 static public MethodInfo void_monitor_enter_object;
172 static public MethodInfo void_monitor_exit_object;
173 static public MethodInfo void_initializearray_array_fieldhandle;
174 static public MethodInfo int_getlength_int;
175 static public MethodInfo delegate_combine_delegate_delegate;
176 static public MethodInfo delegate_remove_delegate_delegate;
177 static public MethodInfo int_get_offset_to_string_data;
178 static public MethodInfo int_array_get_length;
179 static public MethodInfo int_array_get_rank;
180 static public MethodInfo object_array_clone;
181 static public MethodInfo int_array_get_length_int;
182 static public MethodInfo int_array_get_lower_bound_int;
183 static public MethodInfo int_array_get_upper_bound_int;
184 static public MethodInfo void_array_copyto_array_int;
187 // The attribute constructors.
189 static public ConstructorInfo object_ctor;
190 static public ConstructorInfo cons_param_array_attribute;
191 static public ConstructorInfo void_decimal_ctor_five_args;
192 static public ConstructorInfo void_decimal_ctor_int_arg;
193 static public ConstructorInfo unverifiable_code_ctor;
194 static public ConstructorInfo default_member_ctor;
195 static public ConstructorInfo decimal_constant_attribute_ctor;
196 static internal ConstructorInfo struct_layout_attribute_ctor;
202 static internal CustomAttributeBuilder compiler_generated_attr;
203 static internal ConstructorInfo fixed_buffer_attr_ctor;
207 // Holds the Array of Assemblies that have been loaded
208 // (either because it is the default or the user used the
209 // -r command line option)
211 static Assembly [] assemblies;
214 // Keeps a list of modules. We used this to do lookups
215 // on the module using GetType -- needed for arrays
217 static Module [] modules;
220 // This is the type_cache from the assemblies to avoid
221 // hitting System.Reflection on every lookup.
223 static Hashtable types;
226 // This is used to hotld the corresponding TypeContainer objects
227 // since we need this in FindMembers
229 static Hashtable typecontainers;
232 // Keeps track of those types that are defined by the
235 static ArrayList user_types;
237 static PtrHashtable builder_to_declspace;
239 static PtrHashtable builder_to_member_cache;
242 // Tracks the interfaces implemented by typebuilders. We only
243 // enter those who do implement or or more interfaces
245 static PtrHashtable builder_to_ifaces;
248 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
249 // the arguments to the method
251 static Hashtable method_arguments;
254 // Maps PropertyBuilder to a Type array that contains
255 // the arguments to the indexer
257 static Hashtable indexer_arguments;
260 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
262 static Hashtable method_params;
265 // Keeps track of methods
268 static Hashtable builder_to_method;
271 // Contains all public types from referenced assemblies.
272 // This member is used only if CLS Compliance verification is required.
274 public static Hashtable all_imported_types;
276 static Hashtable fieldbuilders_to_fields;
277 static Hashtable fields;
284 public static void CleanUp ()
286 // Lets get everything clean so that we can collect before generating code
290 typecontainers = null;
292 builder_to_declspace = null;
293 builder_to_member_cache = null;
294 builder_to_ifaces = null;
295 method_arguments = null;
296 indexer_arguments = null;
297 method_params = null;
298 builder_to_method = null;
301 builder_to_constant = null;
302 fieldbuilders_to_fields = null;
304 priv_fields_events = null;
308 TypeHandle.CleanUp ();
312 /// A filter for Findmembers that uses the Signature object to
315 static bool SignatureFilter (MemberInfo mi, object criteria)
317 Signature sig = (Signature) criteria;
319 if (!(mi is MethodBase))
322 if (mi.Name != sig.name)
325 int count = sig.args.Length;
327 if (mi is MethodBuilder || mi is ConstructorBuilder){
328 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
330 if (candidate_args.Length != count)
333 for (int i = 0; i < count; i++)
334 if (candidate_args [i] != sig.args [i])
339 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
341 if (pars.Length != count)
344 for (int i = 0; i < count; i++)
345 if (pars [i].ParameterType != sig.args [i])
351 // A delegate that points to the filter above.
352 static MemberFilter signature_filter;
355 // These are expressions that represent some of the internal data types, used
358 static void InitExpressionTypes ()
360 system_object_expr = new TypeLookupExpression ("System.Object");
361 system_string_expr = new TypeLookupExpression ("System.String");
362 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
363 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
364 system_single_expr = new TypeLookupExpression ("System.Single");
365 system_double_expr = new TypeLookupExpression ("System.Double");
366 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
367 system_byte_expr = new TypeLookupExpression ("System.Byte");
368 system_int16_expr = new TypeLookupExpression ("System.Int16");
369 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
370 system_int32_expr = new TypeLookupExpression ("System.Int32");
371 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
372 system_int64_expr = new TypeLookupExpression ("System.Int64");
373 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
374 system_char_expr = new TypeLookupExpression ("System.Char");
375 system_void_expr = new TypeLookupExpression ("System.Void");
376 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
377 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
378 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
379 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
382 static TypeManager ()
386 signature_filter = new MemberFilter (SignatureFilter);
387 InitExpressionTypes ();
390 static public void Reset ()
392 assemblies = new Assembly [0];
394 user_types = new ArrayList ();
396 types = new Hashtable ();
397 typecontainers = new Hashtable ();
399 builder_to_declspace = new PtrHashtable ();
400 builder_to_member_cache = new PtrHashtable ();
401 builder_to_method = new PtrHashtable ();
402 method_arguments = new PtrHashtable ();
403 method_params = new PtrHashtable ();
404 indexer_arguments = new PtrHashtable ();
405 builder_to_ifaces = new PtrHashtable ();
407 NoTypes = new Type [0];
408 NoTypeExprs = new TypeExpr [0];
410 fieldbuilders_to_fields = new Hashtable ();
411 fields = new Hashtable ();
412 type_hash = new DoubleHash ();
415 public static void HandleDuplicate (string name, Type t)
417 Type prev = (Type) types [name];
418 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
422 // This probably never happens, as we catch this before
424 Report.Error (-17, "The type `" + name + "' has already been defined.");
428 tc = builder_to_declspace [t] as TypeContainer;
431 1595, "The type `" + name + "' is defined in an existing assembly;"+
432 " Using the new definition from: " + tc.Location);
435 1595, "The type `" + name + "' is defined in an existing assembly;");
438 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
444 public static void AddUserType (string name, TypeBuilder t)
449 HandleDuplicate (name, t);
456 // This entry point is used by types that we define under the covers
458 public static void RegisterBuilder (Type tb, Type [] ifaces)
461 builder_to_ifaces [tb] = ifaces;
464 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
466 builder_to_declspace.Add (t, tc);
467 typecontainers.Add (name, tc);
468 AddUserType (name, t);
471 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
476 HandleDuplicate (name, t);
479 builder_to_declspace.Add (t, del);
482 public static void AddEnumType (string name, TypeBuilder t, Enum en)
487 HandleDuplicate (name, t);
489 builder_to_declspace.Add (t, en);
492 public static void AddMethod (MethodBase builder, IMethodData method)
494 builder_to_method.Add (builder, method);
497 public static IMethodData GetMethod (MethodBase builder)
499 return (IMethodData) builder_to_method [builder];
503 /// Returns the DeclSpace whose Type is `t' or null if there is no
504 /// DeclSpace for `t' (ie, the Type comes from a library)
506 public static DeclSpace LookupDeclSpace (Type t)
508 return builder_to_declspace [t] as DeclSpace;
512 /// Returns the TypeContainer whose Type is `t' or null if there is no
513 /// TypeContainer for `t' (ie, the Type comes from a library)
515 public static TypeContainer LookupTypeContainer (Type t)
517 return builder_to_declspace [t] as TypeContainer;
520 public static MemberCache LookupMemberCache (Type t)
522 if (t is TypeBuilder) {
523 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
524 if (container != null)
525 return container.MemberCache;
528 return TypeHandle.GetMemberCache (t);
531 public static MemberCache LookupBaseInterfacesCache (Type t)
533 Type [] ifaces = t.GetInterfaces ();
535 if (ifaces != null && ifaces.Length == 1)
536 return LookupMemberCache (ifaces [0]);
538 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
539 MemberCache cache = builder_to_member_cache [t] as MemberCache;
543 cache = new MemberCache (ifaces);
544 builder_to_member_cache.Add (t, cache);
548 public static TypeContainer LookupInterface (Type t)
550 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
551 if ((tc == null) || (tc.Kind != Kind.Interface))
557 public static Delegate LookupDelegate (Type t)
559 return builder_to_declspace [t] as Delegate;
562 public static Enum LookupEnum (Type t)
564 return builder_to_declspace [t] as Enum;
567 public static Class LookupClass (Type t)
569 return (Class) builder_to_declspace [t];
573 /// Registers an assembly to load types from.
575 public static void AddAssembly (Assembly a)
577 foreach (Assembly assembly in assemblies) {
582 int top = assemblies.Length;
583 Assembly [] n = new Assembly [top + 1];
585 assemblies.CopyTo (n, 0);
591 public static Assembly [] GetAssemblies ()
597 /// Registers a module builder to lookup types from
599 public static void AddModule (Module mb)
601 int top = modules != null ? modules.Length : 0;
602 Module [] n = new Module [top + 1];
605 modules.CopyTo (n, 0);
610 public static Module[] Modules {
617 // We use this hash for multiple kinds of constructed types:
619 // (T, "&") Given T, get T &
620 // (T, "*") Given T, get T *
621 // (T, "[]") Given T and a array dimension, get T []
622 // (T, X) Given a type T and a simple name X, get the type T+X
624 // Accessibility tests, if necessary, should be done by the user
626 static DoubleHash type_hash = new DoubleHash ();
629 // Gets the reference to T version of the Type (T&)
631 public static Type GetReferenceType (Type t)
633 return GetConstructedType (t, "&");
637 // Gets the pointer to T version of the Type (T*)
639 public static Type GetPointerType (Type t)
641 return GetConstructedType (t, "*");
644 public static Type GetConstructedType (Type t, string dim)
647 if (!type_hash.Lookup (t, dim, out ret)) {
648 ret = t.Module.GetType (t.ToString () + dim);
649 type_hash.Insert (t, dim, ret);
654 public static Type GetNestedType (Type t, string name)
657 if (!type_hash.Lookup (t, name, out ret)) {
658 string lookup = t.ToString () + "+" + name;
659 ret = t.Module.GetType (lookup);
660 type_hash.Insert (t, name, ret);
666 // Low-level lookup, cache-less
668 public static Type LookupTypeReflection (string name)
672 foreach (Assembly a in assemblies){
673 t = a.GetType (name);
678 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
679 if (ta == TypeAttributes.NotPublic ||
680 ta == TypeAttributes.NestedPrivate ||
681 ta == TypeAttributes.NestedAssembly ||
682 ta == TypeAttributes.NestedFamANDAssem){
685 // In .NET pointers turn out to be private, even if their
686 // element type is not
689 t = t.GetElementType ();
699 foreach (Module mb in modules) {
700 t = mb.GetType (name);
709 /// Computes the namespaces that we import from the assemblies we reference.
711 public static void ComputeNamespaces ()
713 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
715 Hashtable cache = null;
718 // First add the assembly namespaces
720 if (assembly_get_namespaces != null){
721 int count = assemblies.Length;
723 for (int i = 0; i < count; i++){
724 Assembly a = assemblies [i];
725 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
726 foreach (string ns in namespaces){
729 Namespace.LookupNamespace (ns, true);
733 cache = new Hashtable ();
734 cache.Add ("", null);
735 foreach (Assembly a in assemblies) {
736 foreach (Type t in a.GetExportedTypes ()) {
737 string ns = t.Namespace;
738 if (ns == null || cache.Contains (ns))
741 Namespace.LookupNamespace (ns, true);
742 cache.Add (ns, null);
748 // Then add module namespaces
750 foreach (Module m in modules) {
751 if (m == CodeGen.Module.Builder)
754 cache = new Hashtable ();
755 cache.Add ("", null);
757 foreach (Type t in m.GetTypes ()) {
758 string ns = t.Namespace;
759 if (ns == null || cache.Contains (ns))
761 Namespace.LookupNamespace (ns, true);
762 cache.Add (ns, null);
768 /// Fills static table with exported types from all referenced assemblies.
769 /// This information is required for CLS Compliance tests.
771 public static void LoadAllImportedTypes ()
773 all_imported_types = new Hashtable ();
774 foreach (Assembly a in assemblies) {
775 foreach (Type t in a.GetExportedTypes ()) {
776 all_imported_types [t.FullName] = t;
781 public static bool NamespaceClash (string name, Location loc)
783 if (Namespace.LookupNamespace (name, false) == null)
786 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
791 /// Returns the C# name of a type if possible, or the full type name otherwise
793 static public string CSharpName (Type t)
795 return Regex.Replace (t.FullName,
797 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
798 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
799 @"Boolean|String|Void|Null)" +
801 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
804 static public string CSharpName (Type[] types)
806 StringBuilder sb = new StringBuilder ();
807 foreach (Type t in types) {
808 sb.Append (CSharpName (t));
811 sb.Remove (sb.Length - 1, 1);
812 return sb.ToString ();
815 static String CSharpNameMatch (Match match)
817 string s = match.Groups [1].Captures [0].Value;
819 Replace ("int32", "int").
820 Replace ("uint32", "uint").
821 Replace ("int16", "short").
822 Replace ("uint16", "ushort").
823 Replace ("int64", "long").
824 Replace ("uint64", "ulong").
825 Replace ("single", "float").
826 Replace ("boolean", "bool")
827 + match.Groups [2].Captures [0].Value;
831 /// Returns the signature of the method with full namespace classification
833 static public string GetFullNameSignature (MemberInfo mi)
835 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
836 return (mi is MethodBase)
837 ? GetFullNameSignature (mi as MethodBase)
838 : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
841 static public string GetFullNameSignature (MethodBase mb)
843 string name = mb.Name;
845 name = mb.DeclaringType.Name;
847 if (mb.IsSpecialName) {
848 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
849 name = name.Remove (0, 4);
856 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
860 /// Returns the signature of the property and indexer
862 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
865 return GetFullNameSignature (pb);
868 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
869 string signature = GetFullNameSignature (mb);
870 string arg = GetParameterData (mb).ParameterDesc (0);
871 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
875 /// Returns the signature of the method
877 static public string CSharpSignature (MethodBase mb)
879 StringBuilder sig = new StringBuilder ("(");
881 ParameterData iparams = GetParameterData (mb);
884 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
885 return GetFullNameSignature (mb);
887 for (int i = 0; i < iparams.Count; i++) {
891 sig.Append (iparams.ParameterDesc (i));
896 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
897 sig.Replace ('(', '[');
898 sig.Replace (')', ']');
901 return GetFullNameSignature (mb) + sig.ToString ();
905 /// Looks up a type, and aborts if it is not found. This is used
906 /// by types required by the compiler
908 static Type CoreLookupType (string name)
911 if (types.Contains (name))
912 t = (Type) types [name];
914 t = LookupTypeReflection (name);
917 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
924 /// Returns the MethodInfo for a method named `name' defined
925 /// in type `t' which takes arguments of types `args'
927 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
931 BindingFlags flags = instance_and_static | BindingFlags.Public;
937 flags |= BindingFlags.NonPublic;
939 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
940 if (list.Count == 0) {
942 Report.Error (-19, "Can not find the core function `" + name + "'");
946 MethodInfo mi = list [0] as MethodInfo;
949 Report.Error (-19, "Can not find the core function `" + name + "'");
956 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
958 return GetMethod (t, name, args, false, report_errors);
961 static MethodInfo GetMethod (Type t, string name, Type [] args)
963 return GetMethod (t, name, args, true);
968 /// Returns the ConstructorInfo for "args"
970 static ConstructorInfo GetConstructor (Type t, Type [] args)
978 list = FindMembers (t, MemberTypes.Constructor,
979 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
980 signature_filter, sig);
981 if (list.Count == 0){
982 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
986 ConstructorInfo ci = list [0] as ConstructorInfo;
988 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
995 public static void InitEnumUnderlyingTypes ()
998 int32_type = CoreLookupType ("System.Int32");
999 int64_type = CoreLookupType ("System.Int64");
1000 uint32_type = CoreLookupType ("System.UInt32");
1001 uint64_type = CoreLookupType ("System.UInt64");
1002 byte_type = CoreLookupType ("System.Byte");
1003 sbyte_type = CoreLookupType ("System.SByte");
1004 short_type = CoreLookupType ("System.Int16");
1005 ushort_type = CoreLookupType ("System.UInt16");
1009 /// The types have to be initialized after the initial
1010 /// population of the type has happened (for example, to
1011 /// bootstrap the corlib.dll
1013 public static void InitCoreTypes ()
1015 object_type = CoreLookupType ("System.Object");
1016 value_type = CoreLookupType ("System.ValueType");
1018 InitEnumUnderlyingTypes ();
1020 char_type = CoreLookupType ("System.Char");
1021 string_type = CoreLookupType ("System.String");
1022 float_type = CoreLookupType ("System.Single");
1023 double_type = CoreLookupType ("System.Double");
1024 char_ptr_type = CoreLookupType ("System.Char*");
1025 decimal_type = CoreLookupType ("System.Decimal");
1026 bool_type = CoreLookupType ("System.Boolean");
1027 enum_type = CoreLookupType ("System.Enum");
1029 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1030 delegate_type = CoreLookupType ("System.Delegate");
1032 array_type = CoreLookupType ("System.Array");
1033 void_type = CoreLookupType ("System.Void");
1034 type_type = CoreLookupType ("System.Type");
1036 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1037 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1038 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1039 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1040 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1041 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1042 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1043 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1044 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1045 idisposable_type = CoreLookupType ("System.IDisposable");
1046 icloneable_type = CoreLookupType ("System.ICloneable");
1047 iconvertible_type = CoreLookupType ("System.IConvertible");
1048 monitor_type = CoreLookupType ("System.Threading.Monitor");
1049 intptr_type = CoreLookupType ("System.IntPtr");
1051 attribute_type = CoreLookupType ("System.Attribute");
1052 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1053 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1054 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1055 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1056 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1057 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1058 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1059 typed_reference_type = CoreLookupType ("System.TypedReference");
1060 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1061 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1062 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1064 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1066 void_ptr_type = CoreLookupType ("System.Void*");
1068 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1070 exception_type = CoreLookupType ("System.Exception");
1071 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1072 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1077 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1078 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1079 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1080 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1081 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1082 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1088 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1089 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1092 // When compiling corlib, store the "real" types here.
1094 if (!RootContext.StdLib) {
1095 system_int32_type = typeof (System.Int32);
1096 system_array_type = typeof (System.Array);
1097 system_type_type = typeof (System.Type);
1098 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1100 Type [] void_arg = { };
1101 system_int_array_get_length = GetMethod (
1102 system_array_type, "get_Length", void_arg);
1103 system_int_array_get_rank = GetMethod (
1104 system_array_type, "get_Rank", void_arg);
1105 system_object_array_clone = GetMethod (
1106 system_array_type, "Clone", void_arg);
1108 Type [] system_int_arg = { system_int32_type };
1109 system_int_array_get_length_int = GetMethod (
1110 system_array_type, "GetLength", system_int_arg);
1111 system_int_array_get_upper_bound_int = GetMethod (
1112 system_array_type, "GetUpperBound", system_int_arg);
1113 system_int_array_get_lower_bound_int = GetMethod (
1114 system_array_type, "GetLowerBound", system_int_arg);
1116 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1117 system_void_array_copyto_array_int = GetMethod (
1118 system_array_type, "CopyTo", system_array_int_arg);
1120 Type [] system_3_type_arg = {
1121 system_type_type, system_type_type, system_type_type };
1122 Type [] system_4_type_arg = {
1123 system_type_type, system_type_type, system_type_type, system_type_type };
1125 MethodInfo set_corlib_type_builders = GetMethod (
1126 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1127 system_4_type_arg, true, false);
1129 if (set_corlib_type_builders != null) {
1130 object[] args = new object [4];
1131 args [0] = object_type;
1132 args [1] = value_type;
1133 args [2] = enum_type;
1134 args [3] = void_type;
1136 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1138 // Compatibility for an older version of the class libs.
1139 set_corlib_type_builders = GetMethod (
1140 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1141 system_3_type_arg, true, true);
1143 if (set_corlib_type_builders == null) {
1144 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1148 object[] args = new object [3];
1149 args [0] = object_type;
1150 args [1] = value_type;
1151 args [2] = enum_type;
1153 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1157 system_object_expr.Type = object_type;
1158 system_string_expr.Type = string_type;
1159 system_boolean_expr.Type = bool_type;
1160 system_decimal_expr.Type = decimal_type;
1161 system_single_expr.Type = float_type;
1162 system_double_expr.Type = double_type;
1163 system_sbyte_expr.Type = sbyte_type;
1164 system_byte_expr.Type = byte_type;
1165 system_int16_expr.Type = short_type;
1166 system_uint16_expr.Type = ushort_type;
1167 system_int32_expr.Type = int32_type;
1168 system_uint32_expr.Type = uint32_type;
1169 system_int64_expr.Type = int64_type;
1170 system_uint64_expr.Type = uint64_type;
1171 system_char_expr.Type = char_type;
1172 system_void_expr.Type = void_type;
1173 system_asynccallback_expr.Type = asynccallback_type;
1174 system_iasyncresult_expr.Type = iasyncresult_type;
1175 system_valuetype_expr.Type = value_type;
1178 // These are only used for compare purposes
1180 anonymous_method_type = typeof (AnonymousMethod);
1181 null_type = typeof (NullType);
1185 // The helper methods that are used by the compiler
1187 public static void InitCodeHelpers ()
1190 // Now load the default methods that we use.
1192 Type [] string_string = { string_type, string_type };
1193 string_concat_string_string = GetMethod (
1194 string_type, "Concat", string_string);
1195 Type [] string_string_string = { string_type, string_type, string_type };
1196 string_concat_string_string_string = GetMethod (
1197 string_type, "Concat", string_string_string);
1198 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1199 string_concat_string_string_string_string = GetMethod (
1200 string_type, "Concat", string_string_string_string);
1201 Type[] params_string = { GetConstructedType (string_type, "[]") };
1202 string_concat_string_dot_dot_dot = GetMethod (
1203 string_type, "Concat", params_string);
1205 Type [] object_object = { object_type, object_type };
1206 string_concat_object_object = GetMethod (
1207 string_type, "Concat", object_object);
1208 Type [] object_object_object = { object_type, object_type, object_type };
1209 string_concat_object_object_object = GetMethod (
1210 string_type, "Concat", object_object_object);
1211 Type[] params_object = { GetConstructedType (object_type, "[]") };
1212 string_concat_object_dot_dot_dot = GetMethod (
1213 string_type, "Concat", params_object);
1215 Type [] string_ = { string_type };
1216 string_isinterneted_string = GetMethod (
1217 string_type, "IsInterned", string_);
1219 Type [] runtime_type_handle = { runtime_handle_type };
1220 system_type_get_type_from_handle = GetMethod (
1221 type_type, "GetTypeFromHandle", runtime_type_handle);
1223 Type [] delegate_delegate = { delegate_type, delegate_type };
1224 delegate_combine_delegate_delegate = GetMethod (
1225 delegate_type, "Combine", delegate_delegate);
1227 delegate_remove_delegate_delegate = GetMethod (
1228 delegate_type, "Remove", delegate_delegate);
1233 Type [] void_arg = { };
1234 object_getcurrent_void = GetMethod (
1235 ienumerator_type, "get_Current", void_arg);
1236 bool_movenext_void = GetMethod (
1237 ienumerator_type, "MoveNext", void_arg);
1238 void_reset_void = GetMethod (
1239 ienumerator_type, "Reset", void_arg);
1240 void_dispose_void = GetMethod (
1241 idisposable_type, "Dispose", void_arg);
1242 int_get_offset_to_string_data = GetMethod (
1243 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1244 int_array_get_length = GetMethod (
1245 array_type, "get_Length", void_arg);
1246 int_array_get_rank = GetMethod (
1247 array_type, "get_Rank", void_arg);
1248 ienumerable_getenumerator_void = GetMethod (
1249 ienumerable_type, "GetEnumerator", void_arg);
1254 Type [] int_arg = { int32_type };
1255 int_array_get_length_int = GetMethod (
1256 array_type, "GetLength", int_arg);
1257 int_array_get_upper_bound_int = GetMethod (
1258 array_type, "GetUpperBound", int_arg);
1259 int_array_get_lower_bound_int = GetMethod (
1260 array_type, "GetLowerBound", int_arg);
1263 // System.Array methods
1265 object_array_clone = GetMethod (
1266 array_type, "Clone", void_arg);
1267 Type [] array_int_arg = { array_type, int32_type };
1268 void_array_copyto_array_int = GetMethod (
1269 array_type, "CopyTo", array_int_arg);
1274 Type [] object_arg = { object_type };
1275 void_monitor_enter_object = GetMethod (
1276 monitor_type, "Enter", object_arg);
1277 void_monitor_exit_object = GetMethod (
1278 monitor_type, "Exit", object_arg);
1280 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1282 void_initializearray_array_fieldhandle = GetMethod (
1283 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1288 int_getlength_int = GetMethod (
1289 array_type, "GetLength", int_arg);
1292 // Decimal constructors
1294 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1295 void_decimal_ctor_five_args = GetConstructor (
1296 decimal_type, dec_arg);
1298 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1303 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1304 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1305 default_member_ctor = GetConstructor (default_member_type, string_);
1307 Type[] short_arg = { short_type };
1308 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1310 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1311 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1318 compiler_generated_attr = new CustomAttributeBuilder (
1319 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1321 Type[] type_int_arg = { type_type, int32_type };
1322 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1326 object_ctor = GetConstructor (object_type, void_arg);
1330 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1333 /// This is the "old", non-cache based FindMembers() function. We cannot use
1334 /// the cache here because there is no member name argument.
1336 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1337 MemberFilter filter, object criteria)
1339 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1342 // `builder_to_declspace' contains all dynamic types.
1346 Timer.StartTimer (TimerType.FindMembers);
1347 list = decl.FindMembers (mt, bf, filter, criteria);
1348 Timer.StopTimer (TimerType.FindMembers);
1353 // We have to take care of arrays specially, because GetType on
1354 // a TypeBuilder array will return a Type, not a TypeBuilder,
1355 // and we can not call FindMembers on this type.
1357 if (t.IsSubclassOf (TypeManager.array_type))
1358 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1361 // Since FindMembers will not lookup both static and instance
1362 // members, we emulate this behaviour here.
1364 if ((bf & instance_and_static) == instance_and_static){
1365 MemberInfo [] i_members = t.FindMembers (
1366 mt, bf & ~BindingFlags.Static, filter, criteria);
1368 int i_len = i_members.Length;
1370 MemberInfo one = i_members [0];
1373 // If any of these are present, we are done!
1375 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1376 return new MemberList (i_members);
1379 MemberInfo [] s_members = t.FindMembers (
1380 mt, bf & ~BindingFlags.Instance, filter, criteria);
1382 int s_len = s_members.Length;
1383 if (i_len > 0 || s_len > 0)
1384 return new MemberList (i_members, s_members);
1387 return new MemberList (i_members);
1389 return new MemberList (s_members);
1393 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1398 /// This method is only called from within MemberLookup. It tries to use the member
1399 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1400 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1401 /// our return value will already contain all inherited members and the caller don't need
1402 /// to check base classes and interfaces anymore.
1404 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1405 string name, out bool used_cache)
1410 // We have to take care of arrays specially, because GetType on
1411 // a TypeBuilder array will return a Type, not a TypeBuilder,
1412 // and we can not call FindMembers on this type.
1414 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1416 return TypeHandle.ArrayType.MemberCache.FindMembers (
1417 mt, bf, name, FilterWithClosure_delegate, null);
1421 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1422 // and we can ask the DeclSpace for the MemberCache.
1424 if (t is TypeBuilder) {
1425 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1426 cache = decl.MemberCache;
1429 // If this DeclSpace has a MemberCache, use it.
1432 if (cache != null) {
1434 return cache.FindMembers (
1435 mt, bf, name, FilterWithClosure_delegate, null);
1438 // If there is no MemberCache, we need to use the "normal" FindMembers.
1439 // Note, this is a VERY uncommon route!
1442 Timer.StartTimer (TimerType.FindMembers);
1443 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1444 FilterWithClosure_delegate, name);
1445 Timer.StopTimer (TimerType.FindMembers);
1448 return (MemberInfo []) list;
1452 // This call will always succeed. There is exactly one TypeHandle instance per
1453 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1454 // the corresponding MemberCache.
1456 cache = TypeHandle.GetMemberCache (t);
1459 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1462 public static bool IsBuiltinType (Type t)
1464 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1465 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1466 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1467 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1473 public static bool IsBuiltinType (TypeContainer tc)
1475 return IsBuiltinType (tc.TypeBuilder);
1479 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1480 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1482 public static bool IsCLRType (Type t)
1484 if (t == object_type || t == int32_type || t == uint32_type ||
1485 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1486 t == char_type || t == short_type || t == bool_type ||
1487 t == sbyte_type || t == byte_type || t == ushort_type)
1493 public static bool IsDelegateType (Type t)
1495 if (t.IsSubclassOf (TypeManager.delegate_type))
1501 public static bool IsEnumType (Type t)
1503 if (t.IsSubclassOf (TypeManager.enum_type))
1508 public static bool IsBuiltinOrEnum (Type t)
1510 if (IsBuiltinType (t))
1520 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1522 public static bool IsUnmanagedType (Type t)
1524 if (IsBuiltinType (t) && t != TypeManager.string_type)
1533 if (IsValueType (t)){
1534 if (t is TypeBuilder){
1535 TypeContainer tc = LookupTypeContainer (t);
1537 if (tc.Fields != null){
1538 foreach (Field f in tc.Fields){
1539 if (f.FieldBuilder.IsStatic)
1541 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1547 FieldInfo [] fields = t.GetFields ();
1549 foreach (FieldInfo f in fields){
1552 if (!IsUnmanagedType (f.FieldType))
1562 public static bool IsValueType (Type t)
1564 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1570 public static bool IsInterfaceType (Type t)
1572 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1576 return tc.Kind == Kind.Interface;
1579 public static bool IsSubclassOf (Type type, Type base_type)
1582 if (type.Equals (base_type))
1585 type = type.BaseType;
1586 } while (type != null);
1591 public static bool IsFamilyAccessible (Type type, Type base_type)
1593 return IsSubclassOf (type, base_type);
1597 // Checks whether `type' is a subclass or nested child of `base_type'.
1599 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1602 if ((type == base_type) || type.IsSubclassOf (base_type))
1605 // Handle nested types.
1606 type = type.DeclaringType;
1607 } while (type != null);
1613 // Checks whether `type' is a nested child of `parent'.
1615 public static bool IsNestedChildOf (Type type, Type parent)
1620 type = type.DeclaringType;
1621 while (type != null) {
1625 type = type.DeclaringType;
1632 // Do the right thing when returning the element type of an
1633 // array type based on whether we are compiling corlib or not
1635 public static Type GetElementType (Type t)
1637 if (RootContext.StdLib)
1638 return t.GetElementType ();
1640 return TypeToCoreType (t.GetElementType ());
1644 /// This method is not implemented by MS runtime for dynamic types
1646 public static bool HasElementType (Type t)
1648 return t.IsArray || t.IsPointer || t.IsByRef;
1652 /// Returns the User Defined Types
1654 public static ArrayList UserTypes {
1660 public static Hashtable TypeContainers {
1662 return typecontainers;
1666 static Hashtable builder_to_constant;
1668 public static void RegisterConstant (FieldBuilder fb, Const c)
1670 if (builder_to_constant == null)
1671 builder_to_constant = new PtrHashtable ();
1673 if (builder_to_constant.Contains (fb))
1676 builder_to_constant.Add (fb, c);
1679 public static Const LookupConstant (FieldBuilder fb)
1681 if (builder_to_constant == null)
1684 return (Const) builder_to_constant [fb];
1688 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1692 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1693 /// for anything which is dynamic, and we need this in a number of places,
1694 /// we register this information here, and use it afterwards.
1696 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1701 method_arguments.Add (mb, args);
1702 method_params.Add (mb, ip);
1705 static public ParameterData GetParameterData (MethodBase mb)
1707 object pd = method_params [mb];
1709 if (mb is MethodBuilder || mb is ConstructorBuilder)
1710 throw new InternalErrorException ("Argument for Method not registered" + mb);
1712 method_params [mb] = pd = new ReflectionParameters (mb);
1715 return (ParameterData) pd;
1719 /// Returns the argument types for a method based on its methodbase
1721 /// For dynamic methods, we use the compiler provided types, for
1722 /// methods from existing assemblies we load them from GetParameters,
1723 /// and insert them into the cache
1725 static public Type [] GetArgumentTypes (MethodBase mb)
1727 object t = method_arguments [mb];
1731 ParameterInfo [] pi = mb.GetParameters ();
1738 types = new Type [c];
1739 for (int i = 0; i < c; i++)
1740 types [i] = pi [i].ParameterType;
1742 method_arguments.Add (mb, types);
1747 /// Returns the argument types for an indexer based on its PropertyInfo
1749 /// For dynamic indexers, we use the compiler provided types, for
1750 /// indexers from existing assemblies we load them from GetParameters,
1751 /// and insert them into the cache
1753 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1755 if (indexer_arguments.Contains (indexer))
1756 return (Type []) indexer_arguments [indexer];
1757 else if (indexer is PropertyBuilder)
1758 // If we're a PropertyBuilder and not in the
1759 // `indexer_arguments' hash, then we're a property and
1763 ParameterInfo [] pi = indexer.GetIndexParameters ();
1764 // Property, not an indexer.
1768 Type [] types = new Type [c];
1770 for (int i = 0; i < c; i++)
1771 types [i] = pi [i].ParameterType;
1773 indexer_arguments.Add (indexer, types);
1779 // This is a workaround the fact that GetValue is not
1780 // supported for dynamic types
1782 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1784 if (fields.Contains (fb))
1787 fields.Add (fb, value);
1792 static public object GetValue (FieldBuilder fb)
1797 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1799 if (fieldbuilders_to_fields.Contains (fb))
1802 fieldbuilders_to_fields.Add (fb, f);
1807 // The return value can be null; This will be the case for
1808 // auxiliary FieldBuilders created by the compiler that have no
1809 // real field being declared on the source code
1811 static public FieldBase GetField (FieldInfo fb)
1813 return (FieldBase) fieldbuilders_to_fields [fb];
1816 static Hashtable events;
1818 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1821 events = new Hashtable ();
1823 if (!events.Contains (eb)) {
1824 events.Add (eb, new Pair (add, remove));
1828 static public MethodInfo GetAddMethod (EventInfo ei)
1830 if (ei is MyEventBuilder) {
1831 Pair pair = (Pair) events [ei];
1833 return (MethodInfo) pair.First;
1835 return ei.GetAddMethod (true);
1838 static public MethodInfo GetRemoveMethod (EventInfo ei)
1840 if (ei is MyEventBuilder) {
1841 Pair pair = (Pair) events [ei];
1843 return (MethodInfo) pair.Second;
1845 return ei.GetRemoveMethod (true);
1848 static Hashtable priv_fields_events;
1850 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1852 if (priv_fields_events == null)
1853 priv_fields_events = new Hashtable ();
1855 if (priv_fields_events.Contains (einfo))
1858 priv_fields_events.Add (einfo, builder);
1863 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1865 if (priv_fields_events == null)
1868 return (MemberInfo) priv_fields_events [ei];
1871 static Hashtable properties;
1873 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1875 if (properties == null)
1876 properties = new Hashtable ();
1878 if (properties.Contains (pb))
1881 properties.Add (pb, new Pair (get, set));
1886 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1887 MethodBase set, Type[] args)
1889 if (!RegisterProperty (pb, get,set))
1892 indexer_arguments.Add (pb, args);
1897 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1899 Hashtable hash = new Hashtable ();
1900 return CheckStructCycles (tc, seen, hash);
1903 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1906 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1910 // `seen' contains all types we've already visited.
1912 if (seen.Contains (tc))
1914 seen.Add (tc, null);
1916 if (tc.Fields == null)
1919 foreach (FieldMember field in tc.Fields) {
1920 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1923 Type ftype = field.FieldBuilder.FieldType;
1924 TypeContainer ftc = LookupTypeContainer (ftype);
1928 if (hash.Contains (ftc)) {
1929 Report.Error (523, tc.Location,
1930 "Struct member `{0}.{1}' of type `{2}' " +
1931 "causes a cycle in the struct layout",
1932 tc.Name, field.Name, ftc.Name);
1937 // `hash' contains all types in the current path.
1939 hash.Add (tc, null);
1941 bool ok = CheckStructCycles (ftc, seen, hash);
1948 if (!seen.Contains (ftc))
1949 seen.Add (ftc, null);
1956 /// Given an array of interface types, expand and eliminate repeated ocurrences
1957 /// of an interface.
1961 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1964 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1966 ArrayList new_ifaces = new ArrayList ();
1968 foreach (TypeExpr iface in base_interfaces){
1969 Type itype = iface.ResolveType (ec);
1973 if (!new_ifaces.Contains (itype))
1974 new_ifaces.Add (itype);
1976 Type [] implementing = itype.GetInterfaces ();
1978 foreach (Type imp in implementing){
1979 if (!new_ifaces.Contains (imp))
1980 new_ifaces.Add (imp);
1983 Type [] ret = new Type [new_ifaces.Count];
1984 new_ifaces.CopyTo (ret, 0);
1988 static PtrHashtable iface_cache = new PtrHashtable ();
1991 /// This function returns the interfaces in the type `t'. Works with
1992 /// both types and TypeBuilders.
1994 public static Type [] GetInterfaces (Type t)
1997 Type [] cached = iface_cache [t] as Type [];
2002 // The reason for catching the Array case is that Reflection.Emit
2003 // will not return a TypeBuilder for Array types of TypeBuilder types,
2004 // but will still throw an exception if we try to call GetInterfaces
2007 // Since the array interfaces are always constant, we return those for
2012 t = TypeManager.array_type;
2014 if (t is TypeBuilder){
2015 Type [] base_ifaces;
2017 if (t.BaseType == null)
2018 base_ifaces = NoTypes;
2020 base_ifaces = GetInterfaces (t.BaseType);
2021 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
2022 if (type_ifaces == null)
2023 type_ifaces = NoTypes;
2025 int base_count = base_ifaces.Length;
2026 Type [] result = new Type [base_count + type_ifaces.Length];
2027 base_ifaces.CopyTo (result, 0);
2028 type_ifaces.CopyTo (result, base_count);
2030 iface_cache [t] = result;
2033 Type[] ifaces = t.GetInterfaces ();
2034 iface_cache [t] = ifaces;
2040 // gets the interfaces that are declared explicitly on t
2042 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2044 return (Type []) builder_to_ifaces [t];
2048 /// The following is used to check if a given type implements an interface.
2049 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2051 public static bool ImplementsInterface (Type t, Type iface)
2056 // FIXME OPTIMIZATION:
2057 // as soon as we hit a non-TypeBuiler in the interface
2058 // chain, we could return, as the `Type.GetInterfaces'
2059 // will return all the interfaces implement by the type
2063 interfaces = GetInterfaces (t);
2065 if (interfaces != null){
2066 foreach (Type i in interfaces){
2073 } while (t != null);
2078 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2080 // This is a custom version of Convert.ChangeType() which works
2081 // with the TypeBuilder defined types when compiling corlib.
2082 public static object ChangeType (object value, Type conversionType, out bool error)
2084 IConvertible convert_value = value as IConvertible;
2086 if (convert_value == null){
2092 // We must use Type.Equals() here since `conversionType' is
2093 // the TypeBuilder created version of a system type and not
2094 // the system type itself. You cannot use Type.GetTypeCode()
2095 // on such a type - it'd always return TypeCode.Object.
2099 if (conversionType.Equals (typeof (Boolean)))
2100 return (object)(convert_value.ToBoolean (nf_provider));
2101 else if (conversionType.Equals (typeof (Byte)))
2102 return (object)(convert_value.ToByte (nf_provider));
2103 else if (conversionType.Equals (typeof (Char)))
2104 return (object)(convert_value.ToChar (nf_provider));
2105 else if (conversionType.Equals (typeof (DateTime)))
2106 return (object)(convert_value.ToDateTime (nf_provider));
2107 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2108 return (object)(convert_value.ToDecimal (nf_provider));
2109 else if (conversionType.Equals (typeof (Double)))
2110 return (object)(convert_value.ToDouble (nf_provider));
2111 else if (conversionType.Equals (typeof (Int16)))
2112 return (object)(convert_value.ToInt16 (nf_provider));
2113 else if (conversionType.Equals (typeof (Int32)))
2114 return (object)(convert_value.ToInt32 (nf_provider));
2115 else if (conversionType.Equals (typeof (Int64)))
2116 return (object)(convert_value.ToInt64 (nf_provider));
2117 else if (conversionType.Equals (typeof (SByte)))
2118 return (object)(convert_value.ToSByte (nf_provider));
2119 else if (conversionType.Equals (typeof (Single)))
2120 return (object)(convert_value.ToSingle (nf_provider));
2121 else if (conversionType.Equals (typeof (String)))
2122 return (object)(convert_value.ToString (nf_provider));
2123 else if (conversionType.Equals (typeof (UInt16)))
2124 return (object)(convert_value.ToUInt16 (nf_provider));
2125 else if (conversionType.Equals (typeof (UInt32)))
2126 return (object)(convert_value.ToUInt32 (nf_provider));
2127 else if (conversionType.Equals (typeof (UInt64)))
2128 return (object)(convert_value.ToUInt64 (nf_provider));
2129 else if (conversionType.Equals (typeof (Object)))
2130 return (object)(value);
2140 // This is needed, because enumerations from assemblies
2141 // do not report their underlyingtype, but they report
2144 public static Type EnumToUnderlying (Type t)
2146 if (t == TypeManager.enum_type)
2149 t = t.UnderlyingSystemType;
2150 if (!TypeManager.IsEnumType (t))
2153 if (t is TypeBuilder) {
2154 // slow path needed to compile corlib
2155 if (t == TypeManager.bool_type ||
2156 t == TypeManager.byte_type ||
2157 t == TypeManager.sbyte_type ||
2158 t == TypeManager.char_type ||
2159 t == TypeManager.short_type ||
2160 t == TypeManager.ushort_type ||
2161 t == TypeManager.int32_type ||
2162 t == TypeManager.uint32_type ||
2163 t == TypeManager.int64_type ||
2164 t == TypeManager.uint64_type)
2166 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2168 TypeCode tc = Type.GetTypeCode (t);
2171 case TypeCode.Boolean:
2172 return TypeManager.bool_type;
2174 return TypeManager.byte_type;
2175 case TypeCode.SByte:
2176 return TypeManager.sbyte_type;
2178 return TypeManager.char_type;
2179 case TypeCode.Int16:
2180 return TypeManager.short_type;
2181 case TypeCode.UInt16:
2182 return TypeManager.ushort_type;
2183 case TypeCode.Int32:
2184 return TypeManager.int32_type;
2185 case TypeCode.UInt32:
2186 return TypeManager.uint32_type;
2187 case TypeCode.Int64:
2188 return TypeManager.int64_type;
2189 case TypeCode.UInt64:
2190 return TypeManager.uint64_type;
2192 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2196 // When compiling corlib and called with one of the core types, return
2197 // the corresponding typebuilder for that type.
2199 public static Type TypeToCoreType (Type t)
2201 if (RootContext.StdLib || (t is TypeBuilder))
2204 TypeCode tc = Type.GetTypeCode (t);
2207 case TypeCode.Boolean:
2208 return TypeManager.bool_type;
2210 return TypeManager.byte_type;
2211 case TypeCode.SByte:
2212 return TypeManager.sbyte_type;
2214 return TypeManager.char_type;
2215 case TypeCode.Int16:
2216 return TypeManager.short_type;
2217 case TypeCode.UInt16:
2218 return TypeManager.ushort_type;
2219 case TypeCode.Int32:
2220 return TypeManager.int32_type;
2221 case TypeCode.UInt32:
2222 return TypeManager.uint32_type;
2223 case TypeCode.Int64:
2224 return TypeManager.int64_type;
2225 case TypeCode.UInt64:
2226 return TypeManager.uint64_type;
2227 case TypeCode.Single:
2228 return TypeManager.float_type;
2229 case TypeCode.Double:
2230 return TypeManager.double_type;
2231 case TypeCode.String:
2232 return TypeManager.string_type;
2233 case TypeCode.Decimal:
2234 return TypeManager.decimal_type;
2236 if (t == typeof (void))
2237 return TypeManager.void_type;
2238 if (t == typeof (object))
2239 return TypeManager.object_type;
2240 if (t == typeof (System.Type))
2241 return TypeManager.type_type;
2242 if (t == typeof (System.IntPtr))
2243 return TypeManager.intptr_type;
2249 /// Utility function that can be used to probe whether a type
2250 /// is managed or not.
2252 public static bool VerifyUnManaged (Type t, Location loc)
2254 if (t.IsValueType || t.IsPointer){
2256 // FIXME: this is more complex, we actually need to
2257 // make sure that the type does not contain any
2263 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
2264 // We need this explicit check here to make it work when
2265 // compiling corlib.
2270 "Cannot take the address or size of a variable of a managed type ('" +
2271 CSharpName (t) + "')");
2276 /// Returns the name of the indexer in a given type.
2279 /// The default is not always `Item'. The user can change this behaviour by
2280 /// using the IndexerNameAttribute in the container.
2281 /// For example, the String class indexer is named `Chars' not `Item'
2283 public static string IndexerPropertyName (Type t)
2285 if (t is TypeBuilder) {
2286 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2287 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2290 System.Attribute attr = System.Attribute.GetCustomAttribute (
2291 t, TypeManager.default_member_type);
2293 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2294 return dma.MemberName;
2297 return TypeContainer.DefaultIndexerName;
2300 static MethodInfo declare_local_method = null;
2302 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2304 if (declare_local_method == null){
2305 declare_local_method = typeof (ILGenerator).GetMethod (
2307 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2309 new Type [] { typeof (Type), typeof (bool)},
2311 if (declare_local_method == null){
2312 Report.Warning (-24, new Location (-1),
2313 "This version of the runtime does not support making pinned local variables. " +
2314 "This code may cause errors on a runtime with a moving GC");
2315 return ig.DeclareLocal (t);
2318 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2322 // Returns whether the array of memberinfos contains the given method
2324 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2326 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2328 foreach (MethodBase method in array) {
2329 if (method.Name != new_method.Name)
2332 if (method is MethodInfo && new_method is MethodInfo)
2333 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2337 Type [] old_args = TypeManager.GetArgumentTypes (method);
2338 int old_count = old_args.Length;
2341 if (new_args.Length != old_count)
2344 for (i = 0; i < old_count; i++){
2345 if (old_args [i] != new_args [i])
2358 // We copy methods from `new_members' into `target_list' if the signature
2359 // for the method from in the new list does not exist in the target_list
2361 // The name is assumed to be the same.
2363 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2365 if (target_list == null){
2366 target_list = new ArrayList ();
2368 foreach (MemberInfo mi in new_members){
2369 if (mi is MethodBase)
2370 target_list.Add (mi);
2375 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2376 target_list.CopyTo (target_array, 0);
2378 foreach (MemberInfo mi in new_members){
2379 MethodBase new_method = (MethodBase) mi;
2381 if (!ArrayContainsMethod (target_array, new_method))
2382 target_list.Add (new_method);
2388 #region MemberLookup implementation
2391 // Whether we allow private members in the result (since FindMembers
2392 // uses NonPublic for both protected and private), we need to distinguish.
2395 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2400 internal class Closure {
2401 internal bool private_ok;
2403 // Who is invoking us and which type is being queried currently.
2404 internal Type invocation_type;
2405 internal Type qualifier_type;
2407 // The assembly that defines the type is that is calling us
2408 internal Assembly invocation_assembly;
2409 internal IList almost_match;
2411 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2413 if (invocation_type == null)
2416 Debug.Assert (IsNestedFamilyAccessible (invocation_type, m.DeclaringType));
2421 // A nested class has access to all the protected members visible to its parent.
2422 if (qualifier_type != null
2423 && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2426 if (invocation_type == m.DeclaringType
2427 || invocation_type.IsSubclassOf (m.DeclaringType)) {
2428 // Although a derived class can access protected members of its base class
2429 // it cannot do so through an instance of the base class (CS1540).
2430 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2431 if (qualifier_type == null
2432 || qualifier_type == invocation_type
2433 || qualifier_type.IsSubclassOf (invocation_type))
2437 if (almost_match != null)
2438 almost_match.Add (m);
2443 // This filter filters by name + whether it is ok to include private
2444 // members in the search
2446 internal bool Filter (MemberInfo m, object filter_criteria)
2449 // Hack: we know that the filter criteria will always be in the `closure'
2453 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2456 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2457 (m.DeclaringType == invocation_type))
2461 // Ugly: we need to find out the type of `m', and depending
2462 // on this, tell whether we accept or not
2464 if (m is MethodBase){
2465 MethodBase mb = (MethodBase) m;
2466 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2468 if (ma == MethodAttributes.Private)
2469 return private_ok || (invocation_type == m.DeclaringType) ||
2470 IsNestedChildOf (invocation_type, m.DeclaringType);
2472 // Assembly succeeds if we're in the same assembly.
2473 if (ma == MethodAttributes.Assembly)
2474 return (invocation_assembly == mb.DeclaringType.Assembly);
2476 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2477 if (ma == MethodAttributes.FamANDAssem){
2478 if (invocation_assembly != mb.DeclaringType.Assembly)
2482 // Family and FamANDAssem require that we derive.
2483 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem))
2484 return CheckValidFamilyAccess (mb.IsStatic, m);
2490 if (m is FieldInfo){
2491 FieldInfo fi = (FieldInfo) m;
2492 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2494 if (fa == FieldAttributes.Private)
2495 return private_ok || (invocation_type == m.DeclaringType) ||
2496 IsNestedChildOf (invocation_type, m.DeclaringType);
2498 // Assembly succeeds if we're in the same assembly.
2499 if (fa == FieldAttributes.Assembly)
2500 return (invocation_assembly == fi.DeclaringType.Assembly);
2502 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2503 if (fa == FieldAttributes.FamANDAssem){
2504 if (invocation_assembly != fi.DeclaringType.Assembly)
2508 // Family and FamANDAssem require that we derive.
2509 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem))
2510 return CheckValidFamilyAccess (fi.IsStatic, m);
2517 // EventInfos and PropertyInfos, return true because they lack permission
2518 // information, so we need to check later on the methods.
2524 static Closure closure = new Closure ();
2525 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2528 // Looks up a member called `name' in the `queried_type'. This lookup
2529 // is done by code that is contained in the definition for `invocation_type'
2530 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2532 // `invocation_type' is used to check whether we're allowed to access the requested
2533 // member wrt its protection level.
2535 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2536 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2537 // is B and qualifier_type is A). This is used to do the CS1540 check.
2539 // When resolving a SimpleName, `qualifier_type' is null.
2541 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2542 // the same than `queried_type' - except when we're being called from BaseAccess;
2543 // in this case, `invocation_type' is the current type and `queried_type' the base
2544 // type, so this'd normally trigger a CS1540.
2546 // The binding flags are `bf' and the kind of members being looked up are `mt'
2548 // The return value always includes private members which code in `invocation_type'
2549 // is allowed to access (using the specified `qualifier_type' if given); only use
2550 // BindingFlags.NonPublic to bypass the permission check.
2552 // The 'almost_match' argument is used for reporting error CS1540.
2554 // Returns an array of a single element for everything but Methods/Constructors
2555 // that might return multiple matches.
2557 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2558 Type queried_type, MemberTypes mt,
2559 BindingFlags original_bf, string name, IList almost_match)
2561 Timer.StartTimer (TimerType.MemberLookup);
2563 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2564 queried_type, mt, original_bf, name, almost_match);
2566 Timer.StopTimer (TimerType.MemberLookup);
2571 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2572 Type queried_type, MemberTypes mt,
2573 BindingFlags original_bf, string name, IList almost_match)
2575 BindingFlags bf = original_bf;
2577 ArrayList method_list = null;
2578 Type current_type = queried_type;
2579 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2580 bool skip_iface_check = true, used_cache = false;
2581 bool always_ok_flag = false;
2583 closure.invocation_type = invocation_type;
2584 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2585 closure.qualifier_type = qualifier_type;
2586 closure.almost_match = almost_match;
2589 // If we are a nested class, we always have access to our container
2592 if (invocation_type != null){
2593 string invocation_name = invocation_type.FullName;
2594 if (invocation_name.IndexOf ('+') != -1){
2595 string container = queried_type.FullName + "+";
2596 int container_length = container.Length;
2598 if (invocation_name.Length > container_length){
2599 string shared = invocation_name.Substring (0, container_length);
2601 if (shared == container)
2602 always_ok_flag = true;
2607 // This is from the first time we find a method
2608 // in most cases, we do not actually find a method in the base class
2609 // so we can just ignore it, and save the arraylist allocation
2610 MemberInfo [] first_members_list = null;
2611 bool use_first_members_list = false;
2617 // `NonPublic' is lame, because it includes both protected and
2618 // private methods, so we need to control this behavior by
2619 // explicitly tracking if a private method is ok or not.
2621 // The possible cases are:
2622 // public, private and protected (internal does not come into the
2625 if ((invocation_type != null) &&
2626 ((invocation_type == current_type) ||
2627 IsNestedChildOf (invocation_type, current_type)) ||
2629 bf = original_bf | BindingFlags.NonPublic;
2633 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2635 Timer.StopTimer (TimerType.MemberLookup);
2637 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2639 Timer.StartTimer (TimerType.MemberLookup);
2642 // When queried for an interface type, the cache will automatically check all
2643 // inherited members, so we don't need to do this here. However, this only
2644 // works if we already used the cache in the first iteration of this loop.
2646 // If we used the cache in any further iteration, we can still terminate the
2647 // loop since the cache always looks in all base classes.
2653 skip_iface_check = false;
2655 if (current_type == TypeManager.object_type)
2658 current_type = current_type.BaseType;
2661 // This happens with interfaces, they have a null
2662 // basetype. Look members up in the Object class.
2664 if (current_type == null) {
2665 current_type = TypeManager.object_type;
2670 if (list.Length == 0)
2674 // Events and types are returned by both `static' and `instance'
2675 // searches, which means that our above FindMembers will
2676 // return two copies of the same.
2678 if (list.Length == 1 && !(list [0] is MethodBase)){
2683 // Multiple properties: we query those just to find out the indexer
2686 if (list [0] is PropertyInfo)
2690 // We found an event: the cache lookup returns both the event and
2691 // its private field.
2693 if (list [0] is EventInfo) {
2694 if ((list.Length == 2) && (list [1] is FieldInfo))
2695 return new MemberInfo [] { list [0] };
2702 // We found methods, turn the search into "method scan"
2706 if (first_members_list != null) {
2707 if (use_first_members_list) {
2708 method_list = CopyNewMethods (method_list, first_members_list);
2709 use_first_members_list = false;
2712 method_list = CopyNewMethods (method_list, list);
2714 first_members_list = list;
2715 use_first_members_list = true;
2716 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2718 } while (searching);
2720 if (use_first_members_list) {
2721 foreach (MemberInfo mi in first_members_list) {
2722 if (! (mi is MethodBase)) {
2723 method_list = CopyNewMethods (method_list, first_members_list);
2724 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2727 return (MemberInfo []) first_members_list;
2730 if (method_list != null && method_list.Count > 0)
2731 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2734 // This happens if we already used the cache in the first iteration, in this case
2735 // the cache already looked in all interfaces.
2737 if (skip_iface_check)
2741 // Interfaces do not list members they inherit, so we have to
2744 if (!queried_type.IsInterface)
2747 if (queried_type.IsArray)
2748 queried_type = TypeManager.array_type;
2750 Type [] ifaces = GetInterfaces (queried_type);
2754 foreach (Type itype in ifaces){
2757 x = MemberLookup (null, null, itype, mt, bf, name, null);
2765 // Tests whether external method is really special
2766 public static bool IsSpecialMethod (MethodBase mb)
2768 string name = mb.Name;
2769 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2770 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2772 if (name.StartsWith ("add_"))
2773 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2775 if (name.StartsWith ("remove_"))
2776 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2778 if (name.StartsWith ("op_")){
2779 foreach (string oname in Unary.oper_names) {
2784 foreach (string oname in Binary.oper_names) {
2797 /// There is exactly one instance of this class per type.
2799 public sealed class TypeHandle : IMemberContainer {
2800 public readonly TypeHandle BaseType;
2802 readonly int id = ++next_id;
2803 static int next_id = 0;
2805 static TypeHandle ()
2811 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2812 /// a TypeHandle yet, a new instance of it is created. This static method
2813 /// ensures that we'll only have one TypeHandle instance per type.
2815 private static TypeHandle GetTypeHandle (Type t)
2817 TypeHandle handle = (TypeHandle) type_hash [t];
2821 handle = new TypeHandle (t);
2822 type_hash.Add (t, handle);
2826 public static MemberCache GetMemberCache (Type t)
2828 return GetTypeHandle (t).MemberCache;
2831 public static void CleanUp ()
2836 public static void Reset ()
2838 type_hash = new PtrHashtable ();
2842 /// Returns the TypeHandle for TypeManager.object_type.
2844 public static IMemberContainer ObjectType {
2846 if (object_type != null)
2849 object_type = GetTypeHandle (TypeManager.object_type);
2856 /// Returns the TypeHandle for TypeManager.array_type.
2858 public static IMemberContainer ArrayType {
2860 if (array_type != null)
2863 array_type = GetTypeHandle (TypeManager.array_type);
2869 private static PtrHashtable type_hash;
2871 private static TypeHandle object_type = null;
2872 private static TypeHandle array_type = null;
2875 private bool is_interface;
2876 private MemberCache member_cache;
2877 private MemberCache base_cache;
2879 private TypeHandle (Type type)
2882 if (type.BaseType != null) {
2883 BaseType = GetTypeHandle (type.BaseType);
2884 base_cache = BaseType.MemberCache;
2885 } else if (type.IsInterface)
2886 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2887 this.is_interface = type.IsInterface;
2888 this.member_cache = new MemberCache (this);
2891 // IMemberContainer methods
2893 public string Name {
2895 return type.FullName;
2905 public MemberCache BaseCache {
2911 public bool IsInterface {
2913 return is_interface;
2917 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2919 MemberInfo [] members;
2920 if (mt == MemberTypes.Event)
2921 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2923 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2925 Array.Reverse (members);
2927 return new MemberList (members);
2930 // IMemberFinder methods
2932 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2933 MemberFilter filter, object criteria)
2935 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2938 public MemberCache MemberCache {
2940 return member_cache;
2944 public override string ToString ()
2946 if (BaseType != null)
2947 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2949 return "TypeHandle (" + id + "," + Name + ")";