1 // System.Reflection.Binder
4 // Sean MacIsaac (macisaac@ximian.com)
5 // Paolo Molaro (lupus@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (C) Ximian, Inc. 2001 - 2003
9 // (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Globalization;
35 using System.Runtime.InteropServices;
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 static bool ConvertArgs (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture) {
63 if ( pinfo.Length == 0)
66 throw new TargetParameterCountException ();
68 if (pinfo.Length != args.Length)
69 throw new TargetParameterCountException ();
70 for (int i = 0; i < args.Length; ++i) {
71 object v = binder.ChangeType (args [i], pinfo[i].ParameterType, culture);
72 if ((v == null) && (args [i] != null))
79 internal static int GetDerivedLevel (Type type)
81 Type searchType = type;
84 while (searchType.BaseType != null)
87 searchType = searchType.BaseType;
93 internal static MethodBase FindMostDerivedMatch (MethodBase [] match)
97 int count = match.Length;
99 for (int current = 0; current < count; current++)
101 MethodBase m = match [current];
102 int level = GetDerivedLevel (m.DeclaringType);
103 if (level == highLevel)
104 throw new AmbiguousMatchException ();
105 // If the argument types differ we
106 // have an ambigous match, as well
108 ParameterInfo[] p1 = m.GetParameters ();
109 ParameterInfo[] p2 = match [matchId].GetParameters ();
112 if (p1.Length != p2.Length)
117 for (i = 0; i < p1.Length; ++i) {
118 if (p1 [i].ParameterType != p2 [i].ParameterType) {
126 throw new AmbiguousMatchException ();
129 if (level > highLevel)
136 return match[matchId];
139 internal sealed class Default : Binder {
140 public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture)
143 throw new ArgumentNullException ("match");
144 foreach (FieldInfo f in match) {
145 if (check_type (value.GetType (), f.FieldType))
152 // FIXME: There was a MonoTODO, but it does not explain what the problem is
154 public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
158 types = Type.EmptyTypes;
160 types = new Type [args.Length];
161 for (int i = 0; i < args.Length; ++i) {
162 if (args [i] != null)
163 types [i] = args [i].GetType ();
167 MethodBase selected = null;
169 foreach (var m in match) {
170 var parameters = m.GetParameters ();
174 * Find the corresponding parameter for each parameter name,
175 * reorder types/modifiers array during the search.
177 Type[] newTypes = (Type[])types.Clone ();
178 ParameterModifier[] newModifiers = modifiers != null ? (ParameterModifier[])modifiers.Clone () : null;
179 for (i = 0; i < names.Length; ++i) {
180 /* Find the corresponding parameter */
182 for (int j = 0; j < parameters.Length; ++j) {
183 if (parameters [j].Name == names [i]) {
190 if (i < newTypes.Length && nindex < types.Length)
191 newTypes [i] = types [nindex];
192 if (modifiers != null && i < newModifiers.Length && nindex < modifiers.Length)
193 newModifiers [i] = modifiers [nindex];
195 if (i < names.Length)
198 selected = SelectMethod (bindingAttr, new MethodBase [] { m }, newTypes, newModifiers, true, args);
199 if (selected != null)
203 selected = SelectMethod (bindingAttr, match, types, modifiers, true, args);
207 if (selected != null && names != null)
208 ReorderParameters (names, ref args, selected);
210 if (selected != null) {
212 args = new object [0];
214 AdjustArguments (selected, ref args);
220 // probably belongs in ReorderArgumentArray
221 static void AdjustArguments (MethodBase selected, ref object [] args)
223 var parameters = selected.GetParameters ();
224 var parameters_length = parameters.Length;
225 if (parameters_length == 0)
228 var last_parameter = parameters [parameters.Length - 1];
229 Type last_parameter_type = last_parameter.ParameterType;
230 if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
233 var args_length = args.Length;
234 var param_args_count = args_length + 1 - parameters_length;
235 var first_vararg_index = args_length - param_args_count;
236 if (first_vararg_index < args_length) {
237 var first_vararg = args [first_vararg_index];
238 if (first_vararg != null && first_vararg.GetType () == last_parameter_type)
242 var params_args = Array.CreateInstance (last_parameter_type.GetElementType (), param_args_count);
243 for (int i = 0; i < param_args_count; i++)
244 params_args.SetValue (args [first_vararg_index + i], i);
246 var adjusted = new object [parameters_length];
247 Array.Copy (args, adjusted, parameters_length - 1);
249 adjusted [adjusted.Length - 1] = params_args;
253 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
255 object [] newArgs = new object [args.Length];
256 Array.Copy (args, newArgs, args.Length);
257 ParameterInfo [] plist = selected.GetParameters ();
258 for (int n = 0; n < names.Length; n++)
259 for (int p = 0; p < plist.Length; p++) {
260 if (names [n] == plist [p].Name) {
261 newArgs [p] = args [n];
265 Array.Copy (newArgs, args, args.Length);
268 static bool IsArrayAssignable (Type object_type, Type target_type)
270 if (object_type.IsArray && target_type.IsArray)
271 return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
273 if (target_type.IsAssignableFrom (object_type))
279 public override object ChangeType (object value, Type type, CultureInfo culture)
283 Type vtype = value.GetType ();
285 type = type.GetElementType ();
286 if (vtype == type || type.IsInstanceOfType (value))
288 if (vtype.IsArray && type.IsArray){
289 if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
293 if (check_type (vtype, type)) {
294 // These are not supported by Convert
296 return Enum.ToObject (type, value);
297 if (vtype == typeof (Char)) {
298 if (type == typeof (double))
299 return (double)(char)value;
300 if (type == typeof (float))
301 return (float)(char)value;
303 if (vtype == typeof (IntPtr) && type.IsPointer)
305 return Convert.ChangeType (value, type);
310 [MonoTODO ("This method does not do anything in Mono")]
311 public override void ReorderArgumentArray (ref object[] args, object state)
313 //do nothing until we support named arguments
314 //throw new NotImplementedException ();
317 private static bool check_type (Type from, Type to) {
324 if (to.IsByRef != from.IsByRef)
328 return to.IsAssignableFrom (from);
331 to = Enum.GetUnderlyingType (to);
336 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
339 TypeCode fromt = Type.GetTypeCode (from);
340 TypeCode tot = Type.GetTypeCode (to);
345 case TypeCode.UInt16:
346 case TypeCode.UInt32:
348 case TypeCode.UInt64:
350 case TypeCode.Single:
351 case TypeCode.Double:
354 return to == typeof (object);
358 case TypeCode.UInt16:
360 case TypeCode.UInt32:
362 case TypeCode.UInt64:
364 case TypeCode.Single:
365 case TypeCode.Double:
368 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
374 case TypeCode.Single:
375 case TypeCode.Double:
378 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
379 case TypeCode.UInt16:
381 case TypeCode.UInt32:
383 case TypeCode.UInt64:
385 case TypeCode.Single:
386 case TypeCode.Double:
389 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
394 case TypeCode.Single:
395 case TypeCode.Double:
398 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
399 case TypeCode.UInt32:
401 case TypeCode.UInt64:
403 case TypeCode.Single:
404 case TypeCode.Double:
407 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
411 case TypeCode.Single:
412 case TypeCode.Double:
415 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
416 case TypeCode.UInt64:
419 case TypeCode.Single:
420 case TypeCode.Double:
423 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
424 case TypeCode.Single:
425 return tot == TypeCode.Double || to == typeof (object);
427 /* TODO: handle valuetype -> byref */
428 if (to == typeof (object) && from.IsValueType)
430 if (to.IsPointer && from == typeof (IntPtr))
433 return to.IsAssignableFrom (from);
437 private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
438 for (int i = 0; i < types.Length; ++i) {
439 bool match = check_type (types [i], args [i].ParameterType);
440 if (!match && allowByRefMatch) {
441 Type param_type = args [i].ParameterType;
442 if (param_type.IsByRef)
443 match = check_type (types [i], param_type.GetElementType ());
451 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
453 return SelectMethod (bindingAttr, match, types, modifiers,
457 MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch, object[] parameters)
463 throw new ArgumentNullException ("match");
465 /* first look for an exact match... */
466 MethodBase exact_match = null;
467 for (i = 0; i < match.Length; ++i) {
469 ParameterInfo[] args = m.GetParameters ();
470 if (args.Length != types.Length)
472 for (j = 0; j < types.Length; ++j) {
473 if (types [j] != args [j].ParameterType)
476 if (j == types.Length) {
477 if (exact_match != null) {
485 if (exact_match != null)
488 /* Try methods with ParamArray attribute */
489 bool isdefParamArray = false;
490 Type elementType = null;
491 for (i = 0; i < match.Length; ++i) {
493 ParameterInfo[] args = m.GetParameters ();
494 if (args.Length > types.Length + 1)
496 else if (args.Length == 0)
498 isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
499 if (!isdefParamArray)
501 elementType = args [args.Length - 1].ParameterType.GetElementType ();
502 for (j = 0; j < types.Length; ++j) {
503 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
505 else if (j >= (args.Length - 1) && types [j] != elementType)
508 if (j == types.Length)
512 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
515 MethodBase result = null;
516 for (i = 0; i < match.Length; ++i) {
518 ParameterInfo[] args = m.GetParameters ();
519 if (args.Length != types.Length)
521 if (!check_arguments (types, args, allowByRefMatch))
525 result = GetBetterMethod (result, m, types);
530 if (result != null || parameters == null || types.Length != parameters.Length)
533 // Xamarin-5278: try with parameters that are COM objects
534 // REVIEW: do we also need to implement best method match?
535 for (i = 0; i < match.Length; ++i) {
537 ParameterInfo[] methodArgs = m.GetParameters ();
538 if (methodArgs.Length != types.Length)
540 for (j = 0; j < types.Length; ++j) {
541 var requiredType = methodArgs [j].ParameterType;
542 if (types [j] == requiredType)
544 if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
545 var iface = Marshal.GetComInterfaceForObject (parameters [j], requiredType);
546 if (iface != IntPtr.Zero) {
547 // the COM object implements the desired interface
548 Marshal.Release (iface);
555 if (j == types.Length)
561 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
563 ParameterInfo [] pl1 = m1.GetParameters ();
564 ParameterInfo [] pl2 = m2.GetParameters ();
566 for (int i = 0; i < pl1.Length; i++) {
567 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
568 if (cmp != 0 && prev != 0 && prev != cmp)
569 throw new AmbiguousMatchException ();
574 return prev > 0 ? m2 : m1;
576 Type dt1 = m1.DeclaringType;
577 Type dt2 = m2.DeclaringType;
579 if (dt1.IsSubclassOf(dt2))
581 if (dt2.IsSubclassOf(dt1))
585 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
586 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
592 throw new AmbiguousMatchException ();
595 int CompareCloserType (Type t1, Type t2)
599 if (t1.IsGenericParameter && !t2.IsGenericParameter)
601 if (!t1.IsGenericParameter && t2.IsGenericParameter)
603 if (t1.HasElementType && t2.HasElementType)
604 return CompareCloserType (
605 t1.GetElementType (),
606 t2.GetElementType ());
608 if (t1.IsSubclassOf (t2))
610 if (t2.IsSubclassOf (t1))
613 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
615 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
618 // What kind of cases could reach here?
622 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
624 if (match == null || match.Length == 0)
625 throw new ArgumentException ("No properties provided", "match");
627 bool haveRet = (returnType != null);
628 int idxlen = (indexes != null) ? indexes.Length : -1;
629 PropertyInfo result = null;
631 int best_score = Int32.MaxValue - 1;
632 int fail_score = Int32.MaxValue;
635 for (i = match.Length - 1; i >= 0; i--) {
636 PropertyInfo p = match [i];
637 ParameterInfo[] args = p.GetIndexParameters ();
638 if (idxlen >= 0 && idxlen != args.Length)
641 if (haveRet && p.PropertyType != returnType)
644 int score = Int32.MaxValue - 1;
646 score = check_arguments_with_score (indexes, args);
651 int new_level = GetDerivedLevel (p.DeclaringType);
652 if (result != null) {
653 if (best_score < score)
656 if (best_score == score) {
657 if (level == new_level) {
658 // Keep searching. May be there's something
664 if (level > new_level)
674 if (fail_score <= best_score)
675 throw new AmbiguousMatchException ();
680 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
684 for (int i = 0; i < types.Length; ++i) {
685 int res = check_type_with_score (types [i], args [i].ParameterType);
696 // 0 -> same type or null and !valuetype
698 // 2 -> value type that don't lose data
699 // 3 -> to == IsAssignableFrom
701 static int check_type_with_score (Type from, Type to)
704 return to.IsValueType ? -1 : 0;
709 if (to == typeof (object))
712 TypeCode fromt = Type.GetTypeCode (from);
713 TypeCode tot = Type.GetTypeCode (to);
718 case TypeCode.UInt16:
721 case TypeCode.UInt32:
723 case TypeCode.UInt64:
725 case TypeCode.Single:
726 case TypeCode.Double:
733 case TypeCode.UInt16:
735 case TypeCode.UInt32:
737 case TypeCode.UInt64:
739 case TypeCode.Single:
740 case TypeCode.Double:
743 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
749 case TypeCode.Single:
750 case TypeCode.Double:
753 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
754 case TypeCode.UInt16:
756 case TypeCode.UInt32:
758 case TypeCode.UInt64:
760 case TypeCode.Single:
761 case TypeCode.Double:
764 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.UInt32:
776 case TypeCode.UInt64:
778 case TypeCode.Single:
779 case TypeCode.Double:
782 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
786 case TypeCode.Single:
787 case TypeCode.Double:
790 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
791 case TypeCode.UInt64:
794 case TypeCode.Single:
795 case TypeCode.Double:
798 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
799 case TypeCode.Single:
800 return tot == TypeCode.Double ? 2 : -1;
802 return (to.IsAssignableFrom (from)) ? 3 : -1;