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 dllimport_type;
78 static public Type unverifiable_code_type;
79 static public Type methodimpl_attr_type;
80 static public Type marshal_as_attr_type;
81 static public Type new_constraint_attr_type;
82 static public Type param_array_type;
83 static public Type guid_attr_type;
84 static public Type void_ptr_type;
85 static public Type indexer_name_type;
86 static public Type exception_type;
87 static public Type activator_type;
88 static public Type invalid_operation_exception_type;
89 static public Type not_supported_exception_type;
90 static public Type obsolete_attribute_type;
91 static public Type conditional_attribute_type;
92 static public Type in_attribute_type;
93 static public Type anonymous_method_type;
94 static public Type cls_compliant_attribute_type;
95 static public Type typed_reference_type;
96 static public Type arg_iterator_type;
97 static public Type mbr_type;
98 static public Type struct_layout_attribute_type;
99 static public Type field_offset_attribute_type;
100 static public Type security_attr_type;
102 static public Type generic_ienumerator_type;
103 static public Type generic_ienumerable_type;
106 // An empty array of types
108 static public Type [] NoTypes;
109 static public TypeExpr [] NoTypeExprs;
113 // Expressions representing the internal types. Used during declaration
116 static public TypeExpr system_object_expr, system_string_expr;
117 static public TypeExpr system_boolean_expr, system_decimal_expr;
118 static public TypeExpr system_single_expr, system_double_expr;
119 static public TypeExpr system_sbyte_expr, system_byte_expr;
120 static public TypeExpr system_int16_expr, system_uint16_expr;
121 static public TypeExpr system_int32_expr, system_uint32_expr;
122 static public TypeExpr system_int64_expr, system_uint64_expr;
123 static public TypeExpr system_char_expr, system_void_expr;
124 static public TypeExpr system_asynccallback_expr;
125 static public TypeExpr system_iasyncresult_expr;
126 static public TypeExpr system_valuetype_expr;
127 static public TypeExpr system_intptr_expr;
130 // This is only used when compiling corlib
132 static public Type system_int32_type;
133 static public Type system_array_type;
134 static public Type system_type_type;
135 static public Type system_assemblybuilder_type;
136 static public MethodInfo system_int_array_get_length;
137 static public MethodInfo system_int_array_get_rank;
138 static public MethodInfo system_object_array_clone;
139 static public MethodInfo system_int_array_get_length_int;
140 static public MethodInfo system_int_array_get_lower_bound_int;
141 static public MethodInfo system_int_array_get_upper_bound_int;
142 static public MethodInfo system_void_array_copyto_array_int;
146 // Internal, not really used outside
148 static Type runtime_helpers_type;
151 // These methods are called by code generated by the compiler
153 static public MethodInfo string_concat_string_string;
154 static public MethodInfo string_concat_string_string_string;
155 static public MethodInfo string_concat_string_string_string_string;
156 static public MethodInfo string_concat_string_dot_dot_dot;
157 static public MethodInfo string_concat_object_object;
158 static public MethodInfo string_concat_object_object_object;
159 static public MethodInfo string_concat_object_dot_dot_dot;
160 static public MethodInfo string_isinterneted_string;
161 static public MethodInfo system_type_get_type_from_handle;
162 static public MethodInfo object_getcurrent_void;
163 static public MethodInfo bool_movenext_void;
164 static public MethodInfo ienumerable_getenumerator_void;
165 static public MethodInfo void_reset_void;
166 static public MethodInfo void_dispose_void;
167 static public MethodInfo void_monitor_enter_object;
168 static public MethodInfo void_monitor_exit_object;
169 static public MethodInfo void_initializearray_array_fieldhandle;
170 static public MethodInfo int_getlength_int;
171 static public MethodInfo delegate_combine_delegate_delegate;
172 static public MethodInfo delegate_remove_delegate_delegate;
173 static public MethodInfo int_get_offset_to_string_data;
174 static public MethodInfo int_array_get_length;
175 static public MethodInfo int_array_get_rank;
176 static public MethodInfo object_array_clone;
177 static public MethodInfo int_array_get_length_int;
178 static public MethodInfo int_array_get_lower_bound_int;
179 static public MethodInfo int_array_get_upper_bound_int;
180 static public MethodInfo void_array_copyto_array_int;
181 static public MethodInfo activator_create_instance;
184 // The attribute constructors.
186 static public ConstructorInfo object_ctor;
187 static public ConstructorInfo cons_param_array_attribute;
188 static public ConstructorInfo void_decimal_ctor_five_args;
189 static public ConstructorInfo unverifiable_code_ctor;
190 static public ConstructorInfo invalid_operation_ctor;
191 static public ConstructorInfo default_member_ctor;
194 // Holds the Array of Assemblies that have been loaded
195 // (either because it is the default or the user used the
196 // -r command line option)
198 static Assembly [] assemblies;
201 // Keeps a list of modules. We used this to do lookups
202 // on the module using GetType -- needed for arrays
204 static Module [] modules;
207 // This is the type_cache from the assemblies to avoid
208 // hitting System.Reflection on every lookup.
210 static Hashtable types;
213 // This is used to hotld the corresponding TypeContainer objects
214 // since we need this in FindMembers
216 static Hashtable typecontainers;
219 // Keeps track of those types that are defined by the
222 static ArrayList user_types;
224 static PtrHashtable builder_to_declspace;
226 static PtrHashtable builder_to_member_cache;
229 // Tracks the interfaces implemented by typebuilders. We only
230 // enter those who do implement or or more interfaces
232 static PtrHashtable builder_to_ifaces;
235 // Tracks the generic parameters.
237 static PtrHashtable builder_to_type_param;
240 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
241 // the arguments to the method
243 static Hashtable method_arguments;
246 // Maps PropertyBuilder to a Type array that contains
247 // the arguments to the indexer
249 static Hashtable indexer_arguments;
252 // Maybe `method_arguments' should be replaced and only
253 // method_internal_params should be kept?
255 static Hashtable method_internal_params;
258 // Keeps track of methods
261 static Hashtable builder_to_method;
264 // Contains all public types from referenced assemblies.
265 // This member is used only if CLS Compliance verification is required.
267 public static Hashtable all_imported_types;
274 public static void CleanUp ()
276 // Lets get everything clean so that we can collect before generating code
280 typecontainers = null;
282 builder_to_declspace = null;
283 builder_to_member_cache = null;
284 builder_to_ifaces = null;
285 method_arguments = null;
286 indexer_arguments = null;
287 method_internal_params = null;
288 builder_to_method = null;
289 builder_to_type_param = null;
293 negative_hits = null;
294 builder_to_constant = null;
295 fieldbuilders_to_fields = null;
297 priv_fields_events = null;
300 TypeHandle.CleanUp ();
304 /// A filter for Findmembers that uses the Signature object to
307 static bool SignatureFilter (MemberInfo mi, object criteria)
309 Signature sig = (Signature) criteria;
311 if (!(mi is MethodBase))
314 if (mi.Name != sig.name)
317 int count = sig.args.Length;
319 if (mi is MethodBuilder || mi is ConstructorBuilder){
320 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
322 if (candidate_args.Length != count)
325 for (int i = 0; i < count; i++)
326 if (candidate_args [i] != sig.args [i])
331 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
333 if (pars.Length != count)
336 for (int i = 0; i < count; i++)
337 if (pars [i].ParameterType != sig.args [i])
343 // A delegate that points to the filter above.
344 static MemberFilter signature_filter;
347 // These are expressions that represent some of the internal data types, used
350 static void InitExpressionTypes ()
352 system_object_expr = new TypeLookupExpression ("System.Object");
353 system_string_expr = new TypeLookupExpression ("System.String");
354 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
355 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
356 system_single_expr = new TypeLookupExpression ("System.Single");
357 system_double_expr = new TypeLookupExpression ("System.Double");
358 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
359 system_byte_expr = new TypeLookupExpression ("System.Byte");
360 system_int16_expr = new TypeLookupExpression ("System.Int16");
361 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
362 system_int32_expr = new TypeLookupExpression ("System.Int32");
363 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
364 system_int64_expr = new TypeLookupExpression ("System.Int64");
365 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
366 system_char_expr = new TypeLookupExpression ("System.Char");
367 system_void_expr = new TypeLookupExpression ("System.Void");
368 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
369 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
370 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
371 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
374 static TypeManager ()
376 assemblies = new Assembly [0];
378 user_types = new ArrayList ();
380 types = new Hashtable ();
381 typecontainers = new Hashtable ();
383 builder_to_declspace = new PtrHashtable ();
384 builder_to_member_cache = new PtrHashtable ();
385 builder_to_method = new PtrHashtable ();
386 method_arguments = new PtrHashtable ();
387 method_internal_params = new PtrHashtable ();
388 indexer_arguments = new PtrHashtable ();
389 builder_to_ifaces = new PtrHashtable ();
390 builder_to_type_param = new PtrHashtable ();
392 NoTypes = new Type [0];
393 NoTypeExprs = new TypeExpr [0];
395 signature_filter = new MemberFilter (SignatureFilter);
396 InitExpressionTypes ();
399 public static void HandleDuplicate (string name, Type t)
401 Type prev = (Type) types [name];
402 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
406 // This probably never happens, as we catch this before
408 Report.Error (-17, "The type `" + name + "' has already been defined.");
412 tc = builder_to_declspace [t] as TypeContainer;
415 1595, "The type `" + name + "' is defined in an existing assembly;"+
416 " Using the new definition from: " + tc.Location);
419 1595, "The type `" + name + "' is defined in an existing assembly;");
422 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
428 public static void AddUserType (string name, TypeBuilder t)
433 HandleDuplicate (name, t);
439 // This entry point is used by types that we define under the covers
441 public static void RegisterBuilder (Type tb, Type [] ifaces)
444 builder_to_ifaces [tb] = ifaces;
447 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
449 builder_to_declspace.Add (t, tc);
450 typecontainers.Add (name, tc);
451 AddUserType (name, t);
454 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
459 HandleDuplicate (name, t);
462 builder_to_declspace.Add (t, del);
465 public static void AddEnumType (string name, TypeBuilder t, Enum en)
470 HandleDuplicate (name, t);
472 builder_to_declspace.Add (t, en);
475 public static void AddMethod (MethodBase builder, IMethodData method)
477 builder_to_method.Add (builder, method);
480 public static IMethodData GetMethod (MethodBase builder)
482 return (IMethodData) builder_to_method [builder];
485 public static void AddTypeParameter (Type t, TypeParameter tparam)
487 if (!builder_to_type_param.Contains (t))
488 builder_to_type_param.Add (t, tparam);
492 /// Returns the DeclSpace whose Type is `t' or null if there is no
493 /// DeclSpace for `t' (ie, the Type comes from a library)
495 public static DeclSpace LookupDeclSpace (Type t)
497 return builder_to_declspace [t] as DeclSpace;
501 /// Returns the TypeContainer whose Type is `t' or null if there is no
502 /// TypeContainer for `t' (ie, the Type comes from a library)
504 public static TypeContainer LookupTypeContainer (Type t)
506 return builder_to_declspace [t] as TypeContainer;
509 public static TypeContainer LookupGenericTypeContainer (Type t)
511 while (t.IsGenericInstance)
512 t = t.GetGenericTypeDefinition ();
514 return LookupTypeContainer (t);
517 public static MemberCache LookupMemberCache (Type t)
519 if (t is TypeBuilder) {
520 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
521 if (container != null)
522 return container.MemberCache;
525 if (t is GenericTypeParameterBuilder) {
526 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
528 if (container != null)
529 return container.MemberCache;
532 return TypeHandle.GetMemberCache (t);
535 public static MemberCache LookupParentInterfacesCache (Type t)
537 Type [] ifaces = t.GetInterfaces ();
539 if (ifaces != null && ifaces.Length == 1)
540 return LookupMemberCache (ifaces [0]);
542 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
543 MemberCache cache = builder_to_member_cache [t] as MemberCache;
547 cache = new MemberCache (ifaces);
548 builder_to_member_cache.Add (t, cache);
552 public static TypeContainer LookupInterface (Type t)
554 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
555 if ((tc == null) || (tc.Kind != Kind.Interface))
561 public static Delegate LookupDelegate (Type t)
563 return builder_to_declspace [t] as Delegate;
566 public static Enum LookupEnum (Type t)
568 return builder_to_declspace [t] as Enum;
571 public static Class LookupClass (Type t)
573 return (Class) builder_to_declspace [t];
576 public static TypeParameter LookupTypeParameter (Type t)
578 return (TypeParameter) builder_to_type_param [t];
581 public static bool HasConstructorConstraint (Type t)
583 GenericConstraints gc = GetTypeParameterConstraints (t);
587 return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
590 public static GenericConstraints GetTypeParameterConstraints (Type t)
592 if (!t.IsGenericParameter)
593 throw new InvalidOperationException ();
595 TypeParameter tparam = LookupTypeParameter (t);
597 return tparam.GenericConstraints;
599 return new ReflectionConstraints (t);
603 /// Registers an assembly to load types from.
605 public static void AddAssembly (Assembly a)
607 foreach (Assembly assembly in assemblies) {
612 int top = assemblies.Length;
613 Assembly [] n = new Assembly [top + 1];
615 assemblies.CopyTo (n, 0);
621 public static Assembly [] GetAssemblies ()
627 /// Registers a module builder to lookup types from
629 public static void AddModule (Module mb)
631 int top = modules != null ? modules.Length : 0;
632 Module [] n = new Module [top + 1];
635 modules.CopyTo (n, 0);
640 public static Module[] Modules {
646 static Hashtable references = new Hashtable ();
649 // Gets the reference to T version of the Type (T&)
651 public static Type GetReferenceType (Type t)
653 return t.MakeByRefType ();
656 static Hashtable pointers = new Hashtable ();
659 // Gets the pointer to T version of the Type (T*)
661 public static Type GetPointerType (Type t)
663 string tname = t.FullName + "*";
665 Type ret = t.Assembly.GetType (tname);
668 // If the type comes from the assembly we are building
669 // We need the Hashtable, because .NET 1.1 will return different instance types
670 // every time we call ModuleBuilder.GetType.
673 if (pointers [t] == null)
674 pointers [t] = CodeGen.Module.Builder.GetType (tname);
676 ret = (Type) pointers [t];
683 // Low-level lookup, cache-less
685 static Type LookupTypeReflection (string name)
689 foreach (Assembly a in assemblies){
690 t = a.GetType (name);
695 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
696 if (ta == TypeAttributes.NotPublic ||
697 ta == TypeAttributes.NestedPrivate ||
698 ta == TypeAttributes.NestedAssembly ||
699 ta == TypeAttributes.NestedFamANDAssem){
702 // In .NET pointers turn out to be private, even if their
703 // element type is not
706 t = t.GetElementType ();
716 foreach (Module mb in modules) {
717 t = mb.GetType (name);
725 static Hashtable negative_hits = new Hashtable ();
728 // This function is used when you want to avoid the lookups, and want to go
729 // directly to the source. This will use the cache.
731 // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
732 // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
733 // way to test things other than doing a fullname compare
735 public static Type LookupTypeDirect (string name)
737 Type t = (Type) types [name];
741 t = LookupTypeReflection (name);
749 static readonly char [] dot_array = { '.' };
752 /// Returns the Type associated with @name, takes care of the fact that
753 /// reflection expects nested types to be separated from the main type
754 /// with a "+" instead of a "."
756 public static Type LookupType (string name)
761 // First lookup in user defined and cached values
764 t = (Type) types [name];
768 // Two thirds of the failures are caught here.
769 if (negative_hits.Contains (name))
772 // Sadly, split takes a param array, so this ends up allocating *EVERY TIME*
773 string [] elements = name.Split (dot_array);
774 int count = elements.Length;
776 for (int n = 1; n <= count; n++){
777 string top_level_type = String.Join (".", elements, 0, n);
779 // One third of the failures are caught here.
780 if (negative_hits.Contains (top_level_type))
783 t = (Type) types [top_level_type];
785 t = LookupTypeReflection (top_level_type);
787 negative_hits [top_level_type] = null;
798 // We know that System.Object does not have children, and since its the parent of
799 // all the objects, it always gets probbed for inner classes.
801 if (top_level_type == "System.Object")
804 string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
805 //Console.WriteLine ("Looking up: " + newt + " " + name);
806 t = LookupTypeReflection (newt);
808 negative_hits [name] = null;
813 negative_hits [name] = null;
818 /// Computes the namespaces that we import from the assemblies we reference.
820 public static void ComputeNamespaces ()
822 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
825 // First add the assembly namespaces
827 if (assembly_get_namespaces != null){
828 int count = assemblies.Length;
830 for (int i = 0; i < count; i++){
831 Assembly a = assemblies [i];
832 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
833 foreach (string ns in namespaces){
836 Namespace.LookupNamespace (ns, true);
840 Hashtable cache = new Hashtable ();
841 cache.Add ("", null);
842 foreach (Assembly a in assemblies) {
843 foreach (Type t in a.GetExportedTypes ()) {
844 string ns = t.Namespace;
845 if (ns == null || cache.Contains (ns))
848 Namespace.LookupNamespace (ns, true);
849 cache.Add (ns, null);
856 /// Fills static table with exported types from all referenced assemblies.
857 /// This information is required for CLS Compliance tests.
859 public static void LoadAllImportedTypes ()
861 all_imported_types = new Hashtable ();
862 foreach (Assembly a in assemblies) {
863 foreach (Type t in a.GetExportedTypes ()) {
864 all_imported_types [t.FullName] = t;
869 public static bool NamespaceClash (string name, Location loc)
871 if (Namespace.LookupNamespace (name, false) == null)
874 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
879 /// Returns the C# name of a type if possible, or the full type name otherwise
881 static public string CSharpName (Type t)
883 if (t.FullName == null)
886 return Regex.Replace (t.FullName,
888 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
889 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
890 @"Boolean|String|Void|Null)" +
892 new MatchEvaluator (CSharpNameMatch));
895 static String CSharpNameMatch (Match match)
897 string s = match.Groups [1].Captures [0].Value;
899 Replace ("int32", "int").
900 Replace ("uint32", "uint").
901 Replace ("int16", "short").
902 Replace ("uint16", "ushort").
903 Replace ("int64", "long").
904 Replace ("uint64", "ulong").
905 Replace ("single", "float").
906 Replace ("boolean", "bool")
907 + match.Groups [2].Captures [0].Value;
911 /// Returns the signature of the method with full namespace classification
913 static public string GetFullNameSignature (MemberInfo mi)
915 return mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
918 static public string GetFullNameSignature (MethodBase mb)
920 string name = mb.Name;
922 name = mb.DeclaringType.Name;
924 if (mb.IsSpecialName) {
925 if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
926 name = name.Remove (0, 4);
933 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
936 static public string GetFullName (Type t)
938 if (t.FullName == null)
941 string name = t.FullName.Replace ('+', '.');
943 DeclSpace tc = LookupDeclSpace (t);
944 if ((tc != null) && tc.IsGeneric) {
945 TypeParameter[] tparam = tc.TypeParameters;
947 StringBuilder sb = new StringBuilder (name);
949 for (int i = 0; i < tparam.Length; i++) {
952 sb.Append (tparam [i].Name);
955 return sb.ToString ();
956 } else if (t.HasGenericArguments && !t.IsGenericInstance) {
957 Type[] tparam = t.GetGenericArguments ();
959 StringBuilder sb = new StringBuilder (name);
961 for (int i = 0; i < tparam.Length; i++) {
964 sb.Append (tparam [i].Name);
967 return sb.ToString ();
974 /// Returns the signature of the property and indexer
976 static public string CSharpSignature (PropertyBuilder pb, bool is_indexer)
979 return GetFullNameSignature (pb);
982 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
983 string signature = GetFullNameSignature (mb);
984 string arg = TypeManager.LookupParametersByBuilder (mb).ParameterDesc (0);
985 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
989 /// Returns the signature of the method
991 static public string CSharpSignature (MethodBase mb)
993 StringBuilder sig = new StringBuilder ("(");
996 // FIXME: We should really have a single function to do
997 // everything instead of the following 5 line pattern
999 ParameterData iparams = LookupParametersByBuilder (mb);
1001 if (iparams == null)
1002 iparams = new ReflectionParameters (mb);
1005 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
1006 return GetFullNameSignature (mb);
1008 for (int i = 0; i < iparams.Count; i++) {
1012 sig.Append (iparams.ParameterDesc (i));
1017 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
1018 sig.Replace ('(', '[');
1019 sig.Replace (')', ']');
1022 return GetFullNameSignature (mb) + sig.ToString ();
1025 public static string GetMethodName (MethodInfo m)
1027 if (!IsGenericMethod (m))
1030 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
1034 /// Looks up a type, and aborts if it is not found. This is used
1035 /// by types required by the compiler
1037 static Type CoreLookupType (string name)
1039 Type t = LookupTypeDirect (name);
1042 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
1043 Environment.Exit (1);
1050 /// Returns the MethodInfo for a method named `name' defined
1051 /// in type `t' which takes arguments of types `args'
1053 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
1057 BindingFlags flags = instance_and_static | BindingFlags.Public;
1063 flags |= BindingFlags.NonPublic;
1065 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
1066 if (list.Count == 0) {
1068 Report.Error (-19, "Can not find the core function `" + name + "'");
1072 MethodInfo mi = list [0] as MethodInfo;
1075 Report.Error (-19, "Can not find the core function `" + name + "'");
1082 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
1084 return GetMethod (t, name, args, false, report_errors);
1087 static MethodInfo GetMethod (Type t, string name, Type [] args)
1089 return GetMethod (t, name, args, true);
1094 /// Returns the ConstructorInfo for "args"
1096 static ConstructorInfo GetConstructor (Type t, Type [] args)
1104 list = FindMembers (t, MemberTypes.Constructor,
1105 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
1106 signature_filter, sig);
1107 if (list.Count == 0){
1108 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1112 ConstructorInfo ci = list [0] as ConstructorInfo;
1114 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1121 public static void InitEnumUnderlyingTypes ()
1124 int32_type = CoreLookupType ("System.Int32");
1125 int64_type = CoreLookupType ("System.Int64");
1126 uint32_type = CoreLookupType ("System.UInt32");
1127 uint64_type = CoreLookupType ("System.UInt64");
1128 byte_type = CoreLookupType ("System.Byte");
1129 sbyte_type = CoreLookupType ("System.SByte");
1130 short_type = CoreLookupType ("System.Int16");
1131 ushort_type = CoreLookupType ("System.UInt16");
1135 /// The types have to be initialized after the initial
1136 /// population of the type has happened (for example, to
1137 /// bootstrap the corlib.dll
1139 public static void InitCoreTypes ()
1141 object_type = CoreLookupType ("System.Object");
1142 value_type = CoreLookupType ("System.ValueType");
1144 InitEnumUnderlyingTypes ();
1146 char_type = CoreLookupType ("System.Char");
1147 string_type = CoreLookupType ("System.String");
1148 float_type = CoreLookupType ("System.Single");
1149 double_type = CoreLookupType ("System.Double");
1150 char_ptr_type = CoreLookupType ("System.Char*");
1151 decimal_type = CoreLookupType ("System.Decimal");
1152 bool_type = CoreLookupType ("System.Boolean");
1153 enum_type = CoreLookupType ("System.Enum");
1155 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1156 delegate_type = CoreLookupType ("System.Delegate");
1158 array_type = CoreLookupType ("System.Array");
1159 void_type = CoreLookupType ("System.Void");
1160 type_type = CoreLookupType ("System.Type");
1162 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1163 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1164 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1165 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1166 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1167 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1168 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1169 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1170 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1171 idisposable_type = CoreLookupType ("System.IDisposable");
1172 icloneable_type = CoreLookupType ("System.ICloneable");
1173 iconvertible_type = CoreLookupType ("System.IConvertible");
1174 monitor_type = CoreLookupType ("System.Threading.Monitor");
1175 intptr_type = CoreLookupType ("System.IntPtr");
1177 attribute_type = CoreLookupType ("System.Attribute");
1178 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1179 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1180 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1181 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1182 new_constraint_attr_type = CoreLookupType ("System.Runtime.CompilerServices.NewConstraintAttribute");
1183 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1184 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1185 typed_reference_type = CoreLookupType ("System.TypedReference");
1186 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1187 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1190 // Sigh. Remove this before the release. Wonder what versions of Mono
1191 // people are running.
1193 guid_attr_type = LookupType ("System.Runtime.InteropServices.GuidAttribute");
1195 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1197 void_ptr_type = CoreLookupType ("System.Void*");
1199 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1201 exception_type = CoreLookupType ("System.Exception");
1202 activator_type = CoreLookupType ("System.Activator");
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");
1219 generic_ienumerator_type = CoreLookupType (MemberName.MakeName ("System.Collections.Generic.IEnumerator", 1));
1220 generic_ienumerable_type = CoreLookupType (MemberName.MakeName ("System.Collections.Generic.IEnumerable", 1));
1224 // When compiling corlib, store the "real" types here.
1226 if (!RootContext.StdLib) {
1227 system_int32_type = typeof (System.Int32);
1228 system_array_type = typeof (System.Array);
1229 system_type_type = typeof (System.Type);
1230 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1232 Type [] void_arg = { };
1233 system_int_array_get_length = GetMethod (
1234 system_array_type, "get_Length", void_arg);
1235 system_int_array_get_rank = GetMethod (
1236 system_array_type, "get_Rank", void_arg);
1237 system_object_array_clone = GetMethod (
1238 system_array_type, "Clone", void_arg);
1240 Type [] system_int_arg = { system_int32_type };
1241 system_int_array_get_length_int = GetMethod (
1242 system_array_type, "GetLength", system_int_arg);
1243 system_int_array_get_upper_bound_int = GetMethod (
1244 system_array_type, "GetUpperBound", system_int_arg);
1245 system_int_array_get_lower_bound_int = GetMethod (
1246 system_array_type, "GetLowerBound", system_int_arg);
1248 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1249 system_void_array_copyto_array_int = GetMethod (
1250 system_array_type, "CopyTo", system_array_int_arg);
1252 Type [] system_3_type_arg = {
1253 system_type_type, system_type_type, system_type_type };
1254 Type [] system_4_type_arg = {
1255 system_type_type, system_type_type, system_type_type, system_type_type };
1257 MethodInfo set_corlib_type_builders = GetMethod (
1258 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1259 system_4_type_arg, true, false);
1261 if (set_corlib_type_builders != null) {
1262 object[] args = new object [4];
1263 args [0] = object_type;
1264 args [1] = value_type;
1265 args [2] = enum_type;
1266 args [3] = void_type;
1268 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1270 // Compatibility for an older version of the class libs.
1271 set_corlib_type_builders = GetMethod (
1272 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1273 system_3_type_arg, true, true);
1275 if (set_corlib_type_builders == null) {
1276 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1280 object[] args = new object [3];
1281 args [0] = object_type;
1282 args [1] = value_type;
1283 args [2] = enum_type;
1285 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1289 system_object_expr.Type = object_type;
1290 system_string_expr.Type = string_type;
1291 system_boolean_expr.Type = bool_type;
1292 system_decimal_expr.Type = decimal_type;
1293 system_single_expr.Type = float_type;
1294 system_double_expr.Type = double_type;
1295 system_sbyte_expr.Type = sbyte_type;
1296 system_byte_expr.Type = byte_type;
1297 system_int16_expr.Type = short_type;
1298 system_uint16_expr.Type = ushort_type;
1299 system_int32_expr.Type = int32_type;
1300 system_uint32_expr.Type = uint32_type;
1301 system_int64_expr.Type = int64_type;
1302 system_uint64_expr.Type = uint64_type;
1303 system_char_expr.Type = char_type;
1304 system_void_expr.Type = void_type;
1305 system_asynccallback_expr.Type = asynccallback_type;
1306 system_iasyncresult_expr.Type = iasyncresult_type;
1307 system_valuetype_expr.Type = value_type;
1310 // These are only used for compare purposes
1312 anonymous_method_type = typeof (AnonymousMethod);
1313 null_type = typeof (NullType);
1317 // The helper methods that are used by the compiler
1319 public static void InitCodeHelpers ()
1322 // Now load the default methods that we use.
1324 Type [] string_string = { string_type, string_type };
1325 string_concat_string_string = GetMethod (
1326 string_type, "Concat", string_string);
1327 Type [] string_string_string = { string_type, string_type, string_type };
1328 string_concat_string_string_string = GetMethod (
1329 string_type, "Concat", string_string_string);
1330 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1331 string_concat_string_string_string_string = GetMethod (
1332 string_type, "Concat", string_string_string_string);
1333 Type[] params_string = { TypeManager.LookupType ("System.String[]") };
1334 string_concat_string_dot_dot_dot = GetMethod (
1335 string_type, "Concat", params_string);
1337 Type [] object_object = { object_type, object_type };
1338 string_concat_object_object = GetMethod (
1339 string_type, "Concat", object_object);
1340 Type [] object_object_object = { object_type, object_type, object_type };
1341 string_concat_object_object_object = GetMethod (
1342 string_type, "Concat", object_object_object);
1343 Type[] params_object = { TypeManager.LookupType ("System.Object[]") };
1344 string_concat_object_dot_dot_dot = GetMethod (
1345 string_type, "Concat", params_object);
1347 Type [] string_ = { string_type };
1348 string_isinterneted_string = GetMethod (
1349 string_type, "IsInterned", string_);
1351 Type [] runtime_type_handle = { runtime_handle_type };
1352 system_type_get_type_from_handle = GetMethod (
1353 type_type, "GetTypeFromHandle", runtime_type_handle);
1355 Type [] delegate_delegate = { delegate_type, delegate_type };
1356 delegate_combine_delegate_delegate = GetMethod (
1357 delegate_type, "Combine", delegate_delegate);
1359 delegate_remove_delegate_delegate = GetMethod (
1360 delegate_type, "Remove", delegate_delegate);
1365 Type [] void_arg = { };
1366 object_getcurrent_void = GetMethod (
1367 ienumerator_type, "get_Current", void_arg);
1368 bool_movenext_void = GetMethod (
1369 ienumerator_type, "MoveNext", void_arg);
1370 void_reset_void = GetMethod (
1371 ienumerator_type, "Reset", void_arg);
1372 void_dispose_void = GetMethod (
1373 idisposable_type, "Dispose", void_arg);
1374 int_get_offset_to_string_data = GetMethod (
1375 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1376 int_array_get_length = GetMethod (
1377 array_type, "get_Length", void_arg);
1378 int_array_get_rank = GetMethod (
1379 array_type, "get_Rank", void_arg);
1380 ienumerable_getenumerator_void = GetMethod (
1381 ienumerable_type, "GetEnumerator", void_arg);
1386 Type [] int_arg = { int32_type };
1387 int_array_get_length_int = GetMethod (
1388 array_type, "GetLength", int_arg);
1389 int_array_get_upper_bound_int = GetMethod (
1390 array_type, "GetUpperBound", int_arg);
1391 int_array_get_lower_bound_int = GetMethod (
1392 array_type, "GetLowerBound", int_arg);
1395 // System.Array methods
1397 object_array_clone = GetMethod (
1398 array_type, "Clone", void_arg);
1399 Type [] array_int_arg = { array_type, int32_type };
1400 void_array_copyto_array_int = GetMethod (
1401 array_type, "CopyTo", array_int_arg);
1406 Type [] object_arg = { object_type };
1407 void_monitor_enter_object = GetMethod (
1408 monitor_type, "Enter", object_arg);
1409 void_monitor_exit_object = GetMethod (
1410 monitor_type, "Exit", object_arg);
1412 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1414 void_initializearray_array_fieldhandle = GetMethod (
1415 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1420 int_getlength_int = GetMethod (
1421 array_type, "GetLength", int_arg);
1424 // Decimal constructors
1426 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1427 void_decimal_ctor_five_args = GetConstructor (
1428 decimal_type, dec_arg);
1433 cons_param_array_attribute = GetConstructor (
1434 param_array_type, void_arg);
1436 unverifiable_code_ctor = GetConstructor (
1437 unverifiable_code_type, void_arg);
1439 default_member_ctor = GetConstructor (default_member_type, string_);
1442 // InvalidOperationException
1444 invalid_operation_ctor = GetConstructor (
1445 invalid_operation_exception_type, void_arg);
1449 object_ctor = GetConstructor (object_type, void_arg);
1452 Type [] type_arg = { type_type };
1453 activator_create_instance = GetMethod (
1454 activator_type, "CreateInstance", type_arg);
1457 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1460 /// This is the "old", non-cache based FindMembers() function. We cannot use
1461 /// the cache here because there is no member name argument.
1463 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1464 MemberFilter filter, object criteria)
1466 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1469 // `builder_to_declspace' contains all dynamic types.
1473 Timer.StartTimer (TimerType.FindMembers);
1474 list = decl.FindMembers (mt, bf, filter, criteria);
1475 Timer.StopTimer (TimerType.FindMembers);
1480 // We have to take care of arrays specially, because GetType on
1481 // a TypeBuilder array will return a Type, not a TypeBuilder,
1482 // and we can not call FindMembers on this type.
1484 if (t.IsSubclassOf (TypeManager.array_type))
1485 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1487 if (t is GenericTypeParameterBuilder) {
1488 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1490 Timer.StartTimer (TimerType.FindMembers);
1491 MemberList list = tparam.FindMembers (
1492 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1493 Timer.StopTimer (TimerType.FindMembers);
1498 // Since FindMembers will not lookup both static and instance
1499 // members, we emulate this behaviour here.
1501 if ((bf & instance_and_static) == instance_and_static){
1502 MemberInfo [] i_members = t.FindMembers (
1503 mt, bf & ~BindingFlags.Static, filter, criteria);
1505 int i_len = i_members.Length;
1507 MemberInfo one = i_members [0];
1510 // If any of these are present, we are done!
1512 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1513 return new MemberList (i_members);
1516 MemberInfo [] s_members = t.FindMembers (
1517 mt, bf & ~BindingFlags.Instance, filter, criteria);
1519 int s_len = s_members.Length;
1520 if (i_len > 0 || s_len > 0)
1521 return new MemberList (i_members, s_members);
1524 return new MemberList (i_members);
1526 return new MemberList (s_members);
1530 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1535 /// This method is only called from within MemberLookup. It tries to use the member
1536 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1537 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1538 /// our return value will already contain all inherited members and the caller don't need
1539 /// to check base classes and interfaces anymore.
1541 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1542 string name, out bool used_cache)
1547 // We have to take care of arrays specially, because GetType on
1548 // a TypeBuilder array will return a Type, not a TypeBuilder,
1549 // and we can not call FindMembers on this type.
1551 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1553 return TypeHandle.ArrayType.MemberCache.FindMembers (
1554 mt, bf, name, FilterWithClosure_delegate, null);
1558 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1559 // and we can ask the DeclSpace for the MemberCache.
1561 if (t is TypeBuilder) {
1562 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1563 cache = decl.MemberCache;
1566 // If this DeclSpace has a MemberCache, use it.
1569 if (cache != null) {
1571 return cache.FindMembers (
1572 mt, bf, name, FilterWithClosure_delegate, null);
1575 // If there is no MemberCache, we need to use the "normal" FindMembers.
1576 // Note, this is a VERY uncommon route!
1579 Timer.StartTimer (TimerType.FindMembers);
1580 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1581 FilterWithClosure_delegate, name);
1582 Timer.StopTimer (TimerType.FindMembers);
1584 return (MemberInfo []) list;
1587 if (t is GenericTypeParameterBuilder) {
1588 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1591 Timer.StartTimer (TimerType.FindMembers);
1592 list = tparam.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1593 FilterWithClosure_delegate, name);
1594 Timer.StopTimer (TimerType.FindMembers);
1596 return (MemberInfo []) list;
1600 // This call will always succeed. There is exactly one TypeHandle instance per
1601 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1602 // the corresponding MemberCache.
1604 cache = TypeHandle.GetMemberCache (t);
1607 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1610 public static bool IsBuiltinType (Type t)
1612 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1613 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1614 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1615 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1621 public static bool IsBuiltinType (TypeContainer tc)
1623 return IsBuiltinType (tc.TypeBuilder);
1627 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1628 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1630 public static bool IsCLRType (Type t)
1632 if (t == object_type || t == int32_type || t == uint32_type ||
1633 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1634 t == char_type || t == short_type || t == bool_type ||
1635 t == sbyte_type || t == byte_type || t == ushort_type)
1641 public static bool IsDelegateType (Type t)
1643 if (t.IsGenericInstance)
1644 t = t.GetGenericTypeDefinition ();
1646 if (t.IsSubclassOf (TypeManager.delegate_type))
1652 public static bool IsEnumType (Type t)
1654 if (t.IsSubclassOf (TypeManager.enum_type))
1659 public static bool IsBuiltinOrEnum (Type t)
1661 if (IsBuiltinType (t))
1670 public static bool IsNullType (Type t)
1672 return t == null_type;
1676 // Only a quick hack to get things moving, while real runtime support appears
1678 public static bool IsGeneric (Type t)
1680 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1682 return ds.IsGeneric;
1685 public static bool HasGenericArguments (Type t)
1687 return GetNumberOfTypeArguments (t) > 0;
1690 public static int GetNumberOfTypeArguments (Type t)
1692 DeclSpace tc = LookupDeclSpace (t);
1694 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1696 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1699 public static Type[] GetTypeArguments (Type t)
1701 DeclSpace tc = LookupDeclSpace (t);
1704 throw new InvalidOperationException ();
1706 TypeParameter[] tparam = tc.TypeParameters;
1707 Type[] ret = new Type [tparam.Length];
1708 for (int i = 0; i < tparam.Length; i++) {
1709 ret [i] = tparam [i].Type;
1710 if (ret [i] == null)
1711 throw new InternalErrorException ();
1716 return t.GetGenericArguments ();
1720 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1722 public static bool IsUnmanagedType (Type t)
1724 if (IsBuiltinType (t) && t != TypeManager.string_type)
1733 if (IsValueType (t)){
1734 if (t is TypeBuilder){
1735 TypeContainer tc = LookupTypeContainer (t);
1737 if (tc.Fields != null){
1738 foreach (Field f in tc.Fields){
1739 if (f.FieldBuilder.IsStatic)
1741 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1747 FieldInfo [] fields = t.GetFields ();
1749 foreach (FieldInfo f in fields){
1752 if (!IsUnmanagedType (f.FieldType))
1762 public static bool IsValueType (Type t)
1764 return t.IsGenericParameter || t.IsValueType;
1767 public static bool IsInterfaceType (Type t)
1769 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1773 return tc.Kind == Kind.Interface;
1776 public static bool IsEqual (Type a, Type b)
1781 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1783 // `a' is a generic type definition's TypeBuilder and `b' is a
1784 // generic instance of the same type.
1790 // void Test (Stack<T> stack) { }
1793 // The first argument of `Test' will be the generic instance
1794 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1797 // We hit this via Closure.Filter() for gen-82.cs.
1799 if (a != b.GetGenericTypeDefinition ())
1802 Type[] aparams = a.GetGenericArguments ();
1803 Type[] bparams = b.GetGenericArguments ();
1805 if (aparams.Length != bparams.Length)
1808 for (int i = 0; i < aparams.Length; i++)
1809 if (!IsEqual (aparams [i], bparams [i]))
1815 if (a.IsGenericParameter && b.IsGenericParameter) {
1816 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1818 return a.GenericParameterPosition == b.GenericParameterPosition;
1821 if (a.IsArray && b.IsArray) {
1822 if (a.GetArrayRank () != b.GetArrayRank ())
1824 return IsEqual (a.GetElementType (), b.GetElementType ());
1827 if (a.IsGenericInstance && b.IsGenericInstance) {
1828 Type at = a.GetGenericTypeDefinition ();
1829 Type bt = b.GetGenericTypeDefinition ();
1831 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1834 Type[] aargs = a.GetGenericArguments ();
1835 Type[] bargs = b.GetGenericArguments ();
1837 if (aargs.Length != bargs.Length)
1840 for (int i = 0; i < aargs.Length; i++) {
1841 if (!IsEqual (aargs [i], bargs [i]))
1851 public static bool MayBecomeEqualGenericTypes (Type a, Type b)
1853 if (a.IsGenericParameter) {
1855 // If a is an array of a's type, they may never
1859 b = b.GetElementType ();
1865 // If b is a generic parameter or an actual type,
1866 // they may become equal:
1868 // class X<T,U> : I<T>, I<U>
1869 // class X<T> : I<T>, I<float>
1871 if (b.IsGenericParameter || !b.IsGenericInstance)
1875 // We're now comparing a type parameter with a
1876 // generic instance. They may become equal unless
1877 // the type parameter appears anywhere in the
1878 // generic instance:
1880 // class X<T,U> : I<T>, I<X<U>>
1881 // -> error because you could instanciate it as
1884 // class X<T> : I<T>, I<X<T>> -> ok
1887 Type[] bargs = GetTypeArguments (b);
1888 for (int i = 0; i < bargs.Length; i++) {
1889 if (a.Equals (bargs [i]))
1896 if (b.IsGenericParameter)
1897 return MayBecomeEqualGenericTypes (b, a);
1900 // At this point, neither a nor b are a type parameter.
1902 // If one of them is a generic instance, let
1903 // MayBecomeEqualGenericInstances() compare them (if the
1904 // other one is not a generic instance, they can never
1908 if (a.IsGenericInstance || b.IsGenericInstance)
1909 return MayBecomeEqualGenericInstances (a, b);
1912 // If both of them are arrays.
1915 if (a.IsArray && b.IsArray) {
1916 if (a.GetArrayRank () != b.GetArrayRank ())
1919 a = a.GetElementType ();
1920 b = b.GetElementType ();
1922 return MayBecomeEqualGenericTypes (a, b);
1926 // Ok, two ordinary types.
1929 return a.Equals (b);
1933 // Checks whether two generic instances may become equal for some
1934 // particular instantiation (26.3.1).
1936 public static bool MayBecomeEqualGenericInstances (Type a, Type b)
1938 if (!a.IsGenericInstance || !b.IsGenericInstance)
1940 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1943 Type[] aargs = GetTypeArguments (a);
1944 Type[] bargs = GetTypeArguments (b);
1946 if (aargs.Length != bargs.Length)
1949 for (int i = 0; i < aargs.Length; i++) {
1950 if (MayBecomeEqualGenericTypes (aargs [i], bargs [i]))
1957 public static bool IsEqualGenericInstance (Type type, Type parent)
1959 int tcount = GetNumberOfTypeArguments (type);
1960 int pcount = GetNumberOfTypeArguments (parent);
1962 if (type.IsGenericInstance)
1963 type = type.GetGenericTypeDefinition ();
1964 if (parent.IsGenericInstance)
1965 parent = parent.GetGenericTypeDefinition ();
1967 if (tcount != pcount)
1970 return type.Equals (parent);
1973 public static bool IsSubclassOf (Type type, Type parent)
1975 TypeParameter tparam = LookupTypeParameter (type);
1976 TypeParameter pparam = LookupTypeParameter (parent);
1978 if ((tparam != null) && (pparam != null)) {
1979 if (tparam == pparam)
1982 return tparam.IsSubclassOf (parent);
1986 if (type.Equals (parent))
1989 type = type.BaseType;
1990 } while (type != null);
1995 public static bool IsPrivateAccessible (Type type, Type parent)
1997 if (type.Equals (parent))
2000 if ((type is TypeBuilder) && type.IsGenericTypeDefinition && parent.IsGenericInstance) {
2002 // `a' is a generic type definition's TypeBuilder and `b' is a
2003 // generic instance of the same type.
2009 // void Test (Stack<T> stack) { }
2012 // The first argument of `Test' will be the generic instance
2013 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
2016 // We hit this via Closure.Filter() for gen-82.cs.
2018 if (type != parent.GetGenericTypeDefinition ())
2024 if (type.IsGenericInstance && parent.IsGenericInstance) {
2025 Type tdef = type.GetGenericTypeDefinition ();
2026 Type pdef = parent.GetGenericTypeDefinition ();
2028 if (type.GetGenericTypeDefinition () != parent.GetGenericTypeDefinition ())
2037 public static bool IsFamilyAccessible (Type type, Type parent)
2039 TypeParameter tparam = LookupTypeParameter (type);
2040 TypeParameter pparam = LookupTypeParameter (parent);
2042 if ((tparam != null) && (pparam != null)) {
2043 if (tparam == pparam)
2046 return tparam.IsSubclassOf (parent);
2050 if (IsEqualGenericInstance (type, parent))
2053 type = type.BaseType;
2054 } while (type != null);
2060 // Checks whether `type' is a subclass or nested child of `parent'.
2062 public static bool IsNestedFamilyAccessible (Type type, Type parent)
2065 if (IsFamilyAccessible (type, parent))
2068 // Handle nested types.
2069 type = type.DeclaringType;
2070 } while (type != null);
2076 // Checks whether `type' is a nested child of `parent'.
2078 public static bool IsNestedChildOf (Type type, Type parent)
2080 if (IsEqual (type, parent))
2083 type = type.DeclaringType;
2084 while (type != null) {
2085 if (IsEqual (type, parent))
2088 type = type.DeclaringType;
2095 // Do the right thing when returning the element type of an
2096 // array type based on whether we are compiling corlib or not
2098 public static Type GetElementType (Type t)
2100 if (RootContext.StdLib)
2101 return t.GetElementType ();
2103 return TypeToCoreType (t.GetElementType ());
2107 /// Returns the User Defined Types
2109 public static ArrayList UserTypes {
2115 public static Hashtable TypeContainers {
2117 return typecontainers;
2121 static Hashtable builder_to_constant;
2123 public static void RegisterConstant (FieldBuilder fb, Const c)
2125 if (builder_to_constant == null)
2126 builder_to_constant = new PtrHashtable ();
2128 if (builder_to_constant.Contains (fb))
2131 builder_to_constant.Add (fb, c);
2134 public static Const LookupConstant (FieldBuilder fb)
2136 if (builder_to_constant == null)
2139 return (Const) builder_to_constant [fb];
2143 /// Gigantic work around for missing features in System.Reflection.Emit follows.
2147 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
2148 /// for anything which is dynamic, and we need this in a number of places,
2149 /// we register this information here, and use it afterwards.
2151 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
2156 method_arguments.Add (mb, args);
2157 method_internal_params.Add (mb, ip);
2160 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
2162 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
2165 if (method_internal_params.Contains (mb))
2166 return (InternalParameters) method_internal_params [mb];
2168 throw new Exception ("Argument for Method not registered" + mb);
2172 /// Returns the argument types for a method based on its methodbase
2174 /// For dynamic methods, we use the compiler provided types, for
2175 /// methods from existing assemblies we load them from GetParameters,
2176 /// and insert them into the cache
2178 static public Type [] GetArgumentTypes (MethodBase mb)
2180 object t = method_arguments [mb];
2184 ParameterInfo [] pi = mb.GetParameters ();
2191 types = new Type [c];
2192 for (int i = 0; i < c; i++)
2193 types [i] = pi [i].ParameterType;
2195 method_arguments.Add (mb, types);
2200 /// Returns the argument types for an indexer based on its PropertyInfo
2202 /// For dynamic indexers, we use the compiler provided types, for
2203 /// indexers from existing assemblies we load them from GetParameters,
2204 /// and insert them into the cache
2206 static public Type [] GetArgumentTypes (PropertyInfo indexer)
2208 if (indexer_arguments.Contains (indexer))
2209 return (Type []) indexer_arguments [indexer];
2210 else if (indexer is PropertyBuilder)
2211 // If we're a PropertyBuilder and not in the
2212 // `indexer_arguments' hash, then we're a property and
2216 ParameterInfo [] pi = indexer.GetIndexParameters ();
2217 // Property, not an indexer.
2221 Type [] types = new Type [c];
2223 for (int i = 0; i < c; i++)
2224 types [i] = pi [i].ParameterType;
2226 indexer_arguments.Add (indexer, types);
2232 // This is a workaround the fact that GetValue is not
2233 // supported for dynamic types
2235 static Hashtable fields = new Hashtable ();
2236 static public bool RegisterFieldValue (FieldBuilder fb, object value)
2238 if (fields.Contains (fb))
2241 fields.Add (fb, value);
2246 static public object GetValue (FieldBuilder fb)
2251 static Hashtable fieldbuilders_to_fields = new Hashtable ();
2252 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
2254 if (fieldbuilders_to_fields.Contains (fb))
2257 fieldbuilders_to_fields.Add (fb, f);
2262 // The return value can be null; This will be the case for
2263 // auxiliary FieldBuilders created by the compiler that have no
2264 // real field being declared on the source code
2266 static public FieldBase GetField (FieldInfo fb)
2268 return (FieldBase) fieldbuilders_to_fields [fb];
2271 static Hashtable events;
2273 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
2276 events = new Hashtable ();
2278 if (!events.Contains (eb)) {
2279 events.Add (eb, new Pair (add, remove));
2283 static public MethodInfo GetAddMethod (EventInfo ei)
2285 if (ei is MyEventBuilder) {
2286 Pair pair = (Pair) events [ei];
2288 return (MethodInfo) pair.First;
2290 return ei.GetAddMethod (true);
2293 static public MethodInfo GetRemoveMethod (EventInfo ei)
2295 if (ei is MyEventBuilder) {
2296 Pair pair = (Pair) events [ei];
2298 return (MethodInfo) pair.Second;
2300 return ei.GetRemoveMethod (true);
2303 static Hashtable priv_fields_events;
2305 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
2307 if (priv_fields_events == null)
2308 priv_fields_events = new Hashtable ();
2310 if (priv_fields_events.Contains (einfo))
2313 priv_fields_events.Add (einfo, builder);
2318 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
2320 if (priv_fields_events == null)
2323 return (MemberInfo) priv_fields_events [ei];
2326 static Hashtable properties;
2328 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
2330 if (properties == null)
2331 properties = new Hashtable ();
2333 if (properties.Contains (pb))
2336 properties.Add (pb, new Pair (get, set));
2341 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2342 MethodBase set, Type[] args)
2344 if (!RegisterProperty (pb, get,set))
2347 indexer_arguments.Add (pb, args);
2352 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2354 Hashtable hash = new Hashtable ();
2355 return CheckStructCycles (tc, seen, hash);
2358 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2361 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2365 // `seen' contains all types we've already visited.
2367 if (seen.Contains (tc))
2369 seen.Add (tc, null);
2371 if (tc.Fields == null)
2374 foreach (Field field in tc.Fields) {
2375 if (field.FieldBuilder.IsStatic)
2378 Type ftype = field.FieldBuilder.FieldType;
2379 TypeContainer ftc = LookupTypeContainer (ftype);
2383 if (hash.Contains (ftc)) {
2384 Report.Error (523, tc.Location,
2385 "Struct member `{0}.{1}' of type `{2}' " +
2386 "causes a cycle in the struct layout",
2387 tc.Name, field.Name, ftc.Name);
2392 // `hash' contains all types in the current path.
2394 hash.Add (tc, null);
2396 bool ok = CheckStructCycles (ftc, seen, hash);
2403 if (!seen.Contains (ftc))
2404 seen.Add (ftc, null);
2411 /// Given an array of interface types, expand and eliminate repeated ocurrences
2412 /// of an interface.
2416 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2419 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2421 ArrayList new_ifaces = new ArrayList ();
2423 foreach (TypeExpr iface in base_interfaces){
2424 TypeExpr texpr = iface.ResolveAsTypeTerminal (ec);
2428 if (!new_ifaces.Contains (texpr.Type))
2429 new_ifaces.Add (texpr.Type);
2431 Type [] implementing = texpr.Type.GetInterfaces ();
2433 foreach (Type imp in implementing){
2434 if (!new_ifaces.Contains (imp))
2435 new_ifaces.Add (imp);
2438 Type [] ret = new Type [new_ifaces.Count];
2439 new_ifaces.CopyTo (ret, 0);
2443 static PtrHashtable iface_cache = new PtrHashtable ();
2446 /// This function returns the interfaces in the type `t'. Works with
2447 /// both types and TypeBuilders.
2449 public static Type [] GetInterfaces (Type t)
2452 Type [] cached = iface_cache [t] as Type [];
2457 // The reason for catching the Array case is that Reflection.Emit
2458 // will not return a TypeBuilder for Array types of TypeBuilder types,
2459 // but will still throw an exception if we try to call GetInterfaces
2462 // Since the array interfaces are always constant, we return those for
2467 t = TypeManager.array_type;
2469 if (t is TypeBuilder){
2470 Type[] parent_ifaces;
2472 if (t.BaseType == null)
2473 parent_ifaces = NoTypes;
2475 parent_ifaces = GetInterfaces (t.BaseType);
2476 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2477 if (type_ifaces == null)
2478 type_ifaces = NoTypes;
2480 int parent_count = parent_ifaces.Length;
2481 Type[] result = new Type [parent_count + type_ifaces.Length];
2482 parent_ifaces.CopyTo (result, 0);
2483 type_ifaces.CopyTo (result, parent_count);
2485 iface_cache [t] = result;
2487 } else if (t is GenericTypeParameterBuilder){
2488 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2489 if (type_ifaces == null)
2490 type_ifaces = NoTypes;
2492 iface_cache [t] = type_ifaces;
2495 Type[] ifaces = t.GetInterfaces ();
2496 iface_cache [t] = ifaces;
2502 // gets the interfaces that are declared explicitly on t
2504 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2506 return (Type []) builder_to_ifaces [t];
2510 /// The following is used to check if a given type implements an interface.
2511 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2513 public static bool ImplementsInterface (Type t, Type iface)
2518 // FIXME OPTIMIZATION:
2519 // as soon as we hit a non-TypeBuiler in the interface
2520 // chain, we could return, as the `Type.GetInterfaces'
2521 // will return all the interfaces implement by the type
2525 interfaces = GetInterfaces (t);
2527 if (interfaces != null){
2528 foreach (Type i in interfaces){
2535 } while (t != null);
2540 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2542 // This is a custom version of Convert.ChangeType() which works
2543 // with the TypeBuilder defined types when compiling corlib.
2544 public static object ChangeType (object value, Type conversionType, out bool error)
2546 IConvertible convert_value = value as IConvertible;
2548 if (convert_value == null){
2554 // We must use Type.Equals() here since `conversionType' is
2555 // the TypeBuilder created version of a system type and not
2556 // the system type itself. You cannot use Type.GetTypeCode()
2557 // on such a type - it'd always return TypeCode.Object.
2561 if (conversionType.Equals (typeof (Boolean)))
2562 return (object)(convert_value.ToBoolean (nf_provider));
2563 else if (conversionType.Equals (typeof (Byte)))
2564 return (object)(convert_value.ToByte (nf_provider));
2565 else if (conversionType.Equals (typeof (Char)))
2566 return (object)(convert_value.ToChar (nf_provider));
2567 else if (conversionType.Equals (typeof (DateTime)))
2568 return (object)(convert_value.ToDateTime (nf_provider));
2569 else if (conversionType.Equals (typeof (Decimal)))
2570 return (object)(convert_value.ToDecimal (nf_provider));
2571 else if (conversionType.Equals (typeof (Double)))
2572 return (object)(convert_value.ToDouble (nf_provider));
2573 else if (conversionType.Equals (typeof (Int16)))
2574 return (object)(convert_value.ToInt16 (nf_provider));
2575 else if (conversionType.Equals (typeof (Int32)))
2576 return (object)(convert_value.ToInt32 (nf_provider));
2577 else if (conversionType.Equals (typeof (Int64)))
2578 return (object)(convert_value.ToInt64 (nf_provider));
2579 else if (conversionType.Equals (typeof (SByte)))
2580 return (object)(convert_value.ToSByte (nf_provider));
2581 else if (conversionType.Equals (typeof (Single)))
2582 return (object)(convert_value.ToSingle (nf_provider));
2583 else if (conversionType.Equals (typeof (String)))
2584 return (object)(convert_value.ToString (nf_provider));
2585 else if (conversionType.Equals (typeof (UInt16)))
2586 return (object)(convert_value.ToUInt16 (nf_provider));
2587 else if (conversionType.Equals (typeof (UInt32)))
2588 return (object)(convert_value.ToUInt32 (nf_provider));
2589 else if (conversionType.Equals (typeof (UInt64)))
2590 return (object)(convert_value.ToUInt64 (nf_provider));
2591 else if (conversionType.Equals (typeof (Object)))
2592 return (object)(value);
2602 // This is needed, because enumerations from assemblies
2603 // do not report their underlyingtype, but they report
2606 public static Type EnumToUnderlying (Type t)
2608 if (t == TypeManager.enum_type)
2611 t = t.UnderlyingSystemType;
2612 if (!TypeManager.IsEnumType (t))
2615 if (t is TypeBuilder) {
2616 // slow path needed to compile corlib
2617 if (t == TypeManager.bool_type ||
2618 t == TypeManager.byte_type ||
2619 t == TypeManager.sbyte_type ||
2620 t == TypeManager.char_type ||
2621 t == TypeManager.short_type ||
2622 t == TypeManager.ushort_type ||
2623 t == TypeManager.int32_type ||
2624 t == TypeManager.uint32_type ||
2625 t == TypeManager.int64_type ||
2626 t == TypeManager.uint64_type)
2628 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2630 TypeCode tc = Type.GetTypeCode (t);
2633 case TypeCode.Boolean:
2634 return TypeManager.bool_type;
2636 return TypeManager.byte_type;
2637 case TypeCode.SByte:
2638 return TypeManager.sbyte_type;
2640 return TypeManager.char_type;
2641 case TypeCode.Int16:
2642 return TypeManager.short_type;
2643 case TypeCode.UInt16:
2644 return TypeManager.ushort_type;
2645 case TypeCode.Int32:
2646 return TypeManager.int32_type;
2647 case TypeCode.UInt32:
2648 return TypeManager.uint32_type;
2649 case TypeCode.Int64:
2650 return TypeManager.int64_type;
2651 case TypeCode.UInt64:
2652 return TypeManager.uint64_type;
2654 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2658 // When compiling corlib and called with one of the core types, return
2659 // the corresponding typebuilder for that type.
2661 public static Type TypeToCoreType (Type t)
2663 if (RootContext.StdLib || (t is TypeBuilder))
2666 TypeCode tc = Type.GetTypeCode (t);
2669 case TypeCode.Boolean:
2670 return TypeManager.bool_type;
2672 return TypeManager.byte_type;
2673 case TypeCode.SByte:
2674 return TypeManager.sbyte_type;
2676 return TypeManager.char_type;
2677 case TypeCode.Int16:
2678 return TypeManager.short_type;
2679 case TypeCode.UInt16:
2680 return TypeManager.ushort_type;
2681 case TypeCode.Int32:
2682 return TypeManager.int32_type;
2683 case TypeCode.UInt32:
2684 return TypeManager.uint32_type;
2685 case TypeCode.Int64:
2686 return TypeManager.int64_type;
2687 case TypeCode.UInt64:
2688 return TypeManager.uint64_type;
2689 case TypeCode.Single:
2690 return TypeManager.float_type;
2691 case TypeCode.Double:
2692 return TypeManager.double_type;
2693 case TypeCode.String:
2694 return TypeManager.string_type;
2696 if (t == typeof (void))
2697 return TypeManager.void_type;
2698 if (t == typeof (object))
2699 return TypeManager.object_type;
2700 if (t == typeof (System.Type))
2701 return TypeManager.type_type;
2702 if (t == typeof (System.IntPtr))
2703 return TypeManager.intptr_type;
2709 /// Utility function that can be used to probe whether a type
2710 /// is managed or not.
2712 public static bool VerifyUnManaged (Type t, Location loc)
2714 if (t.IsValueType || t.IsPointer){
2716 // FIXME: this is more complex, we actually need to
2717 // make sure that the type does not contain any
2723 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
2724 // We need this explicit check here to make it work when
2725 // compiling corlib.
2730 "Cannot take the address or size of a variable of a managed type ('" +
2731 CSharpName (t) + "')");
2736 /// Returns the name of the indexer in a given type.
2739 /// The default is not always `Item'. The user can change this behaviour by
2740 /// using the IndexerNameAttribute in the container.
2742 /// For example, the String class indexer is named `Chars' not `Item'
2744 public static string IndexerPropertyName (Type t)
2746 if (t.IsGenericInstance)
2747 t = t.GetGenericTypeDefinition ();
2749 if (t is TypeBuilder) {
2750 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2751 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2754 System.Attribute attr = System.Attribute.GetCustomAttribute (
2755 t, TypeManager.default_member_type);
2757 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2758 return dma.MemberName;
2761 return TypeContainer.DefaultIndexerName;
2764 static MethodInfo declare_local_method = null;
2766 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2768 if (declare_local_method == null){
2769 declare_local_method = typeof (ILGenerator).GetMethod (
2771 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2773 new Type [] { typeof (Type), typeof (bool)},
2775 if (declare_local_method == null){
2776 Report.Warning (-24, new Location (-1),
2777 "This version of the runtime does not support making pinned local variables. " +
2778 "This code may cause errors on a runtime with a moving GC");
2779 return ig.DeclareLocal (t);
2782 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2786 // Returns whether the array of memberinfos contains the given method
2788 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2790 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2792 foreach (MethodBase method in array) {
2793 if (method.Name != new_method.Name)
2796 if (method is MethodInfo && new_method is MethodInfo)
2797 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2801 Type [] old_args = TypeManager.GetArgumentTypes (method);
2802 int old_count = old_args.Length;
2805 if (new_args.Length != old_count)
2808 for (i = 0; i < old_count; i++){
2809 if (old_args [i] != new_args [i])
2822 // We copy methods from `new_members' into `target_list' if the signature
2823 // for the method from in the new list does not exist in the target_list
2825 // The name is assumed to be the same.
2827 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2829 if (target_list == null){
2830 target_list = new ArrayList ();
2832 foreach (MemberInfo mi in new_members){
2833 if (mi is MethodBase)
2834 target_list.Add (mi);
2839 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2840 target_list.CopyTo (target_array, 0);
2842 foreach (MemberInfo mi in new_members){
2843 MethodBase new_method = (MethodBase) mi;
2845 if (!ArrayContainsMethod (target_array, new_method))
2846 target_list.Add (new_method);
2851 static public bool IsGenericMethod (MethodBase mb)
2853 if (mb.DeclaringType is TypeBuilder) {
2854 IMethodData method = (IMethodData) builder_to_method [mb];
2858 return method.GenericMethod != null;
2861 return mb.IsGenericMethodDefinition;
2864 #region MemberLookup implementation
2867 // Whether we allow private members in the result (since FindMembers
2868 // uses NonPublic for both protected and private), we need to distinguish.
2871 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2876 internal class Closure {
2877 internal bool private_ok;
2879 // Who is invoking us and which type is being queried currently.
2880 internal Type invocation_type;
2881 internal Type qualifier_type;
2883 // The assembly that defines the type is that is calling us
2884 internal Assembly invocation_assembly;
2885 internal IList almost_match;
2887 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2889 if (invocation_type == null)
2895 // A nested class has access to all the protected members visible
2897 if (qualifier_type != null
2898 && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2901 if (invocation_type == m.DeclaringType
2902 || invocation_type.IsSubclassOf (m.DeclaringType)) {
2903 // Although a derived class can access protected members of
2904 // its base class it cannot do so through an instance of the
2905 // base class (CS1540).
2906 // => Ancestry should be: declaring_type ->* invocation_type
2907 // ->* qualified_type
2908 if (qualifier_type == null
2909 || qualifier_type == invocation_type
2910 || qualifier_type.IsSubclassOf (invocation_type))
2914 if (almost_match != null)
2915 almost_match.Add (m);
2919 bool Filter (MethodBase mb, object filter_criteria)
2921 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2923 if (ma == MethodAttributes.Private)
2924 return private_ok ||
2925 IsPrivateAccessible (invocation_type, mb.DeclaringType) ||
2926 IsNestedChildOf (invocation_type, mb.DeclaringType);
2929 // FamAndAssem requires that we not only derivate, but we are on the
2932 if (ma == MethodAttributes.FamANDAssem){
2933 if (invocation_assembly != mb.DeclaringType.Assembly)
2937 // Assembly and FamORAssem succeed if we're in the same assembly.
2938 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2939 if (invocation_assembly == mb.DeclaringType.Assembly)
2943 // We already know that we aren't in the same assembly.
2944 if (ma == MethodAttributes.Assembly)
2947 // Family and FamANDAssem require that we derive.
2948 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
2949 if (invocation_type == null)
2952 if (!IsNestedFamilyAccessible (invocation_type, mb.DeclaringType))
2955 // Although a derived class can access protected members of its base class
2956 // it cannot do so through an instance of the base class (CS1540).
2957 if (!mb.IsStatic && (qualifier_type != null) &&
2958 !IsEqualGenericInstance (invocation_type, qualifier_type) &&
2959 TypeManager.IsFamilyAccessible (invocation_type, qualifier_type) &&
2960 !TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2970 bool Filter (FieldInfo fi, object filter_criteria)
2972 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2974 if (fa == FieldAttributes.Private)
2975 return private_ok ||
2976 IsPrivateAccessible (invocation_type, fi.DeclaringType) ||
2977 IsNestedChildOf (invocation_type, fi.DeclaringType);
2980 // FamAndAssem requires that we not only derivate, but we are on the
2983 if (fa == FieldAttributes.FamANDAssem){
2984 if (invocation_assembly != fi.DeclaringType.Assembly)
2988 // Assembly and FamORAssem succeed if we're in the same assembly.
2989 if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2990 if (invocation_assembly == fi.DeclaringType.Assembly)
2994 // We already know that we aren't in the same assembly.
2995 if (fa == FieldAttributes.Assembly)
2998 // Family and FamANDAssem require that we derive.
2999 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
3000 if (invocation_type == null)
3003 if (!IsNestedFamilyAccessible (invocation_type, fi.DeclaringType))
3006 // Although a derived class can access protected members of its base class
3007 // it cannot do so through an instance of the base class (CS1540).
3008 if (!fi.IsStatic && (qualifier_type != null) &&
3009 !IsEqualGenericInstance (invocation_type, qualifier_type) &&
3010 TypeManager.IsFamilyAccessible (invocation_type, qualifier_type) &&
3011 !TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
3022 // This filter filters by name + whether it is ok to include private
3023 // members in the search
3025 internal bool Filter (MemberInfo m, object filter_criteria)
3028 // Hack: we know that the filter criteria will always be in the
3029 // `closure' // fields.
3032 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
3035 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
3036 (invocation_type != null) &&
3037 IsPrivateAccessible (m.DeclaringType, invocation_type))
3041 // Ugly: we need to find out the type of `m', and depending
3042 // on this, tell whether we accept or not
3044 if (m is MethodBase)
3045 return Filter ((MethodBase) m, filter_criteria);
3048 return Filter ((FieldInfo) m, filter_criteria);
3051 // EventInfos and PropertyInfos, return true because they lack
3052 // permission information, so we need to check later on the methods.
3058 static Closure closure = new Closure ();
3059 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
3062 // Looks up a member called `name' in the `queried_type'. This lookup
3063 // is done by code that is contained in the definition for `invocation_type'
3064 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
3066 // `invocation_type' is used to check whether we're allowed to access the requested
3067 // member wrt its protection level.
3069 // When called from MemberAccess, `qualifier_type' is the type which is used to access
3070 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
3071 // is B and qualifier_type is A). This is used to do the CS1540 check.
3073 // When resolving a SimpleName, `qualifier_type' is null.
3075 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
3076 // the same than `queried_type' - except when we're being called from BaseAccess;
3077 // in this case, `invocation_type' is the current type and `queried_type' the base
3078 // type, so this'd normally trigger a CS1540.
3080 // The binding flags are `bf' and the kind of members being looked up are `mt'
3082 // The return value always includes private members which code in `invocation_type'
3083 // is allowed to access (using the specified `qualifier_type' if given); only use
3084 // BindingFlags.NonPublic to bypass the permission check.
3086 // The 'almost_match' argument is used for reporting error CS1540.
3088 // Returns an array of a single element for everything but Methods/Constructors
3089 // that might return multiple matches.
3091 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
3092 Type queried_type, MemberTypes mt,
3093 BindingFlags original_bf, string name, IList almost_match)
3095 Timer.StartTimer (TimerType.MemberLookup);
3097 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
3098 queried_type, mt, original_bf, name, almost_match);
3100 Timer.StopTimer (TimerType.MemberLookup);
3105 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
3106 Type queried_type, MemberTypes mt,
3107 BindingFlags original_bf, string name, IList almost_match)
3109 BindingFlags bf = original_bf;
3111 ArrayList method_list = null;
3112 Type current_type = queried_type;
3113 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
3114 bool skip_iface_check = true, used_cache = false;
3115 bool always_ok_flag = false;
3117 closure.invocation_type = invocation_type;
3118 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
3119 closure.qualifier_type = qualifier_type;
3120 closure.almost_match = almost_match;
3123 // If we are a nested class, we always have access to our container
3126 if (invocation_type != null){
3127 string invocation_name = invocation_type.FullName;
3128 if ((invocation_name != null) && (invocation_name.IndexOf ('+') != -1)){
3129 string container = queried_type.FullName + "+";
3130 int container_length = container.Length;
3132 if (invocation_name.Length > container_length){
3133 string shared = invocation_name.Substring (0, container_length);
3135 if (shared == container)
3136 always_ok_flag = true;
3141 // This is from the first time we find a method
3142 // in most cases, we do not actually find a method in the base class
3143 // so we can just ignore it, and save the arraylist allocation
3144 MemberInfo [] first_members_list = null;
3145 bool use_first_members_list = false;
3151 // `NonPublic' is lame, because it includes both protected and
3152 // private methods, so we need to control this behavior by
3153 // explicitly tracking if a private method is ok or not.
3155 // The possible cases are:
3156 // public, private and protected (internal does not come into the
3159 if ((invocation_type != null) &&
3160 ((invocation_type == current_type) ||
3161 IsNestedChildOf (invocation_type, current_type)) ||
3163 bf = original_bf | BindingFlags.NonPublic;
3167 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
3169 Timer.StopTimer (TimerType.MemberLookup);
3171 list = MemberLookup_FindMembers (
3172 current_type, mt, bf, name, out used_cache);
3174 Timer.StartTimer (TimerType.MemberLookup);
3177 // When queried for an interface type, the cache will automatically check all
3178 // inherited members, so we don't need to do this here. However, this only
3179 // works if we already used the cache in the first iteration of this loop.
3181 // If we used the cache in any further iteration, we can still terminate the
3182 // loop since the cache always looks in all parent classes.
3188 skip_iface_check = false;
3190 if (current_type == TypeManager.object_type)
3193 current_type = current_type.BaseType;
3196 // This happens with interfaces, they have a null
3197 // basetype. Look members up in the Object class.
3199 if (current_type == null) {
3200 current_type = TypeManager.object_type;
3205 if (list.Length == 0)
3209 // Events and types are returned by both `static' and `instance'
3210 // searches, which means that our above FindMembers will
3211 // return two copies of the same.
3213 if (list.Length == 1 && !(list [0] is MethodBase)){
3218 // Multiple properties: we query those just to find out the indexer
3221 if (list [0] is PropertyInfo)
3225 // We found an event: the cache lookup returns both the event and
3226 // its private field.
3228 if (list [0] is EventInfo) {
3229 if ((list.Length == 2) && (list [1] is FieldInfo))
3230 return new MemberInfo [] { list [0] };
3237 // We found methods, turn the search into "method scan"
3241 if (first_members_list != null) {
3242 if (use_first_members_list) {
3243 method_list = CopyNewMethods (method_list, first_members_list);
3244 use_first_members_list = false;
3247 method_list = CopyNewMethods (method_list, list);
3249 first_members_list = list;
3250 use_first_members_list = true;
3252 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3254 } while (searching);
3256 if (use_first_members_list) {
3257 foreach (MemberInfo mi in first_members_list) {
3258 if (! (mi is MethodBase)) {
3259 method_list = CopyNewMethods (method_list, first_members_list);
3260 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3263 return (MemberInfo []) first_members_list;
3266 if (method_list != null && method_list.Count > 0) {
3267 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3270 // This happens if we already used the cache in the first iteration, in this case
3271 // the cache already looked in all interfaces.
3273 if (skip_iface_check)
3277 // Interfaces do not list members they inherit, so we have to
3280 if (!queried_type.IsInterface)
3283 if (queried_type.IsArray)
3284 queried_type = TypeManager.array_type;
3286 Type [] ifaces = GetInterfaces (queried_type);
3290 foreach (Type itype in ifaces){
3293 x = MemberLookup (null, null, itype, mt, bf, name, null);
3301 // Tests whether external method is really special
3302 public static bool IsSpecialMethod (MethodBase mb)
3304 string name = mb.Name;
3305 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
3306 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
3308 if (name.StartsWith ("add_"))
3309 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
3311 if (name.StartsWith ("remove_"))
3312 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
3314 if (name.StartsWith ("op_")){
3315 foreach (string oname in Unary.oper_names) {
3320 foreach (string oname in Binary.oper_names) {
3333 /// There is exactly one instance of this class per type.
3335 public sealed class TypeHandle : IMemberContainer {
3336 public readonly TypeHandle BaseType;
3338 readonly int id = ++next_id;
3339 static int next_id = 0;
3342 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3343 /// a TypeHandle yet, a new instance of it is created. This static method
3344 /// ensures that we'll only have one TypeHandle instance per type.
3346 private static TypeHandle GetTypeHandle (Type t)
3348 TypeHandle handle = (TypeHandle) type_hash [t];
3352 handle = new TypeHandle (t);
3353 type_hash.Add (t, handle);
3357 public static MemberCache GetMemberCache (Type t)
3359 return GetTypeHandle (t).MemberCache;
3362 public static void CleanUp ()
3368 /// Returns the TypeHandle for TypeManager.object_type.
3370 public static IMemberContainer ObjectType {
3372 if (object_type != null)
3375 object_type = GetTypeHandle (TypeManager.object_type);
3382 /// Returns the TypeHandle for TypeManager.array_type.
3384 public static IMemberContainer ArrayType {
3386 if (array_type != null)
3389 array_type = GetTypeHandle (TypeManager.array_type);
3395 private static PtrHashtable type_hash = new PtrHashtable ();
3397 private static TypeHandle object_type = null;
3398 private static TypeHandle array_type = null;
3401 private string full_name;
3402 private bool is_interface;
3403 private MemberCache member_cache;
3404 private MemberCache parent_cache;
3406 private TypeHandle (Type type)
3409 full_name = type.FullName != null ? type.FullName : type.Name;
3410 if (type.BaseType != null) {
3411 BaseType = GetTypeHandle (type.BaseType);
3412 parent_cache = BaseType.MemberCache;
3413 } else if (type.IsInterface)
3414 parent_cache = TypeManager.LookupParentInterfacesCache (type);
3415 this.is_interface = type.IsInterface || type.IsGenericParameter;
3416 this.member_cache = new MemberCache (this);
3419 // IMemberContainer methods
3421 public string Name {
3433 public MemberCache ParentCache {
3435 return parent_cache;
3439 public bool IsInterface {
3441 return is_interface;
3445 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3447 MemberInfo [] members;
3448 if (type is GenericTypeParameterBuilder)
3449 return MemberList.Empty;
3450 if (mt == MemberTypes.Event)
3451 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3453 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3455 Array.Reverse (members);
3457 return new MemberList (members);
3460 // IMemberFinder methods
3462 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3463 MemberFilter filter, object criteria)
3465 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3468 public MemberCache MemberCache {
3470 return member_cache;
3474 public override string ToString ()
3476 if (BaseType != null)
3477 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3479 return "TypeHandle (" + id + "," + Name + ")";