remove NotWorking
[mcs.git] / mcs / typemanager.cs
blob01d16fb991318b68faeb1bdfd13cd1607e1c3b9b
1 //
2 // typemanager.cs: C# type manager
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2003-2008 Novell, Inc.
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
21 using System;
22 using System.IO;
23 using System.Globalization;
24 using System.Collections;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Text;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
33 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 short_type;
48 static public Type decimal_type;
49 static public Type bool_type;
50 static public Type sbyte_type;
51 static public Type byte_type;
52 static public Type ushort_type;
53 static public Type enum_type;
54 static public Type delegate_type;
55 static public Type multicast_delegate_type;
56 static public Type void_type;
57 static public Type null_type;
58 static public Type array_type;
59 static public Type runtime_handle_type;
60 static public Type type_type;
61 static public Type ienumerator_type;
62 static public Type ienumerable_type;
63 static public Type idisposable_type;
64 static public Type iasyncresult_type;
65 static public Type asynccallback_type;
66 static public Type intptr_type;
67 static public Type uintptr_type;
68 static public Type runtime_field_handle_type;
69 static public Type runtime_argument_handle_type;
70 static public Type attribute_type;
71 static public Type void_ptr_type;
72 static public Type exception_type;
74 static public Type typed_reference_type;
75 static public Type arg_iterator_type;
76 static public Type mbr_type;
77 public static Type runtime_helpers_type;
79 //
80 // C# 2.0
82 static internal Type isvolatile_type;
83 static public Type generic_ilist_type;
84 static public Type generic_icollection_type;
85 static public Type generic_ienumerator_type;
86 static public Type generic_ienumerable_type;
87 static public Type generic_nullable_type;
90 // C# 3.0
92 static internal Type expression_type;
93 public static Type parameter_expression_type;
94 public static Type fieldinfo_type;
95 public static Type methodinfo_type;
96 public static Type ctorinfo_type;
99 // C# 4.0
101 public static Type call_site_type;
102 public static Type generic_call_site_type;
103 public static TypeExpr binder_type;
104 public static Type binder_flags;
107 // Expressions representing the internal types. Used during declaration
108 // definition.
110 static public TypeExpr system_object_expr, system_string_expr;
111 static public TypeExpr system_boolean_expr, system_decimal_expr;
112 static public TypeExpr system_single_expr, system_double_expr;
113 static public TypeExpr system_sbyte_expr, system_byte_expr;
114 static public TypeExpr system_int16_expr, system_uint16_expr;
115 static public TypeExpr system_int32_expr, system_uint32_expr;
116 static public TypeExpr system_int64_expr, system_uint64_expr;
117 static public TypeExpr system_char_expr, system_void_expr;
118 static public TypeExpr system_valuetype_expr;
119 static public TypeExpr system_intptr_expr;
120 public static TypeExpr expression_type_expr;
124 // These methods are called by code generated by the compiler
126 static public FieldInfo string_empty;
127 static public MethodInfo system_type_get_type_from_handle;
128 static public MethodInfo bool_movenext_void;
129 static public MethodInfo void_dispose_void;
130 static public MethodInfo void_monitor_enter_object;
131 static public MethodInfo void_monitor_exit_object;
132 static public MethodInfo void_initializearray_array_fieldhandle;
133 static public MethodInfo delegate_combine_delegate_delegate;
134 static public MethodInfo delegate_remove_delegate_delegate;
135 static public PropertyInfo int_get_offset_to_string_data;
136 static public MethodInfo int_interlocked_compare_exchange;
137 static public PropertyInfo ienumerator_getcurrent;
138 public static MethodInfo methodbase_get_type_from_handle;
139 public static MethodInfo methodbase_get_type_from_handle_generic;
140 public static MethodInfo fieldinfo_get_field_from_handle;
141 public static MethodInfo fieldinfo_get_field_from_handle_generic;
142 static public MethodInfo activator_create_instance;
145 // The constructors.
147 static public ConstructorInfo void_decimal_ctor_five_args;
148 static public ConstructorInfo void_decimal_ctor_int_arg;
149 public static ConstructorInfo void_decimal_ctor_long_arg;
151 static PtrHashtable builder_to_declspace;
153 static PtrHashtable builder_to_member_cache;
155 // <remarks>
156 // Tracks the interfaces implemented by typebuilders. We only
157 // enter those who do implement or or more interfaces
158 // </remarks>
159 static PtrHashtable builder_to_ifaces;
161 // <remarks>
162 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
163 // <remarks>
164 static Hashtable method_params;
166 // <remarks>
167 // A hash table from override methods to their base virtual method.
168 // <remarks>
169 static Hashtable method_overrides;
171 // <remarks>
172 // Keeps track of methods
173 // </remarks>
175 static Hashtable builder_to_method;
177 // <remarks>
178 // Contains all public types from referenced assemblies.
179 // This member is used only if CLS Compliance verification is required.
180 // </remarks>
181 public static Hashtable AllClsTopLevelTypes;
183 static Hashtable fieldbuilders_to_fields;
184 static Hashtable propertybuilder_to_property;
185 static Hashtable fields;
186 static Hashtable events;
187 static PtrHashtable assembly_internals_vis_attrs;
189 public static void CleanUp ()
191 // Lets get everything clean so that we can collect before generating code
192 builder_to_declspace = null;
193 builder_to_member_cache = null;
194 builder_to_ifaces = null;
195 builder_to_type_param = null;
196 method_params = null;
197 builder_to_method = null;
199 fields = null;
200 events = null;
201 type_hash = null;
202 propertybuilder_to_property = null;
204 TypeHandle.CleanUp ();
208 // These are expressions that represent some of the internal data types, used
209 // elsewhere
211 static void InitExpressionTypes ()
213 system_object_expr = new TypeLookupExpression ("System", "Object");
214 system_string_expr = new TypeLookupExpression ("System", "String");
215 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
216 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
217 system_single_expr = new TypeLookupExpression ("System", "Single");
218 system_double_expr = new TypeLookupExpression ("System", "Double");
219 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
220 system_byte_expr = new TypeLookupExpression ("System", "Byte");
221 system_int16_expr = new TypeLookupExpression ("System", "Int16");
222 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
223 system_int32_expr = new TypeLookupExpression ("System", "Int32");
224 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
225 system_int64_expr = new TypeLookupExpression ("System", "Int64");
226 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
227 system_char_expr = new TypeLookupExpression ("System", "Char");
228 system_void_expr = new TypeLookupExpression ("System", "Void");
229 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
230 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
233 static TypeManager ()
235 Reset ();
238 static public void Reset ()
240 object_type = null;
242 InitExpressionTypes ();
244 builder_to_declspace = new PtrHashtable ();
245 builder_to_member_cache = new PtrHashtable ();
246 builder_to_method = new PtrHashtable ();
247 builder_to_type_param = new PtrHashtable ();
248 method_params = new PtrHashtable ();
249 method_overrides = new PtrHashtable ();
250 builder_to_ifaces = new PtrHashtable ();
252 fieldbuilders_to_fields = new Hashtable ();
253 propertybuilder_to_property = new Hashtable ();
254 fields = new Hashtable ();
255 type_hash = new DoubleHash ();
256 assembly_internals_vis_attrs = new PtrHashtable ();
257 iface_cache = new PtrHashtable ();
259 closure = new Closure ();
260 FilterWithClosure_delegate = new MemberFilter (closure.Filter);
262 // TODO: I am really bored by all this static stuff
263 system_type_get_type_from_handle =
264 bool_movenext_void =
265 void_dispose_void =
266 void_monitor_enter_object =
267 void_monitor_exit_object =
268 void_initializearray_array_fieldhandle =
269 delegate_combine_delegate_delegate =
270 delegate_remove_delegate_delegate =
271 int_interlocked_compare_exchange =
272 methodbase_get_type_from_handle =
273 methodbase_get_type_from_handle_generic =
274 fieldinfo_get_field_from_handle =
275 fieldinfo_get_field_from_handle_generic =
276 activator_create_instance = null;
278 int_get_offset_to_string_data =
279 ienumerator_getcurrent = null;
281 void_decimal_ctor_five_args =
282 void_decimal_ctor_int_arg =
283 void_decimal_ctor_long_arg = null;
285 isvolatile_type = null;
287 call_site_type =
288 generic_call_site_type =
289 binder_flags = null;
291 binder_type = null;
293 // to uncover regressions
294 AllClsTopLevelTypes = null;
297 public static void AddUserType (DeclSpace ds)
299 builder_to_declspace.Add (ds.TypeBuilder, ds);
303 // This entry point is used by types that we define under the covers
305 public static void RegisterBuilder (Type tb, Type [] ifaces)
307 if (ifaces != null)
308 builder_to_ifaces [tb] = ifaces;
311 public static void AddMethod (MethodBase builder, IMethodData method)
313 builder_to_method.Add (builder, method);
314 method_params.Add (builder, method.ParameterInfo);
317 public static IMethodData GetMethod (MethodBase builder)
319 return (IMethodData) builder_to_method [builder];
322 /// <summary>
323 /// Returns the DeclSpace whose Type is `t' or null if there is no
324 /// DeclSpace for `t' (ie, the Type comes from a library)
325 /// </summary>
326 public static DeclSpace LookupDeclSpace (Type t)
328 return builder_to_declspace [t] as DeclSpace;
331 /// <summary>
332 /// Returns the TypeContainer whose Type is `t' or null if there is no
333 /// TypeContainer for `t' (ie, the Type comes from a library)
334 /// </summary>
335 public static TypeContainer LookupTypeContainer (Type t)
337 return builder_to_declspace [t] as TypeContainer;
340 public static MemberCache LookupMemberCache (Type t)
342 if (IsBeingCompiled (t)) {
343 DeclSpace container = (DeclSpace)builder_to_declspace [t];
344 if (container != null)
345 return container.MemberCache;
348 if (t is GenericTypeParameterBuilder) {
349 TypeParameter container = builder_to_type_param [t] as TypeParameter;
351 if (container != null)
352 return container.MemberCache;
355 return TypeHandle.GetMemberCache (t);
358 public static MemberCache LookupBaseInterfacesCache (Type t)
360 Type [] ifaces = GetInterfaces (t);
362 if (ifaces != null && ifaces.Length == 1)
363 return LookupMemberCache (ifaces [0]);
365 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
366 MemberCache cache = builder_to_member_cache [t] as MemberCache;
367 if (cache != null)
368 return cache;
370 cache = new MemberCache (ifaces);
371 builder_to_member_cache.Add (t, cache);
372 return cache;
375 public static TypeContainer LookupInterface (Type t)
377 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
378 if ((tc == null) || (tc.Kind != Kind.Interface))
379 return null;
381 return tc;
384 public static Delegate LookupDelegate (Type t)
386 return builder_to_declspace [t] as Delegate;
389 public static Class LookupClass (Type t)
391 return (Class) builder_to_declspace [t];
395 // We use this hash for multiple kinds of constructed types:
397 // (T, "&") Given T, get T &
398 // (T, "*") Given T, get T *
399 // (T, "[]") Given T and a array dimension, get T []
400 // (T, X) Given a type T and a simple name X, get the type T+X
402 // Accessibility tests, if necessary, should be done by the user
404 static DoubleHash type_hash = new DoubleHash ();
407 // Gets the reference to T version of the Type (T&)
409 public static Type GetReferenceType (Type t)
411 return t.MakeByRefType ();
415 // Gets the pointer to T version of the Type (T*)
417 public static Type GetPointerType (Type t)
419 return GetConstructedType (t, "*");
422 public static Type GetConstructedType (Type t, string dim)
424 object ret = null;
425 if (type_hash.Lookup (t, dim, out ret))
426 return (Type) ret;
428 if (IsDynamicType (t)) {
429 ret = new DynamicArrayType (dim.Length - 1);
430 type_hash.Insert (t, dim, ret);
431 return (Type) ret;
434 ret = t.Module.GetType (t.ToString () + dim);
435 if (ret != null) {
436 type_hash.Insert (t, dim, ret);
437 return (Type) ret;
440 if (dim == "&") {
441 ret = GetReferenceType (t);
442 type_hash.Insert (t, dim, ret);
443 return (Type) ret;
446 if (t.IsGenericParameter || t.IsGenericType) {
447 int pos = 0;
448 Type result = t;
449 while ((pos < dim.Length) && (dim [pos] == '[')) {
450 pos++;
452 if (dim [pos] == ']') {
453 result = result.MakeArrayType ();
454 pos++;
456 if (pos < dim.Length)
457 continue;
459 type_hash.Insert (t, dim, result);
460 return result;
463 int rank = 0;
464 while (dim [pos] == ',') {
465 pos++; rank++;
468 if ((dim [pos] != ']') || (pos != dim.Length-1))
469 break;
471 result = result.MakeArrayType (rank + 1);
472 type_hash.Insert (t, dim, result);
473 return result;
477 type_hash.Insert (t, dim, null);
478 return null;
481 public static Type GetNestedType (Type t, string name)
483 object ret = null;
484 if (!type_hash.Lookup (t, name, out ret)) {
485 ret = t.GetNestedType (name,
486 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
487 type_hash.Insert (t, name, ret);
489 return (Type) ret;
492 /// <summary>
493 /// Fills static table with exported types from all referenced assemblies.
494 /// This information is required for CLS Compliance tests.
495 /// </summary>
496 public static void LoadAllImportedTypes ()
498 AllClsTopLevelTypes = new Hashtable (1500);
499 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
500 foreach (Type t in a.GetExportedTypes ()) {
501 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
506 /// <summary>
507 /// Returns the C# name of a type if possible, or the full type name otherwise
508 /// </summary>
509 static public string CSharpName (Type t)
511 if (t == null_type)
512 return "null";
514 if (t == typeof (ArglistAccess))
515 return "__arglist";
517 if (t == typeof (AnonymousMethodBody))
518 return "anonymous method";
520 if (t == typeof (MethodGroupExpr))
521 return "method group";
523 if (IsDynamicType (t))
524 return "dynamic";
526 if (t == null)
527 return "internal error";
529 return CSharpName (GetFullName (t), t);
532 static readonly char [] elements = new char [] { '*', '[' };
534 public static string CSharpName (string name, Type type)
536 if (name.Length > 10) {
537 string s;
538 switch (name) {
539 case "System.Int32": s = "int"; break;
540 case "System.Int64": s = "long"; break;
541 case "System.String": s = "string"; break;
542 case "System.Boolean": s = "bool"; break;
543 case "System.Void": s = "void"; break;
544 case "System.Object": s = "object"; break;
545 case "System.UInt32": s = "uint"; break;
546 case "System.Int16": s = "short"; break;
547 case "System.UInt16": s = "ushort"; break;
548 case "System.UInt64": s = "ulong"; break;
549 case "System.Single": s = "float"; break;
550 case "System.Double": s = "double"; break;
551 case "System.Decimal": s = "decimal"; break;
552 case "System.Char": s = "char"; break;
553 case "System.Byte": s = "byte"; break;
554 case "System.SByte": s = "sbyte"; break;
555 default: s = null; break;
558 if (s != null) {
560 // Predefined names can come from mscorlib only
562 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
563 return s;
565 return name;
568 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
569 return AnonymousTypeClass.SignatureForError;
571 int idx = name.IndexOfAny (elements, 10);
572 if (idx > 0)
573 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
576 return name.Replace ('+', '.');
579 static public string CSharpName (Type[] types)
581 if (types.Length == 0)
582 return string.Empty;
584 StringBuilder sb = new StringBuilder ();
585 for (int i = 0; i < types.Length; ++i) {
586 if (i > 0)
587 sb.Append (", ");
589 sb.Append (CSharpName (types [i]));
591 return sb.ToString ();
594 /// <summary>
595 /// Returns the signature of the method with full namespace classification
596 /// </summary>
597 static public string GetFullNameSignature (MemberInfo mi)
599 PropertyInfo pi = mi as PropertyInfo;
600 if (pi != null) {
601 MethodBase pmi = pi.GetGetMethod (true);
602 if (pmi == null)
603 pmi = pi.GetSetMethod (true);
604 if (GetParameterData (pmi).Count > 0)
605 mi = pmi;
607 return (mi is MethodBase)
608 ? CSharpSignature (mi as MethodBase)
609 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
612 private static int GetFullName (Type t, StringBuilder sb)
614 int pos = 0;
616 if (!t.IsGenericType) {
617 sb.Append (t.FullName);
618 return 0;
621 if (t.DeclaringType != null) {
622 pos = GetFullName (t.DeclaringType, sb);
623 sb.Append ('.');
624 } else if (t.Namespace != null && t.Namespace.Length != 0) {
625 sb.Append (t.Namespace);
626 sb.Append ('.');
628 sb.Append (RemoveGenericArity (t.Name));
630 Type[] this_args = GetTypeArguments (t);
632 if (this_args.Length < pos)
633 throw new InternalErrorException (
634 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
635 if (this_args.Length == pos)
636 return pos;
638 sb.Append ('<');
639 for (;;) {
640 sb.Append (CSharpName (this_args [pos++]));
641 if (pos == this_args.Length)
642 break;
643 sb.Append (',');
645 sb.Append ('>');
646 return pos;
649 static string GetFullName (Type t)
651 if (t.IsArray) {
652 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
653 return GetFullName (GetElementType (t)) + dimension;
656 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
657 t = TypeToCoreType (GetTypeArguments (t)[0]);
658 return CSharpName (t) + "?";
661 if (t.IsGenericParameter)
662 return t.Name;
663 if (!t.IsGenericType)
664 return t.FullName;
666 StringBuilder sb = new StringBuilder ();
667 int pos = GetFullName (t, sb);
668 if (pos <= 0)
669 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
670 return sb.ToString ();
673 public static string RemoveGenericArity (string from)
675 int i = from.IndexOf ('`');
676 if (i > 0)
677 return from.Substring (0, i);
678 return from;
681 /// <summary>
682 /// When we need to report accessors as well
683 /// </summary>
684 static public string CSharpSignature (MethodBase mb)
686 return CSharpSignature (mb, false);
689 /// <summary>
690 /// Returns the signature of the method
691 /// </summary>
692 static public string CSharpSignature (MethodBase mb, bool show_accessor)
694 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
695 sig.Append ('.');
697 AParametersCollection iparams = GetParameterData (mb);
698 string parameters = iparams.GetSignatureForError ();
699 int accessor_end = 0;
701 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
702 string op_name = Operator.GetName (mb.Name);
703 if (op_name != null) {
704 if (op_name == "explicit" || op_name == "implicit") {
705 sig.Append (op_name);
706 sig.Append (" operator ");
707 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
708 } else {
709 sig.Append ("operator ");
710 sig.Append (op_name);
712 sig.Append (parameters);
713 return sig.ToString ();
716 bool is_getter = mb.Name.StartsWith ("get_");
717 bool is_setter = mb.Name.StartsWith ("set_");
718 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
719 accessor_end = 3;
720 } else if (mb.Name.StartsWith ("remove_")) {
721 accessor_end = 6;
724 // Is indexer
725 if (iparams.Count > (is_getter ? 0 : 1)) {
726 sig.Append ("this[");
727 if (is_getter)
728 sig.Append (parameters.Substring (1, parameters.Length - 2));
729 else
730 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
731 sig.Append (']');
732 } else {
733 sig.Append (mb.Name.Substring (accessor_end + 1));
735 } else {
736 if (mb.Name == ".ctor")
737 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
738 else {
739 sig.Append (mb.Name);
741 if (IsGenericMethod (mb)) {
742 Type[] args = GetGenericArguments (mb);
743 sig.Append ('<');
744 for (int i = 0; i < args.Length; i++) {
745 if (i > 0)
746 sig.Append (',');
747 sig.Append (CSharpName (args [i]));
749 sig.Append ('>');
753 sig.Append (parameters);
756 if (show_accessor && accessor_end > 0) {
757 sig.Append ('.');
758 sig.Append (mb.Name.Substring (0, accessor_end));
761 return sig.ToString ();
764 public static string GetMethodName (MethodInfo m)
766 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
767 return m.Name;
769 return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
772 static public string CSharpSignature (EventInfo ei)
774 return CSharpName (ei.DeclaringType) + "." + ei.Name;
778 // Looks up a type, and aborts if it is not found. This is used
779 // by predefined types required by the compiler
781 public static Type CoreLookupType (CompilerContext ctx, string ns_name, string name, Kind type_kind, bool required)
783 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
784 Expression expr = ns.Lookup (ctx, name, Location.Null);
786 if (expr == null) {
787 if (required) {
788 ctx.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
789 ns_name, name);
791 return null;
794 Type t = expr.Type;
795 if (RootContext.StdLib || t == null || !required)
796 return t;
798 // TODO: All predefined imported types have to have correct signature
799 if (!IsBeingCompiled (t))
800 return t;
802 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
803 if (ds is Delegate) {
804 if (type_kind == Kind.Delegate)
805 return t;
806 } else {
807 TypeContainer tc = (TypeContainer)ds;
808 if (tc.Kind == type_kind)
809 return t;
812 ctx.Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
813 ns_name, name);
814 return null;
817 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
819 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
821 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
822 if (members != null) {
823 for (int i = 0; i < members.Length; ++i) {
824 MemberInfo member = members [i];
825 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
826 MethodBase mb = member as MethodBase;
827 if (mb == null)
828 continue;
830 AParametersCollection pd = TypeManager.GetParameterData (mb);
831 if (IsEqual (pd.Types, args))
832 return member;
834 if (mt == MemberTypes.Field) {
835 FieldInfo fi = member as FieldInfo;
836 if (fi == null)
837 continue;
839 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
840 continue;
842 return member;
845 if (mt == MemberTypes.Property) {
846 PropertyInfo pi = member as PropertyInfo;
847 if (pi == null)
848 continue;
850 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
851 continue;
853 return member;
858 string method_args = null;
859 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
860 method_args = "(" + TypeManager.CSharpName (args) + ")";
862 RootContext.ToplevelTypes.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
863 TypeManager.CSharpName (t), name, method_args);
865 return null;
869 // Returns the ConstructorInfo for "args"
871 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
873 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
877 // Returns the MethodInfo for a method named `name' defined
878 // in type `t' which takes arguments of types `args'
880 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
882 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
885 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
887 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
890 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
892 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
895 /// <remarks>
896 /// The types have to be initialized after the initial
897 /// population of the type has happened (for example, to
898 /// bootstrap the corlib.dll
899 /// </remarks>
900 public static bool InitCoreTypes (CompilerContext ctx)
902 object_type = CoreLookupType (ctx, "System", "Object", Kind.Class, true);
903 system_object_expr.Type = object_type;
904 value_type = CoreLookupType (ctx, "System", "ValueType", Kind.Class, true);
905 system_valuetype_expr.Type = value_type;
906 attribute_type = CoreLookupType (ctx, "System", "Attribute", Kind.Class, true);
908 int32_type = CoreLookupType (ctx, "System", "Int32", Kind.Struct, true);
909 system_int32_expr.Type = int32_type;
910 int64_type = CoreLookupType (ctx, "System", "Int64", Kind.Struct, true);
911 system_int64_expr.Type = int64_type;
912 uint32_type = CoreLookupType (ctx, "System", "UInt32", Kind.Struct, true);
913 system_uint32_expr.Type = uint32_type;
914 uint64_type = CoreLookupType (ctx, "System", "UInt64", Kind.Struct, true);
915 system_uint64_expr.Type = uint64_type;
916 byte_type = CoreLookupType (ctx, "System", "Byte", Kind.Struct, true);
917 system_byte_expr.Type = byte_type;
918 sbyte_type = CoreLookupType (ctx, "System", "SByte", Kind.Struct, true);
919 system_sbyte_expr.Type = sbyte_type;
920 short_type = CoreLookupType (ctx, "System", "Int16", Kind.Struct, true);
921 system_int16_expr.Type = short_type;
922 ushort_type = CoreLookupType (ctx, "System", "UInt16", Kind.Struct, true);
923 system_uint16_expr.Type = ushort_type;
925 ienumerator_type = CoreLookupType (ctx, "System.Collections", "IEnumerator", Kind.Interface, true);
926 ienumerable_type = CoreLookupType (ctx, "System.Collections", "IEnumerable", Kind.Interface, true);
927 idisposable_type = CoreLookupType (ctx, "System", "IDisposable", Kind.Interface, true);
929 // HACK: DefineType immediately resolves iterators (very wrong)
930 generic_ienumerator_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
932 char_type = CoreLookupType (ctx, "System", "Char", Kind.Struct, true);
933 system_char_expr.Type = char_type;
934 string_type = CoreLookupType (ctx, "System", "String", Kind.Class, true);
935 system_string_expr.Type = string_type;
936 float_type = CoreLookupType (ctx, "System", "Single", Kind.Struct, true);
937 system_single_expr.Type = float_type;
938 double_type = CoreLookupType (ctx, "System", "Double", Kind.Struct, true);
939 system_double_expr.Type = double_type;
940 decimal_type = CoreLookupType (ctx, "System", "Decimal", Kind.Struct, true);
941 system_decimal_expr.Type = decimal_type;
942 bool_type = CoreLookupType (ctx, "System", "Boolean", Kind.Struct, true);
943 system_boolean_expr.Type = bool_type;
944 intptr_type = CoreLookupType (ctx, "System", "IntPtr", Kind.Struct, true);
945 system_intptr_expr.Type = intptr_type;
946 uintptr_type = CoreLookupType (ctx, "System", "UIntPtr", Kind.Struct, true);
948 multicast_delegate_type = CoreLookupType (ctx, "System", "MulticastDelegate", Kind.Class, true);
949 delegate_type = CoreLookupType (ctx, "System", "Delegate", Kind.Class, true);
951 enum_type = CoreLookupType (ctx, "System", "Enum", Kind.Class, true);
952 array_type = CoreLookupType (ctx, "System", "Array", Kind.Class, true);
953 void_type = CoreLookupType (ctx, "System", "Void", Kind.Struct, true);
954 system_void_expr.Type = void_type;
955 type_type = CoreLookupType (ctx, "System", "Type", Kind.Class, true);
956 exception_type = CoreLookupType (ctx, "System", "Exception", Kind.Class, true);
958 runtime_field_handle_type = CoreLookupType (ctx, "System", "RuntimeFieldHandle", Kind.Struct, true);
959 runtime_handle_type = CoreLookupType (ctx, "System", "RuntimeTypeHandle", Kind.Struct, true);
961 PredefinedAttributes.Get.ParamArray.Resolve (false);
962 PredefinedAttributes.Get.Out.Resolve (false);
964 return ctx.Report.Errors == 0;
968 // Initializes optional core types
970 public static void InitOptionalCoreTypes (CompilerContext ctx)
973 // These are only used for compare purposes
975 null_type = typeof (NullLiteral);
977 void_ptr_type = GetPointerType (void_type);
980 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
981 // types cache with incorrect accessiblity when any of optional types is internal.
983 PredefinedAttributes.Get.Initialize ();
985 runtime_argument_handle_type = CoreLookupType (ctx, "System", "RuntimeArgumentHandle", Kind.Struct, false);
986 asynccallback_type = CoreLookupType (ctx, "System", "AsyncCallback", Kind.Delegate, false);
987 iasyncresult_type = CoreLookupType (ctx, "System", "IAsyncResult", Kind.Interface, false);
988 typed_reference_type = CoreLookupType (ctx, "System", "TypedReference", Kind.Struct, false);
989 arg_iterator_type = CoreLookupType (ctx, "System", "ArgIterator", Kind.Struct, false);
990 mbr_type = CoreLookupType (ctx, "System", "MarshalByRefObject", Kind.Class, false);
993 // Optional attributes, used for error reporting only
995 //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
996 // Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
997 // if (c != null)
998 // c.Define ();
1001 generic_ilist_type = CoreLookupType (ctx, "System.Collections.Generic", "IList`1", Kind.Interface, false);
1002 generic_icollection_type = CoreLookupType (ctx, "System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1003 generic_ienumerable_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1004 generic_nullable_type = CoreLookupType (ctx, "System", "Nullable`1", Kind.Struct, false);
1007 // Optional types which are used as types and for member lookup
1009 runtime_helpers_type = CoreLookupType (ctx, "System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1011 // New in .NET 3.5
1012 // Note: extension_attribute_type is already loaded
1013 expression_type = CoreLookupType (ctx, "System.Linq.Expressions", "Expression`1", Kind.Class, false);
1015 if (!RootContext.StdLib) {
1017 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1018 // has different predefined types and this method sets mscorlib types
1019 // to be same to avoid any type check errors.
1022 Type type = typeof (Type);
1023 Type [] system_4_type_arg = { type, type, type, type };
1025 MethodInfo set_corlib_type_builders =
1026 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1027 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1028 system_4_type_arg, null);
1030 if (set_corlib_type_builders != null) {
1031 object[] args = new object [4];
1032 args [0] = object_type;
1033 args [1] = value_type;
1034 args [2] = enum_type;
1035 args [3] = void_type;
1037 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1038 } else {
1039 ctx.Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1040 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1041 TypeManager.CSharpName (system_4_type_arg));
1046 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1048 /// <remarks>
1049 /// This is the "old", non-cache based FindMembers() function. We cannot use
1050 /// the cache here because there is no member name argument.
1051 /// </remarks>
1052 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1053 MemberFilter filter, object criteria)
1055 #if MS_COMPATIBLE
1056 if (t.IsGenericType)
1057 t = t.GetGenericTypeDefinition ();
1058 #endif
1060 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1063 // `builder_to_declspace' contains all dynamic types.
1065 if (decl != null) {
1066 MemberList list;
1067 Timer.StartTimer (TimerType.FindMembers);
1068 list = decl.FindMembers (mt, bf, filter, criteria);
1069 Timer.StopTimer (TimerType.FindMembers);
1070 return list;
1074 // We have to take care of arrays specially, because GetType on
1075 // a TypeBuilder array will return a Type, not a TypeBuilder,
1076 // and we can not call FindMembers on this type.
1078 if (
1079 #if MS_COMPATIBLE
1080 !t.IsGenericType &&
1081 #endif
1082 t.IsSubclassOf (TypeManager.array_type))
1083 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1085 if (t is GenericTypeParameterBuilder) {
1086 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1088 Timer.StartTimer (TimerType.FindMembers);
1089 MemberList list = tparam.FindMembers (
1090 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1091 Timer.StopTimer (TimerType.FindMembers);
1092 return list;
1096 // Since FindMembers will not lookup both static and instance
1097 // members, we emulate this behaviour here.
1099 if ((bf & instance_and_static) == instance_and_static){
1100 MemberInfo [] i_members = t.FindMembers (
1101 mt, bf & ~BindingFlags.Static, filter, criteria);
1103 int i_len = i_members.Length;
1104 if (i_len == 1){
1105 MemberInfo one = i_members [0];
1108 // If any of these are present, we are done!
1110 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1111 return new MemberList (i_members);
1114 MemberInfo [] s_members = t.FindMembers (
1115 mt, bf & ~BindingFlags.Instance, filter, criteria);
1117 int s_len = s_members.Length;
1118 if (i_len > 0 || s_len > 0)
1119 return new MemberList (i_members, s_members);
1120 else {
1121 if (i_len > 0)
1122 return new MemberList (i_members);
1123 else
1124 return new MemberList (s_members);
1128 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1132 /// <summary>
1133 /// This method is only called from within MemberLookup. It tries to use the member
1134 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1135 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1136 /// our return value will already contain all inherited members and the caller don't need
1137 /// to check base classes and interfaces anymore.
1138 /// </summary>
1139 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1140 string name, out bool used_cache)
1142 MemberCache cache;
1145 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1146 // and we can ask the DeclSpace for the MemberCache.
1148 #if MS_COMPATIBLE
1149 if (t.Assembly == CodeGen.Assembly.Builder) {
1150 if (t.IsGenericParameter) {
1151 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1153 used_cache = true;
1154 if (tparam.MemberCache == null)
1155 return new MemberInfo[0];
1157 return tparam.MemberCache.FindMembers (
1158 mt, bf, name, FilterWithClosure_delegate, null);
1162 // We have to take care of arrays specially, because GetType on
1163 // a TypeBuilder array will return a Type, not a TypeBuilder,
1164 // and we can not call FindMembers on this type.
1166 if (t.IsArray) {
1167 used_cache = true;
1168 return TypeHandle.ArrayType.MemberCache.FindMembers (
1169 mt, bf, name, FilterWithClosure_delegate, null);
1172 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1173 t = t.GetGenericTypeDefinition ();
1174 #else
1175 if (t is TypeBuilder) {
1176 #endif
1177 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1178 cache = decl.MemberCache;
1181 // If this DeclSpace has a MemberCache, use it.
1184 if (cache != null) {
1185 used_cache = true;
1186 return cache.FindMembers (
1187 mt, bf, name, FilterWithClosure_delegate, null);
1190 // If there is no MemberCache, we need to use the "normal" FindMembers.
1191 // Note, this is a VERY uncommon route!
1193 MemberList list;
1194 Timer.StartTimer (TimerType.FindMembers);
1195 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1196 FilterWithClosure_delegate, name);
1197 Timer.StopTimer (TimerType.FindMembers);
1198 used_cache = false;
1199 return (MemberInfo []) list;
1203 // We have to take care of arrays specially, because GetType on
1204 // a TypeBuilder array will return a Type, not a TypeBuilder,
1205 // and we can not call FindMembers on this type.
1207 if (t.IsArray) {
1208 used_cache = true;
1209 return TypeHandle.ArrayType.MemberCache.FindMembers (
1210 mt, bf, name, FilterWithClosure_delegate, null);
1213 if (t is GenericTypeParameterBuilder) {
1214 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1216 used_cache = true;
1217 if (tparam.MemberCache == null)
1218 return new MemberInfo [0];
1220 return tparam.MemberCache.FindMembers (
1221 mt, bf, name, FilterWithClosure_delegate, null);
1224 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1226 // This happens if we're resolving a class'es base class and interfaces
1227 // in TypeContainer.DefineType(). At this time, the types aren't
1228 // populated yet, so we can't use the cache.
1230 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1231 FilterWithClosure_delegate, name);
1232 used_cache = false;
1233 return info;
1237 // This call will always succeed. There is exactly one TypeHandle instance per
1238 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1239 // the corresponding MemberCache.
1241 cache = TypeHandle.GetMemberCache (t);
1243 used_cache = true;
1244 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1248 // Return true for SRE dynamic/unclosed members
1250 public static bool IsBeingCompiled (MemberInfo mi)
1252 return mi.Module.Assembly == RootContext.ToplevelTypes.Module.Assembly;
1255 public static bool IsBuiltinType (Type t)
1257 t = TypeToCoreType (t);
1258 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1259 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1260 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1261 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1262 return true;
1263 else
1264 return false;
1268 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1269 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1271 public static bool IsPrimitiveType (Type t)
1273 return (t == int32_type || t == uint32_type ||
1274 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1275 t == char_type || t == short_type || t == bool_type ||
1276 t == sbyte_type || t == byte_type || t == ushort_type);
1279 public static bool IsDelegateType (Type t)
1281 if (TypeManager.IsGenericParameter (t))
1282 return false;
1284 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1285 return false;
1287 t = DropGenericTypeArguments (t);
1288 return IsSubclassOf (t, TypeManager.delegate_type);
1292 // Is a type of dynamic type
1294 public static bool IsDynamicType (Type t)
1296 if (object.ReferenceEquals (InternalType.Dynamic, t))
1297 return true;
1299 if (t != object_type)
1300 return false;
1302 if (IsBeingCompiled (t))
1303 return false;
1305 PredefinedAttribute pa = PredefinedAttributes.Get.Dynamic;
1306 if (pa == null)
1307 return false;
1309 object[] res = t.GetCustomAttributes (pa.Type, false);
1310 return res != null && res.Length != 0;
1313 public static bool IsEnumType (Type t)
1315 t = DropGenericTypeArguments (t);
1316 return t.BaseType == TypeManager.enum_type;
1319 public static bool IsBuiltinOrEnum (Type t)
1321 if (IsBuiltinType (t))
1322 return true;
1324 if (IsEnumType (t))
1325 return true;
1327 return false;
1330 public static bool IsAttributeType (Type t)
1332 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1336 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1338 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1339 public static bool IsUnmanagedType (Type t)
1341 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1342 if (ds != null)
1343 return ds.IsUnmanagedType ();
1345 // builtins that are not unmanaged types
1346 if (t == TypeManager.object_type || t == TypeManager.string_type)
1347 return false;
1349 if (IsGenericType (t) || IsGenericParameter (t))
1350 return false;
1352 if (IsBuiltinOrEnum (t))
1353 return true;
1355 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1356 if (t.IsPointer)
1357 return IsUnmanagedType (GetElementType (t));
1359 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1360 if (t.IsArray)
1361 return false;
1363 if (!IsValueType (t))
1364 return false;
1366 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1367 if (IsGenericTypeDefinition (p))
1368 return false;
1371 bool retval = true;
1373 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1375 foreach (FieldInfo f in fields){
1376 if (!IsUnmanagedType (f.FieldType)){
1377 retval = false;
1382 return retval;
1386 // Null is considered to be a reference type
1388 public static bool IsReferenceType (Type t)
1390 if (TypeManager.IsGenericParameter (t)) {
1391 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1392 if (constraints == null)
1393 return false;
1395 return constraints.IsReferenceType;
1398 return !IsStruct (t) && !IsEnumType (t);
1401 public static bool IsValueType (Type t)
1403 if (TypeManager.IsGenericParameter (t)) {
1404 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1405 if (constraints == null)
1406 return false;
1408 return constraints.IsValueType;
1411 return IsStruct (t) || IsEnumType (t);
1414 public static bool IsStruct (Type t)
1416 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1419 public static bool IsInterfaceType (Type t)
1421 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1422 if (tc == null)
1423 return false;
1425 return tc.Kind == Kind.Interface;
1428 public static bool IsSubclassOf (Type type, Type base_type)
1430 TypeParameter tparam = LookupTypeParameter (type);
1431 TypeParameter pparam = LookupTypeParameter (base_type);
1433 if ((tparam != null) && (pparam != null)) {
1434 if (tparam == pparam)
1435 return true;
1437 return tparam.IsSubclassOf (base_type);
1440 #if MS_COMPATIBLE
1441 if (tparam != pparam)
1442 return false;
1444 if (type.IsGenericType)
1445 type = type.GetGenericTypeDefinition ();
1446 #endif
1448 if (type.IsSubclassOf (base_type))
1449 return true;
1451 do {
1452 if (IsEqual (type, base_type))
1453 return true;
1455 type = type.BaseType;
1456 } while (type != null);
1458 return false;
1461 public static bool IsPrivateAccessible (Type type, Type parent)
1463 if (type == null)
1464 return false;
1466 if (type.Equals (parent))
1467 return true;
1469 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1472 public static bool IsFamilyAccessible (Type type, Type parent)
1474 TypeParameter tparam = LookupTypeParameter (type);
1475 TypeParameter pparam = LookupTypeParameter (parent);
1477 if ((tparam != null) && (pparam != null)) {
1478 if (tparam == pparam)
1479 return true;
1481 return tparam.IsSubclassOf (parent);
1484 do {
1485 if (IsInstantiationOfSameGenericType (type, parent))
1486 return true;
1488 type = type.BaseType;
1489 } while (type != null);
1491 return false;
1495 // Checks whether `type' is a subclass or nested child of `base_type'.
1497 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1499 do {
1500 if (IsFamilyAccessible (type, base_type))
1501 return true;
1503 // Handle nested types.
1504 type = type.DeclaringType;
1505 } while (type != null);
1507 return false;
1511 // Checks whether `type' is a nested child of `parent'.
1513 public static bool IsNestedChildOf (Type type, Type parent)
1515 if (type == null)
1516 return false;
1518 type = DropGenericTypeArguments (type);
1519 parent = DropGenericTypeArguments (parent);
1521 if (IsEqual (type, parent))
1522 return false;
1524 type = type.DeclaringType;
1525 while (type != null) {
1526 if (IsEqual (type, parent))
1527 return true;
1529 type = type.DeclaringType;
1532 return false;
1535 public static bool IsSpecialType (Type t)
1537 return t == arg_iterator_type || t == typed_reference_type;
1541 // Checks whether `invocationAssembly' is same or a friend of the assembly
1543 public static bool IsThisOrFriendAssembly (Assembly invocationAssembly, Assembly assembly)
1545 if (assembly == null)
1546 throw new ArgumentNullException ("assembly");
1548 // TODO: This can happen for constants used at assembly level and
1549 // predefined members
1550 // But there is no way to test for it for now, so it could be abused
1551 // elsewhere too.
1552 if (invocationAssembly == null)
1553 invocationAssembly = CodeGen.Assembly.Builder;
1555 if (invocationAssembly == assembly)
1556 return true;
1558 if (assembly_internals_vis_attrs.Contains (assembly))
1559 return (bool)(assembly_internals_vis_attrs [assembly]);
1561 PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
1562 // HACK: Do very early resolve of SRE type checking
1563 if (pa.Type == null)
1564 pa.Resolve (true);
1566 if (!pa.IsDefined)
1567 return false;
1569 object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
1570 if (attrs.Length == 0) {
1571 assembly_internals_vis_attrs.Add (assembly, false);
1572 return false;
1575 bool is_friend = false;
1577 AssemblyName this_name = CodeGen.Assembly.Name;
1578 byte [] this_token = this_name.GetPublicKeyToken ();
1579 foreach (InternalsVisibleToAttribute attr in attrs) {
1580 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1581 continue;
1583 AssemblyName aname = null;
1584 try {
1585 aname = new AssemblyName (attr.AssemblyName);
1586 } catch (FileLoadException) {
1587 } catch (ArgumentException) {
1590 if (aname == null || aname.Name != this_name.Name)
1591 continue;
1593 byte [] key_token = aname.GetPublicKeyToken ();
1594 if (key_token != null) {
1595 if (this_token.Length == 0) {
1596 // Same name, but assembly is not strongnamed
1597 Error_FriendAccessNameNotMatching (aname.FullName, RootContext.ToplevelTypes.Compiler.Report);
1598 break;
1601 if (!CompareKeyTokens (this_token, key_token))
1602 continue;
1605 is_friend = true;
1606 break;
1609 assembly_internals_vis_attrs.Add (assembly, is_friend);
1610 return is_friend;
1613 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1615 for (int i = 0; i < token1.Length; i++)
1616 if (token1 [i] != token2 [i])
1617 return false;
1619 return true;
1622 static void Error_FriendAccessNameNotMatching (string other_name, Report Report)
1624 Report.Error (281,
1625 "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
1626 other_name, CodeGen.Assembly.Name.FullName);
1630 // Do the right thing when returning the element type of an
1631 // array type based on whether we are compiling corlib or not
1633 public static Type GetElementType (Type t)
1635 if (RootContext.StdLib)
1636 return t.GetElementType ();
1637 else
1638 return TypeToCoreType (t.GetElementType ());
1641 /// <summary>
1642 /// This method is not implemented by MS runtime for dynamic types
1643 /// </summary>
1644 public static bool HasElementType (Type t)
1646 return t.IsArray || t.IsPointer || t.IsByRef;
1649 public static Type GetEnumUnderlyingType (Type t)
1651 t = DropGenericTypeArguments (t);
1652 Enum e = LookupTypeContainer (t) as Enum;
1653 if (e != null)
1654 return e.UnderlyingType;
1656 // TODO: cache it ?
1657 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1658 if (fi == null)
1659 return TypeManager.int32_type;
1661 return TypeToCoreType (fi.FieldType);
1664 /// <summary>
1665 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1666 /// </summary>
1668 /// <remarks>
1669 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1670 /// for anything which is dynamic, and we need this in a number of places,
1671 /// we register this information here, and use it afterwards.
1672 /// </remarks>
1673 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1675 method_params.Add (mb, ip);
1678 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1680 method_params.Add (pb, p);
1683 static public AParametersCollection GetParameterData (MethodBase mb)
1685 AParametersCollection pd = (AParametersCollection) method_params [mb];
1686 if (pd == null) {
1687 #if MS_COMPATIBLE
1688 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1689 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1690 pd = GetParameterData (mi);
1692 if (mi.IsGenericMethod)
1693 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1694 else
1695 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1697 method_params.Add (mb, pd);
1698 return pd;
1701 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1702 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1703 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1706 pd = ParametersImported.Create (mb);
1707 #else
1708 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1709 if (generic != mb) {
1710 pd = TypeManager.GetParameterData (generic);
1711 pd = ParametersImported.Create (pd, mb);
1712 } else {
1713 pd = ParametersImported.Create (mb);
1715 #endif
1716 method_params.Add (mb, pd);
1718 return pd;
1721 public static AParametersCollection GetParameterData (PropertyInfo pi)
1723 AParametersCollection pd = (AParametersCollection)method_params [pi];
1724 if (pd == null) {
1725 if (pi is PropertyBuilder)
1726 return ParametersCompiled.EmptyReadOnlyParameters;
1728 ParameterInfo [] p = pi.GetIndexParameters ();
1729 if (p == null)
1730 return ParametersCompiled.EmptyReadOnlyParameters;
1732 pd = ParametersImported.Create (p, null);
1733 method_params.Add (pi, pd);
1736 return pd;
1739 public static AParametersCollection GetDelegateParameters (ResolveContext ec, Type t)
1741 Delegate d = builder_to_declspace [t] as Delegate;
1742 if (d != null)
1743 return d.Parameters;
1745 MethodInfo invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, t, t);
1746 return GetParameterData (invoke_mb);
1749 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1751 if (!method_overrides.Contains (override_method))
1752 method_overrides [override_method] = base_method;
1753 if (method_overrides [override_method] != base_method)
1754 throw new InternalErrorException ("Override mismatch: " + override_method);
1757 static public bool IsOverride (MethodBase m)
1759 m = DropGenericMethodArguments (m);
1761 return m.IsVirtual &&
1762 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1763 (m is MethodBuilder || method_overrides.Contains (m));
1766 static public MethodBase TryGetBaseDefinition (MethodBase m)
1768 m = DropGenericMethodArguments (m);
1770 return (MethodBase) method_overrides [m];
1773 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1775 fields.Add (fb, ic);
1778 public static IConstant GetConstant (FieldInfo fb)
1780 if (fb == null)
1781 return null;
1783 return (IConstant)fields [fb];
1786 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1788 propertybuilder_to_property.Add (pi, pb);
1791 public static PropertyBase GetProperty (PropertyInfo pi)
1793 return (PropertyBase)propertybuilder_to_property [pi];
1796 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1798 fieldbuilders_to_fields.Add (fb, f);
1802 // The return value can be null; This will be the case for
1803 // auxiliary FieldBuilders created by the compiler that have no
1804 // real field being declared on the source code
1806 static public FieldBase GetField (FieldInfo fb)
1808 fb = GetGenericFieldDefinition (fb);
1809 return (FieldBase) fieldbuilders_to_fields [fb];
1812 static public MethodInfo GetAddMethod (EventInfo ei)
1814 if (ei is MyEventBuilder) {
1815 return ((MyEventBuilder)ei).GetAddMethod (true);
1817 return ei.GetAddMethod (true);
1820 static public MethodInfo GetRemoveMethod (EventInfo ei)
1822 if (ei is MyEventBuilder) {
1823 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1825 return ei.GetRemoveMethod (true);
1828 static public void RegisterEventField (EventInfo einfo, EventField e)
1830 if (events == null)
1831 events = new Hashtable ();
1833 events.Add (einfo, e);
1836 static public EventField GetEventField (EventInfo ei)
1838 if (events == null)
1839 return null;
1841 return (EventField) events [ei];
1844 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1846 Hashtable hash = new Hashtable ();
1847 return CheckStructCycles (tc, seen, hash);
1850 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1851 Hashtable hash)
1853 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1854 return true;
1857 // `seen' contains all types we've already visited.
1859 if (seen.Contains (tc))
1860 return true;
1861 seen.Add (tc, null);
1863 if (tc.Fields == null)
1864 return true;
1866 foreach (FieldBase field in tc.Fields) {
1867 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1868 continue;
1870 Type ftype = field.FieldBuilder.FieldType;
1871 TypeContainer ftc = LookupTypeContainer (ftype);
1872 if (ftc == null)
1873 continue;
1875 if (hash.Contains (ftc)) {
1876 RootContext.ToplevelTypes.Compiler.Report.Error (523, tc.Location,
1877 "Struct member `{0}.{1}' of type `{2}' " +
1878 "causes a cycle in the struct layout",
1879 tc.Name, field.Name, ftc.Name);
1880 return false;
1884 // `hash' contains all types in the current path.
1886 hash.Add (tc, null);
1888 bool ok = CheckStructCycles (ftc, seen, hash);
1890 hash.Remove (tc);
1892 if (!ok)
1893 return false;
1895 if (!seen.Contains (ftc))
1896 seen.Add (ftc, null);
1899 return true;
1902 /// <summary>
1903 /// Given an array of interface types, expand and eliminate repeated ocurrences
1904 /// of an interface.
1905 /// </summary>
1907 /// <remarks>
1908 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1909 /// be IA, IB, IC.
1910 /// </remarks>
1911 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1913 ArrayList new_ifaces = new ArrayList ();
1915 foreach (TypeExpr iface in base_interfaces){
1916 Type itype = iface.Type;
1918 if (new_ifaces.Contains (itype))
1919 continue;
1921 new_ifaces.Add (itype);
1923 Type [] implementing = GetInterfaces (itype);
1925 foreach (Type imp in implementing){
1926 if (!new_ifaces.Contains (imp))
1927 new_ifaces.Add (imp);
1930 Type [] ret = new Type [new_ifaces.Count];
1931 new_ifaces.CopyTo (ret, 0);
1932 return ret;
1935 public static Type[] ExpandInterfaces (Type [] base_interfaces)
1937 ArrayList new_ifaces = new ArrayList ();
1939 foreach (Type itype in base_interfaces){
1940 if (new_ifaces.Contains (itype))
1941 continue;
1943 new_ifaces.Add (itype);
1945 Type [] implementing = GetInterfaces (itype);
1947 foreach (Type imp in implementing){
1948 if (!new_ifaces.Contains (imp))
1949 new_ifaces.Add (imp);
1952 Type [] ret = new Type [new_ifaces.Count];
1953 new_ifaces.CopyTo (ret, 0);
1954 return ret;
1957 static PtrHashtable iface_cache;
1959 /// <summary>
1960 /// This function returns the interfaces in the type `t'. Works with
1961 /// both types and TypeBuilders.
1962 /// </summary>
1963 public static Type [] GetInterfaces (Type t)
1965 Type [] cached = iface_cache [t] as Type [];
1966 if (cached != null)
1967 return cached;
1970 // The reason for catching the Array case is that Reflection.Emit
1971 // will not return a TypeBuilder for Array types of TypeBuilder types,
1972 // but will still throw an exception if we try to call GetInterfaces
1973 // on the type.
1975 // Since the array interfaces are always constant, we return those for
1976 // the System.Array
1979 if (t.IsArray)
1980 t = TypeManager.array_type;
1982 if ((t is TypeBuilder) || IsGenericType (t)) {
1983 Type [] base_ifaces;
1985 if (t.BaseType == null)
1986 base_ifaces = Type.EmptyTypes;
1987 else
1988 base_ifaces = GetInterfaces (t.BaseType);
1989 Type[] type_ifaces;
1990 if (IsGenericType (t))
1991 #if MS_COMPATIBLE
1992 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
1993 #else
1994 type_ifaces = t.GetInterfaces ();
1995 #endif
1996 else
1997 type_ifaces = (Type []) builder_to_ifaces [t];
1998 if (type_ifaces == null || type_ifaces.Length == 0)
1999 type_ifaces = Type.EmptyTypes;
2001 int base_count = base_ifaces.Length;
2002 Type [] result = new Type [base_count + type_ifaces.Length];
2003 base_ifaces.CopyTo (result, 0);
2004 type_ifaces.CopyTo (result, base_count);
2006 iface_cache [t] = result;
2007 return result;
2008 } else if (t is GenericTypeParameterBuilder){
2009 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2010 if (type_ifaces == null || type_ifaces.Length == 0)
2011 type_ifaces = Type.EmptyTypes;
2013 iface_cache [t] = type_ifaces;
2014 return type_ifaces;
2015 } else {
2016 Type[] ifaces = t.GetInterfaces ();
2017 iface_cache [t] = ifaces;
2018 return ifaces;
2023 // gets the interfaces that are declared explicitly on t
2025 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2027 return (Type []) builder_to_ifaces [t];
2030 /// <remarks>
2031 /// The following is used to check if a given type implements an interface.
2032 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2033 /// </remarks>
2034 public static bool ImplementsInterface (Type t, Type iface)
2036 Type [] interfaces;
2039 // FIXME OPTIMIZATION:
2040 // as soon as we hit a non-TypeBuiler in the interface
2041 // chain, we could return, as the `Type.GetInterfaces'
2042 // will return all the interfaces implement by the type
2043 // or its bases.
2045 do {
2046 interfaces = GetInterfaces (t);
2048 if (interfaces != null){
2049 foreach (Type i in interfaces){
2050 if (i == iface || IsVariantOf (i, iface))
2051 return true;
2055 t = t.BaseType;
2056 } while (t != null);
2058 return false;
2061 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2063 // This is a custom version of Convert.ChangeType() which works
2064 // with the TypeBuilder defined types when compiling corlib.
2065 public static object ChangeType (object value, Type conversionType, out bool error)
2067 IConvertible convert_value = value as IConvertible;
2069 if (convert_value == null){
2070 error = true;
2071 return null;
2075 // NOTE 1:
2076 // We must use Type.Equals() here since `conversionType' is
2077 // the TypeBuilder created version of a system type and not
2078 // the system type itself. You cannot use Type.GetTypeCode()
2079 // on such a type - it'd always return TypeCode.Object.
2081 // NOTE 2:
2082 // We cannot rely on build-in type conversions as they are
2083 // more limited than what C# supports.
2084 // See char -> float/decimal/double conversion
2087 error = false;
2088 try {
2089 if (conversionType.Equals (typeof (Boolean)))
2090 return (object)(convert_value.ToBoolean (nf_provider));
2091 if (conversionType.Equals (typeof (Byte)))
2092 return (object)(convert_value.ToByte (nf_provider));
2093 if (conversionType.Equals (typeof (Char)))
2094 return (object)(convert_value.ToChar (nf_provider));
2095 if (conversionType.Equals (typeof (DateTime)))
2096 return (object)(convert_value.ToDateTime (nf_provider));
2098 if (conversionType.Equals (decimal_type)) {
2099 if (convert_value.GetType () == TypeManager.char_type)
2100 return (decimal)convert_value.ToInt32 (nf_provider);
2101 return convert_value.ToDecimal (nf_provider);
2104 if (conversionType.Equals (typeof (Double))) {
2105 if (convert_value.GetType () == TypeManager.char_type)
2106 return (double)convert_value.ToInt32 (nf_provider);
2107 return convert_value.ToDouble (nf_provider);
2110 if (conversionType.Equals (typeof (Int16)))
2111 return (object)(convert_value.ToInt16 (nf_provider));
2112 if (conversionType.Equals (int32_type))
2113 return (object)(convert_value.ToInt32 (nf_provider));
2114 if (conversionType.Equals (int64_type))
2115 return (object)(convert_value.ToInt64 (nf_provider));
2116 if (conversionType.Equals (typeof (SByte)))
2117 return (object)(convert_value.ToSByte (nf_provider));
2119 if (conversionType.Equals (typeof (Single))) {
2120 if (convert_value.GetType () == TypeManager.char_type)
2121 return (float)convert_value.ToInt32 (nf_provider);
2122 return convert_value.ToSingle (nf_provider);
2125 if (conversionType.Equals (typeof (String)))
2126 return (object)(convert_value.ToString (nf_provider));
2127 if (conversionType.Equals (typeof (UInt16)))
2128 return (object)(convert_value.ToUInt16 (nf_provider));
2129 if (conversionType.Equals (typeof (UInt32)))
2130 return (object)(convert_value.ToUInt32 (nf_provider));
2131 if (conversionType.Equals (typeof (UInt64)))
2132 return (object)(convert_value.ToUInt64 (nf_provider));
2133 if (conversionType.Equals (typeof (Object)))
2134 return (object)(value);
2135 else
2136 error = true;
2137 } catch {
2138 error = true;
2140 return null;
2144 // When compiling with -nostdlib and the type is imported from an external assembly
2145 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2147 public static Type TypeToCoreType (Type t)
2149 if (RootContext.StdLib || t.Module != typeof (object).Module)
2150 return t;
2152 // TODO: GetTypeCode returns underlying type for enums !!
2153 TypeCode tc = Type.GetTypeCode (t);
2155 switch (tc){
2156 case TypeCode.Boolean:
2157 return TypeManager.bool_type;
2158 case TypeCode.Byte:
2159 return TypeManager.byte_type;
2160 case TypeCode.SByte:
2161 return TypeManager.sbyte_type;
2162 case TypeCode.Char:
2163 return TypeManager.char_type;
2164 case TypeCode.Int16:
2165 return TypeManager.short_type;
2166 case TypeCode.UInt16:
2167 return TypeManager.ushort_type;
2168 case TypeCode.Int32:
2169 return TypeManager.int32_type;
2170 case TypeCode.UInt32:
2171 return TypeManager.uint32_type;
2172 case TypeCode.Int64:
2173 return TypeManager.int64_type;
2174 case TypeCode.UInt64:
2175 return TypeManager.uint64_type;
2176 case TypeCode.Single:
2177 return TypeManager.float_type;
2178 case TypeCode.Double:
2179 return TypeManager.double_type;
2180 case TypeCode.String:
2181 return TypeManager.string_type;
2182 case TypeCode.Decimal:
2183 return TypeManager.decimal_type;
2186 if (t == typeof (void))
2187 return TypeManager.void_type;
2188 if (t == typeof (object))
2189 return TypeManager.object_type;
2190 if (t == typeof (System.Type))
2191 return TypeManager.type_type;
2192 if (t == typeof (System.IntPtr))
2193 return TypeManager.intptr_type;
2194 if (t == typeof (System.UIntPtr))
2195 return TypeManager.uintptr_type;
2197 if (t.IsArray) {
2198 int dim = t.GetArrayRank ();
2199 t = GetElementType (t);
2200 return t.MakeArrayType (dim);
2202 if (t.IsByRef) {
2203 t = GetElementType (t);
2204 return t.MakeByRefType ();
2206 if (t.IsPointer) {
2207 t = GetElementType (t);
2208 return t.MakePointerType ();
2211 return t;
2215 // Converts any type to reflection supported type
2217 public static Type TypeToReflectionType (Type type)
2219 // TODO: Very lame and painful, GetReference () is enough for mcs-cecil
2220 if (IsDynamicType (type))
2221 return object_type;
2223 if (type is DynamicArrayType)
2224 return type.UnderlyingSystemType;
2226 return type;
2229 /// <summary>
2230 /// Utility function that can be used to probe whether a type
2231 /// is managed or not.
2232 /// </summary>
2233 public static bool VerifyUnManaged (Type t, Location loc)
2235 if (IsUnmanagedType (t))
2236 return true;
2238 while (t.IsPointer)
2239 t = GetElementType (t);
2241 RootContext.ToplevelTypes.Compiler.Report.SymbolRelatedToPreviousError (t);
2242 RootContext.ToplevelTypes.Compiler.Report.Error (208, loc,
2243 "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2244 CSharpName (t));
2246 return false;
2249 /// <summary>
2250 /// Returns the name of the indexer in a given type.
2251 /// </summary>
2252 /// <remarks>
2253 /// The default is not always `Item'. The user can change this behaviour by
2254 /// using the IndexerNameAttribute in the container.
2255 /// For example, the String class indexer is named `Chars' not `Item'
2256 /// </remarks>
2257 public static string IndexerPropertyName (Type t)
2259 t = DropGenericTypeArguments (t);
2260 if (t is TypeBuilder) {
2261 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2262 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2265 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
2266 if (pa.IsDefined) {
2267 System.Attribute attr = System.Attribute.GetCustomAttribute (
2268 t, pa.Type);
2269 if (attr != null) {
2270 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2271 return dma.MemberName;
2275 return TypeContainer.DefaultIndexerName;
2278 static MethodInfo declare_local_method = null;
2280 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2282 if (declare_local_method == null){
2283 declare_local_method = typeof (ILGenerator).GetMethod (
2284 "DeclareLocal",
2285 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2286 null,
2287 new Type [] { typeof (Type), typeof (bool)},
2288 null);
2289 if (declare_local_method == null){
2290 RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2291 return ig.DeclareLocal (t);
2294 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2297 private static bool IsSignatureEqual (Type a, Type b)
2300 /// Consider the following example (bug #77674):
2302 /// public abstract class A
2303 /// {
2304 /// public abstract T Foo<T> ();
2305 /// }
2307 /// public abstract class B : A
2308 /// {
2309 /// public override U Foo<T> ()
2310 /// { return default (U); }
2311 /// }
2313 /// Here, `T' and `U' are method type parameters from different methods
2314 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2316 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2317 /// we need to do a signature based comparision and consider them equal.
2319 if (a == b)
2320 return true;
2322 if (a.IsGenericParameter && b.IsGenericParameter &&
2323 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2324 return a.GenericParameterPosition == b.GenericParameterPosition;
2327 if (a.IsArray && b.IsArray) {
2328 if (a.GetArrayRank () != b.GetArrayRank ())
2329 return false;
2331 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2334 if (a.IsByRef && b.IsByRef)
2335 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2337 if (IsGenericType (a) && IsGenericType (b)) {
2338 if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
2339 return false;
2341 Type[] aargs = GetTypeArguments (a);
2342 Type[] bargs = GetTypeArguments (b);
2344 if (aargs.Length != bargs.Length)
2345 return false;
2347 for (int i = 0; i < aargs.Length; i++) {
2348 if (!IsSignatureEqual (aargs [i], bargs [i]))
2349 return false;
2352 return true;
2355 return false;
2359 // Returns whether the array of memberinfos contains the given method
2361 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2363 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2365 foreach (MethodBase method in array) {
2366 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2367 continue;
2369 if (method.Name != new_method.Name)
2370 continue;
2372 if (method is MethodInfo && new_method is MethodInfo &&
2373 !IsSignatureEqual (
2374 TypeToCoreType (((MethodInfo) method).ReturnType),
2375 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2376 continue;
2378 Type [] old_args = TypeManager.GetParameterData (method).Types;
2379 int old_count = old_args.Length;
2380 int i;
2382 if (new_args.Length != old_count)
2383 continue;
2385 for (i = 0; i < old_count; i++){
2386 if (!IsSignatureEqual (old_args [i], new_args [i]))
2387 break;
2389 if (i != old_count)
2390 continue;
2392 return true;
2395 return false;
2399 // We copy methods from `new_members' into `target_list' if the signature
2400 // for the method from in the new list does not exist in the target_list
2402 // The name is assumed to be the same.
2404 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2406 if (target_list == null){
2407 target_list = new ArrayList ();
2409 foreach (MemberInfo mi in new_members){
2410 if (mi is MethodBase)
2411 target_list.Add (mi);
2413 return target_list;
2416 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2417 target_list.CopyTo (target_array, 0);
2419 foreach (MemberInfo mi in new_members){
2420 MethodBase new_method = (MethodBase) mi;
2422 if (!ArrayContainsMethod (target_array, new_method, true))
2423 target_list.Add (new_method);
2425 return target_list;
2428 #region Generics
2429 // <remarks>
2430 // Tracks the generic parameters.
2431 // </remarks>
2432 static PtrHashtable builder_to_type_param;
2434 public static void AddTypeParameter (Type t, TypeParameter tparam)
2436 if (!builder_to_type_param.Contains (t))
2437 builder_to_type_param.Add (t, tparam);
2440 public static TypeParameter LookupTypeParameter (Type t)
2442 return (TypeParameter) builder_to_type_param [t];
2445 // This method always return false for non-generic compiler,
2446 // while Type.IsGenericParameter is returned if it is supported.
2447 public static bool IsGenericParameter (Type type)
2449 return type.IsGenericParameter;
2452 public static int GenericParameterPosition (Type type)
2454 return type.GenericParameterPosition;
2457 public static bool IsGenericType (Type type)
2459 return type.IsGenericType;
2462 public static bool IsGenericTypeDefinition (Type type)
2464 return type.IsGenericTypeDefinition;
2467 public static bool ContainsGenericParameters (Type type)
2469 return type.ContainsGenericParameters;
2472 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2474 if (fi.DeclaringType.IsGenericTypeDefinition ||
2475 !fi.DeclaringType.IsGenericType)
2476 return fi;
2478 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2479 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2480 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2482 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2483 foreach (FieldInfo f in t.GetFields (bf))
2484 if (f.MetadataToken == fi.MetadataToken)
2485 return f;
2487 return fi;
2490 public static bool IsEqual (Type a, Type b)
2492 if (a.Equals (b)) {
2493 // MS BCL returns true even if enum types are different
2494 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2495 return a.FullName == b.FullName;
2497 // Some types are never equal
2498 if (a == TypeManager.null_type || a == InternalType.AnonymousMethod)
2499 return false;
2501 return true;
2504 if (IsGenericParameter (a) && IsGenericParameter (b)) {
2505 // TODO: needs more testing before cleaning up
2506 //if (a.DeclaringMethod != b.DeclaringMethod &&
2507 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2508 // return false;
2509 return a.GenericParameterPosition == b.GenericParameterPosition;
2512 if (a.IsArray && b.IsArray) {
2513 if (a.GetArrayRank () != b.GetArrayRank ())
2514 return false;
2515 return IsEqual (GetElementType (a), GetElementType (b));
2518 if (a.IsByRef && b.IsByRef)
2519 return IsEqual (a.GetElementType (), b.GetElementType ());
2521 if (IsGenericType (a) && IsGenericType (b)) {
2522 Type adef = DropGenericTypeArguments (a);
2523 Type bdef = DropGenericTypeArguments (b);
2525 if (adef != bdef)
2526 return false;
2528 if (adef.IsEnum && bdef.IsEnum)
2529 return true;
2531 Type[] aargs = GetTypeArguments (a);
2532 Type[] bargs = GetTypeArguments (b);
2534 if (aargs.Length != bargs.Length)
2535 return false;
2537 for (int i = 0; i < aargs.Length; i++) {
2538 if (!IsEqual (aargs [i], bargs [i]))
2539 return false;
2542 return true;
2545 return false;
2548 public static bool IsEqual (Type[] a, Type[] b)
2550 if (a == null || b == null || a.Length != b.Length)
2551 return false;
2553 for (int i = 0; i < a.Length; ++i) {
2554 if (a [i] == null || b [i] == null) {
2555 if (a [i] == b [i])
2556 continue;
2558 return false;
2561 if (!IsEqual (a [i], b [i]))
2562 return false;
2565 return true;
2568 public static Type DropGenericTypeArguments (Type t)
2570 if (!t.IsGenericType)
2571 return t;
2572 // Micro-optimization: a generic typebuilder is always a generic type definition
2573 if (t is TypeBuilder)
2574 return t;
2575 return t.GetGenericTypeDefinition ();
2578 public static MethodBase DropGenericMethodArguments (MethodBase m)
2580 if (m.IsGenericMethod)
2581 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2583 Type t = m.DeclaringType;
2584 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2585 return m;
2587 t = t.GetGenericTypeDefinition ();
2588 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2589 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2591 #if MS_COMPATIBLE
2592 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2593 return m;
2594 #endif
2596 if (m is ConstructorInfo) {
2597 foreach (ConstructorInfo c in t.GetConstructors (bf))
2598 if (c.MetadataToken == m.MetadataToken)
2599 return c;
2600 } else {
2601 foreach (MethodBase mb in t.GetMethods (bf))
2602 if (mb.MetadataToken == m.MetadataToken)
2603 return mb;
2606 return m;
2609 public static Type[] GetGenericArguments (MethodBase mi)
2611 return mi.GetGenericArguments () ?? Type.EmptyTypes;
2614 public static Type[] GetTypeArguments (Type t)
2616 DeclSpace tc = LookupDeclSpace (t);
2617 if (tc != null) {
2618 if (!tc.IsGeneric)
2619 return Type.EmptyTypes;
2621 TypeParameter[] tparam = tc.TypeParameters;
2622 Type[] ret = new Type [tparam.Length];
2623 for (int i = 0; i < tparam.Length; i++) {
2624 ret [i] = tparam [i].Type;
2625 if (ret [i] == null)
2626 throw new InternalErrorException ();
2629 return ret;
2630 } else
2631 return t.GetGenericArguments ();
2634 public static GenericConstraints GetTypeParameterConstraints (Type t)
2636 if (!t.IsGenericParameter)
2637 throw new InvalidOperationException ();
2639 TypeParameter tparam = LookupTypeParameter (t);
2640 if (tparam != null)
2641 return tparam.GenericConstraints;
2643 return ReflectionConstraints.GetConstraints (t);
2646 public static bool HasGenericArguments (Type t)
2648 return GetNumberOfTypeArguments (t) > 0;
2651 public static int GetNumberOfTypeArguments (Type t)
2653 if (t.IsGenericParameter)
2654 return 0;
2655 DeclSpace tc = LookupDeclSpace (t);
2656 if (tc != null)
2657 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2658 else
2659 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2662 /// <summary>
2663 /// Check whether `type' and `parent' are both instantiations of the same
2664 /// generic type. Note that we do not check the type parameters here.
2665 /// </summary>
2666 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2668 int tcount = GetNumberOfTypeArguments (type);
2669 int pcount = GetNumberOfTypeArguments (parent);
2671 if (tcount != pcount)
2672 return false;
2674 type = DropGenericTypeArguments (type);
2675 parent = DropGenericTypeArguments (parent);
2677 return type.Equals (parent);
2680 /// <summary>
2681 /// Whether `mb' is a generic method definition.
2682 /// </summary>
2683 public static bool IsGenericMethodDefinition (MethodBase mb)
2685 if (mb.DeclaringType is TypeBuilder) {
2686 IMethodData method = (IMethodData) builder_to_method [mb];
2687 if (method == null)
2688 return false;
2690 return method.GenericMethod != null;
2693 return mb.IsGenericMethodDefinition;
2696 /// <summary>
2697 /// Whether `mb' is a generic method.
2698 /// </summary>
2699 public static bool IsGenericMethod (MethodBase mb)
2701 return mb.IsGenericMethod;
2704 public static bool IsNullableType (Type t)
2706 return generic_nullable_type == DropGenericTypeArguments (t);
2708 #endregion
2710 #region MemberLookup implementation
2713 // Whether we allow private members in the result (since FindMembers
2714 // uses NonPublic for both protected and private), we need to distinguish.
2717 internal class Closure {
2718 internal bool private_ok;
2720 // Who is invoking us and which type is being queried currently.
2721 internal Type invocation_type;
2722 internal Type qualifier_type;
2724 // The assembly that defines the type is that is calling us
2725 internal Assembly invocation_assembly;
2726 internal IList almost_match;
2728 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2730 if (invocation_type == null)
2731 return false;
2733 if (is_static && qualifier_type == null)
2734 // It resolved from a simple name, so it should be visible.
2735 return true;
2737 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2738 return true;
2740 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2741 if (!IsFamilyAccessible (t, m.DeclaringType))
2742 continue;
2744 // Although a derived class can access protected members of its base class
2745 // it cannot do so through an instance of the base class (CS1540).
2746 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2747 if (is_static || qualifier_type == null ||
2748 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2749 IsFamilyAccessible (qualifier_type, t))
2750 return true;
2753 if (almost_match != null)
2754 almost_match.Add (m);
2756 return false;
2760 // This filter filters by name + whether it is ok to include private
2761 // members in the search
2763 internal bool Filter (MemberInfo m, object filter_criteria)
2766 // Hack: we know that the filter criteria will always be in the
2767 // `closure' // fields.
2770 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2771 return false;
2773 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2774 (invocation_type != null) &&
2775 IsPrivateAccessible (m.DeclaringType, invocation_type))
2776 return true;
2779 // Ugly: we need to find out the type of `m', and depending
2780 // on this, tell whether we accept or not
2782 if (m is MethodBase){
2783 MethodBase mb = (MethodBase) m;
2784 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2786 if (ma == MethodAttributes.Public)
2787 return true;
2789 if (ma == MethodAttributes.PrivateScope)
2790 return false;
2792 if (ma == MethodAttributes.Private)
2793 return private_ok ||
2794 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2795 IsNestedChildOf (invocation_type, m.DeclaringType);
2797 if (TypeManager.IsThisOrFriendAssembly (invocation_assembly, mb.DeclaringType.Assembly)) {
2798 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2799 return true;
2800 } else {
2801 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2802 return false;
2805 // Family, FamORAssem or FamANDAssem
2806 return CheckValidFamilyAccess (mb.IsStatic, m);
2809 if (m is FieldInfo){
2810 FieldInfo fi = (FieldInfo) m;
2811 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2813 if (fa == FieldAttributes.Public)
2814 return true;
2816 if (fa == FieldAttributes.PrivateScope)
2817 return false;
2819 if (fa == FieldAttributes.Private)
2820 return private_ok ||
2821 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2822 IsNestedChildOf (invocation_type, m.DeclaringType);
2824 if (TypeManager.IsThisOrFriendAssembly (invocation_assembly, fi.DeclaringType.Assembly)) {
2825 if ((fa == FieldAttributes.Assembly) ||
2826 (fa == FieldAttributes.FamORAssem))
2827 return true;
2828 } else {
2829 if ((fa == FieldAttributes.Assembly) ||
2830 (fa == FieldAttributes.FamANDAssem))
2831 return false;
2834 // Family, FamORAssem or FamANDAssem
2835 return CheckValidFamilyAccess (fi.IsStatic, m);
2839 // EventInfos and PropertyInfos, return true because they lack
2840 // permission information, so we need to check later on the methods.
2842 return true;
2846 static Closure closure;
2847 static MemberFilter FilterWithClosure_delegate;
2850 // Looks up a member called `name' in the `queried_type'. This lookup
2851 // is done by code that is contained in the definition for `invocation_type'
2852 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2854 // `invocation_type' is used to check whether we're allowed to access the requested
2855 // member wrt its protection level.
2857 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2858 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2859 // is B and qualifier_type is A). This is used to do the CS1540 check.
2861 // When resolving a SimpleName, `qualifier_type' is null.
2863 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2864 // the same than `queried_type' - except when we're being called from BaseAccess;
2865 // in this case, `invocation_type' is the current type and `queried_type' the base
2866 // type, so this'd normally trigger a CS1540.
2868 // The binding flags are `bf' and the kind of members being looked up are `mt'
2870 // The return value always includes private members which code in `invocation_type'
2871 // is allowed to access (using the specified `qualifier_type' if given); only use
2872 // BindingFlags.NonPublic to bypass the permission check.
2874 // The 'almost_match' argument is used for reporting error CS1540.
2876 // Returns an array of a single element for everything but Methods/Constructors
2877 // that might return multiple matches.
2879 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2880 Type queried_type, MemberTypes mt,
2881 BindingFlags original_bf, string name, IList almost_match)
2883 Timer.StartTimer (TimerType.MemberLookup);
2885 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2886 queried_type, mt, original_bf, name, almost_match);
2888 Timer.StopTimer (TimerType.MemberLookup);
2890 return retval;
2893 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2894 Type queried_type, MemberTypes mt,
2895 BindingFlags original_bf, string name, IList almost_match)
2897 BindingFlags bf = original_bf;
2899 ArrayList method_list = null;
2900 Type current_type = queried_type;
2901 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2902 bool skip_iface_check = true, used_cache = false;
2903 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2905 closure.invocation_type = invocation_type;
2906 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2907 closure.qualifier_type = qualifier_type;
2908 closure.almost_match = almost_match;
2910 // This is from the first time we find a method
2911 // in most cases, we do not actually find a method in the base class
2912 // so we can just ignore it, and save the arraylist allocation
2913 MemberInfo [] first_members_list = null;
2914 bool use_first_members_list = false;
2916 do {
2917 MemberInfo [] list;
2920 // `NonPublic' is lame, because it includes both protected and
2921 // private methods, so we need to control this behavior by
2922 // explicitly tracking if a private method is ok or not.
2924 // The possible cases are:
2925 // public, private and protected (internal does not come into the
2926 // equation)
2928 if ((invocation_type != null) &&
2929 ((invocation_type == current_type) ||
2930 IsNestedChildOf (invocation_type, current_type)) ||
2931 always_ok_flag)
2932 bf = original_bf | BindingFlags.NonPublic;
2933 else
2934 bf = original_bf;
2936 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2938 Timer.StopTimer (TimerType.MemberLookup);
2940 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2942 Timer.StartTimer (TimerType.MemberLookup);
2945 // When queried for an interface type, the cache will automatically check all
2946 // inherited members, so we don't need to do this here. However, this only
2947 // works if we already used the cache in the first iteration of this loop.
2949 // If we used the cache in any further iteration, we can still terminate the
2950 // loop since the cache always looks in all base classes.
2953 if (used_cache)
2954 searching = false;
2955 else
2956 skip_iface_check = false;
2958 if (current_type == TypeManager.object_type)
2959 searching = false;
2960 else {
2961 current_type = current_type.BaseType;
2964 // This happens with interfaces, they have a null
2965 // basetype. Look members up in the Object class.
2967 if (current_type == null) {
2968 current_type = TypeManager.object_type;
2969 searching = true;
2973 if (list.Length == 0)
2974 continue;
2977 // Events and types are returned by both `static' and `instance'
2978 // searches, which means that our above FindMembers will
2979 // return two copies of the same.
2981 if (list.Length == 1 && !(list [0] is MethodBase)){
2982 return list;
2986 // Multiple properties: we query those just to find out the indexer
2987 // name
2989 if (list [0] is PropertyInfo)
2990 return list;
2993 // We found an event: the cache lookup returns both the event and
2994 // its private field.
2996 if (list [0] is EventInfo) {
2997 if ((list.Length == 2) && (list [1] is FieldInfo))
2998 return new MemberInfo [] { list [0] };
3000 return list;
3004 // We found methods, turn the search into "method scan"
3005 // mode.
3008 if (first_members_list != null) {
3009 if (use_first_members_list) {
3010 method_list = CopyNewMethods (method_list, first_members_list);
3011 use_first_members_list = false;
3014 method_list = CopyNewMethods (method_list, list);
3015 } else {
3016 first_members_list = list;
3017 use_first_members_list = true;
3018 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3020 } while (searching);
3022 if (use_first_members_list)
3023 return first_members_list;
3025 if (method_list != null && method_list.Count > 0) {
3026 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3029 // This happens if we already used the cache in the first iteration, in this case
3030 // the cache already looked in all interfaces.
3032 if (skip_iface_check)
3033 return null;
3036 // Interfaces do not list members they inherit, so we have to
3037 // scan those.
3039 if (!queried_type.IsInterface)
3040 return null;
3042 if (queried_type.IsArray)
3043 queried_type = TypeManager.array_type;
3045 Type [] ifaces = GetInterfaces (queried_type);
3046 if (ifaces == null)
3047 return null;
3049 foreach (Type itype in ifaces){
3050 MemberInfo [] x;
3052 x = MemberLookup (null, null, itype, mt, bf, name, null);
3053 if (x != null)
3054 return x;
3057 return null;
3060 public const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3061 BindingFlags.Static | BindingFlags.Instance |
3062 BindingFlags.DeclaredOnly;
3064 // Currently is designed to work with external types only
3065 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3067 if (!mb.IsSpecialName)
3068 return null;
3070 string name = mb.Name;
3071 if (name.Length < 5)
3072 return null;
3074 if (name [3] != '_')
3075 return null;
3077 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3078 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3079 Type.FilterName, name.Substring (4));
3081 if (pi == null)
3082 return null;
3084 // This can happen when property is indexer (it can have same name but different parameters)
3085 foreach (PropertyInfo p in pi) {
3086 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3087 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3088 return p;
3093 return null;
3096 // Currently is designed to work with external types only
3097 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3099 if (!mb.IsSpecialName)
3100 return null;
3102 string name = mb.Name;
3103 if (name.Length < 5)
3104 return null;
3106 if (name.StartsWith ("add_"))
3107 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3109 if (name.StartsWith ("remove_"))
3110 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3112 return null;
3115 // Tests whether external method is really special
3116 public static bool IsSpecialMethod (MethodBase mb)
3118 if (!mb.IsSpecialName)
3119 return false;
3121 IMethodData md = TypeManager.GetMethod (mb);
3122 if (md != null)
3123 return (md is AbstractPropertyEventMethod || md is Operator);
3125 PropertyInfo pi = GetPropertyFromAccessor (mb);
3126 if (pi != null)
3127 return IsValidProperty (pi);
3129 if (GetEventFromAccessor (mb) != null)
3130 return true;
3132 string name = mb.Name;
3133 if (name.StartsWith ("op_"))
3134 return Operator.GetName (name) != null;
3136 return false;
3139 // Tests whether imported property is valid C# property.
3140 // TODO: It seems to me that we should do a lot of sanity tests before
3141 // we accept property as C# property
3142 static bool IsValidProperty (PropertyInfo pi)
3144 MethodInfo get_method = pi.GetGetMethod (true);
3145 MethodInfo set_method = pi.GetSetMethod (true);
3146 int g_count = 0;
3147 int s_count = 0;
3148 if (get_method != null && set_method != null) {
3149 g_count = get_method.GetParameters ().Length;
3150 s_count = set_method.GetParameters ().Length;
3151 if (g_count + 1 != s_count)
3152 return false;
3153 } else if (get_method != null) {
3154 g_count = get_method.GetParameters ().Length;
3155 } else if (set_method != null) {
3156 s_count = set_method.GetParameters ().Length;
3160 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3162 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
3163 if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
3164 object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
3165 if (o.Length == 0)
3166 return false;
3168 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3169 if (dma.MemberName != pi.Name)
3170 return false;
3171 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3172 return false;
3173 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3174 return false;
3177 return true;
3180 #endregion
3184 class InternalType
3186 public static readonly Type AnonymousMethod = typeof (AnonymousMethodBody);
3187 public static readonly Type Arglist = typeof (ArglistAccess);
3188 public static readonly Type Dynamic = new DynamicType ();
3189 public static readonly Type MethodGroup = typeof (MethodGroupExpr);
3192 /// <summary>
3193 /// There is exactly one instance of this class per type.
3194 /// </summary>
3195 public sealed class TypeHandle : IMemberContainer {
3196 public readonly IMemberContainer BaseType;
3198 readonly int id = ++next_id;
3199 static int next_id = 0;
3201 static TypeHandle ()
3203 Reset ();
3206 /// <summary>
3207 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3208 /// a TypeHandle yet, a new instance of it is created. This static method
3209 /// ensures that we'll only have one TypeHandle instance per type.
3210 /// </summary>
3211 private static TypeHandle GetTypeHandle (Type t)
3213 TypeHandle handle = (TypeHandle) type_hash [t];
3214 if (handle != null)
3215 return handle;
3217 handle = new TypeHandle (t);
3218 type_hash.Add (t, handle);
3219 return handle;
3222 public static MemberCache GetMemberCache (Type t)
3224 return GetTypeHandle (t).MemberCache;
3227 public static void CleanUp ()
3229 type_hash = null;
3232 public static void Reset ()
3234 type_hash = new PtrHashtable ();
3237 /// <summary>
3238 /// Returns the TypeHandle for TypeManager.object_type.
3239 /// </summary>
3240 public static IMemberContainer ObjectType {
3241 get {
3242 if (object_type != null)
3243 return object_type;
3245 object_type = GetTypeHandle (TypeManager.object_type);
3247 return object_type;
3251 /// <summary>
3252 /// Returns the TypeHandle for TypeManager.array_type.
3253 /// </summary>
3254 public static TypeHandle ArrayType {
3255 get {
3256 if (array_type != null)
3257 return array_type;
3259 array_type = GetTypeHandle (TypeManager.array_type);
3261 return array_type;
3265 private static PtrHashtable type_hash;
3267 private static TypeHandle object_type = null;
3268 private static TypeHandle array_type = null;
3270 private Type type;
3271 private string full_name;
3272 private bool is_interface;
3273 private MemberCache member_cache;
3274 private MemberCache base_cache;
3276 private TypeHandle (Type type)
3278 this.type = type;
3279 full_name = type.FullName != null ? type.FullName : type.Name;
3280 if (type.BaseType != null) {
3281 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3282 BaseType = base_cache.Container;
3283 } else if (type.IsInterface)
3284 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3285 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3286 this.member_cache = new MemberCache (this);
3289 // IMemberContainer methods
3291 public string Name {
3292 get {
3293 return full_name;
3297 public Type Type {
3298 get {
3299 return type;
3303 public MemberCache BaseCache {
3304 get {
3305 return base_cache;
3309 public bool IsInterface {
3310 get {
3311 return is_interface;
3315 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3317 MemberInfo [] members;
3319 if (type is GenericTypeParameterBuilder)
3320 return MemberList.Empty;
3322 #if MS_COMPATIBLE
3323 type = TypeManager.DropGenericTypeArguments (type);
3324 #endif
3325 if (mt == MemberTypes.Event)
3326 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3327 else
3328 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3329 null, null);
3331 if (members.Length == 0)
3332 return MemberList.Empty;
3334 Array.Reverse (members);
3335 return new MemberList (members);
3338 // IMemberFinder methods
3340 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3341 MemberFilter filter, object criteria)
3343 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3346 public MemberCache MemberCache {
3347 get {
3348 return member_cache;
3352 public override string ToString ()
3354 if (BaseType != null)
3355 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3356 else
3357 return "TypeHandle (" + id + "," + Name + ")";