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
164 // This is changed from list of ModuleBuilders
165 // to list of Modules for getting addmodule
166 // compiler option working
167 // Anirban - 13.07.2004
169 static System.Reflection.Module [] modules;
172 // This is the type_cache from the assemblies to avoid
173 // hitting System.Reflection on every lookup.
175 static CaseInsensitiveHashtable types;
178 // This is used to hotld the corresponding TypeContainer objects
179 // since we need this in FindMembers
181 static CaseInsensitiveHashtable typecontainers;
184 // Keeps track of those types that are defined by the
187 static ArrayList user_types;
189 static PtrHashtable builder_to_declspace;
192 // Tracks the interfaces implemented by typebuilders. We only
193 // enter those who do implement or or more interfaces
195 static PtrHashtable builder_to_ifaces;
198 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
199 // the arguments to the method
201 static Hashtable method_arguments;
204 // Maps PropertyBuilder to a Type array that contains
205 // the arguments to the indexer
207 static Hashtable indexer_arguments;
210 // Maybe 'method_arguments' should be replaced and only
211 // method_internal_params should be kept?
213 static Hashtable method_internal_params;
216 // Keeps track of attribute types
219 static Hashtable builder_to_attr;
222 // Keeps track of methods
225 static Hashtable builder_to_method;
233 /// A filter for Findmembers that uses the Signature object to
236 static bool SignatureFilter (MemberInfo mi, object criteria)
238 Signature sig = (Signature) criteria;
240 if (!(mi is MethodBase))
243 if (mi.Name != sig.name)
246 int count = sig.args.Length;
248 if (mi is MethodBuilder || mi is ConstructorBuilder){
249 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
251 if (candidate_args.Length != count)
254 for (int i = 0; i < count; i++)
255 if (candidate_args [i] != sig.args [i])
260 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
262 if (pars.Length != count)
265 for (int i = 0; i < count; i++)
266 if (pars [i].ParameterType != sig.args [i])
272 // A delegate that points to the filter above.
273 static MemberFilter signature_filter;
276 // These are expressions that represent some of the internal data types, used
279 static void InitExpressionTypes ()
281 system_object_expr = new TypeLookupExpression ("System.Object");
282 system_string_expr = new TypeLookupExpression ("System.String");
283 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
284 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
285 system_single_expr = new TypeLookupExpression ("System.Single");
286 system_double_expr = new TypeLookupExpression ("System.Double");
287 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
288 system_byte_expr = new TypeLookupExpression ("System.Byte");
289 system_int16_expr = new TypeLookupExpression ("System.Int16");
290 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
291 system_int32_expr = new TypeLookupExpression ("System.Int32");
292 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
293 system_int64_expr = new TypeLookupExpression ("System.Int64");
294 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
295 system_char_expr = new TypeLookupExpression ("System.Char");
296 system_void_expr = new TypeLookupExpression ("System.Void");
297 system_date_expr = new TypeLookupExpression ("System.DateTime");
298 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
299 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
302 static TypeManager ()
304 assemblies = new Assembly [0];
306 user_types = new ArrayList ();
308 types = new CaseInsensitiveHashtable ();
309 typecontainers = new CaseInsensitiveHashtable ();
311 builder_to_declspace = new PtrHashtable ();
312 builder_to_attr = new PtrHashtable ();
313 builder_to_method = new PtrHashtable ();
314 method_arguments = new PtrHashtable ();
315 method_internal_params = new PtrHashtable ();
316 indexer_arguments = new PtrHashtable ();
317 builder_to_ifaces = new PtrHashtable ();
319 NoTypes = new Type [0];
321 signature_filter = new MemberFilter (SignatureFilter);
322 InitExpressionTypes ();
325 public static void AddUserType (string name, TypeBuilder t, Type [] ifaces)
330 Type prev = (Type) types [name];
331 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
335 // This probably never happens, as we catch this before
337 Report.Error (-17, "The type '" + name + "' has already been defined.");
341 tc = builder_to_declspace [t] as TypeContainer;
344 1595, "The type '" + name + "' is defined in an existing assembly;"+
345 " Using the new definition from: " + tc.Location);
346 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
354 builder_to_ifaces [t] = ifaces;
358 // This entry point is used by types that we define under the covers
360 public static void RegisterBuilder (TypeBuilder tb, Type [] ifaces)
363 builder_to_ifaces [tb] = ifaces;
366 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc, Type [] ifaces)
368 builder_to_declspace.Add (t, tc);
369 typecontainers.Add (name, tc);
370 AddUserType (name, t, ifaces);
373 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
376 builder_to_declspace.Add (t, del);
379 public static void AddEnumType (string name, TypeBuilder t, Enum en)
382 builder_to_declspace.Add (t, en);
385 public static void AddUserInterface (string name, TypeBuilder t, Interface i, Type [] ifaces)
387 AddUserType (name, t, ifaces);
388 builder_to_declspace.Add (t, i);
391 public static void AddMethod (MethodBuilder builder, MethodData method)
393 builder_to_method.Add (builder, method);
396 public static void RegisterAttrType (Type t, TypeContainer tc)
398 builder_to_attr.Add (t, tc);
402 /// Returns the TypeContainer whose Type is 't' or null if there is no
403 /// TypeContainer for 't' (ie, the Type comes from a library)
405 public static TypeContainer LookupTypeContainer (Type t)
407 return builder_to_declspace [t] as TypeContainer;
410 public static IMemberContainer LookupMemberContainer (Type t)
412 if (t is TypeBuilder) {
413 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
414 if (container != null)
418 return TypeHandle.GetTypeHandle (t);
421 public static Interface LookupInterface (Type t)
423 return builder_to_declspace [t] as Interface;
426 public static Delegate LookupDelegate (Type t)
428 return builder_to_declspace [t] as Delegate;
431 public static Enum LookupEnum (Type t)
433 return builder_to_declspace [t] as Enum;
436 public static TypeContainer LookupAttr (Type t)
438 return (TypeContainer) builder_to_attr [t];
442 /// Registers an assembly to load types from.
444 public static void AddAssembly (Assembly a)
446 int top = assemblies.Length;
447 Assembly [] n = new Assembly [top + 1];
449 assemblies.CopyTo (n, 0);
454 foreach(Type type in a.GetTypes()) {
455 if (type.IsPublic ) // && type. attributed as standard module
456 AddStandardModule(type);
461 /// Registers a module builder to lookup types from
463 public static void AddModule (System.Reflection.Module mb)
465 int top = modules != null ? modules.Length : 0;
466 System.Reflection.Module [] n = new System.Reflection.Module [top + 1];
469 modules.CopyTo (n, 0);
474 private class StandardModule {
475 public readonly string Namespace;
476 public readonly string Name;
477 public StandardModule(string _namespace, string name) { Namespace = _namespace; Name = name; }
478 public override string ToString() { return ((Namespace != null && Namespace.Length > 0)?(Namespace + "."):"") + Name; }
481 private static StandardModule[] standardModules;
484 /// Registers a new 'standard module' to lookup short-qualified or unqualified members
486 internal static void AddStandardModule(Module module)
488 int top = standardModules != null ? standardModules.Length : 0;
489 StandardModule [] n = new StandardModule [top + 1];
491 if (standardModules != null)
492 standardModules.CopyTo (n, 0);
493 string name = module.Name;
494 int split = name.LastIndexOf('.');
496 name = name.Substring(split+1);
497 n [top] = new StandardModule(module.Namespace.Name, name);
498 // Console.WriteLine("Standard Module added: " + n [top]);
503 /// Registers a existing 'standard module' to lookup short-qualified or unqualified members
505 private static void AddStandardModule(Type type)
507 object[] attributes = type.GetCustomAttributes(false);
508 for (int i = 0; i < attributes.Length; i ++) {
509 if (attributes[i].ToString() == "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute") {
510 int top = standardModules != null ? standardModules.Length : 0;
511 StandardModule [] n = new StandardModule [top + 1];
513 if (standardModules != null)
514 standardModules.CopyTo (n, 0);
515 n [top] = new StandardModule(type.Namespace, type.Name) ;
525 public static Type[] GetPertinentStandardModules(params string[] namespaces)
527 ArrayList list = new ArrayList();
528 foreach(string Namespace in namespaces)
530 for(int i = 0; i < standardModules.Length; i++) {
531 if (standardModules[i].Namespace == Namespace) {
532 string name = standardModules[i].ToString();
533 Type t = LookupType(name);
535 System.Console.WriteLine("Could not find standard module '" + name + "'");
543 return (Type[])list.ToArray(typeof(Type));
547 // Low-level lookup, cache-less
549 static Type LookupTypeReflection (string name)
554 foreach (Assembly a in assemblies){
555 t = a.GetType (name, false, true);
560 foreach (System.Reflection.Module mb in modules) {
561 t = mb.GetType (name, false, true);
566 } catch (Exception e) {
567 System.Console.WriteLine("\nERROR: " + e.ToString() + "WHILE EXECUTING LookupTypeReflection(\"" + name + "\")\n");
573 // This function is used when you want to avoid the lookups, and want to go
574 // directly to the source. This will use the cache.
576 // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
577 // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
578 // way to test things other than doing a fullname compare
580 public static Type LookupTypeDirect (string name)
582 Type t = (Type) types [name];
586 t = LookupTypeReflection (name);
595 /// Returns the Type associated with @name, takes care of the fact that
596 /// reflection expects nested types to be separated from the main type
597 /// with a "+" instead of a "."
599 public static Type LookupType (string name)
604 // First lookup in user defined and cached values
607 t = (Type) types [name];
612 // Optimization: ComposedCast will work with an existing type, and might already have the
613 // full name of the type, so the full system lookup can probably be avoided.
616 string [] elements = name.Split ('.');
617 int count = elements.Length;
619 for (int n = 1; n <= count; n++){
620 string top_level_type = String.Join (".", elements, 0, n);
622 t = (Type) types [top_level_type];
624 t = LookupTypeReflection (top_level_type);
634 string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
635 t = LookupTypeDirect (newt);
644 // Returns a list of all namespaces in the assemblies and types loaded.
646 public static CaseInsensitiveHashtable GetNamespaces ()
648 CaseInsensitiveHashtable namespaces = new CaseInsensitiveHashtable ();
650 foreach (Assembly a in assemblies) {
651 foreach (Type t in a.GetTypes ()) {
652 string ns = t.Namespace;
654 if (namespaces.Contains (ns))
656 namespaces [ns] = ns;
660 foreach (System.Reflection.Module mb in modules) {
661 foreach (Type t in mb.GetTypes ()) {
662 string ns = t.Namespace;
664 if (namespaces.Contains (ns))
666 namespaces [ns] = ns;
674 /// Returns the C# name of a type if possible, or the full type name otherwise
676 static public string MonoBASIC_Name (Type t)
678 return Regex.Replace (t.FullName,
680 @"(Int32|Int16|Int64|Single|Double|Char|Decimal|Byte|Object|Boolean|String|DateTime)" +
682 new MatchEvaluator (MonoBASIC_NameMatch));
685 static String MonoBASIC_NameMatch (Match match)
687 string s = match.Groups [1].Captures [0].Value;
689 Replace ("int32", "integer").
690 Replace ("int16", "short").
691 Replace ("int64", "long").
692 Replace ("datetime", "date")
693 + match.Groups [2].Captures [0].Value;
697 /// Returns the signature of the method
699 static public string MonoBASIC_Signature (MethodBase mb)
704 // FIXME: We should really have a single function to do
705 // everything instead of the following 5 line pattern
707 ParameterData iparams = LookupParametersByBuilder (mb);
709 if (iparams == null){
710 ParameterInfo [] pi = mb.GetParameters ();
711 iparams = new ReflectionParameters (pi);
714 for (int i = 0; i < iparams.Count; i++) {
718 sig += iparams.ParameterDesc(i);
722 return mb.DeclaringType.Name + "." + mb.Name + sig;
726 /// Looks up a type, and aborts if it is not found. This is used
727 /// by types required by the compiler
729 static Type CoreLookupType (string name)
731 Type t = LookupType (name);
734 Report.Error (518, "The predefined type '" + name + "' is not defined or imported");
735 Environment.Exit (0);
742 /// Returns the MethodInfo for a method named 'name' defined
743 /// in type 't' which takes arguments of types 'args'
745 static MethodInfo GetMethod (Type t, string name, Type [] args)
753 list = FindMembers (t, MemberTypes.Method, instance_and_static | BindingFlags.Public| BindingFlags.IgnoreCase,
754 signature_filter, sig);
755 if (list.Count == 0) {
756 Report.Error (-19, "Can not find the core function '" + name + "'");
760 MethodInfo mi = list [0] as MethodInfo;
762 Report.Error (-19, "Can not find the core function '" + name + "'");
770 /// Returns the ConstructorInfo for "args"
772 public static ConstructorInfo GetConstructor (Type t, Type [] args)
780 list = FindMembers (t, MemberTypes.Constructor,
781 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
782 signature_filter, sig);
783 if (list.Count == 0){
784 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
788 ConstructorInfo ci = list [0] as ConstructorInfo;
790 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
797 public static void InitEnumUnderlyingTypes ()
800 int32_type = CoreLookupType ("System.Int32");
801 int64_type = CoreLookupType ("System.Int64");
802 uint32_type = CoreLookupType ("System.UInt32");
803 uint64_type = CoreLookupType ("System.UInt64");
804 byte_type = CoreLookupType ("System.Byte");
805 sbyte_type = CoreLookupType ("System.SByte");
806 short_type = CoreLookupType ("System.Int16");
807 ushort_type = CoreLookupType ("System.UInt16");
811 /// The types have to be initialized after the initial
812 /// population of the type has happened (for example, to
813 /// bootstrap the corlib.dll
815 public static void InitCoreTypes ()
817 object_type = CoreLookupType ("System.Object");
818 value_type = CoreLookupType ("System.ValueType");
820 InitEnumUnderlyingTypes ();
822 char_type = CoreLookupType ("System.Char");
823 string_type = CoreLookupType ("System.String");
824 float_type = CoreLookupType ("System.Single");
825 double_type = CoreLookupType ("System.Double");
826 char_ptr_type = CoreLookupType ("System.Char*");
827 decimal_type = CoreLookupType ("System.Decimal");
828 bool_type = CoreLookupType ("System.Boolean");
829 enum_type = CoreLookupType ("System.Enum");
831 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
832 delegate_type = CoreLookupType ("System.Delegate");
834 array_type = CoreLookupType ("System.Array");
835 void_type = CoreLookupType ("System.Void");
836 date_type = CoreLookupType ("System.DateTime");
837 type_type = CoreLookupType ("System.Type");
839 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
840 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
841 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
842 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
843 asynccallback_type = CoreLookupType ("System.AsyncCallback");
844 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
845 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
846 idisposable_type = CoreLookupType ("System.IDisposable");
847 icloneable_type = CoreLookupType ("System.ICloneable");
848 monitor_type = CoreLookupType ("System.Threading.Monitor");
849 intptr_type = CoreLookupType ("System.IntPtr");
851 attribute_type = CoreLookupType ("System.Attribute");
852 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
853 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
854 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
855 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
856 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
858 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
860 void_ptr_type = CoreLookupType ("System.Void*");
862 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
864 exception_type = CoreLookupType ("System.Exception");
869 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
870 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
873 // When compiling corlib, store the "real" types here.
875 if (!RootContext.StdLib) {
876 system_int32_type = typeof (System.Int32);
877 system_array_type = typeof (System.Array);
878 system_type_type = typeof (System.Type);
879 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
881 Type [] void_arg = { };
882 system_int_array_get_length = GetMethod (
883 system_array_type, "get_Length", void_arg);
884 system_int_array_get_rank = GetMethod (
885 system_array_type, "get_Rank", void_arg);
886 system_object_array_clone = GetMethod (
887 system_array_type, "Clone", void_arg);
889 Type [] system_int_arg = { system_int32_type };
890 system_int_array_get_length_int = GetMethod (
891 system_array_type, "GetLength", system_int_arg);
892 system_int_array_get_upper_bound_int = GetMethod (
893 system_array_type, "GetUpperBound", system_int_arg);
894 system_int_array_get_lower_bound_int = GetMethod (
895 system_array_type, "GetLowerBound", system_int_arg);
897 Type [] system_array_int_arg = { system_array_type, system_int32_type };
898 system_void_array_copyto_array_int = GetMethod (
899 system_array_type, "CopyTo", system_array_int_arg);
901 Type [] system_type_type_arg = { system_type_type, system_type_type, system_type_type };
904 system_void_set_corlib_type_builders = GetMethod (
905 system_assemblybuilder_type, "SetCorlibTypeBuilders",
906 system_type_type_arg);
908 object[] args = new object [3];
909 args [0] = object_type;
910 args [1] = value_type;
911 args [2] = enum_type;
913 system_void_set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
915 Console.WriteLine ("Corlib compilation is not supported in Microsoft.NET due to bugs in it");
921 // The helper methods that are used by the compiler
923 public static void InitCodeHelpers ()
926 // Now load the default methods that we use.
928 Type [] string_string = { string_type, string_type };
929 string_concat_string_string = GetMethod (
930 string_type, "Concat", string_string);
932 Type [] object_object = { object_type, object_type };
933 string_concat_object_object = GetMethod (
934 string_type, "Concat", object_object);
936 Type [] string_ = { string_type };
937 string_isinterneted_string = GetMethod (
938 string_type, "IsInterned", string_);
940 Type [] runtime_type_handle = { runtime_handle_type };
941 system_type_get_type_from_handle = GetMethod (
942 type_type, "GetTypeFromHandle", runtime_type_handle);
944 Type [] delegate_delegate = { delegate_type, delegate_type };
945 delegate_combine_delegate_delegate = GetMethod (
946 delegate_type, "Combine", delegate_delegate);
948 delegate_remove_delegate_delegate = GetMethod (
949 delegate_type, "Remove", delegate_delegate);
954 Type [] void_arg = { };
955 object_getcurrent_void = GetMethod (
956 ienumerator_type, "get_Current", void_arg);
957 bool_movenext_void = GetMethod (
958 ienumerator_type, "MoveNext", void_arg);
959 void_dispose_void = GetMethod (
960 idisposable_type, "Dispose", void_arg);
961 int_get_offset_to_string_data = GetMethod (
962 runtime_helpers_type, "get_OffsetToStringData", void_arg);
963 int_array_get_length = GetMethod (
964 array_type, "get_Length", void_arg);
965 int_array_get_rank = GetMethod (
966 array_type, "get_Rank", void_arg);
971 Type [] int_arg = { int32_type };
972 int_array_get_length_int = GetMethod (
973 array_type, "GetLength", int_arg);
974 int_array_get_upper_bound_int = GetMethod (
975 array_type, "GetUpperBound", int_arg);
976 int_array_get_lower_bound_int = GetMethod (
977 array_type, "GetLowerBound", int_arg);
980 // System.Array methods
982 object_array_clone = GetMethod (
983 array_type, "Clone", void_arg);
984 Type [] array_int_arg = { array_type, int32_type };
985 void_array_copyto_array_int = GetMethod (
986 array_type, "CopyTo", array_int_arg);
991 Type [] object_arg = { object_type };
992 void_monitor_enter_object = GetMethod (
993 monitor_type, "Enter", object_arg);
994 void_monitor_exit_object = GetMethod (
995 monitor_type, "Exit", object_arg);
997 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
999 void_initializearray_array_fieldhandle = GetMethod (
1000 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1005 int_getlength_int = GetMethod (
1006 array_type, "GetLength", int_arg);
1009 // Decimal constructors
1011 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1012 void_decimal_ctor_five_args = GetConstructor (
1013 decimal_type, dec_arg);
1015 // DateTime constructor
1016 Type [] ticks_arg = { int64_type };
1017 void_datetime_ctor_ticks_arg = GetConstructor ( date_type, ticks_arg);
1022 cons_param_array_attribute = GetConstructor (
1023 param_array_type, void_arg);
1025 unverifiable_code_ctor = GetConstructor (
1026 unverifiable_code_type, void_arg);
1030 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1032 static CaseInsensitiveHashtable type_hash = new CaseInsensitiveHashtable ();
1035 /// This is the "old", non-cache based FindMembers() function. We cannot use
1036 /// the cache here because there is no member name argument.
1038 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1039 MemberFilter filter, object criteria)
1041 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1042 bf |= BindingFlags.IgnoreCase;
1044 // 'builder_to_declspace' contains all dynamic types.
1048 Timer.StartTimer (TimerType.FindMembers);
1049 list = decl.FindMembers (mt, bf, filter, criteria);
1050 Timer.StopTimer (TimerType.FindMembers);
1055 // We have to take care of arrays specially, because GetType on
1056 // a TypeBuilder array will return a Type, not a TypeBuilder,
1057 // and we can not call FindMembers on this type.
1059 if (t.IsSubclassOf (TypeManager.array_type))
1060 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1063 // Since FindMembers will not lookup both static and instance
1064 // members, we emulate this behaviour here.
1066 if ((bf & instance_and_static) == instance_and_static){
1067 MemberInfo [] i_members = t.FindMembers (
1068 mt, (bf & ~BindingFlags.Static) | BindingFlags.IgnoreCase, filter, criteria);
1070 int i_len = i_members.Length;
1072 MemberInfo one = i_members [0];
1075 // If any of these are present, we are done!
1077 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1078 return new MemberList (i_members);
1081 MemberInfo [] s_members = t.FindMembers (
1082 mt, (bf & ~BindingFlags.Instance) | BindingFlags.IgnoreCase, filter, criteria);
1084 int s_len = s_members.Length;
1085 if (i_len > 0 || s_len > 0)
1086 return new MemberList (i_members, s_members);
1089 return new MemberList (i_members);
1091 return new MemberList (s_members);
1095 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1100 /// This method is only called from within MemberLookup. It tries to use the member
1101 /// cache if possible and falls back to the normal FindMembers if not. The 'used_cache'
1102 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1103 /// our return value will already contain all inherited members and the caller don't need
1104 /// to check base classes and interfaces anymore.
1106 private static MemberList MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1107 string name, out bool used_cache)
1110 // We have to take care of arrays specially, because GetType on
1111 // a TypeBuilder array will return a Type, not a TypeBuilder,
1112 // and we can not call FindMembers on this type.
1114 if (t.IsSubclassOf (TypeManager.array_type)) {
1116 return TypeHandle.ArrayType.MemberCache.FindMembers (
1117 mt, bf, name, FilterWithClosure_delegate, null);
1121 // If this is a dynamic type, it's always in the 'builder_to_declspace' hash table
1122 // and we can ask the DeclSpace for the MemberCache.
1124 if (t is TypeBuilder) {
1125 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1126 MemberCache cache = decl.MemberCache;
1129 // If this DeclSpace has a MemberCache, use it.
1132 if (cache != null) {
1134 return cache.FindMembers (
1135 mt, bf, name, FilterWithClosure_delegate, null);
1138 // If there is no MemberCache, we need to use the "normal" FindMembers.
1141 Timer.StartTimer (TimerType.FindMembers);
1142 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
1143 FilterWithClosure_delegate, name);
1144 Timer.StopTimer (TimerType.FindMembers);
1150 // This call will always succeed. There is exactly one TypeHandle instance per
1151 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1152 // if it didn't already exist.
1154 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1157 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1160 public static bool IsBuiltinType (Type t)
1162 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1163 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1164 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1165 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type ||
1172 public static bool IsDelegateType (Type t)
1174 if (t.IsSubclassOf (TypeManager.delegate_type))
1180 public static bool IsEnumType (Type t)
1182 if (t.IsSubclassOf (TypeManager.enum_type))
1189 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1191 public static bool IsUnmanagedType (Type t)
1193 if (IsBuiltinType (t) && t != TypeManager.string_type)
1202 if (IsValueType (t)){
1203 if (t is TypeBuilder){
1204 TypeContainer tc = LookupTypeContainer (t);
1206 foreach (Field f in tc.Fields){
1207 if (f.FieldBuilder.IsStatic)
1209 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1213 FieldInfo [] fields = t.GetFields ();
1215 foreach (FieldInfo f in fields){
1218 if (!IsUnmanagedType (f.FieldType))
1228 public static bool IsValueType (Type t)
1230 if (t.IsSubclassOf (TypeManager.value_type))
1236 public static bool IsInterfaceType (Type t)
1238 Interface iface = builder_to_declspace [t] as Interface;
1247 // Checks whether 'type' is a subclass or nested child of 'parent'.
1249 public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1252 if ((type == parent) || type.IsSubclassOf (parent))
1255 // Handle nested types.
1256 type = type.DeclaringType;
1257 } while (type != null);
1263 // Checks whether 'type' is a nested child of 'parent'.
1265 public static bool IsNestedChildOf (Type type, Type parent)
1267 if ((type == parent) || type.IsSubclassOf (parent))
1270 return IsSubclassOrNestedChildOf (type, parent);
1274 /// Returns the User Defined Types
1276 public static ArrayList UserTypes {
1282 public static CaseInsensitiveHashtable TypeContainers {
1284 return typecontainers;
1288 static Hashtable builder_to_constant;
1290 public static void RegisterConstant (FieldBuilder fb, Const c)
1292 if (builder_to_constant == null)
1293 builder_to_constant = new PtrHashtable ();
1295 if (builder_to_constant.Contains (fb))
1298 builder_to_constant.Add (fb, c);
1301 public static Const LookupConstant (FieldBuilder fb)
1303 if (builder_to_constant == null)
1306 return (Const) builder_to_constant [fb];
1310 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1314 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1315 /// for anything which is dynamic, and we need this in a number of places,
1316 /// we register this information here, and use it afterwards.
1318 static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1323 method_arguments.Add (mb, args);
1324 method_internal_params.Add (mb, ip);
1329 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1331 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1334 if (method_internal_params.Contains (mb))
1335 return (InternalParameters) method_internal_params [mb];
1337 throw new Exception ("Argument for Method not registered" + mb);
1341 /// Returns the argument types for a method based on its methodbase
1343 /// For dynamic methods, we use the compiler provided types, for
1344 /// methods from existing assemblies we load them from GetParameters,
1345 /// and insert them into the cache
1347 static public Type [] GetArgumentTypes (MethodBase mb)
1349 if (method_arguments.Contains (mb))
1350 return (Type []) method_arguments [mb];
1352 ParameterInfo [] pi = mb.GetParameters ();
1354 Type [] types = new Type [c];
1356 for (int i = 0; i < c; i++)
1357 types [i] = pi [i].ParameterType;
1359 method_arguments.Add (mb, types);
1365 /// Returns the argument types for an indexer based on its PropertyInfo
1367 /// For dynamic indexers, we use the compiler provided types, for
1368 /// indexers from existing assemblies we load them from GetParameters,
1369 /// and insert them into the cache
1371 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1373 if (indexer_arguments.Contains (indexer))
1374 return (Type []) indexer_arguments [indexer];
1375 else if (indexer is PropertyBuilder)
1376 // If we're a PropertyBuilder and not in the
1377 // 'indexer_arguments' hash, then we're a property and
1381 ParameterInfo [] pi = indexer.GetIndexParameters ();
1382 // Property, not an indexer.
1386 Type [] types = new Type [c];
1388 for (int i = 0; i < c; i++)
1389 types [i] = pi [i].ParameterType;
1391 indexer_arguments.Add (indexer, types);
1397 // This is a workaround the fact that GetValue is not
1398 // supported for dynamic types
1400 static CaseInsensitiveHashtable fields = new CaseInsensitiveHashtable ();
1401 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1403 if (fields.Contains (fb))
1406 fields.Add (fb, value);
1411 static public object GetValue (FieldBuilder fb)
1416 static CaseInsensitiveHashtable fieldbuilders_to_fields = new CaseInsensitiveHashtable ();
1417 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1419 if (fieldbuilders_to_fields.Contains (fb))
1422 fieldbuilders_to_fields.Add (fb, f);
1426 static public FieldBase GetField (FieldInfo fb)
1428 return (FieldBase) fieldbuilders_to_fields [fb];
1431 static CaseInsensitiveHashtable events;
1433 static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1436 events = new CaseInsensitiveHashtable ();
1438 if (events.Contains (eb))
1441 events.Add (eb, new Pair (add, remove));
1446 static public MethodInfo GetAddMethod (EventInfo ei)
1448 if (ei is MyEventBuilder) {
1449 Pair pair = (Pair) events [ei];
1451 return (MethodInfo) pair.First;
1453 return ei.GetAddMethod ();
1456 static public MethodInfo GetRemoveMethod (EventInfo ei)
1458 if (ei is MyEventBuilder) {
1459 Pair pair = (Pair) events [ei];
1461 return (MethodInfo) pair.Second;
1463 return ei.GetAddMethod ();
1466 static CaseInsensitiveHashtable priv_fields_events;
1468 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1470 if (priv_fields_events == null)
1471 priv_fields_events = new CaseInsensitiveHashtable ();
1473 if (priv_fields_events.Contains (einfo))
1476 priv_fields_events.Add (einfo, builder);
1481 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1483 return (MemberInfo) priv_fields_events [ei];
1486 static CaseInsensitiveHashtable properties;
1488 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1490 if (properties == null)
1491 properties = new CaseInsensitiveHashtable ();
1493 if (properties.Contains (pb))
1496 properties.Add (pb, new Pair (get, set));
1501 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get, MethodBase set, Type[] args)
1503 if (!RegisterProperty (pb, get,set))
1506 indexer_arguments.Add (pb, args);
1511 static public MethodInfo GetPropertyGetter (PropertyInfo pi)
1513 if (pi is PropertyBuilder){
1514 Pair de = (Pair) properties [pi];
1516 return (MethodInfo) de.Second;
1518 return pi.GetSetMethod (true);
1521 static public MethodInfo GetPropertySetter (PropertyInfo pi)
1523 if (pi is PropertyBuilder){
1524 Pair de = (Pair) properties [pi];
1526 return (MethodInfo) de.First;
1528 return pi.GetGetMethod (true);
1532 /// Given an array of interface types, expand and eliminate repeated ocurrences
1533 /// of an interface.
1537 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1540 public static Type [] ExpandInterfaces (Type [] base_interfaces)
1542 ArrayList new_ifaces = new ArrayList ();
1544 foreach (Type iface in base_interfaces){
1545 if (!new_ifaces.Contains (iface))
1546 new_ifaces.Add (iface);
1548 Type [] implementing = TypeManager.GetInterfaces (iface);
1550 foreach (Type imp in implementing){
1551 if (!new_ifaces.Contains (imp))
1552 new_ifaces.Add (imp);
1555 Type [] ret = new Type [new_ifaces.Count];
1556 new_ifaces.CopyTo (ret, 0);
1561 /// This function returns the interfaces in the type 't'. Works with
1562 /// both types and TypeBuilders.
1564 public static Type [] GetInterfaces (Type t)
1567 // The reason for catching the Array case is that Reflection.Emit
1568 // will not return a TypeBuilder for Array types of TypeBuilder types,
1569 // but will still throw an exception if we try to call GetInterfaces
1572 // Since the array interfaces are always constant, we return those for
1577 t = TypeManager.array_type;
1579 if (t is TypeBuilder){
1580 Type [] parent_ifaces;
1582 if (t.BaseType == null)
1583 parent_ifaces = NoTypes;
1585 parent_ifaces = GetInterfaces (t.BaseType);
1586 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1587 if (type_ifaces == null)
1588 type_ifaces = NoTypes;
1590 int parent_count = parent_ifaces.Length;
1591 Type [] result = new Type [parent_count + type_ifaces.Length];
1592 parent_ifaces.CopyTo (result, 0);
1593 type_ifaces.CopyTo (result, parent_count);
1597 return t.GetInterfaces ();
1601 /// The following is used to check if a given type implements an interface.
1602 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1604 public static bool ImplementsInterface (Type t, Type iface)
1609 // FIXME OPTIMIZATION:
1610 // as soon as we hit a non-TypeBuiler in the interface
1611 // chain, we could return, as the 'Type.GetInterfaces'
1612 // will return all the interfaces implement by the type
1616 interfaces = GetInterfaces (t);
1618 if (interfaces != null){
1619 foreach (Type i in interfaces){
1626 } while (t != null);
1631 // This is a custom version of Convert.ChangeType() which works
1632 // with the TypeBuilder defined types when compiling corlib.
1633 public static object ChangeType (object value, Type conversionType)
1635 if (!(value is IConvertible))
1636 throw new ArgumentException ();
1638 IConvertible convertValue = (IConvertible) value;
1639 CultureInfo ci = CultureInfo.CurrentCulture;
1640 NumberFormatInfo provider = ci.NumberFormat;
1643 // We must use Type.Equals() here since 'conversionType' is
1644 // the TypeBuilder created version of a system type and not
1645 // the system type itself. You cannot use Type.GetTypeCode()
1646 // on such a type - it'd always return TypeCode.Object.
1648 if (conversionType.Equals (typeof (Boolean)))
1649 return (object)(convertValue.ToBoolean (provider));
1650 else if (conversionType.Equals (typeof (Byte)))
1651 return (object)(convertValue.ToByte (provider));
1652 else if (conversionType.Equals (typeof (Char)))
1653 return (object)(convertValue.ToChar (provider));
1654 else if (conversionType.Equals (typeof (DateTime)))
1655 return (object)(convertValue.ToDateTime (provider));
1656 else if (conversionType.Equals (typeof (Decimal)))
1657 return (object)(convertValue.ToDecimal (provider));
1658 else if (conversionType.Equals (typeof (Double)))
1659 return (object)(convertValue.ToDouble (provider));
1660 else if (conversionType.Equals (typeof (Int16)))
1661 return (object)(convertValue.ToInt16 (provider));
1662 else if (conversionType.Equals (typeof (Int32)))
1663 return (object)(convertValue.ToInt32 (provider));
1664 else if (conversionType.Equals (typeof (Int64)))
1665 return (object)(convertValue.ToInt64 (provider));
1666 else if (conversionType.Equals (typeof (SByte)))
1667 return (object)(convertValue.ToSByte (provider));
1668 else if (conversionType.Equals (typeof (Single)))
1669 return (object)(convertValue.ToSingle (provider));
1670 else if (conversionType.Equals (typeof (String)))
1671 return (object)(convertValue.ToString (provider));
1672 else if (conversionType.Equals (typeof (UInt16)))
1673 return (object)(convertValue.ToUInt16 (provider));
1674 else if (conversionType.Equals (typeof (UInt32)))
1675 return (object)(convertValue.ToUInt32 (provider));
1676 else if (conversionType.Equals (typeof (UInt64)))
1677 return (object)(convertValue.ToUInt64 (provider));
1678 else if (conversionType.Equals (typeof (Object)))
1679 return (object)(value);
1681 throw new InvalidCastException ();
1685 // This is needed, because enumerations from assemblies
1686 // do not report their underlyingtype, but they report
1689 public static Type EnumToUnderlying (Type t)
1691 if (t == TypeManager.enum_type)
1694 t = t.UnderlyingSystemType;
1695 if (!TypeManager.IsEnumType (t))
1698 if (t is TypeBuilder) {
1699 // slow path needed to compile corlib
1700 if (t == TypeManager.bool_type ||
1701 t == TypeManager.byte_type ||
1702 t == TypeManager.sbyte_type ||
1703 t == TypeManager.char_type ||
1704 t == TypeManager.short_type ||
1705 t == TypeManager.ushort_type ||
1706 t == TypeManager.int32_type ||
1707 t == TypeManager.uint32_type ||
1708 t == TypeManager.int64_type ||
1709 t == TypeManager.uint64_type)
1711 throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
1713 TypeCode tc = Type.GetTypeCode (t);
1716 case TypeCode.Boolean:
1717 return TypeManager.bool_type;
1719 return TypeManager.byte_type;
1720 case TypeCode.SByte:
1721 return TypeManager.sbyte_type;
1723 return TypeManager.char_type;
1724 case TypeCode.Int16:
1725 return TypeManager.short_type;
1726 case TypeCode.UInt16:
1727 return TypeManager.ushort_type;
1728 case TypeCode.Int32:
1729 return TypeManager.int32_type;
1730 case TypeCode.UInt32:
1731 return TypeManager.uint32_type;
1732 case TypeCode.Int64:
1733 return TypeManager.int64_type;
1734 case TypeCode.UInt64:
1735 return TypeManager.uint64_type;
1737 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1741 // When compiling corlib and called with one of the core types, return
1742 // the corresponding typebuilder for that type.
1744 public static Type TypeToCoreType (Type t)
1746 if (RootContext.StdLib || (t is TypeBuilder))
1749 TypeCode tc = Type.GetTypeCode (t);
1752 case TypeCode.Boolean:
1753 return TypeManager.bool_type;
1755 return TypeManager.byte_type;
1756 case TypeCode.SByte:
1757 return TypeManager.sbyte_type;
1759 return TypeManager.char_type;
1760 case TypeCode.Int16:
1761 return TypeManager.short_type;
1762 case TypeCode.UInt16:
1763 return TypeManager.ushort_type;
1764 case TypeCode.Int32:
1765 return TypeManager.int32_type;
1766 case TypeCode.UInt32:
1767 return TypeManager.uint32_type;
1768 case TypeCode.Int64:
1769 return TypeManager.int64_type;
1770 case TypeCode.UInt64:
1771 return TypeManager.uint64_type;
1772 case TypeCode.String:
1773 return TypeManager.string_type;
1774 case TypeCode.DateTime:
1775 return TypeManager.date_type;
1777 if (t == typeof (void))
1778 return TypeManager.void_type;
1779 if (t == typeof (object))
1780 return TypeManager.object_type;
1781 if (t == typeof (System.Type))
1782 return TypeManager.type_type;
1788 /// Utility function that can be used to probe whether a type
1789 /// is managed or not.
1791 public static bool VerifyUnManaged (Type t, Location loc)
1793 if (t.IsValueType || t.IsPointer){
1795 // FIXME: this is more complex, we actually need to
1796 // make sure that the type does not contain any
1802 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
1803 // We need this explicit check here to make it work when
1804 // compiling corlib.
1809 "Cannot take the address or size of a variable of a managed type ('" +
1810 MonoBASIC_Name (t) + "')");
1815 /// Returns the name of the indexer in a given type.
1818 /// The default is not always 'Item'. The user can change this behaviour by
1819 /// using the DefaultMemberAttribute in the class.
1821 /// For example, the String class indexer is named 'Chars' not 'Item'
1823 public static string IndexerPropertyName (Type t)
1825 if (t is TypeBuilder) {
1826 if (t.IsInterface) {
1827 Interface i = LookupInterface (t);
1829 if ((i == null) || (i.IndexerName == null))
1832 return i.IndexerName;
1834 TypeContainer tc = LookupTypeContainer (t);
1836 if ((tc == null) || (tc.IndexerName == null))
1839 return tc.IndexerName;
1843 System.Attribute attr = System.Attribute.GetCustomAttribute (
1844 t, TypeManager.default_member_type);
1846 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
1847 return dma.MemberName;
1853 public static void MakePinned (LocalBuilder builder)
1856 // FIXME: Flag the "LocalBuilder" type as being
1857 // pinned. Figure out API.
1863 // Returns whether the array of memberinfos contains the given method
1865 static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
1867 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
1869 foreach (MethodBase method in array){
1870 if (method.Name != new_method.Name)
1873 Type [] old_args = TypeManager.GetArgumentTypes (method);
1874 int old_count = old_args.Length;
1877 if (new_args.Length != old_count)
1880 for (i = 0; i < old_count; i++){
1881 if (old_args [i] != new_args [i])
1893 // We copy methods from 'new_members' into 'target_list' if the signature
1894 // for the method from in the new list does not exist in the target_list
1896 // The name is assumed to be the same.
1898 public static ArrayList CopyNewMethods (ArrayList target_list, MemberList new_members)
1900 if (target_list == null){
1901 target_list = new ArrayList ();
1903 foreach (MemberInfo mi in new_members){
1904 if (mi is MethodBase)
1905 target_list.Add (mi);
1910 MemberInfo [] target_array = new MemberInfo [target_list.Count];
1911 target_list.CopyTo (target_array, 0);
1913 foreach (MemberInfo mi in new_members){
1914 MethodBase new_method = (MethodBase) mi;
1916 if (!ArrayContainsMethod (target_array, new_method))
1917 target_list.Add (new_method);
1923 public enum MethodFlags {
1925 IsObsoleteError = 2,
1930 // Returns the TypeManager.MethodFlags for this method.
1931 // This emits an error 619 / warning 618 if the method is obsolete.
1932 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
1934 static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
1936 MethodFlags flags = 0;
1938 if (mb.DeclaringType is TypeBuilder){
1939 MethodData method = (MethodData) builder_to_method [mb];
1940 if (method == null) {
1941 // FIXME: implement Obsolete attribute on Property,
1942 // Indexer and Event.
1946 return method.GetMethodFlags (loc);
1949 object [] attrs = mb.GetCustomAttributes (true);
1950 foreach (object ta in attrs){
1951 if (!(ta is System.Attribute)){
1952 Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
1955 System.Attribute a = (System.Attribute) ta;
1956 if (a.TypeId == TypeManager.obsolete_attribute_type){
1957 ObsoleteAttribute oa = (ObsoleteAttribute) a;
1959 string method_desc = TypeManager.MonoBASIC_Signature (mb);
1962 Report.Error (619, loc, "Method '" + method_desc +
1963 "' is obsolete: '" + oa.Message + "'");
1964 return MethodFlags.IsObsoleteError;
1966 Report.Warning (618, loc, "Method '" + method_desc +
1967 "' is obsolete: '" + oa.Message + "'");
1969 flags |= MethodFlags.IsObsolete;
1975 // Skip over conditional code.
1977 if (a.TypeId == TypeManager.conditional_attribute_type){
1978 ConditionalAttribute ca = (ConditionalAttribute) a;
1980 if (RootContext.AllDefines [ca.ConditionString] == null)
1981 flags |= MethodFlags.ShouldIgnore;
1988 #region MemberLookup implementation
1991 // Name of the member
1993 static string closure_name;
1996 // Whether we allow private members in the result (since FindMembers
1997 // uses NonPublic for both protected and private), we need to distinguish.
1999 static bool closure_private_ok;
2002 // Who is invoking us and which type is being queried currently.
2004 static Type closure_invocation_type;
2005 static Type closure_queried_type;
2006 static Type closure_start_type;
2009 // The assembly that defines the type is that is calling us
2011 static Assembly closure_invocation_assembly;
2014 // This filter filters by name + whether it is ok to include private
2015 // members in the search
2017 static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
2020 // Hack: we know that the filter criteria will always be in the 'closure'
2024 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2027 if ((closure_start_type == closure_invocation_type) &&
2028 (m.DeclaringType == closure_invocation_type))
2032 // Ugly: we need to find out the type of 'm', and depending
2033 // on this, tell whether we accept or not
2035 if (m is MethodBase){
2036 MethodBase mb = (MethodBase) m;
2037 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2039 if (ma == MethodAttributes.Private)
2040 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2043 // FamAndAssem requires that we not only derivate, but we are on the
2046 if (ma == MethodAttributes.FamANDAssem){
2047 if (closure_invocation_assembly != mb.DeclaringType.Assembly)
2051 // Assembly and FamORAssem succeed if we're in the same assembly.
2052 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2053 if (closure_invocation_assembly == mb.DeclaringType.Assembly)
2057 // We already know that we aren't in the same assembly.
2058 if (ma == MethodAttributes.Assembly)
2061 // Family and FamANDAssem require that we derive.
2062 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
2063 if (closure_invocation_type == null)
2066 if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
2076 if (m is FieldInfo){
2077 FieldInfo fi = (FieldInfo) m;
2078 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2080 if (fa == FieldAttributes.Private)
2081 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2084 // FamAndAssem requires that we not only derivate, but we are on the
2087 if (fa == FieldAttributes.FamANDAssem){
2088 if (closure_invocation_assembly != fi.DeclaringType.Assembly)
2092 // Assembly and FamORAssem succeed if we're in the same assembly.
2093 if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2094 if (closure_invocation_assembly == fi.DeclaringType.Assembly)
2098 // We already know that we aren't in the same assembly.
2099 if (fa == FieldAttributes.Assembly)
2102 // Family and FamANDAssem require that we derive.
2103 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
2104 if (closure_invocation_type == null)
2107 if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.DeclaringType))
2110 // Although a derived class can access protected members of its base class
2111 // it cannot do so through an instance of the base class (CS1540).
2112 if ((closure_invocation_type != closure_start_type) &&
2113 closure_invocation_type.IsSubclassOf (closure_start_type))
2124 // EventInfos and PropertyInfos, return true
2129 static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
2132 // Looks up a member called 'name' in the 'queried_type'. This lookup
2133 // is done by code that is contained in the definition for 'invocation_type'.
2135 // The binding flags are 'bf' and the kind of members being looked up are 'mt'
2137 // Returns an array of a single element for everything but Methods/Constructors
2138 // that might return multiple matches.
2140 public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type,
2141 MemberTypes mt, BindingFlags original_bf, string name)
2143 Timer.StartTimer (TimerType.MemberLookup);
2145 MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
2146 mt, original_bf, name);
2148 Timer.StopTimer (TimerType.MemberLookup);
2153 static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type,
2154 MemberTypes mt, BindingFlags original_bf, string name)
2156 BindingFlags bf = original_bf;
2158 ArrayList method_list = null;
2159 Type current_type = queried_type;
2160 if (queried_type == null)
2161 throw new ArgumentNullException("queried_type");
2162 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2164 bool always_ok_flag = false;
2165 bool skip_iface_check = true, used_cache = false;
2167 closure_name = name;
2168 closure_invocation_type = invocation_type;
2169 closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2170 closure_start_type = queried_type;
2173 // If we are a nested class, we always have access to our container
2176 if (invocation_type != null){
2177 string invocation_name = invocation_type.FullName;
2178 if (invocation_name.IndexOf ('+') != -1){
2179 string container = queried_type.FullName + "+";
2180 int container_length = container.Length;
2182 if (invocation_name.Length > container_length){
2183 string shared = invocation_name.Substring (0, container_length);
2185 if (shared == container)
2186 always_ok_flag = true;
2195 // 'NonPublic' is lame, because it includes both protected and
2196 // private methods, so we need to control this behavior by
2197 // explicitly tracking if a private method is ok or not.
2199 // The possible cases are:
2200 // public, private and protected (internal does not come into the
2203 if (invocation_type != null){
2204 if (invocation_type == current_type){
2205 private_ok = (bf & BindingFlags.NonPublic) != 0;
2207 private_ok = always_ok_flag;
2209 if (invocation_type.IsSubclassOf (current_type))
2213 bf = original_bf | BindingFlags.NonPublic;
2216 bf = original_bf & ~BindingFlags.NonPublic;
2219 closure_private_ok = private_ok;
2220 closure_queried_type = current_type;
2222 Timer.StopTimer (TimerType.MemberLookup);
2223 bf |= BindingFlags.IgnoreCase;
2224 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2226 Timer.StartTimer (TimerType.MemberLookup);
2229 // When queried for an interface type, the cache will automatically check all
2230 // inherited members, so we don't need to do this here. However, this only
2231 // works if we already used the cache in the first iteration of this loop.
2233 // If we used the cache in any further iteration, we can still terminate the
2234 // loop since the cache always looks in all parent classes.
2240 skip_iface_check = false;
2242 if (current_type == TypeManager.object_type)
2245 current_type = current_type.BaseType;
2248 // This happens with interfaces, they have a null
2249 // basetype. Look members up in the Object class.
2251 if (current_type == null)
2252 current_type = TypeManager.object_type;
2255 if (list.Count == 0)
2259 // Events and types are returned by both 'static' and 'instance'
2260 // searches, which means that our above FindMembers will
2261 // return two copies of the same.
2263 if (list.Count == 1 && !(list [0] is MethodBase)){
2264 return (MemberInfo []) list;
2268 // Multiple properties: we query those just to find out the indexer
2271 if (list [0] is PropertyInfo)
2272 return (MemberInfo []) list;
2275 // We found methods, turn the search into "method scan"
2279 method_list = CopyNewMethods (method_list, list);
2280 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2281 } while (searching);
2283 if (method_list != null && method_list.Count > 0)
2284 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2287 // This happens if we already used the cache in the first iteration, in this case
2288 // the cache already looked in all interfaces.
2290 if (skip_iface_check)
2294 // Interfaces do not list members they inherit, so we have to
2297 if (!queried_type.IsInterface)
2300 if (queried_type.IsArray)
2301 queried_type = TypeManager.array_type;
2303 Type [] ifaces = GetInterfaces (queried_type);
2307 foreach (Type itype in ifaces){
2310 x = MemberLookup (null, itype, mt, bf, name);
2322 /// There is exactly one instance of this class per type.
2324 public sealed class TypeHandle : IMemberContainer {
2325 public readonly TypeHandle BaseType;
2327 readonly int id = ++next_id;
2328 static int next_id = 0;
2331 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2332 /// a TypeHandle yet, a new instance of it is created. This static method
2333 /// ensures that we'll only have one TypeHandle instance per type.
2335 public static TypeHandle GetTypeHandle (Type t)
2337 TypeHandle handle = (TypeHandle) type_hash [t];
2341 handle = new TypeHandle (t);
2342 type_hash.Add (t, handle);
2347 /// Returns the TypeHandle for TypeManager.object_type.
2349 public static IMemberContainer ObjectType {
2351 if (object_type != null)
2354 object_type = GetTypeHandle (TypeManager.object_type);
2361 /// Returns the TypeHandle for TypeManager.array_type.
2363 public static IMemberContainer ArrayType {
2365 if (array_type != null)
2368 array_type = GetTypeHandle (TypeManager.array_type);
2374 private static PtrHashtable type_hash = new PtrHashtable ();
2376 private static TypeHandle object_type = null;
2377 private static TypeHandle array_type = null;
2380 private bool is_interface;
2381 private MemberCache member_cache;
2383 private TypeHandle (Type type)
2386 if (type.BaseType != null)
2387 BaseType = GetTypeHandle (type.BaseType);
2388 else if ((type != TypeManager.object_type) && (type != typeof (object)))
2389 is_interface = true;
2390 this.member_cache = new MemberCache (this);
2393 // IMemberContainer methods
2395 public string Name {
2397 return type.FullName;
2407 public IMemberContainer Parent {
2413 public bool IsInterface {
2415 return is_interface;
2419 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2421 if (mt == MemberTypes.Event)
2422 return new MemberList (type.GetEvents (bf | BindingFlags.DeclaredOnly));
2424 return new MemberList (type.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
2428 // IMemberFinder methods
2430 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2431 MemberFilter filter, object criteria)
2433 return member_cache.FindMembers (mt, bf, name, filter, criteria);
2436 public MemberCache MemberCache {
2438 return member_cache;
2442 public override string ToString ()
2444 if (BaseType != null)
2445 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2447 return "TypeHandle (" + id + "," + Name + ")";