2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
15 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
16 // the behavior of the compilation. This can be removed if we rework
17 // the code to get a list of namespaces available.
19 #define SIMPLE_SPEEDUP
23 using System
.Globalization
;
24 using System
.Collections
;
25 using System
.Reflection
;
26 using System
.Reflection
.Emit
;
28 using System
.Text
.RegularExpressions
;
29 using System
.Runtime
.CompilerServices
;
30 using System
.Diagnostics
;
32 namespace Mono
.CSharp
{
34 public partial class TypeManager
{
36 // A list of core types that the compiler requires or uses
38 static public Type object_type
;
39 static public Type value_type
;
40 static public Type string_type
;
41 static public Type int32_type
;
42 static public Type uint32_type
;
43 static public Type int64_type
;
44 static public Type uint64_type
;
45 static public Type float_type
;
46 static public Type double_type
;
47 static public Type char_type
;
48 static public Type char_ptr_type
;
49 static public Type short_type
;
50 static public Type decimal_type
;
51 static public Type bool_type
;
52 static public Type sbyte_type
;
53 static public Type byte_type
;
54 static public Type ushort_type
;
55 static public Type enum_type
;
56 static public Type delegate_type
;
57 static public Type multicast_delegate_type
;
58 static public Type void_type
;
59 static public Type null_type
;
60 static public Type enumeration_type
;
61 static public Type array_type
;
62 static public Type runtime_handle_type
;
63 static public Type icloneable_type
;
64 static public Type type_type
;
65 static public Type ienumerator_type
;
66 static public Type ienumerable_type
;
67 static public Type idisposable_type
;
68 static public Type iconvertible_type
;
69 static public Type default_member_type
;
70 static public Type iasyncresult_type
;
71 static public Type asynccallback_type
;
72 static public Type intptr_type
;
73 static public Type monitor_type
;
74 static public Type runtime_field_handle_type
;
75 static public Type runtime_argument_handle_type
;
76 static public Type attribute_type
;
77 static public Type attribute_usage_type
;
78 static public Type decimal_constant_attribute_type
;
79 static public Type dllimport_type
;
80 static public Type unverifiable_code_type
;
81 static public Type methodimpl_attr_type
;
82 static public Type marshal_as_attr_type
;
83 static public Type param_array_type
;
84 static public Type void_ptr_type
;
85 static public Type indexer_name_type
;
86 static public Type exception_type
;
87 static public Type invalid_operation_exception_type
;
88 static public Type not_supported_exception_type
;
89 static public Type obsolete_attribute_type
;
90 static public Type conditional_attribute_type
;
91 static public Type in_attribute_type
;
92 static public Type out_attribute_type
;
93 static public Type anonymous_method_type
;
94 static public Type cls_compliant_attribute_type
;
95 static public Type typed_reference_type
;
96 static public Type arg_iterator_type
;
97 static public Type mbr_type
;
98 static public Type struct_layout_attribute_type
;
99 static public Type field_offset_attribute_type
;
100 static public Type security_attr_type
;
101 static public Type required_attr_type
;
102 static public Type guid_attr_type
;
103 static public Type assembly_culture_attribute_type
;
104 static public Type coclass_attr_type
;
105 static public Type comimport_attr_type
;
110 static internal Type runtime_compatibility_attr_type
;
111 static internal Type compiler_generated_attr_type
;
112 static internal Type fixed_buffer_attr_type
;
113 static internal Type default_charset_type
;
114 static internal Type internals_visible_attr_type
;
117 // An empty array of types
119 static public Type
[] NoTypes
;
120 static public TypeExpr
[] NoTypeExprs
;
124 // Expressions representing the internal types. Used during declaration
127 static public TypeExpr system_object_expr
, system_string_expr
;
128 static public TypeExpr system_boolean_expr
, system_decimal_expr
;
129 static public TypeExpr system_single_expr
, system_double_expr
;
130 static public TypeExpr system_sbyte_expr
, system_byte_expr
;
131 static public TypeExpr system_int16_expr
, system_uint16_expr
;
132 static public TypeExpr system_int32_expr
, system_uint32_expr
;
133 static public TypeExpr system_int64_expr
, system_uint64_expr
;
134 static public TypeExpr system_char_expr
, system_void_expr
;
135 static public TypeExpr system_asynccallback_expr
;
136 static public TypeExpr system_iasyncresult_expr
;
137 static public TypeExpr system_valuetype_expr
;
138 static public TypeExpr system_intptr_expr
;
141 // This is only used when compiling corlib
143 static public Type system_int32_type
;
144 static public Type system_array_type
;
145 static public Type system_type_type
;
146 static public Type system_assemblybuilder_type
;
147 static public MethodInfo system_int_array_get_length
;
148 static public MethodInfo system_int_array_get_rank
;
149 static public MethodInfo system_object_array_clone
;
150 static public MethodInfo system_int_array_get_length_int
;
151 static public MethodInfo system_int_array_get_lower_bound_int
;
152 static public MethodInfo system_int_array_get_upper_bound_int
;
153 static public MethodInfo system_void_array_copyto_array_int
;
157 // Internal, not really used outside
159 static Type runtime_helpers_type
;
162 // These methods are called by code generated by the compiler
164 static public MethodInfo string_concat_string_string
;
165 static public MethodInfo string_concat_string_string_string
;
166 static public MethodInfo string_concat_string_string_string_string
;
167 static public MethodInfo string_concat_string_dot_dot_dot
;
168 static public MethodInfo string_concat_object_object
;
169 static public MethodInfo string_concat_object_object_object
;
170 static public MethodInfo string_concat_object_dot_dot_dot
;
171 static public MethodInfo string_isinterneted_string
;
172 static public MethodInfo system_type_get_type_from_handle
;
173 static public MethodInfo bool_movenext_void
;
174 static public MethodInfo ienumerable_getenumerator_void
;
175 static public MethodInfo void_reset_void
;
176 static public MethodInfo void_dispose_void
;
177 static public MethodInfo void_monitor_enter_object
;
178 static public MethodInfo void_monitor_exit_object
;
179 static public MethodInfo void_initializearray_array_fieldhandle
;
180 static public MethodInfo int_getlength_int
;
181 static public MethodInfo delegate_combine_delegate_delegate
;
182 static public MethodInfo delegate_remove_delegate_delegate
;
183 static public MethodInfo int_get_offset_to_string_data
;
184 static public MethodInfo int_array_get_length
;
185 static public MethodInfo int_array_get_rank
;
186 static public MethodInfo object_array_clone
;
187 static public MethodInfo int_array_get_length_int
;
188 static public MethodInfo int_array_get_lower_bound_int
;
189 static public MethodInfo int_array_get_upper_bound_int
;
190 static public MethodInfo void_array_copyto_array_int
;
191 static public PropertyInfo ienumerator_getcurrent
;
194 // The attribute constructors.
196 static public ConstructorInfo object_ctor
;
197 static public ConstructorInfo cons_param_array_attribute
;
198 static public ConstructorInfo void_decimal_ctor_five_args
;
199 static public ConstructorInfo void_decimal_ctor_int_arg
;
200 static public ConstructorInfo unverifiable_code_ctor
;
201 static public ConstructorInfo default_member_ctor
;
202 static public ConstructorInfo decimal_constant_attribute_ctor
;
203 static internal ConstructorInfo struct_layout_attribute_ctor
;
204 static public ConstructorInfo field_offset_attribute_ctor
;
209 static internal CustomAttributeBuilder compiler_generated_attr
;
210 static internal ConstructorInfo fixed_buffer_attr_ctor
;
212 static PtrHashtable builder_to_declspace
;
214 static PtrHashtable builder_to_member_cache
;
217 // Tracks the interfaces implemented by typebuilders. We only
218 // enter those who do implement or or more interfaces
220 static PtrHashtable builder_to_ifaces
;
223 // Maps PropertyBuilder to a Type array that contains
224 // the arguments to the indexer
226 static Hashtable indexer_arguments
;
229 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
231 static Hashtable method_params
;
234 // A hash table from override methods to their base virtual method.
236 static Hashtable method_overrides
;
239 // Keeps track of methods
242 static Hashtable builder_to_method
;
245 // Contains all public types from referenced assemblies.
246 // This member is used only if CLS Compliance verification is required.
248 public static Hashtable AllClsTopLevelTypes
;
250 static Hashtable fieldbuilders_to_fields
;
251 static Hashtable fields
;
253 static PtrHashtable assembly_internals_vis_attrs
;
260 public static void CleanUp ()
262 // Lets get everything clean so that we can collect before generating code
263 builder_to_declspace
= null;
264 builder_to_member_cache
= null;
265 builder_to_ifaces
= null;
266 indexer_arguments
= null;
267 method_params
= null;
268 builder_to_method
= null;
271 fieldbuilders_to_fields
= null;
273 priv_fields_events
= null;
277 assembly_internals_vis_attrs
= null;
280 TypeHandle
.CleanUp ();
284 /// A filter for Findmembers that uses the Signature object to
287 static bool SignatureFilter (MemberInfo mi
, object criteria
)
289 Signature sig
= (Signature
) criteria
;
291 if (!(mi
is MethodBase
))
294 if (mi
.Name
!= sig
.name
)
297 int count
= sig
.args
.Length
;
299 if (mi
is MethodBuilder
|| mi
is ConstructorBuilder
){
300 Type
[] candidate_args
= GetParameterData ((MethodBase
) mi
).Types
;
302 if (candidate_args
.Length
!= count
)
305 for (int i
= 0; i
< count
; i
++)
306 if (candidate_args
[i
] != sig
.args
[i
])
311 ParameterInfo
[] pars
= ((MethodBase
) mi
).GetParameters ();
313 if (pars
.Length
!= count
)
316 for (int i
= 0; i
< count
; i
++)
317 if (pars
[i
].ParameterType
!= sig
.args
[i
])
323 // A delegate that points to the filter above.
324 static MemberFilter signature_filter
;
327 // These are expressions that represent some of the internal data types, used
330 static void InitExpressionTypes ()
332 system_object_expr
= new TypeLookupExpression ("System.Object");
333 system_string_expr
= new TypeLookupExpression ("System.String");
334 system_boolean_expr
= new TypeLookupExpression ("System.Boolean");
335 system_decimal_expr
= new TypeLookupExpression ("System.Decimal");
336 system_single_expr
= new TypeLookupExpression ("System.Single");
337 system_double_expr
= new TypeLookupExpression ("System.Double");
338 system_sbyte_expr
= new TypeLookupExpression ("System.SByte");
339 system_byte_expr
= new TypeLookupExpression ("System.Byte");
340 system_int16_expr
= new TypeLookupExpression ("System.Int16");
341 system_uint16_expr
= new TypeLookupExpression ("System.UInt16");
342 system_int32_expr
= new TypeLookupExpression ("System.Int32");
343 system_uint32_expr
= new TypeLookupExpression ("System.UInt32");
344 system_int64_expr
= new TypeLookupExpression ("System.Int64");
345 system_uint64_expr
= new TypeLookupExpression ("System.UInt64");
346 system_char_expr
= new TypeLookupExpression ("System.Char");
347 system_void_expr
= new TypeLookupExpression ("System.Void");
348 system_asynccallback_expr
= new TypeLookupExpression ("System.AsyncCallback");
349 system_iasyncresult_expr
= new TypeLookupExpression ("System.IAsyncResult");
350 system_valuetype_expr
= new TypeLookupExpression ("System.ValueType");
351 system_intptr_expr
= new TypeLookupExpression ("System.IntPtr");
354 static TypeManager ()
358 signature_filter
= new MemberFilter (SignatureFilter
);
359 InitExpressionTypes ();
362 static public void Reset ()
364 builder_to_declspace
= new PtrHashtable ();
365 builder_to_member_cache
= new PtrHashtable ();
366 builder_to_method
= new PtrHashtable ();
367 method_params
= new PtrHashtable ();
368 method_overrides
= new PtrHashtable ();
369 indexer_arguments
= new PtrHashtable ();
370 builder_to_ifaces
= new PtrHashtable ();
372 NoTypes
= new Type
[0];
373 NoTypeExprs
= new TypeExpr
[0];
375 fieldbuilders_to_fields
= new Hashtable ();
376 fields
= new Hashtable ();
377 type_hash
= new DoubleHash ();
379 assembly_internals_vis_attrs
= new PtrHashtable ();
384 public static void AddUserType (DeclSpace ds
)
386 builder_to_declspace
.Add (ds
.TypeBuilder
, ds
);
390 // This entry point is used by types that we define under the covers
392 public static void RegisterBuilder (Type tb
, Type
[] ifaces
)
395 builder_to_ifaces
[tb
] = ifaces
;
398 public static void AddMethod (MethodBase builder
, IMethodData method
)
400 builder_to_method
.Add (builder
, method
);
401 method_params
.Add (builder
, method
.ParameterInfo
);
404 public static IMethodData
GetMethod (MethodBase builder
)
406 return (IMethodData
) builder_to_method
[builder
];
410 /// Returns the DeclSpace whose Type is `t' or null if there is no
411 /// DeclSpace for `t' (ie, the Type comes from a library)
413 public static DeclSpace
LookupDeclSpace (Type t
)
415 return builder_to_declspace
[t
] as DeclSpace
;
419 /// Returns the TypeContainer whose Type is `t' or null if there is no
420 /// TypeContainer for `t' (ie, the Type comes from a library)
422 public static TypeContainer
LookupTypeContainer (Type t
)
424 return builder_to_declspace
[t
] as TypeContainer
;
427 public static MemberCache
LookupMemberCache (Type t
)
429 if (t
is TypeBuilder
) {
430 IMemberContainer container
= builder_to_declspace
[t
] as IMemberContainer
;
431 if (container
!= null)
432 return container
.MemberCache
;
435 if (t
is GenericTypeParameterBuilder
) {
436 IMemberContainer container
= builder_to_type_param
[t
] as IMemberContainer
;
438 if (container
!= null)
439 return container
.MemberCache
;
442 return TypeHandle
.GetMemberCache (t
);
445 public static MemberCache
LookupBaseInterfacesCache (Type t
)
447 Type
[] ifaces
= t
.GetInterfaces ();
449 if (ifaces
!= null && ifaces
.Length
== 1)
450 return LookupMemberCache (ifaces
[0]);
452 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
453 MemberCache cache
= builder_to_member_cache
[t
] as MemberCache
;
457 cache
= new MemberCache (ifaces
);
458 builder_to_member_cache
.Add (t
, cache
);
462 public static TypeContainer
LookupInterface (Type t
)
464 TypeContainer tc
= (TypeContainer
) builder_to_declspace
[t
];
465 if ((tc
== null) || (tc
.Kind
!= Kind
.Interface
))
471 public static Delegate
LookupDelegate (Type t
)
473 return builder_to_declspace
[t
] as Delegate
;
476 public static Class
LookupClass (Type t
)
478 return (Class
) builder_to_declspace
[t
];
482 // We use this hash for multiple kinds of constructed types:
484 // (T, "&") Given T, get T &
485 // (T, "*") Given T, get T *
486 // (T, "[]") Given T and a array dimension, get T []
487 // (T, X) Given a type T and a simple name X, get the type T+X
489 // Accessibility tests, if necessary, should be done by the user
491 static DoubleHash type_hash
= new DoubleHash ();
494 // Gets the reference to T version of the Type (T&)
496 public static Type
GetReferenceType (Type t
)
498 return t
.MakeByRefType ();
502 // Gets the pointer to T version of the Type (T*)
504 public static Type
GetPointerType (Type t
)
506 return GetConstructedType (t
, "*");
509 public static Type
GetConstructedType (Type t
, string dim
)
512 if (type_hash
.Lookup (t
, dim
, out ret
))
515 ret
= t
.Module
.GetType (t
.ToString () + dim
);
517 type_hash
.Insert (t
, dim
, ret
);
522 ret
= GetReferenceType (t
);
523 type_hash
.Insert (t
, dim
, ret
);
527 if (t
.IsGenericParameter
|| t
.IsGenericInstance
) {
530 while ((pos
< dim
.Length
) && (dim
[pos
] == '[')) {
533 if (dim
[pos
] == ']') {
534 result
= result
.MakeArrayType ();
537 if (pos
< dim
.Length
)
540 type_hash
.Insert (t
, dim
, result
);
545 while (dim
[pos
] == ',') {
549 if ((dim
[pos
] != ']') || (pos
!= dim
.Length
-1))
552 result
= result
.MakeArrayType (rank
+ 1);
553 type_hash
.Insert (t
, dim
, result
);
558 type_hash
.Insert (t
, dim
, null);
562 public static Type
GetNestedType (Type t
, string name
)
565 if (!type_hash
.Lookup (t
, name
, out ret
)) {
566 ret
= t
.GetNestedType (name
,
567 BindingFlags
.Static
| BindingFlags
.Public
| BindingFlags
.NonPublic
| BindingFlags
.DeclaredOnly
);
568 type_hash
.Insert (t
, name
, ret
);
574 /// Fills static table with exported types from all referenced assemblies.
575 /// This information is required for CLS Compliance tests.
577 public static void LoadAllImportedTypes ()
579 AllClsTopLevelTypes
= new Hashtable (1500);
580 foreach (Assembly a
in RootNamespace
.Global
.Assemblies
) {
581 foreach (Type t
in a
.GetExportedTypes ()) {
582 AllClsTopLevelTypes
[t
.FullName
.ToLower (System
.Globalization
.CultureInfo
.InvariantCulture
)] = null;
587 public static bool NamespaceClash (string name
, Location loc
)
589 if (! RootNamespace
.Global
.IsNamespace (name
))
592 Report
.Error (519, loc
, String
.Format ("`{0}' clashes with a predefined namespace", name
));
597 /// Returns the C# name of a type if possible, or the full type name otherwise
599 static public string CSharpName (Type t
)
601 string name
= GetFullName (t
);
603 return Regex
.Replace (name
,
605 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
606 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
607 @"Boolean|String|Void|Null)" +
609 new MatchEvaluator (CSharpNameMatch
)).Replace ('+', '.');
612 static public string CSharpName (Type
[] types
)
614 StringBuilder sb
= new StringBuilder ();
615 foreach (Type t
in types
) {
616 sb
.Append (CSharpName (t
));
619 sb
.Remove (sb
.Length
- 1, 1);
620 return sb
.ToString ();
623 static String
CSharpNameMatch (Match match
)
625 string s
= match
.Groups
[1].Captures
[0].Value
;
627 Replace ("int32", "int").
628 Replace ("uint32", "uint").
629 Replace ("int16", "short").
630 Replace ("uint16", "ushort").
631 Replace ("int64", "long").
632 Replace ("uint64", "ulong").
633 Replace ("single", "float").
634 Replace ("boolean", "bool")
635 + match
.Groups
[2].Captures
[0].Value
;
639 /// Returns the signature of the method with full namespace classification
641 static public string GetFullNameSignature (MemberInfo mi
)
643 PropertyInfo pi
= mi
as PropertyInfo
;
645 MethodBase pmi
= pi
.GetGetMethod ();
647 pmi
= pi
.GetSetMethod ();
648 if (GetParameterData (pmi
).Count
> 0)
651 return (mi
is MethodBase
)
652 ? CSharpSignature (mi
as MethodBase
)
653 : CSharpName (mi
.DeclaringType
) + '.' + mi
.Name
;
656 private static int GetFullName (Type t
, StringBuilder sb
)
660 if (!t
.IsGenericType
) {
661 sb
.Append (t
.FullName
);
665 if (t
.DeclaringType
!= null) {
666 pos
= GetFullName (t
.DeclaringType
, sb
);
668 sb
.Append (RemoveGenericArity (t
.Name
));
670 sb
.Append (RemoveGenericArity (t
.FullName
));
673 Type
[] this_args
= GetTypeArguments (t
);
675 if (this_args
.Length
< pos
)
676 throw new InternalErrorException (
677 "Enclosing class " + t
.DeclaringType
+ " has more type arguments than " + t
);
678 if (this_args
.Length
== pos
)
683 sb
.Append (CSharpName (this_args
[pos
++]));
684 if (pos
== this_args
.Length
)
692 public static string GetFullName (Type t
)
694 if (t
.IsGenericParameter
)
696 if (!t
.IsGenericType
)
699 StringBuilder sb
= new StringBuilder ();
700 int pos
= GetFullName (t
, sb
);
702 throw new InternalErrorException ("Generic Type " + t
+ " doesn't have type arguments");
703 return sb
.ToString ();
706 static string RemoveGenericArity (string from)
708 int i
= from.IndexOf ('`');
710 return from.Substring (0, i
);
715 /// When we need to report accessors as well
717 static public string CSharpSignature (MethodBase mb
)
719 return CSharpSignature (mb
, false);
723 /// Returns the signature of the method
725 static public string CSharpSignature (MethodBase mb
, bool show_accessor
)
727 StringBuilder sig
= new StringBuilder (CSharpName (mb
.DeclaringType
));
730 ParameterData iparams
= GetParameterData (mb
);
731 string parameters
= iparams
.GetSignatureForError ();
732 string accessor
= "";
735 if (mb
.IsSpecialName
) {
736 Operator
.OpType ot
= Operator
.GetOperatorType (mb
.Name
);
737 if (ot
!= Operator
.OpType
.TOP
) {
738 sig
.Append ("operator ");
739 sig
.Append (Operator
.GetName (ot
));
740 sig
.Append (parameters
);
741 return sig
.ToString ();
744 if (mb
.Name
.StartsWith ("get_") || mb
.Name
.StartsWith ("set_")) {
745 accessor
= mb
.Name
.Substring (0, 3);
750 if (mb
.IsSpecialName
&& !mb
.IsConstructor
) {
751 if (iparams
.Count
> (mb
.Name
.StartsWith ("get_") ? 0 : 1)) {
752 sig
.Append ("this[");
754 sig
.Append (parameters
.Substring (1, parameters
.Length
- 2));
757 int before_ret_val
= parameters
.LastIndexOf (',');
758 if (before_ret_val
< 0)
759 sig
.Append (parameters
.Substring (1, parameters
.Length
- 2));
761 sig
.Append (parameters
.Substring (1, before_ret_val
- 1));
765 sig
.Append (mb
.Name
.Substring (4));
768 if (mb
.Name
== ".ctor")
769 sig
.Append (mb
.DeclaringType
.Name
);
771 sig
.Append (mb
.Name
);
773 if (mb
.Mono_IsInflatedMethod
|| TypeManager
.IsGenericMethod (mb
)) {
774 Type
[] args
= mb
.GetGenericArguments ();
776 for (int i
= 0; i
< args
.Length
; i
++) {
779 sig
.Append (args
[i
].Name
);
785 sig
.Append (parameters
);
788 if (show_accessor
&& accessor
.Length
> 0) {
790 sig
.Append (accessor
);
793 return sig
.ToString ();
796 public static string GetMethodName (MethodInfo m
)
798 if (!IsGenericMethod (m
))
801 return MemberName
.MakeName (m
.Name
, m
.GetGenericArguments ().Length
);
804 static public string CSharpSignature (EventInfo ei
)
806 return CSharpName (ei
.DeclaringType
) + '.' + ei
.Name
;
810 /// Looks up a type, and aborts if it is not found. This is used
811 /// by types required by the compiler
813 static Type
CoreLookupType (string ns_name
, string name
)
815 Namespace ns
= RootNamespace
.Global
.GetNamespace (ns_name
, true);
816 FullNamedExpression fne
= ns
.Lookup (RootContext
.Tree
.Types
, name
, Location
.Null
);
817 Type t
= fne
== null ? null : fne
.Type
;
819 Report
.Error (518, "The predefined type `" + name
+ "' is not defined or imported");
824 /// Returns the MethodInfo for a method named `name' defined
825 /// in type `t' which takes arguments of types `args'
827 static MethodInfo
GetMethod (Type t
, string name
, Type
[] args
, bool is_private
, bool report_errors
)
831 BindingFlags flags
= instance_and_static
| BindingFlags
.Public
;
837 flags
|= BindingFlags
.NonPublic
;
839 list
= FindMembers (t
, MemberTypes
.Method
, flags
, signature_filter
, sig
);
840 if (list
.Count
== 0) {
842 Report
.Error (-19, "Can not find the core function `" + name
+ "'");
846 MethodInfo mi
= list
[0] as MethodInfo
;
849 Report
.Error (-19, "Can not find the core function `" + name
+ "'");
856 static MethodInfo
GetMethod (Type t
, string name
, Type
[] args
, bool report_errors
)
858 return GetMethod (t
, name
, args
, false, report_errors
);
861 static MethodInfo
GetMethod (Type t
, string name
, Type
[] args
)
863 return GetMethod (t
, name
, args
, true);
867 /// Returns the PropertyInfo for a property named `name' defined
870 public static PropertyInfo
GetProperty (Type t
, string name
)
872 MemberList list
= FindMembers (t
, MemberTypes
.Property
, BindingFlags
.Public
|
873 BindingFlags
.Instance
, Type
.FilterName
, name
);
874 if (list
.Count
== 0) {
875 Report
.Error (-19, "Can not find the core property `" + name
+ "'");
879 PropertyInfo pi
= list
[0] as PropertyInfo
;
881 Report
.Error (-19, "Can not find the core function `" + name
+ "'");
889 /// Returns the ConstructorInfo for "args"
891 public static ConstructorInfo
GetConstructor (Type t
, Type
[] args
)
899 list
= FindMembers (t
, MemberTypes
.Constructor
,
900 instance_and_static
| BindingFlags
.Public
| BindingFlags
.DeclaredOnly
,
901 signature_filter
, sig
);
902 if (list
.Count
== 0){
903 Report
.Error (-19, "Can not find the core constructor for type `" + t
.Name
+ "'");
907 ConstructorInfo ci
= list
[0] as ConstructorInfo
;
909 Report
.Error (-19, "Can not find the core constructor for type `" + t
.Name
+ "'");
916 public static void InitEnumUnderlyingTypes ()
919 int32_type
= CoreLookupType ("System", "Int32");
920 int64_type
= CoreLookupType ("System", "Int64");
921 uint32_type
= CoreLookupType ("System", "UInt32");
922 uint64_type
= CoreLookupType ("System", "UInt64");
923 byte_type
= CoreLookupType ("System", "Byte");
924 sbyte_type
= CoreLookupType ("System", "SByte");
925 short_type
= CoreLookupType ("System", "Int16");
926 ushort_type
= CoreLookupType ("System", "UInt16");
930 /// The types have to be initialized after the initial
931 /// population of the type has happened (for example, to
932 /// bootstrap the corlib.dll
934 public static void InitCoreTypes ()
936 object_type
= CoreLookupType ("System", "Object");
937 value_type
= CoreLookupType ("System", "ValueType");
939 InitEnumUnderlyingTypes ();
941 char_type
= CoreLookupType ("System", "Char");
942 string_type
= CoreLookupType ("System", "String");
943 float_type
= CoreLookupType ("System", "Single");
944 double_type
= CoreLookupType ("System", "Double");
945 char_ptr_type
= GetPointerType (char_type
);
946 decimal_type
= CoreLookupType ("System", "Decimal");
947 bool_type
= CoreLookupType ("System", "Boolean");
948 enum_type
= CoreLookupType ("System", "Enum");
950 multicast_delegate_type
= CoreLookupType ("System", "MulticastDelegate");
951 delegate_type
= CoreLookupType ("System", "Delegate");
953 array_type
= CoreLookupType ("System", "Array");
954 void_type
= CoreLookupType ("System", "Void");
955 type_type
= CoreLookupType ("System", "Type");
957 runtime_field_handle_type
= CoreLookupType ("System", "RuntimeFieldHandle");
958 runtime_argument_handle_type
= CoreLookupType ("System", "RuntimeArgumentHandle");
959 runtime_helpers_type
= CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
960 default_member_type
= CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
961 runtime_handle_type
= CoreLookupType ("System", "RuntimeTypeHandle");
962 asynccallback_type
= CoreLookupType ("System", "AsyncCallback");
963 iasyncresult_type
= CoreLookupType ("System", "IAsyncResult");
964 ienumerator_type
= CoreLookupType ("System.Collections", "IEnumerator");
965 ienumerable_type
= CoreLookupType ("System.Collections", "IEnumerable");
966 idisposable_type
= CoreLookupType ("System", "IDisposable");
967 icloneable_type
= CoreLookupType ("System", "ICloneable");
968 iconvertible_type
= CoreLookupType ("System", "IConvertible");
969 monitor_type
= CoreLookupType ("System.Threading", "Monitor");
970 intptr_type
= CoreLookupType ("System", "IntPtr");
972 attribute_type
= CoreLookupType ("System", "Attribute");
973 attribute_usage_type
= CoreLookupType ("System", "AttributeUsageAttribute");
974 dllimport_type
= CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
975 methodimpl_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
976 marshal_as_attr_type
= CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
977 param_array_type
= CoreLookupType ("System", "ParamArrayAttribute");
978 in_attribute_type
= CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
979 out_attribute_type
= CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
980 typed_reference_type
= CoreLookupType ("System", "TypedReference");
981 arg_iterator_type
= CoreLookupType ("System", "ArgIterator");
982 mbr_type
= CoreLookupType ("System", "MarshalByRefObject");
983 decimal_constant_attribute_type
= CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
985 unverifiable_code_type
= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
987 void_ptr_type
= GetPointerType (void_type
);
989 indexer_name_type
= CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
991 exception_type
= CoreLookupType ("System", "Exception");
992 invalid_operation_exception_type
= CoreLookupType ("System", "InvalidOperationException");
993 not_supported_exception_type
= CoreLookupType ("System", "NotSupportedException");
998 obsolete_attribute_type
= CoreLookupType ("System", "ObsoleteAttribute");
999 conditional_attribute_type
= CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
1000 cls_compliant_attribute_type
= CoreLookupType ("System", "CLSCompliantAttribute");
1001 struct_layout_attribute_type
= CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
1002 field_offset_attribute_type
= CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
1003 security_attr_type
= CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
1004 required_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1005 guid_attr_type
= CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
1006 assembly_culture_attribute_type
= CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
1007 comimport_attr_type
= CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
1008 coclass_attr_type
= CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
1010 InitGenericCoreTypes ();
1015 compiler_generated_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1016 fixed_buffer_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1017 default_charset_type
= CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1018 internals_visible_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1019 runtime_compatibility_attr_type
= CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1021 // When compiling corlib, store the "real" types here.
1023 if (!RootContext
.StdLib
) {
1024 system_int32_type
= typeof (System
.Int32
);
1025 system_array_type
= typeof (System
.Array
);
1026 system_type_type
= typeof (System
.Type
);
1027 system_assemblybuilder_type
= typeof (System
.Reflection
.Emit
.AssemblyBuilder
);
1029 Type
[] void_arg
= { }
;
1030 system_int_array_get_length
= GetMethod (
1031 system_array_type
, "get_Length", void_arg
);
1032 system_int_array_get_rank
= GetMethod (
1033 system_array_type
, "get_Rank", void_arg
);
1034 system_object_array_clone
= GetMethod (
1035 system_array_type
, "Clone", void_arg
);
1037 Type
[] system_int_arg
= { system_int32_type }
;
1038 system_int_array_get_length_int
= GetMethod (
1039 system_array_type
, "GetLength", system_int_arg
);
1040 system_int_array_get_upper_bound_int
= GetMethod (
1041 system_array_type
, "GetUpperBound", system_int_arg
);
1042 system_int_array_get_lower_bound_int
= GetMethod (
1043 system_array_type
, "GetLowerBound", system_int_arg
);
1045 Type
[] system_array_int_arg
= { system_array_type, system_int32_type }
;
1046 system_void_array_copyto_array_int
= GetMethod (
1047 system_array_type
, "CopyTo", system_array_int_arg
);
1049 Type
[] system_3_type_arg
= {
1050 system_type_type
, system_type_type
, system_type_type
};
1051 Type
[] system_4_type_arg
= {
1052 system_type_type
, system_type_type
, system_type_type
, system_type_type
};
1054 MethodInfo set_corlib_type_builders
= GetMethod (
1055 system_assemblybuilder_type
, "SetCorlibTypeBuilders",
1056 system_4_type_arg
, true, false);
1058 if (set_corlib_type_builders
!= null) {
1059 object[] args
= new object [4];
1060 args
[0] = object_type
;
1061 args
[1] = value_type
;
1062 args
[2] = enum_type
;
1063 args
[3] = void_type
;
1065 set_corlib_type_builders
.Invoke (CodeGen
.Assembly
.Builder
, args
);
1067 // Compatibility for an older version of the class libs.
1068 set_corlib_type_builders
= GetMethod (
1069 system_assemblybuilder_type
, "SetCorlibTypeBuilders",
1070 system_3_type_arg
, true, true);
1072 if (set_corlib_type_builders
== null) {
1073 Report
.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1077 object[] args
= new object [3];
1078 args
[0] = object_type
;
1079 args
[1] = value_type
;
1080 args
[2] = enum_type
;
1082 set_corlib_type_builders
.Invoke (CodeGen
.Assembly
.Builder
, args
);
1086 system_object_expr
.Type
= object_type
;
1087 system_string_expr
.Type
= string_type
;
1088 system_boolean_expr
.Type
= bool_type
;
1089 system_decimal_expr
.Type
= decimal_type
;
1090 system_single_expr
.Type
= float_type
;
1091 system_double_expr
.Type
= double_type
;
1092 system_sbyte_expr
.Type
= sbyte_type
;
1093 system_byte_expr
.Type
= byte_type
;
1094 system_int16_expr
.Type
= short_type
;
1095 system_uint16_expr
.Type
= ushort_type
;
1096 system_int32_expr
.Type
= int32_type
;
1097 system_uint32_expr
.Type
= uint32_type
;
1098 system_int64_expr
.Type
= int64_type
;
1099 system_uint64_expr
.Type
= uint64_type
;
1100 system_char_expr
.Type
= char_type
;
1101 system_void_expr
.Type
= void_type
;
1102 system_asynccallback_expr
.Type
= asynccallback_type
;
1103 system_iasyncresult_expr
.Type
= iasyncresult_type
;
1104 system_valuetype_expr
.Type
= value_type
;
1107 // These are only used for compare purposes
1109 anonymous_method_type
= typeof (AnonymousMethod
);
1110 null_type
= typeof (NullType
);
1114 // The helper methods that are used by the compiler
1116 public static void InitCodeHelpers ()
1119 // Now load the default methods that we use.
1121 Type
[] string_string
= { string_type, string_type }
;
1122 string_concat_string_string
= GetMethod (
1123 string_type
, "Concat", string_string
);
1124 Type
[] string_string_string
= { string_type, string_type, string_type }
;
1125 string_concat_string_string_string
= GetMethod (
1126 string_type
, "Concat", string_string_string
);
1127 Type
[] string_string_string_string
= { string_type, string_type, string_type, string_type }
;
1128 string_concat_string_string_string_string
= GetMethod (
1129 string_type
, "Concat", string_string_string_string
);
1130 Type
[] params_string
= { GetConstructedType (string_type, "[]") }
;
1131 string_concat_string_dot_dot_dot
= GetMethod (
1132 string_type
, "Concat", params_string
);
1134 Type
[] object_object
= { object_type, object_type }
;
1135 string_concat_object_object
= GetMethod (
1136 string_type
, "Concat", object_object
);
1137 Type
[] object_object_object
= { object_type, object_type, object_type }
;
1138 string_concat_object_object_object
= GetMethod (
1139 string_type
, "Concat", object_object_object
);
1140 Type
[] params_object
= { GetConstructedType (object_type, "[]") }
;
1141 string_concat_object_dot_dot_dot
= GetMethod (
1142 string_type
, "Concat", params_object
);
1144 Type
[] string_
= { string_type }
;
1145 string_isinterneted_string
= GetMethod (
1146 string_type
, "IsInterned", string_
);
1148 Type
[] runtime_type_handle
= { runtime_handle_type }
;
1149 system_type_get_type_from_handle
= GetMethod (
1150 type_type
, "GetTypeFromHandle", runtime_type_handle
);
1152 Type
[] delegate_delegate
= { delegate_type, delegate_type }
;
1153 delegate_combine_delegate_delegate
= GetMethod (
1154 delegate_type
, "Combine", delegate_delegate
);
1156 delegate_remove_delegate_delegate
= GetMethod (
1157 delegate_type
, "Remove", delegate_delegate
);
1162 Type
[] void_arg
= { }
;
1163 ienumerator_getcurrent
= GetProperty (
1164 ienumerator_type
, "Current");
1165 bool_movenext_void
= GetMethod (
1166 ienumerator_type
, "MoveNext", void_arg
);
1167 void_reset_void
= GetMethod (
1168 ienumerator_type
, "Reset", void_arg
);
1169 void_dispose_void
= GetMethod (
1170 idisposable_type
, "Dispose", void_arg
);
1171 int_get_offset_to_string_data
= GetMethod (
1172 runtime_helpers_type
, "get_OffsetToStringData", void_arg
);
1173 int_array_get_length
= GetMethod (
1174 array_type
, "get_Length", void_arg
);
1175 int_array_get_rank
= GetMethod (
1176 array_type
, "get_Rank", void_arg
);
1177 ienumerable_getenumerator_void
= GetMethod (
1178 ienumerable_type
, "GetEnumerator", void_arg
);
1183 Type
[] int_arg
= { int32_type }
;
1184 int_array_get_length_int
= GetMethod (
1185 array_type
, "GetLength", int_arg
);
1186 int_array_get_upper_bound_int
= GetMethod (
1187 array_type
, "GetUpperBound", int_arg
);
1188 int_array_get_lower_bound_int
= GetMethod (
1189 array_type
, "GetLowerBound", int_arg
);
1192 // System.Array methods
1194 object_array_clone
= GetMethod (
1195 array_type
, "Clone", void_arg
);
1196 Type
[] array_int_arg
= { array_type, int32_type }
;
1197 void_array_copyto_array_int
= GetMethod (
1198 array_type
, "CopyTo", array_int_arg
);
1203 Type
[] object_arg
= { object_type }
;
1204 void_monitor_enter_object
= GetMethod (
1205 monitor_type
, "Enter", object_arg
);
1206 void_monitor_exit_object
= GetMethod (
1207 monitor_type
, "Exit", object_arg
);
1209 Type
[] array_field_handle_arg
= { array_type, runtime_field_handle_type }
;
1211 void_initializearray_array_fieldhandle
= GetMethod (
1212 runtime_helpers_type
, "InitializeArray", array_field_handle_arg
);
1217 int_getlength_int
= GetMethod (
1218 array_type
, "GetLength", int_arg
);
1221 // Decimal constructors
1223 Type
[] dec_arg
= { int32_type, int32_type, int32_type, bool_type, byte_type }
;
1224 void_decimal_ctor_five_args
= GetConstructor (
1225 decimal_type
, dec_arg
);
1227 void_decimal_ctor_int_arg
= GetConstructor (decimal_type
, int_arg
);
1232 cons_param_array_attribute
= GetConstructor (param_array_type
, void_arg
);
1233 unverifiable_code_ctor
= GetConstructor (unverifiable_code_type
, void_arg
);
1234 default_member_ctor
= GetConstructor (default_member_type
, string_
);
1236 Type
[] short_arg
= { short_type }
;
1237 struct_layout_attribute_ctor
= GetConstructor (struct_layout_attribute_type
, short_arg
);
1239 decimal_constant_attribute_ctor
= GetConstructor (decimal_constant_attribute_type
, new Type
[]
1240 { byte_type, byte_type, uint32_type, uint32_type, uint32_type }
);
1242 field_offset_attribute_ctor
= GetConstructor (field_offset_attribute_type
, new Type
[]
1248 compiler_generated_attr
= new CustomAttributeBuilder (
1249 GetConstructor (compiler_generated_attr_type
, void_arg
), new object[0]);
1251 Type
[] type_int_arg
= { type_type, int32_type }
;
1252 fixed_buffer_attr_ctor
= GetConstructor (fixed_buffer_attr_type
, type_int_arg
);
1255 object_ctor
= GetConstructor (object_type
, void_arg
);
1257 InitGenericCodeHelpers ();
1260 const BindingFlags instance_and_static
= BindingFlags
.Static
| BindingFlags
.Instance
;
1263 /// This is the "old", non-cache based FindMembers() function. We cannot use
1264 /// the cache here because there is no member name argument.
1266 public static MemberList
FindMembers (Type t
, MemberTypes mt
, BindingFlags bf
,
1267 MemberFilter filter
, object criteria
)
1269 DeclSpace decl
= (DeclSpace
) builder_to_declspace
[t
];
1272 // `builder_to_declspace' contains all dynamic types.
1276 Timer
.StartTimer (TimerType
.FindMembers
);
1277 list
= decl
.FindMembers (mt
, bf
, filter
, criteria
);
1278 Timer
.StopTimer (TimerType
.FindMembers
);
1283 // We have to take care of arrays specially, because GetType on
1284 // a TypeBuilder array will return a Type, not a TypeBuilder,
1285 // and we can not call FindMembers on this type.
1287 if (t
.IsSubclassOf (TypeManager
.array_type
))
1288 return new MemberList (TypeManager
.array_type
.FindMembers (mt
, bf
, filter
, criteria
));
1290 if (t
is GenericTypeParameterBuilder
) {
1291 TypeParameter tparam
= (TypeParameter
) builder_to_type_param
[t
];
1293 Timer
.StartTimer (TimerType
.FindMembers
);
1294 MemberList list
= tparam
.FindMembers (
1295 mt
, bf
| BindingFlags
.DeclaredOnly
, filter
, criteria
);
1296 Timer
.StopTimer (TimerType
.FindMembers
);
1301 // Since FindMembers will not lookup both static and instance
1302 // members, we emulate this behaviour here.
1304 if ((bf
& instance_and_static
) == instance_and_static
){
1305 MemberInfo
[] i_members
= t
.FindMembers (
1306 mt
, bf
& ~BindingFlags
.Static
, filter
, criteria
);
1308 int i_len
= i_members
.Length
;
1310 MemberInfo one
= i_members
[0];
1313 // If any of these are present, we are done!
1315 if ((one
is Type
) || (one
is EventInfo
) || (one
is FieldInfo
))
1316 return new MemberList (i_members
);
1319 MemberInfo
[] s_members
= t
.FindMembers (
1320 mt
, bf
& ~BindingFlags
.Instance
, filter
, criteria
);
1322 int s_len
= s_members
.Length
;
1323 if (i_len
> 0 || s_len
> 0)
1324 return new MemberList (i_members
, s_members
);
1327 return new MemberList (i_members
);
1329 return new MemberList (s_members
);
1333 return new MemberList (t
.FindMembers (mt
, bf
, filter
, criteria
));
1338 /// This method is only called from within MemberLookup. It tries to use the member
1339 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1340 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1341 /// our return value will already contain all inherited members and the caller don't need
1342 /// to check base classes and interfaces anymore.
1344 private static MemberInfo
[] MemberLookup_FindMembers (Type t
, MemberTypes mt
, BindingFlags bf
,
1345 string name
, out bool used_cache
)
1350 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1351 // and we can ask the DeclSpace for the MemberCache.
1353 if (t
is TypeBuilder
) {
1354 DeclSpace decl
= (DeclSpace
) builder_to_declspace
[t
];
1355 cache
= decl
.MemberCache
;
1358 // If this DeclSpace has a MemberCache, use it.
1361 if (cache
!= null) {
1363 return cache
.FindMembers (
1364 mt
, bf
, name
, FilterWithClosure_delegate
, null);
1367 // If there is no MemberCache, we need to use the "normal" FindMembers.
1368 // Note, this is a VERY uncommon route!
1371 Timer
.StartTimer (TimerType
.FindMembers
);
1372 list
= decl
.FindMembers (mt
, bf
| BindingFlags
.DeclaredOnly
,
1373 FilterWithClosure_delegate
, name
);
1374 Timer
.StopTimer (TimerType
.FindMembers
);
1376 return (MemberInfo
[]) list
;
1380 // We have to take care of arrays specially, because GetType on
1381 // a TypeBuilder array will return a Type, not a TypeBuilder,
1382 // and we can not call FindMembers on this type.
1384 if (t
== TypeManager
.array_type
|| t
.IsSubclassOf (TypeManager
.array_type
)) {
1386 return TypeHandle
.ArrayType
.MemberCache
.FindMembers (
1387 mt
, bf
, name
, FilterWithClosure_delegate
, null);
1390 if (t
is GenericTypeParameterBuilder
) {
1391 TypeParameter tparam
= (TypeParameter
) builder_to_type_param
[t
];
1394 Timer
.StartTimer (TimerType
.FindMembers
);
1395 list
= tparam
.FindMembers (mt
, bf
| BindingFlags
.DeclaredOnly
,
1396 FilterWithClosure_delegate
, name
);
1397 Timer
.StopTimer (TimerType
.FindMembers
);
1399 return (MemberInfo
[]) list
;
1402 if (t
.IsGenericInstance
&& (mt
== MemberTypes
.NestedType
)) {
1404 // This happens if we're resolving a class'es base class and interfaces
1405 // in TypeContainer.DefineType(). At this time, the types aren't
1406 // populated yet, so we can't use the cache.
1408 MemberInfo
[] info
= t
.FindMembers (mt
, bf
| BindingFlags
.DeclaredOnly
,
1409 FilterWithClosure_delegate
, name
);
1415 // This call will always succeed. There is exactly one TypeHandle instance per
1416 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1417 // the corresponding MemberCache.
1419 cache
= TypeHandle
.GetMemberCache (t
);
1422 return cache
.FindMembers (mt
, bf
, name
, FilterWithClosure_delegate
, null);
1425 public static bool IsBuiltinType (Type t
)
1427 t
= TypeToCoreType (t
);
1428 if (t
== object_type
|| t
== string_type
|| t
== int32_type
|| t
== uint32_type
||
1429 t
== int64_type
|| t
== uint64_type
|| t
== float_type
|| t
== double_type
||
1430 t
== char_type
|| t
== short_type
|| t
== decimal_type
|| t
== bool_type
||
1431 t
== sbyte_type
|| t
== byte_type
|| t
== ushort_type
|| t
== void_type
)
1437 public static bool IsBuiltinType (TypeContainer tc
)
1439 return IsBuiltinType (tc
.TypeBuilder
);
1443 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1444 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1446 public static bool IsPrimitiveType (Type t
)
1448 return (t
== int32_type
|| t
== uint32_type
||
1449 t
== int64_type
|| t
== uint64_type
|| t
== float_type
|| t
== double_type
||
1450 t
== char_type
|| t
== short_type
|| t
== bool_type
||
1451 t
== sbyte_type
|| t
== byte_type
|| t
== ushort_type
);
1454 public static bool IsDelegateType (Type t
)
1456 t
= DropGenericTypeArguments (t
);
1457 if (t
.IsSubclassOf (TypeManager
.delegate_type
))
1463 public static bool IsEnumType (Type t
)
1465 if (builder_to_declspace
[t
] is Enum
)
1471 public static bool IsBuiltinOrEnum (Type t
)
1473 if (IsBuiltinType (t
))
1482 public static bool IsNullType (Type t
)
1484 return t
== null_type
;
1487 public static bool IsAttributeType (Type t
)
1489 return t
== attribute_type
&& t
.BaseType
!= null || IsSubclassOf (t
, attribute_type
);
1492 static Stack unmanaged_enclosing_types
= new Stack (4);
1495 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1497 public static bool IsUnmanagedType (Type t
)
1499 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1500 if (unmanaged_enclosing_types
.Contains (t
))
1503 // builtins that are not unmanaged types
1504 if (t
== TypeManager
.object_type
|| t
== TypeManager
.string_type
)
1507 if (IsBuiltinOrEnum (t
))
1510 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1514 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1518 if (!IsValueType (t
))
1521 for (Type p
= t
.DeclaringType
; p
!= null; p
= p
.DeclaringType
) {
1522 if (p
.IsGenericTypeDefinition
)
1526 unmanaged_enclosing_types
.Push (t
);
1530 if (t
is TypeBuilder
) {
1531 TypeContainer tc
= LookupTypeContainer (t
);
1532 if (tc
.Fields
!= null){
1533 foreach (FieldMember f
in tc
.Fields
){
1534 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1535 if ((f
.ModFlags
& Modifiers
.STATIC
) != 0)
1537 if (f
.MemberType
== null)
1539 if (!IsUnmanagedType (f
.MemberType
)){
1540 Report
.SymbolRelatedToPreviousError (f
.Location
, CSharpName (t
) + "." + f
.Name
);
1546 FieldInfo
[] fields
= t
.GetFields (BindingFlags
.Public
| BindingFlags
.NonPublic
| BindingFlags
.Instance
);
1548 foreach (FieldInfo f
in fields
){
1549 if (!IsUnmanagedType (f
.FieldType
)){
1550 Report
.SymbolRelatedToPreviousError (f
);
1556 unmanaged_enclosing_types
.Pop ();
1561 public static bool IsValueType (Type t
)
1563 return t
.IsGenericParameter
|| t
.IsValueType
;
1566 public static bool IsInterfaceType (Type t
)
1568 TypeContainer tc
= (TypeContainer
) builder_to_declspace
[t
];
1572 return tc
.Kind
== Kind
.Interface
;
1575 public static bool IsSubclassOf (Type type
, Type base_type
)
1577 TypeParameter tparam
= LookupTypeParameter (type
);
1578 TypeParameter pparam
= LookupTypeParameter (base_type
);
1580 if ((tparam
!= null) && (pparam
!= null)) {
1581 if (tparam
== pparam
)
1584 return tparam
.IsSubclassOf (base_type
);
1588 if (IsEqual (type
, base_type
))
1591 type
= type
.BaseType
;
1592 } while (type
!= null);
1597 public static bool IsPrivateAccessible (Type type
, Type parent
)
1599 if (type
.Equals (parent
))
1601 return DropGenericTypeArguments (type
) == DropGenericTypeArguments (parent
);
1604 public static bool IsFamilyAccessible (Type type
, Type parent
)
1606 TypeParameter tparam
= LookupTypeParameter (type
);
1607 TypeParameter pparam
= LookupTypeParameter (parent
);
1609 if ((tparam
!= null) && (pparam
!= null)) {
1610 if (tparam
== pparam
)
1613 return tparam
.IsSubclassOf (parent
);
1617 if (IsInstantiationOfSameGenericType (type
, parent
))
1620 type
= type
.BaseType
;
1621 } while (type
!= null);
1627 // Checks whether `type' is a subclass or nested child of `base_type'.
1629 public static bool IsNestedFamilyAccessible (Type type
, Type base_type
)
1632 if (IsFamilyAccessible (type
, base_type
))
1635 // Handle nested types.
1636 type
= type
.DeclaringType
;
1637 } while (type
!= null);
1643 // Checks whether `type' is a nested child of `parent'.
1645 public static bool IsNestedChildOf (Type type
, Type parent
)
1647 if (IsEqual (type
, parent
))
1650 type
= type
.DeclaringType
;
1651 while (type
!= null) {
1652 if (IsEqual (type
, parent
))
1655 type
= type
.DeclaringType
;
1662 // Checks whether `extern_type' is friend of the output assembly
1664 public static bool IsFriendAssembly (Assembly assembly
)
1666 if (assembly_internals_vis_attrs
.Contains (assembly
))
1667 return (bool)(assembly_internals_vis_attrs
[assembly
]);
1669 object [] attrs
= assembly
.GetCustomAttributes (internals_visible_attr_type
, false);
1670 if (attrs
.Length
== 0) {
1671 assembly_internals_vis_attrs
.Add (assembly
, false);
1675 AssemblyName this_name
= CodeGen
.Assembly
.Name
;
1676 byte [] this_token
= this_name
.GetPublicKeyToken ();
1677 bool is_friend
= false;
1678 foreach (InternalsVisibleToAttribute attr
in attrs
) {
1679 if (attr
.AssemblyName
== null || attr
.AssemblyName
.Length
== 0)
1682 AssemblyName aname
= null;
1684 aname
= new AssemblyName (attr
.AssemblyName
);
1685 } catch (FileLoadException
) {
1686 } catch (ArgumentException
) {
1689 if (aname
== null || aname
.Name
!= this_name
.Name
)
1692 byte [] key_token
= aname
.GetPublicKeyToken ();
1693 if (key_token
!= null) {
1694 if (this_token
== null) {
1695 // Same name, but key token is null
1696 Error_FriendAccessNameNotMatching (aname
.FullName
);
1700 if (!CompareKeyTokens (this_token
, key_token
))
1708 assembly_internals_vis_attrs
.Add (assembly
, is_friend
);
1712 static bool CompareKeyTokens (byte [] token1
, byte [] token2
)
1714 for (int i
= 0; i
< token1
.Length
; i
++)
1715 if (token1
[i
] != token2
[i
])
1721 static void Error_FriendAccessNameNotMatching (string other_name
)
1723 Report
.Error (281, "Friend access was granted to `" + other_name
+
1724 "', but the output assembly is named `" + CodeGen
.Assembly
.Name
.FullName
+
1725 "'. Try adding a reference to `" + other_name
+
1726 "' or change the output assembly name to match it");
1730 // Do the right thing when returning the element type of an
1731 // array type based on whether we are compiling corlib or not
1733 public static Type
GetElementType (Type t
)
1735 if (RootContext
.StdLib
)
1736 return t
.GetElementType ();
1738 return TypeToCoreType (t
.GetElementType ());
1742 /// This method is not implemented by MS runtime for dynamic types
1744 public static bool HasElementType (Type t
)
1746 return t
.IsArray
|| t
.IsPointer
|| t
.IsByRef
;
1750 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1754 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1755 /// for anything which is dynamic, and we need this in a number of places,
1756 /// we register this information here, and use it afterwards.
1758 static public void RegisterMethod (MethodBase mb
, Parameters ip
)
1760 method_params
.Add (mb
, ip
);
1763 static public ParameterData
GetParameterData (MethodBase mb
)
1765 ParameterData pd
= (ParameterData
)method_params
[mb
];
1767 if (mb
is MethodBuilder
|| mb
is ConstructorBuilder
)
1768 throw new InternalErrorException ("Argument for Method not registered" + mb
);
1770 pd
= new ReflectionParameters (mb
);
1771 method_params
.Add (mb
, pd
);
1776 static public void RegisterOverride (MethodBase override_method
, MethodBase base_method
)
1778 if (!method_overrides
.Contains (override_method
))
1779 method_overrides
[override_method
] = base_method
;
1780 if (method_overrides
[override_method
] != base_method
)
1781 throw new InternalErrorException ("Override mismatch: " + override_method
);
1784 static public bool IsOverride (MethodBase m
)
1786 return m
.IsVirtual
&&
1787 (m
.Attributes
& MethodAttributes
.NewSlot
) == 0 &&
1788 (m
is MethodBuilder
|| method_overrides
.Contains (m
));
1791 static public MethodBase
TryGetBaseDefinition (MethodBase m
)
1793 return (MethodBase
) method_overrides
[m
];
1797 /// Returns the argument types for an indexer based on its PropertyInfo
1799 /// For dynamic indexers, we use the compiler provided types, for
1800 /// indexers from existing assemblies we load them from GetParameters,
1801 /// and insert them into the cache
1803 static public Type
[] GetArgumentTypes (PropertyInfo indexer
)
1805 if (indexer_arguments
.Contains (indexer
))
1806 return (Type
[]) indexer_arguments
[indexer
];
1807 else if (indexer
is PropertyBuilder
)
1808 // If we're a PropertyBuilder and not in the
1809 // `indexer_arguments' hash, then we're a property and
1813 ParameterInfo
[] pi
= indexer
.GetIndexParameters ();
1814 // Property, not an indexer.
1818 Type
[] types
= new Type
[c
];
1820 for (int i
= 0; i
< c
; i
++)
1821 types
[i
] = pi
[i
].ParameterType
;
1823 indexer_arguments
.Add (indexer
, types
);
1828 public static void RegisterConstant (FieldInfo fb
, IConstant ic
)
1830 fields
.Add (fb
, ic
);
1833 public static IConstant
GetConstant (FieldInfo fb
)
1838 return (IConstant
)fields
[fb
];
1841 static public bool RegisterFieldBase (FieldBuilder fb
, FieldBase f
)
1843 if (fieldbuilders_to_fields
.Contains (fb
))
1846 fieldbuilders_to_fields
.Add (fb
, f
);
1851 // The return value can be null; This will be the case for
1852 // auxiliary FieldBuilders created by the compiler that have no
1853 // real field being declared on the source code
1855 static public FieldBase
GetField (FieldInfo fb
)
1857 if (fb
.DeclaringType
.IsGenericInstance
)
1858 fb
= fb
.Mono_GetGenericFieldDefinition ();
1860 return (FieldBase
) fieldbuilders_to_fields
[fb
];
1863 static Hashtable events
;
1865 static public void RegisterEvent (MyEventBuilder eb
, MethodBase
add, MethodBase
remove)
1868 events
= new Hashtable ();
1870 if (!events
.Contains (eb
)) {
1871 events
.Add (eb
, new Pair (add, remove));
1875 static public MethodInfo
GetAddMethod (EventInfo ei
)
1877 if (ei
is MyEventBuilder
) {
1878 Pair pair
= (Pair
) events
[ei
];
1880 return (MethodInfo
) pair
.First
;
1882 return ei
.GetAddMethod (true);
1885 static public MethodInfo
GetRemoveMethod (EventInfo ei
)
1887 if (ei
is MyEventBuilder
) {
1888 Pair pair
= (Pair
) events
[ei
];
1890 return (MethodInfo
) pair
.Second
;
1892 return ei
.GetRemoveMethod (true);
1895 static Hashtable priv_fields_events
;
1897 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo
, FieldBuilder builder
)
1899 if (priv_fields_events
== null)
1900 priv_fields_events
= new Hashtable ();
1902 if (priv_fields_events
.Contains (einfo
))
1905 priv_fields_events
.Add (einfo
, builder
);
1910 static public MemberInfo
GetPrivateFieldOfEvent (EventInfo ei
)
1912 if (priv_fields_events
== null)
1915 return (MemberInfo
) priv_fields_events
[ei
];
1918 static public bool RegisterIndexer (PropertyBuilder pb
, MethodBase
get,
1919 MethodBase
set, Type
[] args
)
1921 indexer_arguments
.Add (pb
, args
);
1926 public static bool CheckStructCycles (TypeContainer tc
, Hashtable seen
)
1928 Hashtable hash
= new Hashtable ();
1929 return CheckStructCycles (tc
, seen
, hash
);
1932 public static bool CheckStructCycles (TypeContainer tc
, Hashtable seen
,
1935 if ((tc
.Kind
!= Kind
.Struct
) || IsBuiltinType (tc
))
1939 // `seen' contains all types we've already visited.
1941 if (seen
.Contains (tc
))
1943 seen
.Add (tc
, null);
1945 if (tc
.Fields
== null)
1948 foreach (FieldMember field
in tc
.Fields
) {
1949 if (field
.FieldBuilder
== null || field
.FieldBuilder
.IsStatic
)
1952 Type ftype
= field
.FieldBuilder
.FieldType
;
1953 TypeContainer ftc
= LookupTypeContainer (ftype
);
1957 if (hash
.Contains (ftc
)) {
1958 Report
.Error (523, tc
.Location
,
1959 "Struct member `{0}.{1}' of type `{2}' " +
1960 "causes a cycle in the struct layout",
1961 tc
.Name
, field
.Name
, ftc
.Name
);
1966 // `hash' contains all types in the current path.
1968 hash
.Add (tc
, null);
1970 bool ok
= CheckStructCycles (ftc
, seen
, hash
);
1977 if (!seen
.Contains (ftc
))
1978 seen
.Add (ftc
, null);
1985 /// Given an array of interface types, expand and eliminate repeated ocurrences
1986 /// of an interface.
1990 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1993 public static Type
[] ExpandInterfaces (EmitContext ec
, TypeExpr
[] base_interfaces
)
1995 ArrayList new_ifaces
= new ArrayList ();
1997 foreach (TypeExpr iface
in base_interfaces
){
1998 TypeExpr texpr
= iface
.ResolveAsTypeTerminal (ec
);
2002 Type itype
= texpr
.ResolveType (ec
);
2004 if (new_ifaces
.Contains (itype
))
2007 new_ifaces
.Add (itype
);
2009 Type
[] implementing
= itype
.GetInterfaces ();
2011 foreach (Type imp
in implementing
){
2012 if (!new_ifaces
.Contains (imp
))
2013 new_ifaces
.Add (imp
);
2016 Type
[] ret
= new Type
[new_ifaces
.Count
];
2017 new_ifaces
.CopyTo (ret
, 0);
2021 public static Type
[] ExpandInterfaces (Type
[] base_interfaces
)
2023 ArrayList new_ifaces
= new ArrayList ();
2025 foreach (Type itype
in base_interfaces
){
2026 if (new_ifaces
.Contains (itype
))
2029 new_ifaces
.Add (itype
);
2031 Type
[] implementing
= itype
.GetInterfaces ();
2033 foreach (Type imp
in implementing
){
2034 if (!new_ifaces
.Contains (imp
))
2035 new_ifaces
.Add (imp
);
2038 Type
[] ret
= new Type
[new_ifaces
.Count
];
2039 new_ifaces
.CopyTo (ret
, 0);
2043 static PtrHashtable iface_cache
= new PtrHashtable ();
2046 /// This function returns the interfaces in the type `t'. Works with
2047 /// both types and TypeBuilders.
2049 public static Type
[] GetInterfaces (Type t
)
2051 Type
[] cached
= iface_cache
[t
] as Type
[];
2056 // The reason for catching the Array case is that Reflection.Emit
2057 // will not return a TypeBuilder for Array types of TypeBuilder types,
2058 // but will still throw an exception if we try to call GetInterfaces
2061 // Since the array interfaces are always constant, we return those for
2066 t
= TypeManager
.array_type
;
2068 if ((t
is TypeBuilder
) || t
.IsGenericInstance
) {
2069 Type
[] base_ifaces
;
2071 if (t
.BaseType
== null)
2072 base_ifaces
= NoTypes
;
2074 base_ifaces
= GetInterfaces (t
.BaseType
);
2076 if (t
.IsGenericInstance
)
2077 type_ifaces
= t
.GetInterfaces ();
2079 type_ifaces
= (Type
[]) builder_to_ifaces
[t
];
2080 if (type_ifaces
== null)
2081 type_ifaces
= NoTypes
;
2083 int base_count
= base_ifaces
.Length
;
2084 Type
[] result
= new Type
[base_count
+ type_ifaces
.Length
];
2085 base_ifaces
.CopyTo (result
, 0);
2086 type_ifaces
.CopyTo (result
, base_count
);
2088 iface_cache
[t
] = result
;
2090 } else if (t
is GenericTypeParameterBuilder
){
2091 Type
[] type_ifaces
= (Type
[]) builder_to_ifaces
[t
];
2092 if (type_ifaces
== null)
2093 type_ifaces
= NoTypes
;
2095 iface_cache
[t
] = type_ifaces
;
2098 Type
[] ifaces
= t
.GetInterfaces ();
2099 iface_cache
[t
] = ifaces
;
2105 // gets the interfaces that are declared explicitly on t
2107 public static Type
[] GetExplicitInterfaces (TypeBuilder t
)
2109 return (Type
[]) builder_to_ifaces
[t
];
2113 /// The following is used to check if a given type implements an interface.
2114 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2116 public static bool ImplementsInterface (Type t
, Type iface
)
2121 // FIXME OPTIMIZATION:
2122 // as soon as we hit a non-TypeBuiler in the interface
2123 // chain, we could return, as the `Type.GetInterfaces'
2124 // will return all the interfaces implement by the type
2128 interfaces
= GetInterfaces (t
);
2130 if (interfaces
!= null){
2131 foreach (Type i
in interfaces
){
2138 } while (t
!= null);
2143 static NumberFormatInfo nf_provider
= CultureInfo
.CurrentCulture
.NumberFormat
;
2145 // This is a custom version of Convert.ChangeType() which works
2146 // with the TypeBuilder defined types when compiling corlib.
2147 public static object ChangeType (object value, Type conversionType
, out bool error
)
2149 IConvertible convert_value
= value as IConvertible
;
2151 if (convert_value
== null){
2157 // We must use Type.Equals() here since `conversionType' is
2158 // the TypeBuilder created version of a system type and not
2159 // the system type itself. You cannot use Type.GetTypeCode()
2160 // on such a type - it'd always return TypeCode.Object.
2164 if (conversionType
.Equals (typeof (Boolean
)))
2165 return (object)(convert_value
.ToBoolean (nf_provider
));
2166 else if (conversionType
.Equals (typeof (Byte
)))
2167 return (object)(convert_value
.ToByte (nf_provider
));
2168 else if (conversionType
.Equals (typeof (Char
)))
2169 return (object)(convert_value
.ToChar (nf_provider
));
2170 else if (conversionType
.Equals (typeof (DateTime
)))
2171 return (object)(convert_value
.ToDateTime (nf_provider
));
2172 else if (conversionType
.Equals (TypeManager
.decimal_type
)) // typeof (Decimal)))
2173 return (object)(convert_value
.ToDecimal (nf_provider
));
2174 else if (conversionType
.Equals (typeof (Double
)))
2175 return (object)(convert_value
.ToDouble (nf_provider
));
2176 else if (conversionType
.Equals (typeof (Int16
)))
2177 return (object)(convert_value
.ToInt16 (nf_provider
));
2178 else if (conversionType
.Equals (typeof (Int32
)))
2179 return (object)(convert_value
.ToInt32 (nf_provider
));
2180 else if (conversionType
.Equals (typeof (Int64
)))
2181 return (object)(convert_value
.ToInt64 (nf_provider
));
2182 else if (conversionType
.Equals (typeof (SByte
)))
2183 return (object)(convert_value
.ToSByte (nf_provider
));
2184 else if (conversionType
.Equals (typeof (Single
)))
2185 return (object)(convert_value
.ToSingle (nf_provider
));
2186 else if (conversionType
.Equals (typeof (String
)))
2187 return (object)(convert_value
.ToString (nf_provider
));
2188 else if (conversionType
.Equals (typeof (UInt16
)))
2189 return (object)(convert_value
.ToUInt16 (nf_provider
));
2190 else if (conversionType
.Equals (typeof (UInt32
)))
2191 return (object)(convert_value
.ToUInt32 (nf_provider
));
2192 else if (conversionType
.Equals (typeof (UInt64
)))
2193 return (object)(convert_value
.ToUInt64 (nf_provider
));
2194 else if (conversionType
.Equals (typeof (Object
)))
2195 return (object)(value);
2205 // This is needed, because enumerations from assemblies
2206 // do not report their underlyingtype, but they report
2209 public static Type
EnumToUnderlying (Type t
)
2211 if (t
== TypeManager
.enum_type
)
2214 t
= t
.UnderlyingSystemType
;
2215 if (!TypeManager
.IsEnumType (t
))
2218 if (t
is TypeBuilder
) {
2219 // slow path needed to compile corlib
2220 if (t
== TypeManager
.bool_type
||
2221 t
== TypeManager
.byte_type
||
2222 t
== TypeManager
.sbyte_type
||
2223 t
== TypeManager
.char_type
||
2224 t
== TypeManager
.short_type
||
2225 t
== TypeManager
.ushort_type
||
2226 t
== TypeManager
.int32_type
||
2227 t
== TypeManager
.uint32_type
||
2228 t
== TypeManager
.int64_type
||
2229 t
== TypeManager
.uint64_type
)
2232 TypeCode tc
= Type
.GetTypeCode (t
);
2235 case TypeCode
.Boolean
:
2236 return TypeManager
.bool_type
;
2238 return TypeManager
.byte_type
;
2239 case TypeCode
.SByte
:
2240 return TypeManager
.sbyte_type
;
2242 return TypeManager
.char_type
;
2243 case TypeCode
.Int16
:
2244 return TypeManager
.short_type
;
2245 case TypeCode
.UInt16
:
2246 return TypeManager
.ushort_type
;
2247 case TypeCode
.Int32
:
2248 return TypeManager
.int32_type
;
2249 case TypeCode
.UInt32
:
2250 return TypeManager
.uint32_type
;
2251 case TypeCode
.Int64
:
2252 return TypeManager
.int64_type
;
2253 case TypeCode
.UInt64
:
2254 return TypeManager
.uint64_type
;
2256 throw new Exception ("Unhandled typecode in enum " + tc
+ " from " + t
.AssemblyQualifiedName
);
2260 // When compiling corlib and called with one of the core types, return
2261 // the corresponding typebuilder for that type.
2263 public static Type
TypeToCoreType (Type t
)
2265 if (RootContext
.StdLib
|| (t
is TypeBuilder
))
2268 TypeCode tc
= Type
.GetTypeCode (t
);
2271 case TypeCode
.Boolean
:
2272 return TypeManager
.bool_type
;
2274 return TypeManager
.byte_type
;
2275 case TypeCode
.SByte
:
2276 return TypeManager
.sbyte_type
;
2278 return TypeManager
.char_type
;
2279 case TypeCode
.Int16
:
2280 return TypeManager
.short_type
;
2281 case TypeCode
.UInt16
:
2282 return TypeManager
.ushort_type
;
2283 case TypeCode
.Int32
:
2284 return TypeManager
.int32_type
;
2285 case TypeCode
.UInt32
:
2286 return TypeManager
.uint32_type
;
2287 case TypeCode
.Int64
:
2288 return TypeManager
.int64_type
;
2289 case TypeCode
.UInt64
:
2290 return TypeManager
.uint64_type
;
2291 case TypeCode
.Single
:
2292 return TypeManager
.float_type
;
2293 case TypeCode
.Double
:
2294 return TypeManager
.double_type
;
2295 case TypeCode
.String
:
2296 return TypeManager
.string_type
;
2297 case TypeCode
.Decimal
:
2298 return TypeManager
.decimal_type
;
2300 if (t
== typeof (void))
2301 return TypeManager
.void_type
;
2302 if (t
== typeof (object))
2303 return TypeManager
.object_type
;
2304 if (t
== typeof (System
.Type
))
2305 return TypeManager
.type_type
;
2306 if (t
== typeof (System
.IntPtr
))
2307 return TypeManager
.intptr_type
;
2313 /// Utility function that can be used to probe whether a type
2314 /// is managed or not.
2316 public static bool VerifyUnManaged (Type t
, Location loc
)
2318 if (IsUnmanagedType (t
))
2321 Report
.Error (208, loc
, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2328 /// Returns the name of the indexer in a given type.
2331 /// The default is not always `Item'. The user can change this behaviour by
2332 /// using the IndexerNameAttribute in the container.
2334 /// For example, the String class indexer is named `Chars' not `Item'
2336 public static string IndexerPropertyName (Type t
)
2338 t
= DropGenericTypeArguments (t
);
2339 if (t
is TypeBuilder
) {
2340 TypeContainer tc
= t
.IsInterface
? LookupInterface (t
) : LookupTypeContainer (t
);
2341 return tc
== null ? TypeContainer
.DefaultIndexerName
: tc
.IndexerName
;
2344 System
.Attribute attr
= System
.Attribute
.GetCustomAttribute (
2345 t
, TypeManager
.default_member_type
);
2347 DefaultMemberAttribute dma
= (DefaultMemberAttribute
) attr
;
2348 return dma
.MemberName
;
2351 return TypeContainer
.DefaultIndexerName
;
2354 static MethodInfo declare_local_method
= null;
2356 public static LocalBuilder
DeclareLocalPinned (ILGenerator ig
, Type t
)
2358 if (declare_local_method
== null){
2359 declare_local_method
= typeof (ILGenerator
).GetMethod (
2361 BindingFlags
.Instance
| BindingFlags
.Public
| BindingFlags
.NonPublic
,
2363 new Type
[] { typeof (Type), typeof (bool)}
,
2365 if (declare_local_method
== null){
2366 Report
.RuntimeMissingSupport (Location
.Null
, "pinned local variables");
2367 return ig
.DeclareLocal (t
);
2370 return (LocalBuilder
) declare_local_method
.Invoke (ig
, new object [] { t, true }
);
2374 // Returns whether the array of memberinfos contains the given method
2376 public static bool ArrayContainsMethod (MemberInfo
[] array
, MethodBase new_method
)
2378 Type
[] new_args
= TypeManager
.GetParameterData (new_method
).Types
;
2380 foreach (MethodBase method
in array
) {
2381 if (method
.Name
!= new_method
.Name
)
2384 if (method
is MethodInfo
&& new_method
is MethodInfo
)
2385 if (((MethodInfo
) method
).ReturnType
!= ((MethodInfo
) new_method
).ReturnType
)
2389 Type
[] old_args
= TypeManager
.GetParameterData (method
).Types
;
2390 int old_count
= old_args
.Length
;
2393 if (new_args
.Length
!= old_count
)
2396 for (i
= 0; i
< old_count
; i
++){
2397 if (old_args
[i
] != new_args
[i
])
2410 // We copy methods from `new_members' into `target_list' if the signature
2411 // for the method from in the new list does not exist in the target_list
2413 // The name is assumed to be the same.
2415 public static ArrayList
CopyNewMethods (ArrayList target_list
, IList new_members
)
2417 if (target_list
== null){
2418 target_list
= new ArrayList ();
2420 foreach (MemberInfo mi
in new_members
){
2421 if (mi
is MethodBase
)
2422 target_list
.Add (mi
);
2427 MemberInfo
[] target_array
= new MemberInfo
[target_list
.Count
];
2428 target_list
.CopyTo (target_array
, 0);
2430 foreach (MemberInfo mi
in new_members
){
2431 MethodBase new_method
= (MethodBase
) mi
;
2433 if (!ArrayContainsMethod (target_array
, new_method
))
2434 target_list
.Add (new_method
);
2439 // This method always return false for non-generic compiler,
2440 // while Type.IsGenericParameter is returned if it is supported.
2441 public static bool IsGenericParameter (Type type
)
2443 return type
.IsGenericParameter
;
2446 #region MemberLookup implementation
2449 // Whether we allow private members in the result (since FindMembers
2450 // uses NonPublic for both protected and private), we need to distinguish.
2453 static internal bool FilterNone (MemberInfo m
, object filter_criteria
)
2458 internal class Closure
{
2459 internal bool private_ok
;
2461 // Who is invoking us and which type is being queried currently.
2462 internal Type invocation_type
;
2463 internal Type qualifier_type
;
2465 // The assembly that defines the type is that is calling us
2466 internal Assembly invocation_assembly
;
2467 internal IList almost_match
;
2469 private bool CheckValidFamilyAccess (bool is_static
, MemberInfo m
)
2471 if (invocation_type
== null)
2474 if (is_static
&& qualifier_type
== null)
2475 // It resolved from a simple name, so it should be visible.
2478 // A nested class has access to all the protected members visible to its parent.
2479 if (qualifier_type
!= null && TypeManager
.IsNestedChildOf (invocation_type
, qualifier_type
))
2482 if (IsNestedFamilyAccessible (invocation_type
, m
.DeclaringType
)) {
2483 // Although a derived class can access protected members of its base class
2484 // it cannot do so through an instance of the base class (CS1540).
2485 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2487 qualifier_type
== null ||
2488 IsInstantiationOfSameGenericType (invocation_type
, qualifier_type
) ||
2489 !IsFamilyAccessible (invocation_type
, qualifier_type
) ||
2490 IsNestedChildOf (invocation_type
, qualifier_type
))
2494 if (almost_match
!= null)
2495 almost_match
.Add (m
);
2501 // This filter filters by name + whether it is ok to include private
2502 // members in the search
2504 internal bool Filter (MemberInfo m
, object filter_criteria
)
2507 // Hack: we know that the filter criteria will always be in the
2508 // `closure' // fields.
2511 if ((filter_criteria
!= null) && (m
.Name
!= (string) filter_criteria
))
2514 if (((qualifier_type
== null) || (qualifier_type
== invocation_type
)) &&
2515 (invocation_type
!= null) &&
2516 IsPrivateAccessible (m
.DeclaringType
, invocation_type
))
2520 // Ugly: we need to find out the type of `m', and depending
2521 // on this, tell whether we accept or not
2523 if (m
is MethodBase
){
2524 MethodBase mb
= (MethodBase
) m
;
2525 MethodAttributes ma
= mb
.Attributes
& MethodAttributes
.MemberAccessMask
;
2527 if (ma
== MethodAttributes
.Public
)
2530 if (ma
== MethodAttributes
.Private
)
2531 return private_ok
||
2532 IsPrivateAccessible (invocation_type
, m
.DeclaringType
) ||
2533 IsNestedChildOf (invocation_type
, m
.DeclaringType
);
2535 if (invocation_assembly
== mb
.DeclaringType
.Assembly
||
2536 TypeManager
.IsFriendAssembly (mb
.DeclaringType
.Assembly
)) {
2537 if (ma
== MethodAttributes
.Assembly
|| ma
== MethodAttributes
.FamORAssem
)
2540 if (ma
== MethodAttributes
.Assembly
|| ma
== MethodAttributes
.FamANDAssem
)
2544 // Family, FamORAssem or FamANDAssem
2545 return CheckValidFamilyAccess (mb
.IsStatic
, m
);
2548 if (m
is FieldInfo
){
2549 FieldInfo fi
= (FieldInfo
) m
;
2550 FieldAttributes fa
= fi
.Attributes
& FieldAttributes
.FieldAccessMask
;
2552 if (fa
== FieldAttributes
.Public
)
2555 if (fa
== FieldAttributes
.Private
)
2556 return private_ok
||
2557 IsPrivateAccessible (invocation_type
, m
.DeclaringType
) ||
2558 IsNestedChildOf (invocation_type
, m
.DeclaringType
);
2560 if (invocation_assembly
== fi
.DeclaringType
.Assembly
||
2561 TypeManager
.IsFriendAssembly (fi
.DeclaringType
.Assembly
)) {
2562 if (fa
== FieldAttributes
.Assembly
|| fa
== FieldAttributes
.FamORAssem
)
2565 if (fa
== FieldAttributes
.Assembly
|| fa
== FieldAttributes
.FamANDAssem
)
2569 // Family, FamORAssem or FamANDAssem
2570 return CheckValidFamilyAccess (fi
.IsStatic
, m
);
2574 // EventInfos and PropertyInfos, return true because they lack
2575 // permission information, so we need to check later on the methods.
2581 static Closure closure
= new Closure ();
2582 static MemberFilter FilterWithClosure_delegate
= new MemberFilter (closure
.Filter
);
2585 // Looks up a member called `name' in the `queried_type'. This lookup
2586 // is done by code that is contained in the definition for `invocation_type'
2587 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2589 // `invocation_type' is used to check whether we're allowed to access the requested
2590 // member wrt its protection level.
2592 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2593 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2594 // is B and qualifier_type is A). This is used to do the CS1540 check.
2596 // When resolving a SimpleName, `qualifier_type' is null.
2598 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2599 // the same than `queried_type' - except when we're being called from BaseAccess;
2600 // in this case, `invocation_type' is the current type and `queried_type' the base
2601 // type, so this'd normally trigger a CS1540.
2603 // The binding flags are `bf' and the kind of members being looked up are `mt'
2605 // The return value always includes private members which code in `invocation_type'
2606 // is allowed to access (using the specified `qualifier_type' if given); only use
2607 // BindingFlags.NonPublic to bypass the permission check.
2609 // The 'almost_match' argument is used for reporting error CS1540.
2611 // Returns an array of a single element for everything but Methods/Constructors
2612 // that might return multiple matches.
2614 public static MemberInfo
[] MemberLookup (Type invocation_type
, Type qualifier_type
,
2615 Type queried_type
, MemberTypes mt
,
2616 BindingFlags original_bf
, string name
, IList almost_match
)
2618 Timer
.StartTimer (TimerType
.MemberLookup
);
2620 MemberInfo
[] retval
= RealMemberLookup (invocation_type
, qualifier_type
,
2621 queried_type
, mt
, original_bf
, name
, almost_match
);
2623 Timer
.StopTimer (TimerType
.MemberLookup
);
2628 static MemberInfo
[] RealMemberLookup (Type invocation_type
, Type qualifier_type
,
2629 Type queried_type
, MemberTypes mt
,
2630 BindingFlags original_bf
, string name
, IList almost_match
)
2632 BindingFlags bf
= original_bf
;
2634 ArrayList method_list
= null;
2635 Type current_type
= queried_type
;
2636 bool searching
= (original_bf
& BindingFlags
.DeclaredOnly
) == 0;
2637 bool skip_iface_check
= true, used_cache
= false;
2638 bool always_ok_flag
= invocation_type
!= null && IsNestedChildOf (invocation_type
, queried_type
);
2640 closure
.invocation_type
= invocation_type
;
2641 closure
.invocation_assembly
= invocation_type
!= null ? invocation_type
.Assembly
: null;
2642 closure
.qualifier_type
= qualifier_type
;
2643 closure
.almost_match
= almost_match
;
2645 // This is from the first time we find a method
2646 // in most cases, we do not actually find a method in the base class
2647 // so we can just ignore it, and save the arraylist allocation
2648 MemberInfo
[] first_members_list
= null;
2649 bool use_first_members_list
= false;
2655 // `NonPublic' is lame, because it includes both protected and
2656 // private methods, so we need to control this behavior by
2657 // explicitly tracking if a private method is ok or not.
2659 // The possible cases are:
2660 // public, private and protected (internal does not come into the
2663 if ((invocation_type
!= null) &&
2664 ((invocation_type
== current_type
) ||
2665 IsNestedChildOf (invocation_type
, current_type
)) ||
2667 bf
= original_bf
| BindingFlags
.NonPublic
;
2671 closure
.private_ok
= (original_bf
& BindingFlags
.NonPublic
) != 0;
2673 Timer
.StopTimer (TimerType
.MemberLookup
);
2675 list
= MemberLookup_FindMembers (
2676 current_type
, mt
, bf
, name
, out used_cache
);
2678 Timer
.StartTimer (TimerType
.MemberLookup
);
2681 // When queried for an interface type, the cache will automatically check all
2682 // inherited members, so we don't need to do this here. However, this only
2683 // works if we already used the cache in the first iteration of this loop.
2685 // If we used the cache in any further iteration, we can still terminate the
2686 // loop since the cache always looks in all base classes.
2692 skip_iface_check
= false;
2694 if (current_type
== TypeManager
.object_type
)
2697 current_type
= current_type
.BaseType
;
2700 // This happens with interfaces, they have a null
2701 // basetype. Look members up in the Object class.
2703 if (current_type
== null) {
2704 current_type
= TypeManager
.object_type
;
2709 if (list
.Length
== 0)
2713 // Events and types are returned by both `static' and `instance'
2714 // searches, which means that our above FindMembers will
2715 // return two copies of the same.
2717 if (list
.Length
== 1 && !(list
[0] is MethodBase
)){
2722 // Multiple properties: we query those just to find out the indexer
2725 if (list
[0] is PropertyInfo
)
2729 // We found an event: the cache lookup returns both the event and
2730 // its private field.
2732 if (list
[0] is EventInfo
) {
2733 if ((list
.Length
== 2) && (list
[1] is FieldInfo
))
2734 return new MemberInfo
[] { list [0] }
;
2741 // We found methods, turn the search into "method scan"
2745 if (first_members_list
!= null) {
2746 if (use_first_members_list
) {
2747 method_list
= CopyNewMethods (method_list
, first_members_list
);
2748 use_first_members_list
= false;
2751 method_list
= CopyNewMethods (method_list
, list
);
2753 first_members_list
= list
;
2754 use_first_members_list
= true;
2756 mt
&= (MemberTypes
.Method
| MemberTypes
.Constructor
);
2758 } while (searching
);
2760 if (use_first_members_list
) {
2761 foreach (MemberInfo mi
in first_members_list
) {
2762 if (! (mi
is MethodBase
)) {
2763 method_list
= CopyNewMethods (method_list
, first_members_list
);
2764 return (MemberInfo
[]) method_list
.ToArray (typeof (MemberInfo
));
2767 return (MemberInfo
[]) first_members_list
;
2770 if (method_list
!= null && method_list
.Count
> 0) {
2771 return (MemberInfo
[]) method_list
.ToArray (typeof (MemberInfo
));
2774 // This happens if we already used the cache in the first iteration, in this case
2775 // the cache already looked in all interfaces.
2777 if (skip_iface_check
)
2781 // Interfaces do not list members they inherit, so we have to
2784 if (!queried_type
.IsInterface
)
2787 if (queried_type
.IsArray
)
2788 queried_type
= TypeManager
.array_type
;
2790 Type
[] ifaces
= GetInterfaces (queried_type
);
2794 foreach (Type itype
in ifaces
){
2797 x
= MemberLookup (null, null, itype
, mt
, bf
, name
, null);
2805 // Tests whether external method is really special
2806 public static bool IsSpecialMethod (MethodBase mb
)
2808 string name
= mb
.Name
;
2809 if (name
.StartsWith ("get_") || name
.StartsWith ("set_"))
2810 return mb
.DeclaringType
.GetProperty (name
.Substring (4)) != null;
2812 if (name
.StartsWith ("add_"))
2813 return mb
.DeclaringType
.GetEvent (name
.Substring (4)) != null;
2815 if (name
.StartsWith ("remove_"))
2816 return mb
.DeclaringType
.GetEvent (name
.Substring (7)) != null;
2818 if (name
.StartsWith ("op_")){
2819 foreach (string oname
in Unary
.oper_names
) {
2824 foreach (string oname
in Binary
.oper_names
) {
2837 /// There is exactly one instance of this class per type.
2839 public sealed class TypeHandle
: IMemberContainer
{
2840 public readonly IMemberContainer BaseType
;
2842 readonly int id
= ++next_id
;
2843 static int next_id
= 0;
2845 static TypeHandle ()
2851 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2852 /// a TypeHandle yet, a new instance of it is created. This static method
2853 /// ensures that we'll only have one TypeHandle instance per type.
2855 private static TypeHandle
GetTypeHandle (Type t
)
2857 TypeHandle handle
= (TypeHandle
) type_hash
[t
];
2861 handle
= new TypeHandle (t
);
2862 type_hash
.Add (t
, handle
);
2866 public static MemberCache
GetMemberCache (Type t
)
2868 return GetTypeHandle (t
).MemberCache
;
2871 public static void CleanUp ()
2876 public static void Reset ()
2878 type_hash
= new PtrHashtable ();
2882 /// Returns the TypeHandle for TypeManager.object_type.
2884 public static IMemberContainer ObjectType
{
2886 if (object_type
!= null)
2889 object_type
= GetTypeHandle (TypeManager
.object_type
);
2896 /// Returns the TypeHandle for TypeManager.array_type.
2898 public static IMemberContainer ArrayType
{
2900 if (array_type
!= null)
2903 array_type
= GetTypeHandle (TypeManager
.array_type
);
2909 private static PtrHashtable type_hash
;
2911 private static TypeHandle object_type
= null;
2912 private static TypeHandle array_type
= null;
2915 private string full_name
;
2916 private bool is_interface
;
2917 private MemberCache member_cache
;
2918 private MemberCache base_cache
;
2920 private TypeHandle (Type type
)
2923 full_name
= type
.FullName
!= null ? type
.FullName
: type
.Name
;
2924 if (type
.BaseType
!= null) {
2925 base_cache
= TypeManager
.LookupMemberCache (type
.BaseType
);
2926 BaseType
= base_cache
.Container
;
2927 } else if (type
.IsInterface
)
2928 base_cache
= TypeManager
.LookupBaseInterfacesCache (type
);
2929 this.is_interface
= type
.IsInterface
|| type
.IsGenericParameter
;
2930 this.member_cache
= new MemberCache (this);
2933 // IMemberContainer methods
2935 public string Name
{
2947 public MemberCache BaseCache
{
2953 public bool IsInterface
{
2955 return is_interface
;
2959 public MemberList
GetMembers (MemberTypes mt
, BindingFlags bf
)
2961 MemberInfo
[] members
;
2962 if (type
is GenericTypeParameterBuilder
)
2963 return MemberList
.Empty
;
2964 if (mt
== MemberTypes
.Event
)
2965 members
= type
.GetEvents (bf
| BindingFlags
.DeclaredOnly
);
2967 members
= type
.FindMembers (mt
, bf
| BindingFlags
.DeclaredOnly
,
2969 Array
.Reverse (members
);
2971 return new MemberList (members
);
2974 // IMemberFinder methods
2976 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
, string name
,
2977 MemberFilter filter
, object criteria
)
2979 return new MemberList (member_cache
.FindMembers (mt
, bf
, name
, filter
, criteria
));
2982 public MemberCache MemberCache
{
2984 return member_cache
;
2988 public override string ToString ()
2990 if (BaseType
!= null)
2991 return "TypeHandle (" + id
+ "," + Name
+ " : " + BaseType
+ ")";
2993 return "TypeHandle (" + id
+ "," + Name
+ ")";