2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
6 // Manjula GHM (mmanjula@novell.com)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Globalization;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Text.RegularExpressions;
19 using System.Runtime.CompilerServices;
20 using System.Diagnostics;
22 namespace Mono.MonoBASIC {
24 public class TypeManager {
26 // A list of core types that the compiler requires or uses
28 static public Type object_type;
29 static public Type value_type;
30 static public Type string_type;
31 static public Type int32_type;
32 static public Type uint32_type;
33 static public Type int64_type;
34 static public Type uint64_type;
35 static public Type float_type;
36 static public Type double_type;
37 static public Type char_type;
38 static public Type char_ptr_type;
39 static public Type short_type;
40 static public Type decimal_type;
41 static public Type date_type;
42 static public Type bool_type;
43 static public Type sbyte_type;
44 static public Type byte_type;
45 static public Type ushort_type;
46 static public Type enum_type;
47 static public Type delegate_type;
48 static public Type multicast_delegate_type;
49 static public Type void_type;
50 static public Type null_type;
51 static public Type enumeration_type;
52 static public Type array_type;
53 static public Type runtime_handle_type;
54 static public Type icloneable_type;
55 static public Type type_type;
56 static public Type ienumerator_type;
57 static public Type idisposable_type;
58 static public Type default_member_type;
59 static public Type iasyncresult_type;
60 static public Type asynccallback_type;
61 static public Type intptr_type;
62 static public Type monitor_type;
63 static public Type runtime_field_handle_type;
64 static public Type attribute_type;
65 static public Type attribute_usage_type;
66 static public Type decimal_constant_attribute_type;
67 static public Type dllimport_type;
68 static public Type unverifiable_code_type;
69 static public Type methodimpl_attr_type;
70 static public Type marshal_as_attr_type;
71 static public Type param_array_type;
72 static public Type void_ptr_type;
73 static public Type indexer_name_type;
74 static public Type exception_type;
75 static public object obsolete_attribute_type;
76 static public object conditional_attribute_type;
79 // An empty array of types
81 static public Type [] NoTypes;
85 // Expressions representing the internal types. Used during declaration
88 static public TypeExpr system_object_expr, system_string_expr;
89 static public TypeExpr system_boolean_expr, system_decimal_expr;
90 static public TypeExpr system_single_expr, system_double_expr;
91 static public TypeExpr system_sbyte_expr, system_byte_expr;
92 static public TypeExpr system_int16_expr, system_uint16_expr;
93 static public TypeExpr system_int32_expr, system_uint32_expr;
94 static public TypeExpr system_int64_expr, system_uint64_expr;
95 static public TypeExpr system_char_expr, system_void_expr;
96 static public TypeExpr system_date_expr;
97 static public TypeExpr system_asynccallback_expr;
98 static public TypeExpr system_iasyncresult_expr;
101 // This is only used when compiling corlib
103 static public Type system_int32_type;
104 static public Type system_array_type;
105 static public Type system_type_type;
106 static public Type system_assemblybuilder_type;
107 static public MethodInfo system_int_array_get_length;
108 static public MethodInfo system_int_array_get_rank;
109 static public MethodInfo system_object_array_clone;
110 static public MethodInfo system_int_array_get_length_int;
111 static public MethodInfo system_int_array_get_lower_bound_int;
112 static public MethodInfo system_int_array_get_upper_bound_int;
113 static public MethodInfo system_void_array_copyto_array_int;
114 static public MethodInfo system_void_set_corlib_type_builders;
118 // Internal, not really used outside
120 static Type runtime_helpers_type;
123 // These methods are called by code generated by the compiler
125 static public MethodInfo string_concat_string_string;
126 static public MethodInfo string_concat_object_object;
127 static public MethodInfo string_isinterneted_string;
128 static public MethodInfo system_type_get_type_from_handle;
129 static public MethodInfo object_getcurrent_void;
130 static public MethodInfo bool_movenext_void;
131 static public MethodInfo void_dispose_void;
132 static public MethodInfo void_monitor_enter_object;
133 static public MethodInfo void_monitor_exit_object;
134 static public MethodInfo void_initializearray_array_fieldhandle;
135 static public MethodInfo int_getlength_int;
136 static public MethodInfo delegate_combine_delegate_delegate;
137 static public MethodInfo delegate_remove_delegate_delegate;
138 static public MethodInfo int_get_offset_to_string_data;
139 static public MethodInfo int_array_get_length;
140 static public MethodInfo int_array_get_rank;
141 static public MethodInfo object_array_clone;
142 static public MethodInfo int_array_get_length_int;
143 static public MethodInfo int_array_get_lower_bound_int;
144 static public MethodInfo int_array_get_upper_bound_int;
145 static public MethodInfo void_array_copyto_array_int;
148 // The attribute constructors.
150 static public ConstructorInfo cons_param_array_attribute;
151 static public ConstructorInfo void_decimal_ctor_five_args;
152 static public ConstructorInfo void_decimal_ctor_int_arg;
153 static public ConstructorInfo void_datetime_ctor_ticks_arg;
154 static public ConstructorInfo unverifiable_code_ctor;
155 static public ConstructorInfo default_member_ctor;
156 static public ConstructorInfo decimal_constant_attribute_ctor;
159 // Holds the Array of Assemblies that have been loaded
160 // (either because it is the default or the user used the
161 // -r command line option)
163 static Assembly [] assemblies;
166 // Keeps a list of module builders. We used this to do lookups
167 // on the modulebuilder using GetType -- needed for arrays
170 // This is changed from list of ModuleBuilders
171 // to list of Modules for getting addmodule
172 // compiler option working
173 // Anirban - 13.07.2004
175 static System.Reflection.Module [] modules;
178 // This is the type_cache from the assemblies to avoid
179 // hitting System.Reflection on every lookup.
181 static CaseInsensitiveHashtable types;
184 // This is used to hotld the corresponding TypeContainer objects
185 // since we need this in FindMembers
187 static CaseInsensitiveHashtable typecontainers;
190 // Keeps track of those types that are defined by the
193 static ArrayList user_types;
195 static PtrHashtable builder_to_declspace;
198 // Tracks the interfaces implemented by typebuilders. We only
199 // enter those who do implement or or more interfaces
201 static PtrHashtable builder_to_ifaces;
204 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
205 // the arguments to the method
207 static Hashtable method_arguments;
210 // Maps PropertyBuilder to a Type array that contains
211 // the arguments to the indexer
213 static Hashtable indexer_arguments;
216 // Maybe 'method_arguments' should be replaced and only
217 // method_internal_params should be kept?
219 static Hashtable method_internal_params;
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 negative_hits = new CaseInsensitiveHashtable ();
310 typecontainers = new CaseInsensitiveHashtable ();
312 builder_to_declspace = 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);
397 /// Returns the TypeContainer whose Type is 't' or null if there is no
398 /// TypeContainer for 't' (ie, the Type comes from a library)
400 public static TypeContainer LookupTypeContainer (Type t)
402 return builder_to_declspace [t] as TypeContainer;
405 public static IMemberContainer LookupMemberContainer (Type t)
407 if (t is TypeBuilder) {
408 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
409 if (container != null)
413 return TypeHandle.GetTypeHandle (t);
416 public static Interface LookupInterface (Type t)
418 return builder_to_declspace [t] as Interface;
421 public static Delegate LookupDelegate (Type t)
423 return builder_to_declspace [t] as Delegate;
426 public static Enum LookupEnum (Type t)
428 return builder_to_declspace [t] as Enum;
431 public static TypeContainer LookupClass (Type t)
433 return builder_to_declspace [t] as TypeContainer;
437 /// Registers an assembly to load types from.
439 public static void AddAssembly (Assembly a)
441 int top = assemblies.Length;
442 Assembly [] n = new Assembly [top + 1];
444 assemblies.CopyTo (n, 0);
449 foreach(Type type in a.GetTypes()) {
450 if (type.IsPublic ) // && type. attributed as standard module
451 AddStandardModule(type);
456 /// Registers a module builder to lookup types from
458 public static void AddModule (System.Reflection.Module mb)
460 int top = modules != null ? modules.Length : 0;
461 System.Reflection.Module [] n = new System.Reflection.Module [top + 1];
464 modules.CopyTo (n, 0);
469 private class StandardModule {
470 public readonly string Namespace;
471 public readonly string Name;
472 private readonly string asString;
473 public StandardModule(string _namespace, string name) {
474 Namespace = _namespace;
476 asString = ((Namespace != null && Namespace.Length > 0)?(Namespace + "."):"") + Name;
478 public override string ToString() { return asString; }
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 an 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) ;
523 /// Find types from pertinent standard modules (from those namespaces in the scope)
525 public static Type[] GetPertinentStandardModules(params string[] namespaces)
527 ArrayList list = new ArrayList();
528 if (standardModules != null && namespaces != null) {
529 foreach(string Namespace in namespaces)
531 for(int i = 0; i < standardModules.Length; i++) {
532 if (standardModules[i].Namespace.ToLower () == Namespace.ToLower ()) {
533 string name = standardModules[i].ToString();
534 Type t = LookupType(name);
536 System.Console.WriteLine("Could not find standard module '" + name + "'");
545 return (Type[])list.ToArray(typeof(Type));
549 // Low-level lookup, cache-less
551 static Type LookupTypeReflection (string name)
556 foreach (Assembly a in assemblies){
557 t = a.GetType (name, false, true);
562 foreach (System.Reflection.Module mb in modules) {
563 t = mb.GetType (name, false, true);
568 } catch (Exception e) {
569 System.Console.WriteLine("\nERROR: " + e.ToString() + "WHILE EXECUTING LookupTypeReflection(\"" + name + "\")\n");
574 static CaseInsensitiveHashtable negative_hits;
576 // This function is used when you want to avoid the lookups, and want to go
577 // directly to the source. This will use the cache.
579 // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
580 // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
581 // way to test things other than doing a fullname compare
583 public static Type LookupTypeDirect (string name)
585 Type t = (Type) types [name];
589 if (negative_hits.Contains (name))
591 t = LookupTypeReflection (name);
593 negative_hits [name] = null;
600 /// Returns the Type associated with @name, takes care of the fact that
601 /// reflection expects nested types to be separated from the main type
602 /// with a "+" instead of a "."
604 public static Type LookupType (string name)
609 // First lookup in user defined and cached values
612 t = (Type) types [name];
616 if (negative_hits.Contains (name))
620 // Optimization: ComposedCast will work with an existing type, and might already have the
621 // full name of the type, so the full system lookup can probably be avoided.
624 string [] elements = name.Split ('.');
625 int count = elements.Length;
627 for (int n = 1; n <= count; n++){
628 string top_level_type = String.Join (".", elements, 0, n);
630 if (negative_hits.Contains (top_level_type))
633 t = (Type) types [top_level_type];
635 t = LookupTypeReflection (top_level_type);
637 negative_hits [top_level_type] = null;
647 string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
648 t = LookupTypeReflection (newt);
650 negative_hits [name] = null;
655 negative_hits [name] = null;
660 // Returns a list of all namespaces in the assemblies and types loaded.
662 public static CaseInsensitiveHashtable GetNamespaces ()
664 CaseInsensitiveHashtable namespaces = new CaseInsensitiveHashtable ();
666 foreach (Assembly a in assemblies) {
667 foreach (Type t in a.GetTypes ()) {
668 string ns = t.Namespace;
670 if (namespaces.Contains (ns))
672 namespaces [ns] = ns;
676 foreach (System.Reflection.Module mb in modules) {
677 foreach (Type t in mb.GetTypes ()) {
678 string ns = t.Namespace;
680 if (namespaces.Contains (ns))
682 namespaces [ns] = ns;
690 /// Returns the C# name of a type if possible, or the full type name otherwise
692 static public string MonoBASIC_Name (Type t)
694 return Regex.Replace (t.FullName,
696 @"(Int32|Int16|Int64|Single|Double|Char|Decimal|Byte|Object|Boolean|String|DateTime)" +
698 new MatchEvaluator (MonoBASIC_NameMatch));
701 static String MonoBASIC_NameMatch (Match match)
703 string s = match.Groups [1].Captures [0].Value;
705 Replace ("int32", "integer").
706 Replace ("int16", "short").
707 Replace ("int64", "long").
708 Replace ("datetime", "date")
709 + match.Groups [2].Captures [0].Value;
713 /// Returns the signature of the method
715 static public string MonoBASIC_Signature (MethodBase mb)
720 // FIXME: We should really have a single function to do
721 // everything instead of the following 5 line pattern
723 ParameterData iparams = LookupParametersByBuilder (mb);
725 if (iparams == null){
726 ParameterInfo [] pi = mb.GetParameters ();
727 iparams = new ReflectionParameters (pi);
730 for (int i = 0; i < iparams.Count; i++) {
734 sig += iparams.ParameterDesc(i);
738 return mb.DeclaringType.Name + "." + mb.Name + sig;
742 /// Looks up a type, and aborts if it is not found. This is used
743 /// by types required by the compiler
745 static Type CoreLookupType (string name)
747 Type t = LookupType (name);
750 Report.Error (518, "The predefined type '" + name + "' is not defined or imported");
751 Environment.Exit (0);
758 /// Returns the MethodInfo for a method named 'name' defined
759 /// in type 't' which takes arguments of types 'args'
761 static MethodInfo GetMethod (Type t, string name, Type [] args)
769 list = FindMembers (t, MemberTypes.Method, instance_and_static | BindingFlags.Public| BindingFlags.IgnoreCase,
770 signature_filter, sig);
771 if (list.Count == 0) {
772 Report.Error (-19, "Can not find the core function '" + name + "'");
776 MethodInfo mi = list [0] as MethodInfo;
778 Report.Error (-19, "Can not find the core function '" + name + "'");
786 /// Returns the ConstructorInfo for "args"
788 public static ConstructorInfo GetConstructor (Type t, Type [] args)
796 list = FindMembers (t, MemberTypes.Constructor,
797 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
798 signature_filter, sig);
799 if (list.Count == 0){
800 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
804 ConstructorInfo ci = list [0] as ConstructorInfo;
806 Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
813 public static void InitEnumUnderlyingTypes ()
816 int32_type = CoreLookupType ("System.Int32");
817 int64_type = CoreLookupType ("System.Int64");
818 uint32_type = CoreLookupType ("System.UInt32");
819 uint64_type = CoreLookupType ("System.UInt64");
820 byte_type = CoreLookupType ("System.Byte");
821 sbyte_type = CoreLookupType ("System.SByte");
822 short_type = CoreLookupType ("System.Int16");
823 ushort_type = CoreLookupType ("System.UInt16");
827 /// The types have to be initialized after the initial
828 /// population of the type has happened (for example, to
829 /// bootstrap the corlib.dll
831 public static void InitCoreTypes ()
833 object_type = CoreLookupType ("System.Object");
834 value_type = CoreLookupType ("System.ValueType");
836 InitEnumUnderlyingTypes ();
838 char_type = CoreLookupType ("System.Char");
839 string_type = CoreLookupType ("System.String");
840 float_type = CoreLookupType ("System.Single");
841 double_type = CoreLookupType ("System.Double");
842 char_ptr_type = CoreLookupType ("System.Char*");
843 decimal_type = CoreLookupType ("System.Decimal");
844 bool_type = CoreLookupType ("System.Boolean");
845 enum_type = CoreLookupType ("System.Enum");
847 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
848 delegate_type = CoreLookupType ("System.Delegate");
850 array_type = CoreLookupType ("System.Array");
851 void_type = CoreLookupType ("System.Void");
852 date_type = CoreLookupType ("System.DateTime");
853 type_type = CoreLookupType ("System.Type");
855 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
856 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
857 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
858 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
859 asynccallback_type = CoreLookupType ("System.AsyncCallback");
860 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
861 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
862 idisposable_type = CoreLookupType ("System.IDisposable");
863 icloneable_type = CoreLookupType ("System.ICloneable");
864 monitor_type = CoreLookupType ("System.Threading.Monitor");
865 intptr_type = CoreLookupType ("System.IntPtr");
867 attribute_type = CoreLookupType ("System.Attribute");
868 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
869 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
870 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
871 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
872 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
874 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
876 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
878 void_ptr_type = CoreLookupType ("System.Void*");
880 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
882 exception_type = CoreLookupType ("System.Exception");
887 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
888 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
891 // When compiling corlib, store the "real" types here.
893 if (!RootContext.StdLib) {
894 system_int32_type = typeof (System.Int32);
895 system_array_type = typeof (System.Array);
896 system_type_type = typeof (System.Type);
897 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
899 Type [] void_arg = { };
900 system_int_array_get_length = GetMethod (
901 system_array_type, "get_Length", void_arg);
902 system_int_array_get_rank = GetMethod (
903 system_array_type, "get_Rank", void_arg);
904 system_object_array_clone = GetMethod (
905 system_array_type, "Clone", void_arg);
907 Type [] system_int_arg = { system_int32_type };
908 system_int_array_get_length_int = GetMethod (
909 system_array_type, "GetLength", system_int_arg);
910 system_int_array_get_upper_bound_int = GetMethod (
911 system_array_type, "GetUpperBound", system_int_arg);
912 system_int_array_get_lower_bound_int = GetMethod (
913 system_array_type, "GetLowerBound", system_int_arg);
915 Type [] system_array_int_arg = { system_array_type, system_int32_type };
916 system_void_array_copyto_array_int = GetMethod (
917 system_array_type, "CopyTo", system_array_int_arg);
919 Type [] system_type_type_arg = { system_type_type, system_type_type, system_type_type };
922 system_void_set_corlib_type_builders = GetMethod (
923 system_assemblybuilder_type, "SetCorlibTypeBuilders",
924 system_type_type_arg);
926 object[] args = new object [3];
927 args [0] = object_type;
928 args [1] = value_type;
929 args [2] = enum_type;
931 system_void_set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
933 Console.WriteLine ("Corlib compilation is not supported in Microsoft.NET due to bugs in it");
937 null_type = typeof (NullType);
941 // The helper methods that are used by the compiler
943 public static void InitCodeHelpers ()
946 // Now load the default methods that we use.
948 Type [] string_string = { string_type, string_type };
949 string_concat_string_string = GetMethod (
950 string_type, "Concat", string_string);
952 Type [] object_object = { object_type, object_type };
953 string_concat_object_object = GetMethod (
954 string_type, "Concat", object_object);
956 Type [] string_ = { string_type };
957 string_isinterneted_string = GetMethod (
958 string_type, "IsInterned", string_);
960 Type [] runtime_type_handle = { runtime_handle_type };
961 system_type_get_type_from_handle = GetMethod (
962 type_type, "GetTypeFromHandle", runtime_type_handle);
964 Type [] delegate_delegate = { delegate_type, delegate_type };
965 delegate_combine_delegate_delegate = GetMethod (
966 delegate_type, "Combine", delegate_delegate);
968 delegate_remove_delegate_delegate = GetMethod (
969 delegate_type, "Remove", delegate_delegate);
974 Type [] void_arg = { };
975 object_getcurrent_void = GetMethod (
976 ienumerator_type, "get_Current", void_arg);
977 bool_movenext_void = GetMethod (
978 ienumerator_type, "MoveNext", void_arg);
979 void_dispose_void = GetMethod (
980 idisposable_type, "Dispose", void_arg);
981 int_get_offset_to_string_data = GetMethod (
982 runtime_helpers_type, "get_OffsetToStringData", void_arg);
983 int_array_get_length = GetMethod (
984 array_type, "get_Length", void_arg);
985 int_array_get_rank = GetMethod (
986 array_type, "get_Rank", void_arg);
991 Type [] int_arg = { int32_type };
992 int_array_get_length_int = GetMethod (
993 array_type, "GetLength", int_arg);
994 int_array_get_upper_bound_int = GetMethod (
995 array_type, "GetUpperBound", int_arg);
996 int_array_get_lower_bound_int = GetMethod (
997 array_type, "GetLowerBound", int_arg);
1000 // System.Array methods
1002 object_array_clone = GetMethod (
1003 array_type, "Clone", void_arg);
1004 Type [] array_int_arg = { array_type, int32_type };
1005 void_array_copyto_array_int = GetMethod (
1006 array_type, "CopyTo", array_int_arg);
1011 Type [] object_arg = { object_type };
1012 void_monitor_enter_object = GetMethod (
1013 monitor_type, "Enter", object_arg);
1014 void_monitor_exit_object = GetMethod (
1015 monitor_type, "Exit", object_arg);
1017 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1019 void_initializearray_array_fieldhandle = GetMethod (
1020 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1025 int_getlength_int = GetMethod (
1026 array_type, "GetLength", int_arg);
1029 // Decimal constructors
1031 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1032 void_decimal_ctor_five_args = GetConstructor (
1033 decimal_type, dec_arg);
1034 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1037 // DateTime constructor
1038 Type [] ticks_arg = { int64_type };
1039 void_datetime_ctor_ticks_arg = GetConstructor ( date_type, ticks_arg);
1044 cons_param_array_attribute = GetConstructor (
1045 param_array_type, void_arg);
1047 unverifiable_code_ctor = GetConstructor (
1048 unverifiable_code_type, void_arg);
1050 default_member_ctor = GetConstructor (
1051 default_member_type, string_);
1053 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1054 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1058 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1060 //static CaseInsensitiveHashtable type_hash = new CaseInsensitiveHashtable ();
1063 /// This is the "old", non-cache based FindMembers() function. We cannot use
1064 /// the cache here because there is no member name argument.
1066 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1067 MemberFilter filter, object criteria)
1069 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1070 bf |= BindingFlags.IgnoreCase;
1072 // 'builder_to_declspace' contains all dynamic types.
1076 Timer.StartTimer (TimerType.FindMembers);
1077 list = decl.FindMembers (mt, bf, filter, criteria);
1078 Timer.StopTimer (TimerType.FindMembers);
1083 // We have to take care of arrays specially, because GetType on
1084 // a TypeBuilder array will return a Type, not a TypeBuilder,
1085 // and we can not call FindMembers on this type.
1087 if (t.IsSubclassOf (TypeManager.array_type))
1088 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1091 // Since FindMembers will not lookup both static and instance
1092 // members, we emulate this behaviour here.
1094 if ((bf & instance_and_static) == instance_and_static){
1095 MemberInfo [] i_members = t.FindMembers (
1096 mt, (bf & ~BindingFlags.Static) | BindingFlags.IgnoreCase, filter, criteria);
1098 int i_len = i_members.Length;
1100 MemberInfo one = i_members [0];
1103 // If any of these are present, we are done!
1105 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1106 return new MemberList (i_members);
1109 MemberInfo [] s_members = t.FindMembers (
1110 mt, (bf & ~BindingFlags.Instance) | BindingFlags.IgnoreCase, filter, criteria);
1112 int s_len = s_members.Length;
1113 if (i_len > 0 || s_len > 0)
1114 return new MemberList (i_members, s_members);
1117 return new MemberList (i_members);
1119 return new MemberList (s_members);
1123 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1128 /// This method is only called from within MemberLookup. It tries to use the member
1129 /// cache if possible and falls back to the normal FindMembers if not. The 'used_cache'
1130 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1131 /// our return value will already contain all inherited members and the caller don't need
1132 /// to check base classes and interfaces anymore.
1134 private static MemberList MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1135 string name, out bool used_cache)
1138 // We have to take care of arrays specially, because GetType on
1139 // a TypeBuilder array will return a Type, not a TypeBuilder,
1140 // and we can not call FindMembers on this type.
1142 if (t.IsSubclassOf (TypeManager.array_type)) {
1144 return TypeHandle.ArrayType.MemberCache.FindMembers (
1145 mt, bf, name, FilterWithClosure_delegate, null);
1149 // If this is a dynamic type, it's always in the 'builder_to_declspace' hash table
1150 // and we can ask the DeclSpace for the MemberCache.
1152 if (t is TypeBuilder) {
1153 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1154 MemberCache cache = decl.MemberCache;
1157 // If this DeclSpace has a MemberCache, use it.
1160 if (cache != null) {
1162 return cache.FindMembers (
1163 mt, bf, name, FilterWithClosure_delegate, null);
1166 // If there is no MemberCache, we need to use the "normal" FindMembers.
1169 Timer.StartTimer (TimerType.FindMembers);
1170 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
1171 FilterWithClosure_delegate, name);
1172 Timer.StopTimer (TimerType.FindMembers);
1178 // This call will always succeed. There is exactly one TypeHandle instance per
1179 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1180 // if it didn't already exist.
1182 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1185 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1188 public static bool IsBuiltinType (Type t)
1190 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1191 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1192 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1193 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type ||
1200 public static bool IsDelegateType (Type t)
1202 if (t.IsSubclassOf (TypeManager.delegate_type))
1208 public static bool IsEnumType (Type t)
1210 if (t.IsSubclassOf (TypeManager.enum_type))
1217 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1219 public static bool IsUnmanagedType (Type t)
1221 if (IsBuiltinType (t) && t != TypeManager.string_type)
1230 if (IsValueType (t)){
1231 if (t is TypeBuilder){
1232 TypeContainer tc = LookupTypeContainer (t);
1234 foreach (Field f in tc.Fields){
1235 if (f.FieldBuilder.IsStatic)
1237 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1241 FieldInfo [] fields = t.GetFields ();
1243 foreach (FieldInfo f in fields){
1246 if (!IsUnmanagedType (f.FieldType))
1256 public static bool IsValueType (Type t)
1258 if (t.IsSubclassOf (TypeManager.value_type))
1264 public static bool IsInterfaceType (Type t)
1266 Interface iface = builder_to_declspace [t] as Interface;
1275 // Checks whether 'type' is a subclass or nested child of 'parent'.
1277 public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1280 if ((type == parent) || type.IsSubclassOf (parent))
1283 // Handle nested types.
1284 type = type.DeclaringType;
1285 } while (type != null);
1291 // Checks whether 'type' is a nested child of 'parent'.
1293 public static bool IsNestedChildOf (Type type, Type parent)
1295 if ((type == parent) || type.IsSubclassOf (parent))
1298 return IsSubclassOrNestedChildOf (type, parent);
1302 /// Returns the User Defined Types
1304 public static ArrayList UserTypes {
1310 public static CaseInsensitiveHashtable TypeContainers {
1312 return typecontainers;
1316 static Hashtable builder_to_constant;
1318 public static void RegisterConstant (FieldBuilder fb, Const c)
1320 if (builder_to_constant == null)
1321 builder_to_constant = new PtrHashtable ();
1323 if (builder_to_constant.Contains (fb))
1326 builder_to_constant.Add (fb, c);
1329 public static Const LookupConstant (FieldBuilder fb)
1331 if (builder_to_constant == null)
1334 return (Const) builder_to_constant [fb];
1338 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1342 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1343 /// for anything which is dynamic, and we need this in a number of places,
1344 /// we register this information here, and use it afterwards.
1346 static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1351 method_arguments.Add (mb, args);
1352 method_internal_params.Add (mb, ip);
1357 static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1359 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1362 if (method_internal_params.Contains (mb))
1363 return (InternalParameters) method_internal_params [mb];
1365 throw new Exception ("Argument for Method not registered" + mb);
1369 /// Returns the argument types for a method based on its methodbase
1371 /// For dynamic methods, we use the compiler provided types, for
1372 /// methods from existing assemblies we load them from GetParameters,
1373 /// and insert them into the cache
1375 static public Type [] GetArgumentTypes (MethodBase mb)
1377 if (method_arguments.Contains (mb))
1378 return (Type []) method_arguments [mb];
1380 ParameterInfo [] pi = mb.GetParameters ();
1382 Type [] types = new Type [c];
1384 for (int i = 0; i < c; i++)
1385 types [i] = pi [i].ParameterType;
1387 method_arguments.Add (mb, types);
1393 /// Returns the argument types for an indexer based on its PropertyInfo
1395 /// For dynamic indexers, we use the compiler provided types, for
1396 /// indexers from existing assemblies we load them from GetParameters,
1397 /// and insert them into the cache
1399 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1401 if (indexer_arguments.Contains (indexer))
1402 return (Type []) indexer_arguments [indexer];
1404 // If we're a PropertyBuilder and not in the
1405 // 'indexer_arguments' hash, then we're a property and
1408 MethodInfo mi = indexer.GetSetMethod (true);
1410 mi = indexer.GetGetMethod (true);
1415 ParameterInfo [] pi = mi.GetParameters ();
1420 Type [] types = new Type [c];
1422 for (int i = 0; i < c; i++)
1423 types [i] = pi [i].ParameterType;
1425 indexer_arguments.Add (indexer, types);
1430 ParameterInfo [] pi = indexer.GetIndexParameters ();
1431 // Property, not an indexer.
1435 Type [] types = new Type [c];
1437 for (int i = 0; i < c; i++)
1438 types [i] = pi [i].ParameterType;
1440 indexer_arguments.Add (indexer, types);
1446 // This is a workaround the fact that GetValue is not
1447 // supported for dynamic types
1449 static CaseInsensitiveHashtable fields = new CaseInsensitiveHashtable ();
1450 static public bool RegisterFieldValue (FieldBuilder fb, object value)
1452 if (fields.Contains (fb))
1455 fields.Add (fb, value);
1460 static public object GetValue (FieldBuilder fb)
1465 static CaseInsensitiveHashtable fieldbuilders_to_fields = new CaseInsensitiveHashtable ();
1466 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1468 if (fieldbuilders_to_fields.Contains (fb))
1471 fieldbuilders_to_fields.Add (fb, f);
1475 static public FieldBase GetField (FieldInfo fb)
1477 return (FieldBase) fieldbuilders_to_fields [fb];
1480 static CaseInsensitiveHashtable events;
1482 static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1485 events = new CaseInsensitiveHashtable ();
1487 if (events.Contains (eb))
1490 events.Add (eb, new Pair (add, remove));
1495 static public MethodInfo GetAddMethod (EventInfo ei)
1497 if (ei is MyEventBuilder) {
1498 Pair pair = (Pair) events [ei];
1500 return (MethodInfo) pair.First;
1502 return ei.GetAddMethod ();
1505 static public MethodInfo GetRemoveMethod (EventInfo ei)
1507 if (ei is MyEventBuilder) {
1508 Pair pair = (Pair) events [ei];
1510 return (MethodInfo) pair.Second;
1512 return ei.GetAddMethod ();
1515 static CaseInsensitiveHashtable priv_fields_events;
1517 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1519 if (priv_fields_events == null)
1520 priv_fields_events = new CaseInsensitiveHashtable ();
1522 if (priv_fields_events.Contains (einfo))
1525 priv_fields_events.Add (einfo, builder);
1530 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1532 return (MemberInfo) priv_fields_events [ei];
1535 static CaseInsensitiveHashtable properties;
1537 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1539 if (properties == null)
1540 properties = new CaseInsensitiveHashtable ();
1542 if (properties.Contains (pb))
1545 properties.Add (pb, new Pair (get, set));
1546 indexer_arguments.Add (pb, NoTypes);
1551 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get, MethodBase set, Type[] args)
1553 if (!RegisterProperty (pb, get,set))
1556 indexer_arguments.Add (pb, args);
1561 static public MethodInfo GetPropertyGetter (PropertyInfo pi)
1563 if (pi is PropertyBuilder){
1564 Pair de = (Pair) properties [pi];
1566 return (MethodInfo) de.Second;
1568 return pi.GetSetMethod (true);
1571 static public MethodInfo GetPropertySetter (PropertyInfo pi)
1573 if (pi is PropertyBuilder){
1574 Pair de = (Pair) properties [pi];
1576 return (MethodInfo) de.First;
1578 return pi.GetGetMethod (true);
1582 /// Given an array of interface types, expand and eliminate repeated ocurrences
1583 /// of an interface.
1587 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1591 public static Type [] ExpandInterfaces (Type [] base_interfaces)
1593 ArrayList new_ifaces = new ArrayList();
1594 ExpandAllInterfaces (base_interfaces, ref new_ifaces);
1595 Type [] ret = new Type [new_ifaces.Count];
1596 new_ifaces.CopyTo (ret, 0);
1602 /// Recursively finds out each base interface in case
1603 /// of multiple inheritance
1605 public static void ExpandAllInterfaces
1606 (Type [] base_interfaces, ref ArrayList new_ifaces)
1608 foreach (Type iface in base_interfaces) {
1609 if (!new_ifaces.Contains (iface))
1610 new_ifaces.Add (iface);
1612 Type [] implementing = TypeManager.GetInterfaces (iface);
1614 // Incase any base interface is present call this function again
1616 if (implementing.Length != 0)
1617 ExpandAllInterfaces (implementing, ref new_ifaces);
1622 /// This function returns the interfaces in the type 't'. Works with
1623 /// both types and TypeBuilders.
1625 public static Type [] GetInterfaces (Type t)
1628 // The reason for catching the Array case is that Reflection.Emit
1629 // will not return a TypeBuilder for Array types of TypeBuilder types,
1630 // but will still throw an exception if we try to call GetInterfaces
1633 // Since the array interfaces are always constant, we return those for
1638 t = TypeManager.array_type;
1640 if (t is TypeBuilder){
1641 Type [] parent_ifaces;
1643 if (t.BaseType == null)
1644 parent_ifaces = NoTypes;
1646 parent_ifaces = GetInterfaces (t.BaseType);
1647 Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1648 if (type_ifaces == null)
1649 type_ifaces = NoTypes;
1651 int parent_count = parent_ifaces.Length;
1652 Type [] result = new Type [parent_count + type_ifaces.Length];
1653 parent_ifaces.CopyTo (result, 0);
1654 type_ifaces.CopyTo (result, parent_count);
1658 return t.GetInterfaces ();
1662 /// The following is used to check if a given type implements an interface.
1663 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1665 public static bool ImplementsInterface (Type t, Type iface)
1670 // FIXME OPTIMIZATION:
1671 // as soon as we hit a non-TypeBuiler in the interface
1672 // chain, we could return, as the 'Type.GetInterfaces'
1673 // will return all the interfaces implement by the type
1677 interfaces = GetInterfaces (t);
1679 if (interfaces != null){
1680 foreach (Type i in interfaces){
1687 } while (t != null);
1692 // This is a custom version of Convert.ChangeType() which works
1693 // with the TypeBuilder defined types when compiling corlib.
1695 // This function is used by DoDefineMember () in enum.cs
1696 // After replacing it with ChangeType1() following function
1699 public static object ChangeType (object value, Type conversionType)
1701 if (!(value is IConvertible))
1702 throw new ArgumentException ();
1704 IConvertible convertValue = (IConvertible) value;
1705 CultureInfo ci = CultureInfo.CurrentCulture;
1706 NumberFormatInfo provider = ci.NumberFormat;
1709 // We must use Type.Equals() here since 'conversionType' is
1710 // the TypeBuilder created version of a system type and not
1711 // the system type itself. You cannot use Type.GetTypeCode()
1712 // on such a type - it'd always return TypeCode.Object.
1714 if (conversionType.Equals (typeof (Boolean)))
1715 return (object)(convertValue.ToBoolean (provider));
1716 else if (conversionType.Equals (typeof (Byte)))
1717 return (object)(convertValue.ToByte (provider));
1718 else if (conversionType.Equals (typeof (Char)))
1719 return (object)(convertValue.ToChar (provider));
1720 else if (conversionType.Equals (typeof (DateTime)))
1721 return (object)(convertValue.ToDateTime (provider));
1722 else if (conversionType.Equals (typeof (Decimal)))
1723 return (object)(convertValue.ToDecimal (provider));
1724 else if (conversionType.Equals (typeof (Double)))
1725 return (object)(convertValue.ToDouble (provider));
1726 else if (conversionType.Equals (typeof (Int16)))
1727 return (object)(convertValue.ToInt16 (provider));
1728 else if (conversionType.Equals (typeof (Int32)))
1729 return (object)(convertValue.ToInt32 (provider));
1730 else if (conversionType.Equals (typeof (Int64)))
1731 return (object)(convertValue.ToInt64 (provider));
1732 else if (conversionType.Equals (typeof (SByte)))
1733 return (object)(convertValue.ToSByte (provider));
1734 else if (conversionType.Equals (typeof (Single)))
1735 return (object)(convertValue.ToSingle (provider));
1736 else if (conversionType.Equals (typeof (String)))
1737 return (object)(convertValue.ToString (provider));
1738 else if (conversionType.Equals (typeof (UInt16)))
1739 return (object)(convertValue.ToUInt16 (provider));
1740 else if (conversionType.Equals (typeof (UInt32)))
1741 return (object)(convertValue.ToUInt32 (provider));
1742 else if (conversionType.Equals (typeof (UInt64)))
1743 return (object)(convertValue.ToUInt64 (provider));
1744 else if (conversionType.Equals (typeof (Object)))
1745 return (object)(value);
1747 throw new InvalidCastException ();
1750 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
1752 public static object ChangeType1 (object value, Type conversionType, out bool error)
1754 IConvertible convert_value = value as IConvertible;
1756 if (convert_value == null){
1762 // We must use Type.Equals() here since `conversionType' is
1763 // the TypeBuilder created version of a system type and not
1764 // the system type itself. You cannot use Type.GetTypeCode()
1765 // on such a type - it'd always return TypeCode.Object.
1769 if (conversionType.Equals (typeof (Boolean)))
1770 return (object)(convert_value.ToBoolean (nf_provider));
1771 else if (conversionType.Equals (typeof (Byte)))
1772 return (object)(convert_value.ToByte (nf_provider));
1773 else if (conversionType.Equals (typeof (Char)))
1774 return (object)(convert_value.ToChar (nf_provider));
1775 else if (conversionType.Equals (typeof (DateTime)))
1776 return (object)(convert_value.ToDateTime (nf_provider));
1777 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
1778 return (object)(convert_value.ToDecimal (nf_provider));
1779 else if (conversionType.Equals (typeof (Double)))
1780 return (object)(convert_value.ToDouble (nf_provider));
1781 else if (conversionType.Equals (typeof (Int16)))
1782 return (object)(convert_value.ToInt16 (nf_provider));
1783 else if (conversionType.Equals (typeof (Int32)))
1784 return (object)(convert_value.ToInt32 (nf_provider));
1785 else if (conversionType.Equals (typeof (Int64)))
1786 return (object)(convert_value.ToInt64 (nf_provider));
1787 else if (conversionType.Equals (typeof (SByte)))
1788 return (object)(convert_value.ToSByte (nf_provider));
1789 else if (conversionType.Equals (typeof (Single)))
1790 return (object)(convert_value.ToSingle (nf_provider));
1791 else if (conversionType.Equals (typeof (String)))
1792 return (object)(convert_value.ToString (nf_provider));
1793 else if (conversionType.Equals (typeof (UInt16)))
1794 return (object)(convert_value.ToUInt16 (nf_provider));
1795 else if (conversionType.Equals (typeof (UInt32)))
1796 return (object)(convert_value.ToUInt32 (nf_provider));
1797 else if (conversionType.Equals (typeof (UInt64)))
1798 return (object)(convert_value.ToUInt64 (nf_provider));
1799 else if (conversionType.Equals (typeof (Object)))
1800 return (object)(value);
1811 // This is needed, because enumerations from assemblies
1812 // do not report their underlyingtype, but they report
1815 public static Type EnumToUnderlying (Type t)
1817 if (t == TypeManager.enum_type)
1820 t = t.UnderlyingSystemType;
1821 if (!TypeManager.IsEnumType (t))
1824 if (t is TypeBuilder) {
1825 // slow path needed to compile corlib
1826 if (t == TypeManager.bool_type ||
1827 t == TypeManager.byte_type ||
1828 t == TypeManager.sbyte_type ||
1829 t == TypeManager.char_type ||
1830 t == TypeManager.short_type ||
1831 t == TypeManager.ushort_type ||
1832 t == TypeManager.int32_type ||
1833 t == TypeManager.uint32_type ||
1834 t == TypeManager.int64_type ||
1835 t == TypeManager.float_type ||
1836 t == TypeManager.double_type ||
1837 t == TypeManager.decimal_type ||
1838 t == TypeManager.uint64_type)
1840 // Following line is commented out to handle case like
1854 // throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
1856 TypeCode tc = Type.GetTypeCode (t);
1859 case TypeCode.Boolean:
1860 return TypeManager.bool_type;
1862 return TypeManager.byte_type;
1863 case TypeCode.SByte:
1864 return TypeManager.sbyte_type;
1866 return TypeManager.char_type;
1867 case TypeCode.Int16:
1868 return TypeManager.short_type;
1869 case TypeCode.UInt16:
1870 return TypeManager.ushort_type;
1871 case TypeCode.Int32:
1872 return TypeManager.int32_type;
1873 case TypeCode.UInt32:
1874 return TypeManager.uint32_type;
1875 case TypeCode.Int64:
1876 return TypeManager.int64_type;
1877 case TypeCode.UInt64:
1878 return TypeManager.uint64_type;
1879 case TypeCode.Single:
1880 return TypeManager.float_type;
1881 case TypeCode.Double:
1882 return TypeManager.double_type;
1883 case TypeCode.Decimal:
1884 return TypeManager.decimal_type;
1886 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1890 // When compiling corlib and called with one of the core types, return
1891 // the corresponding typebuilder for that type.
1893 public static Type TypeToCoreType (Type t)
1895 if (RootContext.StdLib || (t is TypeBuilder))
1898 TypeCode tc = Type.GetTypeCode (t);
1901 case TypeCode.Boolean:
1902 return TypeManager.bool_type;
1904 return TypeManager.byte_type;
1905 case TypeCode.SByte:
1906 return TypeManager.sbyte_type;
1908 return TypeManager.char_type;
1909 case TypeCode.Int16:
1910 return TypeManager.short_type;
1911 case TypeCode.UInt16:
1912 return TypeManager.ushort_type;
1913 case TypeCode.Int32:
1914 return TypeManager.int32_type;
1915 case TypeCode.UInt32:
1916 return TypeManager.uint32_type;
1917 case TypeCode.Int64:
1918 return TypeManager.int64_type;
1919 case TypeCode.UInt64:
1920 return TypeManager.uint64_type;
1921 case TypeCode.String:
1922 return TypeManager.string_type;
1923 case TypeCode.DateTime:
1924 return TypeManager.date_type;
1926 if (t == typeof (void))
1927 return TypeManager.void_type;
1928 if (t == typeof (object))
1929 return TypeManager.object_type;
1930 if (t == typeof (System.Type))
1931 return TypeManager.type_type;
1936 public static TypeExpr TypeToCoreTypeExpr (Type t)
1941 TypeCode tc = Type.GetTypeCode (t);
1944 case TypeCode.Boolean:
1945 return TypeManager.system_boolean_expr;
1947 return TypeManager.system_byte_expr;
1948 case TypeCode.SByte:
1949 return TypeManager.system_sbyte_expr;
1951 return TypeManager.system_char_expr;
1952 case TypeCode.Int16:
1953 return TypeManager.system_int16_expr;
1954 case TypeCode.UInt16:
1955 return TypeManager.system_uint16_expr;
1956 case TypeCode.Int32:
1957 return TypeManager.system_int32_expr;
1958 case TypeCode.UInt32:
1959 return TypeManager.system_uint32_expr;
1960 case TypeCode.Int64:
1961 return TypeManager.system_int64_expr;
1962 case TypeCode.UInt64:
1963 return TypeManager.system_uint64_expr;
1964 case TypeCode.String:
1965 return TypeManager.system_string_expr;
1966 case TypeCode.Decimal:
1967 return TypeManager.system_decimal_expr;
1968 case TypeCode.Single:
1969 return TypeManager.system_single_expr;
1970 case TypeCode.Double:
1971 return TypeManager.system_double_expr;
1972 case TypeCode.DateTime:
1973 return TypeManager.system_date_expr;
1975 if (t == typeof (void))
1976 return TypeManager.system_void_expr;
1977 if (t == typeof (object))
1978 return TypeManager.system_object_expr;
1979 //FIXME : return t; What should be returned here?
1984 /// Utility function that can be used to probe whether a type
1985 /// is managed or not.
1987 public static bool VerifyUnManaged (Type t, Location loc)
1989 if (t.IsValueType || t.IsPointer){
1991 // FIXME: this is more complex, we actually need to
1992 // make sure that the type does not contain any
1998 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
1999 // We need this explicit check here to make it work when
2000 // compiling corlib.
2005 "Cannot take the address or size of a variable of a managed type ('" +
2006 MonoBASIC_Name (t) + "')");
2011 /// Returns the name of the indexer in a given type.
2014 /// The default is not always 'Item'. The user can change this behaviour by
2015 /// using the DefaultMemberAttribute in the class.
2017 /// For example, the String class indexer is named 'Chars' not 'Item'
2019 public static string IndexerPropertyName (Type t, out Type innerType)
2023 if (t is TypeBuilder) {
2024 if (t.IsInterface) {
2025 Interface i = LookupInterface (t);
2027 if ((i == null) || (i.DefaultPropName == null))
2030 return i.DefaultPropName;
2032 TypeContainer tc = LookupTypeContainer (t);
2037 if ( tc.DefaultPropName == null )
2039 while ( tc is Class )
2041 innerType = innerType.BaseType;
2043 tc = LookupTypeContainer (innerType);
2050 else if ( tc.DefaultPropName != null )
2051 return tc.DefaultPropName;
2055 //if ((tc == null) || (tc.DefaultPropName == null))
2058 return tc.DefaultPropName;
2062 System.Attribute attr = System.Attribute.GetCustomAttribute (
2063 t, TypeManager.default_member_type);
2065 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2066 return dma.MemberName;
2072 public static void MakePinned (LocalBuilder builder)
2075 // FIXME: Flag the "LocalBuilder" type as being
2076 // pinned. Figure out API.
2082 // Returns whether the array of memberinfos contains the given method
2084 static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2086 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2088 foreach (MethodBase method in array){
2089 if (method.Name != new_method.Name)
2092 Type [] old_args = TypeManager.GetArgumentTypes (method);
2093 int old_count = old_args.Length;
2096 if (new_args.Length != old_count)
2099 for (i = 0; i < old_count; i++){
2100 if (old_args [i] != new_args [i])
2112 // We copy methods from 'new_members' into 'target_list' if the signature
2113 // for the method from in the new list does not exist in the target_list
2115 // The name is assumed to be the same.
2117 public static ArrayList CopyNewMethods (ArrayList target_list, MemberList new_members)
2119 if (target_list == null){
2120 target_list = new ArrayList ();
2122 foreach (MemberInfo mi in new_members){
2123 if (mi is MethodBase)
2124 target_list.Add (mi);
2129 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2130 target_list.CopyTo (target_array, 0);
2132 foreach (MemberInfo mi in new_members){
2133 MethodBase new_method = (MethodBase) mi;
2135 if (!ArrayContainsMethod (target_array, new_method))
2136 target_list.Add (new_method);
2142 public enum MethodFlags {
2144 IsObsoleteError = 2,
2149 // Returns the TypeManager.MethodFlags for this method.
2150 // This emits an error 619 / warning 618 if the method is obsolete.
2151 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
2153 static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
2155 MethodFlags flags = 0;
2157 if (mb.DeclaringType is TypeBuilder){
2158 MethodData method = (MethodData) builder_to_method [mb];
2159 if (method == null) {
2160 // FIXME: implement Obsolete attribute on Property,
2161 // Indexer and Event.
2165 return method.GetMethodFlags (loc);
2168 object [] attrs = mb.GetCustomAttributes (true);
2169 foreach (object ta in attrs){
2170 if (!(ta is System.Attribute)){
2171 Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
2174 System.Attribute a = (System.Attribute) ta;
2175 if (a.TypeId == TypeManager.obsolete_attribute_type){
2176 ObsoleteAttribute oa = (ObsoleteAttribute) a;
2178 string method_desc = TypeManager.MonoBASIC_Signature (mb);
2181 Report.Error (619, loc, "Method '" + method_desc +
2182 "' is obsolete: '" + oa.Message + "'");
2183 return MethodFlags.IsObsoleteError;
2185 Report.Warning (618, loc, "Method '" + method_desc +
2186 "' is obsolete: '" + oa.Message + "'");
2188 flags |= MethodFlags.IsObsolete;
2194 // Skip over conditional code.
2196 if (a.TypeId == TypeManager.conditional_attribute_type){
2197 ConditionalAttribute ca = (ConditionalAttribute) a;
2199 if (RootContext.AllDefines [ca.ConditionString] == null)
2200 flags |= MethodFlags.ShouldIgnore;
2207 #region MemberLookup implementation
2210 // Name of the member
2212 //static string closure_name;
2215 // Whether we allow private members in the result (since FindMembers
2216 // uses NonPublic for both protected and private), we need to distinguish.
2218 static bool closure_private_ok;
2221 // Who is invoking us and which type is being queried currently.
2223 static Type closure_invocation_type;
2224 //static Type closure_queried_type;
2225 static Type closure_start_type;
2228 // The assembly that defines the type is that is calling us
2230 static Assembly closure_invocation_assembly;
2233 // This filter filters by name + whether it is ok to include private
2234 // members in the search
2236 static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
2239 // Hack: we know that the filter criteria will always be in the 'closure'
2243 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2246 if ((closure_start_type == closure_invocation_type) &&
2247 (m.DeclaringType == closure_invocation_type))
2251 // Ugly: we need to find out the type of 'm', and depending
2252 // on this, tell whether we accept or not
2254 if (m is MethodBase){
2255 MethodBase mb = (MethodBase) m;
2256 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2258 if (ma == MethodAttributes.Private)
2259 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2262 // FamAndAssem requires that we not only derivate, but we are on the
2265 if (ma == MethodAttributes.FamANDAssem){
2266 if (closure_invocation_assembly != mb.DeclaringType.Assembly)
2270 // Assembly and FamORAssem succeed if we're in the same assembly.
2271 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2272 if (closure_invocation_assembly == mb.DeclaringType.Assembly)
2276 // We already know that we aren't in the same assembly.
2277 if (ma == MethodAttributes.Assembly)
2280 // Family and FamANDAssem require that we derive.
2281 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
2282 if (closure_invocation_type == null)
2285 if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
2295 if (m is FieldInfo){
2296 FieldInfo fi = (FieldInfo) m;
2297 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2299 if (fa == FieldAttributes.Private)
2300 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
2303 // FamAndAssem requires that we not only derivate, but we are on the
2306 if (fa == FieldAttributes.FamANDAssem){
2307 if (closure_invocation_assembly != fi.DeclaringType.Assembly)
2311 // Assembly and FamORAssem succeed if we're in the same assembly.
2312 if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2313 if (closure_invocation_assembly == fi.DeclaringType.Assembly)
2317 // We already know that we aren't in the same assembly.
2318 if (fa == FieldAttributes.Assembly)
2321 // Family and FamANDAssem require that we derive.
2322 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
2323 if (closure_invocation_type == null)
2326 if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.DeclaringType))
2329 // Although a derived class can access protected members of its base class
2330 // it cannot do so through an instance of the base class (CS1540).
2331 if ((closure_invocation_type != closure_start_type) &&
2332 closure_invocation_type.IsSubclassOf (closure_start_type))
2343 // EventInfos and PropertyInfos, return true
2348 static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
2351 // Looks up a member called 'name' in the 'queried_type'. This lookup
2352 // is done by code that is contained in the definition for 'invocation_type'.
2354 // The binding flags are 'bf' and the kind of members being looked up are 'mt'
2356 // Returns an array of a single element for everything but Methods/Constructors
2357 // that might return multiple matches.
2359 public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type,
2360 MemberTypes mt, BindingFlags original_bf, string name)
2362 Timer.StartTimer (TimerType.MemberLookup);
2364 MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
2365 mt, original_bf, name);
2367 Timer.StopTimer (TimerType.MemberLookup);
2372 static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type,
2373 MemberTypes mt, BindingFlags original_bf, string name)
2375 BindingFlags bf = original_bf;
2377 ArrayList method_list = null;
2378 Type current_type = queried_type;
2379 if (queried_type == null)
2380 throw new ArgumentNullException("queried_type");
2381 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2383 bool always_ok_flag = false;
2384 bool skip_iface_check = true, used_cache = false;
2386 //closure_name = name;
2387 closure_invocation_type = invocation_type;
2388 closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2389 closure_start_type = queried_type;
2392 // If we are a nested class, we always have access to our container
2395 if (invocation_type != null){
2396 string invocation_name = invocation_type.FullName;
2397 if (invocation_name.IndexOf ('+') != -1){
2398 string container = queried_type.FullName + "+";
2399 int container_length = container.Length;
2401 if (invocation_name.Length > container_length){
2402 string shared = invocation_name.Substring (0, container_length);
2404 if (shared == container)
2405 always_ok_flag = true;
2414 // 'NonPublic' is lame, because it includes both protected and
2415 // private methods, so we need to control this behavior by
2416 // explicitly tracking if a private method is ok or not.
2418 // The possible cases are:
2419 // public, private and protected (internal does not come into the
2422 if (invocation_type != null){
2423 if (invocation_type == current_type){
2424 private_ok = (bf & BindingFlags.NonPublic) != 0;
2426 private_ok = always_ok_flag;
2428 if (invocation_type.IsSubclassOf (current_type))
2432 bf = original_bf | BindingFlags.NonPublic;
2435 bf = original_bf & ~BindingFlags.NonPublic;
2438 closure_private_ok = private_ok;
2439 //closure_queried_type = current_type;
2441 Timer.StopTimer (TimerType.MemberLookup);
2442 bf |= BindingFlags.IgnoreCase;
2443 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2445 Timer.StartTimer (TimerType.MemberLookup);
2448 // When queried for an interface type, the cache will automatically check all
2449 // inherited members, so we don't need to do this here. However, this only
2450 // works if we already used the cache in the first iteration of this loop.
2452 // If we used the cache in any further iteration, we can still terminate the
2453 // loop since the cache always looks in all parent classes.
2459 skip_iface_check = false;
2461 if (current_type == TypeManager.object_type)
2464 current_type = current_type.BaseType;
2467 // This happens with interfaces, they have a null
2468 // basetype. Look members up in the Object class.
2470 if (current_type == null)
2471 current_type = TypeManager.object_type;
2474 if (list.Count == 0)
2478 // Events and types are returned by both 'static' and 'instance'
2479 // searches, which means that our above FindMembers will
2480 // return two copies of the same.
2482 if (list.Count == 1 && !(list [0] is MethodBase)){
2483 return (MemberInfo []) list;
2487 // Multiple properties: we query those just to find out the indexer
2490 if (list [0] is PropertyInfo) {
2491 foreach (MemberInfo mi in list)
2492 if (mi is FieldInfo)
2493 return new MemberInfo [] {mi};
2494 return (MemberInfo []) list;
2499 // We found an event: the cache lookup returns both the event and
2500 // its private field.
2502 if (list [0] is EventInfo) {
2503 if ((list.Count == 2) && (list [1] is FieldInfo))
2504 return new MemberInfo [] {list [0]};
2511 // We found methods, turn the search into "method scan"
2515 method_list = CopyNewMethods (method_list, list);
2516 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2517 } while (searching);
2519 if (method_list != null && method_list.Count > 0)
2520 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2523 // This happens if we already used the cache in the first iteration, in this case
2524 // the cache already looked in all interfaces.
2526 if (skip_iface_check)
2530 // Interfaces do not list members they inherit, so we have to
2533 if (!queried_type.IsInterface)
2536 if (queried_type.IsArray)
2537 queried_type = TypeManager.array_type;
2539 Type [] ifaces = GetInterfaces (queried_type);
2543 foreach (Type itype in ifaces){
2546 x = MemberLookup (null, itype, mt, bf, name);
2558 /// There is exactly one instance of this class per type.
2560 public sealed class TypeHandle : IMemberContainer {
2561 public readonly TypeHandle BaseType;
2563 readonly int id = ++next_id;
2564 static int next_id = 0;
2567 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2568 /// a TypeHandle yet, a new instance of it is created. This static method
2569 /// ensures that we'll only have one TypeHandle instance per type.
2571 public static TypeHandle GetTypeHandle (Type t)
2573 TypeHandle handle = (TypeHandle) type_hash [t];
2577 handle = new TypeHandle (t);
2578 type_hash.Add (t, handle);
2583 /// Returns the TypeHandle for TypeManager.object_type.
2585 public static IMemberContainer ObjectType {
2587 if (object_type != null)
2590 object_type = GetTypeHandle (TypeManager.object_type);
2597 /// Returns the TypeHandle for TypeManager.array_type.
2599 public static IMemberContainer ArrayType {
2601 if (array_type != null)
2604 array_type = GetTypeHandle (TypeManager.array_type);
2610 private static PtrHashtable type_hash = new PtrHashtable ();
2612 private static TypeHandle object_type = null;
2613 private static TypeHandle array_type = null;
2616 private bool is_interface;
2617 private MemberCache member_cache;
2619 private TypeHandle (Type type)
2622 if (type.BaseType != null)
2623 BaseType = GetTypeHandle (type.BaseType);
2624 else if ((type != TypeManager.object_type) && (type != typeof (object)))
2625 is_interface = true;
2626 this.member_cache = new MemberCache (this);
2629 // IMemberContainer methods
2631 public string Name {
2633 return type.FullName;
2643 public IMemberContainer Parent {
2649 public bool IsInterface {
2651 return is_interface;
2655 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2657 if (mt == MemberTypes.Event)
2658 return new MemberList (type.GetEvents (bf | BindingFlags.DeclaredOnly));
2660 return new MemberList (type.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
2664 // IMemberFinder methods
2666 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2667 MemberFilter filter, object criteria)
2669 return member_cache.FindMembers (mt, bf, name, filter, criteria);
2672 public MemberCache MemberCache {
2674 return member_cache;
2678 public override string ToString ()
2680 if (BaseType != null)
2681 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2683 return "TypeHandle (" + id + "," + Name + ")";