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;
36 namespace System.Reflection
40 [ClassInterface(ClassInterfaceType.AutoDual)]
41 public abstract class Binder
43 protected Binder () {}
45 public abstract FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture);
46 public abstract MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state);
47 public abstract object ChangeType (object value, Type type, CultureInfo culture);
48 public abstract void ReorderArgumentArray( ref object[] args, object state);
49 public abstract MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers);
50 public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers);
52 static readonly Binder default_binder = new Default ();
54 internal static Binder DefaultBinder {
56 return default_binder;
60 internal bool ConvertArgs (object[] args, ParameterInfo[] pinfo, CultureInfo culture, bool exactMatch)
63 if (pinfo.Length == 0)
66 throw new TargetParameterCountException ();
69 if (pinfo.Length != args.Length)
70 throw new TargetParameterCountException ();
72 for (int i = 0; i < args.Length; ++i) {
75 if (arg == Type.Missing) {
76 args [i] = pi.DefaultValue;
80 if (arg != null && arg.GetType () == pi.ParameterType)
86 object v = ChangeType (arg, pi.ParameterType, culture);
87 if (v == null && args [i] != null)
96 internal static int GetDerivedLevel (Type type)
98 Type searchType = type;
101 while (searchType.BaseType != null)
104 searchType = searchType.BaseType;
110 internal static MethodBase FindMostDerivedMatch (MethodBase [] match)
114 int count = match.Length;
116 for (int current = 0; current < count; current++)
118 MethodBase m = match [current];
119 int level = GetDerivedLevel (m.DeclaringType);
120 if (level == highLevel)
121 throw new AmbiguousMatchException ();
122 // If the argument types differ we
123 // have an ambigous match, as well
125 ParameterInfo[] p1 = m.GetParametersInternal ();
126 ParameterInfo[] p2 = match [matchId].GetParametersInternal ();
129 if (p1.Length != p2.Length)
134 for (i = 0; i < p1.Length; ++i) {
135 if (p1 [i].ParameterType != p2 [i].ParameterType) {
143 throw new AmbiguousMatchException ();
146 if (level > highLevel)
153 return match[matchId];
156 internal sealed class Default : Binder {
157 public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture)
160 throw new ArgumentNullException ("match");
161 foreach (FieldInfo f in match) {
162 if (check_type (value.GetType (), f.FieldType))
168 public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
172 types = Type.EmptyTypes;
174 types = new Type [args.Length];
175 for (int i = 0; i < args.Length; ++i) {
176 if (args [i] != null)
177 types [i] = args [i].GetType ();
181 MethodBase selected = null;
183 foreach (var m in match) {
184 var parameters = m.GetParametersInternal ();
188 * Find the corresponding parameter for each parameter name,
189 * reorder types/modifiers array during the search.
191 Type[] newTypes = (Type[])types.Clone ();
192 ParameterModifier[] newModifiers = modifiers != null ? (ParameterModifier[])modifiers.Clone () : null;
193 for (i = 0; i < names.Length; ++i) {
194 /* Find the corresponding parameter */
196 for (int j = 0; j < parameters.Length; ++j) {
197 if (parameters [j].Name == names [i]) {
204 if (i < newTypes.Length && nindex < types.Length)
205 newTypes [i] = types [nindex];
206 if (modifiers != null && i < newModifiers.Length && nindex < modifiers.Length)
207 newModifiers [i] = modifiers [nindex];
209 if (i < names.Length)
212 selected = SelectMethod (bindingAttr, new MethodBase [] { m }, newTypes, newModifiers, true, args);
213 if (selected != null)
217 selected = SelectMethod (bindingAttr, match, types, modifiers, true, args);
221 if (selected != null && names != null)
222 ReorderParameters (names, ref args, selected);
224 if (selected != null) {
226 args = EmptyArray<object>.Value;
228 AdjustArguments (selected, ref args);
234 // probably belongs in ReorderArgumentArray
235 static void AdjustArguments (MethodBase selected, ref object [] args)
237 var parameters = selected.GetParametersInternal ();
238 var parameters_length = parameters.Length;
239 if (parameters_length == 0)
242 var last_parameter = parameters [parameters.Length - 1];
243 Type last_parameter_type = last_parameter.ParameterType;
244 if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
247 var args_length = args.Length;
248 var param_args_count = args_length + 1 - parameters_length;
249 var first_vararg_index = args_length - param_args_count;
250 if (first_vararg_index < args_length) {
251 var first_vararg = args [first_vararg_index];
252 if (first_vararg != null && first_vararg.GetType () == last_parameter_type)
256 var params_args = Array.CreateInstance (last_parameter_type.GetElementType (), param_args_count);
257 for (int i = 0; i < param_args_count; i++)
258 params_args.SetValue (args [first_vararg_index + i], i);
260 var adjusted = new object [parameters_length];
261 Array.Copy (args, adjusted, parameters_length - 1);
263 adjusted [adjusted.Length - 1] = params_args;
267 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
269 object [] newArgs = new object [args.Length];
270 Array.Copy (args, newArgs, args.Length);
271 ParameterInfo [] plist = selected.GetParametersInternal ();
272 for (int n = 0; n < names.Length; n++)
273 for (int p = 0; p < plist.Length; p++) {
274 if (names [n] == plist [p].Name) {
275 newArgs [p] = args [n];
279 Array.Copy (newArgs, args, args.Length);
282 static bool IsArrayAssignable (Type object_type, Type target_type)
284 if (object_type.IsArray && target_type.IsArray)
285 return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
287 if (target_type.IsAssignableFrom (object_type))
293 public override object ChangeType (object value, Type type, CultureInfo culture)
297 Type vtype = value.GetType ();
299 type = type.GetElementType ();
300 if (vtype == type || type.IsInstanceOfType (value))
302 if (vtype.IsArray && type.IsArray){
303 if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
307 if (check_type (vtype, type)) {
308 // These are not supported by Convert
310 return Enum.ToObject (type, value);
311 if (vtype == typeof (Char)) {
312 if (type == typeof (double))
313 return (double)(char)value;
314 if (type == typeof (float))
315 return (float)(char)value;
317 if (vtype == typeof (IntPtr) && type.IsPointer)
319 return Convert.ChangeType (value, type);
324 [MonoTODO ("This method does not do anything in Mono")]
325 public override void ReorderArgumentArray (ref object[] args, object state)
327 //do nothing until we support named arguments
328 //throw new NotImplementedException ();
331 private static bool check_type (Type from, Type to) {
338 if (to.IsByRef != from.IsByRef)
342 return to.IsAssignableFrom (from);
345 to = Enum.GetUnderlyingType (to);
350 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
353 TypeCode fromt = Type.GetTypeCode (from);
354 TypeCode tot = Type.GetTypeCode (to);
359 case TypeCode.UInt16:
360 case TypeCode.UInt32:
362 case TypeCode.UInt64:
364 case TypeCode.Single:
365 case TypeCode.Double:
368 return to == typeof (object);
372 case TypeCode.UInt16:
374 case TypeCode.UInt32:
376 case TypeCode.UInt64:
378 case TypeCode.Single:
379 case TypeCode.Double:
382 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
388 case TypeCode.Single:
389 case TypeCode.Double:
392 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
393 case TypeCode.UInt16:
395 case TypeCode.UInt32:
397 case TypeCode.UInt64:
399 case TypeCode.Single:
400 case TypeCode.Double:
403 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
408 case TypeCode.Single:
409 case TypeCode.Double:
412 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
413 case TypeCode.UInt32:
415 case TypeCode.UInt64:
417 case TypeCode.Single:
418 case TypeCode.Double:
421 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
425 case TypeCode.Single:
426 case TypeCode.Double:
429 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
430 case TypeCode.UInt64:
433 case TypeCode.Single:
434 case TypeCode.Double:
437 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
438 case TypeCode.Single:
439 return tot == TypeCode.Double || to == typeof (object);
441 /* TODO: handle valuetype -> byref */
442 if (to == typeof (object) && from.IsValueType)
444 if (to.IsPointer && from == typeof (IntPtr))
447 return to.IsAssignableFrom (from);
451 private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
452 for (int i = 0; i < types.Length; ++i) {
453 bool match = check_type (types [i], args [i].ParameterType);
454 if (!match && allowByRefMatch) {
455 Type param_type = args [i].ParameterType;
456 if (param_type.IsByRef)
457 match = check_type (types [i], param_type.GetElementType ());
465 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
467 return SelectMethod (bindingAttr, match, types, modifiers,
471 MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch, object[] arguments)
477 throw new ArgumentNullException ("match");
479 /* first look for an exact match... */
480 MethodBase exact_match = null;
481 for (i = 0; i < match.Length; ++i) {
483 if (m.GetParametersCount () != types.Length)
486 ParameterInfo[] args = m.GetParametersInternal ();
487 for (j = 0; j < types.Length; ++j) {
488 if (types [j] != args [j].ParameterType)
491 if (j == types.Length) {
492 if (exact_match != null) {
500 if (exact_match != null)
503 /* Try methods with ParamArray attribute */
504 if (arguments != null) {
505 for (i = 0; i < match.Length; ++i) {
508 var count = m.GetParametersCount ();
509 if (count == 0 || count > types.Length + 1)
512 var pi = m.GetParametersInternal ();
513 if (!Attribute.IsDefined (pi [pi.Length - 1], typeof (ParamArrayAttribute)))
516 var elementType = pi [pi.Length - 1].ParameterType.GetElementType ();
517 for (j = 0; j < types.Length; ++j) {
518 if (j < (pi.Length - 1) && types [j] != pi [j].ParameterType)
521 if (j >= (pi.Length - 1) && types [j] != elementType)
525 if (j == types.Length)
530 if ((bindingAttr & BindingFlags.ExactBinding) != 0)
533 MethodBase result = null;
534 for (i = 0; i < match.Length; ++i) {
536 ParameterInfo[] args = m.GetParametersInternal ();
537 if (args.Length != types.Length)
539 if (!check_arguments (types, args, allowByRefMatch))
543 result = GetBetterMethod (result, m, types);
548 if (result != null || arguments == null || types.Length != arguments.Length)
551 // Xamarin-5278: try with parameters that are COM objects
552 // REVIEW: do we also need to implement best method match?
553 for (i = 0; i < match.Length; ++i) {
555 ParameterInfo[] methodArgs = m.GetParametersInternal ();
556 if (methodArgs.Length != types.Length)
558 for (j = 0; j < types.Length; ++j) {
559 var requiredType = methodArgs [j].ParameterType;
560 if (types [j] == requiredType)
563 if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
564 var iface = Marshal.GetComInterfaceForObject (arguments [j], requiredType);
565 if (iface != IntPtr.Zero) {
566 // the COM object implements the desired interface
567 Marshal.Release (iface);
575 if (j == types.Length)
581 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
583 ParameterInfo [] pl1 = m1.GetParametersInternal ();
584 ParameterInfo [] pl2 = m2.GetParametersInternal ();
586 for (int i = 0; i < pl1.Length; i++) {
587 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
588 if (cmp != 0 && prev != 0 && prev != cmp)
589 throw new AmbiguousMatchException ();
594 return prev > 0 ? m2 : m1;
596 Type dt1 = m1.DeclaringType;
597 Type dt2 = m2.DeclaringType;
599 if (dt1.IsSubclassOf(dt2))
601 if (dt2.IsSubclassOf(dt1))
605 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
606 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
612 throw new AmbiguousMatchException ();
615 int CompareCloserType (Type t1, Type t2)
619 if (t1.IsGenericParameter && !t2.IsGenericParameter)
621 if (!t1.IsGenericParameter && t2.IsGenericParameter)
623 if (t1.HasElementType && t2.HasElementType)
624 return CompareCloserType (
625 t1.GetElementType (),
626 t2.GetElementType ());
628 if (t1.IsSubclassOf (t2))
630 if (t2.IsSubclassOf (t1))
633 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
635 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
638 // What kind of cases could reach here?
642 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
644 if (match == null || match.Length == 0)
645 throw new ArgumentException ("No properties provided", "match");
647 bool haveRet = (returnType != null);
648 int idxlen = (indexes != null) ? indexes.Length : -1;
649 PropertyInfo result = null;
651 int best_score = Int32.MaxValue - 1;
652 int fail_score = Int32.MaxValue;
655 for (i = match.Length - 1; i >= 0; i--) {
656 PropertyInfo p = match [i];
657 ParameterInfo[] args = p.GetIndexParameters ();
658 if (idxlen >= 0 && idxlen != args.Length)
661 if (haveRet && p.PropertyType != returnType)
664 int score = Int32.MaxValue - 1;
666 score = check_arguments_with_score (indexes, args);
671 int new_level = GetDerivedLevel (p.DeclaringType);
672 if (result != null) {
673 if (best_score < score)
676 if (best_score == score) {
677 if (level == new_level) {
678 // Keep searching. May be there's something
684 if (level > new_level)
694 if (fail_score <= best_score)
695 throw new AmbiguousMatchException ();
700 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
704 for (int i = 0; i < types.Length; ++i) {
705 int res = check_type_with_score (types [i], args [i].ParameterType);
716 // 0 -> same type or null and !valuetype
718 // 2 -> value type that don't lose data
719 // 3 -> to == IsAssignableFrom
721 static int check_type_with_score (Type from, Type to)
724 return to.IsValueType ? -1 : 0;
729 if (to == typeof (object))
732 TypeCode fromt = Type.GetTypeCode (from);
733 TypeCode tot = Type.GetTypeCode (to);
738 case TypeCode.UInt16:
741 case TypeCode.UInt32:
743 case TypeCode.UInt64:
745 case TypeCode.Single:
746 case TypeCode.Double:
753 case TypeCode.UInt16:
755 case TypeCode.UInt32:
757 case TypeCode.UInt64:
759 case TypeCode.Single:
760 case TypeCode.Double:
763 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
769 case TypeCode.Single:
770 case TypeCode.Double:
773 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
774 case TypeCode.UInt16:
776 case TypeCode.UInt32:
778 case TypeCode.UInt64:
780 case TypeCode.Single:
781 case TypeCode.Double:
784 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
789 case TypeCode.Single:
790 case TypeCode.Double:
793 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
794 case TypeCode.UInt32:
796 case TypeCode.UInt64:
798 case TypeCode.Single:
799 case TypeCode.Double:
802 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
806 case TypeCode.Single:
807 case TypeCode.Double:
810 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
811 case TypeCode.UInt64:
814 case TypeCode.Single:
815 case TypeCode.Double:
818 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
819 case TypeCode.Single:
820 return tot == TypeCode.Double ? 2 : -1;
822 return (to.IsAssignableFrom (from)) ? 3 : -1;