1 // System.Reflection.Binder
4 // Sean MacIsaac (macisaac@ximian.com)
5 // Paolo Molaro (lupus@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // (C) Ximian, Inc. 2001 - 2003
10 // (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
11 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Globalization;
34 using System.Runtime.InteropServices;
35 using System.Collections.Generic;
37 namespace System.Reflection
41 [ClassInterface(ClassInterfaceType.AutoDual)]
42 public abstract class Binder
44 protected Binder () {}
46 public abstract FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture);
47 public abstract MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state);
48 public abstract object ChangeType (object value, Type type, CultureInfo culture);
49 public abstract void ReorderArgumentArray( ref object[] args, object state);
50 public abstract MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers);
51 public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers);
53 static readonly Binder default_binder = new Default ();
55 internal static Binder DefaultBinder {
57 return default_binder;
61 internal void ConvertValues (object[] args, ParameterInfo[] pinfo, CultureInfo culture, bool exactMatch)
64 if (pinfo.Length == 0)
67 throw new TargetParameterCountException ();
70 if (pinfo.Length != args.Length)
71 throw new TargetParameterCountException ();
73 for (int i = 0; i < args.Length; ++i) {
76 if (arg == Type.Missing) {
77 args [i] = pi.DefaultValue;
81 args [i] = ConvertValue (arg, pi.ParameterType, culture, exactMatch);
85 internal object ConvertValue (object value, Type type, CultureInfo culture, bool exactMatch)
88 var res = TryConvertToType (value, type, ref failed);
92 if (exactMatch || this == default_binder)
93 throw new ArgumentException ("Object type " + value.GetType() + " cannot be converted to target type: " + type.FullName);
95 return ChangeType (value, type, culture);
98 object TryConvertToType (object value, Type type, ref bool failed)
100 if (type.IsInstanceOfType (value)) {
105 var elementType = type.GetElementType ();
106 if (value == null || elementType.IsInstanceOfType (value)) {
115 type = Enum.GetUnderlyingType (type);
116 if (type == value.GetType ())
120 if (type.IsPrimitive) {
121 var res = IsConvertibleToPrimitiveType (value, type);
124 } else if (type.IsPointer) {
125 var vtype = value.GetType ();
126 if (vtype == typeof (IntPtr) || vtype == typeof (UIntPtr))
134 // Binder uses some incompatible conversion rules. For example
135 // int value cannot be used with decimal parameter but in other
136 // ways it's more flexible than normal convertor, for example
137 // long value can be used with int based enum
138 static object IsConvertibleToPrimitiveType (object value, Type targetType)
140 var type = value.GetType ();
142 type = Enum.GetUnderlyingType (type);
143 if (type == targetType)
147 var from = Type.GetTypeCode (type);
148 var to = Type.GetTypeCode (targetType);
154 return (Char) (Byte) value;
155 case TypeCode.UInt16:
162 return (Int16) (Byte) value;
164 return (Int16) (SByte) value;
167 case TypeCode.UInt16:
170 return (UInt16) (Byte) value;
178 return (Int32) (Byte) value;
180 return (Int32) (SByte) value;
182 return (Int32) (Char) value;
184 return (Int32) (Int16) value;
185 case TypeCode.UInt16:
186 return (Int32) (UInt16) value;
189 case TypeCode.UInt32:
192 return (UInt32) (Byte) value;
194 return (UInt32) (Char) value;
195 case TypeCode.UInt16:
196 return (UInt32) (UInt16) value;
202 return (Int64) (Byte) value;
204 return (Int64) (SByte) value;
206 return (Int64) (Int16) value;
208 return (Int64) (Char) value;
209 case TypeCode.UInt16:
210 return (Int64) (UInt16) value;
212 return (Int64) (Int32) value;
213 case TypeCode.UInt32:
214 return (Int64) (UInt32) value;
217 case TypeCode.UInt64:
220 return (UInt64) (Byte) value;
222 return (UInt64) (Char) value;
223 case TypeCode.UInt16:
224 return (UInt64) (UInt16) value;
225 case TypeCode.UInt32:
226 return (UInt64) (UInt32) value;
229 case TypeCode.Single:
232 return (Single) (Byte) value;
234 return (Single) (SByte) value;
236 return (Single) (Int16) value;
238 return (Single) (Char) value;
239 case TypeCode.UInt16:
240 return (Single) (UInt16) value;
242 return (Single) (Int32) value;
243 case TypeCode.UInt32:
244 return (Single) (UInt32) value;
246 return (Single) (Int64) value;
247 case TypeCode.UInt64:
248 return (Single) (UInt64) value;
251 case TypeCode.Double:
254 return (Double) (Byte) value;
256 return (Double) (SByte) value;
258 return (Double) (Char) value;
260 return (Double) (Int16) value;
261 case TypeCode.UInt16:
262 return (Double) (UInt16) value;
264 return (Double) (Int32) value;
265 case TypeCode.UInt32:
266 return (Double) (UInt32) value;
268 return (Double) (Int64) value;
269 case TypeCode.UInt64:
270 return (Double) (UInt64) value;
271 case TypeCode.Single:
272 return (Double) (Single) value;
277 // Everything else is rejected
281 internal static int GetDerivedLevel (Type type)
283 Type searchType = type;
286 while (searchType.BaseType != null)
289 searchType = searchType.BaseType;
295 internal static MethodBase FindMostDerivedMatch (MethodBase [] match)
299 int count = match.Length;
301 for (int current = 0; current < count; current++)
303 MethodBase m = match [current];
304 int level = GetDerivedLevel (m.DeclaringType);
305 if (level == highLevel)
306 throw new AmbiguousMatchException ();
307 // If the argument types differ we
308 // have an ambigous match, as well
310 ParameterInfo[] p1 = m.GetParametersInternal ();
311 ParameterInfo[] p2 = match [matchId].GetParametersInternal ();
314 if (p1.Length != p2.Length)
319 for (i = 0; i < p1.Length; ++i) {
320 if (p1 [i].ParameterType != p2 [i].ParameterType) {
328 throw new AmbiguousMatchException ();
331 if (level > highLevel)
338 return match[matchId];
341 internal sealed class Default : Binder {
342 public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture)
345 throw new ArgumentNullException ("match");
346 foreach (FieldInfo f in match) {
347 if (check_type (value.GetType (), f.FieldType))
353 public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
357 types = Type.EmptyTypes;
359 types = new Type [args.Length];
360 for (int i = 0; i < args.Length; ++i) {
361 if (args [i] != null)
362 types [i] = args [i].GetType ();
366 MethodBase selected = null;
368 foreach (var m in match) {
369 var parameters = m.GetParametersInternal ();
373 * Find the corresponding parameter for each parameter name,
374 * reorder types/modifiers array during the search.
376 Type[] newTypes = new Type [types.Length];
377 Array.FastCopy (types, 0, newTypes, 0, types.Length);
379 ParameterModifier[] newModifiers = null;
380 if (modifiers != null) {
381 newModifiers = new ParameterModifier [modifiers.Length];
382 Array.FastCopy (modifiers, 0, newModifiers, 0, modifiers.Length);
385 for (i = 0; i < names.Length; ++i) {
386 /* Find the corresponding parameter */
388 for (int j = 0; j < parameters.Length; ++j) {
389 if (parameters [j].Name == names [i]) {
396 if (i < newTypes.Length && nindex < types.Length)
397 newTypes [i] = types [nindex];
398 if (modifiers != null && i < newModifiers.Length && nindex < modifiers.Length)
399 newModifiers [i] = modifiers [nindex];
401 if (i < names.Length)
404 selected = SelectMethod (bindingAttr, new MethodBase [] { m }, newTypes, newModifiers, true, ref args);
405 if (selected != null)
409 selected = SelectMethod (bindingAttr, match, types, modifiers, true, ref args);
413 if (selected != null && names != null)
414 ReorderParameters (names, ref args, selected);
416 if (selected != null) {
418 args = EmptyArray<object>.Value;
420 AdjustArguments (selected, ref args);
426 // probably belongs in ReorderArgumentArray
427 static void AdjustArguments (MethodBase selected, ref object [] args)
429 var parameters = selected.GetParametersInternal ();
430 var parameters_length = parameters.Length;
431 if (parameters_length == 0)
434 var last_parameter = parameters [parameters.Length - 1];
435 Type last_parameter_type = last_parameter.ParameterType;
436 if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
439 var args_length = args.Length;
440 var param_args_count = args_length + 1 - parameters_length;
441 var first_vararg_index = args_length - param_args_count;
442 if (first_vararg_index < args_length) {
443 var first_vararg = args [first_vararg_index];
444 if (first_vararg != null && first_vararg.GetType () == last_parameter_type)
448 var params_args = Array.CreateInstance (last_parameter_type.GetElementType (), param_args_count);
449 for (int i = 0; i < param_args_count; i++)
450 params_args.SetValue (args [first_vararg_index + i], i);
452 var adjusted = new object [parameters_length];
453 Array.Copy (args, adjusted, parameters_length - 1);
455 adjusted [adjusted.Length - 1] = params_args;
459 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
461 object [] newArgs = new object [args.Length];
462 Array.Copy (args, newArgs, args.Length);
463 ParameterInfo [] plist = selected.GetParametersInternal ();
464 for (int n = 0; n < names.Length; n++)
465 for (int p = 0; p < plist.Length; p++) {
466 if (names [n] == plist [p].Name) {
467 newArgs [p] = args [n];
471 Array.Copy (newArgs, args, args.Length);
474 public override object ChangeType (object value, Type type, CultureInfo culture)
476 throw new NotSupportedException ();
479 [MonoTODO ("This method does not do anything in Mono")]
480 public override void ReorderArgumentArray (ref object[] args, object state)
482 //do nothing until we support named arguments
483 //throw new NotImplementedException ();
486 private static bool check_type (Type from, Type to) {
493 if (to.IsByRef != from.IsByRef)
497 return to.IsAssignableFrom (from);
500 to = Enum.GetUnderlyingType (to);
505 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
508 TypeCode fromt = Type.GetTypeCode (from);
509 TypeCode tot = Type.GetTypeCode (to);
514 case TypeCode.UInt16:
515 case TypeCode.UInt32:
517 case TypeCode.UInt64:
519 case TypeCode.Single:
520 case TypeCode.Double:
523 return to == typeof (object);
527 case TypeCode.UInt16:
529 case TypeCode.UInt32:
531 case TypeCode.UInt64:
533 case TypeCode.Single:
534 case TypeCode.Double:
537 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
543 case TypeCode.Single:
544 case TypeCode.Double:
547 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
548 case TypeCode.UInt16:
550 case TypeCode.UInt32:
552 case TypeCode.UInt64:
554 case TypeCode.Single:
555 case TypeCode.Double:
558 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
563 case TypeCode.Single:
564 case TypeCode.Double:
567 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
568 case TypeCode.UInt32:
570 case TypeCode.UInt64:
572 case TypeCode.Single:
573 case TypeCode.Double:
576 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
580 case TypeCode.Single:
581 case TypeCode.Double:
584 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
585 case TypeCode.UInt64:
588 case TypeCode.Single:
589 case TypeCode.Double:
592 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
593 case TypeCode.Single:
594 return tot == TypeCode.Double || to == typeof (object);
596 /* TODO: handle valuetype -> byref */
597 if (to == typeof (object) && from.IsValueType)
599 if (to.IsPointer && from == typeof (IntPtr))
602 return to.IsAssignableFrom (from);
606 private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
607 for (int i = 0; i < types.Length; ++i) {
608 bool match = check_type (types [i], args [i].ParameterType);
609 if (!match && allowByRefMatch) {
610 Type param_type = args [i].ParameterType;
611 if (param_type.IsByRef)
612 match = check_type (types [i], param_type.GetElementType ());
620 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
622 object[] args = null;
623 return SelectMethod (bindingAttr, match, types, modifiers, false, ref args);
626 MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch, ref object[] arguments)
632 throw new ArgumentNullException ("match");
634 /* first look for an exact match... */
635 MethodBase exact_match = null;
636 for (i = 0; i < match.Length; ++i) {
638 if (m.GetParametersCount () != types.Length)
641 ParameterInfo[] args = m.GetParametersInternal ();
642 for (j = 0; j < types.Length; ++j) {
643 if (types [j] != args [j].ParameterType)
646 if (j == types.Length) {
647 if (exact_match != null) {
655 if (exact_match != null)
658 /* Try methods with ParamArray attribute */
659 if (arguments != null) {
660 for (i = 0; i < match.Length; ++i) {
663 var count = m.GetParametersCount ();
664 if (count == 0 || count > types.Length + 1)
667 var pi = m.GetParametersInternal ();
668 if (!Attribute.IsDefined (pi [pi.Length - 1], typeof (ParamArrayAttribute)))
671 var elementType = pi [pi.Length - 1].ParameterType.GetElementType ();
672 for (j = 0; j < types.Length; ++j) {
673 if (j < (pi.Length - 1) && types [j] != pi [j].ParameterType)
676 if (j >= (pi.Length - 1) && types [j] != elementType)
680 if (j == types.Length)
685 if ((bindingAttr & BindingFlags.ExactBinding) != 0)
688 MethodBase result = null;
689 ParameterInfo[] result_pi = null;
690 for (i = 0; i < match.Length; ++i) {
692 var pi = m.GetParametersInternal ();
694 if (pi.Length != types.Length) {
695 if ((bindingAttr & BindingFlags.OptionalParamBinding) == 0)
698 List<ParameterInfo> pi_reduced = null;
699 for (var ii = pi.Length - 1; ii >= 0; --ii) {
700 if ((pi [ii].Attributes & ParameterAttributes.HasDefault) == 0)
703 if (pi_reduced == null) {
704 pi_reduced = new List<ParameterInfo> (pi);
707 pi_reduced.RemoveAt (ii);
710 if (pi_reduced == null || pi_reduced.Count != types.Length)
713 pi = pi_reduced.ToArray ();
716 if (!check_arguments (types, pi, allowByRefMatch))
719 if (result != null) {
720 result = GetBetterMethod (result, m, types);
729 if (result != null) {
730 i = arguments == null ? 0 : arguments.Length;
731 Array.Resize (ref arguments, result_pi.Length);
732 for (; i < arguments.Length; ++i)
733 arguments [i] = result_pi [i].DefaultValue;
738 if (arguments == null || types.Length != arguments.Length)
741 // Xamarin-5278: try with parameters that are COM objects
742 // REVIEW: do we also need to implement best method match?
743 for (i = 0; i < match.Length; ++i) {
745 ParameterInfo[] methodArgs = m.GetParametersInternal ();
746 if (methodArgs.Length != types.Length)
748 for (j = 0; j < types.Length; ++j) {
749 var requiredType = methodArgs [j].ParameterType;
750 if (types [j] == requiredType)
753 if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
754 var iface = Marshal.GetComInterfaceForObject (arguments [j], requiredType);
755 if (iface != IntPtr.Zero) {
756 // the COM object implements the desired interface
757 Marshal.Release (iface);
765 if (j == types.Length)
771 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
773 ParameterInfo [] pl1 = m1.GetParametersInternal ();
774 ParameterInfo [] pl2 = m2.GetParametersInternal ();
776 for (int i = 0; i < pl1.Length; i++) {
777 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
778 if (cmp != 0 && prev != 0 && prev != cmp)
779 throw new AmbiguousMatchException ();
784 return prev > 0 ? m2 : m1;
786 Type dt1 = m1.DeclaringType;
787 Type dt2 = m2.DeclaringType;
789 if (dt1.IsSubclassOf(dt2))
791 if (dt2.IsSubclassOf(dt1))
795 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
796 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
802 throw new AmbiguousMatchException ();
805 int CompareCloserType (Type t1, Type t2)
809 if (t1.IsGenericParameter && !t2.IsGenericParameter)
811 if (!t1.IsGenericParameter && t2.IsGenericParameter)
813 if (t1.HasElementType && t2.HasElementType)
814 return CompareCloserType (
815 t1.GetElementType (),
816 t2.GetElementType ());
818 if (t1.IsSubclassOf (t2))
820 if (t2.IsSubclassOf (t1))
823 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
825 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
828 // What kind of cases could reach here?
832 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
834 if (match == null || match.Length == 0)
835 throw new ArgumentException ("No properties provided", "match");
837 bool haveRet = (returnType != null);
838 int idxlen = (indexes != null) ? indexes.Length : -1;
839 PropertyInfo result = null;
841 int best_score = Int32.MaxValue - 1;
842 int fail_score = Int32.MaxValue;
845 for (i = match.Length - 1; i >= 0; i--) {
846 PropertyInfo p = match [i];
847 ParameterInfo[] args = p.GetIndexParameters ();
848 if (idxlen >= 0 && idxlen != args.Length)
851 if (haveRet && p.PropertyType != returnType)
854 int score = Int32.MaxValue - 1;
856 score = check_arguments_with_score (indexes, args);
861 int new_level = GetDerivedLevel (p.DeclaringType);
862 if (result != null) {
863 if (best_score < score)
866 if (best_score == score) {
867 if (level == new_level) {
868 // Keep searching. May be there's something
874 if (level > new_level)
884 if (fail_score <= best_score)
885 throw new AmbiguousMatchException ();
890 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
894 for (int i = 0; i < types.Length; ++i) {
895 int res = check_type_with_score (types [i], args [i].ParameterType);
906 // 0 -> same type or null and !valuetype
908 // 2 -> value type that don't lose data
909 // 3 -> to == IsAssignableFrom
911 static int check_type_with_score (Type from, Type to)
914 return to.IsValueType ? -1 : 0;
919 if (to == typeof (object))
922 TypeCode fromt = Type.GetTypeCode (from);
923 TypeCode tot = Type.GetTypeCode (to);
928 case TypeCode.UInt16:
931 case TypeCode.UInt32:
933 case TypeCode.UInt64:
935 case TypeCode.Single:
936 case TypeCode.Double:
943 case TypeCode.UInt16:
945 case TypeCode.UInt32:
947 case TypeCode.UInt64:
949 case TypeCode.Single:
950 case TypeCode.Double:
953 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
959 case TypeCode.Single:
960 case TypeCode.Double:
963 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
964 case TypeCode.UInt16:
966 case TypeCode.UInt32:
968 case TypeCode.UInt64:
970 case TypeCode.Single:
971 case TypeCode.Double:
974 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
979 case TypeCode.Single:
980 case TypeCode.Double:
983 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
984 case TypeCode.UInt32:
986 case TypeCode.UInt64:
988 case TypeCode.Single:
989 case TypeCode.Double:
992 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
996 case TypeCode.Single:
997 case TypeCode.Double:
1000 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
1001 case TypeCode.UInt64:
1002 case TypeCode.Int64:
1004 case TypeCode.Single:
1005 case TypeCode.Double:
1008 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
1009 case TypeCode.Single:
1010 return tot == TypeCode.Double ? 2 : -1;
1012 return (to.IsAssignableFrom (from)) ? 3 : -1;