2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
17 namespace Mono.CSharp {
19 public class TypeManager {
21 // A list of core types that the compiler requires or uses
23 static public Type object_type;
24 static public Type value_type;
25 static public Type string_type;
26 static public Type int32_type;
27 static public Type uint32_type;
28 static public Type int64_type;
29 static public Type uint64_type;
30 static public Type float_type;
31 static public Type double_type;
32 static public Type char_type;
33 static public Type char_ptr_type;
34 static public Type short_type;
35 static public Type decimal_type;
36 static public Type bool_type;
37 static public Type sbyte_type;
38 static public Type byte_type;
39 static public Type ushort_type;
40 static public Type enum_type;
41 static public Type delegate_type;
42 static public Type multicast_delegate_type;
43 static public Type void_type;
44 static public Type enumeration_type;
45 static public Type array_type;
46 static public Type runtime_handle_type;
47 static public Type icloneable_type;
48 static public Type type_type;
49 static public Type ienumerator_type;
50 static public Type idisposable_type;
51 static public Type default_member_type;
52 static public Type iasyncresult_type;
53 static public Type asynccallback_type;
54 static public Type intptr_type;
55 static public Type monitor_type;
56 static public Type runtime_field_handle_type;
57 static public Type attribute_usage_type;
58 static public Type dllimport_type;
59 static public Type unverifiable_code_type;
60 static public Type methodimpl_attr_type;
61 static public Type param_array_type;
62 static public Type void_ptr_type;
65 // Internal, not really used outside
67 Type runtime_helpers_type;
70 // These methods are called by code generated by the compiler
72 static public MethodInfo string_concat_string_string;
73 static public MethodInfo string_concat_object_object;
74 static public MethodInfo string_isinterneted_string;
75 static public MethodInfo system_type_get_type_from_handle;
76 static public MethodInfo object_getcurrent_void;
77 static public MethodInfo bool_movenext_void;
78 static public MethodInfo void_dispose_void;
79 static public MethodInfo void_monitor_enter_object;
80 static public MethodInfo void_monitor_exit_object;
81 static public MethodInfo void_initializearray_array_fieldhandle;
82 static public MethodInfo int_getlength_int;
83 static public MethodInfo delegate_combine_delegate_delegate;
84 static public MethodInfo delegate_remove_delegate_delegate;
85 static public MethodInfo int_get_offset_to_string_data;
88 // The attribute constructors.
90 static public ConstructorInfo cons_param_array_attribute;
93 // Holds the Array of Assemblies that have been loaded
94 // (either because it is the default or the user used the
95 // -r command line option)
100 // Keeps a list of module builders. We used this to do lookups
101 // on the modulebuilder using GetType -- needed for arrays
106 // This is the type_cache from the assemblies to avoid
107 // hitting System.Reflection on every lookup.
112 // This is used to hotld the corresponding TypeContainer objects
113 // since we need this in FindMembers
115 Hashtable typecontainers;
118 // Keeps track of those types that are defined by the
121 ArrayList user_types;
124 // Keeps a mapping between TypeBuilders and their TypeContainers
126 static PtrHashtable builder_to_container;
129 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
130 // the arguments to the method
132 static Hashtable method_arguments;
135 // Maybe `method_arguments' should be replaced and only
136 // method_internal_params should be kept?
138 static Hashtable method_internal_params;
140 static PtrHashtable builder_to_interface;
143 // Keeps track of delegate types
146 static Hashtable builder_to_delegate;
149 // Keeps track of enum types
152 static Hashtable builder_to_enum;
155 // Keeps track of attribute types
158 static Hashtable builder_to_attr;
160 public TypeManager ()
162 assemblies = new ArrayList ();
163 modules = new ArrayList ();
164 user_types = new ArrayList ();
165 types = new Hashtable ();
166 typecontainers = new Hashtable ();
167 builder_to_interface = new PtrHashtable ();
168 builder_to_delegate = new PtrHashtable ();
169 builder_to_enum = new PtrHashtable ();
170 builder_to_attr = new PtrHashtable ();
173 static TypeManager ()
175 method_arguments = new PtrHashtable ();
176 method_internal_params = new PtrHashtable ();
177 builder_to_container = new PtrHashtable ();
178 type_interface_cache = new PtrHashtable ();
181 public void AddUserType (string name, TypeBuilder t)
187 public void AddUserType (string name, TypeBuilder t, TypeContainer tc)
189 AddUserType (name, t);
190 builder_to_container.Add (t, tc);
191 typecontainers.Add (name, tc);
194 public void AddDelegateType (string name, TypeBuilder t, Delegate del)
197 builder_to_delegate.Add (t, del);
200 public void AddEnumType (string name, TypeBuilder t, Enum en)
203 builder_to_enum.Add (t, en);
206 public void AddUserInterface (string name, TypeBuilder t, Interface i)
208 AddUserType (name, t);
209 builder_to_interface.Add (t, i);
212 public void RegisterAttrType (Type t, TypeContainer tc)
214 builder_to_attr.Add (t, tc);
218 /// Returns the TypeContainer whose Type is `t' or null if there is no
219 /// TypeContainer for `t' (ie, the Type comes from a library)
221 public static TypeContainer LookupTypeContainer (Type t)
223 return (TypeContainer) builder_to_container [t];
226 public Interface LookupInterface (Type t)
228 return (Interface) builder_to_interface [t];
231 public static Delegate LookupDelegate (Type t)
233 return (Delegate) builder_to_delegate [t];
236 public static Enum LookupEnum (Type t)
238 return (Enum) builder_to_enum [t];
241 public static TypeContainer LookupAttr (Type t)
243 return (TypeContainer) builder_to_attr [t];
247 /// Registers an assembly to load types from.
249 public void AddAssembly (Assembly a)
255 /// Registers a module builder to lookup types from
257 public void AddModule (ModuleBuilder mb)
263 /// Returns the Type associated with @name
265 public Type LookupType (string name)
270 // First lookup in user defined and cached values
273 t = (Type) types [name];
277 foreach (Assembly a in assemblies){
278 t = a.GetType (name);
286 foreach (ModuleBuilder mb in modules) {
287 t = mb.GetType (name);
298 /// Returns the C# name of a type if possible, or the full type name otherwise
300 static public string CSharpName (Type t)
304 else if (t == uint32_type)
306 else if (t == int64_type)
308 else if (t == uint64_type)
310 else if (t == float_type)
312 else if (t == double_type)
314 else if (t == char_type)
316 else if (t == short_type)
318 else if (t == decimal_type)
320 else if (t == bool_type)
322 else if (t == sbyte_type)
324 else if (t == byte_type)
326 else if (t == short_type)
328 else if (t == ushort_type)
330 else if (t == string_type)
332 else if (t == object_type)
334 else if (t == void_type)
341 /// Looks up a type, and aborts if it is not found. This is used
342 /// by types required by the compiler
344 Type CoreLookupType (string name)
346 Type t = LookupType (name);
349 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
350 Environment.Exit (0);
357 /// Returns the MethodInfo for a method named `name' defined
358 /// in type `t' which takes arguments of types `args'
360 MethodInfo GetMethod (Type t, string name, Type [] args)
362 MethodInfo mi = t.GetMethod (name, args);
365 throw new Exception ("Can not find the core function `" + name + "'");
370 ConstructorInfo GetConstructor (Type t, Type [] args)
372 ConstructorInfo ci = t.GetConstructor (args);
375 throw new Exception ("Can not find the core constructor for `" + t.FullName + "'");
381 /// The types have to be initialized after the initial
382 /// population of the type has happened (for example, to
383 /// bootstrap the corlib.dll
385 public void InitCoreTypes ()
387 object_type = CoreLookupType ("System.Object");
388 value_type = CoreLookupType ("System.ValueType");
389 string_type = CoreLookupType ("System.String");
390 int32_type = CoreLookupType ("System.Int32");
391 int64_type = CoreLookupType ("System.Int64");
392 uint32_type = CoreLookupType ("System.UInt32");
393 uint64_type = CoreLookupType ("System.UInt64");
394 float_type = CoreLookupType ("System.Single");
395 double_type = CoreLookupType ("System.Double");
396 byte_type = CoreLookupType ("System.Byte");
397 sbyte_type = CoreLookupType ("System.SByte");
398 char_type = CoreLookupType ("System.Char");
399 char_ptr_type = CoreLookupType ("System.Char*");
400 short_type = CoreLookupType ("System.Int16");
401 ushort_type = CoreLookupType ("System.UInt16");
402 decimal_type = CoreLookupType ("System.Decimal");
403 bool_type = CoreLookupType ("System.Boolean");
404 enum_type = CoreLookupType ("System.Enum");
406 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
407 delegate_type = CoreLookupType ("System.Delegate");
409 array_type = CoreLookupType ("System.Array");
410 void_type = CoreLookupType ("System.Void");
411 type_type = CoreLookupType ("System.Type");
413 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
414 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
415 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
416 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
417 asynccallback_type = CoreLookupType ("System.AsyncCallback");
418 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
419 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
420 idisposable_type = CoreLookupType ("System.IDisposable");
421 icloneable_type = CoreLookupType ("System.ICloneable");
422 monitor_type = CoreLookupType ("System.Threading.Monitor");
423 intptr_type = CoreLookupType ("System.IntPtr");
425 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
426 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
427 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
428 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
430 unverifiable_code_type = CoreLookupType ("System.Security.UnverifiableCodeAttribute");
432 void_ptr_type = CoreLookupType ("System.Void*");
435 // Now load the default methods that we use.
437 Type [] string_string = { string_type, string_type };
438 string_concat_string_string = GetMethod (
439 string_type, "Concat", string_string);
441 Type [] object_object = { object_type, object_type };
442 string_concat_object_object = GetMethod (
443 string_type, "Concat", object_object);
445 Type [] string_ = { string_type };
446 string_isinterneted_string = GetMethod (
447 string_type, "IsInterned", string_);
449 Type [] runtime_type_handle = { runtime_handle_type };
450 system_type_get_type_from_handle = GetMethod (
451 type_type, "GetTypeFromHandle", runtime_type_handle);
453 Type [] delegate_delegate = { delegate_type, delegate_type };
454 delegate_combine_delegate_delegate = GetMethod (
455 delegate_type, "Combine", delegate_delegate);
457 delegate_remove_delegate_delegate = GetMethod (
458 delegate_type, "Remove", delegate_delegate);
463 Type [] void_arg = { };
464 object_getcurrent_void = GetMethod (
465 ienumerator_type, "get_Current", void_arg);
466 bool_movenext_void = GetMethod (
467 ienumerator_type, "MoveNext", void_arg);
468 void_dispose_void = GetMethod (
469 idisposable_type, "Dispose", void_arg);
470 int_get_offset_to_string_data = GetMethod (
471 runtime_helpers_type, "get_OffsetToStringData", void_arg);
476 Type [] object_arg = { object_type };
477 void_monitor_enter_object = GetMethod (
478 monitor_type, "Enter", object_arg);
479 void_monitor_exit_object = GetMethod (
480 monitor_type, "Exit", object_arg);
482 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
484 void_initializearray_array_fieldhandle = GetMethod (
485 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
490 Type [] int_arg = { int32_type };
491 int_getlength_int = GetMethod (
492 array_type, "GetLength", int_arg);
497 cons_param_array_attribute = GetConstructor (
498 param_array_type, void_arg);
502 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
504 public MemberInfo [] FindMembers (Type t, MemberTypes mt, BindingFlags bf,
505 MemberFilter filter, object criteria)
508 // We have to take care of arrays specially, because GetType on
509 // a TypeBuilder array will return a Type, not a TypeBuilder,
510 // and we can not call FindMembers on this type.
512 if (t.IsSubclassOf (TypeManager.array_type))
513 return TypeManager.array_type.FindMembers (mt, bf, filter, criteria);
515 if (!(t is TypeBuilder)){
517 // Since FindMembers will not lookup both static and instance
518 // members, we emulate this behaviour here.
520 if ((bf & instance_and_static) == instance_and_static){
521 MemberInfo [] i_members = t.FindMembers (
522 mt, bf & ~BindingFlags.Static, filter, criteria);
523 MemberInfo [] s_members = t.FindMembers (
524 mt, bf & ~BindingFlags.Instance, filter, criteria);
526 int i_len = i_members.Length;
527 int s_len = s_members.Length;
528 if (i_len > 0 || s_len > 0){
529 MemberInfo [] both = new MemberInfo [i_len + s_len];
531 i_members.CopyTo (both, 0);
532 s_members.CopyTo (both, i_len);
538 return t.FindMembers (mt, bf, filter, criteria);
542 // FIXME: We should not have builder_to_blah everywhere,
543 // we should just have a builder_to_findmemberizable
544 // and have them implement a new ICanFindMembers interface
546 Enum e = (Enum) builder_to_enum [t];
549 return e.FindMembers (mt, bf, filter, criteria);
551 Delegate del = (Delegate) builder_to_delegate [t];
554 return del.FindMembers (mt, bf, filter, criteria);
556 Interface iface = (Interface) builder_to_interface [t];
559 return iface.FindMembers (mt, bf, filter, criteria);
561 TypeContainer tc = (TypeContainer) builder_to_container [t];
564 return tc.FindMembers (mt, bf, filter, criteria);
569 public static bool IsBuiltinType (Type t)
571 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
572 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
573 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
574 t == sbyte_type || t == byte_type || t == ushort_type)
580 public static bool IsDelegateType (Type t)
582 if (t.IsSubclassOf (TypeManager.delegate_type))
588 public static bool IsEnumType (Type t)
590 if (t.IsSubclassOf (TypeManager.enum_type))
596 public static bool IsInterfaceType (Type t)
598 Interface iface = (Interface) builder_to_interface [t];
607 /// Returns the User Defined Types
609 public ArrayList UserTypes {
615 public Hashtable TypeContainers {
617 return typecontainers;
621 static Hashtable builder_to_constant;
623 public static void RegisterConstant (FieldBuilder fb, Const c)
625 if (builder_to_constant == null)
626 builder_to_constant = new PtrHashtable ();
628 if (builder_to_constant.Contains (fb))
631 builder_to_constant.Add (fb, c);
634 public static Const LookupConstant (FieldBuilder fb)
636 if (builder_to_constant == null)
639 return (Const) builder_to_constant [fb];
643 /// Gigantic work around for missing features in System.Reflection.Emit follows.
647 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
648 /// for anything which is dynamic, and we need this in a number of places,
649 /// we register this information here, and use it afterwards.
651 static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
653 method_arguments.Add (mb, args);
654 method_internal_params.Add (mb, ip);
659 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
661 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
664 if (method_internal_params.Contains (mb))
665 return (InternalParameters) method_internal_params [mb];
667 throw new Exception ("Argument for Method not registered" + mb);
671 /// Returns the argument types for a method based on its methodbase
673 /// For dynamic methods, we use the compiler provided types, for
674 /// methods from existing assemblies we load them from GetParameters,
675 /// and insert them into the cache
677 static public Type [] GetArgumentTypes (MethodBase mb)
679 if (method_arguments.Contains (mb))
680 return (Type []) method_arguments [mb];
682 ParameterInfo [] pi = mb.GetParameters ();
684 Type [] types = new Type [c];
686 for (int i = 0; i < c; i++)
687 types [i] = pi [i].ParameterType;
689 method_arguments.Add (mb, types);
695 // This is a workaround the fact that GetValue is not
696 // supported for dynamic types
698 static Hashtable fields = new Hashtable ();
699 static public bool RegisterFieldValue (FieldBuilder fb, object value)
701 if (fields.Contains (fb))
704 fields.Add (fb, value);
709 static public object GetValue (FieldBuilder fb)
714 static Hashtable fieldbuilders_to_fields = new Hashtable ();
715 static public bool RegisterField (FieldBuilder fb, Field f)
717 if (fieldbuilders_to_fields.Contains (fb))
720 fieldbuilders_to_fields.Add (fb, f);
724 static public Field GetField (FieldInfo fb)
726 return (Field) fieldbuilders_to_fields [fb];
729 static Hashtable events;
731 static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
734 events = new Hashtable ();
736 if (events.Contains (eb))
739 events.Add (eb, new Pair (add, remove));
744 static public MethodInfo GetAddMethod (EventInfo ei)
746 if (ei is MyEventBuilder) {
747 Pair pair = (Pair) events [ei];
749 return (MethodInfo) pair.First;
751 return ei.GetAddMethod ();
754 static public MethodInfo GetRemoveMethod (EventInfo ei)
756 if (ei is MyEventBuilder) {
757 Pair pair = (Pair) events [ei];
759 return (MethodInfo) pair.Second;
761 return ei.GetAddMethod ();
764 static Hashtable properties;
766 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
768 if (properties == null)
769 properties = new Hashtable ();
771 if (properties.Contains (pb))
774 properties.Add (pb, new Pair (get, set));
780 // FIXME: we need to return the accessors depending on whether
781 // they are visible or not.
783 static public MethodInfo [] GetAccessors (PropertyInfo pi)
787 if (pi is PropertyBuilder){
788 Pair pair = (Pair) properties [pi];
790 ret = new MethodInfo [2];
791 ret [0] = (MethodInfo) pair.First;
792 ret [1] = (MethodInfo) pair.Second;
796 MethodInfo [] mi = new MethodInfo [2];
799 // Why this and not pi.GetAccessors?
800 // Because sometimes index 0 is the getter
803 mi [0] = pi.GetGetMethod (true);
804 mi [1] = pi.GetSetMethod (true);
810 static public MethodInfo GetPropertyGetter (PropertyInfo pi)
812 if (pi is PropertyBuilder){
813 Pair de = (Pair) properties [pi];
815 return (MethodInfo) de.Second;
817 return pi.GetSetMethod ();
820 static public MethodInfo GetPropertySetter (PropertyInfo pi)
822 if (pi is PropertyBuilder){
823 Pair de = (Pair) properties [pi];
825 return (MethodInfo) de.First;
827 return pi.GetGetMethod ();
831 // The following is used to check if a given type implements an interface.
832 // The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
835 static Hashtable type_interface_cache;
836 public static bool ImplementsInterface (Type t, Type iface)
841 interfaces = t.GetInterfaces ();
843 for (int i = interfaces.Length; i > 0; ){
845 if (interfaces [i] == iface)
855 // This is needed, because enumerations from assemblies
856 // do not report their underlyingtype, but they report
859 public static Type EnumToUnderlying (Type t)
861 t = t.UnderlyingSystemType;
862 if (!TypeManager.IsEnumType (t))
865 TypeCode tc = Type.GetTypeCode (t);
868 case TypeCode.Boolean:
869 return TypeManager.bool_type;
871 return TypeManager.byte_type;
873 return TypeManager.sbyte_type;
875 return TypeManager.char_type;
877 return TypeManager.short_type;
878 case TypeCode.UInt16:
879 return TypeManager.ushort_type;
881 return TypeManager.int32_type;
882 case TypeCode.UInt32:
883 return TypeManager.uint32_type;
885 return TypeManager.int64_type;
886 case TypeCode.UInt64:
887 return TypeManager.uint64_type;
889 throw new Exception ("Unhandled typecode in enum" + tc);
893 /// Utility function that can be used to probe whether a type
894 /// is managed or not.
896 public static bool VerifyUnManaged (Type t, Location loc)
900 // FIXME: this is more complex, we actually need to
901 // make sure that the type does not contain any
909 "Cannot take the address or size of a variable of a managed type ('" +
910 CSharpName (t) + "')");
915 /// Returns the name of the indexer in a given type.
918 /// The default is not always `Item'. The user can change this behaviour by
919 /// using the DefaultMemberAttribute in the class.
921 /// For example, the String class indexer is named `Chars' not `Item'
923 public static string IndexerPropertyName (Type t)
926 if (t is TypeBuilder) {
927 TypeContainer tc = (TypeContainer) builder_to_container [t];
929 Attributes attrs = tc.OptAttributes;
931 if (attrs == null || attrs.AttributeSections == null)
934 foreach (AttributeSection asec in attrs.AttributeSections) {
936 if (asec.Attributes == null)
939 foreach (Attribute a in asec.Attributes) {
940 if (a.Name.IndexOf ("DefaultMember") != -1) {
941 ArrayList pos_args = (ArrayList) a.Arguments [0];
942 Expression e = ((Argument) pos_args [0]).expr;
944 if (e is StringConstant)
945 return ((StringConstant) e).Value;
953 System.Attribute attr = System.Attribute.GetCustomAttribute (t, TypeManager.default_member_type);
957 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
959 return dma.MemberName;
965 public static void MakePinned (LocalBuilder builder)
968 // FIXME: Flag the "LocalBuilder" type as being
969 // pinned. Figure out API.