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 partial class TypeManager {
35 // A list of core types that the compiler requires or uses
37 static public Type object_type;
38 static public Type value_type;
39 static public Type string_type;
40 static public Type int32_type;
41 static public Type uint32_type;
42 static public Type int64_type;
43 static public Type uint64_type;
44 static public Type float_type;
45 static public Type double_type;
46 static public Type char_type;
47 static public Type char_ptr_type;
48 static public Type short_type;
49 static public Type decimal_type;
50 static public Type bool_type;
51 static public Type sbyte_type;
52 static public Type byte_type;
53 static public Type ushort_type;
54 static public Type enum_type;
55 static public Type delegate_type;
56 static public Type multicast_delegate_type;
57 static public Type void_type;
58 static public Type null_type;
59 static public Type enumeration_type;
60 static public Type array_type;
61 static public Type runtime_handle_type;
62 static public Type icloneable_type;
63 static public Type type_type;
64 static public Type ienumerator_type;
65 static public Type ienumerable_type;
66 static public Type idisposable_type;
67 static public Type iconvertible_type;
68 static public Type default_member_type;
69 static public Type iasyncresult_type;
70 static public Type asynccallback_type;
71 static public Type intptr_type;
72 static public Type monitor_type;
73 static public Type runtime_field_handle_type;
74 static public Type runtime_argument_handle_type;
75 static public Type attribute_type;
76 static public Type attribute_usage_type;
77 static public Type decimal_constant_attribute_type;
78 static public Type dllimport_type;
79 static public Type unverifiable_code_type;
80 static public Type methodimpl_attr_type;
81 static public Type marshal_as_attr_type;
82 static public Type param_array_type;
83 static public Type void_ptr_type;
84 static public Type indexer_name_type;
85 static public Type exception_type;
86 static public Type invalid_operation_exception_type;
87 static public Type not_supported_exception_type;
88 static public Type obsolete_attribute_type;
89 static public Type conditional_attribute_type;
90 static public Type in_attribute_type;
91 static public Type out_attribute_type;
92 static public Type anonymous_method_type;
93 static public Type cls_compliant_attribute_type;
94 static public Type typed_reference_type;
95 static public Type arg_iterator_type;
96 static public Type mbr_type;
97 static public Type struct_layout_attribute_type;
98 static public Type field_offset_attribute_type;
99 static public Type security_attr_type;
100 static public Type required_attr_type;
101 static public Type guid_attr_type;
106 static internal Type compiler_generated_attr_type;
107 static internal Type fixed_buffer_attr_type;
108 static internal Type default_charset_type;
111 // An empty array of types
113 static public Type [] NoTypes;
114 static public TypeExpr [] NoTypeExprs;
118 // Expressions representing the internal types. Used during declaration
121 static public TypeExpr system_object_expr, system_string_expr;
122 static public TypeExpr system_boolean_expr, system_decimal_expr;
123 static public TypeExpr system_single_expr, system_double_expr;
124 static public TypeExpr system_sbyte_expr, system_byte_expr;
125 static public TypeExpr system_int16_expr, system_uint16_expr;
126 static public TypeExpr system_int32_expr, system_uint32_expr;
127 static public TypeExpr system_int64_expr, system_uint64_expr;
128 static public TypeExpr system_char_expr, system_void_expr;
129 static public TypeExpr system_asynccallback_expr;
130 static public TypeExpr system_iasyncresult_expr;
131 static public TypeExpr system_valuetype_expr;
132 static public TypeExpr system_intptr_expr;
135 // This is only used when compiling corlib
137 static public Type system_int32_type;
138 static public Type system_array_type;
139 static public Type system_type_type;
140 static public Type system_assemblybuilder_type;
141 static public MethodInfo system_int_array_get_length;
142 static public MethodInfo system_int_array_get_rank;
143 static public MethodInfo system_object_array_clone;
144 static public MethodInfo system_int_array_get_length_int;
145 static public MethodInfo system_int_array_get_lower_bound_int;
146 static public MethodInfo system_int_array_get_upper_bound_int;
147 static public MethodInfo system_void_array_copyto_array_int;
151 // Internal, not really used outside
153 static Type runtime_helpers_type;
156 // These methods are called by code generated by the compiler
158 static public MethodInfo string_concat_string_string;
159 static public MethodInfo string_concat_string_string_string;
160 static public MethodInfo string_concat_string_string_string_string;
161 static public MethodInfo string_concat_string_dot_dot_dot;
162 static public MethodInfo string_concat_object_object;
163 static public MethodInfo string_concat_object_object_object;
164 static public MethodInfo string_concat_object_dot_dot_dot;
165 static public MethodInfo string_isinterneted_string;
166 static public MethodInfo system_type_get_type_from_handle;
167 static public MethodInfo bool_movenext_void;
168 static public MethodInfo ienumerable_getenumerator_void;
169 static public MethodInfo void_reset_void;
170 static public MethodInfo void_dispose_void;
171 static public MethodInfo void_monitor_enter_object;
172 static public MethodInfo void_monitor_exit_object;
173 static public MethodInfo void_initializearray_array_fieldhandle;
174 static public MethodInfo int_getlength_int;
175 static public MethodInfo delegate_combine_delegate_delegate;
176 static public MethodInfo delegate_remove_delegate_delegate;
177 static public MethodInfo int_get_offset_to_string_data;
178 static public MethodInfo int_array_get_length;
179 static public MethodInfo int_array_get_rank;
180 static public MethodInfo object_array_clone;
181 static public MethodInfo int_array_get_length_int;
182 static public MethodInfo int_array_get_lower_bound_int;
183 static public MethodInfo int_array_get_upper_bound_int;
184 static public MethodInfo void_array_copyto_array_int;
185 static public PropertyInfo ienumerator_getcurrent;
188 // The attribute constructors.
190 static public ConstructorInfo object_ctor;
191 static public ConstructorInfo cons_param_array_attribute;
192 static public ConstructorInfo void_decimal_ctor_five_args;
193 static public ConstructorInfo void_decimal_ctor_int_arg;
194 static public ConstructorInfo unverifiable_code_ctor;
195 static public ConstructorInfo default_member_ctor;
196 static public ConstructorInfo decimal_constant_attribute_ctor;
197 static internal ConstructorInfo struct_layout_attribute_ctor;
198 static public ConstructorInfo field_offset_attribute_ctor;
203 static internal CustomAttributeBuilder compiler_generated_attr;
204 static internal ConstructorInfo fixed_buffer_attr_ctor;
207 // Holds the Array of Assemblies that have been loaded
208 // (either because it is the default or the user used the
209 // -r command line option)
211 static Assembly [] assemblies;
214 // Keeps a list of modules. We used this to do lookups
215 // on the module using GetType -- needed for arrays
217 static Module [] modules;
220 // This is the type_cache from the assemblies to avoid
221 // hitting System.Reflection on every lookup.
223 static Hashtable types;
226 // This is used to hotld the corresponding TypeContainer objects
227 // since we need this in FindMembers
229 static Hashtable typecontainers;
232 // Keeps track of those types that are defined by the
235 static ArrayList user_types;
237 static PtrHashtable builder_to_declspace;
239 static PtrHashtable builder_to_member_cache;
242 // Tracks the interfaces implemented by typebuilders. We only
243 // enter those who do implement or or more interfaces
245 static PtrHashtable builder_to_ifaces;
248 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
249 // the arguments to the method
251 static Hashtable method_arguments;
254 // Maps PropertyBuilder to a Type array that contains
255 // the arguments to the indexer
257 static Hashtable indexer_arguments;
260 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
262 static Hashtable method_params;
265 // A hash table from override methods to their base virtual method.
267 static Hashtable method_overrides;
270 // Keeps track of methods
273 static Hashtable builder_to_method;
276 // Contains all public types from referenced assemblies.
277 // This member is used only if CLS Compliance verification is required.
279 public static Hashtable all_imported_types;
281 static Hashtable fieldbuilders_to_fields;
282 static Hashtable fields;
289 public static void CleanUp ()
291 // Lets get everything clean so that we can collect before generating code
295 typecontainers = null;
297 builder_to_declspace = null;
298 builder_to_member_cache = null;
299 builder_to_ifaces = null;
300 method_arguments = null;
301 indexer_arguments = null;
302 method_params = null;
303 builder_to_method = null;
306 builder_to_constant = null;
307 fieldbuilders_to_fields = null;
309 priv_fields_events = null;
315 TypeHandle.CleanUp ();
319 /// A filter for Findmembers that uses the Signature object to
322 static bool SignatureFilter (MemberInfo mi, object criteria)
324 Signature sig = (Signature) criteria;
326 if (!(mi is MethodBase))
329 if (mi.Name != sig.name)
332 int count = sig.args.Length;
334 if (mi is MethodBuilder || mi is ConstructorBuilder){
335 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
337 if (candidate_args.Length != count)
340 for (int i = 0; i < count; i++)
341 if (candidate_args [i] != sig.args [i])
346 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
348 if (pars.Length != count)
351 for (int i = 0; i < count; i++)
352 if (pars [i].ParameterType != sig.args [i])
358 // A delegate that points to the filter above.
359 static MemberFilter signature_filter;
362 // These are expressions that represent some of the internal data types, used
365 static void InitExpressionTypes ()
367 system_object_expr = new TypeLookupExpression ("System.Object");
368 system_string_expr = new TypeLookupExpression ("System.String");
369 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
370 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
371 system_single_expr = new TypeLookupExpression ("System.Single");
372 system_double_expr = new TypeLookupExpression ("System.Double");
373 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
374 system_byte_expr = new TypeLookupExpression ("System.Byte");
375 system_int16_expr = new TypeLookupExpression ("System.Int16");
376 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
377 system_int32_expr = new TypeLookupExpression ("System.Int32");
378 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
379 system_int64_expr = new TypeLookupExpression ("System.Int64");
380 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
381 system_char_expr = new TypeLookupExpression ("System.Char");
382 system_void_expr = new TypeLookupExpression ("System.Void");
383 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
384 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
385 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
386 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
389 static TypeManager ()
393 signature_filter = new MemberFilter (SignatureFilter);
394 InitExpressionTypes ();
397 static public void Reset ()
399 assemblies = new Assembly [0];
401 user_types = new ArrayList ();
403 types = new Hashtable ();
404 typecontainers = new Hashtable ();
406 builder_to_declspace = new PtrHashtable ();
407 builder_to_member_cache = new PtrHashtable ();
408 builder_to_method = new PtrHashtable ();
409 method_arguments = new PtrHashtable ();
410 method_params = new PtrHashtable ();
411 method_overrides = new PtrHashtable ();
412 indexer_arguments = new PtrHashtable ();
413 builder_to_ifaces = new PtrHashtable ();
415 NoTypes = new Type [0];
416 NoTypeExprs = new TypeExpr [0];
418 fieldbuilders_to_fields = new Hashtable ();
419 fields = new Hashtable ();
420 type_hash = new DoubleHash ();
425 public static void HandleDuplicate (string name, Type t)
427 Type prev = (Type) types [name];
428 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
432 // This probably never happens, as we catch this before
434 Report.Error (-17, "The type `" + name + "' has already been defined.");
438 tc = builder_to_declspace [t] as TypeContainer;
441 1595, "The type `" + name + "' is defined in an existing assembly;"+
442 " Using the new definition from: " + tc.Location);
445 1595, "The type `" + name + "' is defined in an existing assembly;");
448 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
454 public static void AddUserType (string name, TypeBuilder t)
459 HandleDuplicate (name, t);
466 // This entry point is used by types that we define under the covers
468 public static void RegisterBuilder (Type tb, Type [] ifaces)
471 builder_to_ifaces [tb] = ifaces;
474 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
476 builder_to_declspace.Add (t, tc);
477 typecontainers.Add (name, tc);
478 AddUserType (name, t);
481 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
486 HandleDuplicate (name, t);
489 builder_to_declspace.Add (t, del);
492 public static void AddEnumType (string name, TypeBuilder t, Enum en)
497 HandleDuplicate (name, t);
499 builder_to_declspace.Add (t, en);
502 public static void AddMethod (MethodBase builder, IMethodData method)
504 builder_to_method.Add (builder, method);
507 public static IMethodData GetMethod (MethodBase builder)
509 return (IMethodData) builder_to_method [builder];
513 /// Returns the DeclSpace whose Type is `t' or null if there is no
514 /// DeclSpace for `t' (ie, the Type comes from a library)
516 public static DeclSpace LookupDeclSpace (Type t)
518 return builder_to_declspace [t] as DeclSpace;
522 /// Returns the TypeContainer whose Type is `t' or null if there is no
523 /// TypeContainer for `t' (ie, the Type comes from a library)
525 public static TypeContainer LookupTypeContainer (Type t)
527 return builder_to_declspace [t] as TypeContainer;
530 public static MemberCache LookupMemberCache (Type t)
532 if (t is TypeBuilder) {
533 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
534 if (container != null)
535 return container.MemberCache;
538 if (t is GenericTypeParameterBuilder) {
539 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
541 if (container != null)
542 return container.MemberCache;
545 return TypeHandle.GetMemberCache (t);
548 public static MemberCache LookupBaseInterfacesCache (Type t)
550 Type [] ifaces = t.GetInterfaces ();
552 if (ifaces != null && ifaces.Length == 1)
553 return LookupMemberCache (ifaces [0]);
555 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
556 MemberCache cache = builder_to_member_cache [t] as MemberCache;
560 cache = new MemberCache (ifaces);
561 builder_to_member_cache.Add (t, cache);
565 public static TypeContainer LookupInterface (Type t)
567 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
568 if ((tc == null) || (tc.Kind != Kind.Interface))
574 public static Delegate LookupDelegate (Type t)
576 return builder_to_declspace [t] as Delegate;
579 public static Enum LookupEnum (Type t)
581 return builder_to_declspace [t] as Enum;
584 public static Class LookupClass (Type t)
586 return (Class) builder_to_declspace [t];
590 /// Registers an assembly to load types from.
592 public static void AddAssembly (Assembly a)
594 foreach (Assembly assembly in assemblies) {
599 int top = assemblies.Length;
600 Assembly [] n = new Assembly [top + 1];
602 assemblies.CopyTo (n, 0);
608 public static Assembly [] GetAssemblies ()
614 /// Registers a module builder to lookup types from
616 public static void AddModule (Module mb)
618 int top = modules != null ? modules.Length : 0;
619 Module [] n = new Module [top + 1];
622 modules.CopyTo (n, 0);
627 public static Module[] Modules {
634 // We use this hash for multiple kinds of constructed types:
636 // (T, "&") Given T, get T &
637 // (T, "*") Given T, get T *
638 // (T, "[]") Given T and a array dimension, get T []
639 // (T, X) Given a type T and a simple name X, get the type T+X
641 // Accessibility tests, if necessary, should be done by the user
643 static DoubleHash type_hash = new DoubleHash ();
646 // Gets the reference to T version of the Type (T&)
648 public static Type GetReferenceType (Type t)
650 return t.MakeByRefType ();
654 // Gets the pointer to T version of the Type (T*)
656 public static Type GetPointerType (Type t)
658 return GetConstructedType (t, "*");
661 public static Type GetConstructedType (Type t, string dim)
664 if (type_hash.Lookup (t, dim, out ret))
667 ret = t.Module.GetType (t.ToString () + dim);
669 type_hash.Insert (t, dim, ret);
674 ret = GetReferenceType (t);
675 type_hash.Insert (t, dim, ret);
679 if (t.IsGenericParameter || t.IsGenericInstance) {
682 while ((pos < dim.Length) && (dim [pos] == '[')) {
685 if (dim [pos] == ']') {
686 result = result.MakeArrayType ();
689 if (pos < dim.Length)
692 type_hash.Insert (t, dim, result);
697 while (dim [pos] == ',') {
701 if ((dim [pos] != ']') || (pos != dim.Length-1))
704 result = result.MakeArrayType (rank + 1);
705 type_hash.Insert (t, dim, result);
710 type_hash.Insert (t, dim, null);
714 public static Type GetNestedType (Type t, string name)
717 if (!type_hash.Lookup (t, name, out ret)) {
718 string lookup = t.FullName + "+" + name;
719 ret = t.Module.GetType (lookup);
720 type_hash.Insert (t, name, ret);
726 // Low-level lookup, cache-less
728 public static Type LookupTypeReflection (string name)
732 foreach (Assembly a in assemblies){
733 t = a.GetType (name);
738 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
739 if (ta == TypeAttributes.NotPublic ||
740 ta == TypeAttributes.NestedPrivate ||
741 ta == TypeAttributes.NestedAssembly ||
742 ta == TypeAttributes.NestedFamANDAssem){
745 // In .NET pointers turn out to be private, even if their
746 // element type is not
749 t = t.GetElementType ();
759 foreach (Module mb in modules) {
760 t = mb.GetType (name);
769 /// Computes the namespaces that we import from the assemblies we reference.
771 public static void ComputeNamespaces ()
773 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
775 Hashtable cache = null;
778 // First add the assembly namespaces
780 if (assembly_get_namespaces != null){
781 int count = assemblies.Length;
783 for (int i = 0; i < count; i++){
784 Assembly a = assemblies [i];
785 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
786 foreach (string ns in namespaces){
789 Namespace.LookupNamespace (ns, true);
793 cache = new Hashtable ();
794 cache.Add ("", null);
795 foreach (Assembly a in assemblies) {
796 foreach (Type t in a.GetExportedTypes ()) {
797 string ns = t.Namespace;
798 if (ns == null || cache.Contains (ns))
801 Namespace.LookupNamespace (ns, true);
802 cache.Add (ns, null);
808 // Then add module namespaces
810 foreach (Module m in modules) {
811 if (m == CodeGen.Module.Builder)
814 cache = new Hashtable ();
815 cache.Add ("", null);
817 foreach (Type t in m.GetTypes ()) {
818 string ns = t.Namespace;
819 if (ns == null || cache.Contains (ns))
821 Namespace.LookupNamespace (ns, true);
822 cache.Add (ns, null);
828 /// Fills static table with exported types from all referenced assemblies.
829 /// This information is required for CLS Compliance tests.
831 public static void LoadAllImportedTypes ()
833 all_imported_types = new Hashtable ();
834 foreach (Assembly a in assemblies) {
835 foreach (Type t in a.GetExportedTypes ()) {
836 all_imported_types [t.FullName] = t;
841 public static bool NamespaceClash (string name, Location loc)
843 if (Namespace.LookupNamespace (name, false) == null)
846 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
851 /// Returns the C# name of a type if possible, or the full type name otherwise
853 static public string CSharpName (Type t)
855 string name = GetFullName (t);
857 return Regex.Replace (name,
859 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
860 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
861 @"Boolean|String|Void|Null)" +
863 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
866 static public string CSharpName (Type[] types)
868 StringBuilder sb = new StringBuilder ();
869 foreach (Type t in types) {
870 sb.Append (CSharpName (t));
873 sb.Remove (sb.Length - 1, 1);
874 return sb.ToString ();
877 static String CSharpNameMatch (Match match)
879 string s = match.Groups [1].Captures [0].Value;
881 Replace ("int32", "int").
882 Replace ("uint32", "uint").
883 Replace ("int16", "short").
884 Replace ("uint16", "ushort").
885 Replace ("int64", "long").
886 Replace ("uint64", "ulong").
887 Replace ("single", "float").
888 Replace ("boolean", "bool")
889 + match.Groups [2].Captures [0].Value;
893 /// Returns the signature of the method with full namespace classification
895 static public string GetFullNameSignature (MemberInfo mi)
897 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
898 return (mi is MethodBase)
899 ? GetFullNameSignature (mi as MethodBase)
900 : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
903 static public string GetFullNameSignature (MethodBase mb)
905 string name = mb.Name;
907 name = mb.DeclaringType.Name;
909 if (mb.IsSpecialName) {
910 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
911 name = name.Remove (0, 4);
918 return GetFullName (mb.DeclaringType) + '.' + name;
921 private static void GetFullName_recursed (StringBuilder sb, Type t, bool recursed)
923 if (t.IsGenericParameter) {
928 if (t.DeclaringType != null) {
929 GetFullName_recursed (sb, t.DeclaringType, true);
934 string ns = t.Namespace;
935 if ((ns != null) && (ns != "")) {
941 sb.Append (SimpleName.RemoveGenericArity (t.Name));
943 Type[] args = GetTypeArguments (t);
944 if (args.Length > 0) {
946 for (int i = 0; i < args.Length; i++) {
949 sb.Append (GetFullName (args [i]));
955 static public string GetFullName (Type t)
957 StringBuilder sb = new StringBuilder ();
958 GetFullName_recursed (sb, t, false);
959 return sb.ToString ();
963 /// Returns the signature of the property and indexer
965 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
968 return GetFullNameSignature (pb);
971 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
972 string signature = GetFullNameSignature (mb);
973 string arg = GetParameterData (mb).ParameterDesc (0);
974 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
978 /// Returns the signature of the method
980 static public string CSharpSignature (MethodBase mb)
982 StringBuilder sig = new StringBuilder ("(");
984 ParameterData iparams = GetParameterData (mb);
987 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
988 return GetFullNameSignature (mb);
990 for (int i = 0; i < iparams.Count; i++) {
994 sig.Append (iparams.ParameterDesc (i));
999 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
1000 sig.Replace ('(', '[');
1001 sig.Replace (')', ']');
1004 return GetFullNameSignature (mb) + sig.ToString ();
1007 public static string GetMethodName (MethodInfo m)
1009 if (!IsGenericMethod (m))
1012 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
1016 /// Looks up a type, and aborts if it is not found. This is used
1017 /// by types required by the compiler
1019 static Type CoreLookupType (string name)
1022 if (types.Contains (name))
1023 t = (Type) types [name];
1025 t = LookupTypeReflection (name);
1028 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
1035 /// Returns the MethodInfo for a method named `name' defined
1036 /// in type `t' which takes arguments of types `args'
1038 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
1042 BindingFlags flags = instance_and_static | BindingFlags.Public;
1048 flags |= BindingFlags.NonPublic;
1050 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
1051 if (list.Count == 0) {
1053 Report.Error (-19, "Can not find the core function `" + name + "'");
1057 MethodInfo mi = list [0] as MethodInfo;
1060 Report.Error (-19, "Can not find the core function `" + name + "'");
1067 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
1069 return GetMethod (t, name, args, false, report_errors);
1072 static MethodInfo GetMethod (Type t, string name, Type [] args)
1074 return GetMethod (t, name, args, true);
1078 /// Returns the PropertyInfo for a property named `name' defined
1081 static PropertyInfo GetProperty (Type t, string name)
1083 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
1084 BindingFlags.Instance, Type.FilterName, name);
1085 if (list.Count == 0) {
1086 Report.Error (-19, "Can not find the core property `" + name + "'");
1090 PropertyInfo pi = list [0] as PropertyInfo;
1092 Report.Error (-19, "Can not find the core function `" + name + "'");
1100 /// Returns the ConstructorInfo for "args"
1102 public static ConstructorInfo GetConstructor (Type t, Type [] args)
1110 list = FindMembers (t, MemberTypes.Constructor,
1111 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
1112 signature_filter, sig);
1113 if (list.Count == 0){
1114 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1118 ConstructorInfo ci = list [0] as ConstructorInfo;
1120 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1127 public static void InitEnumUnderlyingTypes ()
1130 int32_type = CoreLookupType ("System.Int32");
1131 int64_type = CoreLookupType ("System.Int64");
1132 uint32_type = CoreLookupType ("System.UInt32");
1133 uint64_type = CoreLookupType ("System.UInt64");
1134 byte_type = CoreLookupType ("System.Byte");
1135 sbyte_type = CoreLookupType ("System.SByte");
1136 short_type = CoreLookupType ("System.Int16");
1137 ushort_type = CoreLookupType ("System.UInt16");
1141 /// The types have to be initialized after the initial
1142 /// population of the type has happened (for example, to
1143 /// bootstrap the corlib.dll
1145 public static void InitCoreTypes ()
1147 object_type = CoreLookupType ("System.Object");
1148 value_type = CoreLookupType ("System.ValueType");
1150 InitEnumUnderlyingTypes ();
1152 char_type = CoreLookupType ("System.Char");
1153 string_type = CoreLookupType ("System.String");
1154 float_type = CoreLookupType ("System.Single");
1155 double_type = CoreLookupType ("System.Double");
1156 char_ptr_type = CoreLookupType ("System.Char*");
1157 decimal_type = CoreLookupType ("System.Decimal");
1158 bool_type = CoreLookupType ("System.Boolean");
1159 enum_type = CoreLookupType ("System.Enum");
1161 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1162 delegate_type = CoreLookupType ("System.Delegate");
1164 array_type = CoreLookupType ("System.Array");
1165 void_type = CoreLookupType ("System.Void");
1166 type_type = CoreLookupType ("System.Type");
1168 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1169 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1170 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1171 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1172 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1173 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1174 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1175 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1176 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1177 idisposable_type = CoreLookupType ("System.IDisposable");
1178 icloneable_type = CoreLookupType ("System.ICloneable");
1179 iconvertible_type = CoreLookupType ("System.IConvertible");
1180 monitor_type = CoreLookupType ("System.Threading.Monitor");
1181 intptr_type = CoreLookupType ("System.IntPtr");
1183 attribute_type = CoreLookupType ("System.Attribute");
1184 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1185 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1186 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1187 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1188 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1189 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1190 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1191 typed_reference_type = CoreLookupType ("System.TypedReference");
1192 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1193 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1194 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1196 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1198 void_ptr_type = CoreLookupType ("System.Void*");
1200 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1202 exception_type = CoreLookupType ("System.Exception");
1203 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1204 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1209 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1210 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1211 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1212 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1213 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1214 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1215 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1216 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices.GuidAttribute");
1218 InitGenericCoreTypes ();
1223 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1224 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1225 default_charset_type = CoreLookupType ("System.Runtime.InteropServices.DefaultCharSetAttribute");
1227 // When compiling corlib, store the "real" types here.
1229 if (!RootContext.StdLib) {
1230 system_int32_type = typeof (System.Int32);
1231 system_array_type = typeof (System.Array);
1232 system_type_type = typeof (System.Type);
1233 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1235 Type [] void_arg = { };
1236 system_int_array_get_length = GetMethod (
1237 system_array_type, "get_Length", void_arg);
1238 system_int_array_get_rank = GetMethod (
1239 system_array_type, "get_Rank", void_arg);
1240 system_object_array_clone = GetMethod (
1241 system_array_type, "Clone", void_arg);
1243 Type [] system_int_arg = { system_int32_type };
1244 system_int_array_get_length_int = GetMethod (
1245 system_array_type, "GetLength", system_int_arg);
1246 system_int_array_get_upper_bound_int = GetMethod (
1247 system_array_type, "GetUpperBound", system_int_arg);
1248 system_int_array_get_lower_bound_int = GetMethod (
1249 system_array_type, "GetLowerBound", system_int_arg);
1251 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1252 system_void_array_copyto_array_int = GetMethod (
1253 system_array_type, "CopyTo", system_array_int_arg);
1255 Type [] system_3_type_arg = {
1256 system_type_type, system_type_type, system_type_type };
1257 Type [] system_4_type_arg = {
1258 system_type_type, system_type_type, system_type_type, system_type_type };
1260 MethodInfo set_corlib_type_builders = GetMethod (
1261 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1262 system_4_type_arg, true, false);
1264 if (set_corlib_type_builders != null) {
1265 object[] args = new object [4];
1266 args [0] = object_type;
1267 args [1] = value_type;
1268 args [2] = enum_type;
1269 args [3] = void_type;
1271 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1273 // Compatibility for an older version of the class libs.
1274 set_corlib_type_builders = GetMethod (
1275 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1276 system_3_type_arg, true, true);
1278 if (set_corlib_type_builders == null) {
1279 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1283 object[] args = new object [3];
1284 args [0] = object_type;
1285 args [1] = value_type;
1286 args [2] = enum_type;
1288 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1292 system_object_expr.Type = object_type;
1293 system_string_expr.Type = string_type;
1294 system_boolean_expr.Type = bool_type;
1295 system_decimal_expr.Type = decimal_type;
1296 system_single_expr.Type = float_type;
1297 system_double_expr.Type = double_type;
1298 system_sbyte_expr.Type = sbyte_type;
1299 system_byte_expr.Type = byte_type;
1300 system_int16_expr.Type = short_type;
1301 system_uint16_expr.Type = ushort_type;
1302 system_int32_expr.Type = int32_type;
1303 system_uint32_expr.Type = uint32_type;
1304 system_int64_expr.Type = int64_type;
1305 system_uint64_expr.Type = uint64_type;
1306 system_char_expr.Type = char_type;
1307 system_void_expr.Type = void_type;
1308 system_asynccallback_expr.Type = asynccallback_type;
1309 system_iasyncresult_expr.Type = iasyncresult_type;
1310 system_valuetype_expr.Type = value_type;
1313 // These are only used for compare purposes
1315 anonymous_method_type = typeof (AnonymousMethod);
1316 null_type = typeof (NullType);
1320 // The helper methods that are used by the compiler
1322 public static void InitCodeHelpers ()
1325 // Now load the default methods that we use.
1327 Type [] string_string = { string_type, string_type };
1328 string_concat_string_string = GetMethod (
1329 string_type, "Concat", string_string);
1330 Type [] string_string_string = { string_type, string_type, string_type };
1331 string_concat_string_string_string = GetMethod (
1332 string_type, "Concat", string_string_string);
1333 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1334 string_concat_string_string_string_string = GetMethod (
1335 string_type, "Concat", string_string_string_string);
1336 Type[] params_string = { GetConstructedType (string_type, "[]") };
1337 string_concat_string_dot_dot_dot = GetMethod (
1338 string_type, "Concat", params_string);
1340 Type [] object_object = { object_type, object_type };
1341 string_concat_object_object = GetMethod (
1342 string_type, "Concat", object_object);
1343 Type [] object_object_object = { object_type, object_type, object_type };
1344 string_concat_object_object_object = GetMethod (
1345 string_type, "Concat", object_object_object);
1346 Type[] params_object = { GetConstructedType (object_type, "[]") };
1347 string_concat_object_dot_dot_dot = GetMethod (
1348 string_type, "Concat", params_object);
1350 Type [] string_ = { string_type };
1351 string_isinterneted_string = GetMethod (
1352 string_type, "IsInterned", string_);
1354 Type [] runtime_type_handle = { runtime_handle_type };
1355 system_type_get_type_from_handle = GetMethod (
1356 type_type, "GetTypeFromHandle", runtime_type_handle);
1358 Type [] delegate_delegate = { delegate_type, delegate_type };
1359 delegate_combine_delegate_delegate = GetMethod (
1360 delegate_type, "Combine", delegate_delegate);
1362 delegate_remove_delegate_delegate = GetMethod (
1363 delegate_type, "Remove", delegate_delegate);
1368 Type [] void_arg = { };
1369 ienumerator_getcurrent = GetProperty (
1370 ienumerator_type, "Current");
1371 bool_movenext_void = GetMethod (
1372 ienumerator_type, "MoveNext", void_arg);
1373 void_reset_void = GetMethod (
1374 ienumerator_type, "Reset", void_arg);
1375 void_dispose_void = GetMethod (
1376 idisposable_type, "Dispose", void_arg);
1377 int_get_offset_to_string_data = GetMethod (
1378 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1379 int_array_get_length = GetMethod (
1380 array_type, "get_Length", void_arg);
1381 int_array_get_rank = GetMethod (
1382 array_type, "get_Rank", void_arg);
1383 ienumerable_getenumerator_void = GetMethod (
1384 ienumerable_type, "GetEnumerator", void_arg);
1389 Type [] int_arg = { int32_type };
1390 int_array_get_length_int = GetMethod (
1391 array_type, "GetLength", int_arg);
1392 int_array_get_upper_bound_int = GetMethod (
1393 array_type, "GetUpperBound", int_arg);
1394 int_array_get_lower_bound_int = GetMethod (
1395 array_type, "GetLowerBound", int_arg);
1398 // System.Array methods
1400 object_array_clone = GetMethod (
1401 array_type, "Clone", void_arg);
1402 Type [] array_int_arg = { array_type, int32_type };
1403 void_array_copyto_array_int = GetMethod (
1404 array_type, "CopyTo", array_int_arg);
1409 Type [] object_arg = { object_type };
1410 void_monitor_enter_object = GetMethod (
1411 monitor_type, "Enter", object_arg);
1412 void_monitor_exit_object = GetMethod (
1413 monitor_type, "Exit", object_arg);
1415 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1417 void_initializearray_array_fieldhandle = GetMethod (
1418 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1423 int_getlength_int = GetMethod (
1424 array_type, "GetLength", int_arg);
1427 // Decimal constructors
1429 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1430 void_decimal_ctor_five_args = GetConstructor (
1431 decimal_type, dec_arg);
1433 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1438 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1439 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1440 default_member_ctor = GetConstructor (default_member_type, string_);
1442 Type[] short_arg = { short_type };
1443 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1445 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1446 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1448 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1454 compiler_generated_attr = new CustomAttributeBuilder (
1455 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1457 Type[] type_int_arg = { type_type, int32_type };
1458 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1461 object_ctor = GetConstructor (object_type, void_arg);
1463 InitGenericCodeHelpers ();
1466 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1469 /// This is the "old", non-cache based FindMembers() function. We cannot use
1470 /// the cache here because there is no member name argument.
1472 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1473 MemberFilter filter, object criteria)
1475 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1478 // `builder_to_declspace' contains all dynamic types.
1482 Timer.StartTimer (TimerType.FindMembers);
1483 list = decl.FindMembers (mt, bf, filter, criteria);
1484 Timer.StopTimer (TimerType.FindMembers);
1489 // We have to take care of arrays specially, because GetType on
1490 // a TypeBuilder array will return a Type, not a TypeBuilder,
1491 // and we can not call FindMembers on this type.
1493 if (t.IsSubclassOf (TypeManager.array_type))
1494 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1496 if (t is GenericTypeParameterBuilder) {
1497 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1499 Timer.StartTimer (TimerType.FindMembers);
1500 MemberList list = tparam.FindMembers (
1501 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1502 Timer.StopTimer (TimerType.FindMembers);
1507 // Since FindMembers will not lookup both static and instance
1508 // members, we emulate this behaviour here.
1510 if ((bf & instance_and_static) == instance_and_static){
1511 MemberInfo [] i_members = t.FindMembers (
1512 mt, bf & ~BindingFlags.Static, filter, criteria);
1514 int i_len = i_members.Length;
1516 MemberInfo one = i_members [0];
1519 // If any of these are present, we are done!
1521 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1522 return new MemberList (i_members);
1525 MemberInfo [] s_members = t.FindMembers (
1526 mt, bf & ~BindingFlags.Instance, filter, criteria);
1528 int s_len = s_members.Length;
1529 if (i_len > 0 || s_len > 0)
1530 return new MemberList (i_members, s_members);
1533 return new MemberList (i_members);
1535 return new MemberList (s_members);
1539 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1544 /// This method is only called from within MemberLookup. It tries to use the member
1545 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1546 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1547 /// our return value will already contain all inherited members and the caller don't need
1548 /// to check base classes and interfaces anymore.
1550 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1551 string name, out bool used_cache)
1556 // We have to take care of arrays specially, because GetType on
1557 // a TypeBuilder array will return a Type, not a TypeBuilder,
1558 // and we can not call FindMembers on this type.
1560 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1562 return TypeHandle.ArrayType.MemberCache.FindMembers (
1563 mt, bf, name, FilterWithClosure_delegate, null);
1567 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1568 // and we can ask the DeclSpace for the MemberCache.
1570 if (t is TypeBuilder) {
1571 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1572 cache = decl.MemberCache;
1575 // If this DeclSpace has a MemberCache, use it.
1578 if (cache != null) {
1580 return cache.FindMembers (
1581 mt, bf, name, FilterWithClosure_delegate, null);
1584 // If there is no MemberCache, we need to use the "normal" FindMembers.
1585 // Note, this is a VERY uncommon route!
1588 Timer.StartTimer (TimerType.FindMembers);
1589 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1590 FilterWithClosure_delegate, name);
1591 Timer.StopTimer (TimerType.FindMembers);
1593 return (MemberInfo []) list;
1596 if (t is GenericTypeParameterBuilder) {
1597 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1600 Timer.StartTimer (TimerType.FindMembers);
1601 list = tparam.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1602 FilterWithClosure_delegate, name);
1603 Timer.StopTimer (TimerType.FindMembers);
1605 return (MemberInfo []) list;
1608 if (t.IsGenericInstance && (mt == MemberTypes.NestedType)) {
1610 // This happens if we're resolving a class'es base class and interfaces
1611 // in TypeContainer.DefineType(). At this time, the types aren't
1612 // populated yet, so we can't use the cache.
1614 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1615 FilterWithClosure_delegate, name);
1621 // This call will always succeed. There is exactly one TypeHandle instance per
1622 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1623 // the corresponding MemberCache.
1625 cache = TypeHandle.GetMemberCache (t);
1628 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1631 public static bool IsBuiltinType (Type t)
1633 t = TypeToCoreType (t);
1634 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1635 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1636 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1637 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1643 public static bool IsBuiltinType (TypeContainer tc)
1645 return IsBuiltinType (tc.TypeBuilder);
1649 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1650 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1652 public static bool IsPrimitiveType (Type t)
1654 return (t == int32_type || t == uint32_type ||
1655 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1656 t == char_type || t == short_type || t == bool_type ||
1657 t == sbyte_type || t == byte_type || t == ushort_type);
1660 public static bool IsDelegateType (Type t)
1662 if (t.IsGenericInstance)
1663 t = t.GetGenericTypeDefinition ();
1665 if (t.IsSubclassOf (TypeManager.delegate_type))
1671 public static bool IsEnumType (Type t)
1673 if (t.IsSubclassOf (TypeManager.enum_type))
1678 public static bool IsBuiltinOrEnum (Type t)
1680 if (IsBuiltinType (t))
1689 public static bool IsNullType (Type t)
1691 return t == null_type;
1694 public static bool IsAttributeType (Type t)
1696 return (t == attribute_type) || t.IsSubclassOf (attribute_type);
1699 static Stack unmanaged_enclosing_types = new Stack (4);
1702 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1704 public static bool IsUnmanagedType (Type t)
1706 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1707 if (unmanaged_enclosing_types.Contains (t))
1710 // builtins that are not unmanaged types
1711 if (t == TypeManager.object_type || t == TypeManager.string_type)
1714 if (IsBuiltinOrEnum (t))
1717 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1721 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1725 if (!IsValueType (t))
1728 unmanaged_enclosing_types.Push (t);
1732 if (t is TypeBuilder){
1733 TypeContainer tc = LookupTypeContainer (t);
1734 if (tc.Fields != null){
1735 foreach (Field f in tc.Fields){
1736 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1737 if ((f.ModFlags & Modifiers.STATIC) != 0)
1739 if (f.MemberType == null)
1741 if (!IsUnmanagedType (f.MemberType)){
1742 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1748 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1750 foreach (FieldInfo f in fields){
1751 if (!IsUnmanagedType (f.FieldType)){
1752 Report.SymbolRelatedToPreviousError (f);
1758 unmanaged_enclosing_types.Pop ();
1763 public static bool IsValueType (Type t)
1765 return t.IsGenericParameter || t.IsValueType;
1768 public static bool IsInterfaceType (Type t)
1770 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1774 return tc.Kind == Kind.Interface;
1777 public static bool IsSubclassOf (Type type, Type base_type)
1779 TypeParameter tparam = LookupTypeParameter (type);
1780 TypeParameter pparam = LookupTypeParameter (base_type);
1782 if ((tparam != null) && (pparam != null)) {
1783 if (tparam == pparam)
1786 return tparam.IsSubclassOf (base_type);
1790 if (type.Equals (base_type))
1793 type = type.BaseType;
1794 } while (type != null);
1799 public static bool IsPrivateAccessible (Type type, Type parent)
1801 if (type.Equals (parent))
1804 if ((type is TypeBuilder) && type.IsGenericTypeDefinition && parent.IsGenericInstance) {
1806 // `a' is a generic type definition's TypeBuilder and `b' is a
1807 // generic instance of the same type.
1813 // void Test (Stack<T> stack) { }
1816 // The first argument of `Test' will be the generic instance
1817 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1820 // We hit this via Closure.Filter() for gen-82.cs.
1822 if (type != parent.GetGenericTypeDefinition ())
1828 if (type.IsGenericInstance && parent.IsGenericInstance) {
1829 if (type.GetGenericTypeDefinition () != parent.GetGenericTypeDefinition ())
1838 public static bool IsFamilyAccessible (Type type, Type parent)
1840 TypeParameter tparam = LookupTypeParameter (type);
1841 TypeParameter pparam = LookupTypeParameter (parent);
1843 if ((tparam != null) && (pparam != null)) {
1844 if (tparam == pparam)
1847 return tparam.IsSubclassOf (parent);
1851 if (IsEqualGenericInstance (type, parent))
1854 type = type.BaseType;
1855 } while (type != null);
1861 // Checks whether `type' is a subclass or nested child of `base_type'.
1863 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1866 if (IsFamilyAccessible (type, base_type))
1869 // Handle nested types.
1870 type = type.DeclaringType;
1871 } while (type != null);
1877 // Checks whether `type' is a nested child of `parent'.
1879 public static bool IsNestedChildOf (Type type, Type parent)
1881 if (IsEqual (type, parent))
1884 type = type.DeclaringType;
1885 while (type != null) {
1886 if (IsEqual (type, parent))
1889 type = type.DeclaringType;
1896 // Do the right thing when returning the element type of an
1897 // array type based on whether we are compiling corlib or not
1899 public static Type GetElementType (Type t)
1901 if (RootContext.StdLib)
1902 return t.GetElementType ();
1904 return TypeToCoreType (t.GetElementType ());
1908 /// This method is not implemented by MS runtime for dynamic types
1910 public static bool HasElementType (Type t)
1912 return t.IsArray || t.IsPointer || t.IsByRef;
1916 /// Returns the User Defined Types
1918 public static ArrayList UserTypes {
1924 public static Hashtable TypeContainers {
1926 return typecontainers;
1930 static Hashtable builder_to_constant;
1932 public static void RegisterConstant (FieldBuilder fb, Const c)
1934 if (builder_to_constant == null)
1935 builder_to_constant = new PtrHashtable ();
1937 if (builder_to_constant.Contains (fb))
1940 builder_to_constant.Add (fb, c);
1943 public static Const LookupConstant (FieldBuilder fb)
1945 if (builder_to_constant == null)
1948 return (Const) builder_to_constant [fb];
1952 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1956 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1957 /// for anything which is dynamic, and we need this in a number of places,
1958 /// we register this information here, and use it afterwards.
1960 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1965 method_arguments.Add (mb, args);
1966 method_params.Add (mb, ip);
1969 static public ParameterData GetParameterData (MethodBase mb)
1971 object pd = method_params [mb];
1973 if (mb is MethodBuilder || mb is ConstructorBuilder)
1974 throw new InternalErrorException ("Argument for Method not registered" + mb);
1976 method_params [mb] = pd = new ReflectionParameters (mb);
1979 return (ParameterData) pd;
1982 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1984 if (method_overrides.Contains (override_method)) {
1985 if (method_overrides [override_method] != base_method)
1986 throw new InternalErrorException ("Override mismatch: " + override_method);
1989 method_overrides [override_method] = base_method;
1992 static public bool IsOverride (MethodBase m)
1994 return m.IsVirtual &&
1995 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1996 (m is MethodBuilder || method_overrides.Contains (m));
2000 /// Returns the argument types for a method based on its methodbase
2002 /// For dynamic methods, we use the compiler provided types, for
2003 /// methods from existing assemblies we load them from GetParameters,
2004 /// and insert them into the cache
2006 static public Type [] GetArgumentTypes (MethodBase mb)
2008 object t = method_arguments [mb];
2012 ParameterInfo [] pi = mb.GetParameters ();
2019 types = new Type [c];
2020 for (int i = 0; i < c; i++)
2021 types [i] = pi [i].ParameterType;
2023 method_arguments.Add (mb, types);
2028 /// Returns the argument types for an indexer based on its PropertyInfo
2030 /// For dynamic indexers, we use the compiler provided types, for
2031 /// indexers from existing assemblies we load them from GetParameters,
2032 /// and insert them into the cache
2034 static public Type [] GetArgumentTypes (PropertyInfo indexer)
2036 if (indexer_arguments.Contains (indexer))
2037 return (Type []) indexer_arguments [indexer];
2038 else if (indexer is PropertyBuilder)
2039 // If we're a PropertyBuilder and not in the
2040 // `indexer_arguments' hash, then we're a property and
2044 ParameterInfo [] pi = indexer.GetIndexParameters ();
2045 // Property, not an indexer.
2049 Type [] types = new Type [c];
2051 for (int i = 0; i < c; i++)
2052 types [i] = pi [i].ParameterType;
2054 indexer_arguments.Add (indexer, types);
2060 // This is a workaround the fact that GetValue is not
2061 // supported for dynamic types
2063 static public bool RegisterFieldValue (FieldBuilder fb, object value)
2065 if (fields.Contains (fb))
2068 fields.Add (fb, value);
2073 static public object GetValue (FieldBuilder fb)
2078 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
2080 if (fieldbuilders_to_fields.Contains (fb))
2083 fieldbuilders_to_fields.Add (fb, f);
2088 // The return value can be null; This will be the case for
2089 // auxiliary FieldBuilders created by the compiler that have no
2090 // real field being declared on the source code
2092 static public FieldBase GetField (FieldInfo fb)
2094 if (fb.DeclaringType.IsGenericInstance)
2095 fb = fb.Mono_GetGenericFieldDefinition ();
2097 return (FieldBase) fieldbuilders_to_fields [fb];
2100 static Hashtable events;
2102 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
2105 events = new Hashtable ();
2107 if (!events.Contains (eb)) {
2108 events.Add (eb, new Pair (add, remove));
2112 static public MethodInfo GetAddMethod (EventInfo ei)
2114 if (ei is MyEventBuilder) {
2115 Pair pair = (Pair) events [ei];
2117 return (MethodInfo) pair.First;
2119 return ei.GetAddMethod (true);
2122 static public MethodInfo GetRemoveMethod (EventInfo ei)
2124 if (ei is MyEventBuilder) {
2125 Pair pair = (Pair) events [ei];
2127 return (MethodInfo) pair.Second;
2129 return ei.GetRemoveMethod (true);
2132 static Hashtable priv_fields_events;
2134 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
2136 if (priv_fields_events == null)
2137 priv_fields_events = new Hashtable ();
2139 if (priv_fields_events.Contains (einfo))
2142 priv_fields_events.Add (einfo, builder);
2147 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
2149 if (priv_fields_events == null)
2152 return (MemberInfo) priv_fields_events [ei];
2155 static Hashtable properties;
2157 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
2159 if (properties == null)
2160 properties = new Hashtable ();
2162 if (properties.Contains (pb))
2165 properties.Add (pb, new Pair (get, set));
2170 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2171 MethodBase set, Type[] args)
2173 if (!RegisterProperty (pb, get,set))
2176 indexer_arguments.Add (pb, args);
2181 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2183 Hashtable hash = new Hashtable ();
2184 return CheckStructCycles (tc, seen, hash);
2187 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2190 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2194 // `seen' contains all types we've already visited.
2196 if (seen.Contains (tc))
2198 seen.Add (tc, null);
2200 if (tc.Fields == null)
2203 foreach (FieldMember field in tc.Fields) {
2204 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
2207 Type ftype = field.FieldBuilder.FieldType;
2208 TypeContainer ftc = LookupTypeContainer (ftype);
2212 if (hash.Contains (ftc)) {
2213 Report.Error (523, tc.Location,
2214 "Struct member `{0}.{1}' of type `{2}' " +
2215 "causes a cycle in the struct layout",
2216 tc.Name, field.Name, ftc.Name);
2221 // `hash' contains all types in the current path.
2223 hash.Add (tc, null);
2225 bool ok = CheckStructCycles (ftc, seen, hash);
2232 if (!seen.Contains (ftc))
2233 seen.Add (ftc, null);
2240 /// Given an array of interface types, expand and eliminate repeated ocurrences
2241 /// of an interface.
2245 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2248 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2250 ArrayList new_ifaces = new ArrayList ();
2252 foreach (TypeExpr iface in base_interfaces){
2253 TypeExpr texpr = iface.ResolveAsTypeTerminal (ec);
2257 if (new_ifaces.Contains (texpr.Type))
2260 new_ifaces.Add (texpr.Type);
2262 Type [] implementing = texpr.Type.GetInterfaces ();
2264 foreach (Type imp in implementing){
2265 if (!new_ifaces.Contains (imp))
2266 new_ifaces.Add (imp);
2269 Type [] ret = new Type [new_ifaces.Count];
2270 new_ifaces.CopyTo (ret, 0);
2274 static PtrHashtable iface_cache = new PtrHashtable ();
2277 /// This function returns the interfaces in the type `t'. Works with
2278 /// both types and TypeBuilders.
2280 public static Type [] GetInterfaces (Type t)
2282 Type [] cached = iface_cache [t] as Type [];
2287 // The reason for catching the Array case is that Reflection.Emit
2288 // will not return a TypeBuilder for Array types of TypeBuilder types,
2289 // but will still throw an exception if we try to call GetInterfaces
2292 // Since the array interfaces are always constant, we return those for
2297 t = TypeManager.array_type;
2299 if ((t is TypeBuilder) || t.IsGenericInstance) {
2300 Type [] base_ifaces;
2302 if (t.BaseType == null)
2303 base_ifaces = NoTypes;
2305 base_ifaces = GetInterfaces (t.BaseType);
2307 if (t.IsGenericInstance)
2308 type_ifaces = t.GetInterfaces ();
2310 type_ifaces = (Type []) builder_to_ifaces [t];
2311 if (type_ifaces == null)
2312 type_ifaces = NoTypes;
2314 int base_count = base_ifaces.Length;
2315 Type [] result = new Type [base_count + type_ifaces.Length];
2316 base_ifaces.CopyTo (result, 0);
2317 type_ifaces.CopyTo (result, base_count);
2319 iface_cache [t] = result;
2321 } else if (t is GenericTypeParameterBuilder){
2322 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2323 if (type_ifaces == null)
2324 type_ifaces = NoTypes;
2326 iface_cache [t] = type_ifaces;
2329 Type[] ifaces = t.GetInterfaces ();
2330 iface_cache [t] = ifaces;
2336 // gets the interfaces that are declared explicitly on t
2338 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2340 return (Type []) builder_to_ifaces [t];
2344 /// The following is used to check if a given type implements an interface.
2345 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2347 public static bool ImplementsInterface (Type t, Type iface)
2352 // FIXME OPTIMIZATION:
2353 // as soon as we hit a non-TypeBuiler in the interface
2354 // chain, we could return, as the `Type.GetInterfaces'
2355 // will return all the interfaces implement by the type
2359 interfaces = GetInterfaces (t);
2361 if (interfaces != null){
2362 foreach (Type i in interfaces){
2369 } while (t != null);
2374 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2376 // This is a custom version of Convert.ChangeType() which works
2377 // with the TypeBuilder defined types when compiling corlib.
2378 public static object ChangeType (object value, Type conversionType, out bool error)
2380 IConvertible convert_value = value as IConvertible;
2382 if (convert_value == null){
2388 // We must use Type.Equals() here since `conversionType' is
2389 // the TypeBuilder created version of a system type and not
2390 // the system type itself. You cannot use Type.GetTypeCode()
2391 // on such a type - it'd always return TypeCode.Object.
2395 if (conversionType.Equals (typeof (Boolean)))
2396 return (object)(convert_value.ToBoolean (nf_provider));
2397 else if (conversionType.Equals (typeof (Byte)))
2398 return (object)(convert_value.ToByte (nf_provider));
2399 else if (conversionType.Equals (typeof (Char)))
2400 return (object)(convert_value.ToChar (nf_provider));
2401 else if (conversionType.Equals (typeof (DateTime)))
2402 return (object)(convert_value.ToDateTime (nf_provider));
2403 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2404 return (object)(convert_value.ToDecimal (nf_provider));
2405 else if (conversionType.Equals (typeof (Double)))
2406 return (object)(convert_value.ToDouble (nf_provider));
2407 else if (conversionType.Equals (typeof (Int16)))
2408 return (object)(convert_value.ToInt16 (nf_provider));
2409 else if (conversionType.Equals (typeof (Int32)))
2410 return (object)(convert_value.ToInt32 (nf_provider));
2411 else if (conversionType.Equals (typeof (Int64)))
2412 return (object)(convert_value.ToInt64 (nf_provider));
2413 else if (conversionType.Equals (typeof (SByte)))
2414 return (object)(convert_value.ToSByte (nf_provider));
2415 else if (conversionType.Equals (typeof (Single)))
2416 return (object)(convert_value.ToSingle (nf_provider));
2417 else if (conversionType.Equals (typeof (String)))
2418 return (object)(convert_value.ToString (nf_provider));
2419 else if (conversionType.Equals (typeof (UInt16)))
2420 return (object)(convert_value.ToUInt16 (nf_provider));
2421 else if (conversionType.Equals (typeof (UInt32)))
2422 return (object)(convert_value.ToUInt32 (nf_provider));
2423 else if (conversionType.Equals (typeof (UInt64)))
2424 return (object)(convert_value.ToUInt64 (nf_provider));
2425 else if (conversionType.Equals (typeof (Object)))
2426 return (object)(value);
2436 // This is needed, because enumerations from assemblies
2437 // do not report their underlyingtype, but they report
2440 public static Type EnumToUnderlying (Type t)
2442 if (t == TypeManager.enum_type)
2445 t = t.UnderlyingSystemType;
2446 if (!TypeManager.IsEnumType (t))
2449 if (t is TypeBuilder) {
2450 // slow path needed to compile corlib
2451 if (t == TypeManager.bool_type ||
2452 t == TypeManager.byte_type ||
2453 t == TypeManager.sbyte_type ||
2454 t == TypeManager.char_type ||
2455 t == TypeManager.short_type ||
2456 t == TypeManager.ushort_type ||
2457 t == TypeManager.int32_type ||
2458 t == TypeManager.uint32_type ||
2459 t == TypeManager.int64_type ||
2460 t == TypeManager.uint64_type)
2463 TypeCode tc = Type.GetTypeCode (t);
2466 case TypeCode.Boolean:
2467 return TypeManager.bool_type;
2469 return TypeManager.byte_type;
2470 case TypeCode.SByte:
2471 return TypeManager.sbyte_type;
2473 return TypeManager.char_type;
2474 case TypeCode.Int16:
2475 return TypeManager.short_type;
2476 case TypeCode.UInt16:
2477 return TypeManager.ushort_type;
2478 case TypeCode.Int32:
2479 return TypeManager.int32_type;
2480 case TypeCode.UInt32:
2481 return TypeManager.uint32_type;
2482 case TypeCode.Int64:
2483 return TypeManager.int64_type;
2484 case TypeCode.UInt64:
2485 return TypeManager.uint64_type;
2487 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2491 // When compiling corlib and called with one of the core types, return
2492 // the corresponding typebuilder for that type.
2494 public static Type TypeToCoreType (Type t)
2496 if (RootContext.StdLib || (t is TypeBuilder))
2499 TypeCode tc = Type.GetTypeCode (t);
2502 case TypeCode.Boolean:
2503 return TypeManager.bool_type;
2505 return TypeManager.byte_type;
2506 case TypeCode.SByte:
2507 return TypeManager.sbyte_type;
2509 return TypeManager.char_type;
2510 case TypeCode.Int16:
2511 return TypeManager.short_type;
2512 case TypeCode.UInt16:
2513 return TypeManager.ushort_type;
2514 case TypeCode.Int32:
2515 return TypeManager.int32_type;
2516 case TypeCode.UInt32:
2517 return TypeManager.uint32_type;
2518 case TypeCode.Int64:
2519 return TypeManager.int64_type;
2520 case TypeCode.UInt64:
2521 return TypeManager.uint64_type;
2522 case TypeCode.Single:
2523 return TypeManager.float_type;
2524 case TypeCode.Double:
2525 return TypeManager.double_type;
2526 case TypeCode.String:
2527 return TypeManager.string_type;
2528 case TypeCode.Decimal:
2529 return TypeManager.decimal_type;
2531 if (t == typeof (void))
2532 return TypeManager.void_type;
2533 if (t == typeof (object))
2534 return TypeManager.object_type;
2535 if (t == typeof (System.Type))
2536 return TypeManager.type_type;
2537 if (t == typeof (System.IntPtr))
2538 return TypeManager.intptr_type;
2544 /// Utility function that can be used to probe whether a type
2545 /// is managed or not.
2547 public static bool VerifyUnManaged (Type t, Location loc)
2549 if (IsUnmanagedType (t))
2554 "Cannot take the address or size of a variable of a managed type ('" +
2555 CSharpName (t) + "')");
2560 /// Returns the name of the indexer in a given type.
2563 /// The default is not always `Item'. The user can change this behaviour by
2564 /// using the IndexerNameAttribute in the container.
2566 /// For example, the String class indexer is named `Chars' not `Item'
2568 public static string IndexerPropertyName (Type t)
2570 if (t.IsGenericInstance)
2571 t = t.GetGenericTypeDefinition ();
2573 if (t is TypeBuilder) {
2574 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2575 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2578 System.Attribute attr = System.Attribute.GetCustomAttribute (
2579 t, TypeManager.default_member_type);
2581 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2582 return dma.MemberName;
2585 return TypeContainer.DefaultIndexerName;
2588 static MethodInfo declare_local_method = null;
2590 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2592 if (declare_local_method == null){
2593 declare_local_method = typeof (ILGenerator).GetMethod (
2595 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2597 new Type [] { typeof (Type), typeof (bool)},
2599 if (declare_local_method == null){
2600 Report.Warning (-30, new Location (-1),
2601 "This version of the runtime does not support making pinned local variables. " +
2602 "This code may cause errors on a runtime with a moving GC");
2603 return ig.DeclareLocal (t);
2606 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2610 // Returns whether the array of memberinfos contains the given method
2612 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2614 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2616 foreach (MethodBase method in array) {
2617 if (method.Name != new_method.Name)
2620 if (method is MethodInfo && new_method is MethodInfo)
2621 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2625 Type [] old_args = TypeManager.GetArgumentTypes (method);
2626 int old_count = old_args.Length;
2629 if (new_args.Length != old_count)
2632 for (i = 0; i < old_count; i++){
2633 if (old_args [i] != new_args [i])
2646 // We copy methods from `new_members' into `target_list' if the signature
2647 // for the method from in the new list does not exist in the target_list
2649 // The name is assumed to be the same.
2651 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2653 if (target_list == null){
2654 target_list = new ArrayList ();
2656 foreach (MemberInfo mi in new_members){
2657 if (mi is MethodBase)
2658 target_list.Add (mi);
2663 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2664 target_list.CopyTo (target_array, 0);
2666 foreach (MemberInfo mi in new_members){
2667 MethodBase new_method = (MethodBase) mi;
2669 if (!ArrayContainsMethod (target_array, new_method))
2670 target_list.Add (new_method);
2675 #region MemberLookup implementation
2678 // Whether we allow private members in the result (since FindMembers
2679 // uses NonPublic for both protected and private), we need to distinguish.
2682 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2687 internal class Closure {
2688 internal bool private_ok;
2690 // Who is invoking us and which type is being queried currently.
2691 internal Type invocation_type;
2692 internal Type qualifier_type;
2694 // The assembly that defines the type is that is calling us
2695 internal Assembly invocation_assembly;
2696 internal IList almost_match;
2698 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2700 if (invocation_type == null)
2703 if (is_static && qualifier_type == null)
2704 // It resolved from a simple name, so it should be visible.
2707 // A nested class has access to all the protected members visible to its parent.
2708 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2711 if (IsNestedFamilyAccessible (invocation_type, m.DeclaringType)) {
2712 // Although a derived class can access protected members of its base class
2713 // it cannot do so through an instance of the base class (CS1540).
2714 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2716 qualifier_type == null ||
2717 IsEqualGenericInstance (invocation_type, qualifier_type) ||
2718 !IsFamilyAccessible (invocation_type, qualifier_type) ||
2719 IsNestedChildOf (invocation_type, qualifier_type))
2723 if (!is_static && almost_match != null)
2724 almost_match.Add (m);
2730 // This filter filters by name + whether it is ok to include private
2731 // members in the search
2733 internal bool Filter (MemberInfo m, object filter_criteria)
2736 // Hack: we know that the filter criteria will always be in the
2737 // `closure' // fields.
2740 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2743 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2744 (invocation_type != null) &&
2745 IsPrivateAccessible (m.DeclaringType, invocation_type))
2749 // Ugly: we need to find out the type of `m', and depending
2750 // on this, tell whether we accept or not
2752 if (m is MethodBase){
2753 MethodBase mb = (MethodBase) m;
2754 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2756 if (ma == MethodAttributes.Private)
2757 return private_ok ||
2758 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2759 IsNestedChildOf (invocation_type, m.DeclaringType);
2761 if (invocation_assembly == mb.DeclaringType.Assembly) {
2762 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2765 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2769 if (ma == MethodAttributes.Family ||
2770 ma == MethodAttributes.FamANDAssem ||
2771 ma == MethodAttributes.FamORAssem)
2772 return CheckValidFamilyAccess (mb.IsStatic, m);
2778 if (m is FieldInfo){
2779 FieldInfo fi = (FieldInfo) m;
2780 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2782 if (fa == FieldAttributes.Private)
2783 return private_ok ||
2784 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2785 IsNestedChildOf (invocation_type, m.DeclaringType);
2787 if (invocation_assembly == fi.DeclaringType.Assembly) {
2788 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2791 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2795 if (fa == FieldAttributes.Family ||
2796 fa == FieldAttributes.FamANDAssem ||
2797 fa == FieldAttributes.FamORAssem)
2798 return CheckValidFamilyAccess (fi.IsStatic, m);
2805 // EventInfos and PropertyInfos, return true because they lack
2806 // permission information, so we need to check later on the methods.
2812 static Closure closure = new Closure ();
2813 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2816 // Looks up a member called `name' in the `queried_type'. This lookup
2817 // is done by code that is contained in the definition for `invocation_type'
2818 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2820 // `invocation_type' is used to check whether we're allowed to access the requested
2821 // member wrt its protection level.
2823 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2824 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2825 // is B and qualifier_type is A). This is used to do the CS1540 check.
2827 // When resolving a SimpleName, `qualifier_type' is null.
2829 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2830 // the same than `queried_type' - except when we're being called from BaseAccess;
2831 // in this case, `invocation_type' is the current type and `queried_type' the base
2832 // type, so this'd normally trigger a CS1540.
2834 // The binding flags are `bf' and the kind of members being looked up are `mt'
2836 // The return value always includes private members which code in `invocation_type'
2837 // is allowed to access (using the specified `qualifier_type' if given); only use
2838 // BindingFlags.NonPublic to bypass the permission check.
2840 // The 'almost_match' argument is used for reporting error CS1540.
2842 // Returns an array of a single element for everything but Methods/Constructors
2843 // that might return multiple matches.
2845 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2846 Type queried_type, MemberTypes mt,
2847 BindingFlags original_bf, string name, IList almost_match)
2849 Timer.StartTimer (TimerType.MemberLookup);
2851 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2852 queried_type, mt, original_bf, name, almost_match);
2854 Timer.StopTimer (TimerType.MemberLookup);
2859 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2860 Type queried_type, MemberTypes mt,
2861 BindingFlags original_bf, string name, IList almost_match)
2863 BindingFlags bf = original_bf;
2865 ArrayList method_list = null;
2866 Type current_type = queried_type;
2867 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2868 bool skip_iface_check = true, used_cache = false;
2869 bool always_ok_flag = false;
2871 closure.invocation_type = invocation_type;
2872 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2873 closure.qualifier_type = qualifier_type;
2874 closure.almost_match = almost_match;
2877 // If we are a nested class, we always have access to our container
2880 if (invocation_type != null){
2881 string invocation_name = invocation_type.FullName;
2882 if ((invocation_name != null) && (invocation_name.IndexOf ('+') != -1)){
2883 string container = queried_type.FullName + "+";
2884 int container_length = container.Length;
2886 if (invocation_name.Length > container_length){
2887 string shared = invocation_name.Substring (0, container_length);
2889 if (shared == container)
2890 always_ok_flag = true;
2895 // This is from the first time we find a method
2896 // in most cases, we do not actually find a method in the base class
2897 // so we can just ignore it, and save the arraylist allocation
2898 MemberInfo [] first_members_list = null;
2899 bool use_first_members_list = false;
2905 // `NonPublic' is lame, because it includes both protected and
2906 // private methods, so we need to control this behavior by
2907 // explicitly tracking if a private method is ok or not.
2909 // The possible cases are:
2910 // public, private and protected (internal does not come into the
2913 if ((invocation_type != null) &&
2914 ((invocation_type == current_type) ||
2915 IsNestedChildOf (invocation_type, current_type)) ||
2917 bf = original_bf | BindingFlags.NonPublic;
2921 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2923 Timer.StopTimer (TimerType.MemberLookup);
2925 list = MemberLookup_FindMembers (
2926 current_type, mt, bf, name, out used_cache);
2928 Timer.StartTimer (TimerType.MemberLookup);
2931 // When queried for an interface type, the cache will automatically check all
2932 // inherited members, so we don't need to do this here. However, this only
2933 // works if we already used the cache in the first iteration of this loop.
2935 // If we used the cache in any further iteration, we can still terminate the
2936 // loop since the cache always looks in all base classes.
2942 skip_iface_check = false;
2944 if (current_type == TypeManager.object_type)
2947 current_type = current_type.BaseType;
2950 // This happens with interfaces, they have a null
2951 // basetype. Look members up in the Object class.
2953 if (current_type == null) {
2954 current_type = TypeManager.object_type;
2959 if (list.Length == 0)
2963 // Events and types are returned by both `static' and `instance'
2964 // searches, which means that our above FindMembers will
2965 // return two copies of the same.
2967 if (list.Length == 1 && !(list [0] is MethodBase)){
2972 // Multiple properties: we query those just to find out the indexer
2975 if (list [0] is PropertyInfo)
2979 // We found an event: the cache lookup returns both the event and
2980 // its private field.
2982 if (list [0] is EventInfo) {
2983 if ((list.Length == 2) && (list [1] is FieldInfo))
2984 return new MemberInfo [] { list [0] };
2991 // We found methods, turn the search into "method scan"
2995 if (first_members_list != null) {
2996 if (use_first_members_list) {
2997 method_list = CopyNewMethods (method_list, first_members_list);
2998 use_first_members_list = false;
3001 method_list = CopyNewMethods (method_list, list);
3003 first_members_list = list;
3004 use_first_members_list = true;
3006 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3008 } while (searching);
3010 if (use_first_members_list) {
3011 foreach (MemberInfo mi in first_members_list) {
3012 if (! (mi is MethodBase)) {
3013 method_list = CopyNewMethods (method_list, first_members_list);
3014 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3017 return (MemberInfo []) first_members_list;
3020 if (method_list != null && method_list.Count > 0) {
3021 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3024 // This happens if we already used the cache in the first iteration, in this case
3025 // the cache already looked in all interfaces.
3027 if (skip_iface_check)
3031 // Interfaces do not list members they inherit, so we have to
3034 if (!queried_type.IsInterface)
3037 if (queried_type.IsArray)
3038 queried_type = TypeManager.array_type;
3040 Type [] ifaces = GetInterfaces (queried_type);
3044 foreach (Type itype in ifaces){
3047 x = MemberLookup (null, null, itype, mt, bf, name, null);
3055 // Tests whether external method is really special
3056 public static bool IsSpecialMethod (MethodBase mb)
3058 string name = mb.Name;
3059 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
3060 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
3062 if (name.StartsWith ("add_"))
3063 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
3065 if (name.StartsWith ("remove_"))
3066 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
3068 if (name.StartsWith ("op_")){
3069 foreach (string oname in Unary.oper_names) {
3074 foreach (string oname in Binary.oper_names) {
3087 /// There is exactly one instance of this class per type.
3089 public sealed class TypeHandle : IMemberContainer {
3090 public readonly IMemberContainer BaseType;
3092 readonly int id = ++next_id;
3093 static int next_id = 0;
3095 static TypeHandle ()
3101 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3102 /// a TypeHandle yet, a new instance of it is created. This static method
3103 /// ensures that we'll only have one TypeHandle instance per type.
3105 private static TypeHandle GetTypeHandle (Type t)
3107 TypeHandle handle = (TypeHandle) type_hash [t];
3111 handle = new TypeHandle (t);
3112 type_hash.Add (t, handle);
3116 public static MemberCache GetMemberCache (Type t)
3118 return GetTypeHandle (t).MemberCache;
3121 public static void CleanUp ()
3126 public static void Reset ()
3128 type_hash = new PtrHashtable ();
3132 /// Returns the TypeHandle for TypeManager.object_type.
3134 public static IMemberContainer ObjectType {
3136 if (object_type != null)
3139 object_type = GetTypeHandle (TypeManager.object_type);
3146 /// Returns the TypeHandle for TypeManager.array_type.
3148 public static IMemberContainer ArrayType {
3150 if (array_type != null)
3153 array_type = GetTypeHandle (TypeManager.array_type);
3159 private static PtrHashtable type_hash;
3161 private static TypeHandle object_type = null;
3162 private static TypeHandle array_type = null;
3165 private string full_name;
3166 private bool is_interface;
3167 private MemberCache member_cache;
3168 private MemberCache base_cache;
3170 private TypeHandle (Type type)
3173 full_name = type.FullName != null ? type.FullName : type.Name;
3174 if (type.BaseType != null) {
3175 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3176 BaseType = base_cache.Container;
3177 } else if (type.IsInterface)
3178 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3179 this.is_interface = type.IsInterface || type.IsGenericParameter;
3180 this.member_cache = new MemberCache (this);
3183 // IMemberContainer methods
3185 public string Name {
3197 public MemberCache BaseCache {
3203 public bool IsInterface {
3205 return is_interface;
3209 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3211 MemberInfo [] members;
3212 if (type is GenericTypeParameterBuilder)
3213 return MemberList.Empty;
3214 if (mt == MemberTypes.Event)
3215 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3217 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3219 Array.Reverse (members);
3221 return new MemberList (members);
3224 // IMemberFinder methods
3226 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3227 MemberFilter filter, object criteria)
3229 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3232 public MemberCache MemberCache {
3234 return member_cache;
3238 public override string ToString ()
3240 if (BaseType != null)
3241 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3243 return "TypeHandle (" + id + "," + Name + ")";