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)
14 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
15 // the behavior of the compilation. This can be removed if we rework
16 // the code to get a list of namespaces available.
18 #define SIMPLE_SPEEDUP
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
27 using System.Text.RegularExpressions;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
33 public partial class TypeManager {
35 // A list of core types that the compiler requires or uses
37 static public Type object_type;
38 static public Type value_type;
39 static public Type string_type;
40 static public Type int32_type;
41 static public Type uint32_type;
42 static public Type int64_type;
43 static public Type uint64_type;
44 static public Type float_type;
45 static public Type double_type;
46 static public Type char_type;
47 static public Type char_ptr_type;
48 static public Type short_type;
49 static public Type decimal_type;
50 static public Type bool_type;
51 static public Type sbyte_type;
52 static public Type byte_type;
53 static public Type ushort_type;
54 static public Type enum_type;
55 static public Type delegate_type;
56 static public Type multicast_delegate_type;
57 static public Type void_type;
58 static public Type null_type;
59 static public Type enumeration_type;
60 static public Type array_type;
61 static public Type runtime_handle_type;
62 static public Type icloneable_type;
63 static public Type type_type;
64 static public Type ienumerator_type;
65 static public Type ienumerable_type;
66 static public Type idisposable_type;
67 static public Type iconvertible_type;
68 static public Type default_member_type;
69 static public Type iasyncresult_type;
70 static public Type asynccallback_type;
71 static public Type intptr_type;
72 static public Type monitor_type;
73 static public Type runtime_field_handle_type;
74 static public Type runtime_argument_handle_type;
75 static public Type attribute_type;
76 static public Type attribute_usage_type;
77 static public Type decimal_constant_attribute_type;
78 static public Type dllimport_type;
79 static public Type unverifiable_code_type;
80 static public Type methodimpl_attr_type;
81 static public Type marshal_as_attr_type;
82 static public Type param_array_type;
83 static public Type void_ptr_type;
84 static public Type indexer_name_type;
85 static public Type exception_type;
86 static public Type invalid_operation_exception_type;
87 static public Type not_supported_exception_type;
88 static public Type obsolete_attribute_type;
89 static public Type conditional_attribute_type;
90 static public Type in_attribute_type;
91 static public Type out_attribute_type;
92 static public Type anonymous_method_type;
93 static public Type cls_compliant_attribute_type;
94 static public Type typed_reference_type;
95 static public Type arg_iterator_type;
96 static public Type mbr_type;
97 static public Type struct_layout_attribute_type;
98 static public Type field_offset_attribute_type;
99 static public Type security_attr_type;
100 static public Type required_attr_type;
101 static public Type guid_attr_type;
106 static internal Type compiler_generated_attr_type;
107 static internal Type fixed_buffer_attr_type;
108 static internal Type default_charset_type;
111 // An empty array of types
113 static public Type [] NoTypes;
114 static public TypeExpr [] NoTypeExprs;
118 // Expressions representing the internal types. Used during declaration
121 static public TypeExpr system_object_expr, system_string_expr;
122 static public TypeExpr system_boolean_expr, system_decimal_expr;
123 static public TypeExpr system_single_expr, system_double_expr;
124 static public TypeExpr system_sbyte_expr, system_byte_expr;
125 static public TypeExpr system_int16_expr, system_uint16_expr;
126 static public TypeExpr system_int32_expr, system_uint32_expr;
127 static public TypeExpr system_int64_expr, system_uint64_expr;
128 static public TypeExpr system_char_expr, system_void_expr;
129 static public TypeExpr system_asynccallback_expr;
130 static public TypeExpr system_iasyncresult_expr;
131 static public TypeExpr system_valuetype_expr;
132 static public TypeExpr system_intptr_expr;
135 // This is only used when compiling corlib
137 static public Type system_int32_type;
138 static public Type system_array_type;
139 static public Type system_type_type;
140 static public Type system_assemblybuilder_type;
141 static public MethodInfo system_int_array_get_length;
142 static public MethodInfo system_int_array_get_rank;
143 static public MethodInfo system_object_array_clone;
144 static public MethodInfo system_int_array_get_length_int;
145 static public MethodInfo system_int_array_get_lower_bound_int;
146 static public MethodInfo system_int_array_get_upper_bound_int;
147 static public MethodInfo system_void_array_copyto_array_int;
151 // Internal, not really used outside
153 static Type runtime_helpers_type;
156 // These methods are called by code generated by the compiler
158 static public MethodInfo string_concat_string_string;
159 static public MethodInfo string_concat_string_string_string;
160 static public MethodInfo string_concat_string_string_string_string;
161 static public MethodInfo string_concat_string_dot_dot_dot;
162 static public MethodInfo string_concat_object_object;
163 static public MethodInfo string_concat_object_object_object;
164 static public MethodInfo string_concat_object_dot_dot_dot;
165 static public MethodInfo string_isinterneted_string;
166 static public MethodInfo system_type_get_type_from_handle;
167 static public MethodInfo bool_movenext_void;
168 static public MethodInfo ienumerable_getenumerator_void;
169 static public MethodInfo void_reset_void;
170 static public MethodInfo void_dispose_void;
171 static public MethodInfo void_monitor_enter_object;
172 static public MethodInfo void_monitor_exit_object;
173 static public MethodInfo void_initializearray_array_fieldhandle;
174 static public MethodInfo int_getlength_int;
175 static public MethodInfo delegate_combine_delegate_delegate;
176 static public MethodInfo delegate_remove_delegate_delegate;
177 static public MethodInfo int_get_offset_to_string_data;
178 static public MethodInfo int_array_get_length;
179 static public MethodInfo int_array_get_rank;
180 static public MethodInfo object_array_clone;
181 static public MethodInfo int_array_get_length_int;
182 static public MethodInfo int_array_get_lower_bound_int;
183 static public MethodInfo int_array_get_upper_bound_int;
184 static public MethodInfo void_array_copyto_array_int;
185 static public PropertyInfo ienumerator_getcurrent;
188 // The attribute constructors.
190 static public ConstructorInfo object_ctor;
191 static public ConstructorInfo cons_param_array_attribute;
192 static public ConstructorInfo void_decimal_ctor_five_args;
193 static public ConstructorInfo void_decimal_ctor_int_arg;
194 static public ConstructorInfo unverifiable_code_ctor;
195 static public ConstructorInfo default_member_ctor;
196 static public ConstructorInfo decimal_constant_attribute_ctor;
197 static internal ConstructorInfo struct_layout_attribute_ctor;
198 static public ConstructorInfo field_offset_attribute_ctor;
203 static internal CustomAttributeBuilder compiler_generated_attr;
204 static internal ConstructorInfo fixed_buffer_attr_ctor;
207 // Holds the Array of Assemblies that have been loaded
208 // (either because it is the default or the user used the
209 // -r command line option)
211 static Assembly [] assemblies;
214 // Keeps a list of modules. We used this to do lookups
215 // on the module using GetType -- needed for arrays
217 static Module [] modules;
220 // This is the type_cache from the assemblies to avoid
221 // hitting System.Reflection on every lookup.
223 static Hashtable types;
226 // This is used to hotld the corresponding TypeContainer objects
227 // since we need this in FindMembers
229 static Hashtable typecontainers;
232 // Keeps track of those types that are defined by the
235 static ArrayList user_types;
237 static PtrHashtable builder_to_declspace;
239 static PtrHashtable builder_to_member_cache;
242 // Tracks the interfaces implemented by typebuilders. We only
243 // enter those who do implement or or more interfaces
245 static PtrHashtable builder_to_ifaces;
248 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
249 // the arguments to the method
251 static Hashtable method_arguments;
254 // Maps PropertyBuilder to a Type array that contains
255 // the arguments to the indexer
257 static Hashtable indexer_arguments;
260 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
262 static Hashtable method_params;
265 // A hash table from override methods to their base virtual method.
267 static Hashtable method_overrides;
270 // Keeps track of methods
273 static Hashtable builder_to_method;
276 // Contains all public types from referenced assemblies.
277 // This member is used only if CLS Compliance verification is required.
279 public static Hashtable all_imported_types;
281 static Hashtable fieldbuilders_to_fields;
282 static Hashtable fields;
289 public static void CleanUp ()
291 // Lets get everything clean so that we can collect before generating code
295 typecontainers = null;
297 builder_to_declspace = null;
298 builder_to_member_cache = null;
299 builder_to_ifaces = null;
300 method_arguments = null;
301 indexer_arguments = null;
302 method_params = null;
303 builder_to_method = null;
306 builder_to_constant = null;
307 fieldbuilders_to_fields = null;
309 priv_fields_events = null;
315 TypeHandle.CleanUp ();
319 /// A filter for Findmembers that uses the Signature object to
322 static bool SignatureFilter (MemberInfo mi, object criteria)
324 Signature sig = (Signature) criteria;
326 if (!(mi is MethodBase))
329 if (mi.Name != sig.name)
332 int count = sig.args.Length;
334 if (mi is MethodBuilder || mi is ConstructorBuilder){
335 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
337 if (candidate_args.Length != count)
340 for (int i = 0; i < count; i++)
341 if (candidate_args [i] != sig.args [i])
346 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
348 if (pars.Length != count)
351 for (int i = 0; i < count; i++)
352 if (pars [i].ParameterType != sig.args [i])
358 // A delegate that points to the filter above.
359 static MemberFilter signature_filter;
362 // These are expressions that represent some of the internal data types, used
365 static void InitExpressionTypes ()
367 system_object_expr = new TypeLookupExpression ("System.Object");
368 system_string_expr = new TypeLookupExpression ("System.String");
369 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
370 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
371 system_single_expr = new TypeLookupExpression ("System.Single");
372 system_double_expr = new TypeLookupExpression ("System.Double");
373 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
374 system_byte_expr = new TypeLookupExpression ("System.Byte");
375 system_int16_expr = new TypeLookupExpression ("System.Int16");
376 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
377 system_int32_expr = new TypeLookupExpression ("System.Int32");
378 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
379 system_int64_expr = new TypeLookupExpression ("System.Int64");
380 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
381 system_char_expr = new TypeLookupExpression ("System.Char");
382 system_void_expr = new TypeLookupExpression ("System.Void");
383 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
384 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
385 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
386 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
389 static TypeManager ()
393 signature_filter = new MemberFilter (SignatureFilter);
394 InitExpressionTypes ();
397 static public void Reset ()
399 assemblies = new Assembly [0];
401 user_types = new ArrayList ();
403 types = new Hashtable ();
404 typecontainers = new Hashtable ();
406 builder_to_declspace = new PtrHashtable ();
407 builder_to_member_cache = new PtrHashtable ();
408 builder_to_method = new PtrHashtable ();
409 method_arguments = new PtrHashtable ();
410 method_params = new PtrHashtable ();
411 method_overrides = new PtrHashtable ();
412 indexer_arguments = new PtrHashtable ();
413 builder_to_ifaces = new PtrHashtable ();
415 NoTypes = new Type [0];
416 NoTypeExprs = new TypeExpr [0];
418 fieldbuilders_to_fields = new Hashtable ();
419 fields = new Hashtable ();
420 type_hash = new DoubleHash ();
425 public static void HandleDuplicate (string name, Type t)
427 Type prev = (Type) types [name];
428 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
432 // This probably never happens, as we catch this before
434 Report.Error (-17, "The type `" + name + "' has already been defined.");
438 tc = builder_to_declspace [t] as TypeContainer;
441 1595, "The type `" + name + "' is defined in an existing assembly;"+
442 " Using the new definition from: " + tc.Location);
445 1595, "The type `" + name + "' is defined in an existing assembly;");
448 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
454 public static void AddUserType (string name, TypeBuilder t)
459 HandleDuplicate (name, t);
466 // This entry point is used by types that we define under the covers
468 public static void RegisterBuilder (Type tb, Type [] ifaces)
471 builder_to_ifaces [tb] = ifaces;
474 public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
476 builder_to_declspace.Add (t, tc);
477 typecontainers.Add (name, tc);
478 AddUserType (name, t);
481 public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
486 HandleDuplicate (name, t);
489 builder_to_declspace.Add (t, del);
492 public static void AddEnumType (string name, TypeBuilder t, Enum en)
497 HandleDuplicate (name, t);
499 builder_to_declspace.Add (t, en);
502 public static void AddMethod (MethodBase builder, IMethodData method)
504 builder_to_method.Add (builder, method);
507 public static IMethodData GetMethod (MethodBase builder)
509 return (IMethodData) builder_to_method [builder];
513 /// Returns the DeclSpace whose Type is `t' or null if there is no
514 /// DeclSpace for `t' (ie, the Type comes from a library)
516 public static DeclSpace LookupDeclSpace (Type t)
518 return builder_to_declspace [t] as DeclSpace;
522 /// Returns the TypeContainer whose Type is `t' or null if there is no
523 /// TypeContainer for `t' (ie, the Type comes from a library)
525 public static TypeContainer LookupTypeContainer (Type t)
527 return builder_to_declspace [t] as TypeContainer;
530 public static MemberCache LookupMemberCache (Type t)
532 if (t is TypeBuilder) {
533 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
534 if (container != null)
535 return container.MemberCache;
538 if (t is GenericTypeParameterBuilder) {
539 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
541 if (container != null)
542 return container.MemberCache;
545 return TypeHandle.GetMemberCache (t);
548 public static MemberCache LookupBaseInterfacesCache (Type t)
550 Type [] ifaces = t.GetInterfaces ();
552 if (ifaces != null && ifaces.Length == 1)
553 return LookupMemberCache (ifaces [0]);
555 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
556 MemberCache cache = builder_to_member_cache [t] as MemberCache;
560 cache = new MemberCache (ifaces);
561 builder_to_member_cache.Add (t, cache);
565 public static TypeContainer LookupInterface (Type t)
567 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
568 if ((tc == null) || (tc.Kind != Kind.Interface))
574 public static Delegate LookupDelegate (Type t)
576 return builder_to_declspace [t] as Delegate;
579 public static Enum LookupEnum (Type t)
581 return builder_to_declspace [t] as Enum;
584 public static Class LookupClass (Type t)
586 return (Class) builder_to_declspace [t];
590 /// Registers an assembly to load types from.
592 public static void AddAssembly (Assembly a)
594 foreach (Assembly assembly in assemblies) {
599 int top = assemblies.Length;
600 Assembly [] n = new Assembly [top + 1];
602 assemblies.CopyTo (n, 0);
608 public static Assembly [] GetAssemblies ()
614 /// Registers a module builder to lookup types from
616 public static void AddModule (Module mb)
618 int top = modules != null ? modules.Length : 0;
619 Module [] n = new Module [top + 1];
622 modules.CopyTo (n, 0);
627 public static Module[] Modules {
634 // We use this hash for multiple kinds of constructed types:
636 // (T, "&") Given T, get T &
637 // (T, "*") Given T, get T *
638 // (T, "[]") Given T and a array dimension, get T []
639 // (T, X) Given a type T and a simple name X, get the type T+X
641 // Accessibility tests, if necessary, should be done by the user
643 static DoubleHash type_hash = new DoubleHash ();
646 // Gets the reference to T version of the Type (T&)
648 public static Type GetReferenceType (Type t)
650 return t.MakeByRefType ();
654 // Gets the pointer to T version of the Type (T*)
656 public static Type GetPointerType (Type t)
658 return GetConstructedType (t, "*");
661 public static Type GetConstructedType (Type t, string dim)
664 if (type_hash.Lookup (t, dim, out ret))
667 ret = t.Module.GetType (t.ToString () + dim);
669 type_hash.Insert (t, dim, ret);
674 ret = GetReferenceType (t);
675 type_hash.Insert (t, dim, ret);
679 if (t.IsGenericParameter || t.IsGenericInstance) {
682 while ((pos < dim.Length) && (dim [pos] == '[')) {
685 if (dim [pos] == ']') {
686 result = result.MakeArrayType ();
689 if (pos < dim.Length)
692 type_hash.Insert (t, dim, result);
697 while (dim [pos] == ',') {
701 if ((dim [pos] != ']') || (pos != dim.Length-1))
704 result = result.MakeArrayType (rank + 1);
705 type_hash.Insert (t, dim, result);
710 type_hash.Insert (t, dim, null);
714 public static Type GetNestedType (Type t, string name)
717 if (!type_hash.Lookup (t, name, out ret)) {
718 string lookup = t.FullName + "+" + name;
719 ret = t.Module.GetType (lookup);
720 type_hash.Insert (t, name, ret);
726 // Low-level lookup, cache-less
728 public static Type LookupTypeReflection (string name)
732 foreach (Assembly a in assemblies){
733 t = a.GetType (name);
738 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
739 if (ta == TypeAttributes.NotPublic ||
740 ta == TypeAttributes.NestedPrivate ||
741 ta == TypeAttributes.NestedAssembly ||
742 ta == TypeAttributes.NestedFamANDAssem){
745 // In .NET pointers turn out to be private, even if their
746 // element type is not
749 t = t.GetElementType ();
759 foreach (Module mb in modules) {
760 t = mb.GetType (name);
769 /// Computes the namespaces that we import from the assemblies we reference.
771 public static void ComputeNamespaces ()
773 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
775 Hashtable cache = null;
778 // First add the assembly namespaces
780 if (assembly_get_namespaces != null){
781 int count = assemblies.Length;
783 for (int i = 0; i < count; i++){
784 Assembly a = assemblies [i];
785 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
786 foreach (string ns in namespaces){
789 Namespace.LookupNamespace (ns, true);
793 cache = new Hashtable ();
794 cache.Add ("", null);
795 foreach (Assembly a in assemblies) {
796 foreach (Type t in a.GetExportedTypes ()) {
797 string ns = t.Namespace;
798 if (ns == null || cache.Contains (ns))
801 Namespace.LookupNamespace (ns, true);
802 cache.Add (ns, null);
808 // Then add module namespaces
810 foreach (Module m in modules) {
811 if (m == CodeGen.Module.Builder)
814 cache = new Hashtable ();
815 cache.Add ("", null);
817 foreach (Type t in m.GetTypes ()) {
818 string ns = t.Namespace;
819 if (ns == null || cache.Contains (ns))
821 Namespace.LookupNamespace (ns, true);
822 cache.Add (ns, null);
828 /// Fills static table with exported types from all referenced assemblies.
829 /// This information is required for CLS Compliance tests.
831 public static void LoadAllImportedTypes ()
833 all_imported_types = new Hashtable ();
834 foreach (Assembly a in assemblies) {
835 foreach (Type t in a.GetExportedTypes ()) {
836 all_imported_types [t.FullName] = t;
841 public static bool NamespaceClash (string name, Location loc)
843 if (Namespace.LookupNamespace (name, false) == null)
846 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
851 /// Returns the C# name of a type if possible, or the full type name otherwise
853 static public string CSharpName (Type t)
855 string name = GetFullName (t);
857 return Regex.Replace (name,
859 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
860 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
861 @"Boolean|String|Void|Null)" +
863 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
866 static public string CSharpName (Type[] types)
868 StringBuilder sb = new StringBuilder ();
869 foreach (Type t in types) {
870 sb.Append (CSharpName (t));
873 sb.Remove (sb.Length - 1, 1);
874 return sb.ToString ();
877 static String CSharpNameMatch (Match match)
879 string s = match.Groups [1].Captures [0].Value;
881 Replace ("int32", "int").
882 Replace ("uint32", "uint").
883 Replace ("int16", "short").
884 Replace ("uint16", "ushort").
885 Replace ("int64", "long").
886 Replace ("uint64", "ulong").
887 Replace ("single", "float").
888 Replace ("boolean", "bool")
889 + match.Groups [2].Captures [0].Value;
893 /// Returns the signature of the method with full namespace classification
895 static public string GetFullNameSignature (MemberInfo mi)
897 return (mi is MethodBase)
898 ? CSharpSignature (mi as MethodBase)
899 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
902 private static void GetFullName_recursed (StringBuilder sb, Type t, Type original_type,
903 ref int pos, bool recursed)
905 if (t.IsGenericParameter) {
911 string ns = t.Namespace;
912 if ((ns != null) && (ns != "")) {
918 if (t.DeclaringType != null) {
919 GetFullName_recursed (sb, t.DeclaringType, t, ref pos, true);
923 sb.Append (SimpleName.RemoveGenericArity (t.Name));
925 Type[] args = GetTypeArguments (original_type);
926 Type[] this_args = GetTypeArguments (t);
928 if (this_args.Length > pos) {
930 for (int i = pos; i < this_args.Length; i++) {
933 sb.Append (GetFullName (args [i]));
938 pos += this_args.Length;
941 static public string GetFullName (Type t)
943 StringBuilder sb = new StringBuilder ();
945 GetFullName_recursed (sb, t, t, ref pos, false);
946 return sb.ToString ();
950 /// When we need to report accessors as well
952 static public string CSharpSignature (MethodBase mb)
954 return CSharpSignature (mb, false);
958 /// Returns the signature of the method
960 static public string CSharpSignature (MethodBase mb, bool show_accessor)
962 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
965 ParameterData iparams = GetParameterData (mb);
966 string parameters = iparams.GetSignatureForError ();
967 string accessor = "";
970 if (mb.IsSpecialName) {
971 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
972 if (ot != Operator.OpType.TOP) {
973 sig.Append ("operator ");
974 sig.Append (Operator.GetName (ot));
975 sig.Append (parameters);
976 return sig.ToString ();
979 if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
980 accessor = mb.Name.Substring (0, 3);
985 if (mb.IsSpecialName && !mb.IsConstructor) {
986 if (iparams.Count > 1) {
987 sig.Append ("this[");
988 int before_ret_val = parameters.LastIndexOf (',');
989 sig.Append (parameters.Substring (1, before_ret_val - 1));
992 sig.Append (mb.Name.Substring (4));
995 if (mb.Name == ".ctor")
996 sig.Append (mb.DeclaringType.Name);
998 sig.Append (mb.Name);
1000 sig.Append (parameters);
1003 if (show_accessor && accessor.Length > 0) {
1005 sig.Append (accessor);
1008 return sig.ToString ();
1011 public static string GetMethodName (MethodInfo m)
1013 if (!IsGenericMethod (m))
1016 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
1019 static public string CSharpSignature (EventInfo ei)
1021 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
1025 /// Looks up a type, and aborts if it is not found. This is used
1026 /// by types required by the compiler
1028 static Type CoreLookupType (string name)
1031 if (types.Contains (name))
1032 t = (Type) types [name];
1034 t = LookupTypeReflection (name);
1037 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
1044 /// Returns the MethodInfo for a method named `name' defined
1045 /// in type `t' which takes arguments of types `args'
1047 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
1051 BindingFlags flags = instance_and_static | BindingFlags.Public;
1057 flags |= BindingFlags.NonPublic;
1059 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
1060 if (list.Count == 0) {
1062 Report.Error (-19, "Can not find the core function `" + name + "'");
1066 MethodInfo mi = list [0] as MethodInfo;
1069 Report.Error (-19, "Can not find the core function `" + name + "'");
1076 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
1078 return GetMethod (t, name, args, false, report_errors);
1081 static MethodInfo GetMethod (Type t, string name, Type [] args)
1083 return GetMethod (t, name, args, true);
1087 /// Returns the PropertyInfo for a property named `name' defined
1090 static PropertyInfo GetProperty (Type t, string name)
1092 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
1093 BindingFlags.Instance, Type.FilterName, name);
1094 if (list.Count == 0) {
1095 Report.Error (-19, "Can not find the core property `" + name + "'");
1099 PropertyInfo pi = list [0] as PropertyInfo;
1101 Report.Error (-19, "Can not find the core function `" + name + "'");
1109 /// Returns the ConstructorInfo for "args"
1111 public static ConstructorInfo GetConstructor (Type t, Type [] args)
1119 list = FindMembers (t, MemberTypes.Constructor,
1120 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
1121 signature_filter, sig);
1122 if (list.Count == 0){
1123 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1127 ConstructorInfo ci = list [0] as ConstructorInfo;
1129 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1136 public static void InitEnumUnderlyingTypes ()
1139 int32_type = CoreLookupType ("System.Int32");
1140 int64_type = CoreLookupType ("System.Int64");
1141 uint32_type = CoreLookupType ("System.UInt32");
1142 uint64_type = CoreLookupType ("System.UInt64");
1143 byte_type = CoreLookupType ("System.Byte");
1144 sbyte_type = CoreLookupType ("System.SByte");
1145 short_type = CoreLookupType ("System.Int16");
1146 ushort_type = CoreLookupType ("System.UInt16");
1150 /// The types have to be initialized after the initial
1151 /// population of the type has happened (for example, to
1152 /// bootstrap the corlib.dll
1154 public static void InitCoreTypes ()
1156 object_type = CoreLookupType ("System.Object");
1157 value_type = CoreLookupType ("System.ValueType");
1159 InitEnumUnderlyingTypes ();
1161 char_type = CoreLookupType ("System.Char");
1162 string_type = CoreLookupType ("System.String");
1163 float_type = CoreLookupType ("System.Single");
1164 double_type = CoreLookupType ("System.Double");
1165 char_ptr_type = CoreLookupType ("System.Char*");
1166 decimal_type = CoreLookupType ("System.Decimal");
1167 bool_type = CoreLookupType ("System.Boolean");
1168 enum_type = CoreLookupType ("System.Enum");
1170 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1171 delegate_type = CoreLookupType ("System.Delegate");
1173 array_type = CoreLookupType ("System.Array");
1174 void_type = CoreLookupType ("System.Void");
1175 type_type = CoreLookupType ("System.Type");
1177 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1178 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1179 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1180 default_member_type = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1181 runtime_handle_type = CoreLookupType ("System.RuntimeTypeHandle");
1182 asynccallback_type = CoreLookupType ("System.AsyncCallback");
1183 iasyncresult_type = CoreLookupType ("System.IAsyncResult");
1184 ienumerator_type = CoreLookupType ("System.Collections.IEnumerator");
1185 ienumerable_type = CoreLookupType ("System.Collections.IEnumerable");
1186 idisposable_type = CoreLookupType ("System.IDisposable");
1187 icloneable_type = CoreLookupType ("System.ICloneable");
1188 iconvertible_type = CoreLookupType ("System.IConvertible");
1189 monitor_type = CoreLookupType ("System.Threading.Monitor");
1190 intptr_type = CoreLookupType ("System.IntPtr");
1192 attribute_type = CoreLookupType ("System.Attribute");
1193 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1194 dllimport_type = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1195 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1196 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1197 param_array_type = CoreLookupType ("System.ParamArrayAttribute");
1198 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1199 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1200 typed_reference_type = CoreLookupType ("System.TypedReference");
1201 arg_iterator_type = CoreLookupType ("System.ArgIterator");
1202 mbr_type = CoreLookupType ("System.MarshalByRefObject");
1203 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1205 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1207 void_ptr_type = CoreLookupType ("System.Void*");
1209 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1211 exception_type = CoreLookupType ("System.Exception");
1212 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1213 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1218 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1219 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1220 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1221 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1222 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1223 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1224 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1225 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices.GuidAttribute");
1227 InitGenericCoreTypes ();
1232 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1233 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1234 default_charset_type = CoreLookupType ("System.Runtime.InteropServices.DefaultCharSetAttribute");
1236 // When compiling corlib, store the "real" types here.
1238 if (!RootContext.StdLib) {
1239 system_int32_type = typeof (System.Int32);
1240 system_array_type = typeof (System.Array);
1241 system_type_type = typeof (System.Type);
1242 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1244 Type [] void_arg = { };
1245 system_int_array_get_length = GetMethod (
1246 system_array_type, "get_Length", void_arg);
1247 system_int_array_get_rank = GetMethod (
1248 system_array_type, "get_Rank", void_arg);
1249 system_object_array_clone = GetMethod (
1250 system_array_type, "Clone", void_arg);
1252 Type [] system_int_arg = { system_int32_type };
1253 system_int_array_get_length_int = GetMethod (
1254 system_array_type, "GetLength", system_int_arg);
1255 system_int_array_get_upper_bound_int = GetMethod (
1256 system_array_type, "GetUpperBound", system_int_arg);
1257 system_int_array_get_lower_bound_int = GetMethod (
1258 system_array_type, "GetLowerBound", system_int_arg);
1260 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1261 system_void_array_copyto_array_int = GetMethod (
1262 system_array_type, "CopyTo", system_array_int_arg);
1264 Type [] system_3_type_arg = {
1265 system_type_type, system_type_type, system_type_type };
1266 Type [] system_4_type_arg = {
1267 system_type_type, system_type_type, system_type_type, system_type_type };
1269 MethodInfo set_corlib_type_builders = GetMethod (
1270 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1271 system_4_type_arg, true, false);
1273 if (set_corlib_type_builders != null) {
1274 object[] args = new object [4];
1275 args [0] = object_type;
1276 args [1] = value_type;
1277 args [2] = enum_type;
1278 args [3] = void_type;
1280 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1282 // Compatibility for an older version of the class libs.
1283 set_corlib_type_builders = GetMethod (
1284 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1285 system_3_type_arg, true, true);
1287 if (set_corlib_type_builders == null) {
1288 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1292 object[] args = new object [3];
1293 args [0] = object_type;
1294 args [1] = value_type;
1295 args [2] = enum_type;
1297 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1301 system_object_expr.Type = object_type;
1302 system_string_expr.Type = string_type;
1303 system_boolean_expr.Type = bool_type;
1304 system_decimal_expr.Type = decimal_type;
1305 system_single_expr.Type = float_type;
1306 system_double_expr.Type = double_type;
1307 system_sbyte_expr.Type = sbyte_type;
1308 system_byte_expr.Type = byte_type;
1309 system_int16_expr.Type = short_type;
1310 system_uint16_expr.Type = ushort_type;
1311 system_int32_expr.Type = int32_type;
1312 system_uint32_expr.Type = uint32_type;
1313 system_int64_expr.Type = int64_type;
1314 system_uint64_expr.Type = uint64_type;
1315 system_char_expr.Type = char_type;
1316 system_void_expr.Type = void_type;
1317 system_asynccallback_expr.Type = asynccallback_type;
1318 system_iasyncresult_expr.Type = iasyncresult_type;
1319 system_valuetype_expr.Type = value_type;
1322 // These are only used for compare purposes
1324 anonymous_method_type = typeof (AnonymousMethod);
1325 null_type = typeof (NullType);
1329 // The helper methods that are used by the compiler
1331 public static void InitCodeHelpers ()
1334 // Now load the default methods that we use.
1336 Type [] string_string = { string_type, string_type };
1337 string_concat_string_string = GetMethod (
1338 string_type, "Concat", string_string);
1339 Type [] string_string_string = { string_type, string_type, string_type };
1340 string_concat_string_string_string = GetMethod (
1341 string_type, "Concat", string_string_string);
1342 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1343 string_concat_string_string_string_string = GetMethod (
1344 string_type, "Concat", string_string_string_string);
1345 Type[] params_string = { GetConstructedType (string_type, "[]") };
1346 string_concat_string_dot_dot_dot = GetMethod (
1347 string_type, "Concat", params_string);
1349 Type [] object_object = { object_type, object_type };
1350 string_concat_object_object = GetMethod (
1351 string_type, "Concat", object_object);
1352 Type [] object_object_object = { object_type, object_type, object_type };
1353 string_concat_object_object_object = GetMethod (
1354 string_type, "Concat", object_object_object);
1355 Type[] params_object = { GetConstructedType (object_type, "[]") };
1356 string_concat_object_dot_dot_dot = GetMethod (
1357 string_type, "Concat", params_object);
1359 Type [] string_ = { string_type };
1360 string_isinterneted_string = GetMethod (
1361 string_type, "IsInterned", string_);
1363 Type [] runtime_type_handle = { runtime_handle_type };
1364 system_type_get_type_from_handle = GetMethod (
1365 type_type, "GetTypeFromHandle", runtime_type_handle);
1367 Type [] delegate_delegate = { delegate_type, delegate_type };
1368 delegate_combine_delegate_delegate = GetMethod (
1369 delegate_type, "Combine", delegate_delegate);
1371 delegate_remove_delegate_delegate = GetMethod (
1372 delegate_type, "Remove", delegate_delegate);
1377 Type [] void_arg = { };
1378 ienumerator_getcurrent = GetProperty (
1379 ienumerator_type, "Current");
1380 bool_movenext_void = GetMethod (
1381 ienumerator_type, "MoveNext", void_arg);
1382 void_reset_void = GetMethod (
1383 ienumerator_type, "Reset", void_arg);
1384 void_dispose_void = GetMethod (
1385 idisposable_type, "Dispose", void_arg);
1386 int_get_offset_to_string_data = GetMethod (
1387 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1388 int_array_get_length = GetMethod (
1389 array_type, "get_Length", void_arg);
1390 int_array_get_rank = GetMethod (
1391 array_type, "get_Rank", void_arg);
1392 ienumerable_getenumerator_void = GetMethod (
1393 ienumerable_type, "GetEnumerator", void_arg);
1398 Type [] int_arg = { int32_type };
1399 int_array_get_length_int = GetMethod (
1400 array_type, "GetLength", int_arg);
1401 int_array_get_upper_bound_int = GetMethod (
1402 array_type, "GetUpperBound", int_arg);
1403 int_array_get_lower_bound_int = GetMethod (
1404 array_type, "GetLowerBound", int_arg);
1407 // System.Array methods
1409 object_array_clone = GetMethod (
1410 array_type, "Clone", void_arg);
1411 Type [] array_int_arg = { array_type, int32_type };
1412 void_array_copyto_array_int = GetMethod (
1413 array_type, "CopyTo", array_int_arg);
1418 Type [] object_arg = { object_type };
1419 void_monitor_enter_object = GetMethod (
1420 monitor_type, "Enter", object_arg);
1421 void_monitor_exit_object = GetMethod (
1422 monitor_type, "Exit", object_arg);
1424 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1426 void_initializearray_array_fieldhandle = GetMethod (
1427 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1432 int_getlength_int = GetMethod (
1433 array_type, "GetLength", int_arg);
1436 // Decimal constructors
1438 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1439 void_decimal_ctor_five_args = GetConstructor (
1440 decimal_type, dec_arg);
1442 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1447 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1448 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1449 default_member_ctor = GetConstructor (default_member_type, string_);
1451 Type[] short_arg = { short_type };
1452 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1454 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1455 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1457 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1463 compiler_generated_attr = new CustomAttributeBuilder (
1464 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1466 Type[] type_int_arg = { type_type, int32_type };
1467 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1470 object_ctor = GetConstructor (object_type, void_arg);
1472 InitGenericCodeHelpers ();
1475 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1478 /// This is the "old", non-cache based FindMembers() function. We cannot use
1479 /// the cache here because there is no member name argument.
1481 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1482 MemberFilter filter, object criteria)
1484 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1487 // `builder_to_declspace' contains all dynamic types.
1491 Timer.StartTimer (TimerType.FindMembers);
1492 list = decl.FindMembers (mt, bf, filter, criteria);
1493 Timer.StopTimer (TimerType.FindMembers);
1498 // We have to take care of arrays specially, because GetType on
1499 // a TypeBuilder array will return a Type, not a TypeBuilder,
1500 // and we can not call FindMembers on this type.
1502 if (t.IsSubclassOf (TypeManager.array_type))
1503 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1505 if (t is GenericTypeParameterBuilder) {
1506 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1508 Timer.StartTimer (TimerType.FindMembers);
1509 MemberList list = tparam.FindMembers (
1510 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1511 Timer.StopTimer (TimerType.FindMembers);
1516 // Since FindMembers will not lookup both static and instance
1517 // members, we emulate this behaviour here.
1519 if ((bf & instance_and_static) == instance_and_static){
1520 MemberInfo [] i_members = t.FindMembers (
1521 mt, bf & ~BindingFlags.Static, filter, criteria);
1523 int i_len = i_members.Length;
1525 MemberInfo one = i_members [0];
1528 // If any of these are present, we are done!
1530 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1531 return new MemberList (i_members);
1534 MemberInfo [] s_members = t.FindMembers (
1535 mt, bf & ~BindingFlags.Instance, filter, criteria);
1537 int s_len = s_members.Length;
1538 if (i_len > 0 || s_len > 0)
1539 return new MemberList (i_members, s_members);
1542 return new MemberList (i_members);
1544 return new MemberList (s_members);
1548 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1553 /// This method is only called from within MemberLookup. It tries to use the member
1554 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1555 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1556 /// our return value will already contain all inherited members and the caller don't need
1557 /// to check base classes and interfaces anymore.
1559 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1560 string name, out bool used_cache)
1565 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1566 // and we can ask the DeclSpace for the MemberCache.
1568 if (t is TypeBuilder) {
1569 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1570 cache = decl.MemberCache;
1573 // If this DeclSpace has a MemberCache, use it.
1576 if (cache != null) {
1578 return cache.FindMembers (
1579 mt, bf, name, FilterWithClosure_delegate, null);
1582 // If there is no MemberCache, we need to use the "normal" FindMembers.
1583 // Note, this is a VERY uncommon route!
1586 Timer.StartTimer (TimerType.FindMembers);
1587 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1588 FilterWithClosure_delegate, name);
1589 Timer.StopTimer (TimerType.FindMembers);
1591 return (MemberInfo []) list;
1595 // We have to take care of arrays specially, because GetType on
1596 // a TypeBuilder array will return a Type, not a TypeBuilder,
1597 // and we can not call FindMembers on this type.
1599 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1601 return TypeHandle.ArrayType.MemberCache.FindMembers (
1602 mt, bf, name, FilterWithClosure_delegate, null);
1605 if (t is GenericTypeParameterBuilder) {
1606 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1609 Timer.StartTimer (TimerType.FindMembers);
1610 list = tparam.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1611 FilterWithClosure_delegate, name);
1612 Timer.StopTimer (TimerType.FindMembers);
1614 return (MemberInfo []) list;
1617 if (t.IsGenericInstance && (mt == MemberTypes.NestedType)) {
1619 // This happens if we're resolving a class'es base class and interfaces
1620 // in TypeContainer.DefineType(). At this time, the types aren't
1621 // populated yet, so we can't use the cache.
1623 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1624 FilterWithClosure_delegate, name);
1630 // This call will always succeed. There is exactly one TypeHandle instance per
1631 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1632 // the corresponding MemberCache.
1634 cache = TypeHandle.GetMemberCache (t);
1637 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1640 public static bool IsBuiltinType (Type t)
1642 t = TypeToCoreType (t);
1643 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1644 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1645 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1646 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1652 public static bool IsBuiltinType (TypeContainer tc)
1654 return IsBuiltinType (tc.TypeBuilder);
1658 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1659 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1661 public static bool IsPrimitiveType (Type t)
1663 return (t == int32_type || t == uint32_type ||
1664 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1665 t == char_type || t == short_type || t == bool_type ||
1666 t == sbyte_type || t == byte_type || t == ushort_type);
1669 public static bool IsDelegateType (Type t)
1671 if (t.IsGenericInstance)
1672 t = t.GetGenericTypeDefinition ();
1674 if (t.IsSubclassOf (TypeManager.delegate_type))
1680 public static bool IsEnumType (Type t)
1682 if (t.IsSubclassOf (TypeManager.enum_type))
1687 public static bool IsBuiltinOrEnum (Type t)
1689 if (IsBuiltinType (t))
1698 public static bool IsNullType (Type t)
1700 return t == null_type;
1703 public static bool IsAttributeType (Type t)
1705 return (t == attribute_type) || t.IsSubclassOf (attribute_type);
1708 static Stack unmanaged_enclosing_types = new Stack (4);
1711 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1713 public static bool IsUnmanagedType (Type t)
1715 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1716 if (unmanaged_enclosing_types.Contains (t))
1719 // builtins that are not unmanaged types
1720 if (t == TypeManager.object_type || t == TypeManager.string_type)
1723 if (IsBuiltinOrEnum (t))
1726 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1730 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1734 if (!IsValueType (t))
1737 unmanaged_enclosing_types.Push (t);
1741 if (t is TypeBuilder){
1742 TypeContainer tc = LookupTypeContainer (t);
1743 if (tc.Fields != null){
1744 foreach (Field f in tc.Fields){
1745 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1746 if ((f.ModFlags & Modifiers.STATIC) != 0)
1748 if (f.MemberType == null)
1750 if (!IsUnmanagedType (f.MemberType)){
1751 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1757 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1759 foreach (FieldInfo f in fields){
1760 if (!IsUnmanagedType (f.FieldType)){
1761 Report.SymbolRelatedToPreviousError (f);
1767 unmanaged_enclosing_types.Pop ();
1772 public static bool IsValueType (Type t)
1774 return t.IsGenericParameter || t.IsValueType;
1777 public static bool IsInterfaceType (Type t)
1779 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1783 return tc.Kind == Kind.Interface;
1786 public static bool IsSubclassOf (Type type, Type base_type)
1788 TypeParameter tparam = LookupTypeParameter (type);
1789 TypeParameter pparam = LookupTypeParameter (base_type);
1791 if ((tparam != null) && (pparam != null)) {
1792 if (tparam == pparam)
1795 return tparam.IsSubclassOf (base_type);
1799 if (IsEqual (type, base_type))
1802 type = type.BaseType;
1803 } while (type != null);
1808 public static bool IsPrivateAccessible (Type type, Type parent)
1810 if (type.Equals (parent))
1813 if ((type is TypeBuilder) && type.IsGenericTypeDefinition && parent.IsGenericInstance) {
1815 // `a' is a generic type definition's TypeBuilder and `b' is a
1816 // generic instance of the same type.
1822 // void Test (Stack<T> stack) { }
1825 // The first argument of `Test' will be the generic instance
1826 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1829 // We hit this via Closure.Filter() for gen-82.cs.
1831 if (type != parent.GetGenericTypeDefinition ())
1837 if (type.IsGenericInstance && parent.IsGenericInstance) {
1838 if (type.GetGenericTypeDefinition () != parent.GetGenericTypeDefinition ())
1847 public static bool IsFamilyAccessible (Type type, Type parent)
1849 TypeParameter tparam = LookupTypeParameter (type);
1850 TypeParameter pparam = LookupTypeParameter (parent);
1852 if ((tparam != null) && (pparam != null)) {
1853 if (tparam == pparam)
1856 return tparam.IsSubclassOf (parent);
1860 if (IsEqualGenericInstance (type, parent))
1863 type = type.BaseType;
1864 } while (type != null);
1870 // Checks whether `type' is a subclass or nested child of `base_type'.
1872 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1875 if (IsFamilyAccessible (type, base_type))
1878 // Handle nested types.
1879 type = type.DeclaringType;
1880 } while (type != null);
1886 // Checks whether `type' is a nested child of `parent'.
1888 public static bool IsNestedChildOf (Type type, Type parent)
1890 if (IsEqual (type, parent))
1893 type = type.DeclaringType;
1894 while (type != null) {
1895 if (IsEqual (type, parent))
1898 type = type.DeclaringType;
1905 // Do the right thing when returning the element type of an
1906 // array type based on whether we are compiling corlib or not
1908 public static Type GetElementType (Type t)
1910 if (RootContext.StdLib)
1911 return t.GetElementType ();
1913 return TypeToCoreType (t.GetElementType ());
1917 /// This method is not implemented by MS runtime for dynamic types
1919 public static bool HasElementType (Type t)
1921 return t.IsArray || t.IsPointer || t.IsByRef;
1925 /// Returns the User Defined Types
1927 public static ArrayList UserTypes {
1933 public static Hashtable TypeContainers {
1935 return typecontainers;
1939 static Hashtable builder_to_constant;
1941 public static void RegisterConstant (FieldBuilder fb, Const c)
1943 if (builder_to_constant == null)
1944 builder_to_constant = new PtrHashtable ();
1946 if (builder_to_constant.Contains (fb))
1949 builder_to_constant.Add (fb, c);
1952 public static Const LookupConstant (FieldBuilder fb)
1954 if (builder_to_constant == null)
1957 return (Const) builder_to_constant [fb];
1961 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1965 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1966 /// for anything which is dynamic, and we need this in a number of places,
1967 /// we register this information here, and use it afterwards.
1969 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1974 method_arguments.Add (mb, args);
1975 method_params.Add (mb, ip);
1978 static public ParameterData GetParameterData (MethodBase mb)
1980 object pd = method_params [mb];
1982 if (mb is MethodBuilder || mb is ConstructorBuilder)
1983 throw new InternalErrorException ("Argument for Method not registered" + mb);
1985 method_params [mb] = pd = new ReflectionParameters (mb);
1988 return (ParameterData) pd;
1991 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1993 if (method_overrides.Contains (override_method)) {
1994 if (method_overrides [override_method] != base_method)
1995 throw new InternalErrorException ("Override mismatch: " + override_method);
1998 method_overrides [override_method] = base_method;
2001 static public bool IsOverride (MethodBase m)
2003 return m.IsVirtual &&
2004 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
2005 (m is MethodBuilder || method_overrides.Contains (m));
2009 /// Returns the argument types for a method based on its methodbase
2011 /// For dynamic methods, we use the compiler provided types, for
2012 /// methods from existing assemblies we load them from GetParameters,
2013 /// and insert them into the cache
2015 static public Type [] GetArgumentTypes (MethodBase mb)
2017 object t = method_arguments [mb];
2021 ParameterInfo [] pi = mb.GetParameters ();
2028 types = new Type [c];
2029 for (int i = 0; i < c; i++)
2030 types [i] = pi [i].ParameterType;
2032 method_arguments.Add (mb, types);
2037 /// Returns the argument types for an indexer based on its PropertyInfo
2039 /// For dynamic indexers, we use the compiler provided types, for
2040 /// indexers from existing assemblies we load them from GetParameters,
2041 /// and insert them into the cache
2043 static public Type [] GetArgumentTypes (PropertyInfo indexer)
2045 if (indexer_arguments.Contains (indexer))
2046 return (Type []) indexer_arguments [indexer];
2047 else if (indexer is PropertyBuilder)
2048 // If we're a PropertyBuilder and not in the
2049 // `indexer_arguments' hash, then we're a property and
2053 ParameterInfo [] pi = indexer.GetIndexParameters ();
2054 // Property, not an indexer.
2058 Type [] types = new Type [c];
2060 for (int i = 0; i < c; i++)
2061 types [i] = pi [i].ParameterType;
2063 indexer_arguments.Add (indexer, types);
2069 // This is a workaround the fact that GetValue is not
2070 // supported for dynamic types
2072 static public bool RegisterFieldValue (FieldBuilder fb, object value)
2074 if (fields.Contains (fb))
2077 fields.Add (fb, value);
2082 static public object GetValue (FieldBuilder fb)
2087 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
2089 if (fieldbuilders_to_fields.Contains (fb))
2092 fieldbuilders_to_fields.Add (fb, f);
2097 // The return value can be null; This will be the case for
2098 // auxiliary FieldBuilders created by the compiler that have no
2099 // real field being declared on the source code
2101 static public FieldBase GetField (FieldInfo fb)
2103 if (fb.DeclaringType.IsGenericInstance)
2104 fb = fb.Mono_GetGenericFieldDefinition ();
2106 return (FieldBase) fieldbuilders_to_fields [fb];
2109 static Hashtable events;
2111 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
2114 events = new Hashtable ();
2116 if (!events.Contains (eb)) {
2117 events.Add (eb, new Pair (add, remove));
2121 static public MethodInfo GetAddMethod (EventInfo ei)
2123 if (ei is MyEventBuilder) {
2124 Pair pair = (Pair) events [ei];
2126 return (MethodInfo) pair.First;
2128 return ei.GetAddMethod (true);
2131 static public MethodInfo GetRemoveMethod (EventInfo ei)
2133 if (ei is MyEventBuilder) {
2134 Pair pair = (Pair) events [ei];
2136 return (MethodInfo) pair.Second;
2138 return ei.GetRemoveMethod (true);
2141 static Hashtable priv_fields_events;
2143 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
2145 if (priv_fields_events == null)
2146 priv_fields_events = new Hashtable ();
2148 if (priv_fields_events.Contains (einfo))
2151 priv_fields_events.Add (einfo, builder);
2156 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
2158 if (priv_fields_events == null)
2161 return (MemberInfo) priv_fields_events [ei];
2164 static Hashtable properties;
2166 static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
2168 if (properties == null)
2169 properties = new Hashtable ();
2171 if (properties.Contains (pb))
2174 properties.Add (pb, new Pair (get, set));
2179 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2180 MethodBase set, Type[] args)
2182 if (!RegisterProperty (pb, get,set))
2185 indexer_arguments.Add (pb, args);
2190 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2192 Hashtable hash = new Hashtable ();
2193 return CheckStructCycles (tc, seen, hash);
2196 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2199 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2203 // `seen' contains all types we've already visited.
2205 if (seen.Contains (tc))
2207 seen.Add (tc, null);
2209 if (tc.Fields == null)
2212 foreach (FieldMember field in tc.Fields) {
2213 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
2216 Type ftype = field.FieldBuilder.FieldType;
2217 TypeContainer ftc = LookupTypeContainer (ftype);
2221 if (hash.Contains (ftc)) {
2222 Report.Error (523, tc.Location,
2223 "Struct member `{0}.{1}' of type `{2}' " +
2224 "causes a cycle in the struct layout",
2225 tc.Name, field.Name, ftc.Name);
2230 // `hash' contains all types in the current path.
2232 hash.Add (tc, null);
2234 bool ok = CheckStructCycles (ftc, seen, hash);
2241 if (!seen.Contains (ftc))
2242 seen.Add (ftc, null);
2249 /// Given an array of interface types, expand and eliminate repeated ocurrences
2250 /// of an interface.
2254 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2257 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2259 ArrayList new_ifaces = new ArrayList ();
2261 foreach (TypeExpr iface in base_interfaces){
2262 TypeExpr texpr = iface.ResolveAsTypeTerminal (ec);
2266 if (new_ifaces.Contains (texpr.Type))
2269 new_ifaces.Add (texpr.Type);
2271 Type [] implementing = texpr.Type.GetInterfaces ();
2273 foreach (Type imp in implementing){
2274 if (!new_ifaces.Contains (imp))
2275 new_ifaces.Add (imp);
2278 Type [] ret = new Type [new_ifaces.Count];
2279 new_ifaces.CopyTo (ret, 0);
2283 static PtrHashtable iface_cache = new PtrHashtable ();
2286 /// This function returns the interfaces in the type `t'. Works with
2287 /// both types and TypeBuilders.
2289 public static Type [] GetInterfaces (Type t)
2291 Type [] cached = iface_cache [t] as Type [];
2296 // The reason for catching the Array case is that Reflection.Emit
2297 // will not return a TypeBuilder for Array types of TypeBuilder types,
2298 // but will still throw an exception if we try to call GetInterfaces
2301 // Since the array interfaces are always constant, we return those for
2306 t = TypeManager.array_type;
2308 if ((t is TypeBuilder) || t.IsGenericInstance) {
2309 Type [] base_ifaces;
2311 if (t.BaseType == null)
2312 base_ifaces = NoTypes;
2314 base_ifaces = GetInterfaces (t.BaseType);
2316 if (t.IsGenericInstance)
2317 type_ifaces = t.GetInterfaces ();
2319 type_ifaces = (Type []) builder_to_ifaces [t];
2320 if (type_ifaces == null)
2321 type_ifaces = NoTypes;
2323 int base_count = base_ifaces.Length;
2324 Type [] result = new Type [base_count + type_ifaces.Length];
2325 base_ifaces.CopyTo (result, 0);
2326 type_ifaces.CopyTo (result, base_count);
2328 iface_cache [t] = result;
2330 } else if (t is GenericTypeParameterBuilder){
2331 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2332 if (type_ifaces == null)
2333 type_ifaces = NoTypes;
2335 iface_cache [t] = type_ifaces;
2338 Type[] ifaces = t.GetInterfaces ();
2339 iface_cache [t] = ifaces;
2345 // gets the interfaces that are declared explicitly on t
2347 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2349 return (Type []) builder_to_ifaces [t];
2353 /// The following is used to check if a given type implements an interface.
2354 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2356 public static bool ImplementsInterface (Type t, Type iface)
2361 // FIXME OPTIMIZATION:
2362 // as soon as we hit a non-TypeBuiler in the interface
2363 // chain, we could return, as the `Type.GetInterfaces'
2364 // will return all the interfaces implement by the type
2368 interfaces = GetInterfaces (t);
2370 if (interfaces != null){
2371 foreach (Type i in interfaces){
2378 } while (t != null);
2383 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2385 // This is a custom version of Convert.ChangeType() which works
2386 // with the TypeBuilder defined types when compiling corlib.
2387 public static object ChangeType (object value, Type conversionType, out bool error)
2389 IConvertible convert_value = value as IConvertible;
2391 if (convert_value == null){
2397 // We must use Type.Equals() here since `conversionType' is
2398 // the TypeBuilder created version of a system type and not
2399 // the system type itself. You cannot use Type.GetTypeCode()
2400 // on such a type - it'd always return TypeCode.Object.
2404 if (conversionType.Equals (typeof (Boolean)))
2405 return (object)(convert_value.ToBoolean (nf_provider));
2406 else if (conversionType.Equals (typeof (Byte)))
2407 return (object)(convert_value.ToByte (nf_provider));
2408 else if (conversionType.Equals (typeof (Char)))
2409 return (object)(convert_value.ToChar (nf_provider));
2410 else if (conversionType.Equals (typeof (DateTime)))
2411 return (object)(convert_value.ToDateTime (nf_provider));
2412 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2413 return (object)(convert_value.ToDecimal (nf_provider));
2414 else if (conversionType.Equals (typeof (Double)))
2415 return (object)(convert_value.ToDouble (nf_provider));
2416 else if (conversionType.Equals (typeof (Int16)))
2417 return (object)(convert_value.ToInt16 (nf_provider));
2418 else if (conversionType.Equals (typeof (Int32)))
2419 return (object)(convert_value.ToInt32 (nf_provider));
2420 else if (conversionType.Equals (typeof (Int64)))
2421 return (object)(convert_value.ToInt64 (nf_provider));
2422 else if (conversionType.Equals (typeof (SByte)))
2423 return (object)(convert_value.ToSByte (nf_provider));
2424 else if (conversionType.Equals (typeof (Single)))
2425 return (object)(convert_value.ToSingle (nf_provider));
2426 else if (conversionType.Equals (typeof (String)))
2427 return (object)(convert_value.ToString (nf_provider));
2428 else if (conversionType.Equals (typeof (UInt16)))
2429 return (object)(convert_value.ToUInt16 (nf_provider));
2430 else if (conversionType.Equals (typeof (UInt32)))
2431 return (object)(convert_value.ToUInt32 (nf_provider));
2432 else if (conversionType.Equals (typeof (UInt64)))
2433 return (object)(convert_value.ToUInt64 (nf_provider));
2434 else if (conversionType.Equals (typeof (Object)))
2435 return (object)(value);
2445 // This is needed, because enumerations from assemblies
2446 // do not report their underlyingtype, but they report
2449 public static Type EnumToUnderlying (Type t)
2451 if (t == TypeManager.enum_type)
2454 t = t.UnderlyingSystemType;
2455 if (!TypeManager.IsEnumType (t))
2458 if (t is TypeBuilder) {
2459 // slow path needed to compile corlib
2460 if (t == TypeManager.bool_type ||
2461 t == TypeManager.byte_type ||
2462 t == TypeManager.sbyte_type ||
2463 t == TypeManager.char_type ||
2464 t == TypeManager.short_type ||
2465 t == TypeManager.ushort_type ||
2466 t == TypeManager.int32_type ||
2467 t == TypeManager.uint32_type ||
2468 t == TypeManager.int64_type ||
2469 t == TypeManager.uint64_type)
2472 TypeCode tc = Type.GetTypeCode (t);
2475 case TypeCode.Boolean:
2476 return TypeManager.bool_type;
2478 return TypeManager.byte_type;
2479 case TypeCode.SByte:
2480 return TypeManager.sbyte_type;
2482 return TypeManager.char_type;
2483 case TypeCode.Int16:
2484 return TypeManager.short_type;
2485 case TypeCode.UInt16:
2486 return TypeManager.ushort_type;
2487 case TypeCode.Int32:
2488 return TypeManager.int32_type;
2489 case TypeCode.UInt32:
2490 return TypeManager.uint32_type;
2491 case TypeCode.Int64:
2492 return TypeManager.int64_type;
2493 case TypeCode.UInt64:
2494 return TypeManager.uint64_type;
2496 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2500 // When compiling corlib and called with one of the core types, return
2501 // the corresponding typebuilder for that type.
2503 public static Type TypeToCoreType (Type t)
2505 if (RootContext.StdLib || (t is TypeBuilder))
2508 TypeCode tc = Type.GetTypeCode (t);
2511 case TypeCode.Boolean:
2512 return TypeManager.bool_type;
2514 return TypeManager.byte_type;
2515 case TypeCode.SByte:
2516 return TypeManager.sbyte_type;
2518 return TypeManager.char_type;
2519 case TypeCode.Int16:
2520 return TypeManager.short_type;
2521 case TypeCode.UInt16:
2522 return TypeManager.ushort_type;
2523 case TypeCode.Int32:
2524 return TypeManager.int32_type;
2525 case TypeCode.UInt32:
2526 return TypeManager.uint32_type;
2527 case TypeCode.Int64:
2528 return TypeManager.int64_type;
2529 case TypeCode.UInt64:
2530 return TypeManager.uint64_type;
2531 case TypeCode.Single:
2532 return TypeManager.float_type;
2533 case TypeCode.Double:
2534 return TypeManager.double_type;
2535 case TypeCode.String:
2536 return TypeManager.string_type;
2537 case TypeCode.Decimal:
2538 return TypeManager.decimal_type;
2540 if (t == typeof (void))
2541 return TypeManager.void_type;
2542 if (t == typeof (object))
2543 return TypeManager.object_type;
2544 if (t == typeof (System.Type))
2545 return TypeManager.type_type;
2546 if (t == typeof (System.IntPtr))
2547 return TypeManager.intptr_type;
2553 /// Utility function that can be used to probe whether a type
2554 /// is managed or not.
2556 public static bool VerifyUnManaged (Type t, Location loc)
2558 if (IsUnmanagedType (t))
2561 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2568 /// Returns the name of the indexer in a given type.
2571 /// The default is not always `Item'. The user can change this behaviour by
2572 /// using the IndexerNameAttribute in the container.
2574 /// For example, the String class indexer is named `Chars' not `Item'
2576 public static string IndexerPropertyName (Type t)
2578 if (t.IsGenericInstance)
2579 t = t.GetGenericTypeDefinition ();
2581 if (t is TypeBuilder) {
2582 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2583 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2586 System.Attribute attr = System.Attribute.GetCustomAttribute (
2587 t, TypeManager.default_member_type);
2589 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2590 return dma.MemberName;
2593 return TypeContainer.DefaultIndexerName;
2596 static MethodInfo declare_local_method = null;
2598 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2600 if (declare_local_method == null){
2601 declare_local_method = typeof (ILGenerator).GetMethod (
2603 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2605 new Type [] { typeof (Type), typeof (bool)},
2607 if (declare_local_method == null){
2608 Report.Warning (-30, new Location (-1),
2609 "This version of the runtime does not support making pinned local variables. " +
2610 "This code may cause errors on a runtime with a moving GC");
2611 return ig.DeclareLocal (t);
2614 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2618 // Returns whether the array of memberinfos contains the given method
2620 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2622 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2624 foreach (MethodBase method in array) {
2625 if (method.Name != new_method.Name)
2628 if (method is MethodInfo && new_method is MethodInfo)
2629 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2633 Type [] old_args = TypeManager.GetArgumentTypes (method);
2634 int old_count = old_args.Length;
2637 if (new_args.Length != old_count)
2640 for (i = 0; i < old_count; i++){
2641 if (old_args [i] != new_args [i])
2654 // We copy methods from `new_members' into `target_list' if the signature
2655 // for the method from in the new list does not exist in the target_list
2657 // The name is assumed to be the same.
2659 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2661 if (target_list == null){
2662 target_list = new ArrayList ();
2664 foreach (MemberInfo mi in new_members){
2665 if (mi is MethodBase)
2666 target_list.Add (mi);
2671 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2672 target_list.CopyTo (target_array, 0);
2674 foreach (MemberInfo mi in new_members){
2675 MethodBase new_method = (MethodBase) mi;
2677 if (!ArrayContainsMethod (target_array, new_method))
2678 target_list.Add (new_method);
2683 #region MemberLookup implementation
2686 // Whether we allow private members in the result (since FindMembers
2687 // uses NonPublic for both protected and private), we need to distinguish.
2690 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2695 internal class Closure {
2696 internal bool private_ok;
2698 // Who is invoking us and which type is being queried currently.
2699 internal Type invocation_type;
2700 internal Type qualifier_type;
2702 // The assembly that defines the type is that is calling us
2703 internal Assembly invocation_assembly;
2704 internal IList almost_match;
2706 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2708 if (invocation_type == null)
2711 if (is_static && qualifier_type == null)
2712 // It resolved from a simple name, so it should be visible.
2715 // A nested class has access to all the protected members visible to its parent.
2716 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2719 if (IsNestedFamilyAccessible (invocation_type, m.DeclaringType)) {
2720 // Although a derived class can access protected members of its base class
2721 // it cannot do so through an instance of the base class (CS1540).
2722 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2724 qualifier_type == null ||
2725 IsEqualGenericInstance (invocation_type, qualifier_type) ||
2726 !IsFamilyAccessible (invocation_type, qualifier_type) ||
2727 IsNestedChildOf (invocation_type, qualifier_type))
2731 if (almost_match != null)
2732 almost_match.Add (m);
2738 // This filter filters by name + whether it is ok to include private
2739 // members in the search
2741 internal bool Filter (MemberInfo m, object filter_criteria)
2744 // Hack: we know that the filter criteria will always be in the
2745 // `closure' // fields.
2748 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2751 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2752 (invocation_type != null) &&
2753 IsPrivateAccessible (m.DeclaringType, invocation_type))
2757 // Ugly: we need to find out the type of `m', and depending
2758 // on this, tell whether we accept or not
2760 if (m is MethodBase){
2761 MethodBase mb = (MethodBase) m;
2762 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2764 if (ma == MethodAttributes.Private)
2765 return private_ok ||
2766 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2767 IsNestedChildOf (invocation_type, m.DeclaringType);
2769 if (invocation_assembly == mb.DeclaringType.Assembly) {
2770 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2773 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2777 if (ma == MethodAttributes.Family ||
2778 ma == MethodAttributes.FamANDAssem ||
2779 ma == MethodAttributes.FamORAssem)
2780 return CheckValidFamilyAccess (mb.IsStatic, m);
2786 if (m is FieldInfo){
2787 FieldInfo fi = (FieldInfo) m;
2788 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2790 if (fa == FieldAttributes.Private)
2791 return private_ok ||
2792 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2793 IsNestedChildOf (invocation_type, m.DeclaringType);
2795 if (invocation_assembly == fi.DeclaringType.Assembly) {
2796 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2799 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2803 if (fa == FieldAttributes.Family ||
2804 fa == FieldAttributes.FamANDAssem ||
2805 fa == FieldAttributes.FamORAssem)
2806 return CheckValidFamilyAccess (fi.IsStatic, m);
2813 // EventInfos and PropertyInfos, return true because they lack
2814 // permission information, so we need to check later on the methods.
2820 static Closure closure = new Closure ();
2821 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2824 // Looks up a member called `name' in the `queried_type'. This lookup
2825 // is done by code that is contained in the definition for `invocation_type'
2826 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2828 // `invocation_type' is used to check whether we're allowed to access the requested
2829 // member wrt its protection level.
2831 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2832 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2833 // is B and qualifier_type is A). This is used to do the CS1540 check.
2835 // When resolving a SimpleName, `qualifier_type' is null.
2837 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2838 // the same than `queried_type' - except when we're being called from BaseAccess;
2839 // in this case, `invocation_type' is the current type and `queried_type' the base
2840 // type, so this'd normally trigger a CS1540.
2842 // The binding flags are `bf' and the kind of members being looked up are `mt'
2844 // The return value always includes private members which code in `invocation_type'
2845 // is allowed to access (using the specified `qualifier_type' if given); only use
2846 // BindingFlags.NonPublic to bypass the permission check.
2848 // The 'almost_match' argument is used for reporting error CS1540.
2850 // Returns an array of a single element for everything but Methods/Constructors
2851 // that might return multiple matches.
2853 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2854 Type queried_type, MemberTypes mt,
2855 BindingFlags original_bf, string name, IList almost_match)
2857 Timer.StartTimer (TimerType.MemberLookup);
2859 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2860 queried_type, mt, original_bf, name, almost_match);
2862 Timer.StopTimer (TimerType.MemberLookup);
2867 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2868 Type queried_type, MemberTypes mt,
2869 BindingFlags original_bf, string name, IList almost_match)
2871 BindingFlags bf = original_bf;
2873 ArrayList method_list = null;
2874 Type current_type = queried_type;
2875 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2876 bool skip_iface_check = true, used_cache = false;
2877 bool always_ok_flag = false;
2879 closure.invocation_type = invocation_type;
2880 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2881 closure.qualifier_type = qualifier_type;
2882 closure.almost_match = almost_match;
2885 // If we are a nested class, we always have access to our container
2888 if (invocation_type != null){
2889 string invocation_name = invocation_type.FullName;
2890 if ((invocation_name != null) && (invocation_name.IndexOf ('+') != -1)){
2891 string container = queried_type.FullName + "+";
2892 int container_length = container.Length;
2894 if (invocation_name.Length > container_length){
2895 string shared = invocation_name.Substring (0, container_length);
2897 if (shared == container)
2898 always_ok_flag = true;
2903 // This is from the first time we find a method
2904 // in most cases, we do not actually find a method in the base class
2905 // so we can just ignore it, and save the arraylist allocation
2906 MemberInfo [] first_members_list = null;
2907 bool use_first_members_list = false;
2913 // `NonPublic' is lame, because it includes both protected and
2914 // private methods, so we need to control this behavior by
2915 // explicitly tracking if a private method is ok or not.
2917 // The possible cases are:
2918 // public, private and protected (internal does not come into the
2921 if ((invocation_type != null) &&
2922 ((invocation_type == current_type) ||
2923 IsNestedChildOf (invocation_type, current_type)) ||
2925 bf = original_bf | BindingFlags.NonPublic;
2929 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2931 Timer.StopTimer (TimerType.MemberLookup);
2933 list = MemberLookup_FindMembers (
2934 current_type, mt, bf, name, out used_cache);
2936 Timer.StartTimer (TimerType.MemberLookup);
2939 // When queried for an interface type, the cache will automatically check all
2940 // inherited members, so we don't need to do this here. However, this only
2941 // works if we already used the cache in the first iteration of this loop.
2943 // If we used the cache in any further iteration, we can still terminate the
2944 // loop since the cache always looks in all base classes.
2950 skip_iface_check = false;
2952 if (current_type == TypeManager.object_type)
2955 current_type = current_type.BaseType;
2958 // This happens with interfaces, they have a null
2959 // basetype. Look members up in the Object class.
2961 if (current_type == null) {
2962 current_type = TypeManager.object_type;
2967 if (list.Length == 0)
2971 // Events and types are returned by both `static' and `instance'
2972 // searches, which means that our above FindMembers will
2973 // return two copies of the same.
2975 if (list.Length == 1 && !(list [0] is MethodBase)){
2980 // Multiple properties: we query those just to find out the indexer
2983 if (list [0] is PropertyInfo)
2987 // We found an event: the cache lookup returns both the event and
2988 // its private field.
2990 if (list [0] is EventInfo) {
2991 if ((list.Length == 2) && (list [1] is FieldInfo))
2992 return new MemberInfo [] { list [0] };
2999 // We found methods, turn the search into "method scan"
3003 if (first_members_list != null) {
3004 if (use_first_members_list) {
3005 method_list = CopyNewMethods (method_list, first_members_list);
3006 use_first_members_list = false;
3009 method_list = CopyNewMethods (method_list, list);
3011 first_members_list = list;
3012 use_first_members_list = true;
3014 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3016 } while (searching);
3018 if (use_first_members_list) {
3019 foreach (MemberInfo mi in first_members_list) {
3020 if (! (mi is MethodBase)) {
3021 method_list = CopyNewMethods (method_list, first_members_list);
3022 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3025 return (MemberInfo []) first_members_list;
3028 if (method_list != null && method_list.Count > 0) {
3029 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3032 // This happens if we already used the cache in the first iteration, in this case
3033 // the cache already looked in all interfaces.
3035 if (skip_iface_check)
3039 // Interfaces do not list members they inherit, so we have to
3042 if (!queried_type.IsInterface)
3045 if (queried_type.IsArray)
3046 queried_type = TypeManager.array_type;
3048 Type [] ifaces = GetInterfaces (queried_type);
3052 foreach (Type itype in ifaces){
3055 x = MemberLookup (null, null, itype, mt, bf, name, null);
3063 // Tests whether external method is really special
3064 public static bool IsSpecialMethod (MethodBase mb)
3066 string name = mb.Name;
3067 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
3068 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
3070 if (name.StartsWith ("add_"))
3071 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
3073 if (name.StartsWith ("remove_"))
3074 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
3076 if (name.StartsWith ("op_")){
3077 foreach (string oname in Unary.oper_names) {
3082 foreach (string oname in Binary.oper_names) {
3095 /// There is exactly one instance of this class per type.
3097 public sealed class TypeHandle : IMemberContainer {
3098 public readonly IMemberContainer BaseType;
3100 readonly int id = ++next_id;
3101 static int next_id = 0;
3103 static TypeHandle ()
3109 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3110 /// a TypeHandle yet, a new instance of it is created. This static method
3111 /// ensures that we'll only have one TypeHandle instance per type.
3113 private static TypeHandle GetTypeHandle (Type t)
3115 TypeHandle handle = (TypeHandle) type_hash [t];
3119 handle = new TypeHandle (t);
3120 type_hash.Add (t, handle);
3124 public static MemberCache GetMemberCache (Type t)
3126 return GetTypeHandle (t).MemberCache;
3129 public static void CleanUp ()
3134 public static void Reset ()
3136 type_hash = new PtrHashtable ();
3140 /// Returns the TypeHandle for TypeManager.object_type.
3142 public static IMemberContainer ObjectType {
3144 if (object_type != null)
3147 object_type = GetTypeHandle (TypeManager.object_type);
3154 /// Returns the TypeHandle for TypeManager.array_type.
3156 public static IMemberContainer ArrayType {
3158 if (array_type != null)
3161 array_type = GetTypeHandle (TypeManager.array_type);
3167 private static PtrHashtable type_hash;
3169 private static TypeHandle object_type = null;
3170 private static TypeHandle array_type = null;
3173 private string full_name;
3174 private bool is_interface;
3175 private MemberCache member_cache;
3176 private MemberCache base_cache;
3178 private TypeHandle (Type type)
3181 full_name = type.FullName != null ? type.FullName : type.Name;
3182 if (type.BaseType != null) {
3183 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3184 BaseType = base_cache.Container;
3185 } else if (type.IsInterface)
3186 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3187 this.is_interface = type.IsInterface || type.IsGenericParameter;
3188 this.member_cache = new MemberCache (this);
3191 // IMemberContainer methods
3193 public string Name {
3205 public MemberCache BaseCache {
3211 public bool IsInterface {
3213 return is_interface;
3217 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3219 MemberInfo [] members;
3220 if (type is GenericTypeParameterBuilder)
3221 return MemberList.Empty;
3222 if (mt == MemberTypes.Event)
3223 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3225 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3227 Array.Reverse (members);
3229 return new MemberList (members);
3232 // IMemberFinder methods
3234 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3235 MemberFilter filter, object criteria)
3237 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3240 public MemberCache MemberCache {
3242 return member_cache;
3246 public override string ToString ()
3248 if (BaseType != null)
3249 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3251 return "TypeHandle (" + id + "," + Name + ")";