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.MonoBASIC {
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 date_type;
41 static public Type bool_type;
42 static public Type sbyte_type;
43 static public Type byte_type;
44 static public Type ushort_type;
45 static public Type enum_type;
46 static public Type delegate_type;
47 static public Type multicast_delegate_type;
48 static public Type void_type;
49 static public Type enumeration_type;
50 static public Type array_type;
51 static public Type runtime_handle_type;
52 static public Type icloneable_type;
53 static public Type type_type;
54 static public Type ienumerator_type;
55 static public Type idisposable_type;
56 static public Type default_member_type;
57 static public Type iasyncresult_type;
58 static public Type asynccallback_type;
59 static public Type intptr_type;
60 static public Type monitor_type;
61 static public Type runtime_field_handle_type;
62 static public Type attribute_type;
63 static public Type attribute_usage_type;
64 static public Type dllimport_type;
65 static public Type unverifiable_code_type;
66 static public Type methodimpl_attr_type;
67 static public Type marshal_as_attr_type;
68 static public Type param_array_type;
69 static public Type void_ptr_type;
70 static public Type indexer_name_type;
71 static public Type exception_type;
72 static public object obsolete_attribute_type;
73 static public object conditional_attribute_type;
76 // An empty array of types
78 static public Type [] NoTypes;
82 // Expressions representing the internal types. Used during declaration
85 static public Expression system_object_expr, system_string_expr;
86 static public Expression system_boolean_expr, system_decimal_expr;
87 static public Expression system_single_expr, system_double_expr;
88 static public Expression system_sbyte_expr, system_byte_expr;
89 static public Expression system_int16_expr, system_uint16_expr;
90 static public Expression system_int32_expr, system_uint32_expr;
91 static public Expression system_int64_expr, system_uint64_expr;
92 static public Expression system_char_expr, system_void_expr;
93 static public Expression system_date_expr;
94 static public Expression system_asynccallback_expr;
95 static public Expression system_iasyncresult_expr;
98 // This is only used when compiling corlib
100 static public Type system_int32_type;
101 static public Type system_array_type;
102 static public Type system_type_type;
103 static public Type system_assemblybuilder_type;
104 static public MethodInfo system_int_array_get_length;
105 static public MethodInfo system_int_array_get_rank;
106 static public MethodInfo system_object_array_clone;
107 static public MethodInfo system_int_array_get_length_int;
108 static public MethodInfo system_int_array_get_lower_bound_int;
109 static public MethodInfo system_int_array_get_upper_bound_int;
110 static public MethodInfo system_void_array_copyto_array_int;
111 static public MethodInfo system_void_set_corlib_type_builders;
115 // Internal, not really used outside
117 static Type runtime_helpers_type;
120 // These methods are called by code generated by the compiler
122 static public MethodInfo string_concat_string_string;
123 static public MethodInfo string_concat_object_object;
124 static public MethodInfo string_isinterneted_string;
125 static public MethodInfo system_type_get_type_from_handle;
126 static public MethodInfo object_getcurrent_void;
127 static public MethodInfo bool_movenext_void;
128 static public MethodInfo void_dispose_void;
129 static public MethodInfo void_monitor_enter_object;
130 static public MethodInfo void_monitor_exit_object;
131 static public MethodInfo void_initializearray_array_fieldhandle;
132 static public MethodInfo int_getlength_int;
133 static public MethodInfo delegate_combine_delegate_delegate;
134 static public MethodInfo delegate_remove_delegate_delegate;
135 static public MethodInfo int_get_offset_to_string_data;
136 static public MethodInfo int_array_get_length;
137 static public MethodInfo int_array_get_rank;
138 static public MethodInfo object_array_clone;
139 static public MethodInfo int_array_get_length_int;
140 static public MethodInfo int_array_get_lower_bound_int;
141 static public MethodInfo int_array_get_upper_bound_int;
142 static public MethodInfo void_array_copyto_array_int;
145 // The attribute constructors.
147 static public ConstructorInfo cons_param_array_attribute;
148 static public ConstructorInfo void_decimal_ctor_five_args;
149 static public ConstructorInfo void_datetime_ctor_ticks_arg;
150 static public ConstructorInfo unverifiable_code_ctor;
153 // Holds the Array of Assemblies that have been loaded
154 // (either because it is the default or the user used the
155 // -r command line option)
157 static Assembly [] assemblies;
160 // Keeps a list of module builders. We used this to do lookups
161 // on the modulebuilder using GetType -- needed for arrays
163 static ModuleBuilder [] modules;
166 // This is the type_cache from the assemblies to avoid
167 // hitting System.Reflection on every lookup.
169 static CaseInsensitiveHashtable types;
172 // This is used to hotld the corresponding TypeContainer objects
173 // since we need this in FindMembers
175 static CaseInsensitiveHashtable typecontainers;
178 // Keeps track of those types that are defined by the
181 static ArrayList user_types;
183 static PtrHashtable builder_to_declspace;
186 // Tracks the interfaces implemented by typebuilders. We only
187 // enter those who do implement or or more interfaces
189 static PtrHashtable builder_to_ifaces;
192 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
193 // the arguments to the method
195 static Hashtable method_arguments;
198 // Maps PropertyBuilder to a Type array that contains
199 // the arguments to the indexer
201 static Hashtable indexer_arguments;
204 // Maybe 'method_arguments' should be replaced and only
205 // method_internal_params should be kept?
207 static Hashtable method_internal_params;
210 // Keeps track of attribute types
213 static Hashtable builder_to_attr;
216 // Keeps track of methods
219 static Hashtable builder_to_method;
227 /// A filter for Findmembers that uses the Signature object to
230 static bool SignatureFilter (MemberInfo mi, object criteria)
232 Signature sig = (Signature) criteria;
234 if (!(mi is MethodBase))
237 if (mi.Name != sig.name)
240 int count = sig.args.Length;
242 if (mi is MethodBuilder || mi is ConstructorBuilder){
243 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
245 if (candidate_args.Length != count)
248 for (int i = 0; i < count; i++)
249 if (candidate_args [i] != sig.args [i])
254 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
256 if (pars.Length != count)
259 for (int i = 0; i < count; i++)
260 if (pars [i].ParameterType != sig.args [i])
266 // A delegate that points to the filter above.
267 static MemberFilter signature_filter;
270 // These are expressions that represent some of the internal data types, used
273 static void InitExpressionTypes ()
275 system_object_expr = new TypeLookupExpression ("System.Object");
276 system_string_expr = new TypeLookupExpression ("System.String");
277 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
278 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
279 system_single_expr = new TypeLookupExpression ("System.Single");
280 system_double_expr = new TypeLookupExpression ("System.Double");
281 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
282 system_byte_expr = new TypeLookupExpression ("System.Byte");
283 system_int16_expr = new TypeLookupExpression ("System.Int16");
284 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
285 system_int32_expr = new TypeLookupExpression ("System.Int32");
286 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
287 system_int64_expr = new TypeLookupExpression ("System.Int64");
288 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
289 system_char_expr = new TypeLookupExpression ("System.Char");
290 system_void_expr = new TypeLookupExpression ("System.Void");
291 system_date_expr = new TypeLookupExpression ("System.DateTime");
292 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
293 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
296 static TypeManager ()
298 assemblies = new Assembly [0];
300 user_types = new ArrayList ();
302 types = new CaseInsensitiveHashtable ();
303 typecontainers = new CaseInsensitiveHashtable ();
305 builder_to_declspace = new PtrHashtable ();
306 builder_to_attr = new PtrHashtable ();
307 builder_to_method = new PtrHashtable ();
308 method_arguments = new PtrHashtable ();
309 method_internal_params = new PtrHashtable ();
310 indexer_arguments = new PtrHashtable ();
311 builder_to_ifaces = new PtrHashtable ();
313 NoTypes = new Type [0];
315 signature_filter = new MemberFilter (SignatureFilter);
316 InitExpressionTypes ();
319 public static void AddUserType (string name, TypeBuilder t, Type [] ifaces)
324 Type prev = (Type) types [name];
325 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
329 // This probably never happens, as we catch this before
331 Report.Error (-17, "The type '" + name + "' has already been defined.");
335 tc = builder_to_declspace [t] as TypeContainer;
338 1595, "The type '" + name + "' is defined in an existing assembly;"+
339 " Using the new definition from: " + tc.Location);
340 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
348 builder_to_ifaces [t] = ifaces;
352 // This entry point is used by types that we define under the covers
354 public static void RegisterBuilder (TypeBuilder tb, Type [] ifaces)
357 builder_to_ifaces [tb] = ifaces;
360 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc, Type [] ifaces)
362 builder_to_declspace.Add (t, tc);
363 typecontainers.Add (name, tc);
364 AddUserType (name, t, ifaces);
367 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
370 builder_to_declspace.Add (t, del);
373 public static void AddEnumType (string name, TypeBuilder t, Enum en)
376 builder_to_declspace.Add (t, en);
379 public static void AddUserInterface (string name, TypeBuilder t, Interface i, Type [] ifaces)
381 AddUserType (name, t, ifaces);
382 builder_to_declspace.Add (t, i);
385 public static void AddMethod (MethodBuilder builder, MethodData method)
387 builder_to_method.Add (builder, method);
390 public static void RegisterAttrType (Type t, TypeContainer tc)
392 builder_to_attr.Add (t, tc);
396 /// Returns the TypeContainer whose Type is 't' or null if there is no
397 /// TypeContainer for 't' (ie, the Type comes from a library)
399 public static TypeContainer LookupTypeContainer (Type t)
401 return builder_to_declspace [t] as TypeContainer;
404 public static IMemberContainer LookupMemberContainer (Type t)
406 if (t is TypeBuilder) {
407 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
408 if (container != null)
412 return TypeHandle.GetTypeHandle (t);
415 public static Interface LookupInterface (Type t)
417 return builder_to_declspace [t] as Interface;
420 public static Delegate LookupDelegate (Type t)
422 return builder_to_declspace [t] as Delegate;
425 public static Enum LookupEnum (Type t)
427 return builder_to_declspace [t] as Enum;
430 public static TypeContainer LookupAttr (Type t)
432 return (TypeContainer) builder_to_attr [t];
436 /// Registers an assembly to load types from.
438 public static void AddAssembly (Assembly a)
440 int top = assemblies.Length;
441 Assembly [] n = new Assembly [top + 1];
443 assemblies.CopyTo (n, 0);
448 foreach(Type type in a.GetTypes()) {
449 if (type.IsPublic ) // && type. attributed as standard module
450 AddStandardModule(type);
455 /// Registers a module builder to lookup types from
457 public static void AddModule (ModuleBuilder mb)
459 int top = modules != null ? modules.Length : 0;
460 ModuleBuilder [] n = new ModuleBuilder [top + 1];
463 modules.CopyTo (n, 0);
469 private class StandardModule {
470 public readonly string Namespace;
471 public readonly string Name;
472 public StandardModule(string _namespace, string name) { Namespace = _namespace; Name = name; }
473 public override string ToString() { return ((Namespace != null && Namespace.Length > 0)?(Namespace + "."):"") + Name; }
476 private static StandardModule[] standardModules;
479 /// Registers a new 'standard module' to lookup short-qualified or unqualified members
481 internal static void AddStandardModule(Module module)
483 int top = standardModules != null ? standardModules.Length : 0;
484 StandardModule [] n = new StandardModule [top + 1];
486 if (standardModules != null)
487 standardModules.CopyTo (n, 0);
488 n [top] = new StandardModule(module.Namespace.Name, module.Name) ;
493 /// Registers a existing 'standard module' to lookup short-qualified or unqualified members
495 private static void AddStandardModule(Type type)
497 object[] attributes = type.GetCustomAttributes(false);
498 for (int i = 0; i < attributes.Length; i ++) {
499 if (attributes[i].ToString() == "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute") {
500 int top = standardModules != null ? standardModules.Length : 0;
501 StandardModule [] n = new StandardModule [top + 1];
503 if (standardModules != null)
504 standardModules.CopyTo (n, 0);
505 n [top] = new StandardModule(type.Namespace, type.Name) ;
516 public static Type[] GetPertinentStandardModules(string[] namespaces)
518 ArrayList list = new ArrayList();
519 foreach(string Namespace in namespaces)
521 for(int i = 0; i < standardModules.Length; i++)
522 if (standardModules[i].Namespace == Namespace)
523 list.Add(LookupType(standardModules[i].ToString()));
525 return (Type[])list.ToArray(typeof(Type));
529 // Low-level lookup, cache-less
531 static Type LookupTypeReflection (string name)
536 foreach (Assembly a in assemblies){
537 t = a.GetType (name, false, true);
542 foreach (ModuleBuilder mb in modules) {
543 t = mb.GetType (name, false, true);
548 } catch (Exception e) {
549 System.Console.WriteLine("\nERROR: " + e.ToString() + "WHILE EXECUTING LookupTypeReflection(\"" + name + "\")\n");
555 // This function is used when you want to avoid the lookups, and want to go
556 // directly to the source. This will use the cache.
558 // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
559 // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
560 // way to test things other than doing a fullname compare
562 public static Type LookupTypeDirect (string name)
564 Type t = (Type) types [name];
568 t = LookupTypeReflection (name);
577 /// Returns the Type associated with @name, takes care of the fact that
578 /// reflection expects nested types to be separated from the main type
579 /// with a "+" instead of a "."
581 public static Type LookupType (string name)
586 // First lookup in user defined and cached values
589 t = (Type) types [name];
594 // Optimization: ComposedCast will work with an existing type, and might already have the
595 // full name of the type, so the full system lookup can probably be avoided.
598 string [] elements = name.Split ('.');
599 int count = elements.Length;
601 for (int n = 1; n <= count; n++){
602 string top_level_type = String.Join (".", elements, 0, n);
604 t = (Type) types [top_level_type];
606 t = LookupTypeReflection (top_level_type);
616 string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
617 t = LookupTypeDirect (newt);
626 // Returns a list of all namespaces in the assemblies and types loaded.
628 public static CaseInsensitiveHashtable GetNamespaces ()
630 CaseInsensitiveHashtable namespaces = new CaseInsensitiveHashtable ();
632 foreach (Assembly a in assemblies){
633 foreach (Type t in a.GetTypes ()){
634 string ns = t.Namespace;
636 if (namespaces.Contains (ns))
638 namespaces [ns] = ns;
642 foreach (ModuleBuilder mb in modules){
643 foreach (Type t in mb.GetTypes ()){
644 string ns = t.Namespace;
646 if (namespaces.Contains (ns))
648 namespaces [ns] = ns;
655 /// Returns the C# name of a type if possible, or the full type name otherwise
657 static public string MonoBASIC_Name (Type t)
659 return Regex.Replace (t.FullName,
661 @"(Int32|Int16|Int64|Single|Double|Char|Decimal|Byte|Object|Boolean|String|DateTime)" +
663 new MatchEvaluator (MonoBASIC_NameMatch));
666 static String MonoBASIC_NameMatch (Match match)
668 string s = match.Groups [1].Captures [0].Value;
670 Replace ("int32", "integer").
671 Replace ("int16", "short").
672 Replace ("int64", "long").
673 Replace ("datetime", "date")
674 + match.Groups [2].Captures [0].Value;
678 /// Returns the signature of the method
680 static public string MonoBASIC_Signature (MethodBase mb)
685 // FIXME: We should really have a single function to do
686 // everything instead of the following 5 line pattern
688 ParameterData iparams = LookupParametersByBuilder (mb);
690 if (iparams == null){
691 ParameterInfo [] pi = mb.GetParameters ();
692 iparams = new ReflectionParameters (pi);
695 for (int i = 0; i < iparams.Count; i++) {
699 sig += iparams.ParameterDesc(i);
703 return mb.DeclaringType.Name + "." + mb.Name + sig;
707 /// Looks up a type, and aborts if it is not found. This is used
708 /// by types required by the compiler
710 static Type CoreLookupType (string name)
712 Type t = LookupType (name);
715 Report.Error (518, "The predefined type '" + name + "' is not defined or imported");
716 Environment.Exit (0);
723 /// Returns the MethodInfo for a method named 'name' defined
724 /// in type 't' which takes arguments of types 'args'
726 static MethodInfo GetMethod (Type t, string name, Type [] args)
734 list = FindMembers (t, MemberTypes.Method, instance_and_static | BindingFlags.Public| BindingFlags.IgnoreCase,
735 signature_filter, sig);
736 if (list.Count == 0) {
737 Report.Error (-19, "Can not find the core function '" + name + "'");
741 MethodInfo mi = list [0] as MethodInfo;
743 Report.Error (-19, "Can not find the core function '" + name + "'");
751 /// Returns the ConstructorInfo for "args"
753 public static ConstructorInfo GetConstructor (Type t, Type [] args)
761 list = FindMembers (t, MemberTypes.Constructor,
762 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
763 signature_filter, sig);
764 if (list.Count == 0){
765 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
769 ConstructorInfo ci = list [0] as ConstructorInfo;
771 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
778 public static void InitEnumUnderlyingTypes ()
781 int32_type = CoreLookupType ("System.Int32");
782 int64_type = CoreLookupType ("System.Int64");
783 uint32_type = CoreLookupType ("System.UInt32");
784 uint64_type = CoreLookupType ("System.UInt64");
785 byte_type = CoreLookupType ("System.Byte");
786 sbyte_type = CoreLookupType ("System.SByte");
787 short_type = CoreLookupType ("System.Int16");
788 ushort_type = CoreLookupType ("System.UInt16");
792 /// The types have to be initialized after the initial
793 /// population of the type has happened (for example, to
794 /// bootstrap the corlib.dll
796 public static void InitCoreTypes ()
798 object_type = CoreLookupType ("System.Object");
799 value_type = CoreLookupType ("System.ValueType");
801 InitEnumUnderlyingTypes ();
803 char_type = CoreLookupType ("System.Char");
804 string_type = CoreLookupType ("System.String");
805 float_type = CoreLookupType ("System.Single");
806 double_type = CoreLookupType ("System.Double");
807 char_ptr_type = CoreLookupType ("System.Char*");
808 decimal_type = CoreLookupType ("System.Decimal");
809 bool_type = CoreLookupType ("System.Boolean");
810 enum_type = CoreLookupType ("System.Enum");
812 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
813 delegate_type = CoreLookupType ("System.Delegate");
815 array_type = CoreLookupType ("System.Array");
816 void_type = CoreLookupType ("System.Void");
817 date_type = CoreLookupType ("System.DateTime");
818 type_type = CoreLookupType ("System.Type");
820 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
821 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
822 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
823 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
824 asynccallback_type = CoreLookupType ("System.AsyncCallback");
825 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
826 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
827 idisposable_type = CoreLookupType ("System.IDisposable");
828 icloneable_type = CoreLookupType ("System.ICloneable");
829 monitor_type = CoreLookupType ("System.Threading.Monitor");
830 intptr_type = CoreLookupType ("System.IntPtr");
832 attribute_type = CoreLookupType ("System.Attribute");
833 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
834 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
835 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
836 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
837 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
839 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
841 void_ptr_type = CoreLookupType ("System.Void*");
843 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
845 exception_type = CoreLookupType ("System.Exception");
850 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
851 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
854 // When compiling corlib, store the "real" types here.
856 if (!RootContext.StdLib) {
857 system_int32_type = typeof (System.Int32);
858 system_array_type = typeof (System.Array);
859 system_type_type = typeof (System.Type);
860 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
862 Type [] void_arg = { };
863 system_int_array_get_length = GetMethod (
864 system_array_type, "get_Length", void_arg);
865 system_int_array_get_rank = GetMethod (
866 system_array_type, "get_Rank", void_arg);
867 system_object_array_clone = GetMethod (
868 system_array_type, "Clone", void_arg);
870 Type [] system_int_arg = { system_int32_type };
871 system_int_array_get_length_int = GetMethod (
872 system_array_type, "GetLength", system_int_arg);
873 system_int_array_get_upper_bound_int = GetMethod (
874 system_array_type, "GetUpperBound", system_int_arg);
875 system_int_array_get_lower_bound_int = GetMethod (
876 system_array_type, "GetLowerBound", system_int_arg);
878 Type [] system_array_int_arg = { system_array_type, system_int32_type };
879 system_void_array_copyto_array_int = GetMethod (
880 system_array_type, "CopyTo", system_array_int_arg);
882 Type [] system_type_type_arg = { system_type_type, system_type_type, system_type_type };
885 system_void_set_corlib_type_builders = GetMethod (
886 system_assemblybuilder_type, "SetCorlibTypeBuilders",
887 system_type_type_arg);
889 object[] args = new object [3];
890 args [0] = object_type;
891 args [1] = value_type;
892 args [2] = enum_type;
894 system_void_set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
896 Console.WriteLine ("Corlib compilation is not supported in Microsoft.NET due to bugs in it");
902 // The helper methods that are used by the compiler
904 public static void InitCodeHelpers ()
907 // Now load the default methods that we use.
909 Type [] string_string = { string_type, string_type };
910 string_concat_string_string = GetMethod (
911 string_type, "Concat", string_string);
913 Type [] object_object = { object_type, object_type };
914 string_concat_object_object = GetMethod (
915 string_type, "Concat", object_object);
917 Type [] string_ = { string_type };
918 string_isinterneted_string = GetMethod (
919 string_type, "IsInterned", string_);
921 Type [] runtime_type_handle = { runtime_handle_type };
922 system_type_get_type_from_handle = GetMethod (
923 type_type, "GetTypeFromHandle", runtime_type_handle);
925 Type [] delegate_delegate = { delegate_type, delegate_type };
926 delegate_combine_delegate_delegate = GetMethod (
927 delegate_type, "Combine", delegate_delegate);
929 delegate_remove_delegate_delegate = GetMethod (
930 delegate_type, "Remove", delegate_delegate);
935 Type [] void_arg = { };
936 object_getcurrent_void = GetMethod (
937 ienumerator_type, "get_Current", void_arg);
938 bool_movenext_void = GetMethod (
939 ienumerator_type, "MoveNext", void_arg);
940 void_dispose_void = GetMethod (
941 idisposable_type, "Dispose", void_arg);
942 int_get_offset_to_string_data = GetMethod (
943 runtime_helpers_type, "get_OffsetToStringData", void_arg);
944 int_array_get_length = GetMethod (
945 array_type, "get_Length", void_arg);
946 int_array_get_rank = GetMethod (
947 array_type, "get_Rank", void_arg);
952 Type [] int_arg = { int32_type };
953 int_array_get_length_int = GetMethod (
954 array_type, "GetLength", int_arg);
955 int_array_get_upper_bound_int = GetMethod (
956 array_type, "GetUpperBound", int_arg);
957 int_array_get_lower_bound_int = GetMethod (
958 array_type, "GetLowerBound", int_arg);
961 // System.Array methods
963 object_array_clone = GetMethod (
964 array_type, "Clone", void_arg);
965 Type [] array_int_arg = { array_type, int32_type };
966 void_array_copyto_array_int = GetMethod (
967 array_type, "CopyTo", array_int_arg);
972 Type [] object_arg = { object_type };
973 void_monitor_enter_object = GetMethod (
974 monitor_type, "Enter", object_arg);
975 void_monitor_exit_object = GetMethod (
976 monitor_type, "Exit", object_arg);
978 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
980 void_initializearray_array_fieldhandle = GetMethod (
981 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
986 int_getlength_int = GetMethod (
987 array_type, "GetLength", int_arg);
990 // Decimal constructors
992 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
993 void_decimal_ctor_five_args = GetConstructor (
994 decimal_type, dec_arg);
996 // DateTime constructor
997 Type [] ticks_arg = { int64_type };
998 void_datetime_ctor_ticks_arg = GetConstructor ( date_type, ticks_arg);
1003 cons_param_array_attribute = GetConstructor (
1004 param_array_type, void_arg);
1006 unverifiable_code_ctor = GetConstructor (
1007 unverifiable_code_type, void_arg);
1011 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1013 static CaseInsensitiveHashtable type_hash = new CaseInsensitiveHashtable ();
1016 /// This is the "old", non-cache based FindMembers() function. We cannot use
1017 /// the cache here because there is no member name argument.
1019 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1020 MemberFilter filter, object criteria)
1022 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1023 bf |= BindingFlags.IgnoreCase;
1025 // 'builder_to_declspace' contains all dynamic types.
1029 Timer.StartTimer (TimerType.FindMembers);
1030 list = decl.FindMembers (mt, bf, filter, criteria);
1031 Timer.StopTimer (TimerType.FindMembers);
1036 // We have to take care of arrays specially, because GetType on
1037 // a TypeBuilder array will return a Type, not a TypeBuilder,
1038 // and we can not call FindMembers on this type.
1040 if (t.IsSubclassOf (TypeManager.array_type))
1041 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1044 // Since FindMembers will not lookup both static and instance
1045 // members, we emulate this behaviour here.
1047 if ((bf & instance_and_static) == instance_and_static){
1048 MemberInfo [] i_members = t.FindMembers (
1049 mt, (bf & ~BindingFlags.Static) | BindingFlags.IgnoreCase, filter, criteria);
1051 int i_len = i_members.Length;
1053 MemberInfo one = i_members [0];
1056 // If any of these are present, we are done!
1058 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1059 return new MemberList (i_members);
1062 MemberInfo [] s_members = t.FindMembers (
1063 mt, (bf & ~BindingFlags.Instance) | BindingFlags.IgnoreCase, filter, criteria);
1065 int s_len = s_members.Length;
1066 if (i_len > 0 || s_len > 0)
1067 return new MemberList (i_members, s_members);
1070 return new MemberList (i_members);
1072 return new MemberList (s_members);
1076 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1081 /// This method is only called from within MemberLookup. It tries to use the member
1082 /// cache if possible and falls back to the normal FindMembers if not. The 'used_cache'
1083 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1084 /// our return value will already contain all inherited members and the caller don't need
1085 /// to check base classes and interfaces anymore.
1087 private static MemberList MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1088 string name, out bool used_cache)
1091 // We have to take care of arrays specially, because GetType on
1092 // a TypeBuilder array will return a Type, not a TypeBuilder,
1093 // and we can not call FindMembers on this type.
1095 if (t.IsSubclassOf (TypeManager.array_type)) {
1097 return TypeHandle.ArrayType.MemberCache.FindMembers (
1098 mt, bf, name, FilterWithClosure_delegate, null);
1102 // If this is a dynamic type, it's always in the 'builder_to_declspace' hash table
1103 // and we can ask the DeclSpace for the MemberCache.
1105 if (t is TypeBuilder) {
1106 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1107 MemberCache cache = decl.MemberCache;
1110 // If this DeclSpace has a MemberCache, use it.
1113 if (cache != null) {
1115 return cache.FindMembers (
1116 mt, bf, name, FilterWithClosure_delegate, null);
1119 // If there is no MemberCache, we need to use the "normal" FindMembers.
1122 Timer.StartTimer (TimerType.FindMembers);
1123 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
1124 FilterWithClosure_delegate, name);
1125 Timer.StopTimer (TimerType.FindMembers);
1131 // This call will always succeed. There is exactly one TypeHandle instance per
1132 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1133 // if it didn't already exist.
1135 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1138 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1141 public static bool IsBuiltinType (Type t)
1143 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1144 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1145 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1146 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type ||
1153 public static bool IsDelegateType (Type t)
1155 if (t.IsSubclassOf (TypeManager.delegate_type))
1161 public static bool IsEnumType (Type t)
1163 if (t.IsSubclassOf (TypeManager.enum_type))
1170 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1172 public static bool IsUnmanagedType (Type t)
1174 if (IsBuiltinType (t) && t != TypeManager.string_type)
1183 if (IsValueType (t)){
1184 if (t is TypeBuilder){
1185 TypeContainer tc = LookupTypeContainer (t);
1187 foreach (Field f in tc.Fields){
1188 if (f.FieldBuilder.IsStatic)
1190 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1194 FieldInfo [] fields = t.GetFields ();
1196 foreach (FieldInfo f in fields){
1199 if (!IsUnmanagedType (f.FieldType))
1209 public static bool IsValueType (Type t)
1211 if (t.IsSubclassOf (TypeManager.value_type))
1217 public static bool IsInterfaceType (Type t)
1219 Interface iface = builder_to_declspace [t] as Interface;
1228 // Checks whether 'type' is a subclass or nested child of 'parent'.
1230 public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1233 if ((type == parent) || type.IsSubclassOf (parent))
1236 // Handle nested types.
1237 type = type.DeclaringType;
1238 } while (type != null);
1244 // Checks whether 'type' is a nested child of 'parent'.
1246 public static bool IsNestedChildOf (Type type, Type parent)
1248 if ((type == parent) || type.IsSubclassOf (parent))
1251 return IsSubclassOrNestedChildOf (type, parent);
1255 /// Returns the User Defined Types
1257 public static ArrayList UserTypes {
1263 public static CaseInsensitiveHashtable TypeContainers {
1265 return typecontainers;
1269 static Hashtable builder_to_constant;
1271 public static void RegisterConstant (FieldBuilder fb, Const c)
1273 if (builder_to_constant == null)
1274 builder_to_constant = new PtrHashtable ();
1276 if (builder_to_constant.Contains (fb))
1279 builder_to_constant.Add (fb, c);
1282 public static Const LookupConstant (FieldBuilder fb)
1284 if (builder_to_constant == null)
1287 return (Const) builder_to_constant [fb];
1291 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1295 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1296 /// for anything which is dynamic, and we need this in a number of places,
1297 /// we register this information here, and use it afterwards.
1299 static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1304 method_arguments.Add (mb, args);
1305 method_internal_params.Add (mb, ip);
1310 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1312 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1315 if (method_internal_params.Contains (mb))
1316 return (InternalParameters) method_internal_params [mb];
1318 throw new Exception ("Argument for Method not registered" + mb);
1322 /// Returns the argument types for a method based on its methodbase
1324 /// For dynamic methods, we use the compiler provided types, for
1325 /// methods from existing assemblies we load them from GetParameters,
1326 /// and insert them into the cache
1328 static public Type [] GetArgumentTypes (MethodBase mb)
1330 if (method_arguments.Contains (mb))
1331 return (Type []) method_arguments [mb];
1333 ParameterInfo [] pi = mb.GetParameters ();
1335 Type [] types = new Type [c];
1337 for (int i = 0; i < c; i++)
1338 types [i] = pi [i].ParameterType;
1340 method_arguments.Add (mb, types);
1346 /// Returns the argument types for an indexer based on its PropertyInfo
1348 /// For dynamic indexers, we use the compiler provided types, for
1349 /// indexers from existing assemblies we load them from GetParameters,
1350 /// and insert them into the cache
1352 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1354 if (indexer_arguments.Contains (indexer))
1355 return (Type []) indexer_arguments [indexer];
1356 else if (indexer is PropertyBuilder)
1357 // If we're a PropertyBuilder and not in the
1358 // 'indexer_arguments' hash, then we're a property and
1362 ParameterInfo [] pi = indexer.GetIndexParameters ();
1363 // Property, not an indexer.
1367 Type [] types = new Type [c];
1369 for (int i = 0; i < c; i++)
1370 types [i] = pi [i].ParameterType;
1372 indexer_arguments.Add (indexer, types);
1378 // This is a workaround the fact that GetValue is not
1379 // supported for dynamic types
1381 static CaseInsensitiveHashtable fields = new CaseInsensitiveHashtable ();
1382 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1384 if (fields.Contains (fb))
1387 fields.Add (fb, value);
1392 static public object GetValue (FieldBuilder fb)
1397 static CaseInsensitiveHashtable fieldbuilders_to_fields = new CaseInsensitiveHashtable ();
1398 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1400 if (fieldbuilders_to_fields.Contains (fb))
1403 fieldbuilders_to_fields.Add (fb, f);
1407 static public FieldBase GetField (FieldInfo fb)
1409 return (FieldBase) fieldbuilders_to_fields [fb];
1412 static CaseInsensitiveHashtable events;
1414 static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1417 events = new CaseInsensitiveHashtable ();
1419 if (events.Contains (eb))
1422 events.Add (eb, new Pair (add, remove));
1427 static public MethodInfo GetAddMethod (EventInfo ei)
1429 if (ei is MyEventBuilder) {
1430 Pair pair = (Pair) events [ei];
1432 return (MethodInfo) pair.First;
1434 return ei.GetAddMethod ();
1437 static public MethodInfo GetRemoveMethod (EventInfo ei)
1439 if (ei is MyEventBuilder) {
1440 Pair pair = (Pair) events [ei];
1442 return (MethodInfo) pair.Second;
1444 return ei.GetAddMethod ();
1447 static CaseInsensitiveHashtable priv_fields_events;
1449 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1451 if (priv_fields_events == null)
1452 priv_fields_events = new CaseInsensitiveHashtable ();
1454 if (priv_fields_events.Contains (einfo))
1457 priv_fields_events.Add (einfo, builder);
1462 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1464 return (MemberInfo) priv_fields_events [ei];
1467 static CaseInsensitiveHashtable properties;
1469 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1471 if (properties == null)
1472 properties = new CaseInsensitiveHashtable ();
1474 if (properties.Contains (pb))
1477 properties.Add (pb, new Pair (get, set));
1482 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get, MethodBase set, Type[] args)
1484 if (!RegisterProperty (pb, get,set))
1487 indexer_arguments.Add (pb, args);
1492 static public MethodInfo GetPropertyGetter (PropertyInfo pi)
1494 if (pi is PropertyBuilder){
1495 Pair de = (Pair) properties [pi];
1497 return (MethodInfo) de.Second;
1499 return pi.GetSetMethod ();
1502 static public MethodInfo GetPropertySetter (PropertyInfo pi)
1504 if (pi is PropertyBuilder){
1505 Pair de = (Pair) properties [pi];
1507 return (MethodInfo) de.First;
1509 return pi.GetGetMethod ();
1513 /// Given an array of interface types, expand and eliminate repeated ocurrences
1514 /// of an interface.
1518 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1521 public static Type [] ExpandInterfaces (Type [] base_interfaces)
1523 ArrayList new_ifaces = new ArrayList ();
1525 foreach (Type iface in base_interfaces){
1526 if (!new_ifaces.Contains (iface))
1527 new_ifaces.Add (iface);
1529 Type [] implementing = TypeManager.GetInterfaces (iface);
1531 foreach (Type imp in implementing){
1532 if (!new_ifaces.Contains (imp))
1533 new_ifaces.Add (imp);
1536 Type [] ret = new Type [new_ifaces.Count];
1537 new_ifaces.CopyTo (ret, 0);
1542 /// This function returns the interfaces in the type 't'. Works with
1543 /// both types and TypeBuilders.
1545 public static Type [] GetInterfaces (Type t)
1548 // The reason for catching the Array case is that Reflection.Emit
1549 // will not return a TypeBuilder for Array types of TypeBuilder types,
1550 // but will still throw an exception if we try to call GetInterfaces
1553 // Since the array interfaces are always constant, we return those for
1558 t = TypeManager.array_type;
1560 if (t is TypeBuilder){
1561 Type [] parent_ifaces;
1563 if (t.BaseType == null)
1564 parent_ifaces = NoTypes;
1566 parent_ifaces = GetInterfaces (t.BaseType);
1567 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1568 if (type_ifaces == null)
1569 type_ifaces = NoTypes;
1571 int parent_count = parent_ifaces.Length;
1572 Type [] result = new Type [parent_count + type_ifaces.Length];
1573 parent_ifaces.CopyTo (result, 0);
1574 type_ifaces.CopyTo (result, parent_count);
1578 return t.GetInterfaces ();
1582 /// The following is used to check if a given type implements an interface.
1583 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1585 public static bool ImplementsInterface (Type t, Type iface)
1590 // FIXME OPTIMIZATION:
1591 // as soon as we hit a non-TypeBuiler in the interface
1592 // chain, we could return, as the 'Type.GetInterfaces'
1593 // will return all the interfaces implement by the type
1597 interfaces = GetInterfaces (t);
1599 if (interfaces != null){
1600 foreach (Type i in interfaces){
1607 } while (t != null);
1612 // This is a custom version of Convert.ChangeType() which works
1613 // with the TypeBuilder defined types when compiling corlib.
1614 public static object ChangeType (object value, Type conversionType)
1616 if (!(value is IConvertible))
1617 throw new ArgumentException ();
1619 IConvertible convertValue = (IConvertible) value;
1620 CultureInfo ci = CultureInfo.CurrentCulture;
1621 NumberFormatInfo provider = ci.NumberFormat;
1624 // We must use Type.Equals() here since 'conversionType' is
1625 // the TypeBuilder created version of a system type and not
1626 // the system type itself. You cannot use Type.GetTypeCode()
1627 // on such a type - it'd always return TypeCode.Object.
1629 if (conversionType.Equals (typeof (Boolean)))
1630 return (object)(convertValue.ToBoolean (provider));
1631 else if (conversionType.Equals (typeof (Byte)))
1632 return (object)(convertValue.ToByte (provider));
1633 else if (conversionType.Equals (typeof (Char)))
1634 return (object)(convertValue.ToChar (provider));
1635 else if (conversionType.Equals (typeof (DateTime)))
1636 return (object)(convertValue.ToDateTime (provider));
1637 else if (conversionType.Equals (typeof (Decimal)))
1638 return (object)(convertValue.ToDecimal (provider));
1639 else if (conversionType.Equals (typeof (Double)))
1640 return (object)(convertValue.ToDouble (provider));
1641 else if (conversionType.Equals (typeof (Int16)))
1642 return (object)(convertValue.ToInt16 (provider));
1643 else if (conversionType.Equals (typeof (Int32)))
1644 return (object)(convertValue.ToInt32 (provider));
1645 else if (conversionType.Equals (typeof (Int64)))
1646 return (object)(convertValue.ToInt64 (provider));
1647 else if (conversionType.Equals (typeof (SByte)))
1648 return (object)(convertValue.ToSByte (provider));
1649 else if (conversionType.Equals (typeof (Single)))
1650 return (object)(convertValue.ToSingle (provider));
1651 else if (conversionType.Equals (typeof (String)))
1652 return (object)(convertValue.ToString (provider));
1653 else if (conversionType.Equals (typeof (UInt16)))
1654 return (object)(convertValue.ToUInt16 (provider));
1655 else if (conversionType.Equals (typeof (UInt32)))
1656 return (object)(convertValue.ToUInt32 (provider));
1657 else if (conversionType.Equals (typeof (UInt64)))
1658 return (object)(convertValue.ToUInt64 (provider));
1659 else if (conversionType.Equals (typeof (Object)))
1660 return (object)(value);
1662 throw new InvalidCastException ();
1666 // This is needed, because enumerations from assemblies
1667 // do not report their underlyingtype, but they report
1670 public static Type EnumToUnderlying (Type t)
1672 if (t == TypeManager.enum_type)
1675 t = t.UnderlyingSystemType;
1676 if (!TypeManager.IsEnumType (t))
1679 if (t is TypeBuilder) {
1680 // slow path needed to compile corlib
1681 if (t == TypeManager.bool_type ||
1682 t == TypeManager.byte_type ||
1683 t == TypeManager.sbyte_type ||
1684 t == TypeManager.char_type ||
1685 t == TypeManager.short_type ||
1686 t == TypeManager.ushort_type ||
1687 t == TypeManager.int32_type ||
1688 t == TypeManager.uint32_type ||
1689 t == TypeManager.int64_type ||
1690 t == TypeManager.uint64_type)
1692 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
1694 TypeCode tc = Type.GetTypeCode (t);
1697 case TypeCode.Boolean:
1698 return TypeManager.bool_type;
1700 return TypeManager.byte_type;
1701 case TypeCode.SByte:
1702 return TypeManager.sbyte_type;
1704 return TypeManager.char_type;
1705 case TypeCode.Int16:
1706 return TypeManager.short_type;
1707 case TypeCode.UInt16:
1708 return TypeManager.ushort_type;
1709 case TypeCode.Int32:
1710 return TypeManager.int32_type;
1711 case TypeCode.UInt32:
1712 return TypeManager.uint32_type;
1713 case TypeCode.Int64:
1714 return TypeManager.int64_type;
1715 case TypeCode.UInt64:
1716 return TypeManager.uint64_type;
1718 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1722 // When compiling corlib and called with one of the core types, return
1723 // the corresponding typebuilder for that type.
1725 public static Type TypeToCoreType (Type t)
1727 if (RootContext.StdLib || (t is TypeBuilder))
1730 TypeCode tc = Type.GetTypeCode (t);
1733 case TypeCode.Boolean:
1734 return TypeManager.bool_type;
1736 return TypeManager.byte_type;
1737 case TypeCode.SByte:
1738 return TypeManager.sbyte_type;
1740 return TypeManager.char_type;
1741 case TypeCode.Int16:
1742 return TypeManager.short_type;
1743 case TypeCode.UInt16:
1744 return TypeManager.ushort_type;
1745 case TypeCode.Int32:
1746 return TypeManager.int32_type;
1747 case TypeCode.UInt32:
1748 return TypeManager.uint32_type;
1749 case TypeCode.Int64:
1750 return TypeManager.int64_type;
1751 case TypeCode.UInt64:
1752 return TypeManager.uint64_type;
1753 case TypeCode.String:
1754 return TypeManager.string_type;
1755 case TypeCode.DateTime:
1756 return TypeManager.date_type;
1758 if (t == typeof (void))
1759 return TypeManager.void_type;
1760 if (t == typeof (object))
1761 return TypeManager.object_type;
1762 if (t == typeof (System.Type))
1763 return TypeManager.type_type;
1769 /// Utility function that can be used to probe whether a type
1770 /// is managed or not.
1772 public static bool VerifyUnManaged (Type t, Location loc)
1774 if (t.IsValueType || t.IsPointer){
1776 // FIXME: this is more complex, we actually need to
1777 // make sure that the type does not contain any
1783 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
1784 // We need this explicit check here to make it work when
1785 // compiling corlib.
1790 "Cannot take the address or size of a variable of a managed type ('" +
1791 MonoBASIC_Name (t) + "')");
1796 /// Returns the name of the indexer in a given type.
1799 /// The default is not always 'Item'. The user can change this behaviour by
1800 /// using the DefaultMemberAttribute in the class.
1802 /// For example, the String class indexer is named 'Chars' not 'Item'
1804 public static string IndexerPropertyName (Type t)
1806 if (t is TypeBuilder) {
1807 if (t.IsInterface) {
1808 Interface i = LookupInterface (t);
1810 if ((i == null) || (i.IndexerName == null))
1813 return i.IndexerName;
1815 TypeContainer tc = LookupTypeContainer (t);
1817 if ((tc == null) || (tc.IndexerName == null))
1820 return tc.IndexerName;
1824 System.Attribute attr = System.Attribute.GetCustomAttribute (
1825 t, TypeManager.default_member_type);
1827 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
1828 return dma.MemberName;
1834 public static void MakePinned (LocalBuilder builder)
1837 // FIXME: Flag the "LocalBuilder" type as being
1838 // pinned. Figure out API.
1844 // Returns whether the array of memberinfos contains the given method
1846 static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
1848 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
1850 foreach (MethodBase method in array){
1851 if (method.Name != new_method.Name)
1854 Type [] old_args = TypeManager.GetArgumentTypes (method);
1855 int old_count = old_args.Length;
1858 if (new_args.Length != old_count)
1861 for (i = 0; i < old_count; i++){
1862 if (old_args [i] != new_args [i])
1874 // We copy methods from 'new_members' into 'target_list' if the signature
1875 // for the method from in the new list does not exist in the target_list
1877 // The name is assumed to be the same.
1879 public static ArrayList CopyNewMethods (ArrayList target_list, MemberList new_members)
1881 if (target_list == null){
1882 target_list = new ArrayList ();
1884 foreach (MemberInfo mi in new_members){
1885 if (mi is MethodBase)
1886 target_list.Add (mi);
1891 MemberInfo [] target_array = new MemberInfo [target_list.Count];
1892 target_list.CopyTo (target_array, 0);
1894 foreach (MemberInfo mi in new_members){
1895 MethodBase new_method = (MethodBase) mi;
1897 if (!ArrayContainsMethod (target_array, new_method))
1898 target_list.Add (new_method);
1904 public enum MethodFlags {
1906 IsObsoleteError = 2,
1911 // Returns the TypeManager.MethodFlags for this method.
1912 // This emits an error 619 / warning 618 if the method is obsolete.
1913 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
1915 static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
1917 MethodFlags flags = 0;
1919 if (mb.DeclaringType is TypeBuilder){
1920 MethodData method = (MethodData) builder_to_method [mb];
1921 if (method == null) {
1922 // FIXME: implement Obsolete attribute on Property,
1923 // Indexer and Event.
1927 return method.GetMethodFlags (loc);
1930 object [] attrs = mb.GetCustomAttributes (true);
1931 foreach (object ta in attrs){
1932 if (!(ta is System.Attribute)){
1933 Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
1936 System.Attribute a = (System.Attribute) ta;
1937 if (a.TypeId == TypeManager.obsolete_attribute_type){
1938 ObsoleteAttribute oa = (ObsoleteAttribute) a;
1940 string method_desc = TypeManager.MonoBASIC_Signature (mb);
1943 Report.Error (619, loc, "Method '" + method_desc +
1944 "' is obsolete: '" + oa.Message + "'");
1945 return MethodFlags.IsObsoleteError;
1947 Report.Warning (618, loc, "Method '" + method_desc +
1948 "' is obsolete: '" + oa.Message + "'");
1950 flags |= MethodFlags.IsObsolete;
1956 // Skip over conditional code.
1958 if (a.TypeId == TypeManager.conditional_attribute_type){
1959 ConditionalAttribute ca = (ConditionalAttribute) a;
1961 if (RootContext.AllDefines [ca.ConditionString] == null)
1962 flags |= MethodFlags.ShouldIgnore;
1969 #region MemberLookup implementation
1972 // Name of the member
1974 static string closure_name;
1977 // Whether we allow private members in the result (since FindMembers
1978 // uses NonPublic for both protected and private), we need to distinguish.
1980 static bool closure_private_ok;
1983 // Who is invoking us and which type is being queried currently.
1985 static Type closure_invocation_type;
1986 static Type closure_queried_type;
1987 static Type closure_start_type;
1990 // The assembly that defines the type is that is calling us
1992 static Assembly closure_invocation_assembly;
1995 // This filter filters by name + whether it is ok to include private
1996 // members in the search
1998 static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
2001 // Hack: we know that the filter criteria will always be in the 'closure'
2005 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2008 if ((closure_start_type == closure_invocation_type) &&
2009 (m.DeclaringType == closure_invocation_type))
2013 // Ugly: we need to find out the type of 'm', and depending
2014 // on this, tell whether we accept or not
2016 if (m is MethodBase){
2017 MethodBase mb = (MethodBase) m;
2018 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2020 if (ma == MethodAttributes.Private)
2021 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2024 // FamAndAssem requires that we not only derivate, but we are on the
2027 if (ma == MethodAttributes.FamANDAssem){
2028 if (closure_invocation_assembly != mb.DeclaringType.Assembly)
2032 // Assembly and FamORAssem succeed if we're in the same assembly.
2033 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2034 if (closure_invocation_assembly == mb.DeclaringType.Assembly)
2038 // We already know that we aren't in the same assembly.
2039 if (ma == MethodAttributes.Assembly)
2042 // Family and FamANDAssem require that we derive.
2043 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
2044 if (closure_invocation_type == null)
2047 if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
2057 if (m is FieldInfo){
2058 FieldInfo fi = (FieldInfo) m;
2059 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2061 if (fa == FieldAttributes.Private)
2062 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2065 // FamAndAssem requires that we not only derivate, but we are on the
2068 if (fa == FieldAttributes.FamANDAssem){
2069 if (closure_invocation_assembly != fi.DeclaringType.Assembly)
2073 // Assembly and FamORAssem succeed if we're in the same assembly.
2074 if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2075 if (closure_invocation_assembly == fi.DeclaringType.Assembly)
2079 // We already know that we aren't in the same assembly.
2080 if (fa == FieldAttributes.Assembly)
2083 // Family and FamANDAssem require that we derive.
2084 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
2085 if (closure_invocation_type == null)
2088 if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.DeclaringType))
2091 // Although a derived class can access protected members of its base class
2092 // it cannot do so through an instance of the base class (CS1540).
2093 if ((closure_invocation_type != closure_start_type) &&
2094 closure_invocation_type.IsSubclassOf (closure_start_type))
2105 // EventInfos and PropertyInfos, return true
2110 static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
2113 // Looks up a member called 'name' in the 'queried_type'. This lookup
2114 // is done by code that is contained in the definition for 'invocation_type'.
2116 // The binding flags are 'bf' and the kind of members being looked up are 'mt'
2118 // Returns an array of a single element for everything but Methods/Constructors
2119 // that might return multiple matches.
2121 public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type,
2122 MemberTypes mt, BindingFlags original_bf, string name)
2124 Timer.StartTimer (TimerType.MemberLookup);
2126 MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
2127 mt, original_bf, name);
2129 Timer.StopTimer (TimerType.MemberLookup);
2134 static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type,
2135 MemberTypes mt, BindingFlags original_bf, string name)
2137 BindingFlags bf = original_bf;
2139 ArrayList method_list = null;
2140 Type current_type = queried_type;
2141 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2143 bool always_ok_flag = false;
2144 bool skip_iface_check = true, used_cache = false;
2146 closure_name = name;
2147 closure_invocation_type = invocation_type;
2148 closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2149 closure_start_type = queried_type;
2152 // If we are a nested class, we always have access to our container
2155 if (invocation_type != null){
2156 string invocation_name = invocation_type.FullName;
2157 if (invocation_name.IndexOf ('+') != -1){
2158 string container = queried_type.FullName + "+";
2159 int container_length = container.Length;
2161 if (invocation_name.Length > container_length){
2162 string shared = invocation_name.Substring (0, container_length);
2164 if (shared == container)
2165 always_ok_flag = true;
2174 // 'NonPublic' is lame, because it includes both protected and
2175 // private methods, so we need to control this behavior by
2176 // explicitly tracking if a private method is ok or not.
2178 // The possible cases are:
2179 // public, private and protected (internal does not come into the
2182 if (invocation_type != null){
2183 if (invocation_type == current_type){
2184 private_ok = (bf & BindingFlags.NonPublic) != 0;
2186 private_ok = always_ok_flag;
2188 if (invocation_type.IsSubclassOf (current_type))
2192 bf = original_bf | BindingFlags.NonPublic;
2195 bf = original_bf & ~BindingFlags.NonPublic;
2198 closure_private_ok = private_ok;
2199 closure_queried_type = current_type;
2201 Timer.StopTimer (TimerType.MemberLookup);
2202 bf |= BindingFlags.IgnoreCase;
2203 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2205 Timer.StartTimer (TimerType.MemberLookup);
2208 // When queried for an interface type, the cache will automatically check all
2209 // inherited members, so we don't need to do this here. However, this only
2210 // works if we already used the cache in the first iteration of this loop.
2212 // If we used the cache in any further iteration, we can still terminate the
2213 // loop since the cache always looks in all parent classes.
2219 skip_iface_check = false;
2221 if (current_type == TypeManager.object_type)
2224 current_type = current_type.BaseType;
2227 // This happens with interfaces, they have a null
2228 // basetype. Look members up in the Object class.
2230 if (current_type == null)
2231 current_type = TypeManager.object_type;
2234 if (list.Count == 0)
2238 // Events and types are returned by both 'static' and 'instance'
2239 // searches, which means that our above FindMembers will
2240 // return two copies of the same.
2242 if (list.Count == 1 && !(list [0] is MethodBase)){
2243 return (MemberInfo []) list;
2247 // Multiple properties: we query those just to find out the indexer
2250 if (list [0] is PropertyInfo)
2251 return (MemberInfo []) list;
2254 // We found methods, turn the search into "method scan"
2258 method_list = CopyNewMethods (method_list, list);
2259 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2260 } while (searching);
2262 if (method_list != null && method_list.Count > 0)
2263 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2266 // This happens if we already used the cache in the first iteration, in this case
2267 // the cache already looked in all interfaces.
2269 if (skip_iface_check)
2273 // Interfaces do not list members they inherit, so we have to
2276 if (!queried_type.IsInterface)
2279 if (queried_type.IsArray)
2280 queried_type = TypeManager.array_type;
2282 Type [] ifaces = GetInterfaces (queried_type);
2286 foreach (Type itype in ifaces){
2289 x = MemberLookup (null, itype, mt, bf, name);
2301 /// There is exactly one instance of this class per type.
2303 public sealed class TypeHandle : IMemberContainer {
2304 public readonly TypeHandle BaseType;
2306 readonly int id = ++next_id;
2307 static int next_id = 0;
2310 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2311 /// a TypeHandle yet, a new instance of it is created. This static method
2312 /// ensures that we'll only have one TypeHandle instance per type.
2314 public static TypeHandle GetTypeHandle (Type t)
2316 TypeHandle handle = (TypeHandle) type_hash [t];
2320 handle = new TypeHandle (t);
2321 type_hash.Add (t, handle);
2326 /// Returns the TypeHandle for TypeManager.object_type.
2328 public static IMemberContainer ObjectType {
2330 if (object_type != null)
2333 object_type = GetTypeHandle (TypeManager.object_type);
2340 /// Returns the TypeHandle for TypeManager.array_type.
2342 public static IMemberContainer ArrayType {
2344 if (array_type != null)
2347 array_type = GetTypeHandle (TypeManager.array_type);
2353 private static PtrHashtable type_hash = new PtrHashtable ();
2355 private static TypeHandle object_type = null;
2356 private static TypeHandle array_type = null;
2359 private bool is_interface;
2360 private MemberCache member_cache;
2362 private TypeHandle (Type type)
2365 if (type.BaseType != null)
2366 BaseType = GetTypeHandle (type.BaseType);
2367 else if ((type != TypeManager.object_type) && (type != typeof (object)))
2368 is_interface = true;
2369 this.member_cache = new MemberCache (this);
2372 // IMemberContainer methods
2374 public string Name {
2376 return type.FullName;
2386 public IMemberContainer Parent {
2392 public bool IsInterface {
2394 return is_interface;
2398 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2400 if (mt == MemberTypes.Event)
2401 return new MemberList (type.GetEvents (bf | BindingFlags.DeclaredOnly));
2403 return new MemberList (type.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
2407 // IMemberFinder methods
2409 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2410 MemberFilter filter, object criteria)
2412 return member_cache.FindMembers (mt, bf, name, filter, criteria);
2415 public MemberCache MemberCache {
2417 return member_cache;
2421 public override string ToString ()
2423 if (BaseType != null)
2424 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2426 return "TypeHandle (" + id + "," + Name + ")";