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 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 ();
166 MethodBase selected = SelectMethod (bindingAttr, match, types, modifiers, true);
169 ReorderParameters (names, ref args, selected);
171 if (selected != null) {
173 args = new object [0];
175 AdjustArguments (selected, ref args);
181 // probably belongs in ReorderArgumentArray
182 static void AdjustArguments (MethodBase selected, ref object [] args)
184 var parameters = selected.GetParameters ();
185 if (parameters.Length == 0)
188 var last_parameter = parameters [parameters.Length - 1];
189 if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
192 var adjusted = new object [parameters.Length];
193 Array.Copy (args, adjusted, parameters.Length - 1);
195 var param_args_count = args.Length + 1 - parameters.Length;
196 var params_args = Array.CreateInstance (last_parameter.ParameterType.GetElementType (), param_args_count);
198 for (int i = 0; i < param_args_count; i++)
199 params_args.SetValue (args [args.Length - param_args_count + i], i);
201 adjusted [adjusted.Length - 1] = params_args;
205 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
207 object [] newArgs = new object [args.Length];
208 Array.Copy (args, newArgs, args.Length);
209 ParameterInfo [] plist = selected.GetParameters ();
210 for (int n = 0; n < names.Length; n++)
211 for (int p = 0; p < plist.Length; p++) {
212 if (names [n] == plist [p].Name) {
213 newArgs [p] = args [n];
217 Array.Copy (newArgs, args, args.Length);
220 static bool IsArrayAssignable (Type object_type, Type target_type)
222 if (object_type.IsArray && target_type.IsArray)
223 return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
225 if (target_type.IsAssignableFrom (object_type))
231 public override object ChangeType (object value, Type type, CultureInfo culture)
235 Type vtype = value.GetType ();
237 type = type.GetElementType ();
238 if (vtype == type || type.IsInstanceOfType (value))
240 if (vtype.IsArray && type.IsArray){
241 if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
245 if (check_type (vtype, type)) {
246 // These are not supported by Convert
248 return Enum.ToObject (type, value);
249 if (vtype == typeof (Char)) {
250 if (type == typeof (double))
251 return (double)(char)value;
252 if (type == typeof (float))
253 return (float)(char)value;
255 if (vtype == typeof (IntPtr) && type.IsPointer)
257 return Convert.ChangeType (value, type);
262 [MonoTODO ("This method does not do anything in Mono")]
263 public override void ReorderArgumentArray (ref object[] args, object state)
265 //do nothing until we support named arguments
266 //throw new NotImplementedException ();
269 private static bool check_type (Type from, Type to) {
276 if (to.IsByRef != from.IsByRef)
280 return to.IsAssignableFrom (from);
283 to = Enum.GetUnderlyingType (to);
288 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
291 TypeCode fromt = Type.GetTypeCode (from);
292 TypeCode tot = Type.GetTypeCode (to);
297 case TypeCode.UInt16:
298 case TypeCode.UInt32:
300 case TypeCode.UInt64:
302 case TypeCode.Single:
303 case TypeCode.Double:
306 return to == typeof (object);
310 case TypeCode.UInt16:
312 case TypeCode.UInt32:
314 case TypeCode.UInt64:
316 case TypeCode.Single:
317 case TypeCode.Double:
320 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
326 case TypeCode.Single:
327 case TypeCode.Double:
330 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
331 case TypeCode.UInt16:
333 case TypeCode.UInt32:
335 case TypeCode.UInt64:
337 case TypeCode.Single:
338 case TypeCode.Double:
341 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
346 case TypeCode.Single:
347 case TypeCode.Double:
350 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
351 case TypeCode.UInt32:
353 case TypeCode.UInt64:
355 case TypeCode.Single:
356 case TypeCode.Double:
359 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
363 case TypeCode.Single:
364 case TypeCode.Double:
367 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
368 case TypeCode.UInt64:
371 case TypeCode.Single:
372 case TypeCode.Double:
375 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
376 case TypeCode.Single:
377 return tot == TypeCode.Double || to == typeof (object);
379 /* TODO: handle valuetype -> byref */
380 if (to == typeof (object) && from.IsValueType)
382 if (to.IsPointer && from == typeof (IntPtr))
385 return to.IsAssignableFrom (from);
389 private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
390 for (int i = 0; i < types.Length; ++i) {
391 bool match = check_type (types [i], args [i].ParameterType);
392 if (!match && allowByRefMatch) {
393 Type param_type = args [i].ParameterType;
394 if (param_type.IsByRef)
395 match = check_type (types [i], param_type.GetElementType ());
403 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
405 return SelectMethod (bindingAttr, match, types, modifiers,
409 MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch)
415 throw new ArgumentNullException ("match");
417 /* first look for an exact match... */
418 MethodBase exact_match = null;
419 for (i = 0; i < match.Length; ++i) {
421 ParameterInfo[] args = m.GetParameters ();
422 if (args.Length != types.Length)
424 for (j = 0; j < types.Length; ++j) {
425 if (types [j] != args [j].ParameterType)
428 if (j == types.Length) {
429 if (exact_match != null) {
437 if (exact_match != null)
440 /* Try methods with ParamArray attribute */
441 bool isdefParamArray = false;
442 Type elementType = null;
443 for (i = 0; i < match.Length; ++i) {
445 ParameterInfo[] args = m.GetParameters ();
446 if (args.Length > types.Length + 1)
448 else if (args.Length == 0)
450 isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
451 if (!isdefParamArray)
453 elementType = args [args.Length - 1].ParameterType.GetElementType ();
454 for (j = 0; j < types.Length; ++j) {
455 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
457 else if (j >= (args.Length - 1) && types [j] != elementType)
460 if (j == types.Length)
464 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
467 MethodBase result = null;
468 for (i = 0; i < match.Length; ++i) {
470 ParameterInfo[] args = m.GetParameters ();
471 if (args.Length != types.Length)
473 if (!check_arguments (types, args, allowByRefMatch))
477 result = GetBetterMethod (result, m, types);
485 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
487 ParameterInfo [] pl1 = m1.GetParameters ();
488 ParameterInfo [] pl2 = m2.GetParameters ();
490 for (int i = 0; i < pl1.Length; i++) {
491 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
492 if (cmp != 0 && prev != 0 && prev != cmp)
493 throw new AmbiguousMatchException ();
498 return prev > 0 ? m2 : m1;
500 Type dt1 = m1.DeclaringType;
501 Type dt2 = m2.DeclaringType;
503 if (dt1.IsSubclassOf(dt2))
505 if (dt2.IsSubclassOf(dt1))
509 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
510 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
516 throw new AmbiguousMatchException ();
519 int CompareCloserType (Type t1, Type t2)
523 if (t1.IsGenericParameter && !t2.IsGenericParameter)
525 if (!t1.IsGenericParameter && t2.IsGenericParameter)
527 if (t1.HasElementType && t2.HasElementType)
528 return CompareCloserType (
529 t1.GetElementType (),
530 t2.GetElementType ());
532 if (t1.IsSubclassOf (t2))
534 if (t2.IsSubclassOf (t1))
537 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
539 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
542 // What kind of cases could reach here?
546 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
548 if (match == null || match.Length == 0)
549 throw new ArgumentException ("No properties provided", "match");
551 bool haveRet = (returnType != null);
552 int idxlen = (indexes != null) ? indexes.Length : -1;
553 PropertyInfo result = null;
555 int best_score = Int32.MaxValue - 1;
556 int fail_score = Int32.MaxValue;
559 for (i = match.Length - 1; i >= 0; i--) {
560 PropertyInfo p = match [i];
561 ParameterInfo[] args = p.GetIndexParameters ();
562 if (idxlen >= 0 && idxlen != args.Length)
565 if (haveRet && p.PropertyType != returnType)
568 int score = Int32.MaxValue - 1;
570 score = check_arguments_with_score (indexes, args);
575 int new_level = GetDerivedLevel (p.DeclaringType);
576 if (result != null) {
577 if (best_score < score)
580 if (best_score == score) {
581 if (level == new_level) {
582 // Keep searching. May be there's something
588 if (level > new_level)
598 if (fail_score <= best_score)
599 throw new AmbiguousMatchException ();
604 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
608 for (int i = 0; i < types.Length; ++i) {
609 int res = check_type_with_score (types [i], args [i].ParameterType);
620 // 0 -> same type or null and !valuetype
622 // 2 -> value type that don't lose data
623 // 3 -> to == IsAssignableFrom
625 static int check_type_with_score (Type from, Type to)
628 return to.IsValueType ? -1 : 0;
633 if (to == typeof (object))
636 TypeCode fromt = Type.GetTypeCode (from);
637 TypeCode tot = Type.GetTypeCode (to);
642 case TypeCode.UInt16:
645 case TypeCode.UInt32:
647 case TypeCode.UInt64:
649 case TypeCode.Single:
650 case TypeCode.Double:
657 case TypeCode.UInt16:
659 case TypeCode.UInt32:
661 case TypeCode.UInt64:
663 case TypeCode.Single:
664 case TypeCode.Double:
667 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
673 case TypeCode.Single:
674 case TypeCode.Double:
677 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
678 case TypeCode.UInt16:
680 case TypeCode.UInt32:
682 case TypeCode.UInt64:
684 case TypeCode.Single:
685 case TypeCode.Double:
688 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
693 case TypeCode.Single:
694 case TypeCode.Double:
697 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
698 case TypeCode.UInt32:
700 case TypeCode.UInt64:
702 case TypeCode.Single:
703 case TypeCode.Double:
706 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
710 case TypeCode.Single:
711 case TypeCode.Double:
714 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
715 case TypeCode.UInt64:
718 case TypeCode.Single:
719 case TypeCode.Double:
722 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
723 case TypeCode.Single:
724 return tot == TypeCode.Double ? 2 : -1;
726 return (to.IsAssignableFrom (from)) ? 3 : -1;