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.GetParameters ();
126 ParameterInfo[] p2 = match [matchId].GetParameters ();
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.GetParameters ();
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 = new object [0];
228 AdjustArguments (selected, ref args);
234 // probably belongs in ReorderArgumentArray
235 static void AdjustArguments (MethodBase selected, ref object [] args)
237 var parameters = selected.GetParameters ();
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.GetParameters ();
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[] parameters)
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 ParameterInfo[] args = m.GetParameters ();
484 if (args.Length != types.Length)
486 for (j = 0; j < types.Length; ++j) {
487 if (types [j] != args [j].ParameterType)
490 if (j == types.Length) {
491 if (exact_match != null) {
499 if (exact_match != null)
502 /* Try methods with ParamArray attribute */
503 bool isdefParamArray = false;
504 Type elementType = null;
505 for (i = 0; i < match.Length; ++i) {
507 ParameterInfo[] args = m.GetParameters ();
508 if (args.Length > types.Length + 1)
510 else if (args.Length == 0)
512 isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
513 if (!isdefParamArray)
515 elementType = args [args.Length - 1].ParameterType.GetElementType ();
516 for (j = 0; j < types.Length; ++j) {
517 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
519 else if (j >= (args.Length - 1) && types [j] != elementType)
522 if (j == types.Length)
526 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
529 MethodBase result = null;
530 for (i = 0; i < match.Length; ++i) {
532 ParameterInfo[] args = m.GetParameters ();
533 if (args.Length != types.Length)
535 if (!check_arguments (types, args, allowByRefMatch))
539 result = GetBetterMethod (result, m, types);
544 if (result != null || parameters == null || types.Length != parameters.Length)
547 // Xamarin-5278: try with parameters that are COM objects
548 // REVIEW: do we also need to implement best method match?
549 for (i = 0; i < match.Length; ++i) {
551 ParameterInfo[] methodArgs = m.GetParameters ();
552 if (methodArgs.Length != types.Length)
554 for (j = 0; j < types.Length; ++j) {
555 var requiredType = methodArgs [j].ParameterType;
556 if (types [j] == requiredType)
558 if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
559 var iface = Marshal.GetComInterfaceForObject (parameters [j], requiredType);
560 if (iface != IntPtr.Zero) {
561 // the COM object implements the desired interface
562 Marshal.Release (iface);
569 if (j == types.Length)
575 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
577 ParameterInfo [] pl1 = m1.GetParameters ();
578 ParameterInfo [] pl2 = m2.GetParameters ();
580 for (int i = 0; i < pl1.Length; i++) {
581 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
582 if (cmp != 0 && prev != 0 && prev != cmp)
583 throw new AmbiguousMatchException ();
588 return prev > 0 ? m2 : m1;
590 Type dt1 = m1.DeclaringType;
591 Type dt2 = m2.DeclaringType;
593 if (dt1.IsSubclassOf(dt2))
595 if (dt2.IsSubclassOf(dt1))
599 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
600 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
606 throw new AmbiguousMatchException ();
609 int CompareCloserType (Type t1, Type t2)
613 if (t1.IsGenericParameter && !t2.IsGenericParameter)
615 if (!t1.IsGenericParameter && t2.IsGenericParameter)
617 if (t1.HasElementType && t2.HasElementType)
618 return CompareCloserType (
619 t1.GetElementType (),
620 t2.GetElementType ());
622 if (t1.IsSubclassOf (t2))
624 if (t2.IsSubclassOf (t1))
627 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
629 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
632 // What kind of cases could reach here?
636 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
638 if (match == null || match.Length == 0)
639 throw new ArgumentException ("No properties provided", "match");
641 bool haveRet = (returnType != null);
642 int idxlen = (indexes != null) ? indexes.Length : -1;
643 PropertyInfo result = null;
645 int best_score = Int32.MaxValue - 1;
646 int fail_score = Int32.MaxValue;
649 for (i = match.Length - 1; i >= 0; i--) {
650 PropertyInfo p = match [i];
651 ParameterInfo[] args = p.GetIndexParameters ();
652 if (idxlen >= 0 && idxlen != args.Length)
655 if (haveRet && p.PropertyType != returnType)
658 int score = Int32.MaxValue - 1;
660 score = check_arguments_with_score (indexes, args);
665 int new_level = GetDerivedLevel (p.DeclaringType);
666 if (result != null) {
667 if (best_score < score)
670 if (best_score == score) {
671 if (level == new_level) {
672 // Keep searching. May be there's something
678 if (level > new_level)
688 if (fail_score <= best_score)
689 throw new AmbiguousMatchException ();
694 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
698 for (int i = 0; i < types.Length; ++i) {
699 int res = check_type_with_score (types [i], args [i].ParameterType);
710 // 0 -> same type or null and !valuetype
712 // 2 -> value type that don't lose data
713 // 3 -> to == IsAssignableFrom
715 static int check_type_with_score (Type from, Type to)
718 return to.IsValueType ? -1 : 0;
723 if (to == typeof (object))
726 TypeCode fromt = Type.GetTypeCode (from);
727 TypeCode tot = Type.GetTypeCode (to);
732 case TypeCode.UInt16:
735 case TypeCode.UInt32:
737 case TypeCode.UInt64:
739 case TypeCode.Single:
740 case TypeCode.Double:
747 case TypeCode.UInt16:
749 case TypeCode.UInt32:
751 case TypeCode.UInt64:
753 case TypeCode.Single:
754 case TypeCode.Double:
757 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
763 case TypeCode.Single:
764 case TypeCode.Double:
767 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
768 case TypeCode.UInt16:
770 case TypeCode.UInt32:
772 case TypeCode.UInt64:
774 case TypeCode.Single:
775 case TypeCode.Double:
778 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
783 case TypeCode.Single:
784 case TypeCode.Double:
787 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
788 case TypeCode.UInt32:
790 case TypeCode.UInt64:
792 case TypeCode.Single:
793 case TypeCode.Double:
796 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
800 case TypeCode.Single:
801 case TypeCode.Double:
804 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
805 case TypeCode.UInt64:
808 case TypeCode.Single:
809 case TypeCode.Double:
812 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
813 case TypeCode.Single:
814 return tot == TypeCode.Double ? 2 : -1;
816 return (to.IsAssignableFrom (from)) ? 3 : -1;