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);
173 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
175 object [] newArgs = new object [args.Length];
176 Array.Copy (args, newArgs, args.Length);
177 ParameterInfo [] plist = selected.GetParameters ();
178 for (int n = 0; n < names.Length; n++)
179 for (int p = 0; p < plist.Length; p++) {
180 if (names [n] == plist [p].Name) {
181 newArgs [p] = args [n];
185 Array.Copy (newArgs, args, args.Length);
188 static bool IsArrayAssignable (Type object_type, Type target_type)
190 if (object_type.IsArray && target_type.IsArray)
191 return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
193 if (target_type.IsAssignableFrom (object_type))
199 public override object ChangeType (object value, Type type, CultureInfo culture)
203 Type vtype = value.GetType ();
205 type = type.GetElementType ();
206 if (vtype == type || type.IsInstanceOfType (value))
208 if (vtype.IsArray && type.IsArray){
209 if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
213 if (check_type (vtype, type)) {
214 // These are not supported by Convert
216 return Enum.ToObject (type, value);
217 if (vtype == typeof (Char)) {
218 if (type == typeof (double))
219 return (double)(char)value;
220 if (type == typeof (float))
221 return (float)(char)value;
223 if (vtype == typeof (IntPtr) && type.IsPointer)
225 return Convert.ChangeType (value, type);
230 [MonoTODO ("This method does not do anything in Mono")]
231 public override void ReorderArgumentArray (ref object[] args, object state)
233 //do nothing until we support named arguments
234 //throw new NotImplementedException ();
237 private static bool check_type (Type from, Type to) {
244 if (to.IsByRef != from.IsByRef)
248 return to.IsAssignableFrom (from);
251 to = Enum.GetUnderlyingType (to);
256 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
259 TypeCode fromt = Type.GetTypeCode (from);
260 TypeCode tot = Type.GetTypeCode (to);
265 case TypeCode.UInt16:
266 case TypeCode.UInt32:
268 case TypeCode.UInt64:
270 case TypeCode.Single:
271 case TypeCode.Double:
274 return to == typeof (object);
278 case TypeCode.UInt16:
280 case TypeCode.UInt32:
282 case TypeCode.UInt64:
284 case TypeCode.Single:
285 case TypeCode.Double:
288 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
294 case TypeCode.Single:
295 case TypeCode.Double:
298 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
299 case TypeCode.UInt16:
301 case TypeCode.UInt32:
303 case TypeCode.UInt64:
305 case TypeCode.Single:
306 case TypeCode.Double:
309 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
314 case TypeCode.Single:
315 case TypeCode.Double:
318 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
319 case TypeCode.UInt32:
321 case TypeCode.UInt64:
323 case TypeCode.Single:
324 case TypeCode.Double:
327 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
331 case TypeCode.Single:
332 case TypeCode.Double:
335 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
336 case TypeCode.UInt64:
339 case TypeCode.Single:
340 case TypeCode.Double:
343 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
344 case TypeCode.Single:
345 return tot == TypeCode.Double || to == typeof (object);
347 /* TODO: handle valuetype -> byref */
348 if (to == typeof (object) && from.IsValueType)
350 if (to.IsPointer && from == typeof (IntPtr))
353 return to.IsAssignableFrom (from);
357 private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
358 for (int i = 0; i < types.Length; ++i) {
359 bool match = check_type (types [i], args [i].ParameterType);
360 if (!match && allowByRefMatch) {
361 Type param_type = args [i].ParameterType;
362 if (param_type.IsByRef)
363 match = check_type (types [i], param_type.GetElementType ());
371 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
373 return SelectMethod (bindingAttr, match, types, modifiers,
377 MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch)
383 throw new ArgumentNullException ("match");
385 /* first look for an exact match... */
386 for (i = 0; i < match.Length; ++i) {
388 ParameterInfo[] args = m.GetParameters ();
389 if (args.Length != types.Length)
391 for (j = 0; j < types.Length; ++j) {
392 if (types [j] != args [j].ParameterType)
395 if (j == types.Length)
399 /* Try methods with ParamArray attribute */
400 bool isdefParamArray = false;
401 Type elementType = null;
402 for (i = 0; i < match.Length; ++i) {
404 ParameterInfo[] args = m.GetParameters ();
405 if (args.Length > types.Length)
407 else if (args.Length == 0)
409 isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
410 if (!isdefParamArray)
412 elementType = args [args.Length - 1].ParameterType.GetElementType ();
413 for (j = 0; j < types.Length; ++j) {
414 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
416 else if (j >= (args.Length - 1) && types [j] != elementType)
419 if (j == types.Length)
423 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
426 MethodBase result = null;
427 for (i = 0; i < match.Length; ++i) {
429 ParameterInfo[] args = m.GetParameters ();
430 if (args.Length != types.Length)
432 if (!check_arguments (types, args, allowByRefMatch))
436 result = GetBetterMethod (result, m, types);
444 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
446 if (m1.IsGenericMethodDefinition &&
447 !m2.IsGenericMethodDefinition)
449 if (m2.IsGenericMethodDefinition &&
450 !m1.IsGenericMethodDefinition)
453 ParameterInfo [] pl1 = m1.GetParameters ();
454 ParameterInfo [] pl2 = m2.GetParameters ();
456 for (int i = 0; i < pl1.Length; i++) {
457 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
458 if (cmp != 0 && prev != 0 && prev != cmp)
459 throw new AmbiguousMatchException ();
464 return prev > 0 ? m2 : m1;
466 Type dt1 = m1.DeclaringType;
467 Type dt2 = m2.DeclaringType;
469 if (dt1.IsSubclassOf(dt2))
471 if (dt2.IsSubclassOf(dt1))
475 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
476 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
482 throw new AmbiguousMatchException ();
485 int CompareCloserType (Type t1, Type t2)
489 if (t1.IsGenericParameter && !t2.IsGenericParameter)
491 if (!t1.IsGenericParameter && t2.IsGenericParameter)
493 if (t1.HasElementType && t2.HasElementType)
494 return CompareCloserType (
495 t1.GetElementType (),
496 t2.GetElementType ());
498 if (t1.IsSubclassOf (t2))
500 if (t2.IsSubclassOf (t1))
503 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
505 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
508 // What kind of cases could reach here?
512 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
514 if (match == null || match.Length == 0)
515 throw new ArgumentException ("No properties provided", "match");
517 bool haveRet = (returnType != null);
518 int idxlen = (indexes != null) ? indexes.Length : -1;
519 PropertyInfo result = null;
521 int best_score = Int32.MaxValue - 1;
522 int fail_score = Int32.MaxValue;
525 for (i = match.Length - 1; i >= 0; i--) {
526 PropertyInfo p = match [i];
527 ParameterInfo[] args = p.GetIndexParameters ();
528 if (idxlen >= 0 && idxlen != args.Length)
531 if (haveRet && p.PropertyType != returnType)
534 int score = Int32.MaxValue - 1;
536 score = check_arguments_with_score (indexes, args);
541 int new_level = GetDerivedLevel (p.DeclaringType);
542 if (result != null) {
543 if (best_score < score)
546 if (best_score == score) {
547 if (level == new_level) {
548 // Keep searching. May be there's something
554 if (level > new_level)
564 if (fail_score <= best_score)
565 throw new AmbiguousMatchException ();
570 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
574 for (int i = 0; i < types.Length; ++i) {
575 int res = check_type_with_score (types [i], args [i].ParameterType);
586 // 0 -> same type or null and !valuetype
588 // 2 -> value type that don't lose data
589 // 3 -> to == IsAssignableFrom
591 static int check_type_with_score (Type from, Type to)
594 return to.IsValueType ? -1 : 0;
599 if (to == typeof (object))
602 TypeCode fromt = Type.GetTypeCode (from);
603 TypeCode tot = Type.GetTypeCode (to);
608 case TypeCode.UInt16:
611 case TypeCode.UInt32:
613 case TypeCode.UInt64:
615 case TypeCode.Single:
616 case TypeCode.Double:
623 case TypeCode.UInt16:
625 case TypeCode.UInt32:
627 case TypeCode.UInt64:
629 case TypeCode.Single:
630 case TypeCode.Double:
633 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
639 case TypeCode.Single:
640 case TypeCode.Double:
643 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
644 case TypeCode.UInt16:
646 case TypeCode.UInt32:
648 case TypeCode.UInt64:
650 case TypeCode.Single:
651 case TypeCode.Double:
654 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
659 case TypeCode.Single:
660 case TypeCode.Double:
663 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
664 case TypeCode.UInt32:
666 case TypeCode.UInt64:
668 case TypeCode.Single:
669 case TypeCode.Double:
672 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
676 case TypeCode.Single:
677 case TypeCode.Double:
680 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
681 case TypeCode.UInt64:
684 case TypeCode.Single:
685 case TypeCode.Double:
688 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
689 case TypeCode.Single:
690 return tot == TypeCode.Double ? 2 : -1;
692 return (to.IsAssignableFrom (from)) ? 3 : -1;