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;
108 static internal Type default_charset_type;
112 // An empty array of types
114 static public Type [] NoTypes;
115 static public TypeExpr [] NoTypeExprs;
119 // Expressions representing the internal types. Used during declaration
122 static public TypeExpr system_object_expr, system_string_expr;
123 static public TypeExpr system_boolean_expr, system_decimal_expr;
124 static public TypeExpr system_single_expr, system_double_expr;
125 static public TypeExpr system_sbyte_expr, system_byte_expr;
126 static public TypeExpr system_int16_expr, system_uint16_expr;
127 static public TypeExpr system_int32_expr, system_uint32_expr;
128 static public TypeExpr system_int64_expr, system_uint64_expr;
129 static public TypeExpr system_char_expr, system_void_expr;
130 static public TypeExpr system_asynccallback_expr;
131 static public TypeExpr system_iasyncresult_expr;
132 static public TypeExpr system_valuetype_expr;
133 static public TypeExpr system_intptr_expr;
136 // This is only used when compiling corlib
138 static public Type system_int32_type;
139 static public Type system_array_type;
140 static public Type system_type_type;
141 static public Type system_assemblybuilder_type;
142 static public MethodInfo system_int_array_get_length;
143 static public MethodInfo system_int_array_get_rank;
144 static public MethodInfo system_object_array_clone;
145 static public MethodInfo system_int_array_get_length_int;
146 static public MethodInfo system_int_array_get_lower_bound_int;
147 static public MethodInfo system_int_array_get_upper_bound_int;
148 static public MethodInfo system_void_array_copyto_array_int;
152 // Internal, not really used outside
154 static Type runtime_helpers_type;
157 // These methods are called by code generated by the compiler
159 static public MethodInfo string_concat_string_string;
160 static public MethodInfo string_concat_string_string_string;
161 static public MethodInfo string_concat_string_string_string_string;
162 static public MethodInfo string_concat_string_dot_dot_dot;
163 static public MethodInfo string_concat_object_object;
164 static public MethodInfo string_concat_object_object_object;
165 static public MethodInfo string_concat_object_dot_dot_dot;
166 static public MethodInfo string_isinterneted_string;
167 static public MethodInfo system_type_get_type_from_handle;
168 static public MethodInfo object_getcurrent_void;
169 static public MethodInfo bool_movenext_void;
170 static public MethodInfo ienumerable_getenumerator_void;
171 static public MethodInfo void_reset_void;
172 static public MethodInfo void_dispose_void;
173 static public MethodInfo void_monitor_enter_object;
174 static public MethodInfo void_monitor_exit_object;
175 static public MethodInfo void_initializearray_array_fieldhandle;
176 static public MethodInfo int_getlength_int;
177 static public MethodInfo delegate_combine_delegate_delegate;
178 static public MethodInfo delegate_remove_delegate_delegate;
179 static public MethodInfo int_get_offset_to_string_data;
180 static public MethodInfo int_array_get_length;
181 static public MethodInfo int_array_get_rank;
182 static public MethodInfo object_array_clone;
183 static public MethodInfo int_array_get_length_int;
184 static public MethodInfo int_array_get_lower_bound_int;
185 static public MethodInfo int_array_get_upper_bound_int;
186 static public MethodInfo void_array_copyto_array_int;
189 // The attribute constructors.
191 static public ConstructorInfo object_ctor;
192 static public ConstructorInfo cons_param_array_attribute;
193 static public ConstructorInfo void_decimal_ctor_five_args;
194 static public ConstructorInfo void_decimal_ctor_int_arg;
195 static public ConstructorInfo unverifiable_code_ctor;
196 static public ConstructorInfo default_member_ctor;
197 static public ConstructorInfo decimal_constant_attribute_ctor;
198 static internal ConstructorInfo struct_layout_attribute_ctor;
199 static public ConstructorInfo field_offset_attribute_ctor;
205 static internal CustomAttributeBuilder compiler_generated_attr;
206 static internal ConstructorInfo fixed_buffer_attr_ctor;
210 // Holds the Array of Assemblies that have been loaded
211 // (either because it is the default or the user used the
212 // -r command line option)
214 static Assembly [] assemblies;
217 // Keeps a list of modules. We used this to do lookups
218 // on the module using GetType -- needed for arrays
220 static Module [] modules;
223 // This is the type_cache from the assemblies to avoid
224 // hitting System.Reflection on every lookup.
226 static Hashtable types;
229 // This is used to hotld the corresponding TypeContainer objects
230 // since we need this in FindMembers
232 static Hashtable typecontainers;
235 // Keeps track of those types that are defined by the
238 static ArrayList user_types;
240 static PtrHashtable builder_to_declspace;
242 static PtrHashtable builder_to_member_cache;
245 // Tracks the interfaces implemented by typebuilders. We only
246 // enter those who do implement or or more interfaces
248 static PtrHashtable builder_to_ifaces;
251 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
252 // the arguments to the method
254 static Hashtable method_arguments;
257 // Maps PropertyBuilder to a Type array that contains
258 // the arguments to the indexer
260 static Hashtable indexer_arguments;
263 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
265 static Hashtable method_params;
268 // A hash table from override methods to their base virtual method.
270 static Hashtable method_overrides;
273 // Keeps track of methods
276 static Hashtable builder_to_method;
279 // Contains all public types from referenced assemblies.
280 // This member is used only if CLS Compliance verification is required.
282 public static Hashtable all_imported_types;
284 static Hashtable fieldbuilders_to_fields;
285 static Hashtable fields;
292 public static void CleanUp ()
294 // Lets get everything clean so that we can collect before generating code
298 typecontainers = null;
300 builder_to_declspace = null;
301 builder_to_member_cache = null;
302 builder_to_ifaces = null;
303 method_arguments = null;
304 indexer_arguments = null;
305 method_params = null;
306 builder_to_method = null;
309 builder_to_constant = null;
310 fieldbuilders_to_fields = null;
312 priv_fields_events = null;
316 TypeHandle.CleanUp ();
320 /// A filter for Findmembers that uses the Signature object to
323 static bool SignatureFilter (MemberInfo mi, object criteria)
325 Signature sig = (Signature) criteria;
327 if (!(mi is MethodBase))
330 if (mi.Name != sig.name)
333 int count = sig.args.Length;
335 if (mi is MethodBuilder || mi is ConstructorBuilder){
336 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
338 if (candidate_args.Length != count)
341 for (int i = 0; i < count; i++)
342 if (candidate_args [i] != sig.args [i])
347 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
349 if (pars.Length != count)
352 for (int i = 0; i < count; i++)
353 if (pars [i].ParameterType != sig.args [i])
359 // A delegate that points to the filter above.
360 static MemberFilter signature_filter;
363 // These are expressions that represent some of the internal data types, used
366 static void InitExpressionTypes ()
368 system_object_expr = new TypeLookupExpression ("System.Object");
369 system_string_expr = new TypeLookupExpression ("System.String");
370 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
371 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
372 system_single_expr = new TypeLookupExpression ("System.Single");
373 system_double_expr = new TypeLookupExpression ("System.Double");
374 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
375 system_byte_expr = new TypeLookupExpression ("System.Byte");
376 system_int16_expr = new TypeLookupExpression ("System.Int16");
377 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
378 system_int32_expr = new TypeLookupExpression ("System.Int32");
379 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
380 system_int64_expr = new TypeLookupExpression ("System.Int64");
381 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
382 system_char_expr = new TypeLookupExpression ("System.Char");
383 system_void_expr = new TypeLookupExpression ("System.Void");
384 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
385 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
386 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
387 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
390 static TypeManager ()
394 signature_filter = new MemberFilter (SignatureFilter);
395 InitExpressionTypes ();
398 static public void Reset ()
400 assemblies = new Assembly [0];
402 user_types = new ArrayList ();
404 types = new Hashtable ();
405 typecontainers = new Hashtable ();
407 builder_to_declspace = new PtrHashtable ();
408 builder_to_member_cache = new PtrHashtable ();
409 builder_to_method = new PtrHashtable ();
410 method_arguments = new PtrHashtable ();
411 method_params = new PtrHashtable ();
412 method_overrides = new PtrHashtable ();
413 indexer_arguments = new PtrHashtable ();
414 builder_to_ifaces = new PtrHashtable ();
416 NoTypes = new Type [0];
417 NoTypeExprs = new TypeExpr [0];
419 fieldbuilders_to_fields = new Hashtable ();
420 fields = new Hashtable ();
421 type_hash = new DoubleHash ();
424 public static void HandleDuplicate (string name, Type t)
426 Type prev = (Type) types [name];
427 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
431 // This probably never happens, as we catch this before
433 Report.Error (-17, "The type `" + name + "' has already been defined.");
437 tc = builder_to_declspace [t] as TypeContainer;
440 1595, "The type `" + name + "' is defined in an existing assembly;"+
441 " Using the new definition from: " + tc.Location);
444 1595, "The type `" + name + "' is defined in an existing assembly;");
447 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
453 public static void AddUserType (string name, TypeBuilder t)
458 HandleDuplicate (name, t);
465 // This entry point is used by types that we define under the covers
467 public static void RegisterBuilder (Type tb, Type [] ifaces)
470 builder_to_ifaces [tb] = ifaces;
473 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
475 builder_to_declspace.Add (t, tc);
476 typecontainers.Add (name, tc);
477 AddUserType (name, t);
480 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
485 HandleDuplicate (name, t);
488 builder_to_declspace.Add (t, del);
491 public static void AddEnumType (string name, TypeBuilder t, Enum en)
496 HandleDuplicate (name, t);
498 builder_to_declspace.Add (t, en);
501 public static void AddMethod (MethodBase builder, IMethodData method)
503 builder_to_method.Add (builder, method);
506 public static IMethodData GetMethod (MethodBase builder)
508 return (IMethodData) builder_to_method [builder];
512 /// Returns the DeclSpace whose Type is `t' or null if there is no
513 /// DeclSpace for `t' (ie, the Type comes from a library)
515 public static DeclSpace LookupDeclSpace (Type t)
517 return builder_to_declspace [t] as DeclSpace;
521 /// Returns the TypeContainer whose Type is `t' or null if there is no
522 /// TypeContainer for `t' (ie, the Type comes from a library)
524 public static TypeContainer LookupTypeContainer (Type t)
526 return builder_to_declspace [t] as TypeContainer;
529 public static MemberCache LookupMemberCache (Type t)
531 if (t is TypeBuilder) {
532 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
533 if (container != null)
534 return container.MemberCache;
537 return TypeHandle.GetMemberCache (t);
540 public static MemberCache LookupBaseInterfacesCache (Type t)
542 Type [] ifaces = t.GetInterfaces ();
544 if (ifaces != null && ifaces.Length == 1)
545 return LookupMemberCache (ifaces [0]);
547 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
548 MemberCache cache = builder_to_member_cache [t] as MemberCache;
552 cache = new MemberCache (ifaces);
553 builder_to_member_cache.Add (t, cache);
557 public static TypeContainer LookupInterface (Type t)
559 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
560 if ((tc == null) || (tc.Kind != Kind.Interface))
566 public static Delegate LookupDelegate (Type t)
568 return builder_to_declspace [t] as Delegate;
571 public static Enum LookupEnum (Type t)
573 return builder_to_declspace [t] as Enum;
576 public static Class LookupClass (Type t)
578 return (Class) builder_to_declspace [t];
582 /// Registers an assembly to load types from.
584 public static void AddAssembly (Assembly a)
586 foreach (Assembly assembly in assemblies) {
591 int top = assemblies.Length;
592 Assembly [] n = new Assembly [top + 1];
594 assemblies.CopyTo (n, 0);
600 public static Assembly [] GetAssemblies ()
606 /// Registers a module builder to lookup types from
608 public static void AddModule (Module mb)
610 int top = modules != null ? modules.Length : 0;
611 Module [] n = new Module [top + 1];
614 modules.CopyTo (n, 0);
619 public static Module[] Modules {
626 // We use this hash for multiple kinds of constructed types:
628 // (T, "&") Given T, get T &
629 // (T, "*") Given T, get T *
630 // (T, "[]") Given T and a array dimension, get T []
631 // (T, X) Given a type T and a simple name X, get the type T+X
633 // Accessibility tests, if necessary, should be done by the user
635 static DoubleHash type_hash = new DoubleHash ();
638 // Gets the reference to T version of the Type (T&)
640 public static Type GetReferenceType (Type t)
642 return GetConstructedType (t, "&");
646 // Gets the pointer to T version of the Type (T*)
648 public static Type GetPointerType (Type t)
650 return GetConstructedType (t, "*");
653 public static Type GetConstructedType (Type t, string dim)
656 if (!type_hash.Lookup (t, dim, out ret)) {
657 ret = t.Module.GetType (t.ToString () + dim);
658 type_hash.Insert (t, dim, ret);
663 public static Type GetNestedType (Type t, string name)
666 if (!type_hash.Lookup (t, name, out ret)) {
667 string lookup = t.ToString () + "+" + name;
668 ret = t.Module.GetType (lookup);
669 type_hash.Insert (t, name, ret);
675 // Low-level lookup, cache-less
677 public static Type LookupTypeReflection (string name)
681 foreach (Assembly a in assemblies){
682 t = a.GetType (name);
687 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
688 if (ta == TypeAttributes.NotPublic ||
689 ta == TypeAttributes.NestedPrivate ||
690 ta == TypeAttributes.NestedAssembly ||
691 ta == TypeAttributes.NestedFamANDAssem){
694 // In .NET pointers turn out to be private, even if their
695 // element type is not
698 t = t.GetElementType ();
708 foreach (Module mb in modules) {
709 t = mb.GetType (name);
718 /// Computes the namespaces that we import from the assemblies we reference.
720 public static void ComputeNamespaces ()
722 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
724 Hashtable cache = null;
727 // First add the assembly namespaces
729 if (assembly_get_namespaces != null){
730 int count = assemblies.Length;
732 for (int i = 0; i < count; i++){
733 Assembly a = assemblies [i];
734 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
735 foreach (string ns in namespaces){
738 Namespace.LookupNamespace (ns, true);
742 cache = new Hashtable ();
743 cache.Add ("", null);
744 foreach (Assembly a in assemblies) {
745 foreach (Type t in a.GetExportedTypes ()) {
746 string ns = t.Namespace;
747 if (ns == null || cache.Contains (ns))
750 Namespace.LookupNamespace (ns, true);
751 cache.Add (ns, null);
757 // Then add module namespaces
759 foreach (Module m in modules) {
760 if (m == CodeGen.Module.Builder)
763 cache = new Hashtable ();
764 cache.Add ("", null);
766 foreach (Type t in m.GetTypes ()) {
767 string ns = t.Namespace;
768 if (ns == null || cache.Contains (ns))
770 Namespace.LookupNamespace (ns, true);
771 cache.Add (ns, null);
777 /// Fills static table with exported types from all referenced assemblies.
778 /// This information is required for CLS Compliance tests.
780 public static void LoadAllImportedTypes ()
782 all_imported_types = new Hashtable ();
783 foreach (Assembly a in assemblies) {
784 foreach (Type t in a.GetExportedTypes ()) {
785 all_imported_types [t.FullName] = t;
790 public static bool NamespaceClash (string name, Location loc)
792 if (Namespace.LookupNamespace (name, false) == null)
795 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
800 /// Returns the C# name of a type if possible, or the full type name otherwise
802 static public string CSharpName (Type t)
804 return Regex.Replace (t.FullName,
806 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
807 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
808 @"Boolean|String|Void|Null)" +
810 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
813 static public string CSharpName (Type[] types)
815 StringBuilder sb = new StringBuilder ();
816 foreach (Type t in types) {
817 sb.Append (CSharpName (t));
820 sb.Remove (sb.Length - 1, 1);
821 return sb.ToString ();
824 static String CSharpNameMatch (Match match)
826 string s = match.Groups [1].Captures [0].Value;
828 Replace ("int32", "int").
829 Replace ("uint32", "uint").
830 Replace ("int16", "short").
831 Replace ("uint16", "ushort").
832 Replace ("int64", "long").
833 Replace ("uint64", "ulong").
834 Replace ("single", "float").
835 Replace ("boolean", "bool")
836 + match.Groups [2].Captures [0].Value;
840 /// Returns the signature of the method with full namespace classification
842 static public string GetFullNameSignature (MemberInfo mi)
844 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
845 return (mi is MethodBase)
846 ? GetFullNameSignature (mi as MethodBase)
847 : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
850 static public string GetFullNameSignature (MethodBase mb)
852 string name = mb.Name;
854 name = mb.DeclaringType.Name;
856 if (mb.IsSpecialName) {
857 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
858 name = name.Remove (0, 4);
865 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
869 /// Returns the signature of the property and indexer
871 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
874 return GetFullNameSignature (pb);
877 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
878 string signature = GetFullNameSignature (mb);
879 string arg = GetParameterData (mb).ParameterDesc (0);
880 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
884 /// Returns the signature of the method
886 static public string CSharpSignature (MethodBase mb)
888 StringBuilder sig = new StringBuilder ("(");
890 ParameterData iparams = GetParameterData (mb);
893 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
894 return GetFullNameSignature (mb);
896 for (int i = 0; i < iparams.Count; i++) {
900 sig.Append (iparams.ParameterDesc (i));
905 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
906 sig.Replace ('(', '[');
907 sig.Replace (')', ']');
910 return GetFullNameSignature (mb) + sig.ToString ();
914 /// Looks up a type, and aborts if it is not found. This is used
915 /// by types required by the compiler
917 static Type CoreLookupType (string name)
920 if (types.Contains (name))
921 t = (Type) types [name];
923 t = LookupTypeReflection (name);
926 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
933 /// Returns the MethodInfo for a method named `name' defined
934 /// in type `t' which takes arguments of types `args'
936 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
940 BindingFlags flags = instance_and_static | BindingFlags.Public;
946 flags |= BindingFlags.NonPublic;
948 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
949 if (list.Count == 0) {
951 Report.Error (-19, "Can not find the core function `" + name + "'");
955 MethodInfo mi = list [0] as MethodInfo;
958 Report.Error (-19, "Can not find the core function `" + name + "'");
965 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
967 return GetMethod (t, name, args, false, report_errors);
970 static MethodInfo GetMethod (Type t, string name, Type [] args)
972 return GetMethod (t, name, args, true);
977 /// Returns the ConstructorInfo for "args"
979 public static ConstructorInfo GetConstructor (Type t, Type [] args)
987 list = FindMembers (t, MemberTypes.Constructor,
988 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
989 signature_filter, sig);
990 if (list.Count == 0){
991 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
995 ConstructorInfo ci = list [0] as ConstructorInfo;
997 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1004 public static void InitEnumUnderlyingTypes ()
1007 int32_type = CoreLookupType ("System.Int32");
1008 int64_type = CoreLookupType ("System.Int64");
1009 uint32_type = CoreLookupType ("System.UInt32");
1010 uint64_type = CoreLookupType ("System.UInt64");
1011 byte_type = CoreLookupType ("System.Byte");
1012 sbyte_type = CoreLookupType ("System.SByte");
1013 short_type = CoreLookupType ("System.Int16");
1014 ushort_type = CoreLookupType ("System.UInt16");
1018 /// The types have to be initialized after the initial
1019 /// population of the type has happened (for example, to
1020 /// bootstrap the corlib.dll
1022 public static void InitCoreTypes ()
1024 object_type = CoreLookupType ("System.Object");
1025 value_type = CoreLookupType ("System.ValueType");
1027 InitEnumUnderlyingTypes ();
1029 char_type = CoreLookupType ("System.Char");
1030 string_type = CoreLookupType ("System.String");
1031 float_type = CoreLookupType ("System.Single");
1032 double_type = CoreLookupType ("System.Double");
1033 char_ptr_type = CoreLookupType ("System.Char*");
1034 decimal_type = CoreLookupType ("System.Decimal");
1035 bool_type = CoreLookupType ("System.Boolean");
1036 enum_type = CoreLookupType ("System.Enum");
1038 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1039 delegate_type = CoreLookupType ("System.Delegate");
1041 array_type = CoreLookupType ("System.Array");
1042 void_type = CoreLookupType ("System.Void");
1043 type_type = CoreLookupType ("System.Type");
1045 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1046 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1047 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1048 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1049 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1050 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1051 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1052 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1053 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1054 idisposable_type = CoreLookupType ("System.IDisposable");
1055 icloneable_type = CoreLookupType ("System.ICloneable");
1056 iconvertible_type = CoreLookupType ("System.IConvertible");
1057 monitor_type = CoreLookupType ("System.Threading.Monitor");
1058 intptr_type = CoreLookupType ("System.IntPtr");
1060 attribute_type = CoreLookupType ("System.Attribute");
1061 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1062 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1063 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1064 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1065 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1066 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1067 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1068 typed_reference_type = CoreLookupType ("System.TypedReference");
1069 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1070 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1071 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1073 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1075 void_ptr_type = CoreLookupType ("System.Void*");
1077 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1079 exception_type = CoreLookupType ("System.Exception");
1080 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1081 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1086 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1087 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1088 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1089 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1090 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1091 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1092 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1098 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1099 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1100 default_charset_type = CoreLookupType ("System.Runtime.InteropServices.DefaultCharSetAttribute");
1103 // When compiling corlib, store the "real" types here.
1105 if (!RootContext.StdLib) {
1106 system_int32_type = typeof (System.Int32);
1107 system_array_type = typeof (System.Array);
1108 system_type_type = typeof (System.Type);
1109 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1111 Type [] void_arg = { };
1112 system_int_array_get_length = GetMethod (
1113 system_array_type, "get_Length", void_arg);
1114 system_int_array_get_rank = GetMethod (
1115 system_array_type, "get_Rank", void_arg);
1116 system_object_array_clone = GetMethod (
1117 system_array_type, "Clone", void_arg);
1119 Type [] system_int_arg = { system_int32_type };
1120 system_int_array_get_length_int = GetMethod (
1121 system_array_type, "GetLength", system_int_arg);
1122 system_int_array_get_upper_bound_int = GetMethod (
1123 system_array_type, "GetUpperBound", system_int_arg);
1124 system_int_array_get_lower_bound_int = GetMethod (
1125 system_array_type, "GetLowerBound", system_int_arg);
1127 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1128 system_void_array_copyto_array_int = GetMethod (
1129 system_array_type, "CopyTo", system_array_int_arg);
1131 Type [] system_3_type_arg = {
1132 system_type_type, system_type_type, system_type_type };
1133 Type [] system_4_type_arg = {
1134 system_type_type, system_type_type, system_type_type, system_type_type };
1136 MethodInfo set_corlib_type_builders = GetMethod (
1137 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1138 system_4_type_arg, true, false);
1140 if (set_corlib_type_builders != null) {
1141 object[] args = new object [4];
1142 args [0] = object_type;
1143 args [1] = value_type;
1144 args [2] = enum_type;
1145 args [3] = void_type;
1147 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1149 // Compatibility for an older version of the class libs.
1150 set_corlib_type_builders = GetMethod (
1151 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1152 system_3_type_arg, true, true);
1154 if (set_corlib_type_builders == null) {
1155 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1159 object[] args = new object [3];
1160 args [0] = object_type;
1161 args [1] = value_type;
1162 args [2] = enum_type;
1164 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1168 system_object_expr.Type = object_type;
1169 system_string_expr.Type = string_type;
1170 system_boolean_expr.Type = bool_type;
1171 system_decimal_expr.Type = decimal_type;
1172 system_single_expr.Type = float_type;
1173 system_double_expr.Type = double_type;
1174 system_sbyte_expr.Type = sbyte_type;
1175 system_byte_expr.Type = byte_type;
1176 system_int16_expr.Type = short_type;
1177 system_uint16_expr.Type = ushort_type;
1178 system_int32_expr.Type = int32_type;
1179 system_uint32_expr.Type = uint32_type;
1180 system_int64_expr.Type = int64_type;
1181 system_uint64_expr.Type = uint64_type;
1182 system_char_expr.Type = char_type;
1183 system_void_expr.Type = void_type;
1184 system_asynccallback_expr.Type = asynccallback_type;
1185 system_iasyncresult_expr.Type = iasyncresult_type;
1186 system_valuetype_expr.Type = value_type;
1189 // These are only used for compare purposes
1191 anonymous_method_type = typeof (AnonymousMethod);
1192 null_type = typeof (NullType);
1196 // The helper methods that are used by the compiler
1198 public static void InitCodeHelpers ()
1201 // Now load the default methods that we use.
1203 Type [] string_string = { string_type, string_type };
1204 string_concat_string_string = GetMethod (
1205 string_type, "Concat", string_string);
1206 Type [] string_string_string = { string_type, string_type, string_type };
1207 string_concat_string_string_string = GetMethod (
1208 string_type, "Concat", string_string_string);
1209 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1210 string_concat_string_string_string_string = GetMethod (
1211 string_type, "Concat", string_string_string_string);
1212 Type[] params_string = { GetConstructedType (string_type, "[]") };
1213 string_concat_string_dot_dot_dot = GetMethod (
1214 string_type, "Concat", params_string);
1216 Type [] object_object = { object_type, object_type };
1217 string_concat_object_object = GetMethod (
1218 string_type, "Concat", object_object);
1219 Type [] object_object_object = { object_type, object_type, object_type };
1220 string_concat_object_object_object = GetMethod (
1221 string_type, "Concat", object_object_object);
1222 Type[] params_object = { GetConstructedType (object_type, "[]") };
1223 string_concat_object_dot_dot_dot = GetMethod (
1224 string_type, "Concat", params_object);
1226 Type [] string_ = { string_type };
1227 string_isinterneted_string = GetMethod (
1228 string_type, "IsInterned", string_);
1230 Type [] runtime_type_handle = { runtime_handle_type };
1231 system_type_get_type_from_handle = GetMethod (
1232 type_type, "GetTypeFromHandle", runtime_type_handle);
1234 Type [] delegate_delegate = { delegate_type, delegate_type };
1235 delegate_combine_delegate_delegate = GetMethod (
1236 delegate_type, "Combine", delegate_delegate);
1238 delegate_remove_delegate_delegate = GetMethod (
1239 delegate_type, "Remove", delegate_delegate);
1244 Type [] void_arg = { };
1245 object_getcurrent_void = GetMethod (
1246 ienumerator_type, "get_Current", void_arg);
1247 bool_movenext_void = GetMethod (
1248 ienumerator_type, "MoveNext", void_arg);
1249 void_reset_void = GetMethod (
1250 ienumerator_type, "Reset", void_arg);
1251 void_dispose_void = GetMethod (
1252 idisposable_type, "Dispose", void_arg);
1253 int_get_offset_to_string_data = GetMethod (
1254 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1255 int_array_get_length = GetMethod (
1256 array_type, "get_Length", void_arg);
1257 int_array_get_rank = GetMethod (
1258 array_type, "get_Rank", void_arg);
1259 ienumerable_getenumerator_void = GetMethod (
1260 ienumerable_type, "GetEnumerator", void_arg);
1265 Type [] int_arg = { int32_type };
1266 int_array_get_length_int = GetMethod (
1267 array_type, "GetLength", int_arg);
1268 int_array_get_upper_bound_int = GetMethod (
1269 array_type, "GetUpperBound", int_arg);
1270 int_array_get_lower_bound_int = GetMethod (
1271 array_type, "GetLowerBound", int_arg);
1274 // System.Array methods
1276 object_array_clone = GetMethod (
1277 array_type, "Clone", void_arg);
1278 Type [] array_int_arg = { array_type, int32_type };
1279 void_array_copyto_array_int = GetMethod (
1280 array_type, "CopyTo", array_int_arg);
1285 Type [] object_arg = { object_type };
1286 void_monitor_enter_object = GetMethod (
1287 monitor_type, "Enter", object_arg);
1288 void_monitor_exit_object = GetMethod (
1289 monitor_type, "Exit", object_arg);
1291 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1293 void_initializearray_array_fieldhandle = GetMethod (
1294 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1299 int_getlength_int = GetMethod (
1300 array_type, "GetLength", int_arg);
1303 // Decimal constructors
1305 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1306 void_decimal_ctor_five_args = GetConstructor (
1307 decimal_type, dec_arg);
1309 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1314 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1315 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1316 default_member_ctor = GetConstructor (default_member_type, string_);
1318 Type[] short_arg = { short_type };
1319 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1321 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1322 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1324 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1331 compiler_generated_attr = new CustomAttributeBuilder (
1332 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1334 Type[] type_int_arg = { type_type, int32_type };
1335 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1339 object_ctor = GetConstructor (object_type, void_arg);
1343 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1346 /// This is the "old", non-cache based FindMembers() function. We cannot use
1347 /// the cache here because there is no member name argument.
1349 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1350 MemberFilter filter, object criteria)
1352 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1355 // `builder_to_declspace' contains all dynamic types.
1359 Timer.StartTimer (TimerType.FindMembers);
1360 list = decl.FindMembers (mt, bf, filter, criteria);
1361 Timer.StopTimer (TimerType.FindMembers);
1366 // We have to take care of arrays specially, because GetType on
1367 // a TypeBuilder array will return a Type, not a TypeBuilder,
1368 // and we can not call FindMembers on this type.
1370 if (t.IsSubclassOf (TypeManager.array_type))
1371 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1374 // Since FindMembers will not lookup both static and instance
1375 // members, we emulate this behaviour here.
1377 if ((bf & instance_and_static) == instance_and_static){
1378 MemberInfo [] i_members = t.FindMembers (
1379 mt, bf & ~BindingFlags.Static, filter, criteria);
1381 int i_len = i_members.Length;
1383 MemberInfo one = i_members [0];
1386 // If any of these are present, we are done!
1388 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1389 return new MemberList (i_members);
1392 MemberInfo [] s_members = t.FindMembers (
1393 mt, bf & ~BindingFlags.Instance, filter, criteria);
1395 int s_len = s_members.Length;
1396 if (i_len > 0 || s_len > 0)
1397 return new MemberList (i_members, s_members);
1400 return new MemberList (i_members);
1402 return new MemberList (s_members);
1406 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1411 /// This method is only called from within MemberLookup. It tries to use the member
1412 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1413 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1414 /// our return value will already contain all inherited members and the caller don't need
1415 /// to check base classes and interfaces anymore.
1417 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1418 string name, out bool used_cache)
1423 // We have to take care of arrays specially, because GetType on
1424 // a TypeBuilder array will return a Type, not a TypeBuilder,
1425 // and we can not call FindMembers on this type.
1427 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1429 return TypeHandle.ArrayType.MemberCache.FindMembers (
1430 mt, bf, name, FilterWithClosure_delegate, null);
1434 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1435 // and we can ask the DeclSpace for the MemberCache.
1437 if (t is TypeBuilder) {
1438 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1439 cache = decl.MemberCache;
1442 // If this DeclSpace has a MemberCache, use it.
1445 if (cache != null) {
1447 return cache.FindMembers (
1448 mt, bf, name, FilterWithClosure_delegate, null);
1451 // If there is no MemberCache, we need to use the "normal" FindMembers.
1452 // Note, this is a VERY uncommon route!
1455 Timer.StartTimer (TimerType.FindMembers);
1456 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1457 FilterWithClosure_delegate, name);
1458 Timer.StopTimer (TimerType.FindMembers);
1461 return (MemberInfo []) list;
1465 // This call will always succeed. There is exactly one TypeHandle instance per
1466 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1467 // the corresponding MemberCache.
1469 cache = TypeHandle.GetMemberCache (t);
1472 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1475 public static bool IsBuiltinType (Type t)
1477 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1478 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1479 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1480 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1486 public static bool IsBuiltinType (TypeContainer tc)
1488 return IsBuiltinType (tc.TypeBuilder);
1492 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1493 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1495 public static bool IsPrimitiveType (Type t)
1497 return (t == int32_type || t == uint32_type ||
1498 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1499 t == char_type || t == short_type || t == bool_type ||
1500 t == sbyte_type || t == byte_type || t == ushort_type);
1503 public static bool IsDelegateType (Type t)
1505 if (t.IsSubclassOf (TypeManager.delegate_type))
1511 public static bool IsEnumType (Type t)
1513 if (t.IsSubclassOf (TypeManager.enum_type))
1518 public static bool IsBuiltinOrEnum (Type t)
1520 if (IsBuiltinType (t))
1530 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1532 public static bool IsUnmanagedType (Type t)
1534 // builtins that are not unmanaged types
1535 if (t == TypeManager.object_type || t == TypeManager.string_type)
1538 if (IsBuiltinOrEnum (t))
1541 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1545 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1549 if (!IsValueType (t))
1552 if (t is TypeBuilder){
1553 TypeContainer tc = LookupTypeContainer (t);
1554 if (tc.Fields == null)
1556 foreach (Field f in tc.Fields){
1557 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1558 if ((f.ModFlags & Modifiers.STATIC) != 0)
1560 if (f.MemberType == null)
1562 if (!IsUnmanagedType (f.MemberType)){
1563 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1570 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1572 foreach (FieldInfo f in fields){
1573 if (!IsUnmanagedType (f.FieldType)){
1574 Report.SymbolRelatedToPreviousError (f);
1582 public static bool IsValueType (Type t)
1584 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1590 public static bool IsInterfaceType (Type t)
1592 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1596 return tc.Kind == Kind.Interface;
1599 public static bool IsSubclassOf (Type type, Type base_type)
1602 if (type.Equals (base_type))
1605 type = type.BaseType;
1606 } while (type != null);
1611 public static bool IsFamilyAccessible (Type type, Type base_type)
1613 return IsSubclassOf (type, base_type);
1617 // Checks whether `type' is a subclass or nested child of `base_type'.
1619 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1622 if ((type == base_type) || type.IsSubclassOf (base_type))
1625 // Handle nested types.
1626 type = type.DeclaringType;
1627 } while (type != null);
1633 // Checks whether `type' is a nested child of `parent'.
1635 public static bool IsNestedChildOf (Type type, Type parent)
1640 type = type.DeclaringType;
1641 while (type != null) {
1645 type = type.DeclaringType;
1652 // Do the right thing when returning the element type of an
1653 // array type based on whether we are compiling corlib or not
1655 public static Type GetElementType (Type t)
1657 if (RootContext.StdLib)
1658 return t.GetElementType ();
1660 return TypeToCoreType (t.GetElementType ());
1664 /// This method is not implemented by MS runtime for dynamic types
1666 public static bool HasElementType (Type t)
1668 return t.IsArray || t.IsPointer || t.IsByRef;
1672 /// Returns the User Defined Types
1674 public static ArrayList UserTypes {
1680 public static Hashtable TypeContainers {
1682 return typecontainers;
1686 static Hashtable builder_to_constant;
1688 public static void RegisterConstant (FieldBuilder fb, Const c)
1690 if (builder_to_constant == null)
1691 builder_to_constant = new PtrHashtable ();
1693 if (builder_to_constant.Contains (fb))
1696 builder_to_constant.Add (fb, c);
1699 public static Const LookupConstant (FieldBuilder fb)
1701 if (builder_to_constant == null)
1704 return (Const) builder_to_constant [fb];
1708 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1712 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1713 /// for anything which is dynamic, and we need this in a number of places,
1714 /// we register this information here, and use it afterwards.
1716 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1721 method_arguments.Add (mb, args);
1722 method_params.Add (mb, ip);
1725 static public ParameterData GetParameterData (MethodBase mb)
1727 object pd = method_params [mb];
1729 if (mb is MethodBuilder || mb is ConstructorBuilder)
1730 throw new InternalErrorException ("Argument for Method not registered" + mb);
1732 method_params [mb] = pd = new ReflectionParameters (mb);
1735 return (ParameterData) pd;
1738 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1740 if (method_overrides.Contains (override_method)) {
1741 if (method_overrides [override_method] != base_method)
1742 throw new InternalErrorException ("Override mismatch: " + override_method);
1745 method_overrides [override_method] = base_method;
1748 static public bool IsOverride (MethodBase m)
1750 return m.IsVirtual &&
1751 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1752 (m is MethodBuilder || method_overrides.Contains (m));
1756 /// Returns the argument types for a method based on its methodbase
1758 /// For dynamic methods, we use the compiler provided types, for
1759 /// methods from existing assemblies we load them from GetParameters,
1760 /// and insert them into the cache
1762 static public Type [] GetArgumentTypes (MethodBase mb)
1764 object t = method_arguments [mb];
1768 ParameterInfo [] pi = mb.GetParameters ();
1775 types = new Type [c];
1776 for (int i = 0; i < c; i++)
1777 types [i] = pi [i].ParameterType;
1779 method_arguments.Add (mb, types);
1784 /// Returns the argument types for an indexer based on its PropertyInfo
1786 /// For dynamic indexers, we use the compiler provided types, for
1787 /// indexers from existing assemblies we load them from GetParameters,
1788 /// and insert them into the cache
1790 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1792 if (indexer_arguments.Contains (indexer))
1793 return (Type []) indexer_arguments [indexer];
1794 else if (indexer is PropertyBuilder)
1795 // If we're a PropertyBuilder and not in the
1796 // `indexer_arguments' hash, then we're a property and
1800 ParameterInfo [] pi = indexer.GetIndexParameters ();
1801 // Property, not an indexer.
1805 Type [] types = new Type [c];
1807 for (int i = 0; i < c; i++)
1808 types [i] = pi [i].ParameterType;
1810 indexer_arguments.Add (indexer, types);
1816 // This is a workaround the fact that GetValue is not
1817 // supported for dynamic types
1819 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1821 if (fields.Contains (fb))
1824 fields.Add (fb, value);
1829 static public object GetValue (FieldBuilder fb)
1834 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1836 if (fieldbuilders_to_fields.Contains (fb))
1839 fieldbuilders_to_fields.Add (fb, f);
1844 // The return value can be null; This will be the case for
1845 // auxiliary FieldBuilders created by the compiler that have no
1846 // real field being declared on the source code
1848 static public FieldBase GetField (FieldInfo fb)
1850 return (FieldBase) fieldbuilders_to_fields [fb];
1853 static Hashtable events;
1855 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1858 events = new Hashtable ();
1860 if (!events.Contains (eb)) {
1861 events.Add (eb, new Pair (add, remove));
1865 static public MethodInfo GetAddMethod (EventInfo ei)
1867 if (ei is MyEventBuilder) {
1868 Pair pair = (Pair) events [ei];
1870 return (MethodInfo) pair.First;
1872 return ei.GetAddMethod (true);
1875 static public MethodInfo GetRemoveMethod (EventInfo ei)
1877 if (ei is MyEventBuilder) {
1878 Pair pair = (Pair) events [ei];
1880 return (MethodInfo) pair.Second;
1882 return ei.GetRemoveMethod (true);
1885 static Hashtable priv_fields_events;
1887 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1889 if (priv_fields_events == null)
1890 priv_fields_events = new Hashtable ();
1892 if (priv_fields_events.Contains (einfo))
1895 priv_fields_events.Add (einfo, builder);
1900 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1902 if (priv_fields_events == null)
1905 return (MemberInfo) priv_fields_events [ei];
1908 static Hashtable properties;
1910 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1912 if (properties == null)
1913 properties = new Hashtable ();
1915 if (properties.Contains (pb))
1918 properties.Add (pb, new Pair (get, set));
1923 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1924 MethodBase set, Type[] args)
1926 if (!RegisterProperty (pb, get,set))
1929 indexer_arguments.Add (pb, args);
1934 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1936 Hashtable hash = new Hashtable ();
1937 return CheckStructCycles (tc, seen, hash);
1940 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1943 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1947 // `seen' contains all types we've already visited.
1949 if (seen.Contains (tc))
1951 seen.Add (tc, null);
1953 if (tc.Fields == null)
1956 foreach (FieldMember field in tc.Fields) {
1957 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1960 Type ftype = field.FieldBuilder.FieldType;
1961 TypeContainer ftc = LookupTypeContainer (ftype);
1965 if (hash.Contains (ftc)) {
1966 Report.Error (523, tc.Location,
1967 "Struct member `{0}.{1}' of type `{2}' " +
1968 "causes a cycle in the struct layout",
1969 tc.Name, field.Name, ftc.Name);
1974 // `hash' contains all types in the current path.
1976 hash.Add (tc, null);
1978 bool ok = CheckStructCycles (ftc, seen, hash);
1985 if (!seen.Contains (ftc))
1986 seen.Add (ftc, null);
1993 /// Given an array of interface types, expand and eliminate repeated ocurrences
1994 /// of an interface.
1998 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2001 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2003 ArrayList new_ifaces = new ArrayList ();
2005 foreach (TypeExpr iface in base_interfaces){
2006 Type itype = iface.ResolveType (ec);
2010 if (!new_ifaces.Contains (itype))
2011 new_ifaces.Add (itype);
2013 Type [] implementing = itype.GetInterfaces ();
2015 foreach (Type imp in implementing){
2016 if (!new_ifaces.Contains (imp))
2017 new_ifaces.Add (imp);
2020 Type [] ret = new Type [new_ifaces.Count];
2021 new_ifaces.CopyTo (ret, 0);
2025 static PtrHashtable iface_cache = new PtrHashtable ();
2028 /// This function returns the interfaces in the type `t'. Works with
2029 /// both types and TypeBuilders.
2031 public static Type [] GetInterfaces (Type t)
2034 Type [] cached = iface_cache [t] as Type [];
2039 // The reason for catching the Array case is that Reflection.Emit
2040 // will not return a TypeBuilder for Array types of TypeBuilder types,
2041 // but will still throw an exception if we try to call GetInterfaces
2044 // Since the array interfaces are always constant, we return those for
2049 t = TypeManager.array_type;
2051 if (t is TypeBuilder){
2052 Type [] base_ifaces;
2054 if (t.BaseType == null)
2055 base_ifaces = NoTypes;
2057 base_ifaces = GetInterfaces (t.BaseType);
2058 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
2059 if (type_ifaces == null)
2060 type_ifaces = NoTypes;
2062 int base_count = base_ifaces.Length;
2063 Type [] result = new Type [base_count + type_ifaces.Length];
2064 base_ifaces.CopyTo (result, 0);
2065 type_ifaces.CopyTo (result, base_count);
2067 iface_cache [t] = result;
2070 Type[] ifaces = t.GetInterfaces ();
2071 iface_cache [t] = ifaces;
2077 // gets the interfaces that are declared explicitly on t
2079 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2081 return (Type []) builder_to_ifaces [t];
2085 /// The following is used to check if a given type implements an interface.
2086 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2088 public static bool ImplementsInterface (Type t, Type iface)
2093 // FIXME OPTIMIZATION:
2094 // as soon as we hit a non-TypeBuiler in the interface
2095 // chain, we could return, as the `Type.GetInterfaces'
2096 // will return all the interfaces implement by the type
2100 interfaces = GetInterfaces (t);
2102 if (interfaces != null){
2103 foreach (Type i in interfaces){
2110 } while (t != null);
2115 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2117 // This is a custom version of Convert.ChangeType() which works
2118 // with the TypeBuilder defined types when compiling corlib.
2119 public static object ChangeType (object value, Type conversionType, out bool error)
2121 IConvertible convert_value = value as IConvertible;
2123 if (convert_value == null){
2129 // We must use Type.Equals() here since `conversionType' is
2130 // the TypeBuilder created version of a system type and not
2131 // the system type itself. You cannot use Type.GetTypeCode()
2132 // on such a type - it'd always return TypeCode.Object.
2136 if (conversionType.Equals (typeof (Boolean)))
2137 return (object)(convert_value.ToBoolean (nf_provider));
2138 else if (conversionType.Equals (typeof (Byte)))
2139 return (object)(convert_value.ToByte (nf_provider));
2140 else if (conversionType.Equals (typeof (Char)))
2141 return (object)(convert_value.ToChar (nf_provider));
2142 else if (conversionType.Equals (typeof (DateTime)))
2143 return (object)(convert_value.ToDateTime (nf_provider));
2144 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2145 return (object)(convert_value.ToDecimal (nf_provider));
2146 else if (conversionType.Equals (typeof (Double)))
2147 return (object)(convert_value.ToDouble (nf_provider));
2148 else if (conversionType.Equals (typeof (Int16)))
2149 return (object)(convert_value.ToInt16 (nf_provider));
2150 else if (conversionType.Equals (typeof (Int32)))
2151 return (object)(convert_value.ToInt32 (nf_provider));
2152 else if (conversionType.Equals (typeof (Int64)))
2153 return (object)(convert_value.ToInt64 (nf_provider));
2154 else if (conversionType.Equals (typeof (SByte)))
2155 return (object)(convert_value.ToSByte (nf_provider));
2156 else if (conversionType.Equals (typeof (Single)))
2157 return (object)(convert_value.ToSingle (nf_provider));
2158 else if (conversionType.Equals (typeof (String)))
2159 return (object)(convert_value.ToString (nf_provider));
2160 else if (conversionType.Equals (typeof (UInt16)))
2161 return (object)(convert_value.ToUInt16 (nf_provider));
2162 else if (conversionType.Equals (typeof (UInt32)))
2163 return (object)(convert_value.ToUInt32 (nf_provider));
2164 else if (conversionType.Equals (typeof (UInt64)))
2165 return (object)(convert_value.ToUInt64 (nf_provider));
2166 else if (conversionType.Equals (typeof (Object)))
2167 return (object)(value);
2177 // This is needed, because enumerations from assemblies
2178 // do not report their underlyingtype, but they report
2181 public static Type EnumToUnderlying (Type t)
2183 if (t == TypeManager.enum_type)
2186 t = t.UnderlyingSystemType;
2187 if (!TypeManager.IsEnumType (t))
2190 if (t is TypeBuilder) {
2191 // slow path needed to compile corlib
2192 if (t == TypeManager.bool_type ||
2193 t == TypeManager.byte_type ||
2194 t == TypeManager.sbyte_type ||
2195 t == TypeManager.char_type ||
2196 t == TypeManager.short_type ||
2197 t == TypeManager.ushort_type ||
2198 t == TypeManager.int32_type ||
2199 t == TypeManager.uint32_type ||
2200 t == TypeManager.int64_type ||
2201 t == TypeManager.uint64_type)
2203 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2205 TypeCode tc = Type.GetTypeCode (t);
2208 case TypeCode.Boolean:
2209 return TypeManager.bool_type;
2211 return TypeManager.byte_type;
2212 case TypeCode.SByte:
2213 return TypeManager.sbyte_type;
2215 return TypeManager.char_type;
2216 case TypeCode.Int16:
2217 return TypeManager.short_type;
2218 case TypeCode.UInt16:
2219 return TypeManager.ushort_type;
2220 case TypeCode.Int32:
2221 return TypeManager.int32_type;
2222 case TypeCode.UInt32:
2223 return TypeManager.uint32_type;
2224 case TypeCode.Int64:
2225 return TypeManager.int64_type;
2226 case TypeCode.UInt64:
2227 return TypeManager.uint64_type;
2229 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2233 // When compiling corlib and called with one of the core types, return
2234 // the corresponding typebuilder for that type.
2236 public static Type TypeToCoreType (Type t)
2238 if (RootContext.StdLib || (t is TypeBuilder))
2241 TypeCode tc = Type.GetTypeCode (t);
2244 case TypeCode.Boolean:
2245 return TypeManager.bool_type;
2247 return TypeManager.byte_type;
2248 case TypeCode.SByte:
2249 return TypeManager.sbyte_type;
2251 return TypeManager.char_type;
2252 case TypeCode.Int16:
2253 return TypeManager.short_type;
2254 case TypeCode.UInt16:
2255 return TypeManager.ushort_type;
2256 case TypeCode.Int32:
2257 return TypeManager.int32_type;
2258 case TypeCode.UInt32:
2259 return TypeManager.uint32_type;
2260 case TypeCode.Int64:
2261 return TypeManager.int64_type;
2262 case TypeCode.UInt64:
2263 return TypeManager.uint64_type;
2264 case TypeCode.Single:
2265 return TypeManager.float_type;
2266 case TypeCode.Double:
2267 return TypeManager.double_type;
2268 case TypeCode.String:
2269 return TypeManager.string_type;
2270 case TypeCode.Decimal:
2271 return TypeManager.decimal_type;
2273 if (t == typeof (void))
2274 return TypeManager.void_type;
2275 if (t == typeof (object))
2276 return TypeManager.object_type;
2277 if (t == typeof (System.Type))
2278 return TypeManager.type_type;
2279 if (t == typeof (System.IntPtr))
2280 return TypeManager.intptr_type;
2286 /// Utility function that can be used to probe whether a type
2287 /// is managed or not.
2289 public static bool VerifyUnManaged (Type t, Location loc)
2291 if (IsUnmanagedType (t))
2296 "Cannot take the address or size of a variable of a managed type ('" +
2297 CSharpName (t) + "')");
2302 /// Returns the name of the indexer in a given type.
2305 /// The default is not always `Item'. The user can change this behaviour by
2306 /// using the IndexerNameAttribute in the container.
2307 /// For example, the String class indexer is named `Chars' not `Item'
2309 public static string IndexerPropertyName (Type t)
2311 if (t is TypeBuilder) {
2312 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2313 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2316 System.Attribute attr = System.Attribute.GetCustomAttribute (
2317 t, TypeManager.default_member_type);
2319 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2320 return dma.MemberName;
2323 return TypeContainer.DefaultIndexerName;
2326 static MethodInfo declare_local_method = null;
2328 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2330 if (declare_local_method == null){
2331 declare_local_method = typeof (ILGenerator).GetMethod (
2333 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2335 new Type [] { typeof (Type), typeof (bool)},
2337 if (declare_local_method == null){
2338 Report.Warning (-30, new Location (-1),
2339 "This version of the runtime does not support making pinned local variables. " +
2340 "This code may cause errors on a runtime with a moving GC");
2341 return ig.DeclareLocal (t);
2344 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2348 // Returns whether the array of memberinfos contains the given method
2350 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2352 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2354 foreach (MethodBase method in array) {
2355 if (method.Name != new_method.Name)
2358 if (method is MethodInfo && new_method is MethodInfo)
2359 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2363 Type [] old_args = TypeManager.GetArgumentTypes (method);
2364 int old_count = old_args.Length;
2367 if (new_args.Length != old_count)
2370 for (i = 0; i < old_count; i++){
2371 if (old_args [i] != new_args [i])
2384 // We copy methods from `new_members' into `target_list' if the signature
2385 // for the method from in the new list does not exist in the target_list
2387 // The name is assumed to be the same.
2389 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2391 if (target_list == null){
2392 target_list = new ArrayList ();
2394 foreach (MemberInfo mi in new_members){
2395 if (mi is MethodBase)
2396 target_list.Add (mi);
2401 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2402 target_list.CopyTo (target_array, 0);
2404 foreach (MemberInfo mi in new_members){
2405 MethodBase new_method = (MethodBase) mi;
2407 if (!ArrayContainsMethod (target_array, new_method))
2408 target_list.Add (new_method);
2414 #region MemberLookup implementation
2417 // Whether we allow private members in the result (since FindMembers
2418 // uses NonPublic for both protected and private), we need to distinguish.
2421 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2426 internal class Closure {
2427 internal bool private_ok;
2429 // Who is invoking us and which type is being queried currently.
2430 internal Type invocation_type;
2431 internal Type qualifier_type;
2433 // The assembly that defines the type is that is calling us
2434 internal Assembly invocation_assembly;
2435 internal IList almost_match;
2437 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2439 if (invocation_type == null)
2442 if (is_static && qualifier_type == null)
2443 // It resolved from a simple name, so it should be visible.
2446 // A nested class has access to all the protected members visible to its parent.
2447 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2450 if (invocation_type == m.DeclaringType || invocation_type.IsSubclassOf (m.DeclaringType)) {
2451 // Although a derived class can access protected members of its base class
2452 // it cannot do so through an instance of the base class (CS1540).
2453 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2455 qualifier_type == null ||
2456 qualifier_type == invocation_type ||
2457 qualifier_type.IsSubclassOf (invocation_type))
2461 if (!is_static && almost_match != null)
2462 almost_match.Add (m);
2468 // This filter filters by name + whether it is ok to include private
2469 // members in the search
2471 internal bool Filter (MemberInfo m, object filter_criteria)
2474 // Hack: we know that the filter criteria will always be in the `closure'
2478 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2481 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2482 (m.DeclaringType == invocation_type))
2486 // Ugly: we need to find out the type of `m', and depending
2487 // on this, tell whether we accept or not
2489 if (m is MethodBase){
2490 MethodBase mb = (MethodBase) m;
2491 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2493 if (ma == MethodAttributes.Private)
2494 return private_ok || invocation_type == m.DeclaringType ||
2495 IsNestedChildOf (invocation_type, m.DeclaringType);
2497 if (invocation_assembly == mb.DeclaringType.Assembly) {
2498 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2501 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2505 if (ma == MethodAttributes.Family ||
2506 ma == MethodAttributes.FamANDAssem ||
2507 ma == MethodAttributes.FamORAssem)
2508 return CheckValidFamilyAccess (mb.IsStatic, m);
2514 if (m is FieldInfo){
2515 FieldInfo fi = (FieldInfo) m;
2516 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2518 if (fa == FieldAttributes.Private)
2519 return private_ok || (invocation_type == m.DeclaringType) ||
2520 IsNestedChildOf (invocation_type, m.DeclaringType);
2522 if (invocation_assembly == fi.DeclaringType.Assembly) {
2523 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2526 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2530 if (fa == FieldAttributes.Family ||
2531 fa == FieldAttributes.FamANDAssem ||
2532 fa == FieldAttributes.FamORAssem)
2533 return CheckValidFamilyAccess (fi.IsStatic, m);
2540 // EventInfos and PropertyInfos, return true because they lack permission
2541 // information, so we need to check later on the methods.
2547 static Closure closure = new Closure ();
2548 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2551 // Looks up a member called `name' in the `queried_type'. This lookup
2552 // is done by code that is contained in the definition for `invocation_type'
2553 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2555 // `invocation_type' is used to check whether we're allowed to access the requested
2556 // member wrt its protection level.
2558 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2559 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2560 // is B and qualifier_type is A). This is used to do the CS1540 check.
2562 // When resolving a SimpleName, `qualifier_type' is null.
2564 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2565 // the same than `queried_type' - except when we're being called from BaseAccess;
2566 // in this case, `invocation_type' is the current type and `queried_type' the base
2567 // type, so this'd normally trigger a CS1540.
2569 // The binding flags are `bf' and the kind of members being looked up are `mt'
2571 // The return value always includes private members which code in `invocation_type'
2572 // is allowed to access (using the specified `qualifier_type' if given); only use
2573 // BindingFlags.NonPublic to bypass the permission check.
2575 // The 'almost_match' argument is used for reporting error CS1540.
2577 // Returns an array of a single element for everything but Methods/Constructors
2578 // that might return multiple matches.
2580 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2581 Type queried_type, MemberTypes mt,
2582 BindingFlags original_bf, string name, IList almost_match)
2584 Timer.StartTimer (TimerType.MemberLookup);
2586 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2587 queried_type, mt, original_bf, name, almost_match);
2589 Timer.StopTimer (TimerType.MemberLookup);
2594 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2595 Type queried_type, MemberTypes mt,
2596 BindingFlags original_bf, string name, IList almost_match)
2598 BindingFlags bf = original_bf;
2600 ArrayList method_list = null;
2601 Type current_type = queried_type;
2602 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2603 bool skip_iface_check = true, used_cache = false;
2604 bool always_ok_flag = false;
2606 closure.invocation_type = invocation_type;
2607 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2608 closure.qualifier_type = qualifier_type;
2609 closure.almost_match = almost_match;
2612 // If we are a nested class, we always have access to our container
2615 if (invocation_type != null){
2616 string invocation_name = invocation_type.FullName;
2617 if (invocation_name.IndexOf ('+') != -1){
2618 string container = queried_type.FullName + "+";
2619 int container_length = container.Length;
2621 if (invocation_name.Length > container_length){
2622 string shared = invocation_name.Substring (0, container_length);
2624 if (shared == container)
2625 always_ok_flag = true;
2630 // This is from the first time we find a method
2631 // in most cases, we do not actually find a method in the base class
2632 // so we can just ignore it, and save the arraylist allocation
2633 MemberInfo [] first_members_list = null;
2634 bool use_first_members_list = false;
2640 // `NonPublic' is lame, because it includes both protected and
2641 // private methods, so we need to control this behavior by
2642 // explicitly tracking if a private method is ok or not.
2644 // The possible cases are:
2645 // public, private and protected (internal does not come into the
2648 if ((invocation_type != null) &&
2649 ((invocation_type == current_type) ||
2650 IsNestedChildOf (invocation_type, current_type)) ||
2652 bf = original_bf | BindingFlags.NonPublic;
2656 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2658 Timer.StopTimer (TimerType.MemberLookup);
2660 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2662 Timer.StartTimer (TimerType.MemberLookup);
2665 // When queried for an interface type, the cache will automatically check all
2666 // inherited members, so we don't need to do this here. However, this only
2667 // works if we already used the cache in the first iteration of this loop.
2669 // If we used the cache in any further iteration, we can still terminate the
2670 // loop since the cache always looks in all base classes.
2676 skip_iface_check = false;
2678 if (current_type == TypeManager.object_type)
2681 current_type = current_type.BaseType;
2684 // This happens with interfaces, they have a null
2685 // basetype. Look members up in the Object class.
2687 if (current_type == null) {
2688 current_type = TypeManager.object_type;
2693 if (list.Length == 0)
2697 // Events and types are returned by both `static' and `instance'
2698 // searches, which means that our above FindMembers will
2699 // return two copies of the same.
2701 if (list.Length == 1 && !(list [0] is MethodBase)){
2706 // Multiple properties: we query those just to find out the indexer
2709 if (list [0] is PropertyInfo)
2713 // We found an event: the cache lookup returns both the event and
2714 // its private field.
2716 if (list [0] is EventInfo) {
2717 if ((list.Length == 2) && (list [1] is FieldInfo))
2718 return new MemberInfo [] { list [0] };
2725 // We found methods, turn the search into "method scan"
2729 if (first_members_list != null) {
2730 if (use_first_members_list) {
2731 method_list = CopyNewMethods (method_list, first_members_list);
2732 use_first_members_list = false;
2735 method_list = CopyNewMethods (method_list, list);
2737 first_members_list = list;
2738 use_first_members_list = true;
2739 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2741 } while (searching);
2743 if (use_first_members_list) {
2744 foreach (MemberInfo mi in first_members_list) {
2745 if (! (mi is MethodBase)) {
2746 method_list = CopyNewMethods (method_list, first_members_list);
2747 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2750 return (MemberInfo []) first_members_list;
2753 if (method_list != null && method_list.Count > 0)
2754 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2757 // This happens if we already used the cache in the first iteration, in this case
2758 // the cache already looked in all interfaces.
2760 if (skip_iface_check)
2764 // Interfaces do not list members they inherit, so we have to
2767 if (!queried_type.IsInterface)
2770 if (queried_type.IsArray)
2771 queried_type = TypeManager.array_type;
2773 Type [] ifaces = GetInterfaces (queried_type);
2777 foreach (Type itype in ifaces){
2780 x = MemberLookup (null, null, itype, mt, bf, name, null);
2788 // Tests whether external method is really special
2789 public static bool IsSpecialMethod (MethodBase mb)
2791 string name = mb.Name;
2792 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2793 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2795 if (name.StartsWith ("add_"))
2796 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2798 if (name.StartsWith ("remove_"))
2799 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2801 if (name.StartsWith ("op_")){
2802 foreach (string oname in Unary.oper_names) {
2807 foreach (string oname in Binary.oper_names) {
2820 /// There is exactly one instance of this class per type.
2822 public sealed class TypeHandle : IMemberContainer {
2823 public readonly IMemberContainer BaseType;
2825 readonly int id = ++next_id;
2826 static int next_id = 0;
2828 static TypeHandle ()
2834 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2835 /// a TypeHandle yet, a new instance of it is created. This static method
2836 /// ensures that we'll only have one TypeHandle instance per type.
2838 private static TypeHandle GetTypeHandle (Type t)
2840 TypeHandle handle = (TypeHandle) type_hash [t];
2844 handle = new TypeHandle (t);
2845 type_hash.Add (t, handle);
2849 public static MemberCache GetMemberCache (Type t)
2851 return GetTypeHandle (t).MemberCache;
2854 public static void CleanUp ()
2859 public static void Reset ()
2861 type_hash = new PtrHashtable ();
2865 /// Returns the TypeHandle for TypeManager.object_type.
2867 public static IMemberContainer ObjectType {
2869 if (object_type != null)
2872 object_type = GetTypeHandle (TypeManager.object_type);
2879 /// Returns the TypeHandle for TypeManager.array_type.
2881 public static IMemberContainer ArrayType {
2883 if (array_type != null)
2886 array_type = GetTypeHandle (TypeManager.array_type);
2892 private static PtrHashtable type_hash;
2894 private static TypeHandle object_type = null;
2895 private static TypeHandle array_type = null;
2898 private bool is_interface;
2899 private MemberCache member_cache;
2900 private MemberCache base_cache;
2902 private TypeHandle (Type type)
2905 if (type.BaseType != null) {
2906 base_cache = TypeManager.LookupMemberCache (type.BaseType);
2907 BaseType = base_cache.Container;
2908 } else if (type.IsInterface)
2909 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2910 this.is_interface = type.IsInterface;
2911 this.member_cache = new MemberCache (this);
2914 // IMemberContainer methods
2916 public string Name {
2918 return type.FullName;
2928 public MemberCache BaseCache {
2934 public bool IsInterface {
2936 return is_interface;
2940 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2942 MemberInfo [] members;
2943 if (mt == MemberTypes.Event)
2944 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2946 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2948 Array.Reverse (members);
2950 return new MemberList (members);
2953 // IMemberFinder methods
2955 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2956 MemberFilter filter, object criteria)
2958 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2961 public MemberCache MemberCache {
2963 return member_cache;
2967 public override string ToString ()
2969 if (BaseType != null)
2970 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2972 return "TypeHandle (" + id + "," + Name + ")";