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)
13 using System.Globalization;
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Text.RegularExpressions;
18 using System.Runtime.CompilerServices;
19 using System.Diagnostics;
21 namespace Mono.CSharp {
23 public class TypeManager {
25 // A list of core types that the compiler requires or uses
27 static public Type object_type;
28 static public Type value_type;
29 static public Type string_type;
30 static public Type int32_type;
31 static public Type uint32_type;
32 static public Type int64_type;
33 static public Type uint64_type;
34 static public Type float_type;
35 static public Type double_type;
36 static public Type char_type;
37 static public Type char_ptr_type;
38 static public Type short_type;
39 static public Type decimal_type;
40 static public Type bool_type;
41 static public Type sbyte_type;
42 static public Type byte_type;
43 static public Type ushort_type;
44 static public Type enum_type;
45 static public Type delegate_type;
46 static public Type multicast_delegate_type;
47 static public Type void_type;
48 static public Type enumeration_type;
49 static public Type array_type;
50 static public Type runtime_handle_type;
51 static public Type icloneable_type;
52 static public Type type_type;
53 static public Type ienumerator_type;
54 static public Type idisposable_type;
55 static public Type default_member_type;
56 static public Type iasyncresult_type;
57 static public Type asynccallback_type;
58 static public Type intptr_type;
59 static public Type monitor_type;
60 static public Type runtime_field_handle_type;
61 static public Type attribute_type;
62 static public Type attribute_usage_type;
63 static public Type dllimport_type;
64 static public Type unverifiable_code_type;
65 static public Type methodimpl_attr_type;
66 static public Type marshal_as_attr_type;
67 static public Type param_array_type;
68 static public Type void_ptr_type;
69 static public Type indexer_name_type;
70 static public Type exception_type;
71 static public object obsolete_attribute_type;
72 static public object conditional_attribute_type;
75 // An empty array of types
77 static public Type [] NoTypes;
81 // Expressions representing the internal types. Used during declaration
84 static public Expression system_object_expr, system_string_expr;
85 static public Expression system_boolean_expr, system_decimal_expr;
86 static public Expression system_single_expr, system_double_expr;
87 static public Expression system_sbyte_expr, system_byte_expr;
88 static public Expression system_int16_expr, system_uint16_expr;
89 static public Expression system_int32_expr, system_uint32_expr;
90 static public Expression system_int64_expr, system_uint64_expr;
91 static public Expression system_char_expr, system_void_expr;
92 static public Expression system_asynccallback_expr;
93 static public Expression system_iasyncresult_expr;
96 // This is only used when compiling corlib
98 static public Type system_int32_type;
99 static public Type system_array_type;
100 static public Type system_type_type;
101 static public Type system_assemblybuilder_type;
102 static public MethodInfo system_int_array_get_length;
103 static public MethodInfo system_int_array_get_rank;
104 static public MethodInfo system_object_array_clone;
105 static public MethodInfo system_int_array_get_length_int;
106 static public MethodInfo system_int_array_get_lower_bound_int;
107 static public MethodInfo system_int_array_get_upper_bound_int;
108 static public MethodInfo system_void_array_copyto_array_int;
109 static public MethodInfo system_void_set_corlib_type_builders;
113 // Internal, not really used outside
115 static Type runtime_helpers_type;
118 // These methods are called by code generated by the compiler
120 static public MethodInfo string_concat_string_string;
121 static public MethodInfo string_concat_object_object;
122 static public MethodInfo string_isinterneted_string;
123 static public MethodInfo system_type_get_type_from_handle;
124 static public MethodInfo object_getcurrent_void;
125 static public MethodInfo bool_movenext_void;
126 static public MethodInfo void_dispose_void;
127 static public MethodInfo void_monitor_enter_object;
128 static public MethodInfo void_monitor_exit_object;
129 static public MethodInfo void_initializearray_array_fieldhandle;
130 static public MethodInfo int_getlength_int;
131 static public MethodInfo delegate_combine_delegate_delegate;
132 static public MethodInfo delegate_remove_delegate_delegate;
133 static public MethodInfo int_get_offset_to_string_data;
134 static public MethodInfo int_array_get_length;
135 static public MethodInfo int_array_get_rank;
136 static public MethodInfo object_array_clone;
137 static public MethodInfo int_array_get_length_int;
138 static public MethodInfo int_array_get_lower_bound_int;
139 static public MethodInfo int_array_get_upper_bound_int;
140 static public MethodInfo void_array_copyto_array_int;
143 // The attribute constructors.
145 static public ConstructorInfo cons_param_array_attribute;
146 static public ConstructorInfo void_decimal_ctor_five_args;
147 static public ConstructorInfo unverifiable_code_ctor;
150 // Holds the Array of Assemblies that have been loaded
151 // (either because it is the default or the user used the
152 // -r command line option)
154 static Assembly [] assemblies;
157 // Keeps a list of module builders. We used this to do lookups
158 // on the modulebuilder using GetType -- needed for arrays
160 static ModuleBuilder [] modules;
163 // This is the type_cache from the assemblies to avoid
164 // hitting System.Reflection on every lookup.
166 static Hashtable types;
169 // This is used to hotld the corresponding TypeContainer objects
170 // since we need this in FindMembers
172 static Hashtable typecontainers;
175 // Keeps track of those types that are defined by the
178 static ArrayList user_types;
180 static PtrHashtable builder_to_declspace;
183 // Tracks the interfaces implemented by typebuilders. We only
184 // enter those who do implement or or more interfaces
186 static PtrHashtable builder_to_ifaces;
189 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
190 // the arguments to the method
192 static Hashtable method_arguments;
195 // Maps PropertyBuilder to a Type array that contains
196 // the arguments to the indexer
198 static Hashtable indexer_arguments;
201 // Maybe `method_arguments' should be replaced and only
202 // method_internal_params should be kept?
204 static Hashtable method_internal_params;
207 // Keeps track of attribute types
210 static Hashtable builder_to_attr;
213 // Keeps track of methods
216 static Hashtable builder_to_method;
224 /// A filter for Findmembers that uses the Signature object to
227 static bool SignatureFilter (MemberInfo mi, object criteria)
229 Signature sig = (Signature) criteria;
231 if (!(mi is MethodBase))
234 if (mi.Name != sig.name)
237 int count = sig.args.Length;
239 if (mi is MethodBuilder || mi is ConstructorBuilder){
240 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
242 if (candidate_args.Length != count)
245 for (int i = 0; i < count; i++)
246 if (candidate_args [i] != sig.args [i])
251 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
253 if (pars.Length != count)
256 for (int i = 0; i < count; i++)
257 if (pars [i].ParameterType != sig.args [i])
263 // A delegate that points to the filter above.
264 static MemberFilter signature_filter;
267 // These are expressions that represent some of the internal data types, used
270 static void InitExpressionTypes ()
272 system_object_expr = new TypeLookupExpression ("System.Object");
273 system_string_expr = new TypeLookupExpression ("System.String");
274 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
275 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
276 system_single_expr = new TypeLookupExpression ("System.Single");
277 system_double_expr = new TypeLookupExpression ("System.Double");
278 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
279 system_byte_expr = new TypeLookupExpression ("System.Byte");
280 system_int16_expr = new TypeLookupExpression ("System.Int16");
281 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
282 system_int32_expr = new TypeLookupExpression ("System.Int32");
283 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
284 system_int64_expr = new TypeLookupExpression ("System.Int64");
285 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
286 system_char_expr = new TypeLookupExpression ("System.Char");
287 system_void_expr = new TypeLookupExpression ("System.Void");
288 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
289 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
292 static TypeManager ()
294 assemblies = new Assembly [0];
296 user_types = new ArrayList ();
298 types = new Hashtable ();
299 typecontainers = new Hashtable ();
301 builder_to_declspace = new PtrHashtable ();
302 builder_to_attr = new PtrHashtable ();
303 builder_to_method = new PtrHashtable ();
304 method_arguments = new PtrHashtable ();
305 method_internal_params = new PtrHashtable ();
306 indexer_arguments = new PtrHashtable ();
307 builder_to_ifaces = new PtrHashtable ();
309 NoTypes = new Type [0];
311 signature_filter = new MemberFilter (SignatureFilter);
312 InitExpressionTypes ();
315 public static void AddUserType (string name, TypeBuilder t, Type [] ifaces)
320 Type prev = (Type) types [name];
321 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
325 // This probably never happens, as we catch this before
327 Report.Error (-17, "The type `" + name + "' has already been defined.");
331 tc = builder_to_declspace [t] as TypeContainer;
334 1595, "The type `" + name + "' is defined in an existing assembly;"+
335 " Using the new definition from: " + tc.Location);
336 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
344 builder_to_ifaces [t] = ifaces;
348 // This entry point is used by types that we define under the covers
350 public static void RegisterBuilder (TypeBuilder tb, Type [] ifaces)
353 builder_to_ifaces [tb] = ifaces;
356 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc, Type [] ifaces)
358 builder_to_declspace.Add (t, tc);
359 typecontainers.Add (name, tc);
360 AddUserType (name, t, ifaces);
363 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
366 builder_to_declspace.Add (t, del);
369 public static void AddEnumType (string name, TypeBuilder t, Enum en)
372 builder_to_declspace.Add (t, en);
375 public static void AddUserInterface (string name, TypeBuilder t, Interface i, Type [] ifaces)
377 AddUserType (name, t, ifaces);
378 builder_to_declspace.Add (t, i);
381 public static void AddMethod (MethodBuilder builder, MethodData method)
383 builder_to_method.Add (builder, method);
386 public static void RegisterAttrType (Type t, TypeContainer tc)
388 builder_to_attr.Add (t, tc);
392 /// Returns the TypeContainer whose Type is `t' or null if there is no
393 /// TypeContainer for `t' (ie, the Type comes from a library)
395 public static TypeContainer LookupTypeContainer (Type t)
397 return builder_to_declspace [t] as TypeContainer;
400 public static IMemberContainer LookupMemberContainer (Type t)
402 if (t is TypeBuilder) {
403 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
404 if (container != null)
408 return TypeHandle.GetTypeHandle (t);
411 public static Interface LookupInterface (Type t)
413 return builder_to_declspace [t] as Interface;
416 public static Delegate LookupDelegate (Type t)
418 return builder_to_declspace [t] as Delegate;
421 public static Enum LookupEnum (Type t)
423 return builder_to_declspace [t] as Enum;
426 public static TypeContainer LookupAttr (Type t)
428 return (TypeContainer) builder_to_attr [t];
432 /// Registers an assembly to load types from.
434 public static void AddAssembly (Assembly a)
436 int top = assemblies.Length;
437 Assembly [] n = new Assembly [top + 1];
439 assemblies.CopyTo (n, 0);
446 /// Registers a module builder to lookup types from
448 public static void AddModule (ModuleBuilder mb)
450 int top = modules != null ? modules.Length : 0;
451 ModuleBuilder [] n = new ModuleBuilder [top + 1];
454 modules.CopyTo (n, 0);
460 // Low-level lookup, cache-less
462 static Type LookupTypeReflection (string name)
466 foreach (Assembly a in assemblies){
467 t = a.GetType (name);
472 foreach (ModuleBuilder mb in modules) {
473 t = mb.GetType (name);
482 // This function is used when you want to avoid the lookups, and want to go
483 // directly to the source. This will use the cache.
485 // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
486 // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
487 // way to test things other than doing a fullname compare
489 public static Type LookupTypeDirect (string name)
491 Type t = (Type) types [name];
495 t = LookupTypeReflection (name);
504 /// Returns the Type associated with @name, takes care of the fact that
505 /// reflection expects nested types to be separated from the main type
506 /// with a "+" instead of a "."
508 public static Type LookupType (string name)
513 // First lookup in user defined and cached values
516 t = (Type) types [name];
521 // Optimization: ComposedCast will work with an existing type, and might already have the
522 // full name of the type, so the full system lookup can probably be avoided.
525 string [] elements = name.Split ('.');
526 int count = elements.Length;
528 for (int n = 1; n <= count; n++){
529 string top_level_type = String.Join (".", elements, 0, n);
531 t = (Type) types [top_level_type];
533 t = LookupTypeReflection (top_level_type);
543 string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
544 t = LookupTypeDirect (newt);
553 // Returns a list of all namespaces in the assemblies and types loaded.
555 public static Hashtable GetNamespaces ()
557 Hashtable namespaces = new Hashtable ();
559 foreach (Assembly a in assemblies){
560 foreach (Type t in a.GetTypes ()){
561 string ns = t.Namespace;
563 if (namespaces.Contains (ns))
565 namespaces [ns] = ns;
569 foreach (ModuleBuilder mb in modules){
570 foreach (Type t in mb.GetTypes ()){
571 string ns = t.Namespace;
573 if (namespaces.Contains (ns))
575 namespaces [ns] = ns;
582 /// Returns the C# name of a type if possible, or the full type name otherwise
584 static public string CSharpName (Type t)
586 return Regex.Replace (t.FullName,
588 @"(Int32|UInt32|Int16|Uint16|Int64|UInt64|" +
589 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
590 @"Boolean|String|Void)" +
592 new MatchEvaluator (CSharpNameMatch));
595 static String CSharpNameMatch (Match match)
597 string s = match.Groups [1].Captures [0].Value;
599 Replace ("int32", "int").
600 Replace ("uint32", "uint").
601 Replace ("int16", "short").
602 Replace ("uint16", "ushort").
603 Replace ("int64", "long").
604 Replace ("uint64", "ulong").
605 Replace ("single", "float").
606 Replace ("boolean", "bool")
607 + match.Groups [2].Captures [0].Value;
611 /// Returns the signature of the method
613 static public string CSharpSignature (MethodBase mb)
618 // FIXME: We should really have a single function to do
619 // everything instead of the following 5 line pattern
621 ParameterData iparams = LookupParametersByBuilder (mb);
623 if (iparams == null){
624 ParameterInfo [] pi = mb.GetParameters ();
625 iparams = new ReflectionParameters (pi);
628 for (int i = 0; i < iparams.Count; i++) {
632 sig += iparams.ParameterDesc(i);
636 return mb.DeclaringType.Name + "." + mb.Name + sig;
640 /// Looks up a type, and aborts if it is not found. This is used
641 /// by types required by the compiler
643 static Type CoreLookupType (string name)
645 Type t = LookupType (name);
648 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
649 Environment.Exit (0);
656 /// Returns the MethodInfo for a method named `name' defined
657 /// in type `t' which takes arguments of types `args'
659 static MethodInfo GetMethod (Type t, string name, Type [] args)
667 list = FindMembers (t, MemberTypes.Method, instance_and_static | BindingFlags.Public,
668 signature_filter, sig);
669 if (list.Count == 0) {
670 Report.Error (-19, "Can not find the core function `" + name + "'");
674 MethodInfo mi = list [0] as MethodInfo;
676 Report.Error (-19, "Can not find the core function `" + name + "'");
684 /// Returns the ConstructorInfo for "args"
686 static ConstructorInfo GetConstructor (Type t, Type [] args)
694 list = FindMembers (t, MemberTypes.Constructor,
695 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
696 signature_filter, sig);
697 if (list.Count == 0){
698 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
702 ConstructorInfo ci = list [0] as ConstructorInfo;
704 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
711 public static void InitEnumUnderlyingTypes ()
714 int32_type = CoreLookupType ("System.Int32");
715 int64_type = CoreLookupType ("System.Int64");
716 uint32_type = CoreLookupType ("System.UInt32");
717 uint64_type = CoreLookupType ("System.UInt64");
718 byte_type = CoreLookupType ("System.Byte");
719 sbyte_type = CoreLookupType ("System.SByte");
720 short_type = CoreLookupType ("System.Int16");
721 ushort_type = CoreLookupType ("System.UInt16");
725 /// The types have to be initialized after the initial
726 /// population of the type has happened (for example, to
727 /// bootstrap the corlib.dll
729 public static void InitCoreTypes ()
731 object_type = CoreLookupType ("System.Object");
732 value_type = CoreLookupType ("System.ValueType");
734 InitEnumUnderlyingTypes ();
736 char_type = CoreLookupType ("System.Char");
737 string_type = CoreLookupType ("System.String");
738 float_type = CoreLookupType ("System.Single");
739 double_type = CoreLookupType ("System.Double");
740 char_ptr_type = CoreLookupType ("System.Char*");
741 decimal_type = CoreLookupType ("System.Decimal");
742 bool_type = CoreLookupType ("System.Boolean");
743 enum_type = CoreLookupType ("System.Enum");
745 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
746 delegate_type = CoreLookupType ("System.Delegate");
748 array_type = CoreLookupType ("System.Array");
749 void_type = CoreLookupType ("System.Void");
750 type_type = CoreLookupType ("System.Type");
752 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
753 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
754 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
755 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
756 asynccallback_type = CoreLookupType ("System.AsyncCallback");
757 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
758 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
759 idisposable_type = CoreLookupType ("System.IDisposable");
760 icloneable_type = CoreLookupType ("System.ICloneable");
761 monitor_type = CoreLookupType ("System.Threading.Monitor");
762 intptr_type = CoreLookupType ("System.IntPtr");
764 attribute_type = CoreLookupType ("System.Attribute");
765 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
766 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
767 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
768 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
769 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
771 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
773 void_ptr_type = CoreLookupType ("System.Void*");
775 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
777 exception_type = CoreLookupType ("System.Exception");
782 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
783 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
786 // When compiling corlib, store the "real" types here.
788 if (!RootContext.StdLib) {
789 system_int32_type = typeof (System.Int32);
790 system_array_type = typeof (System.Array);
791 system_type_type = typeof (System.Type);
792 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
794 Type [] void_arg = { };
795 system_int_array_get_length = GetMethod (
796 system_array_type, "get_Length", void_arg);
797 system_int_array_get_rank = GetMethod (
798 system_array_type, "get_Rank", void_arg);
799 system_object_array_clone = GetMethod (
800 system_array_type, "Clone", void_arg);
802 Type [] system_int_arg = { system_int32_type };
803 system_int_array_get_length_int = GetMethod (
804 system_array_type, "GetLength", system_int_arg);
805 system_int_array_get_upper_bound_int = GetMethod (
806 system_array_type, "GetUpperBound", system_int_arg);
807 system_int_array_get_lower_bound_int = GetMethod (
808 system_array_type, "GetLowerBound", system_int_arg);
810 Type [] system_array_int_arg = { system_array_type, system_int32_type };
811 system_void_array_copyto_array_int = GetMethod (
812 system_array_type, "CopyTo", system_array_int_arg);
814 Type [] system_type_type_arg = { system_type_type, system_type_type, system_type_type };
817 system_void_set_corlib_type_builders = GetMethod (
818 system_assemblybuilder_type, "SetCorlibTypeBuilders",
819 system_type_type_arg);
821 object[] args = new object [3];
822 args [0] = object_type;
823 args [1] = value_type;
824 args [2] = enum_type;
826 system_void_set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
828 Console.WriteLine ("Corlib compilation is not supported in Microsoft.NET due to bugs in it");
834 // The helper methods that are used by the compiler
836 public static void InitCodeHelpers ()
839 // Now load the default methods that we use.
841 Type [] string_string = { string_type, string_type };
842 string_concat_string_string = GetMethod (
843 string_type, "Concat", string_string);
845 Type [] object_object = { object_type, object_type };
846 string_concat_object_object = GetMethod (
847 string_type, "Concat", object_object);
849 Type [] string_ = { string_type };
850 string_isinterneted_string = GetMethod (
851 string_type, "IsInterned", string_);
853 Type [] runtime_type_handle = { runtime_handle_type };
854 system_type_get_type_from_handle = GetMethod (
855 type_type, "GetTypeFromHandle", runtime_type_handle);
857 Type [] delegate_delegate = { delegate_type, delegate_type };
858 delegate_combine_delegate_delegate = GetMethod (
859 delegate_type, "Combine", delegate_delegate);
861 delegate_remove_delegate_delegate = GetMethod (
862 delegate_type, "Remove", delegate_delegate);
867 Type [] void_arg = { };
868 object_getcurrent_void = GetMethod (
869 ienumerator_type, "get_Current", void_arg);
870 bool_movenext_void = GetMethod (
871 ienumerator_type, "MoveNext", void_arg);
872 void_dispose_void = GetMethod (
873 idisposable_type, "Dispose", void_arg);
874 int_get_offset_to_string_data = GetMethod (
875 runtime_helpers_type, "get_OffsetToStringData", void_arg);
876 int_array_get_length = GetMethod (
877 array_type, "get_Length", void_arg);
878 int_array_get_rank = GetMethod (
879 array_type, "get_Rank", void_arg);
884 Type [] int_arg = { int32_type };
885 int_array_get_length_int = GetMethod (
886 array_type, "GetLength", int_arg);
887 int_array_get_upper_bound_int = GetMethod (
888 array_type, "GetUpperBound", int_arg);
889 int_array_get_lower_bound_int = GetMethod (
890 array_type, "GetLowerBound", int_arg);
893 // System.Array methods
895 object_array_clone = GetMethod (
896 array_type, "Clone", void_arg);
897 Type [] array_int_arg = { array_type, int32_type };
898 void_array_copyto_array_int = GetMethod (
899 array_type, "CopyTo", array_int_arg);
904 Type [] object_arg = { object_type };
905 void_monitor_enter_object = GetMethod (
906 monitor_type, "Enter", object_arg);
907 void_monitor_exit_object = GetMethod (
908 monitor_type, "Exit", object_arg);
910 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
912 void_initializearray_array_fieldhandle = GetMethod (
913 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
918 int_getlength_int = GetMethod (
919 array_type, "GetLength", int_arg);
922 // Decimal constructors
924 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
925 void_decimal_ctor_five_args = GetConstructor (
926 decimal_type, dec_arg);
931 cons_param_array_attribute = GetConstructor (
932 param_array_type, void_arg);
934 unverifiable_code_ctor = GetConstructor (
935 unverifiable_code_type, void_arg);
939 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
941 static Hashtable type_hash = new Hashtable ();
944 /// This is the "old", non-cache based FindMembers() function. We cannot use
945 /// the cache here because there is no member name argument.
947 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
948 MemberFilter filter, object criteria)
950 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
953 // `builder_to_declspace' contains all dynamic types.
957 Timer.StartTimer (TimerType.FindMembers);
958 list = decl.FindMembers (mt, bf, filter, criteria);
959 Timer.StopTimer (TimerType.FindMembers);
964 // We have to take care of arrays specially, because GetType on
965 // a TypeBuilder array will return a Type, not a TypeBuilder,
966 // and we can not call FindMembers on this type.
968 if (t.IsSubclassOf (TypeManager.array_type))
969 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
972 // Since FindMembers will not lookup both static and instance
973 // members, we emulate this behaviour here.
975 if ((bf & instance_and_static) == instance_and_static){
976 MemberInfo [] i_members = t.FindMembers (
977 mt, bf & ~BindingFlags.Static, filter, criteria);
979 int i_len = i_members.Length;
981 MemberInfo one = i_members [0];
984 // If any of these are present, we are done!
986 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
987 return new MemberList (i_members);
990 MemberInfo [] s_members = t.FindMembers (
991 mt, bf & ~BindingFlags.Instance, filter, criteria);
993 int s_len = s_members.Length;
994 if (i_len > 0 || s_len > 0)
995 return new MemberList (i_members, s_members);
998 return new MemberList (i_members);
1000 return new MemberList (s_members);
1004 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1009 /// This method is only called from within MemberLookup. It tries to use the member
1010 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1011 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1012 /// our return value will already contain all inherited members and the caller don't need
1013 /// to check base classes and interfaces anymore.
1015 private static MemberList MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1016 string name, out bool used_cache)
1019 // We have to take care of arrays specially, because GetType on
1020 // a TypeBuilder array will return a Type, not a TypeBuilder,
1021 // and we can not call FindMembers on this type.
1023 if (t.IsSubclassOf (TypeManager.array_type)) {
1025 return TypeHandle.ArrayType.MemberCache.FindMembers (
1026 mt, bf, name, FilterWithClosure_delegate, null);
1030 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1031 // and we can ask the DeclSpace for the MemberCache.
1033 if (t is TypeBuilder) {
1034 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1035 MemberCache cache = decl.MemberCache;
1038 // If this DeclSpace has a MemberCache, use it.
1041 if (cache != null) {
1043 return cache.FindMembers (
1044 mt, bf, name, FilterWithClosure_delegate, null);
1047 // If there is no MemberCache, we need to use the "normal" FindMembers.
1050 Timer.StartTimer (TimerType.FindMembers);
1051 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1052 FilterWithClosure_delegate, name);
1053 Timer.StopTimer (TimerType.FindMembers);
1059 // This call will always succeed. There is exactly one TypeHandle instance per
1060 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1061 // if it didn't already exist.
1063 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1066 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1069 public static bool IsBuiltinType (Type t)
1071 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1072 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1073 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1074 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1080 public static bool IsDelegateType (Type t)
1082 if (t.IsSubclassOf (TypeManager.delegate_type))
1088 public static bool IsEnumType (Type t)
1090 if (t.IsSubclassOf (TypeManager.enum_type))
1097 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1099 Hashtable managed_types;
1100 public static bool IsUnmanagedType (Type t)
1102 if (IsBuiltinType (t) && t != TypeManager.string_type)
1111 if (IsValueType (t)){
1112 if (t is TypeBuilder){
1113 TypeContainer tc = LookupTypeContainer (t);
1115 foreach (Field f in tc.Fields){
1116 if (f.FieldBuilder.IsStatic)
1118 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1122 FieldInfo [] fields = t.GetFields ();
1124 foreach (FieldInfo f in fields){
1127 if (!IsUnmanagedType (f.FieldType))
1137 public static bool IsValueType (Type t)
1139 if (t.IsSubclassOf (TypeManager.value_type))
1145 public static bool IsInterfaceType (Type t)
1147 Interface iface = builder_to_declspace [t] as Interface;
1156 // Checks whether `type' is a subclass or nested child of `parent'.
1158 public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1161 if ((type == parent) || type.IsSubclassOf (parent))
1164 // Handle nested types.
1165 type = type.DeclaringType;
1166 } while (type != null);
1172 // Checks whether `type' is a nested child of `parent'.
1174 public static bool IsNestedChildOf (Type type, Type parent)
1176 if ((type == parent) || type.IsSubclassOf (parent))
1179 return IsSubclassOrNestedChildOf (type, parent);
1183 /// Returns the User Defined Types
1185 public static ArrayList UserTypes {
1191 public static Hashtable TypeContainers {
1193 return typecontainers;
1197 static Hashtable builder_to_constant;
1199 public static void RegisterConstant (FieldBuilder fb, Const c)
1201 if (builder_to_constant == null)
1202 builder_to_constant = new PtrHashtable ();
1204 if (builder_to_constant.Contains (fb))
1207 builder_to_constant.Add (fb, c);
1210 public static Const LookupConstant (FieldBuilder fb)
1212 if (builder_to_constant == null)
1215 return (Const) builder_to_constant [fb];
1219 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1223 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1224 /// for anything which is dynamic, and we need this in a number of places,
1225 /// we register this information here, and use it afterwards.
1227 static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1232 method_arguments.Add (mb, args);
1233 method_internal_params.Add (mb, ip);
1238 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1240 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1243 if (method_internal_params.Contains (mb))
1244 return (InternalParameters) method_internal_params [mb];
1246 throw new Exception ("Argument for Method not registered" + mb);
1250 /// Returns the argument types for a method based on its methodbase
1252 /// For dynamic methods, we use the compiler provided types, for
1253 /// methods from existing assemblies we load them from GetParameters,
1254 /// and insert them into the cache
1256 static public Type [] GetArgumentTypes (MethodBase mb)
1258 if (method_arguments.Contains (mb))
1259 return (Type []) method_arguments [mb];
1261 ParameterInfo [] pi = mb.GetParameters ();
1263 Type [] types = new Type [c];
1265 for (int i = 0; i < c; i++)
1266 types [i] = pi [i].ParameterType;
1268 method_arguments.Add (mb, types);
1274 /// Returns the argument types for an indexer based on its PropertyInfo
1276 /// For dynamic indexers, we use the compiler provided types, for
1277 /// indexers from existing assemblies we load them from GetParameters,
1278 /// and insert them into the cache
1280 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1282 if (indexer_arguments.Contains (indexer))
1283 return (Type []) indexer_arguments [indexer];
1284 else if (indexer is PropertyBuilder)
1285 // If we're a PropertyBuilder and not in the
1286 // `indexer_arguments' hash, then we're a property and
1290 ParameterInfo [] pi = indexer.GetIndexParameters ();
1291 // Property, not an indexer.
1295 Type [] types = new Type [c];
1297 for (int i = 0; i < c; i++)
1298 types [i] = pi [i].ParameterType;
1300 indexer_arguments.Add (indexer, types);
1306 // This is a workaround the fact that GetValue is not
1307 // supported for dynamic types
1309 static Hashtable fields = new Hashtable ();
1310 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1312 if (fields.Contains (fb))
1315 fields.Add (fb, value);
1320 static public object GetValue (FieldBuilder fb)
1325 static Hashtable fieldbuilders_to_fields = new Hashtable ();
1326 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1328 if (fieldbuilders_to_fields.Contains (fb))
1331 fieldbuilders_to_fields.Add (fb, f);
1335 static public FieldBase GetField (FieldInfo fb)
1337 return (FieldBase) fieldbuilders_to_fields [fb];
1340 static Hashtable events;
1342 static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1345 events = new Hashtable ();
1347 if (events.Contains (eb))
1350 events.Add (eb, new Pair (add, remove));
1355 static public MethodInfo GetAddMethod (EventInfo ei)
1357 if (ei is MyEventBuilder) {
1358 Pair pair = (Pair) events [ei];
1360 return (MethodInfo) pair.First;
1362 return ei.GetAddMethod ();
1365 static public MethodInfo GetRemoveMethod (EventInfo ei)
1367 if (ei is MyEventBuilder) {
1368 Pair pair = (Pair) events [ei];
1370 return (MethodInfo) pair.Second;
1372 return ei.GetAddMethod ();
1375 static Hashtable priv_fields_events;
1377 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1379 if (priv_fields_events == null)
1380 priv_fields_events = new Hashtable ();
1382 if (priv_fields_events.Contains (einfo))
1385 priv_fields_events.Add (einfo, builder);
1390 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1392 return (MemberInfo) priv_fields_events [ei];
1395 static Hashtable properties;
1397 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1399 if (properties == null)
1400 properties = new Hashtable ();
1402 if (properties.Contains (pb))
1405 properties.Add (pb, new Pair (get, set));
1410 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get, MethodBase set, Type[] args)
1412 if (!RegisterProperty (pb, get,set))
1415 indexer_arguments.Add (pb, args);
1421 // FIXME: we need to return the accessors depending on whether
1422 // they are visible or not.
1424 static public MethodInfo [] GetAccessors (PropertyInfo pi)
1428 if (pi is PropertyBuilder){
1429 Pair pair = (Pair) properties [pi];
1431 ret = new MethodInfo [2];
1432 ret [0] = (MethodInfo) pair.First;
1433 ret [1] = (MethodInfo) pair.Second;
1437 MethodInfo [] mi = new MethodInfo [2];
1440 // Why this and not pi.GetAccessors?
1441 // Because sometimes index 0 is the getter
1442 // sometimes it is 1
1444 mi [0] = pi.GetGetMethod (true);
1445 mi [1] = pi.GetSetMethod (true);
1451 static public MethodInfo GetPropertyGetter (PropertyInfo pi)
1453 if (pi is PropertyBuilder){
1454 Pair de = (Pair) properties [pi];
1456 return (MethodInfo) de.Second;
1458 return pi.GetSetMethod ();
1461 static public MethodInfo GetPropertySetter (PropertyInfo pi)
1463 if (pi is PropertyBuilder){
1464 Pair de = (Pair) properties [pi];
1466 return (MethodInfo) de.First;
1468 return pi.GetGetMethod ();
1472 /// Given an array of interface types, expand and eliminate repeated ocurrences
1473 /// of an interface.
1477 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1480 public static Type [] ExpandInterfaces (Type [] base_interfaces)
1482 ArrayList new_ifaces = new ArrayList ();
1484 foreach (Type iface in base_interfaces){
1485 if (!new_ifaces.Contains (iface))
1486 new_ifaces.Add (iface);
1488 Type [] implementing = TypeManager.GetInterfaces (iface);
1490 foreach (Type imp in implementing){
1491 if (!new_ifaces.Contains (imp))
1492 new_ifaces.Add (imp);
1495 Type [] ret = new Type [new_ifaces.Count];
1496 new_ifaces.CopyTo (ret, 0);
1501 /// This function returns the interfaces in the type `t'. Works with
1502 /// both types and TypeBuilders.
1504 public static Type [] GetInterfaces (Type t)
1507 // The reason for catching the Array case is that Reflection.Emit
1508 // will not return a TypeBuilder for Array types of TypeBuilder types,
1509 // but will still throw an exception if we try to call GetInterfaces
1512 // Since the array interfaces are always constant, we return those for
1517 t = TypeManager.array_type;
1519 if (t is TypeBuilder){
1520 Type [] parent_ifaces;
1522 if (t.BaseType == null)
1523 parent_ifaces = NoTypes;
1525 parent_ifaces = GetInterfaces (t.BaseType);
1526 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1527 if (type_ifaces == null)
1528 type_ifaces = NoTypes;
1530 int parent_count = parent_ifaces.Length;
1531 Type [] result = new Type [parent_count + type_ifaces.Length];
1532 parent_ifaces.CopyTo (result, 0);
1533 type_ifaces.CopyTo (result, parent_count);
1537 return t.GetInterfaces ();
1541 /// The following is used to check if a given type implements an interface.
1542 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1544 public static bool ImplementsInterface (Type t, Type iface)
1549 // FIXME OPTIMIZATION:
1550 // as soon as we hit a non-TypeBuiler in the interface
1551 // chain, we could return, as the `Type.GetInterfaces'
1552 // will return all the interfaces implement by the type
1556 interfaces = GetInterfaces (t);
1558 if (interfaces != null){
1559 foreach (Type i in interfaces){
1566 } while (t != null);
1571 // This is a custom version of Convert.ChangeType() which works
1572 // with the TypeBuilder defined types when compiling corlib.
1573 public static object ChangeType (object value, Type conversionType)
1575 if (!(value is IConvertible))
1576 throw new ArgumentException ();
1578 IConvertible convertValue = (IConvertible) value;
1579 CultureInfo ci = CultureInfo.CurrentCulture;
1580 NumberFormatInfo provider = ci.NumberFormat;
1583 // We must use Type.Equals() here since `conversionType' is
1584 // the TypeBuilder created version of a system type and not
1585 // the system type itself. You cannot use Type.GetTypeCode()
1586 // on such a type - it'd always return TypeCode.Object.
1588 if (conversionType.Equals (typeof (Boolean)))
1589 return (object)(convertValue.ToBoolean (provider));
1590 else if (conversionType.Equals (typeof (Byte)))
1591 return (object)(convertValue.ToByte (provider));
1592 else if (conversionType.Equals (typeof (Char)))
1593 return (object)(convertValue.ToChar (provider));
1594 else if (conversionType.Equals (typeof (DateTime)))
1595 return (object)(convertValue.ToDateTime (provider));
1596 else if (conversionType.Equals (typeof (Decimal)))
1597 return (object)(convertValue.ToDecimal (provider));
1598 else if (conversionType.Equals (typeof (Double)))
1599 return (object)(convertValue.ToDouble (provider));
1600 else if (conversionType.Equals (typeof (Int16)))
1601 return (object)(convertValue.ToInt16 (provider));
1602 else if (conversionType.Equals (typeof (Int32)))
1603 return (object)(convertValue.ToInt32 (provider));
1604 else if (conversionType.Equals (typeof (Int64)))
1605 return (object)(convertValue.ToInt64 (provider));
1606 else if (conversionType.Equals (typeof (SByte)))
1607 return (object)(convertValue.ToSByte (provider));
1608 else if (conversionType.Equals (typeof (Single)))
1609 return (object)(convertValue.ToSingle (provider));
1610 else if (conversionType.Equals (typeof (String)))
1611 return (object)(convertValue.ToString (provider));
1612 else if (conversionType.Equals (typeof (UInt16)))
1613 return (object)(convertValue.ToUInt16 (provider));
1614 else if (conversionType.Equals (typeof (UInt32)))
1615 return (object)(convertValue.ToUInt32 (provider));
1616 else if (conversionType.Equals (typeof (UInt64)))
1617 return (object)(convertValue.ToUInt64 (provider));
1618 else if (conversionType.Equals (typeof (Object)))
1619 return (object)(value);
1621 throw new InvalidCastException ();
1625 // This is needed, because enumerations from assemblies
1626 // do not report their underlyingtype, but they report
1629 public static Type EnumToUnderlying (Type t)
1631 if (t == TypeManager.enum_type)
1634 t = t.UnderlyingSystemType;
1635 if (!TypeManager.IsEnumType (t))
1638 if (t is TypeBuilder) {
1639 // slow path needed to compile corlib
1640 if (t == TypeManager.bool_type ||
1641 t == TypeManager.byte_type ||
1642 t == TypeManager.sbyte_type ||
1643 t == TypeManager.char_type ||
1644 t == TypeManager.short_type ||
1645 t == TypeManager.ushort_type ||
1646 t == TypeManager.int32_type ||
1647 t == TypeManager.uint32_type ||
1648 t == TypeManager.int64_type ||
1649 t == TypeManager.uint64_type)
1651 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
1653 TypeCode tc = Type.GetTypeCode (t);
1656 case TypeCode.Boolean:
1657 return TypeManager.bool_type;
1659 return TypeManager.byte_type;
1660 case TypeCode.SByte:
1661 return TypeManager.sbyte_type;
1663 return TypeManager.char_type;
1664 case TypeCode.Int16:
1665 return TypeManager.short_type;
1666 case TypeCode.UInt16:
1667 return TypeManager.ushort_type;
1668 case TypeCode.Int32:
1669 return TypeManager.int32_type;
1670 case TypeCode.UInt32:
1671 return TypeManager.uint32_type;
1672 case TypeCode.Int64:
1673 return TypeManager.int64_type;
1674 case TypeCode.UInt64:
1675 return TypeManager.uint64_type;
1677 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1681 // When compiling corlib and called with one of the core types, return
1682 // the corresponding typebuilder for that type.
1684 public static Type TypeToCoreType (Type t)
1686 if (RootContext.StdLib || (t is TypeBuilder))
1689 TypeCode tc = Type.GetTypeCode (t);
1692 case TypeCode.Boolean:
1693 return TypeManager.bool_type;
1695 return TypeManager.byte_type;
1696 case TypeCode.SByte:
1697 return TypeManager.sbyte_type;
1699 return TypeManager.char_type;
1700 case TypeCode.Int16:
1701 return TypeManager.short_type;
1702 case TypeCode.UInt16:
1703 return TypeManager.ushort_type;
1704 case TypeCode.Int32:
1705 return TypeManager.int32_type;
1706 case TypeCode.UInt32:
1707 return TypeManager.uint32_type;
1708 case TypeCode.Int64:
1709 return TypeManager.int64_type;
1710 case TypeCode.UInt64:
1711 return TypeManager.uint64_type;
1712 case TypeCode.String:
1713 return TypeManager.string_type;
1715 if (t == typeof (void))
1716 return TypeManager.void_type;
1717 if (t == typeof (object))
1718 return TypeManager.object_type;
1719 if (t == typeof (System.Type))
1720 return TypeManager.type_type;
1726 /// Utility function that can be used to probe whether a type
1727 /// is managed or not.
1729 public static bool VerifyUnManaged (Type t, Location loc)
1731 if (t.IsValueType || t.IsPointer){
1733 // FIXME: this is more complex, we actually need to
1734 // make sure that the type does not contain any
1740 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
1741 // We need this explicit check here to make it work when
1742 // compiling corlib.
1747 "Cannot take the address or size of a variable of a managed type ('" +
1748 CSharpName (t) + "')");
1753 /// Returns the name of the indexer in a given type.
1756 /// The default is not always `Item'. The user can change this behaviour by
1757 /// using the DefaultMemberAttribute in the class.
1759 /// For example, the String class indexer is named `Chars' not `Item'
1761 public static string IndexerPropertyName (Type t)
1763 if (t is TypeBuilder) {
1764 if (t.IsInterface) {
1765 Interface i = LookupInterface (t);
1767 if ((i == null) || (i.IndexerName == null))
1770 return i.IndexerName;
1772 TypeContainer tc = LookupTypeContainer (t);
1774 if ((tc == null) || (tc.IndexerName == null))
1777 return tc.IndexerName;
1781 System.Attribute attr = System.Attribute.GetCustomAttribute (
1782 t, TypeManager.default_member_type);
1784 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
1785 return dma.MemberName;
1791 public static void MakePinned (LocalBuilder builder)
1794 // FIXME: Flag the "LocalBuilder" type as being
1795 // pinned. Figure out API.
1801 // Returns whether the array of memberinfos contains the given method
1803 static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
1805 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
1807 foreach (MethodBase method in array){
1808 if (method.Name != new_method.Name)
1811 Type [] old_args = TypeManager.GetArgumentTypes (method);
1812 int old_count = old_args.Length;
1815 if (new_args.Length != old_count)
1818 for (i = 0; i < old_count; i++){
1819 if (old_args [i] != new_args [i])
1831 // We copy methods from `new_members' into `target_list' if the signature
1832 // for the method from in the new list does not exist in the target_list
1834 // The name is assumed to be the same.
1836 public static ArrayList CopyNewMethods (ArrayList target_list, MemberList new_members)
1838 if (target_list == null){
1839 target_list = new ArrayList ();
1841 foreach (MemberInfo mi in new_members){
1842 if (mi is MethodBase)
1843 target_list.Add (mi);
1848 MemberInfo [] target_array = new MemberInfo [target_list.Count];
1849 target_list.CopyTo (target_array, 0);
1851 foreach (MemberInfo mi in new_members){
1852 MethodBase new_method = (MethodBase) mi;
1854 if (!ArrayContainsMethod (target_array, new_method))
1855 target_list.Add (new_method);
1861 public enum MethodFlags {
1863 IsObsoleteError = 2,
1868 // Returns the TypeManager.MethodFlags for this method.
1869 // This emits an error 619 / warning 618 if the method is obsolete.
1870 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
1872 static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
1874 MethodFlags flags = 0;
1876 if (mb.DeclaringType is TypeBuilder){
1877 MethodData method = (MethodData) builder_to_method [mb];
1878 if (method == null) {
1879 // FIXME: implement Obsolete attribute on Property,
1880 // Indexer and Event.
1884 return method.GetMethodFlags (loc);
1887 object [] attrs = mb.GetCustomAttributes (true);
1888 foreach (object ta in attrs){
1889 if (!(ta is System.Attribute)){
1890 Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
1893 System.Attribute a = (System.Attribute) ta;
1894 if (a.TypeId == TypeManager.obsolete_attribute_type){
1895 ObsoleteAttribute oa = (ObsoleteAttribute) a;
1897 string method_desc = TypeManager.CSharpSignature (mb);
1900 Report.Error (619, loc, "Method `" + method_desc +
1901 "' is obsolete: `" + oa.Message + "'");
1902 return MethodFlags.IsObsoleteError;
1904 Report.Warning (618, loc, "Method `" + method_desc +
1905 "' is obsolete: `" + oa.Message + "'");
1907 flags |= MethodFlags.IsObsolete;
1913 // Skip over conditional code.
1915 if (a.TypeId == TypeManager.conditional_attribute_type){
1916 ConditionalAttribute ca = (ConditionalAttribute) a;
1918 if (RootContext.AllDefines [ca.ConditionString] == null)
1919 flags |= MethodFlags.ShouldIgnore;
1926 #region MemberLookup implementation
1929 // Name of the member
1931 static string closure_name;
1934 // Whether we allow private members in the result (since FindMembers
1935 // uses NonPublic for both protected and private), we need to distinguish.
1937 static bool closure_private_ok;
1940 // Who is invoking us and which type is being queried currently.
1942 static Type closure_invocation_type;
1943 static Type closure_queried_type;
1944 static Type closure_start_type;
1947 // The assembly that defines the type is that is calling us
1949 static Assembly closure_invocation_assembly;
1952 // This filter filters by name + whether it is ok to include private
1953 // members in the search
1955 static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
1958 // Hack: we know that the filter criteria will always be in the `closure'
1962 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
1965 if ((closure_start_type == closure_invocation_type) &&
1966 (m.DeclaringType == closure_invocation_type))
1970 // Ugly: we need to find out the type of `m', and depending
1971 // on this, tell whether we accept or not
1973 if (m is MethodBase){
1974 MethodBase mb = (MethodBase) m;
1975 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
1977 if (ma == MethodAttributes.Private)
1978 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
1981 // FamAndAssem requires that we not only derivate, but we are on the
1984 if (ma == MethodAttributes.FamANDAssem){
1985 if (closure_invocation_assembly != mb.DeclaringType.Assembly)
1989 // Assembly and FamORAssem succeed if we're in the same assembly.
1990 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
1991 if (closure_invocation_assembly == mb.DeclaringType.Assembly)
1995 // We already know that we aren't in the same assembly.
1996 if (ma == MethodAttributes.Assembly)
1999 // Family and FamANDAssem require that we derive.
2000 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
2001 if (closure_invocation_type == null)
2004 if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
2007 // Although a derived class can access protected members of its base class
2008 // it cannot do so through an instance of the base class (CS1540).
2009 if ((closure_invocation_type != closure_start_type) &&
2010 closure_invocation_type.IsSubclassOf (closure_start_type))
2020 if (m is FieldInfo){
2021 FieldInfo fi = (FieldInfo) m;
2022 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2024 if (fa == FieldAttributes.Private)
2025 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2028 // FamAndAssem requires that we not only derivate, but we are on the
2031 if (fa == FieldAttributes.FamANDAssem){
2032 if (closure_invocation_assembly != fi.DeclaringType.Assembly)
2036 // Assembly and FamORAssem succeed if we're in the same assembly.
2037 if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2038 if (closure_invocation_assembly == fi.DeclaringType.Assembly)
2042 // We already know that we aren't in the same assembly.
2043 if (fa == FieldAttributes.Assembly)
2046 // Family and FamANDAssem require that we derive.
2047 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
2048 if (closure_invocation_type == null)
2051 if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.DeclaringType))
2054 // Although a derived class can access protected members of its base class
2055 // it cannot do so through an instance of the base class (CS1540).
2056 if ((closure_invocation_type != closure_start_type) &&
2057 closure_invocation_type.IsSubclassOf (closure_start_type))
2068 // EventInfos and PropertyInfos, return true
2073 static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
2076 // Looks up a member called `name' in the `queried_type'. This lookup
2077 // is done by code that is contained in the definition for `invocation_type'.
2079 // The binding flags are `bf' and the kind of members being looked up are `mt'
2081 // Returns an array of a single element for everything but Methods/Constructors
2082 // that might return multiple matches.
2084 public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type,
2085 MemberTypes mt, BindingFlags original_bf, string name)
2087 Timer.StartTimer (TimerType.MemberLookup);
2089 MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
2090 mt, original_bf, name);
2092 Timer.StopTimer (TimerType.MemberLookup);
2097 static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type,
2098 MemberTypes mt, BindingFlags original_bf, string name)
2100 BindingFlags bf = original_bf;
2102 ArrayList method_list = null;
2103 Type current_type = queried_type;
2104 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2106 bool always_ok_flag = false;
2107 bool skip_iface_check = true, used_cache = false;
2109 closure_name = name;
2110 closure_invocation_type = invocation_type;
2111 closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2112 closure_start_type = queried_type;
2115 // If we are a nested class, we always have access to our container
2118 if (invocation_type != null){
2119 string invocation_name = invocation_type.FullName;
2120 if (invocation_name.IndexOf ('+') != -1){
2121 string container = queried_type.FullName + "+";
2122 int container_length = container.Length;
2124 if (invocation_name.Length > container_length){
2125 string shared = invocation_name.Substring (0, container_length);
2127 if (shared == container)
2128 always_ok_flag = true;
2137 // `NonPublic' is lame, because it includes both protected and
2138 // private methods, so we need to control this behavior by
2139 // explicitly tracking if a private method is ok or not.
2141 // The possible cases are:
2142 // public, private and protected (internal does not come into the
2145 if (invocation_type != null){
2146 if (invocation_type == current_type){
2147 private_ok = (bf & BindingFlags.NonPublic) != 0;
2149 private_ok = always_ok_flag;
2151 if (private_ok || invocation_type.IsSubclassOf (current_type))
2152 bf = original_bf | BindingFlags.NonPublic;
2155 bf = original_bf & ~BindingFlags.NonPublic;
2158 closure_private_ok = private_ok;
2159 closure_queried_type = current_type;
2161 Timer.StopTimer (TimerType.MemberLookup);
2163 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2165 Timer.StartTimer (TimerType.MemberLookup);
2168 // When queried for an interface type, the cache will automatically check all
2169 // inherited members, so we don't need to do this here. However, this only
2170 // works if we already used the cache in the first iteration of this loop.
2172 // If we used the cache in any further iteration, we can still terminate the
2173 // loop since the cache always looks in all parent classes.
2179 skip_iface_check = false;
2181 if (current_type == TypeManager.object_type)
2184 current_type = current_type.BaseType;
2187 // This happens with interfaces, they have a null
2188 // basetype. Look members up in the Object class.
2190 if (current_type == null)
2191 current_type = TypeManager.object_type;
2194 if (list.Count == 0)
2198 // Events and types are returned by both `static' and `instance'
2199 // searches, which means that our above FindMembers will
2200 // return two copies of the same.
2202 if (list.Count == 1 && !(list [0] is MethodBase)){
2203 return (MemberInfo []) list;
2207 // Multiple properties: we query those just to find out the indexer
2210 if (list [0] is PropertyInfo)
2211 return (MemberInfo []) list;
2214 // We found methods, turn the search into "method scan"
2218 method_list = CopyNewMethods (method_list, list);
2219 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2220 } while (searching);
2222 if (method_list != null && method_list.Count > 0)
2223 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2226 // This happens if we already used the cache in the first iteration, in this case
2227 // the cache already looked in all interfaces.
2229 if (skip_iface_check)
2233 // Interfaces do not list members they inherit, so we have to
2236 if (!queried_type.IsInterface)
2239 if (queried_type.IsArray)
2240 queried_type = TypeManager.array_type;
2242 Type [] ifaces = GetInterfaces (queried_type);
2246 foreach (Type itype in ifaces){
2249 x = MemberLookup (null, itype, mt, bf, name);
2261 /// There is exactly one instance of this class per type.
2263 public sealed class TypeHandle : IMemberContainer {
2264 public readonly TypeHandle BaseType;
2266 readonly int id = ++next_id;
2267 static int next_id = 0;
2270 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2271 /// a TypeHandle yet, a new instance of it is created. This static method
2272 /// ensures that we'll only have one TypeHandle instance per type.
2274 public static TypeHandle GetTypeHandle (Type t)
2276 TypeHandle handle = (TypeHandle) type_hash [t];
2280 handle = new TypeHandle (t);
2281 type_hash.Add (t, handle);
2286 /// Returns the TypeHandle for TypeManager.object_type.
2288 public static IMemberContainer ObjectType {
2290 if (object_type != null)
2293 object_type = GetTypeHandle (TypeManager.object_type);
2300 /// Returns the TypeHandle for TypeManager.array_type.
2302 public static IMemberContainer ArrayType {
2304 if (array_type != null)
2307 array_type = GetTypeHandle (TypeManager.array_type);
2313 private static PtrHashtable type_hash = new PtrHashtable ();
2315 private static TypeHandle object_type = null;
2316 private static TypeHandle array_type = null;
2319 private bool is_interface;
2320 private MemberCache member_cache;
2322 private TypeHandle (Type type)
2325 if (type.BaseType != null)
2326 BaseType = GetTypeHandle (type.BaseType);
2327 else if ((type != TypeManager.object_type) && (type != typeof (object)))
2328 is_interface = true;
2329 this.member_cache = new MemberCache (this);
2332 // IMemberContainer methods
2334 public string Name {
2336 return type.FullName;
2346 public IMemberContainer Parent {
2352 public bool IsInterface {
2354 return is_interface;
2358 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2360 if (mt == MemberTypes.Event)
2361 return new MemberList (type.GetEvents (bf | BindingFlags.DeclaredOnly));
2363 return new MemberList (type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2367 // IMemberFinder methods
2369 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2370 MemberFilter filter, object criteria)
2372 return member_cache.FindMembers (mt, bf, name, filter, criteria);
2375 public MemberCache MemberCache {
2377 return member_cache;
2381 public override string ToString ()
2383 if (BaseType != null)
2384 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2386 return "TypeHandle (" + id + "," + Name + ")";