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 // It is not straightforward, using reflection, to determine if a method overrides another.
269 // Oftentimes, a non-override is marked with both the 'virtual' and 'newslot' method attributes.
270 // However, it's not always the case. We use this table to store those non-override methods
271 // that aren't so conveniently marked.
273 static Hashtable method_non_override;
276 // Keeps track of methods
279 static Hashtable builder_to_method;
282 // Contains all public types from referenced assemblies.
283 // This member is used only if CLS Compliance verification is required.
285 public static Hashtable all_imported_types;
287 static Hashtable fieldbuilders_to_fields;
288 static Hashtable fields;
295 public static void CleanUp ()
297 // Lets get everything clean so that we can collect before generating code
301 typecontainers = null;
303 builder_to_declspace = null;
304 builder_to_member_cache = null;
305 builder_to_ifaces = null;
306 method_arguments = null;
307 indexer_arguments = null;
308 method_params = null;
309 builder_to_method = null;
312 builder_to_constant = null;
313 fieldbuilders_to_fields = null;
315 priv_fields_events = null;
319 TypeHandle.CleanUp ();
323 /// A filter for Findmembers that uses the Signature object to
326 static bool SignatureFilter (MemberInfo mi, object criteria)
328 Signature sig = (Signature) criteria;
330 if (!(mi is MethodBase))
333 if (mi.Name != sig.name)
336 int count = sig.args.Length;
338 if (mi is MethodBuilder || mi is ConstructorBuilder){
339 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
341 if (candidate_args.Length != count)
344 for (int i = 0; i < count; i++)
345 if (candidate_args [i] != sig.args [i])
350 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
352 if (pars.Length != count)
355 for (int i = 0; i < count; i++)
356 if (pars [i].ParameterType != sig.args [i])
362 // A delegate that points to the filter above.
363 static MemberFilter signature_filter;
366 // These are expressions that represent some of the internal data types, used
369 static void InitExpressionTypes ()
371 system_object_expr = new TypeLookupExpression ("System.Object");
372 system_string_expr = new TypeLookupExpression ("System.String");
373 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
374 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
375 system_single_expr = new TypeLookupExpression ("System.Single");
376 system_double_expr = new TypeLookupExpression ("System.Double");
377 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
378 system_byte_expr = new TypeLookupExpression ("System.Byte");
379 system_int16_expr = new TypeLookupExpression ("System.Int16");
380 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
381 system_int32_expr = new TypeLookupExpression ("System.Int32");
382 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
383 system_int64_expr = new TypeLookupExpression ("System.Int64");
384 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
385 system_char_expr = new TypeLookupExpression ("System.Char");
386 system_void_expr = new TypeLookupExpression ("System.Void");
387 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
388 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
389 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
390 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
393 static TypeManager ()
397 signature_filter = new MemberFilter (SignatureFilter);
398 InitExpressionTypes ();
401 static public void Reset ()
403 assemblies = new Assembly [0];
405 user_types = new ArrayList ();
407 types = new Hashtable ();
408 typecontainers = new Hashtable ();
410 builder_to_declspace = new PtrHashtable ();
411 builder_to_member_cache = new PtrHashtable ();
412 builder_to_method = new PtrHashtable ();
413 method_arguments = new PtrHashtable ();
414 method_params = new PtrHashtable ();
415 method_non_override = new PtrHashtable ();
416 indexer_arguments = new PtrHashtable ();
417 builder_to_ifaces = new PtrHashtable ();
419 NoTypes = new Type [0];
420 NoTypeExprs = new TypeExpr [0];
422 fieldbuilders_to_fields = new Hashtable ();
423 fields = new Hashtable ();
424 type_hash = new DoubleHash ();
427 public static void HandleDuplicate (string name, Type t)
429 Type prev = (Type) types [name];
430 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
434 // This probably never happens, as we catch this before
436 Report.Error (-17, "The type `" + name + "' has already been defined.");
440 tc = builder_to_declspace [t] as TypeContainer;
443 1595, "The type `" + name + "' is defined in an existing assembly;"+
444 " Using the new definition from: " + tc.Location);
447 1595, "The type `" + name + "' is defined in an existing assembly;");
450 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
456 public static void AddUserType (string name, TypeBuilder t)
461 HandleDuplicate (name, t);
468 // This entry point is used by types that we define under the covers
470 public static void RegisterBuilder (Type tb, Type [] ifaces)
473 builder_to_ifaces [tb] = ifaces;
476 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
478 builder_to_declspace.Add (t, tc);
479 typecontainers.Add (name, tc);
480 AddUserType (name, t);
483 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
488 HandleDuplicate (name, t);
491 builder_to_declspace.Add (t, del);
494 public static void AddEnumType (string name, TypeBuilder t, Enum en)
499 HandleDuplicate (name, t);
501 builder_to_declspace.Add (t, en);
504 public static void AddMethod (MethodBase builder, IMethodData method)
506 builder_to_method.Add (builder, method);
509 public static IMethodData GetMethod (MethodBase builder)
511 return (IMethodData) builder_to_method [builder];
515 /// Returns the DeclSpace whose Type is `t' or null if there is no
516 /// DeclSpace for `t' (ie, the Type comes from a library)
518 public static DeclSpace LookupDeclSpace (Type t)
520 return builder_to_declspace [t] as DeclSpace;
524 /// Returns the TypeContainer whose Type is `t' or null if there is no
525 /// TypeContainer for `t' (ie, the Type comes from a library)
527 public static TypeContainer LookupTypeContainer (Type t)
529 return builder_to_declspace [t] as TypeContainer;
532 public static MemberCache LookupMemberCache (Type t)
534 if (t is TypeBuilder) {
535 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
536 if (container != null)
537 return container.MemberCache;
540 return TypeHandle.GetMemberCache (t);
543 public static MemberCache LookupBaseInterfacesCache (Type t)
545 Type [] ifaces = t.GetInterfaces ();
547 if (ifaces != null && ifaces.Length == 1)
548 return LookupMemberCache (ifaces [0]);
550 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
551 MemberCache cache = builder_to_member_cache [t] as MemberCache;
555 cache = new MemberCache (ifaces);
556 builder_to_member_cache.Add (t, cache);
560 public static TypeContainer LookupInterface (Type t)
562 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
563 if ((tc == null) || (tc.Kind != Kind.Interface))
569 public static Delegate LookupDelegate (Type t)
571 return builder_to_declspace [t] as Delegate;
574 public static Enum LookupEnum (Type t)
576 return builder_to_declspace [t] as Enum;
579 public static Class LookupClass (Type t)
581 return (Class) builder_to_declspace [t];
585 /// Registers an assembly to load types from.
587 public static void AddAssembly (Assembly a)
589 foreach (Assembly assembly in assemblies) {
594 int top = assemblies.Length;
595 Assembly [] n = new Assembly [top + 1];
597 assemblies.CopyTo (n, 0);
603 public static Assembly [] GetAssemblies ()
609 /// Registers a module builder to lookup types from
611 public static void AddModule (Module mb)
613 int top = modules != null ? modules.Length : 0;
614 Module [] n = new Module [top + 1];
617 modules.CopyTo (n, 0);
622 public static Module[] Modules {
629 // We use this hash for multiple kinds of constructed types:
631 // (T, "&") Given T, get T &
632 // (T, "*") Given T, get T *
633 // (T, "[]") Given T and a array dimension, get T []
634 // (T, X) Given a type T and a simple name X, get the type T+X
636 // Accessibility tests, if necessary, should be done by the user
638 static DoubleHash type_hash = new DoubleHash ();
641 // Gets the reference to T version of the Type (T&)
643 public static Type GetReferenceType (Type t)
645 return GetConstructedType (t, "&");
649 // Gets the pointer to T version of the Type (T*)
651 public static Type GetPointerType (Type t)
653 return GetConstructedType (t, "*");
656 public static Type GetConstructedType (Type t, string dim)
659 if (!type_hash.Lookup (t, dim, out ret)) {
660 ret = t.Module.GetType (t.ToString () + dim);
661 type_hash.Insert (t, dim, ret);
666 public static Type GetNestedType (Type t, string name)
669 if (!type_hash.Lookup (t, name, out ret)) {
670 string lookup = t.ToString () + "+" + name;
671 ret = t.Module.GetType (lookup);
672 type_hash.Insert (t, name, ret);
678 // Low-level lookup, cache-less
680 public static Type LookupTypeReflection (string name)
684 foreach (Assembly a in assemblies){
685 t = a.GetType (name);
690 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
691 if (ta == TypeAttributes.NotPublic ||
692 ta == TypeAttributes.NestedPrivate ||
693 ta == TypeAttributes.NestedAssembly ||
694 ta == TypeAttributes.NestedFamANDAssem){
697 // In .NET pointers turn out to be private, even if their
698 // element type is not
701 t = t.GetElementType ();
711 foreach (Module mb in modules) {
712 t = mb.GetType (name);
721 /// Computes the namespaces that we import from the assemblies we reference.
723 public static void ComputeNamespaces ()
725 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
727 Hashtable cache = null;
730 // First add the assembly namespaces
732 if (assembly_get_namespaces != null){
733 int count = assemblies.Length;
735 for (int i = 0; i < count; i++){
736 Assembly a = assemblies [i];
737 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
738 foreach (string ns in namespaces){
741 Namespace.LookupNamespace (ns, true);
745 cache = new Hashtable ();
746 cache.Add ("", null);
747 foreach (Assembly a in assemblies) {
748 foreach (Type t in a.GetExportedTypes ()) {
749 string ns = t.Namespace;
750 if (ns == null || cache.Contains (ns))
753 Namespace.LookupNamespace (ns, true);
754 cache.Add (ns, null);
760 // Then add module namespaces
762 foreach (Module m in modules) {
763 if (m == CodeGen.Module.Builder)
766 cache = new Hashtable ();
767 cache.Add ("", null);
769 foreach (Type t in m.GetTypes ()) {
770 string ns = t.Namespace;
771 if (ns == null || cache.Contains (ns))
773 Namespace.LookupNamespace (ns, true);
774 cache.Add (ns, null);
780 /// Fills static table with exported types from all referenced assemblies.
781 /// This information is required for CLS Compliance tests.
783 public static void LoadAllImportedTypes ()
785 all_imported_types = new Hashtable ();
786 foreach (Assembly a in assemblies) {
787 foreach (Type t in a.GetExportedTypes ()) {
788 all_imported_types [t.FullName] = t;
793 public static bool NamespaceClash (string name, Location loc)
795 if (Namespace.LookupNamespace (name, false) == null)
798 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
803 /// Returns the C# name of a type if possible, or the full type name otherwise
805 static public string CSharpName (Type t)
807 return Regex.Replace (t.FullName,
809 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
810 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
811 @"Boolean|String|Void|Null)" +
813 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
816 static public string CSharpName (Type[] types)
818 StringBuilder sb = new StringBuilder ();
819 foreach (Type t in types) {
820 sb.Append (CSharpName (t));
823 sb.Remove (sb.Length - 1, 1);
824 return sb.ToString ();
827 static String CSharpNameMatch (Match match)
829 string s = match.Groups [1].Captures [0].Value;
831 Replace ("int32", "int").
832 Replace ("uint32", "uint").
833 Replace ("int16", "short").
834 Replace ("uint16", "ushort").
835 Replace ("int64", "long").
836 Replace ("uint64", "ulong").
837 Replace ("single", "float").
838 Replace ("boolean", "bool")
839 + match.Groups [2].Captures [0].Value;
843 /// Returns the signature of the method with full namespace classification
845 static public string GetFullNameSignature (MemberInfo mi)
847 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
848 return (mi is MethodBase)
849 ? GetFullNameSignature (mi as MethodBase)
850 : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
853 static public string GetFullNameSignature (MethodBase mb)
855 string name = mb.Name;
857 name = mb.DeclaringType.Name;
859 if (mb.IsSpecialName) {
860 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
861 name = name.Remove (0, 4);
868 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
872 /// Returns the signature of the property and indexer
874 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
877 return GetFullNameSignature (pb);
880 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
881 string signature = GetFullNameSignature (mb);
882 string arg = GetParameterData (mb).ParameterDesc (0);
883 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
887 /// Returns the signature of the method
889 static public string CSharpSignature (MethodBase mb)
891 StringBuilder sig = new StringBuilder ("(");
893 ParameterData iparams = GetParameterData (mb);
896 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
897 return GetFullNameSignature (mb);
899 for (int i = 0; i < iparams.Count; i++) {
903 sig.Append (iparams.ParameterDesc (i));
908 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
909 sig.Replace ('(', '[');
910 sig.Replace (')', ']');
913 return GetFullNameSignature (mb) + sig.ToString ();
917 /// Looks up a type, and aborts if it is not found. This is used
918 /// by types required by the compiler
920 static Type CoreLookupType (string name)
923 if (types.Contains (name))
924 t = (Type) types [name];
926 t = LookupTypeReflection (name);
929 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
936 /// Returns the MethodInfo for a method named `name' defined
937 /// in type `t' which takes arguments of types `args'
939 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
943 BindingFlags flags = instance_and_static | BindingFlags.Public;
949 flags |= BindingFlags.NonPublic;
951 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
952 if (list.Count == 0) {
954 Report.Error (-19, "Can not find the core function `" + name + "'");
958 MethodInfo mi = list [0] as MethodInfo;
961 Report.Error (-19, "Can not find the core function `" + name + "'");
968 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
970 return GetMethod (t, name, args, false, report_errors);
973 static MethodInfo GetMethod (Type t, string name, Type [] args)
975 return GetMethod (t, name, args, true);
980 /// Returns the ConstructorInfo for "args"
982 public static ConstructorInfo GetConstructor (Type t, Type [] args)
990 list = FindMembers (t, MemberTypes.Constructor,
991 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
992 signature_filter, sig);
993 if (list.Count == 0){
994 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
998 ConstructorInfo ci = list [0] as ConstructorInfo;
1000 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1007 public static void InitEnumUnderlyingTypes ()
1010 int32_type = CoreLookupType ("System.Int32");
1011 int64_type = CoreLookupType ("System.Int64");
1012 uint32_type = CoreLookupType ("System.UInt32");
1013 uint64_type = CoreLookupType ("System.UInt64");
1014 byte_type = CoreLookupType ("System.Byte");
1015 sbyte_type = CoreLookupType ("System.SByte");
1016 short_type = CoreLookupType ("System.Int16");
1017 ushort_type = CoreLookupType ("System.UInt16");
1021 /// The types have to be initialized after the initial
1022 /// population of the type has happened (for example, to
1023 /// bootstrap the corlib.dll
1025 public static void InitCoreTypes ()
1027 object_type = CoreLookupType ("System.Object");
1028 value_type = CoreLookupType ("System.ValueType");
1030 InitEnumUnderlyingTypes ();
1032 char_type = CoreLookupType ("System.Char");
1033 string_type = CoreLookupType ("System.String");
1034 float_type = CoreLookupType ("System.Single");
1035 double_type = CoreLookupType ("System.Double");
1036 char_ptr_type = CoreLookupType ("System.Char*");
1037 decimal_type = CoreLookupType ("System.Decimal");
1038 bool_type = CoreLookupType ("System.Boolean");
1039 enum_type = CoreLookupType ("System.Enum");
1041 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1042 delegate_type = CoreLookupType ("System.Delegate");
1044 array_type = CoreLookupType ("System.Array");
1045 void_type = CoreLookupType ("System.Void");
1046 type_type = CoreLookupType ("System.Type");
1048 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1049 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1050 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1051 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1052 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1053 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1054 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1055 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1056 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1057 idisposable_type = CoreLookupType ("System.IDisposable");
1058 icloneable_type = CoreLookupType ("System.ICloneable");
1059 iconvertible_type = CoreLookupType ("System.IConvertible");
1060 monitor_type = CoreLookupType ("System.Threading.Monitor");
1061 intptr_type = CoreLookupType ("System.IntPtr");
1063 attribute_type = CoreLookupType ("System.Attribute");
1064 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1065 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1066 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1067 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1068 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1069 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1070 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1071 typed_reference_type = CoreLookupType ("System.TypedReference");
1072 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1073 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1074 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1076 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1078 void_ptr_type = CoreLookupType ("System.Void*");
1080 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1082 exception_type = CoreLookupType ("System.Exception");
1083 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1084 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1089 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1090 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1091 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1092 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1093 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1094 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1095 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1101 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1102 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1103 default_charset_type = CoreLookupType ("System.Runtime.InteropServices.DefaultCharSetAttribute");
1106 // When compiling corlib, store the "real" types here.
1108 if (!RootContext.StdLib) {
1109 system_int32_type = typeof (System.Int32);
1110 system_array_type = typeof (System.Array);
1111 system_type_type = typeof (System.Type);
1112 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1114 Type [] void_arg = { };
1115 system_int_array_get_length = GetMethod (
1116 system_array_type, "get_Length", void_arg);
1117 system_int_array_get_rank = GetMethod (
1118 system_array_type, "get_Rank", void_arg);
1119 system_object_array_clone = GetMethod (
1120 system_array_type, "Clone", void_arg);
1122 Type [] system_int_arg = { system_int32_type };
1123 system_int_array_get_length_int = GetMethod (
1124 system_array_type, "GetLength", system_int_arg);
1125 system_int_array_get_upper_bound_int = GetMethod (
1126 system_array_type, "GetUpperBound", system_int_arg);
1127 system_int_array_get_lower_bound_int = GetMethod (
1128 system_array_type, "GetLowerBound", system_int_arg);
1130 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1131 system_void_array_copyto_array_int = GetMethod (
1132 system_array_type, "CopyTo", system_array_int_arg);
1134 Type [] system_3_type_arg = {
1135 system_type_type, system_type_type, system_type_type };
1136 Type [] system_4_type_arg = {
1137 system_type_type, system_type_type, system_type_type, system_type_type };
1139 MethodInfo set_corlib_type_builders = GetMethod (
1140 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1141 system_4_type_arg, true, false);
1143 if (set_corlib_type_builders != null) {
1144 object[] args = new object [4];
1145 args [0] = object_type;
1146 args [1] = value_type;
1147 args [2] = enum_type;
1148 args [3] = void_type;
1150 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1152 // Compatibility for an older version of the class libs.
1153 set_corlib_type_builders = GetMethod (
1154 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1155 system_3_type_arg, true, true);
1157 if (set_corlib_type_builders == null) {
1158 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1162 object[] args = new object [3];
1163 args [0] = object_type;
1164 args [1] = value_type;
1165 args [2] = enum_type;
1167 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1171 system_object_expr.Type = object_type;
1172 system_string_expr.Type = string_type;
1173 system_boolean_expr.Type = bool_type;
1174 system_decimal_expr.Type = decimal_type;
1175 system_single_expr.Type = float_type;
1176 system_double_expr.Type = double_type;
1177 system_sbyte_expr.Type = sbyte_type;
1178 system_byte_expr.Type = byte_type;
1179 system_int16_expr.Type = short_type;
1180 system_uint16_expr.Type = ushort_type;
1181 system_int32_expr.Type = int32_type;
1182 system_uint32_expr.Type = uint32_type;
1183 system_int64_expr.Type = int64_type;
1184 system_uint64_expr.Type = uint64_type;
1185 system_char_expr.Type = char_type;
1186 system_void_expr.Type = void_type;
1187 system_asynccallback_expr.Type = asynccallback_type;
1188 system_iasyncresult_expr.Type = iasyncresult_type;
1189 system_valuetype_expr.Type = value_type;
1192 // These are only used for compare purposes
1194 anonymous_method_type = typeof (AnonymousMethod);
1195 null_type = typeof (NullType);
1199 // The helper methods that are used by the compiler
1201 public static void InitCodeHelpers ()
1204 // Now load the default methods that we use.
1206 Type [] string_string = { string_type, string_type };
1207 string_concat_string_string = GetMethod (
1208 string_type, "Concat", string_string);
1209 Type [] string_string_string = { string_type, string_type, string_type };
1210 string_concat_string_string_string = GetMethod (
1211 string_type, "Concat", string_string_string);
1212 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1213 string_concat_string_string_string_string = GetMethod (
1214 string_type, "Concat", string_string_string_string);
1215 Type[] params_string = { GetConstructedType (string_type, "[]") };
1216 string_concat_string_dot_dot_dot = GetMethod (
1217 string_type, "Concat", params_string);
1219 Type [] object_object = { object_type, object_type };
1220 string_concat_object_object = GetMethod (
1221 string_type, "Concat", object_object);
1222 Type [] object_object_object = { object_type, object_type, object_type };
1223 string_concat_object_object_object = GetMethod (
1224 string_type, "Concat", object_object_object);
1225 Type[] params_object = { GetConstructedType (object_type, "[]") };
1226 string_concat_object_dot_dot_dot = GetMethod (
1227 string_type, "Concat", params_object);
1229 Type [] string_ = { string_type };
1230 string_isinterneted_string = GetMethod (
1231 string_type, "IsInterned", string_);
1233 Type [] runtime_type_handle = { runtime_handle_type };
1234 system_type_get_type_from_handle = GetMethod (
1235 type_type, "GetTypeFromHandle", runtime_type_handle);
1237 Type [] delegate_delegate = { delegate_type, delegate_type };
1238 delegate_combine_delegate_delegate = GetMethod (
1239 delegate_type, "Combine", delegate_delegate);
1241 delegate_remove_delegate_delegate = GetMethod (
1242 delegate_type, "Remove", delegate_delegate);
1247 Type [] void_arg = { };
1248 object_getcurrent_void = GetMethod (
1249 ienumerator_type, "get_Current", void_arg);
1250 bool_movenext_void = GetMethod (
1251 ienumerator_type, "MoveNext", void_arg);
1252 void_reset_void = GetMethod (
1253 ienumerator_type, "Reset", void_arg);
1254 void_dispose_void = GetMethod (
1255 idisposable_type, "Dispose", void_arg);
1256 int_get_offset_to_string_data = GetMethod (
1257 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1258 int_array_get_length = GetMethod (
1259 array_type, "get_Length", void_arg);
1260 int_array_get_rank = GetMethod (
1261 array_type, "get_Rank", void_arg);
1262 ienumerable_getenumerator_void = GetMethod (
1263 ienumerable_type, "GetEnumerator", void_arg);
1268 Type [] int_arg = { int32_type };
1269 int_array_get_length_int = GetMethod (
1270 array_type, "GetLength", int_arg);
1271 int_array_get_upper_bound_int = GetMethod (
1272 array_type, "GetUpperBound", int_arg);
1273 int_array_get_lower_bound_int = GetMethod (
1274 array_type, "GetLowerBound", int_arg);
1277 // System.Array methods
1279 object_array_clone = GetMethod (
1280 array_type, "Clone", void_arg);
1281 Type [] array_int_arg = { array_type, int32_type };
1282 void_array_copyto_array_int = GetMethod (
1283 array_type, "CopyTo", array_int_arg);
1288 Type [] object_arg = { object_type };
1289 void_monitor_enter_object = GetMethod (
1290 monitor_type, "Enter", object_arg);
1291 void_monitor_exit_object = GetMethod (
1292 monitor_type, "Exit", object_arg);
1294 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1296 void_initializearray_array_fieldhandle = GetMethod (
1297 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1302 int_getlength_int = GetMethod (
1303 array_type, "GetLength", int_arg);
1306 // Decimal constructors
1308 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1309 void_decimal_ctor_five_args = GetConstructor (
1310 decimal_type, dec_arg);
1312 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1317 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1318 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1319 default_member_ctor = GetConstructor (default_member_type, string_);
1321 Type[] short_arg = { short_type };
1322 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1324 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1325 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1327 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1334 compiler_generated_attr = new CustomAttributeBuilder (
1335 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1337 Type[] type_int_arg = { type_type, int32_type };
1338 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1342 object_ctor = GetConstructor (object_type, void_arg);
1346 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1349 /// This is the "old", non-cache based FindMembers() function. We cannot use
1350 /// the cache here because there is no member name argument.
1352 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1353 MemberFilter filter, object criteria)
1355 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1358 // `builder_to_declspace' contains all dynamic types.
1362 Timer.StartTimer (TimerType.FindMembers);
1363 list = decl.FindMembers (mt, bf, filter, criteria);
1364 Timer.StopTimer (TimerType.FindMembers);
1369 // We have to take care of arrays specially, because GetType on
1370 // a TypeBuilder array will return a Type, not a TypeBuilder,
1371 // and we can not call FindMembers on this type.
1373 if (t.IsSubclassOf (TypeManager.array_type))
1374 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1377 // Since FindMembers will not lookup both static and instance
1378 // members, we emulate this behaviour here.
1380 if ((bf & instance_and_static) == instance_and_static){
1381 MemberInfo [] i_members = t.FindMembers (
1382 mt, bf & ~BindingFlags.Static, filter, criteria);
1384 int i_len = i_members.Length;
1386 MemberInfo one = i_members [0];
1389 // If any of these are present, we are done!
1391 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1392 return new MemberList (i_members);
1395 MemberInfo [] s_members = t.FindMembers (
1396 mt, bf & ~BindingFlags.Instance, filter, criteria);
1398 int s_len = s_members.Length;
1399 if (i_len > 0 || s_len > 0)
1400 return new MemberList (i_members, s_members);
1403 return new MemberList (i_members);
1405 return new MemberList (s_members);
1409 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1414 /// This method is only called from within MemberLookup. It tries to use the member
1415 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1416 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1417 /// our return value will already contain all inherited members and the caller don't need
1418 /// to check base classes and interfaces anymore.
1420 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1421 string name, out bool used_cache)
1426 // We have to take care of arrays specially, because GetType on
1427 // a TypeBuilder array will return a Type, not a TypeBuilder,
1428 // and we can not call FindMembers on this type.
1430 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1432 return TypeHandle.ArrayType.MemberCache.FindMembers (
1433 mt, bf, name, FilterWithClosure_delegate, null);
1437 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1438 // and we can ask the DeclSpace for the MemberCache.
1440 if (t is TypeBuilder) {
1441 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1442 cache = decl.MemberCache;
1445 // If this DeclSpace has a MemberCache, use it.
1448 if (cache != null) {
1450 return cache.FindMembers (
1451 mt, bf, name, FilterWithClosure_delegate, null);
1454 // If there is no MemberCache, we need to use the "normal" FindMembers.
1455 // Note, this is a VERY uncommon route!
1458 Timer.StartTimer (TimerType.FindMembers);
1459 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1460 FilterWithClosure_delegate, name);
1461 Timer.StopTimer (TimerType.FindMembers);
1464 return (MemberInfo []) list;
1468 // This call will always succeed. There is exactly one TypeHandle instance per
1469 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1470 // the corresponding MemberCache.
1472 cache = TypeHandle.GetMemberCache (t);
1475 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1478 public static bool IsBuiltinType (Type t)
1480 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1481 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1482 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1483 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1489 public static bool IsBuiltinType (TypeContainer tc)
1491 return IsBuiltinType (tc.TypeBuilder);
1495 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1496 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1498 public static bool IsPrimitiveType (Type t)
1500 return (t == int32_type || t == uint32_type ||
1501 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1502 t == char_type || t == short_type || t == bool_type ||
1503 t == sbyte_type || t == byte_type || t == ushort_type);
1506 public static bool IsDelegateType (Type t)
1508 if (t.IsSubclassOf (TypeManager.delegate_type))
1514 public static bool IsEnumType (Type t)
1516 if (t.IsSubclassOf (TypeManager.enum_type))
1521 public static bool IsBuiltinOrEnum (Type t)
1523 if (IsBuiltinType (t))
1533 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1535 public static bool IsUnmanagedType (Type t)
1537 // builtins that are not unmanaged types
1538 if (t == TypeManager.object_type || t == TypeManager.string_type)
1541 if (IsBuiltinOrEnum (t))
1544 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1548 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1552 if (!IsValueType (t))
1555 if (t is TypeBuilder){
1556 TypeContainer tc = LookupTypeContainer (t);
1557 if (tc.Fields == null)
1559 foreach (Field f in tc.Fields){
1560 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1561 if ((f.ModFlags & Modifiers.STATIC) != 0)
1563 if (f.MemberType == null)
1565 if (!IsUnmanagedType (f.MemberType)){
1566 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1573 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1575 foreach (FieldInfo f in fields){
1576 if (!IsUnmanagedType (f.FieldType)){
1577 Report.SymbolRelatedToPreviousError (f);
1585 public static bool IsValueType (Type t)
1587 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1593 public static bool IsInterfaceType (Type t)
1595 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1599 return tc.Kind == Kind.Interface;
1602 public static bool IsSubclassOf (Type type, Type base_type)
1605 if (type.Equals (base_type))
1608 type = type.BaseType;
1609 } while (type != null);
1614 public static bool IsFamilyAccessible (Type type, Type base_type)
1616 return IsSubclassOf (type, base_type);
1620 // Checks whether `type' is a subclass or nested child of `base_type'.
1622 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1625 if ((type == base_type) || type.IsSubclassOf (base_type))
1628 // Handle nested types.
1629 type = type.DeclaringType;
1630 } while (type != null);
1636 // Checks whether `type' is a nested child of `parent'.
1638 public static bool IsNestedChildOf (Type type, Type parent)
1643 type = type.DeclaringType;
1644 while (type != null) {
1648 type = type.DeclaringType;
1655 // Do the right thing when returning the element type of an
1656 // array type based on whether we are compiling corlib or not
1658 public static Type GetElementType (Type t)
1660 if (RootContext.StdLib)
1661 return t.GetElementType ();
1663 return TypeToCoreType (t.GetElementType ());
1667 /// This method is not implemented by MS runtime for dynamic types
1669 public static bool HasElementType (Type t)
1671 return t.IsArray || t.IsPointer || t.IsByRef;
1675 /// Returns the User Defined Types
1677 public static ArrayList UserTypes {
1683 public static Hashtable TypeContainers {
1685 return typecontainers;
1689 static Hashtable builder_to_constant;
1691 public static void RegisterConstant (FieldBuilder fb, Const c)
1693 if (builder_to_constant == null)
1694 builder_to_constant = new PtrHashtable ();
1696 if (builder_to_constant.Contains (fb))
1699 builder_to_constant.Add (fb, c);
1702 public static Const LookupConstant (FieldBuilder fb)
1704 if (builder_to_constant == null)
1707 return (Const) builder_to_constant [fb];
1711 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1715 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1716 /// for anything which is dynamic, and we need this in a number of places,
1717 /// we register this information here, and use it afterwards.
1719 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1724 method_arguments.Add (mb, args);
1725 method_params.Add (mb, ip);
1728 static public ParameterData GetParameterData (MethodBase mb)
1730 object pd = method_params [mb];
1732 if (mb is MethodBuilder || mb is ConstructorBuilder)
1733 throw new InternalErrorException ("Argument for Method not registered" + mb);
1735 method_params [mb] = pd = new ReflectionParameters (mb);
1738 return (ParameterData) pd;
1741 static public void RegisterNonOverride (MethodBase m)
1743 method_non_override [m] = m;
1746 static public bool IsOverride (MethodBase m)
1748 return m.IsVirtual &&
1749 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1750 !method_non_override.Contains (m);
1754 /// Returns the argument types for a method based on its methodbase
1756 /// For dynamic methods, we use the compiler provided types, for
1757 /// methods from existing assemblies we load them from GetParameters,
1758 /// and insert them into the cache
1760 static public Type [] GetArgumentTypes (MethodBase mb)
1762 object t = method_arguments [mb];
1766 ParameterInfo [] pi = mb.GetParameters ();
1773 types = new Type [c];
1774 for (int i = 0; i < c; i++)
1775 types [i] = pi [i].ParameterType;
1777 method_arguments.Add (mb, types);
1782 /// Returns the argument types for an indexer based on its PropertyInfo
1784 /// For dynamic indexers, we use the compiler provided types, for
1785 /// indexers from existing assemblies we load them from GetParameters,
1786 /// and insert them into the cache
1788 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1790 if (indexer_arguments.Contains (indexer))
1791 return (Type []) indexer_arguments [indexer];
1792 else if (indexer is PropertyBuilder)
1793 // If we're a PropertyBuilder and not in the
1794 // `indexer_arguments' hash, then we're a property and
1798 ParameterInfo [] pi = indexer.GetIndexParameters ();
1799 // Property, not an indexer.
1803 Type [] types = new Type [c];
1805 for (int i = 0; i < c; i++)
1806 types [i] = pi [i].ParameterType;
1808 indexer_arguments.Add (indexer, types);
1814 // This is a workaround the fact that GetValue is not
1815 // supported for dynamic types
1817 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1819 if (fields.Contains (fb))
1822 fields.Add (fb, value);
1827 static public object GetValue (FieldBuilder fb)
1832 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1834 if (fieldbuilders_to_fields.Contains (fb))
1837 fieldbuilders_to_fields.Add (fb, f);
1842 // The return value can be null; This will be the case for
1843 // auxiliary FieldBuilders created by the compiler that have no
1844 // real field being declared on the source code
1846 static public FieldBase GetField (FieldInfo fb)
1848 return (FieldBase) fieldbuilders_to_fields [fb];
1851 static Hashtable events;
1853 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1856 events = new Hashtable ();
1858 if (!events.Contains (eb)) {
1859 events.Add (eb, new Pair (add, remove));
1863 static public MethodInfo GetAddMethod (EventInfo ei)
1865 if (ei is MyEventBuilder) {
1866 Pair pair = (Pair) events [ei];
1868 return (MethodInfo) pair.First;
1870 return ei.GetAddMethod (true);
1873 static public MethodInfo GetRemoveMethod (EventInfo ei)
1875 if (ei is MyEventBuilder) {
1876 Pair pair = (Pair) events [ei];
1878 return (MethodInfo) pair.Second;
1880 return ei.GetRemoveMethod (true);
1883 static Hashtable priv_fields_events;
1885 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1887 if (priv_fields_events == null)
1888 priv_fields_events = new Hashtable ();
1890 if (priv_fields_events.Contains (einfo))
1893 priv_fields_events.Add (einfo, builder);
1898 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1900 if (priv_fields_events == null)
1903 return (MemberInfo) priv_fields_events [ei];
1906 static Hashtable properties;
1908 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1910 if (properties == null)
1911 properties = new Hashtable ();
1913 if (properties.Contains (pb))
1916 properties.Add (pb, new Pair (get, set));
1921 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1922 MethodBase set, Type[] args)
1924 if (!RegisterProperty (pb, get,set))
1927 indexer_arguments.Add (pb, args);
1932 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1934 Hashtable hash = new Hashtable ();
1935 return CheckStructCycles (tc, seen, hash);
1938 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1941 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1945 // `seen' contains all types we've already visited.
1947 if (seen.Contains (tc))
1949 seen.Add (tc, null);
1951 if (tc.Fields == null)
1954 foreach (FieldMember field in tc.Fields) {
1955 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1958 Type ftype = field.FieldBuilder.FieldType;
1959 TypeContainer ftc = LookupTypeContainer (ftype);
1963 if (hash.Contains (ftc)) {
1964 Report.Error (523, tc.Location,
1965 "Struct member `{0}.{1}' of type `{2}' " +
1966 "causes a cycle in the struct layout",
1967 tc.Name, field.Name, ftc.Name);
1972 // `hash' contains all types in the current path.
1974 hash.Add (tc, null);
1976 bool ok = CheckStructCycles (ftc, seen, hash);
1983 if (!seen.Contains (ftc))
1984 seen.Add (ftc, null);
1991 /// Given an array of interface types, expand and eliminate repeated ocurrences
1992 /// of an interface.
1996 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1999 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2001 ArrayList new_ifaces = new ArrayList ();
2003 foreach (TypeExpr iface in base_interfaces){
2004 Type itype = iface.ResolveType (ec);
2008 if (!new_ifaces.Contains (itype))
2009 new_ifaces.Add (itype);
2011 Type [] implementing = itype.GetInterfaces ();
2013 foreach (Type imp in implementing){
2014 if (!new_ifaces.Contains (imp))
2015 new_ifaces.Add (imp);
2018 Type [] ret = new Type [new_ifaces.Count];
2019 new_ifaces.CopyTo (ret, 0);
2023 static PtrHashtable iface_cache = new PtrHashtable ();
2026 /// This function returns the interfaces in the type `t'. Works with
2027 /// both types and TypeBuilders.
2029 public static Type [] GetInterfaces (Type t)
2032 Type [] cached = iface_cache [t] as Type [];
2037 // The reason for catching the Array case is that Reflection.Emit
2038 // will not return a TypeBuilder for Array types of TypeBuilder types,
2039 // but will still throw an exception if we try to call GetInterfaces
2042 // Since the array interfaces are always constant, we return those for
2047 t = TypeManager.array_type;
2049 if (t is TypeBuilder){
2050 Type [] base_ifaces;
2052 if (t.BaseType == null)
2053 base_ifaces = NoTypes;
2055 base_ifaces = GetInterfaces (t.BaseType);
2056 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
2057 if (type_ifaces == null)
2058 type_ifaces = NoTypes;
2060 int base_count = base_ifaces.Length;
2061 Type [] result = new Type [base_count + type_ifaces.Length];
2062 base_ifaces.CopyTo (result, 0);
2063 type_ifaces.CopyTo (result, base_count);
2065 iface_cache [t] = result;
2068 Type[] ifaces = t.GetInterfaces ();
2069 iface_cache [t] = ifaces;
2075 // gets the interfaces that are declared explicitly on t
2077 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2079 return (Type []) builder_to_ifaces [t];
2083 /// The following is used to check if a given type implements an interface.
2084 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2086 public static bool ImplementsInterface (Type t, Type iface)
2091 // FIXME OPTIMIZATION:
2092 // as soon as we hit a non-TypeBuiler in the interface
2093 // chain, we could return, as the `Type.GetInterfaces'
2094 // will return all the interfaces implement by the type
2098 interfaces = GetInterfaces (t);
2100 if (interfaces != null){
2101 foreach (Type i in interfaces){
2108 } while (t != null);
2113 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2115 // This is a custom version of Convert.ChangeType() which works
2116 // with the TypeBuilder defined types when compiling corlib.
2117 public static object ChangeType (object value, Type conversionType, out bool error)
2119 IConvertible convert_value = value as IConvertible;
2121 if (convert_value == null){
2127 // We must use Type.Equals() here since `conversionType' is
2128 // the TypeBuilder created version of a system type and not
2129 // the system type itself. You cannot use Type.GetTypeCode()
2130 // on such a type - it'd always return TypeCode.Object.
2134 if (conversionType.Equals (typeof (Boolean)))
2135 return (object)(convert_value.ToBoolean (nf_provider));
2136 else if (conversionType.Equals (typeof (Byte)))
2137 return (object)(convert_value.ToByte (nf_provider));
2138 else if (conversionType.Equals (typeof (Char)))
2139 return (object)(convert_value.ToChar (nf_provider));
2140 else if (conversionType.Equals (typeof (DateTime)))
2141 return (object)(convert_value.ToDateTime (nf_provider));
2142 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2143 return (object)(convert_value.ToDecimal (nf_provider));
2144 else if (conversionType.Equals (typeof (Double)))
2145 return (object)(convert_value.ToDouble (nf_provider));
2146 else if (conversionType.Equals (typeof (Int16)))
2147 return (object)(convert_value.ToInt16 (nf_provider));
2148 else if (conversionType.Equals (typeof (Int32)))
2149 return (object)(convert_value.ToInt32 (nf_provider));
2150 else if (conversionType.Equals (typeof (Int64)))
2151 return (object)(convert_value.ToInt64 (nf_provider));
2152 else if (conversionType.Equals (typeof (SByte)))
2153 return (object)(convert_value.ToSByte (nf_provider));
2154 else if (conversionType.Equals (typeof (Single)))
2155 return (object)(convert_value.ToSingle (nf_provider));
2156 else if (conversionType.Equals (typeof (String)))
2157 return (object)(convert_value.ToString (nf_provider));
2158 else if (conversionType.Equals (typeof (UInt16)))
2159 return (object)(convert_value.ToUInt16 (nf_provider));
2160 else if (conversionType.Equals (typeof (UInt32)))
2161 return (object)(convert_value.ToUInt32 (nf_provider));
2162 else if (conversionType.Equals (typeof (UInt64)))
2163 return (object)(convert_value.ToUInt64 (nf_provider));
2164 else if (conversionType.Equals (typeof (Object)))
2165 return (object)(value);
2175 // This is needed, because enumerations from assemblies
2176 // do not report their underlyingtype, but they report
2179 public static Type EnumToUnderlying (Type t)
2181 if (t == TypeManager.enum_type)
2184 t = t.UnderlyingSystemType;
2185 if (!TypeManager.IsEnumType (t))
2188 if (t is TypeBuilder) {
2189 // slow path needed to compile corlib
2190 if (t == TypeManager.bool_type ||
2191 t == TypeManager.byte_type ||
2192 t == TypeManager.sbyte_type ||
2193 t == TypeManager.char_type ||
2194 t == TypeManager.short_type ||
2195 t == TypeManager.ushort_type ||
2196 t == TypeManager.int32_type ||
2197 t == TypeManager.uint32_type ||
2198 t == TypeManager.int64_type ||
2199 t == TypeManager.uint64_type)
2201 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2203 TypeCode tc = Type.GetTypeCode (t);
2206 case TypeCode.Boolean:
2207 return TypeManager.bool_type;
2209 return TypeManager.byte_type;
2210 case TypeCode.SByte:
2211 return TypeManager.sbyte_type;
2213 return TypeManager.char_type;
2214 case TypeCode.Int16:
2215 return TypeManager.short_type;
2216 case TypeCode.UInt16:
2217 return TypeManager.ushort_type;
2218 case TypeCode.Int32:
2219 return TypeManager.int32_type;
2220 case TypeCode.UInt32:
2221 return TypeManager.uint32_type;
2222 case TypeCode.Int64:
2223 return TypeManager.int64_type;
2224 case TypeCode.UInt64:
2225 return TypeManager.uint64_type;
2227 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2231 // When compiling corlib and called with one of the core types, return
2232 // the corresponding typebuilder for that type.
2234 public static Type TypeToCoreType (Type t)
2236 if (RootContext.StdLib || (t is TypeBuilder))
2239 TypeCode tc = Type.GetTypeCode (t);
2242 case TypeCode.Boolean:
2243 return TypeManager.bool_type;
2245 return TypeManager.byte_type;
2246 case TypeCode.SByte:
2247 return TypeManager.sbyte_type;
2249 return TypeManager.char_type;
2250 case TypeCode.Int16:
2251 return TypeManager.short_type;
2252 case TypeCode.UInt16:
2253 return TypeManager.ushort_type;
2254 case TypeCode.Int32:
2255 return TypeManager.int32_type;
2256 case TypeCode.UInt32:
2257 return TypeManager.uint32_type;
2258 case TypeCode.Int64:
2259 return TypeManager.int64_type;
2260 case TypeCode.UInt64:
2261 return TypeManager.uint64_type;
2262 case TypeCode.Single:
2263 return TypeManager.float_type;
2264 case TypeCode.Double:
2265 return TypeManager.double_type;
2266 case TypeCode.String:
2267 return TypeManager.string_type;
2268 case TypeCode.Decimal:
2269 return TypeManager.decimal_type;
2271 if (t == typeof (void))
2272 return TypeManager.void_type;
2273 if (t == typeof (object))
2274 return TypeManager.object_type;
2275 if (t == typeof (System.Type))
2276 return TypeManager.type_type;
2277 if (t == typeof (System.IntPtr))
2278 return TypeManager.intptr_type;
2284 /// Utility function that can be used to probe whether a type
2285 /// is managed or not.
2287 public static bool VerifyUnManaged (Type t, Location loc)
2289 if (IsUnmanagedType (t))
2294 "Cannot take the address or size of a variable of a managed type ('" +
2295 CSharpName (t) + "')");
2300 /// Returns the name of the indexer in a given type.
2303 /// The default is not always `Item'. The user can change this behaviour by
2304 /// using the IndexerNameAttribute in the container.
2305 /// For example, the String class indexer is named `Chars' not `Item'
2307 public static string IndexerPropertyName (Type t)
2309 if (t is TypeBuilder) {
2310 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2311 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2314 System.Attribute attr = System.Attribute.GetCustomAttribute (
2315 t, TypeManager.default_member_type);
2317 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2318 return dma.MemberName;
2321 return TypeContainer.DefaultIndexerName;
2324 static MethodInfo declare_local_method = null;
2326 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2328 if (declare_local_method == null){
2329 declare_local_method = typeof (ILGenerator).GetMethod (
2331 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2333 new Type [] { typeof (Type), typeof (bool)},
2335 if (declare_local_method == null){
2336 Report.Warning (-30, new Location (-1),
2337 "This version of the runtime does not support making pinned local variables. " +
2338 "This code may cause errors on a runtime with a moving GC");
2339 return ig.DeclareLocal (t);
2342 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2346 // Returns whether the array of memberinfos contains the given method
2348 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2350 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2352 foreach (MethodBase method in array) {
2353 if (method.Name != new_method.Name)
2356 if (method is MethodInfo && new_method is MethodInfo)
2357 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2361 Type [] old_args = TypeManager.GetArgumentTypes (method);
2362 int old_count = old_args.Length;
2365 if (new_args.Length != old_count)
2368 for (i = 0; i < old_count; i++){
2369 if (old_args [i] != new_args [i])
2382 // We copy methods from `new_members' into `target_list' if the signature
2383 // for the method from in the new list does not exist in the target_list
2385 // The name is assumed to be the same.
2387 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2389 if (target_list == null){
2390 target_list = new ArrayList ();
2392 foreach (MemberInfo mi in new_members){
2393 if (mi is MethodBase)
2394 target_list.Add (mi);
2399 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2400 target_list.CopyTo (target_array, 0);
2402 foreach (MemberInfo mi in new_members){
2403 MethodBase new_method = (MethodBase) mi;
2405 if (!ArrayContainsMethod (target_array, new_method))
2406 target_list.Add (new_method);
2412 #region MemberLookup implementation
2415 // Whether we allow private members in the result (since FindMembers
2416 // uses NonPublic for both protected and private), we need to distinguish.
2419 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2424 internal class Closure {
2425 internal bool private_ok;
2427 // Who is invoking us and which type is being queried currently.
2428 internal Type invocation_type;
2429 internal Type qualifier_type;
2431 // The assembly that defines the type is that is calling us
2432 internal Assembly invocation_assembly;
2433 internal IList almost_match;
2435 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2437 if (invocation_type == null)
2440 Debug.Assert (IsNestedFamilyAccessible (invocation_type, m.DeclaringType));
2445 // A nested class has access to all the protected members visible to its parent.
2446 if (qualifier_type != null
2447 && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2450 if (invocation_type == m.DeclaringType
2451 || invocation_type.IsSubclassOf (m.DeclaringType)) {
2452 // Although a derived class can access protected members of its base class
2453 // it cannot do so through an instance of the base class (CS1540).
2454 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2455 if (qualifier_type == null
2456 || qualifier_type == invocation_type
2457 || qualifier_type.IsSubclassOf (invocation_type))
2461 if (almost_match != null)
2462 almost_match.Add (m);
2467 // This filter filters by name + whether it is ok to include private
2468 // members in the search
2470 internal bool Filter (MemberInfo m, object filter_criteria)
2473 // Hack: we know that the filter criteria will always be in the `closure'
2477 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2480 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2481 (m.DeclaringType == invocation_type))
2485 // Ugly: we need to find out the type of `m', and depending
2486 // on this, tell whether we accept or not
2488 if (m is MethodBase){
2489 MethodBase mb = (MethodBase) m;
2490 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2492 if (ma == MethodAttributes.Private)
2493 return private_ok || (invocation_type == m.DeclaringType) ||
2494 IsNestedChildOf (invocation_type, m.DeclaringType);
2496 // Assembly succeeds if we're in the same assembly.
2497 if (ma == MethodAttributes.Assembly)
2498 return (invocation_assembly == mb.DeclaringType.Assembly);
2500 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2501 if (ma == MethodAttributes.FamANDAssem){
2502 if (invocation_assembly != mb.DeclaringType.Assembly)
2506 // Family and FamANDAssem require that we derive.
2507 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem))
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 // Assembly succeeds if we're in the same assembly.
2523 if (fa == FieldAttributes.Assembly)
2524 return (invocation_assembly == fi.DeclaringType.Assembly);
2526 // FamAndAssem requires that we not only derive, but we are on the same assembly.
2527 if (fa == FieldAttributes.FamANDAssem){
2528 if (invocation_assembly != fi.DeclaringType.Assembly)
2532 // Family and FamANDAssem require that we derive.
2533 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem))
2534 return CheckValidFamilyAccess (fi.IsStatic, m);
2541 // EventInfos and PropertyInfos, return true because they lack permission
2542 // information, so we need to check later on the methods.
2548 static Closure closure = new Closure ();
2549 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2552 // Looks up a member called `name' in the `queried_type'. This lookup
2553 // is done by code that is contained in the definition for `invocation_type'
2554 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2556 // `invocation_type' is used to check whether we're allowed to access the requested
2557 // member wrt its protection level.
2559 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2560 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2561 // is B and qualifier_type is A). This is used to do the CS1540 check.
2563 // When resolving a SimpleName, `qualifier_type' is null.
2565 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2566 // the same than `queried_type' - except when we're being called from BaseAccess;
2567 // in this case, `invocation_type' is the current type and `queried_type' the base
2568 // type, so this'd normally trigger a CS1540.
2570 // The binding flags are `bf' and the kind of members being looked up are `mt'
2572 // The return value always includes private members which code in `invocation_type'
2573 // is allowed to access (using the specified `qualifier_type' if given); only use
2574 // BindingFlags.NonPublic to bypass the permission check.
2576 // The 'almost_match' argument is used for reporting error CS1540.
2578 // Returns an array of a single element for everything but Methods/Constructors
2579 // that might return multiple matches.
2581 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2582 Type queried_type, MemberTypes mt,
2583 BindingFlags original_bf, string name, IList almost_match)
2585 Timer.StartTimer (TimerType.MemberLookup);
2587 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2588 queried_type, mt, original_bf, name, almost_match);
2590 Timer.StopTimer (TimerType.MemberLookup);
2595 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2596 Type queried_type, MemberTypes mt,
2597 BindingFlags original_bf, string name, IList almost_match)
2599 BindingFlags bf = original_bf;
2601 ArrayList method_list = null;
2602 Type current_type = queried_type;
2603 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2604 bool skip_iface_check = true, used_cache = false;
2605 bool always_ok_flag = false;
2607 closure.invocation_type = invocation_type;
2608 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2609 closure.qualifier_type = qualifier_type;
2610 closure.almost_match = almost_match;
2613 // If we are a nested class, we always have access to our container
2616 if (invocation_type != null){
2617 string invocation_name = invocation_type.FullName;
2618 if (invocation_name.IndexOf ('+') != -1){
2619 string container = queried_type.FullName + "+";
2620 int container_length = container.Length;
2622 if (invocation_name.Length > container_length){
2623 string shared = invocation_name.Substring (0, container_length);
2625 if (shared == container)
2626 always_ok_flag = true;
2631 // This is from the first time we find a method
2632 // in most cases, we do not actually find a method in the base class
2633 // so we can just ignore it, and save the arraylist allocation
2634 MemberInfo [] first_members_list = null;
2635 bool use_first_members_list = false;
2641 // `NonPublic' is lame, because it includes both protected and
2642 // private methods, so we need to control this behavior by
2643 // explicitly tracking if a private method is ok or not.
2645 // The possible cases are:
2646 // public, private and protected (internal does not come into the
2649 if ((invocation_type != null) &&
2650 ((invocation_type == current_type) ||
2651 IsNestedChildOf (invocation_type, current_type)) ||
2653 bf = original_bf | BindingFlags.NonPublic;
2657 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2659 Timer.StopTimer (TimerType.MemberLookup);
2661 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2663 Timer.StartTimer (TimerType.MemberLookup);
2666 // When queried for an interface type, the cache will automatically check all
2667 // inherited members, so we don't need to do this here. However, this only
2668 // works if we already used the cache in the first iteration of this loop.
2670 // If we used the cache in any further iteration, we can still terminate the
2671 // loop since the cache always looks in all base classes.
2677 skip_iface_check = false;
2679 if (current_type == TypeManager.object_type)
2682 current_type = current_type.BaseType;
2685 // This happens with interfaces, they have a null
2686 // basetype. Look members up in the Object class.
2688 if (current_type == null) {
2689 current_type = TypeManager.object_type;
2694 if (list.Length == 0)
2698 // Events and types are returned by both `static' and `instance'
2699 // searches, which means that our above FindMembers will
2700 // return two copies of the same.
2702 if (list.Length == 1 && !(list [0] is MethodBase)){
2707 // Multiple properties: we query those just to find out the indexer
2710 if (list [0] is PropertyInfo)
2714 // We found an event: the cache lookup returns both the event and
2715 // its private field.
2717 if (list [0] is EventInfo) {
2718 if ((list.Length == 2) && (list [1] is FieldInfo))
2719 return new MemberInfo [] { list [0] };
2726 // We found methods, turn the search into "method scan"
2730 if (first_members_list != null) {
2731 if (use_first_members_list) {
2732 method_list = CopyNewMethods (method_list, first_members_list);
2733 use_first_members_list = false;
2736 method_list = CopyNewMethods (method_list, list);
2738 first_members_list = list;
2739 use_first_members_list = true;
2740 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2742 } while (searching);
2744 if (use_first_members_list) {
2745 foreach (MemberInfo mi in first_members_list) {
2746 if (! (mi is MethodBase)) {
2747 method_list = CopyNewMethods (method_list, first_members_list);
2748 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2751 return (MemberInfo []) first_members_list;
2754 if (method_list != null && method_list.Count > 0)
2755 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2758 // This happens if we already used the cache in the first iteration, in this case
2759 // the cache already looked in all interfaces.
2761 if (skip_iface_check)
2765 // Interfaces do not list members they inherit, so we have to
2768 if (!queried_type.IsInterface)
2771 if (queried_type.IsArray)
2772 queried_type = TypeManager.array_type;
2774 Type [] ifaces = GetInterfaces (queried_type);
2778 foreach (Type itype in ifaces){
2781 x = MemberLookup (null, null, itype, mt, bf, name, null);
2789 // Tests whether external method is really special
2790 public static bool IsSpecialMethod (MethodBase mb)
2792 string name = mb.Name;
2793 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2794 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2796 if (name.StartsWith ("add_"))
2797 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2799 if (name.StartsWith ("remove_"))
2800 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2802 if (name.StartsWith ("op_")){
2803 foreach (string oname in Unary.oper_names) {
2808 foreach (string oname in Binary.oper_names) {
2821 /// There is exactly one instance of this class per type.
2823 public sealed class TypeHandle : IMemberContainer {
2824 public readonly IMemberContainer BaseType;
2826 readonly int id = ++next_id;
2827 static int next_id = 0;
2829 static TypeHandle ()
2835 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2836 /// a TypeHandle yet, a new instance of it is created. This static method
2837 /// ensures that we'll only have one TypeHandle instance per type.
2839 private static TypeHandle GetTypeHandle (Type t)
2841 TypeHandle handle = (TypeHandle) type_hash [t];
2845 handle = new TypeHandle (t);
2846 type_hash.Add (t, handle);
2850 public static MemberCache GetMemberCache (Type t)
2852 return GetTypeHandle (t).MemberCache;
2855 public static void CleanUp ()
2860 public static void Reset ()
2862 type_hash = new PtrHashtable ();
2866 /// Returns the TypeHandle for TypeManager.object_type.
2868 public static IMemberContainer ObjectType {
2870 if (object_type != null)
2873 object_type = GetTypeHandle (TypeManager.object_type);
2880 /// Returns the TypeHandle for TypeManager.array_type.
2882 public static IMemberContainer ArrayType {
2884 if (array_type != null)
2887 array_type = GetTypeHandle (TypeManager.array_type);
2893 private static PtrHashtable type_hash;
2895 private static TypeHandle object_type = null;
2896 private static TypeHandle array_type = null;
2899 private bool is_interface;
2900 private MemberCache member_cache;
2901 private MemberCache base_cache;
2903 private TypeHandle (Type type)
2906 if (type.BaseType != null) {
2907 base_cache = TypeManager.LookupMemberCache (type.BaseType);
2908 BaseType = base_cache.Container;
2909 } else if (type.IsInterface)
2910 base_cache = TypeManager.LookupBaseInterfacesCache (type);
2911 this.is_interface = type.IsInterface;
2912 this.member_cache = new MemberCache (this);
2915 // IMemberContainer methods
2917 public string Name {
2919 return type.FullName;
2929 public MemberCache BaseCache {
2935 public bool IsInterface {
2937 return is_interface;
2941 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2943 MemberInfo [] members;
2944 if (mt == MemberTypes.Event)
2945 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2947 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2949 Array.Reverse (members);
2951 return new MemberList (members);
2954 // IMemberFinder methods
2956 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2957 MemberFilter filter, object criteria)
2959 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2962 public MemberCache MemberCache {
2964 return member_cache;
2968 public override string ToString ()
2970 if (BaseType != null)
2971 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2973 return "TypeHandle (" + id + "," + Name + ")";