2009-07-28 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / typemanager.cs
blob64c08f1faae3c6ec07d32ebfd6031bbafb2c380f
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;
96 // C# 4.0
98 public static Type call_site_type;
99 public static Type generic_call_site_type;
102 // Expressions representing the internal types. Used during declaration
103 // definition.
105 static public TypeExpr system_object_expr, system_string_expr;
106 static public TypeExpr system_boolean_expr, system_decimal_expr;
107 static public TypeExpr system_single_expr, system_double_expr;
108 static public TypeExpr system_sbyte_expr, system_byte_expr;
109 static public TypeExpr system_int16_expr, system_uint16_expr;
110 static public TypeExpr system_int32_expr, system_uint32_expr;
111 static public TypeExpr system_int64_expr, system_uint64_expr;
112 static public TypeExpr system_char_expr, system_void_expr;
113 static public TypeExpr system_valuetype_expr;
114 static public TypeExpr system_intptr_expr;
115 public static TypeExpr expression_type_expr;
119 // These methods are called by code generated by the compiler
121 static public FieldInfo string_empty;
122 static public MethodInfo system_type_get_type_from_handle;
123 static public MethodInfo bool_movenext_void;
124 static public MethodInfo void_dispose_void;
125 static public MethodInfo void_monitor_enter_object;
126 static public MethodInfo void_monitor_exit_object;
127 static public MethodInfo void_initializearray_array_fieldhandle;
128 static public MethodInfo delegate_combine_delegate_delegate;
129 static public MethodInfo delegate_remove_delegate_delegate;
130 static public PropertyInfo int_get_offset_to_string_data;
131 static public MethodInfo int_interlocked_compare_exchange;
132 static public PropertyInfo ienumerator_getcurrent;
133 public static MethodInfo methodbase_get_type_from_handle;
134 public static MethodInfo methodbase_get_type_from_handle_generic;
135 public static MethodInfo fieldinfo_get_field_from_handle;
136 static public MethodInfo activator_create_instance;
139 // The constructors.
141 static public ConstructorInfo void_decimal_ctor_five_args;
142 static public ConstructorInfo void_decimal_ctor_int_arg;
144 static PtrHashtable builder_to_declspace;
146 static PtrHashtable builder_to_member_cache;
148 // <remarks>
149 // Tracks the interfaces implemented by typebuilders. We only
150 // enter those who do implement or or more interfaces
151 // </remarks>
152 static PtrHashtable builder_to_ifaces;
154 // <remarks>
155 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
156 // <remarks>
157 static Hashtable method_params;
159 // <remarks>
160 // A hash table from override methods to their base virtual method.
161 // <remarks>
162 static Hashtable method_overrides;
164 // <remarks>
165 // Keeps track of methods
166 // </remarks>
168 static Hashtable builder_to_method;
170 // <remarks>
171 // Contains all public types from referenced assemblies.
172 // This member is used only if CLS Compliance verification is required.
173 // </remarks>
174 public static Hashtable AllClsTopLevelTypes;
176 static Hashtable fieldbuilders_to_fields;
177 static Hashtable propertybuilder_to_property;
178 static Hashtable fields;
179 static Hashtable events;
180 static PtrHashtable assembly_internals_vis_attrs;
182 public static void CleanUp ()
184 // Lets get everything clean so that we can collect before generating code
185 builder_to_declspace = null;
186 builder_to_member_cache = null;
187 builder_to_ifaces = null;
188 builder_to_type_param = null;
189 method_params = null;
190 builder_to_method = null;
192 fields = null;
193 events = null;
194 type_hash = null;
195 propertybuilder_to_property = null;
197 TypeHandle.CleanUp ();
201 // These are expressions that represent some of the internal data types, used
202 // elsewhere
204 static void InitExpressionTypes ()
206 system_object_expr = new TypeLookupExpression ("System", "Object");
207 system_string_expr = new TypeLookupExpression ("System", "String");
208 system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
209 system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
210 system_single_expr = new TypeLookupExpression ("System", "Single");
211 system_double_expr = new TypeLookupExpression ("System", "Double");
212 system_sbyte_expr = new TypeLookupExpression ("System", "SByte");
213 system_byte_expr = new TypeLookupExpression ("System", "Byte");
214 system_int16_expr = new TypeLookupExpression ("System", "Int16");
215 system_uint16_expr = new TypeLookupExpression ("System", "UInt16");
216 system_int32_expr = new TypeLookupExpression ("System", "Int32");
217 system_uint32_expr = new TypeLookupExpression ("System", "UInt32");
218 system_int64_expr = new TypeLookupExpression ("System", "Int64");
219 system_uint64_expr = new TypeLookupExpression ("System", "UInt64");
220 system_char_expr = new TypeLookupExpression ("System", "Char");
221 system_void_expr = new TypeLookupExpression ("System", "Void");
222 system_valuetype_expr = new TypeLookupExpression ("System", "ValueType");
223 system_intptr_expr = new TypeLookupExpression ("System", "IntPtr");
226 static TypeManager ()
228 Reset ();
231 static public void Reset ()
233 InitExpressionTypes ();
235 builder_to_declspace = new PtrHashtable ();
236 builder_to_member_cache = new PtrHashtable ();
237 builder_to_method = new PtrHashtable ();
238 builder_to_type_param = new PtrHashtable ();
239 method_params = new PtrHashtable ();
240 method_overrides = new PtrHashtable ();
241 builder_to_ifaces = new PtrHashtable ();
243 fieldbuilders_to_fields = new Hashtable ();
244 propertybuilder_to_property = new Hashtable ();
245 fields = new Hashtable ();
246 type_hash = new DoubleHash ();
247 assembly_internals_vis_attrs = new PtrHashtable ();
248 iface_cache = new PtrHashtable ();
250 closure = new Closure ();
251 FilterWithClosure_delegate = new MemberFilter (closure.Filter);
253 // TODO: I am really bored by all this static stuff
254 system_type_get_type_from_handle =
255 bool_movenext_void =
256 void_dispose_void =
257 void_monitor_enter_object =
258 void_monitor_exit_object =
259 void_initializearray_array_fieldhandle =
260 delegate_combine_delegate_delegate =
261 delegate_remove_delegate_delegate =
262 int_interlocked_compare_exchange =
263 methodbase_get_type_from_handle =
264 methodbase_get_type_from_handle_generic =
265 fieldinfo_get_field_from_handle =
266 activator_create_instance = null;
268 int_get_offset_to_string_data =
269 ienumerator_getcurrent = null;
271 void_decimal_ctor_five_args =
272 void_decimal_ctor_int_arg = null;
274 isvolatile_type = null;
276 // to uncover regressions
277 AllClsTopLevelTypes = null;
280 public static void AddUserType (DeclSpace ds)
282 builder_to_declspace.Add (ds.TypeBuilder, ds);
286 // This entry point is used by types that we define under the covers
288 public static void RegisterBuilder (Type tb, Type [] ifaces)
290 if (ifaces != null)
291 builder_to_ifaces [tb] = ifaces;
294 public static void AddMethod (MethodBase builder, IMethodData method)
296 builder_to_method.Add (builder, method);
297 method_params.Add (builder, method.ParameterInfo);
300 public static IMethodData GetMethod (MethodBase builder)
302 return (IMethodData) builder_to_method [builder];
305 /// <summary>
306 /// Returns the DeclSpace whose Type is `t' or null if there is no
307 /// DeclSpace for `t' (ie, the Type comes from a library)
308 /// </summary>
309 public static DeclSpace LookupDeclSpace (Type t)
311 return builder_to_declspace [t] as DeclSpace;
314 /// <summary>
315 /// Returns the TypeContainer whose Type is `t' or null if there is no
316 /// TypeContainer for `t' (ie, the Type comes from a library)
317 /// </summary>
318 public static TypeContainer LookupTypeContainer (Type t)
320 return builder_to_declspace [t] as TypeContainer;
323 public static MemberCache LookupMemberCache (Type t)
325 if (t.Module == RootContext.ToplevelTypes.Builder) {
326 DeclSpace container = (DeclSpace)builder_to_declspace [t];
327 if (container != null)
328 return container.MemberCache;
331 #if GMCS_SOURCE
332 if (t is GenericTypeParameterBuilder) {
333 TypeParameter container = builder_to_type_param [t] as TypeParameter;
335 if (container != null)
336 return container.MemberCache;
338 #endif
340 return TypeHandle.GetMemberCache (t);
343 public static MemberCache LookupBaseInterfacesCache (Type t)
345 Type [] ifaces = GetInterfaces (t);
347 if (ifaces != null && ifaces.Length == 1)
348 return LookupMemberCache (ifaces [0]);
350 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
351 MemberCache cache = builder_to_member_cache [t] as MemberCache;
352 if (cache != null)
353 return cache;
355 cache = new MemberCache (ifaces);
356 builder_to_member_cache.Add (t, cache);
357 return cache;
360 public static TypeContainer LookupInterface (Type t)
362 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
363 if ((tc == null) || (tc.Kind != Kind.Interface))
364 return null;
366 return tc;
369 public static Delegate LookupDelegate (Type t)
371 return builder_to_declspace [t] as Delegate;
374 public static Class LookupClass (Type t)
376 return (Class) builder_to_declspace [t];
380 // We use this hash for multiple kinds of constructed types:
382 // (T, "&") Given T, get T &
383 // (T, "*") Given T, get T *
384 // (T, "[]") Given T and a array dimension, get T []
385 // (T, X) Given a type T and a simple name X, get the type T+X
387 // Accessibility tests, if necessary, should be done by the user
389 static DoubleHash type_hash = new DoubleHash ();
392 // Gets the reference to T version of the Type (T&)
394 public static Type GetReferenceType (Type t)
396 #if GMCS_SOURCE
397 return t.MakeByRefType ();
398 #else
399 return GetConstructedType (t, "&");
400 #endif
404 // Gets the pointer to T version of the Type (T*)
406 public static Type GetPointerType (Type t)
408 return GetConstructedType (t, "*");
411 public static Type GetConstructedType (Type t, string dim)
413 object ret = null;
414 if (type_hash.Lookup (t, dim, out ret))
415 return (Type) ret;
417 ret = t.Module.GetType (t.ToString () + dim);
418 if (ret != null) {
419 type_hash.Insert (t, dim, ret);
420 return (Type) ret;
423 if (dim == "&") {
424 ret = GetReferenceType (t);
425 type_hash.Insert (t, dim, ret);
426 return (Type) ret;
429 #if GMCS_SOURCE
430 if (t.IsGenericParameter || t.IsGenericType) {
431 int pos = 0;
432 Type result = t;
433 while ((pos < dim.Length) && (dim [pos] == '[')) {
434 pos++;
436 if (dim [pos] == ']') {
437 result = result.MakeArrayType ();
438 pos++;
440 if (pos < dim.Length)
441 continue;
443 type_hash.Insert (t, dim, result);
444 return result;
447 int rank = 0;
448 while (dim [pos] == ',') {
449 pos++; rank++;
452 if ((dim [pos] != ']') || (pos != dim.Length-1))
453 break;
455 result = result.MakeArrayType (rank + 1);
456 type_hash.Insert (t, dim, result);
457 return result;
460 #endif
462 type_hash.Insert (t, dim, null);
463 return null;
466 public static Type GetNestedType (Type t, string name)
468 object ret = null;
469 if (!type_hash.Lookup (t, name, out ret)) {
470 ret = t.GetNestedType (name,
471 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
472 type_hash.Insert (t, name, ret);
474 return (Type) ret;
477 /// <summary>
478 /// Fills static table with exported types from all referenced assemblies.
479 /// This information is required for CLS Compliance tests.
480 /// </summary>
481 public static void LoadAllImportedTypes ()
483 AllClsTopLevelTypes = new Hashtable (1500);
484 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
485 foreach (Type t in a.GetExportedTypes ()) {
486 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
491 public static bool NamespaceClash (string name, Location loc)
493 if (!GlobalRootNamespace.Instance.IsNamespace (name))
494 return false;
496 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
497 return true;
500 /// <summary>
501 /// Returns the C# name of a type if possible, or the full type name otherwise
502 /// </summary>
503 static public string CSharpName (Type t)
505 if (t == null_type)
506 return "null";
508 if (t == typeof (ArglistAccess))
509 return "__arglist";
511 if (t == typeof (AnonymousMethodBody))
512 return "anonymous method";
514 if (t == typeof (MethodGroupExpr))
515 return "method group";
517 if (t == null)
518 return "internal error";
520 return CSharpName (GetFullName (t), t);
523 static readonly char [] elements = new char [] { '*', '[' };
525 public static string CSharpName (string name, Type type)
527 if (name.Length > 10) {
528 string s;
529 switch (name) {
530 case "System.Int32": s = "int"; break;
531 case "System.Int64": s = "long"; break;
532 case "System.String": s = "string"; break;
533 case "System.Boolean": s = "bool"; break;
534 case "System.Void": s = "void"; break;
535 case "System.Object": s = "object"; break;
536 case "System.UInt32": s = "uint"; break;
537 case "System.Int16": s = "short"; break;
538 case "System.UInt16": s = "ushort"; break;
539 case "System.UInt64": s = "ulong"; break;
540 case "System.Single": s = "float"; break;
541 case "System.Double": s = "double"; break;
542 case "System.Decimal": s = "decimal"; break;
543 case "System.Char": s = "char"; break;
544 case "System.Byte": s = "byte"; break;
545 case "System.SByte": s = "sbyte"; break;
546 default: s = null; break;
549 if (s != null) {
551 // Predefined names can come from mscorlib only
553 if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
554 return s;
556 return name;
559 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
560 return AnonymousTypeClass.SignatureForError;
562 int idx = name.IndexOfAny (elements, 10);
563 if (idx > 0)
564 return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
567 return name.Replace ('+', '.');
570 static public string CSharpName (Type[] types)
572 if (types.Length == 0)
573 return string.Empty;
575 StringBuilder sb = new StringBuilder ();
576 for (int i = 0; i < types.Length; ++i) {
577 if (i > 0)
578 sb.Append (", ");
580 sb.Append (CSharpName (types [i]));
582 return sb.ToString ();
585 /// <summary>
586 /// Returns the signature of the method with full namespace classification
587 /// </summary>
588 static public string GetFullNameSignature (MemberInfo mi)
590 PropertyInfo pi = mi as PropertyInfo;
591 if (pi != null) {
592 MethodBase pmi = pi.GetGetMethod (true);
593 if (pmi == null)
594 pmi = pi.GetSetMethod (true);
595 if (GetParameterData (pmi).Count > 0)
596 mi = pmi;
598 return (mi is MethodBase)
599 ? CSharpSignature (mi as MethodBase)
600 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
603 #if GMCS_SOURCE
604 private static int GetFullName (Type t, StringBuilder sb)
606 int pos = 0;
608 if (!t.IsGenericType) {
609 sb.Append (t.FullName);
610 return 0;
613 if (t.DeclaringType != null) {
614 pos = GetFullName (t.DeclaringType, sb);
615 sb.Append ('.');
616 } else if (t.Namespace != null && t.Namespace.Length != 0) {
617 sb.Append (t.Namespace);
618 sb.Append ('.');
620 sb.Append (RemoveGenericArity (t.Name));
622 Type[] this_args = GetTypeArguments (t);
624 if (this_args.Length < pos)
625 throw new InternalErrorException (
626 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
627 if (this_args.Length == pos)
628 return pos;
630 sb.Append ('<');
631 for (;;) {
632 sb.Append (CSharpName (this_args [pos++]));
633 if (pos == this_args.Length)
634 break;
635 sb.Append (',');
637 sb.Append ('>');
638 return pos;
641 static string GetFullName (Type t)
643 if (t.IsArray) {
644 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
645 return GetFullName (GetElementType (t)) + dimension;
648 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
649 t = GetTypeArguments (t)[0];
650 return CSharpName (t) + "?";
653 if (t.IsGenericParameter)
654 return t.Name;
655 if (!t.IsGenericType)
656 return t.FullName;
658 StringBuilder sb = new StringBuilder ();
659 int pos = GetFullName (t, sb);
660 if (pos <= 0)
661 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
662 return sb.ToString ();
664 #else
665 public static string GetFullName (Type t)
667 return t.FullName;
669 #endif
671 public static string RemoveGenericArity (string from)
673 int i = from.IndexOf ('`');
674 if (i > 0)
675 return from.Substring (0, i);
676 return from;
679 /// <summary>
680 /// When we need to report accessors as well
681 /// </summary>
682 static public string CSharpSignature (MethodBase mb)
684 return CSharpSignature (mb, false);
687 /// <summary>
688 /// Returns the signature of the method
689 /// </summary>
690 static public string CSharpSignature (MethodBase mb, bool show_accessor)
692 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
693 sig.Append ('.');
695 AParametersCollection iparams = GetParameterData (mb);
696 string parameters = iparams.GetSignatureForError ();
697 int accessor_end = 0;
699 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
700 string op_name = Operator.GetName (mb.Name);
701 if (op_name != null) {
702 if (op_name == "explicit" || op_name == "implicit") {
703 sig.Append (op_name);
704 sig.Append (" operator ");
705 sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
706 } else {
707 sig.Append ("operator ");
708 sig.Append (op_name);
710 sig.Append (parameters);
711 return sig.ToString ();
714 bool is_getter = mb.Name.StartsWith ("get_");
715 bool is_setter = mb.Name.StartsWith ("set_");
716 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
717 accessor_end = 3;
718 } else if (mb.Name.StartsWith ("remove_")) {
719 accessor_end = 6;
722 // Is indexer
723 if (iparams.Count > (is_getter ? 0 : 1)) {
724 sig.Append ("this[");
725 if (is_getter)
726 sig.Append (parameters.Substring (1, parameters.Length - 2));
727 else
728 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
729 sig.Append (']');
730 } else {
731 sig.Append (mb.Name.Substring (accessor_end + 1));
733 } else {
734 if (mb.Name == ".ctor")
735 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
736 else {
737 sig.Append (mb.Name);
739 if (IsGenericMethod (mb)) {
740 Type[] args = GetGenericArguments (mb);
741 sig.Append ('<');
742 for (int i = 0; i < args.Length; i++) {
743 if (i > 0)
744 sig.Append (',');
745 sig.Append (CSharpName (args [i]));
747 sig.Append ('>');
751 sig.Append (parameters);
754 if (show_accessor && accessor_end > 0) {
755 sig.Append ('.');
756 sig.Append (mb.Name.Substring (0, accessor_end));
759 return sig.ToString ();
762 public static string GetMethodName (MethodInfo m)
764 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
765 return m.Name;
767 return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
770 static public string CSharpSignature (EventInfo ei)
772 return CSharpName (ei.DeclaringType) + "." + ei.Name;
776 // Looks up a type, and aborts if it is not found. This is used
777 // by predefined types required by the compiler
779 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
781 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
782 Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
784 if (expr == null) {
785 if (required) {
786 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
787 ns_name, name);
789 return null;
792 Type t = expr.Type;
793 if (RootContext.StdLib || t == null || !required)
794 return t;
796 // TODO: All predefined imported types have to have correct signature
797 if (t.Module != RootContext.ToplevelTypes.Builder)
798 return t;
800 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
801 if (ds is Delegate) {
802 if (type_kind == Kind.Delegate)
803 return t;
804 } else {
805 TypeContainer tc = (TypeContainer)ds;
806 if (tc.Kind == type_kind)
807 return t;
810 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
811 ns_name, name);
812 return null;
815 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
817 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
819 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
820 if (members != null) {
821 for (int i = 0; i < members.Length; ++i) {
822 MemberInfo member = members [i];
823 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
824 MethodBase mb = member as MethodBase;
825 if (mb == null)
826 continue;
828 AParametersCollection pd = TypeManager.GetParameterData (mb);
829 if (IsEqual (pd.Types, args))
830 return member;
832 if (mt == MemberTypes.Field) {
833 FieldInfo fi = member as FieldInfo;
834 if (fi == null)
835 continue;
837 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
838 continue;
840 return member;
843 if (mt == MemberTypes.Property) {
844 PropertyInfo pi = member as PropertyInfo;
845 if (pi == null)
846 continue;
848 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
849 continue;
851 return member;
856 string method_args = null;
857 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
858 method_args = "(" + TypeManager.CSharpName (args) + ")";
860 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
861 TypeManager.CSharpName (t), name, method_args);
863 return null;
867 // Returns the ConstructorInfo for "args"
869 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
871 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
875 // Returns the MethodInfo for a method named `name' defined
876 // in type `t' which takes arguments of types `args'
878 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
880 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
883 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
885 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
888 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
890 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
893 /// <remarks>
894 /// The types have to be initialized after the initial
895 /// population of the type has happened (for example, to
896 /// bootstrap the corlib.dll
897 /// </remarks>
898 public static bool InitCoreTypes ()
900 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
901 system_object_expr.Type = object_type;
902 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
903 system_valuetype_expr.Type = value_type;
904 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
906 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
907 system_int32_expr.Type = int32_type;
908 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
909 system_int64_expr.Type = int64_type;
910 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
911 system_uint32_expr.Type = uint32_type;
912 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
913 system_uint64_expr.Type = uint64_type;
914 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
915 system_byte_expr.Type = byte_type;
916 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
917 system_sbyte_expr.Type = sbyte_type;
918 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
919 system_int16_expr.Type = short_type;
920 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
921 system_uint16_expr.Type = ushort_type;
923 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
924 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
925 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
927 // HACK: DefineType immediately resolves iterators (very wrong)
928 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
930 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
931 system_char_expr.Type = char_type;
932 string_type = CoreLookupType ("System", "String", Kind.Class, true);
933 system_string_expr.Type = string_type;
934 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
935 system_single_expr.Type = float_type;
936 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
937 system_double_expr.Type = double_type;
938 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
939 system_decimal_expr.Type = decimal_type;
940 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
941 system_boolean_expr.Type = bool_type;
942 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
943 system_intptr_expr.Type = intptr_type;
944 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
946 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
947 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
949 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
950 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
951 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
952 system_void_expr.Type = void_type;
953 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
954 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
956 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
957 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
959 PredefinedAttributes.Get.ParamArray.Resolve (false);
960 PredefinedAttributes.Get.Out.Resolve (false);
962 return Report.Errors == 0;
966 // Initializes optional core types
968 public static void InitOptionalCoreTypes ()
971 // These are only used for compare purposes
973 null_type = typeof (NullLiteral);
975 void_ptr_type = GetPointerType (void_type);
978 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
979 // types cache with incorrect accessiblity when any of optional types is internal.
981 PredefinedAttributes.Get.Initialize ();
983 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
984 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
985 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
986 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
987 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
988 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
991 // Optional attributes, used for error reporting only
993 //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
994 // Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
995 // if (c != null)
996 // c.Define ();
999 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1000 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1001 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1002 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1005 // Optional types which are used as types and for member lookup
1007 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1009 // New in .NET 3.5
1010 // Note: extension_attribute_type is already loaded
1011 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1013 if (!RootContext.StdLib) {
1015 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1016 // has different predefined types and this method sets mscorlib types
1017 // to be same to avoid any type check errors.
1020 Type type = typeof (Type);
1021 Type [] system_4_type_arg = { type, type, type, type };
1023 MethodInfo set_corlib_type_builders =
1024 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1025 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1026 system_4_type_arg, null);
1028 if (set_corlib_type_builders != null) {
1029 object[] args = new object [4];
1030 args [0] = object_type;
1031 args [1] = value_type;
1032 args [2] = enum_type;
1033 args [3] = void_type;
1035 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1036 } else {
1037 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1038 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1039 TypeManager.CSharpName (system_4_type_arg));
1044 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1046 /// <remarks>
1047 /// This is the "old", non-cache based FindMembers() function. We cannot use
1048 /// the cache here because there is no member name argument.
1049 /// </remarks>
1050 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1051 MemberFilter filter, object criteria)
1053 #if MS_COMPATIBLE && GMCS_SOURCE
1054 if (t.IsGenericType)
1055 t = t.GetGenericTypeDefinition ();
1056 #endif
1058 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1061 // `builder_to_declspace' contains all dynamic types.
1063 if (decl != null) {
1064 MemberList list;
1065 Timer.StartTimer (TimerType.FindMembers);
1066 list = decl.FindMembers (mt, bf, filter, criteria);
1067 Timer.StopTimer (TimerType.FindMembers);
1068 return list;
1072 // We have to take care of arrays specially, because GetType on
1073 // a TypeBuilder array will return a Type, not a TypeBuilder,
1074 // and we can not call FindMembers on this type.
1076 if (
1077 #if MS_COMPATIBLE && GMCS_SOURCE
1078 !t.IsGenericType &&
1079 #endif
1080 t.IsSubclassOf (TypeManager.array_type))
1081 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1083 #if GMCS_SOURCE
1084 if (t is GenericTypeParameterBuilder) {
1085 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1087 Timer.StartTimer (TimerType.FindMembers);
1088 MemberList list = tparam.FindMembers (
1089 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1090 Timer.StopTimer (TimerType.FindMembers);
1091 return list;
1093 #endif
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 GMCS_SOURCE
1214 if (t is GenericTypeParameterBuilder) {
1215 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1217 used_cache = true;
1218 if (tparam.MemberCache == null)
1219 return new MemberInfo [0];
1221 return tparam.MemberCache.FindMembers (
1222 mt, bf, name, FilterWithClosure_delegate, null);
1224 #endif
1226 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1228 // This happens if we're resolving a class'es base class and interfaces
1229 // in TypeContainer.DefineType(). At this time, the types aren't
1230 // populated yet, so we can't use the cache.
1232 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1233 FilterWithClosure_delegate, name);
1234 used_cache = false;
1235 return info;
1239 // This call will always succeed. There is exactly one TypeHandle instance per
1240 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1241 // the corresponding MemberCache.
1243 cache = TypeHandle.GetMemberCache (t);
1245 used_cache = true;
1246 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1249 public static bool IsBuiltinType (Type t)
1251 t = TypeToCoreType (t);
1252 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1253 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1254 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1255 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1256 return true;
1257 else
1258 return false;
1262 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1263 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1265 public static bool IsPrimitiveType (Type t)
1267 return (t == int32_type || t == uint32_type ||
1268 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1269 t == char_type || t == short_type || t == bool_type ||
1270 t == sbyte_type || t == byte_type || t == ushort_type);
1273 public static bool IsDelegateType (Type t)
1275 if (TypeManager.IsGenericParameter (t))
1276 return false;
1278 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1279 return false;
1281 t = DropGenericTypeArguments (t);
1282 return IsSubclassOf (t, TypeManager.delegate_type);
1286 // Is a type of dynamic type
1288 public static bool IsDynamicType (Type t)
1290 if (t == InternalType.Dynamic)
1291 return true;
1293 if (t != object_type)
1294 return false;
1296 if (t.Module == RootContext.ToplevelTypes.Builder)
1297 return false;
1299 PredefinedAttribute pa = PredefinedAttributes.Get.Dynamic;
1300 if (pa == null)
1301 return false;
1303 object[] res = t.GetCustomAttributes (pa.Type, false);
1304 return res != null && res.Length != 0;
1307 public static bool IsEnumType (Type t)
1309 t = DropGenericTypeArguments (t);
1310 return t.BaseType == TypeManager.enum_type;
1313 public static bool IsBuiltinOrEnum (Type t)
1315 if (IsBuiltinType (t))
1316 return true;
1318 if (IsEnumType (t))
1319 return true;
1321 return false;
1324 public static bool IsAttributeType (Type t)
1326 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1330 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1332 // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
1333 public static bool IsUnmanagedType (Type t)
1335 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1336 if (ds != null)
1337 return ds.IsUnmanagedType ();
1339 // builtins that are not unmanaged types
1340 if (t == TypeManager.object_type || t == TypeManager.string_type)
1341 return false;
1343 if (IsGenericType (t) || IsGenericParameter (t))
1344 return false;
1346 if (IsBuiltinOrEnum (t))
1347 return true;
1349 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1350 if (t.IsPointer)
1351 return IsUnmanagedType (GetElementType (t));
1353 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1354 if (t.IsArray)
1355 return false;
1357 if (!IsValueType (t))
1358 return false;
1360 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1361 if (IsGenericTypeDefinition (p))
1362 return false;
1365 bool retval = true;
1367 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1369 foreach (FieldInfo f in fields){
1370 if (!IsUnmanagedType (f.FieldType)){
1371 retval = false;
1376 return retval;
1380 // Null is considered to be a reference type
1382 public static bool IsReferenceType (Type t)
1384 if (TypeManager.IsGenericParameter (t)) {
1385 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1386 if (constraints == null)
1387 return false;
1389 return constraints.IsReferenceType;
1392 return !IsStruct (t) && !IsEnumType (t);
1395 public static bool IsValueType (Type t)
1397 if (TypeManager.IsGenericParameter (t)) {
1398 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1399 if (constraints == null)
1400 return false;
1402 return constraints.IsValueType;
1405 return IsStruct (t) || IsEnumType (t);
1408 public static bool IsStruct (Type t)
1410 return t.BaseType == value_type && t != enum_type && t.IsSealed;
1413 public static bool IsInterfaceType (Type t)
1415 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1416 if (tc == null)
1417 return false;
1419 return tc.Kind == Kind.Interface;
1422 public static bool IsSubclassOf (Type type, Type base_type)
1424 TypeParameter tparam = LookupTypeParameter (type);
1425 TypeParameter pparam = LookupTypeParameter (base_type);
1427 if ((tparam != null) && (pparam != null)) {
1428 if (tparam == pparam)
1429 return true;
1431 return tparam.IsSubclassOf (base_type);
1434 #if MS_COMPATIBLE && GMCS_SOURCE
1435 if (type.IsGenericType)
1436 type = type.GetGenericTypeDefinition ();
1437 #endif
1439 if (type.IsSubclassOf (base_type))
1440 return true;
1442 do {
1443 if (IsEqual (type, base_type))
1444 return true;
1446 type = type.BaseType;
1447 } while (type != null);
1449 return false;
1452 public static bool IsPrivateAccessible (Type type, Type parent)
1454 if (type == null)
1455 return false;
1457 if (type.Equals (parent))
1458 return true;
1460 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1463 public static bool IsFamilyAccessible (Type type, Type parent)
1465 TypeParameter tparam = LookupTypeParameter (type);
1466 TypeParameter pparam = LookupTypeParameter (parent);
1468 if ((tparam != null) && (pparam != null)) {
1469 if (tparam == pparam)
1470 return true;
1472 return tparam.IsSubclassOf (parent);
1475 do {
1476 if (IsInstantiationOfSameGenericType (type, parent))
1477 return true;
1479 type = type.BaseType;
1480 } while (type != null);
1482 return false;
1486 // Checks whether `type' is a subclass or nested child of `base_type'.
1488 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1490 do {
1491 if (IsFamilyAccessible (type, base_type))
1492 return true;
1494 // Handle nested types.
1495 type = type.DeclaringType;
1496 } while (type != null);
1498 return false;
1502 // Checks whether `type' is a nested child of `parent'.
1504 public static bool IsNestedChildOf (Type type, Type parent)
1506 if (type == null)
1507 return false;
1509 type = DropGenericTypeArguments (type);
1510 parent = DropGenericTypeArguments (parent);
1512 if (IsEqual (type, parent))
1513 return false;
1515 type = type.DeclaringType;
1516 while (type != null) {
1517 if (IsEqual (type, parent))
1518 return true;
1520 type = type.DeclaringType;
1523 return false;
1526 public static bool IsSpecialType (Type t)
1528 return t == arg_iterator_type || t == typed_reference_type;
1532 // Checks whether `extern_type' is friend of the output assembly
1534 public static bool IsThisOrFriendAssembly (Assembly assembly)
1536 if (assembly == CodeGen.Assembly.Builder)
1537 return true;
1539 if (assembly_internals_vis_attrs.Contains (assembly))
1540 return (bool)(assembly_internals_vis_attrs [assembly]);
1542 PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
1543 // HACK: Do very early resolve of SRE type checking
1544 if (pa.Type == null)
1545 pa.Resolve (true);
1547 if (!pa.IsDefined)
1548 return false;
1550 object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
1551 if (attrs.Length == 0) {
1552 assembly_internals_vis_attrs.Add (assembly, false);
1553 return false;
1556 bool is_friend = false;
1558 AssemblyName this_name = CodeGen.Assembly.Name;
1559 byte [] this_token = this_name.GetPublicKeyToken ();
1560 foreach (InternalsVisibleToAttribute attr in attrs) {
1561 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1562 continue;
1564 AssemblyName aname = null;
1565 try {
1566 #if GMCS_SOURCE
1567 aname = new AssemblyName (attr.AssemblyName);
1568 #else
1569 throw new NotSupportedException ();
1570 #endif
1571 } catch (FileLoadException) {
1572 } catch (ArgumentException) {
1575 if (aname == null || aname.Name != this_name.Name)
1576 continue;
1578 byte [] key_token = aname.GetPublicKeyToken ();
1579 if (key_token != null) {
1580 if (this_token.Length == 0) {
1581 // Same name, but assembly is not strongnamed
1582 Error_FriendAccessNameNotMatching (aname.FullName);
1583 break;
1586 if (!CompareKeyTokens (this_token, key_token))
1587 continue;
1590 is_friend = true;
1591 break;
1594 assembly_internals_vis_attrs.Add (assembly, is_friend);
1595 return is_friend;
1598 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1600 for (int i = 0; i < token1.Length; i++)
1601 if (token1 [i] != token2 [i])
1602 return false;
1604 return true;
1607 static void Error_FriendAccessNameNotMatching (string other_name)
1609 Report.Error (281,
1610 "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",
1611 other_name, CodeGen.Assembly.Name.FullName);
1615 // Do the right thing when returning the element type of an
1616 // array type based on whether we are compiling corlib or not
1618 public static Type GetElementType (Type t)
1620 if (RootContext.StdLib)
1621 return t.GetElementType ();
1622 else
1623 return TypeToCoreType (t.GetElementType ());
1626 /// <summary>
1627 /// This method is not implemented by MS runtime for dynamic types
1628 /// </summary>
1629 public static bool HasElementType (Type t)
1631 return t.IsArray || t.IsPointer || t.IsByRef;
1634 public static Type GetEnumUnderlyingType (Type t)
1636 t = DropGenericTypeArguments (t);
1637 Enum e = LookupTypeContainer (t) as Enum;
1638 if (e != null)
1639 return e.UnderlyingType;
1641 // TODO: cache it ?
1642 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1643 if (fi == null)
1644 return TypeManager.int32_type;
1646 return TypeToCoreType (fi.FieldType);
1649 /// <summary>
1650 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1651 /// </summary>
1653 /// <remarks>
1654 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1655 /// for anything which is dynamic, and we need this in a number of places,
1656 /// we register this information here, and use it afterwards.
1657 /// </remarks>
1658 static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1660 method_params.Add (mb, ip);
1663 static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1665 method_params.Add (pb, p);
1668 static public AParametersCollection GetParameterData (MethodBase mb)
1670 AParametersCollection pd = (AParametersCollection) method_params [mb];
1671 if (pd == null) {
1672 #if MS_COMPATIBLE
1673 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1674 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1675 pd = GetParameterData (mi);
1677 if (mi.IsGenericMethod)
1678 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1679 else
1680 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1682 method_params.Add (mb, pd);
1683 return pd;
1686 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1687 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1688 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1691 pd = ParametersImported.Create (mb);
1692 #else
1693 MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1694 if (generic != mb) {
1695 pd = TypeManager.GetParameterData (generic);
1696 pd = ParametersImported.Create (pd, mb);
1697 } else {
1698 pd = ParametersImported.Create (mb);
1700 #endif
1701 method_params.Add (mb, pd);
1703 return pd;
1706 public static AParametersCollection GetParameterData (PropertyInfo pi)
1708 AParametersCollection pd = (AParametersCollection)method_params [pi];
1709 if (pd == null) {
1710 if (pi is PropertyBuilder)
1711 return ParametersCompiled.EmptyReadOnlyParameters;
1713 ParameterInfo [] p = pi.GetIndexParameters ();
1714 if (p == null)
1715 return ParametersCompiled.EmptyReadOnlyParameters;
1717 pd = ParametersImported.Create (p, null);
1718 method_params.Add (pi, pd);
1721 return pd;
1724 public static AParametersCollection GetDelegateParameters (Type t)
1726 Delegate d = builder_to_declspace [t] as Delegate;
1727 if (d != null)
1728 return d.Parameters;
1730 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1731 return GetParameterData (invoke_mb);
1734 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1736 if (!method_overrides.Contains (override_method))
1737 method_overrides [override_method] = base_method;
1738 if (method_overrides [override_method] != base_method)
1739 throw new InternalErrorException ("Override mismatch: " + override_method);
1742 static public bool IsOverride (MethodBase m)
1744 m = DropGenericMethodArguments (m);
1746 return m.IsVirtual &&
1747 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1748 (m is MethodBuilder || method_overrides.Contains (m));
1751 static public MethodBase TryGetBaseDefinition (MethodBase m)
1753 m = DropGenericMethodArguments (m);
1755 return (MethodBase) method_overrides [m];
1758 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1760 fields.Add (fb, ic);
1763 public static IConstant GetConstant (FieldInfo fb)
1765 if (fb == null)
1766 return null;
1768 return (IConstant)fields [fb];
1771 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1773 propertybuilder_to_property.Add (pi, pb);
1776 public static PropertyBase GetProperty (PropertyInfo pi)
1778 return (PropertyBase)propertybuilder_to_property [pi];
1781 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1783 fieldbuilders_to_fields.Add (fb, f);
1787 // The return value can be null; This will be the case for
1788 // auxiliary FieldBuilders created by the compiler that have no
1789 // real field being declared on the source code
1791 static public FieldBase GetField (FieldInfo fb)
1793 #if GMCS_SOURCE
1794 fb = GetGenericFieldDefinition (fb);
1795 #endif
1796 return (FieldBase) fieldbuilders_to_fields [fb];
1799 static public MethodInfo GetAddMethod (EventInfo ei)
1801 if (ei is MyEventBuilder) {
1802 return ((MyEventBuilder)ei).GetAddMethod (true);
1804 return ei.GetAddMethod (true);
1807 static public MethodInfo GetRemoveMethod (EventInfo ei)
1809 if (ei is MyEventBuilder) {
1810 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1812 return ei.GetRemoveMethod (true);
1815 static public void RegisterEventField (EventInfo einfo, EventField e)
1817 if (events == null)
1818 events = new Hashtable ();
1820 events.Add (einfo, e);
1823 static public EventField GetEventField (EventInfo ei)
1825 if (events == null)
1826 return null;
1828 return (EventField) events [ei];
1831 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1833 Hashtable hash = new Hashtable ();
1834 return CheckStructCycles (tc, seen, hash);
1837 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1838 Hashtable hash)
1840 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1841 return true;
1844 // `seen' contains all types we've already visited.
1846 if (seen.Contains (tc))
1847 return true;
1848 seen.Add (tc, null);
1850 if (tc.Fields == null)
1851 return true;
1853 foreach (FieldBase field in tc.Fields) {
1854 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1855 continue;
1857 Type ftype = field.FieldBuilder.FieldType;
1858 TypeContainer ftc = LookupTypeContainer (ftype);
1859 if (ftc == null)
1860 continue;
1862 if (hash.Contains (ftc)) {
1863 Report.Error (523, tc.Location,
1864 "Struct member `{0}.{1}' of type `{2}' " +
1865 "causes a cycle in the struct layout",
1866 tc.Name, field.Name, ftc.Name);
1867 return false;
1871 // `hash' contains all types in the current path.
1873 hash.Add (tc, null);
1875 bool ok = CheckStructCycles (ftc, seen, hash);
1877 hash.Remove (tc);
1879 if (!ok)
1880 return false;
1882 if (!seen.Contains (ftc))
1883 seen.Add (ftc, null);
1886 return true;
1889 /// <summary>
1890 /// Given an array of interface types, expand and eliminate repeated ocurrences
1891 /// of an interface.
1892 /// </summary>
1894 /// <remarks>
1895 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1896 /// be IA, IB, IC.
1897 /// </remarks>
1898 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1900 ArrayList new_ifaces = new ArrayList ();
1902 foreach (TypeExpr iface in base_interfaces){
1903 Type itype = iface.Type;
1905 if (new_ifaces.Contains (itype))
1906 continue;
1908 new_ifaces.Add (itype);
1910 Type [] implementing = GetInterfaces (itype);
1912 foreach (Type imp in implementing){
1913 if (!new_ifaces.Contains (imp))
1914 new_ifaces.Add (imp);
1917 Type [] ret = new Type [new_ifaces.Count];
1918 new_ifaces.CopyTo (ret, 0);
1919 return ret;
1922 public static Type[] ExpandInterfaces (Type [] base_interfaces)
1924 ArrayList new_ifaces = new ArrayList ();
1926 foreach (Type itype in base_interfaces){
1927 if (new_ifaces.Contains (itype))
1928 continue;
1930 new_ifaces.Add (itype);
1932 Type [] implementing = GetInterfaces (itype);
1934 foreach (Type imp in implementing){
1935 if (!new_ifaces.Contains (imp))
1936 new_ifaces.Add (imp);
1939 Type [] ret = new Type [new_ifaces.Count];
1940 new_ifaces.CopyTo (ret, 0);
1941 return ret;
1944 static PtrHashtable iface_cache;
1946 /// <summary>
1947 /// This function returns the interfaces in the type `t'. Works with
1948 /// both types and TypeBuilders.
1949 /// </summary>
1950 public static Type [] GetInterfaces (Type t)
1952 Type [] cached = iface_cache [t] as Type [];
1953 if (cached != null)
1954 return cached;
1957 // The reason for catching the Array case is that Reflection.Emit
1958 // will not return a TypeBuilder for Array types of TypeBuilder types,
1959 // but will still throw an exception if we try to call GetInterfaces
1960 // on the type.
1962 // Since the array interfaces are always constant, we return those for
1963 // the System.Array
1966 if (t.IsArray)
1967 t = TypeManager.array_type;
1969 if ((t is TypeBuilder) || IsGenericType (t)) {
1970 Type [] base_ifaces;
1972 if (t.BaseType == null)
1973 base_ifaces = Type.EmptyTypes;
1974 else
1975 base_ifaces = GetInterfaces (t.BaseType);
1976 Type[] type_ifaces;
1977 if (IsGenericType (t))
1978 #if MS_COMPATIBLE && GMCS_SOURCE
1979 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
1980 #else
1981 type_ifaces = t.GetInterfaces ();
1982 #endif
1983 else
1984 type_ifaces = (Type []) builder_to_ifaces [t];
1985 if (type_ifaces == null || type_ifaces.Length == 0)
1986 type_ifaces = Type.EmptyTypes;
1988 int base_count = base_ifaces.Length;
1989 Type [] result = new Type [base_count + type_ifaces.Length];
1990 base_ifaces.CopyTo (result, 0);
1991 type_ifaces.CopyTo (result, base_count);
1993 iface_cache [t] = result;
1994 return result;
1995 } else if (t is GenericTypeParameterBuilder){
1996 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
1997 if (type_ifaces == null || type_ifaces.Length == 0)
1998 type_ifaces = Type.EmptyTypes;
2000 iface_cache [t] = type_ifaces;
2001 return type_ifaces;
2002 } else {
2003 Type[] ifaces = t.GetInterfaces ();
2004 iface_cache [t] = ifaces;
2005 return ifaces;
2010 // gets the interfaces that are declared explicitly on t
2012 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2014 return (Type []) builder_to_ifaces [t];
2017 /// <remarks>
2018 /// The following is used to check if a given type implements an interface.
2019 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2020 /// </remarks>
2021 public static bool ImplementsInterface (Type t, Type iface)
2023 Type [] interfaces;
2026 // FIXME OPTIMIZATION:
2027 // as soon as we hit a non-TypeBuiler in the interface
2028 // chain, we could return, as the `Type.GetInterfaces'
2029 // will return all the interfaces implement by the type
2030 // or its bases.
2032 do {
2033 interfaces = GetInterfaces (t);
2035 if (interfaces != null){
2036 foreach (Type i in interfaces){
2037 if (i == iface || IsVariantOf (i, iface))
2038 return true;
2042 t = t.BaseType;
2043 } while (t != null);
2045 return false;
2048 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2050 // This is a custom version of Convert.ChangeType() which works
2051 // with the TypeBuilder defined types when compiling corlib.
2052 public static object ChangeType (object value, Type conversionType, out bool error)
2054 IConvertible convert_value = value as IConvertible;
2056 if (convert_value == null){
2057 error = true;
2058 return null;
2062 // NOTE 1:
2063 // We must use Type.Equals() here since `conversionType' is
2064 // the TypeBuilder created version of a system type and not
2065 // the system type itself. You cannot use Type.GetTypeCode()
2066 // on such a type - it'd always return TypeCode.Object.
2068 // NOTE 2:
2069 // We cannot rely on build-in type conversions as they are
2070 // more limited than what C# supports.
2071 // See char -> float/decimal/double conversion
2074 error = false;
2075 try {
2076 if (conversionType.Equals (typeof (Boolean)))
2077 return (object)(convert_value.ToBoolean (nf_provider));
2078 if (conversionType.Equals (typeof (Byte)))
2079 return (object)(convert_value.ToByte (nf_provider));
2080 if (conversionType.Equals (typeof (Char)))
2081 return (object)(convert_value.ToChar (nf_provider));
2082 if (conversionType.Equals (typeof (DateTime)))
2083 return (object)(convert_value.ToDateTime (nf_provider));
2085 if (conversionType.Equals (decimal_type)) {
2086 if (convert_value.GetType () == TypeManager.char_type)
2087 return (decimal)convert_value.ToInt32 (nf_provider);
2088 return convert_value.ToDecimal (nf_provider);
2091 if (conversionType.Equals (typeof (Double))) {
2092 if (convert_value.GetType () == TypeManager.char_type)
2093 return (double)convert_value.ToInt32 (nf_provider);
2094 return convert_value.ToDouble (nf_provider);
2097 if (conversionType.Equals (typeof (Int16)))
2098 return (object)(convert_value.ToInt16 (nf_provider));
2099 if (conversionType.Equals (int32_type))
2100 return (object)(convert_value.ToInt32 (nf_provider));
2101 if (conversionType.Equals (int64_type))
2102 return (object)(convert_value.ToInt64 (nf_provider));
2103 if (conversionType.Equals (typeof (SByte)))
2104 return (object)(convert_value.ToSByte (nf_provider));
2106 if (conversionType.Equals (typeof (Single))) {
2107 if (convert_value.GetType () == TypeManager.char_type)
2108 return (float)convert_value.ToInt32 (nf_provider);
2109 return convert_value.ToSingle (nf_provider);
2112 if (conversionType.Equals (typeof (String)))
2113 return (object)(convert_value.ToString (nf_provider));
2114 if (conversionType.Equals (typeof (UInt16)))
2115 return (object)(convert_value.ToUInt16 (nf_provider));
2116 if (conversionType.Equals (typeof (UInt32)))
2117 return (object)(convert_value.ToUInt32 (nf_provider));
2118 if (conversionType.Equals (typeof (UInt64)))
2119 return (object)(convert_value.ToUInt64 (nf_provider));
2120 if (conversionType.Equals (typeof (Object)))
2121 return (object)(value);
2122 else
2123 error = true;
2124 } catch {
2125 error = true;
2127 return null;
2131 // When compiling with -nostdlib and the type is imported from an external assembly
2132 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2134 public static Type TypeToCoreType (Type t)
2136 if (RootContext.StdLib || t.Module != typeof (object).Module)
2137 return t;
2139 TypeCode tc = Type.GetTypeCode (t);
2141 switch (tc){
2142 case TypeCode.Boolean:
2143 return TypeManager.bool_type;
2144 case TypeCode.Byte:
2145 return TypeManager.byte_type;
2146 case TypeCode.SByte:
2147 return TypeManager.sbyte_type;
2148 case TypeCode.Char:
2149 return TypeManager.char_type;
2150 case TypeCode.Int16:
2151 return TypeManager.short_type;
2152 case TypeCode.UInt16:
2153 return TypeManager.ushort_type;
2154 case TypeCode.Int32:
2155 return TypeManager.int32_type;
2156 case TypeCode.UInt32:
2157 return TypeManager.uint32_type;
2158 case TypeCode.Int64:
2159 return TypeManager.int64_type;
2160 case TypeCode.UInt64:
2161 return TypeManager.uint64_type;
2162 case TypeCode.Single:
2163 return TypeManager.float_type;
2164 case TypeCode.Double:
2165 return TypeManager.double_type;
2166 case TypeCode.String:
2167 return TypeManager.string_type;
2168 case TypeCode.Decimal:
2169 return TypeManager.decimal_type;
2172 if (t == typeof (void))
2173 return TypeManager.void_type;
2174 if (t == typeof (object))
2175 return TypeManager.object_type;
2176 if (t == typeof (System.Type))
2177 return TypeManager.type_type;
2178 if (t == typeof (System.IntPtr))
2179 return TypeManager.intptr_type;
2180 if (t == typeof (System.UIntPtr))
2181 return TypeManager.uintptr_type;
2182 #if GMCS_SOURCE
2183 if (t.IsArray) {
2184 int dim = t.GetArrayRank ();
2185 t = GetElementType (t);
2186 return t.MakeArrayType (dim);
2188 if (t.IsByRef) {
2189 t = GetElementType (t);
2190 return t.MakeByRefType ();
2192 if (t.IsPointer) {
2193 t = GetElementType (t);
2194 return t.MakePointerType ();
2196 #endif
2197 return t;
2201 // Converts any type to reflection supported type
2203 public static Type TypeToReflectionType (Type type)
2205 // TODO: Very lame and painful, GetReference () is enough for mcs-cecil
2206 return IsDynamicType (type) ? object_type : type;
2209 /// <summary>
2210 /// Utility function that can be used to probe whether a type
2211 /// is managed or not.
2212 /// </summary>
2213 public static bool VerifyUnManaged (Type t, Location loc)
2215 if (IsUnmanagedType (t))
2216 return true;
2218 while (t.IsPointer)
2219 t = GetElementType (t);
2221 Report.SymbolRelatedToPreviousError (t);
2222 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2223 CSharpName (t));
2225 return false;
2228 /// <summary>
2229 /// Returns the name of the indexer in a given type.
2230 /// </summary>
2231 /// <remarks>
2232 /// The default is not always `Item'. The user can change this behaviour by
2233 /// using the IndexerNameAttribute in the container.
2234 /// For example, the String class indexer is named `Chars' not `Item'
2235 /// </remarks>
2236 public static string IndexerPropertyName (Type t)
2238 t = DropGenericTypeArguments (t);
2239 if (t is TypeBuilder) {
2240 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2241 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2244 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
2245 if (pa.IsDefined) {
2246 System.Attribute attr = System.Attribute.GetCustomAttribute (
2247 t, pa.Type);
2248 if (attr != null) {
2249 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2250 return dma.MemberName;
2254 return TypeContainer.DefaultIndexerName;
2257 static MethodInfo declare_local_method = null;
2259 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2261 if (declare_local_method == null){
2262 declare_local_method = typeof (ILGenerator).GetMethod (
2263 "DeclareLocal",
2264 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2265 null,
2266 new Type [] { typeof (Type), typeof (bool)},
2267 null);
2268 if (declare_local_method == null){
2269 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2270 return ig.DeclareLocal (t);
2273 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2276 private static bool IsSignatureEqual (Type a, Type b)
2279 /// Consider the following example (bug #77674):
2281 /// public abstract class A
2282 /// {
2283 /// public abstract T Foo<T> ();
2284 /// }
2286 /// public abstract class B : A
2287 /// {
2288 /// public override U Foo<T> ()
2289 /// { return default (U); }
2290 /// }
2292 /// Here, `T' and `U' are method type parameters from different methods
2293 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2295 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2296 /// we need to do a signature based comparision and consider them equal.
2298 if (a == b)
2299 return true;
2301 #if GMCS_SOURCE
2302 if (a.IsGenericParameter && b.IsGenericParameter &&
2303 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2304 return a.GenericParameterPosition == b.GenericParameterPosition;
2306 #endif
2308 if (a.IsArray && b.IsArray) {
2309 if (a.GetArrayRank () != b.GetArrayRank ())
2310 return false;
2312 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2315 if (a.IsByRef && b.IsByRef)
2316 return IsSignatureEqual (GetElementType (a), GetElementType (b));
2318 if (IsGenericType (a) && IsGenericType (b)) {
2319 if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
2320 return false;
2322 Type[] aargs = GetTypeArguments (a);
2323 Type[] bargs = GetTypeArguments (b);
2325 if (aargs.Length != bargs.Length)
2326 return false;
2328 for (int i = 0; i < aargs.Length; i++) {
2329 if (!IsSignatureEqual (aargs [i], bargs [i]))
2330 return false;
2333 return true;
2336 return false;
2340 // Returns whether the array of memberinfos contains the given method
2342 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2344 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2346 foreach (MethodBase method in array) {
2347 if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2348 continue;
2350 if (method.Name != new_method.Name)
2351 continue;
2353 if (method is MethodInfo && new_method is MethodInfo &&
2354 !IsSignatureEqual (
2355 TypeToCoreType (((MethodInfo) method).ReturnType),
2356 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2357 continue;
2359 Type [] old_args = TypeManager.GetParameterData (method).Types;
2360 int old_count = old_args.Length;
2361 int i;
2363 if (new_args.Length != old_count)
2364 continue;
2366 for (i = 0; i < old_count; i++){
2367 if (!IsSignatureEqual (old_args [i], new_args [i]))
2368 break;
2370 if (i != old_count)
2371 continue;
2373 return true;
2376 return false;
2380 // We copy methods from `new_members' into `target_list' if the signature
2381 // for the method from in the new list does not exist in the target_list
2383 // The name is assumed to be the same.
2385 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2387 if (target_list == null){
2388 target_list = new ArrayList ();
2390 foreach (MemberInfo mi in new_members){
2391 if (mi is MethodBase)
2392 target_list.Add (mi);
2394 return target_list;
2397 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2398 target_list.CopyTo (target_array, 0);
2400 foreach (MemberInfo mi in new_members){
2401 MethodBase new_method = (MethodBase) mi;
2403 if (!ArrayContainsMethod (target_array, new_method, true))
2404 target_list.Add (new_method);
2406 return target_list;
2409 #region Generics
2410 // <remarks>
2411 // Tracks the generic parameters.
2412 // </remarks>
2413 static PtrHashtable builder_to_type_param;
2415 public static void AddTypeParameter (Type t, TypeParameter tparam)
2417 if (!builder_to_type_param.Contains (t))
2418 builder_to_type_param.Add (t, tparam);
2421 public static TypeParameter LookupTypeParameter (Type t)
2423 return (TypeParameter) builder_to_type_param [t];
2426 // This method always return false for non-generic compiler,
2427 // while Type.IsGenericParameter is returned if it is supported.
2428 public static bool IsGenericParameter (Type type)
2430 #if GMCS_SOURCE
2431 return type.IsGenericParameter;
2432 #else
2433 return false;
2434 #endif
2437 public static int GenericParameterPosition (Type type)
2439 #if GMCS_SOURCE
2440 return type.GenericParameterPosition;
2441 #else
2442 throw new InternalErrorException ("should not be called");
2443 #endif
2446 public static bool IsGenericType (Type type)
2448 #if GMCS_SOURCE
2449 return type.IsGenericType;
2450 #else
2451 return false;
2452 #endif
2455 public static bool IsGenericTypeDefinition (Type type)
2457 #if GMCS_SOURCE
2458 return type.IsGenericTypeDefinition;
2459 #else
2460 return false;
2461 #endif
2464 public static bool ContainsGenericParameters (Type type)
2466 #if GMCS_SOURCE
2467 return type.ContainsGenericParameters;
2468 #else
2469 return false;
2470 #endif
2473 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2475 #if GMCS_SOURCE
2476 if (fi.DeclaringType.IsGenericTypeDefinition ||
2477 !fi.DeclaringType.IsGenericType)
2478 return fi;
2480 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2481 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2482 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2484 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2485 foreach (FieldInfo f in t.GetFields (bf))
2486 if (f.MetadataToken == fi.MetadataToken)
2487 return f;
2488 #endif
2490 return fi;
2493 public static bool IsEqual (Type a, Type b)
2495 if (a.Equals (b)) {
2496 // MS BCL returns true even if enum types are different
2497 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2498 return a.FullName == b.FullName;
2500 // Some types are never equal
2501 if (a == TypeManager.null_type || a == InternalType.AnonymousMethod)
2502 return false;
2504 return true;
2507 if (IsGenericParameter (a) && IsGenericParameter (b)) {
2508 // TODO: needs more testing before cleaning up
2509 //if (a.DeclaringMethod != b.DeclaringMethod &&
2510 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2511 // return false;
2512 #if GMCS_SOURCE
2513 return a.GenericParameterPosition == b.GenericParameterPosition;
2514 #else
2515 throw new NotSupportedException ();
2516 #endif
2519 if (a.IsArray && b.IsArray) {
2520 if (a.GetArrayRank () != b.GetArrayRank ())
2521 return false;
2522 return IsEqual (GetElementType (a), GetElementType (b));
2525 if (a.IsByRef && b.IsByRef)
2526 return IsEqual (a.GetElementType (), b.GetElementType ());
2528 if (IsGenericType (a) && IsGenericType (b)) {
2529 Type adef = DropGenericTypeArguments (a);
2530 Type bdef = DropGenericTypeArguments (b);
2532 if (adef != bdef)
2533 return false;
2535 if (adef.IsEnum && bdef.IsEnum)
2536 return true;
2538 Type[] aargs = GetTypeArguments (a);
2539 Type[] bargs = GetTypeArguments (b);
2541 if (aargs.Length != bargs.Length)
2542 return false;
2544 for (int i = 0; i < aargs.Length; i++) {
2545 if (!IsEqual (aargs [i], bargs [i]))
2546 return false;
2549 return true;
2552 return false;
2555 public static bool IsEqual (Type[] a, Type[] b)
2557 if (a == null || b == null || a.Length != b.Length)
2558 return false;
2560 for (int i = 0; i < a.Length; ++i) {
2561 if (a [i] == null || b [i] == null) {
2562 if (a [i] == b [i])
2563 continue;
2565 return false;
2568 if (!IsEqual (a [i], b [i]))
2569 return false;
2572 return true;
2575 public static Type DropGenericTypeArguments (Type t)
2577 #if GMCS_SOURCE
2578 if (!t.IsGenericType)
2579 return t;
2580 // Micro-optimization: a generic typebuilder is always a generic type definition
2581 if (t is TypeBuilder)
2582 return t;
2583 return t.GetGenericTypeDefinition ();
2584 #else
2585 return t;
2586 #endif
2589 public static MethodBase DropGenericMethodArguments (MethodBase m)
2591 #if GMCS_SOURCE
2592 if (m.IsGenericMethod)
2593 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2595 Type t = m.DeclaringType;
2596 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2597 return m;
2599 t = t.GetGenericTypeDefinition ();
2600 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2601 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2603 #if MS_COMPATIBLE
2604 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2605 return m;
2606 #endif
2608 if (m is ConstructorInfo) {
2609 foreach (ConstructorInfo c in t.GetConstructors (bf))
2610 if (c.MetadataToken == m.MetadataToken)
2611 return c;
2612 } else {
2613 foreach (MethodBase mb in t.GetMethods (bf))
2614 if (mb.MetadataToken == m.MetadataToken)
2615 return mb;
2617 #endif
2619 return m;
2622 public static Type[] GetGenericArguments (MethodBase mi)
2624 #if GMCS_SOURCE
2625 return mi.GetGenericArguments ();
2626 #else
2627 return Type.EmptyTypes;
2628 #endif
2631 public static Type[] GetTypeArguments (Type t)
2633 #if GMCS_SOURCE
2634 DeclSpace tc = LookupDeclSpace (t);
2635 if (tc != null) {
2636 if (!tc.IsGeneric)
2637 return Type.EmptyTypes;
2639 TypeParameter[] tparam = tc.TypeParameters;
2640 Type[] ret = new Type [tparam.Length];
2641 for (int i = 0; i < tparam.Length; i++) {
2642 ret [i] = tparam [i].Type;
2643 if (ret [i] == null)
2644 throw new InternalErrorException ();
2647 return ret;
2648 } else
2649 return t.GetGenericArguments ();
2650 #else
2651 throw new InternalErrorException ();
2652 #endif
2655 public static GenericConstraints GetTypeParameterConstraints (Type t)
2657 #if GMCS_SOURCE
2658 if (!t.IsGenericParameter)
2659 throw new InvalidOperationException ();
2661 TypeParameter tparam = LookupTypeParameter (t);
2662 if (tparam != null)
2663 return tparam.GenericConstraints;
2665 return ReflectionConstraints.GetConstraints (t);
2666 #else
2667 throw new InternalErrorException ();
2668 #endif
2671 public static bool HasGenericArguments (Type t)
2673 return GetNumberOfTypeArguments (t) > 0;
2676 public static int GetNumberOfTypeArguments (Type t)
2678 #if GMCS_SOURCE
2679 if (t.IsGenericParameter)
2680 return 0;
2681 DeclSpace tc = LookupDeclSpace (t);
2682 if (tc != null)
2683 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2684 else
2685 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2686 #else
2687 return 0;
2688 #endif
2691 /// <summary>
2692 /// Check whether `type' and `parent' are both instantiations of the same
2693 /// generic type. Note that we do not check the type parameters here.
2694 /// </summary>
2695 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2697 int tcount = GetNumberOfTypeArguments (type);
2698 int pcount = GetNumberOfTypeArguments (parent);
2700 if (tcount != pcount)
2701 return false;
2703 type = DropGenericTypeArguments (type);
2704 parent = DropGenericTypeArguments (parent);
2706 return type.Equals (parent);
2709 /// <summary>
2710 /// Whether `mb' is a generic method definition.
2711 /// </summary>
2712 public static bool IsGenericMethodDefinition (MethodBase mb)
2714 #if GMCS_SOURCE
2715 if (mb.DeclaringType is TypeBuilder) {
2716 IMethodData method = (IMethodData) builder_to_method [mb];
2717 if (method == null)
2718 return false;
2720 return method.GenericMethod != null;
2723 return mb.IsGenericMethodDefinition;
2724 #else
2725 return false;
2726 #endif
2729 /// <summary>
2730 /// Whether `mb' is a generic method.
2731 /// </summary>
2732 public static bool IsGenericMethod (MethodBase mb)
2734 #if GMCS_SOURCE
2735 return mb.IsGenericMethod;
2736 #else
2737 return false;
2738 #endif
2741 public static bool IsNullableType (Type t)
2743 #if GMCS_SOURCE
2744 return generic_nullable_type == DropGenericTypeArguments (t);
2745 #else
2746 return false;
2747 #endif
2749 #endregion
2751 #region MemberLookup implementation
2754 // Whether we allow private members in the result (since FindMembers
2755 // uses NonPublic for both protected and private), we need to distinguish.
2758 internal class Closure {
2759 internal bool private_ok;
2761 // Who is invoking us and which type is being queried currently.
2762 internal Type invocation_type;
2763 internal Type qualifier_type;
2765 // The assembly that defines the type is that is calling us
2766 internal Assembly invocation_assembly;
2767 internal IList almost_match;
2769 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2771 if (invocation_type == null)
2772 return false;
2774 if (is_static && qualifier_type == null)
2775 // It resolved from a simple name, so it should be visible.
2776 return true;
2778 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2779 return true;
2781 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2782 if (!IsFamilyAccessible (t, m.DeclaringType))
2783 continue;
2785 // Although a derived class can access protected members of its base class
2786 // it cannot do so through an instance of the base class (CS1540).
2787 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2788 if (is_static || qualifier_type == null ||
2789 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2790 IsFamilyAccessible (qualifier_type, t))
2791 return true;
2794 if (almost_match != null)
2795 almost_match.Add (m);
2797 return false;
2801 // This filter filters by name + whether it is ok to include private
2802 // members in the search
2804 internal bool Filter (MemberInfo m, object filter_criteria)
2807 // Hack: we know that the filter criteria will always be in the
2808 // `closure' // fields.
2811 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2812 return false;
2814 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2815 (invocation_type != null) &&
2816 IsPrivateAccessible (m.DeclaringType, invocation_type))
2817 return true;
2820 // Ugly: we need to find out the type of `m', and depending
2821 // on this, tell whether we accept or not
2823 if (m is MethodBase){
2824 MethodBase mb = (MethodBase) m;
2825 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2827 if (ma == MethodAttributes.Public)
2828 return true;
2830 if (ma == MethodAttributes.PrivateScope)
2831 return false;
2833 if (ma == MethodAttributes.Private)
2834 return private_ok ||
2835 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2836 IsNestedChildOf (invocation_type, m.DeclaringType);
2838 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2839 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2840 return true;
2841 } else {
2842 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2843 return false;
2846 // Family, FamORAssem or FamANDAssem
2847 return CheckValidFamilyAccess (mb.IsStatic, m);
2850 if (m is FieldInfo){
2851 FieldInfo fi = (FieldInfo) m;
2852 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2854 if (fa == FieldAttributes.Public)
2855 return true;
2857 if (fa == FieldAttributes.PrivateScope)
2858 return false;
2860 if (fa == FieldAttributes.Private)
2861 return private_ok ||
2862 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2863 IsNestedChildOf (invocation_type, m.DeclaringType);
2865 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2866 if ((fa == FieldAttributes.Assembly) ||
2867 (fa == FieldAttributes.FamORAssem))
2868 return true;
2869 } else {
2870 if ((fa == FieldAttributes.Assembly) ||
2871 (fa == FieldAttributes.FamANDAssem))
2872 return false;
2875 // Family, FamORAssem or FamANDAssem
2876 return CheckValidFamilyAccess (fi.IsStatic, m);
2880 // EventInfos and PropertyInfos, return true because they lack
2881 // permission information, so we need to check later on the methods.
2883 return true;
2887 static Closure closure;
2888 static MemberFilter FilterWithClosure_delegate;
2891 // Looks up a member called `name' in the `queried_type'. This lookup
2892 // is done by code that is contained in the definition for `invocation_type'
2893 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2895 // `invocation_type' is used to check whether we're allowed to access the requested
2896 // member wrt its protection level.
2898 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2899 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2900 // is B and qualifier_type is A). This is used to do the CS1540 check.
2902 // When resolving a SimpleName, `qualifier_type' is null.
2904 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2905 // the same than `queried_type' - except when we're being called from BaseAccess;
2906 // in this case, `invocation_type' is the current type and `queried_type' the base
2907 // type, so this'd normally trigger a CS1540.
2909 // The binding flags are `bf' and the kind of members being looked up are `mt'
2911 // The return value always includes private members which code in `invocation_type'
2912 // is allowed to access (using the specified `qualifier_type' if given); only use
2913 // BindingFlags.NonPublic to bypass the permission check.
2915 // The 'almost_match' argument is used for reporting error CS1540.
2917 // Returns an array of a single element for everything but Methods/Constructors
2918 // that might return multiple matches.
2920 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2921 Type queried_type, MemberTypes mt,
2922 BindingFlags original_bf, string name, IList almost_match)
2924 Timer.StartTimer (TimerType.MemberLookup);
2926 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2927 queried_type, mt, original_bf, name, almost_match);
2929 Timer.StopTimer (TimerType.MemberLookup);
2931 return retval;
2934 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2935 Type queried_type, MemberTypes mt,
2936 BindingFlags original_bf, string name, IList almost_match)
2938 BindingFlags bf = original_bf;
2940 ArrayList method_list = null;
2941 Type current_type = queried_type;
2942 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2943 bool skip_iface_check = true, used_cache = false;
2944 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2946 closure.invocation_type = invocation_type;
2947 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2948 closure.qualifier_type = qualifier_type;
2949 closure.almost_match = almost_match;
2951 // This is from the first time we find a method
2952 // in most cases, we do not actually find a method in the base class
2953 // so we can just ignore it, and save the arraylist allocation
2954 MemberInfo [] first_members_list = null;
2955 bool use_first_members_list = false;
2957 do {
2958 MemberInfo [] list;
2961 // `NonPublic' is lame, because it includes both protected and
2962 // private methods, so we need to control this behavior by
2963 // explicitly tracking if a private method is ok or not.
2965 // The possible cases are:
2966 // public, private and protected (internal does not come into the
2967 // equation)
2969 if ((invocation_type != null) &&
2970 ((invocation_type == current_type) ||
2971 IsNestedChildOf (invocation_type, current_type)) ||
2972 always_ok_flag)
2973 bf = original_bf | BindingFlags.NonPublic;
2974 else
2975 bf = original_bf;
2977 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2979 Timer.StopTimer (TimerType.MemberLookup);
2981 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2983 Timer.StartTimer (TimerType.MemberLookup);
2986 // When queried for an interface type, the cache will automatically check all
2987 // inherited members, so we don't need to do this here. However, this only
2988 // works if we already used the cache in the first iteration of this loop.
2990 // If we used the cache in any further iteration, we can still terminate the
2991 // loop since the cache always looks in all base classes.
2994 if (used_cache)
2995 searching = false;
2996 else
2997 skip_iface_check = false;
2999 if (current_type == TypeManager.object_type)
3000 searching = false;
3001 else {
3002 current_type = current_type.BaseType;
3005 // This happens with interfaces, they have a null
3006 // basetype. Look members up in the Object class.
3008 if (current_type == null) {
3009 current_type = TypeManager.object_type;
3010 searching = true;
3014 if (list.Length == 0)
3015 continue;
3018 // Events and types are returned by both `static' and `instance'
3019 // searches, which means that our above FindMembers will
3020 // return two copies of the same.
3022 if (list.Length == 1 && !(list [0] is MethodBase)){
3023 return list;
3027 // Multiple properties: we query those just to find out the indexer
3028 // name
3030 if (list [0] is PropertyInfo)
3031 return list;
3034 // We found an event: the cache lookup returns both the event and
3035 // its private field.
3037 if (list [0] is EventInfo) {
3038 if ((list.Length == 2) && (list [1] is FieldInfo))
3039 return new MemberInfo [] { list [0] };
3041 return list;
3045 // We found methods, turn the search into "method scan"
3046 // mode.
3049 if (first_members_list != null) {
3050 if (use_first_members_list) {
3051 method_list = CopyNewMethods (method_list, first_members_list);
3052 use_first_members_list = false;
3055 method_list = CopyNewMethods (method_list, list);
3056 } else {
3057 first_members_list = list;
3058 use_first_members_list = true;
3059 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3061 } while (searching);
3063 if (use_first_members_list)
3064 return first_members_list;
3066 if (method_list != null && method_list.Count > 0) {
3067 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3070 // This happens if we already used the cache in the first iteration, in this case
3071 // the cache already looked in all interfaces.
3073 if (skip_iface_check)
3074 return null;
3077 // Interfaces do not list members they inherit, so we have to
3078 // scan those.
3080 if (!queried_type.IsInterface)
3081 return null;
3083 if (queried_type.IsArray)
3084 queried_type = TypeManager.array_type;
3086 Type [] ifaces = GetInterfaces (queried_type);
3087 if (ifaces == null)
3088 return null;
3090 foreach (Type itype in ifaces){
3091 MemberInfo [] x;
3093 x = MemberLookup (null, null, itype, mt, bf, name, null);
3094 if (x != null)
3095 return x;
3098 return null;
3101 const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3102 BindingFlags.Static | BindingFlags.Instance |
3103 BindingFlags.DeclaredOnly;
3105 // Currently is designed to work with external types only
3106 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3108 if (!mb.IsSpecialName)
3109 return null;
3111 string name = mb.Name;
3112 if (name.Length < 5)
3113 return null;
3115 if (name [3] != '_')
3116 return null;
3118 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3119 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3120 Type.FilterName, name.Substring (4));
3122 if (pi == null)
3123 return null;
3125 // This can happen when property is indexer (it can have same name but different parameters)
3126 foreach (PropertyInfo p in pi) {
3127 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3128 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3129 return p;
3134 return null;
3137 // Currently is designed to work with external types only
3138 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3140 if (!mb.IsSpecialName)
3141 return null;
3143 string name = mb.Name;
3144 if (name.Length < 5)
3145 return null;
3147 if (name.StartsWith ("add_"))
3148 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3150 if (name.StartsWith ("remove_"))
3151 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3153 return null;
3156 // Tests whether external method is really special
3157 public static bool IsSpecialMethod (MethodBase mb)
3159 if (!mb.IsSpecialName)
3160 return false;
3162 IMethodData md = TypeManager.GetMethod (mb);
3163 if (md != null)
3164 return (md is AbstractPropertyEventMethod || md is Operator);
3166 PropertyInfo pi = GetPropertyFromAccessor (mb);
3167 if (pi != null)
3168 return IsValidProperty (pi);
3170 if (GetEventFromAccessor (mb) != null)
3171 return true;
3173 string name = mb.Name;
3174 if (name.StartsWith ("op_"))
3175 return Operator.GetName (name) != null;
3177 return false;
3180 // Tests whether imported property is valid C# property.
3181 // TODO: It seems to me that we should do a lot of sanity tests before
3182 // we accept property as C# property
3183 static bool IsValidProperty (PropertyInfo pi)
3185 MethodInfo get_method = pi.GetGetMethod (true);
3186 MethodInfo set_method = pi.GetSetMethod (true);
3187 int g_count = 0;
3188 int s_count = 0;
3189 if (get_method != null && set_method != null) {
3190 g_count = get_method.GetParameters ().Length;
3191 s_count = set_method.GetParameters ().Length;
3192 if (g_count + 1 != s_count)
3193 return false;
3194 } else if (get_method != null) {
3195 g_count = get_method.GetParameters ().Length;
3196 } else if (set_method != null) {
3197 s_count = set_method.GetParameters ().Length;
3201 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3203 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
3204 if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
3205 object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
3206 if (o.Length == 0)
3207 return false;
3209 DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3210 if (dma.MemberName != pi.Name)
3211 return false;
3212 if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3213 return false;
3214 if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3215 return false;
3218 return true;
3221 #endregion
3225 class InternalType
3227 public static readonly Type AnonymousMethod = typeof (AnonymousMethodBody);
3228 public static readonly Type Arglist = typeof (ArglistAccess);
3229 public static readonly Type Dynamic = new DynamicType ();
3230 public static readonly Type MethodGroup = typeof (MethodGroupExpr);
3233 /// <summary>
3234 /// There is exactly one instance of this class per type.
3235 /// </summary>
3236 public sealed class TypeHandle : IMemberContainer {
3237 public readonly IMemberContainer BaseType;
3239 readonly int id = ++next_id;
3240 static int next_id = 0;
3242 static TypeHandle ()
3244 Reset ();
3247 /// <summary>
3248 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3249 /// a TypeHandle yet, a new instance of it is created. This static method
3250 /// ensures that we'll only have one TypeHandle instance per type.
3251 /// </summary>
3252 private static TypeHandle GetTypeHandle (Type t)
3254 TypeHandle handle = (TypeHandle) type_hash [t];
3255 if (handle != null)
3256 return handle;
3258 handle = new TypeHandle (t);
3259 type_hash.Add (t, handle);
3260 return handle;
3263 public static MemberCache GetMemberCache (Type t)
3265 return GetTypeHandle (t).MemberCache;
3268 public static void CleanUp ()
3270 type_hash = null;
3273 public static void Reset ()
3275 type_hash = new PtrHashtable ();
3278 /// <summary>
3279 /// Returns the TypeHandle for TypeManager.object_type.
3280 /// </summary>
3281 public static IMemberContainer ObjectType {
3282 get {
3283 if (object_type != null)
3284 return object_type;
3286 object_type = GetTypeHandle (TypeManager.object_type);
3288 return object_type;
3292 /// <summary>
3293 /// Returns the TypeHandle for TypeManager.array_type.
3294 /// </summary>
3295 public static TypeHandle ArrayType {
3296 get {
3297 if (array_type != null)
3298 return array_type;
3300 array_type = GetTypeHandle (TypeManager.array_type);
3302 return array_type;
3306 private static PtrHashtable type_hash;
3308 private static TypeHandle object_type = null;
3309 private static TypeHandle array_type = null;
3311 private Type type;
3312 private string full_name;
3313 private bool is_interface;
3314 private MemberCache member_cache;
3315 private MemberCache base_cache;
3317 private TypeHandle (Type type)
3319 this.type = type;
3320 full_name = type.FullName != null ? type.FullName : type.Name;
3321 if (type.BaseType != null) {
3322 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3323 BaseType = base_cache.Container;
3324 } else if (type.IsInterface)
3325 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3326 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3327 this.member_cache = new MemberCache (this);
3330 // IMemberContainer methods
3332 public string Name {
3333 get {
3334 return full_name;
3338 public Type Type {
3339 get {
3340 return type;
3344 public MemberCache BaseCache {
3345 get {
3346 return base_cache;
3350 public bool IsInterface {
3351 get {
3352 return is_interface;
3356 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3358 MemberInfo [] members;
3360 if (type is GenericTypeParameterBuilder)
3361 return MemberList.Empty;
3363 #if MS_COMPATIBLE
3364 type = TypeManager.DropGenericTypeArguments (type);
3365 #endif
3366 if (mt == MemberTypes.Event)
3367 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3368 else
3369 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3370 null, null);
3372 if (members.Length == 0)
3373 return MemberList.Empty;
3375 Array.Reverse (members);
3376 return new MemberList (members);
3379 // IMemberFinder methods
3381 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3382 MemberFilter filter, object criteria)
3384 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3387 public MemberCache MemberCache {
3388 get {
3389 return member_cache;
3393 public override string ToString ()
3395 if (BaseType != null)
3396 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3397 else
3398 return "TypeHandle (" + id + "," + Name + ")";