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
43 [ClassInterface(ClassInterfaceType.AutoDual)]
44 public abstract class Binder
46 protected Binder () {}
48 public abstract FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture);
49 public abstract MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state);
50 public abstract object ChangeType (object value, Type type, CultureInfo culture);
51 public abstract void ReorderArgumentArray( ref object[] args, object state);
52 public abstract MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers);
53 public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers);
55 static Binder default_binder = new Default ();
57 internal static Binder DefaultBinder {
59 return default_binder;
63 internal static bool ConvertArgs (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture) {
65 if ( pinfo.Length == 0)
68 throw new TargetParameterCountException ();
70 if (pinfo.Length != args.Length)
71 throw new TargetParameterCountException ();
72 for (int i = 0; i < args.Length; ++i) {
73 object v = binder.ChangeType (args [i], pinfo[i].ParameterType, culture);
74 if ((v == null) && (args [i] != null))
81 internal static int GetDerivedLevel (Type type)
83 Type searchType = type;
86 while (searchType.BaseType != null)
89 searchType = searchType.BaseType;
95 internal static MethodBase FindMostDerivedMatch (MethodBase [] match)
99 int count = match.Length;
101 for (int current = 0; current < count; current++)
103 MethodBase m = match [current];
104 int level = GetDerivedLevel (m.DeclaringType);
105 if (level == highLevel)
106 throw new AmbiguousMatchException ();
107 // If the argument types differ we
108 // have an ambigous match, as well
110 ParameterInfo[] p1 = m.GetParameters ();
111 ParameterInfo[] p2 = match [matchId].GetParameters ();
114 if (p1.Length != p2.Length)
119 for (i = 0; i < p1.Length; ++i) {
120 if (p1 [i].ParameterType != p2 [i].ParameterType) {
128 throw new AmbiguousMatchException ();
131 if (level > highLevel)
138 return match[matchId];
141 internal sealed class Default : Binder {
142 public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture)
145 throw new ArgumentNullException ("match");
146 foreach (FieldInfo f in match) {
147 if (check_type (value.GetType (), f.FieldType))
154 // FIXME: There was a MonoTODO, but it does not explain what the problem is
156 public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
160 types = Type.EmptyTypes;
162 types = new Type [args.Length];
163 for (int i = 0; i < args.Length; ++i) {
164 if (args [i] != null)
165 types [i] = args [i].GetType ();
168 MethodBase selected = SelectMethod (bindingAttr, match, types, modifiers);
171 ReorderParameters (names, ref args, selected);
175 void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
177 object [] newArgs = new object [args.Length];
178 Array.Copy (args, newArgs, args.Length);
179 ParameterInfo [] plist = selected.GetParameters ();
180 for (int n = 0; n < names.Length; n++)
181 for (int p = 0; p < plist.Length; p++) {
182 if (names [n] == plist [p].Name) {
183 newArgs [p] = args [n];
187 Array.Copy (newArgs, args, args.Length);
190 static bool IsArrayAssignable (Type object_type, Type target_type)
192 if (object_type.IsArray && target_type.IsArray)
193 return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
195 if (target_type.IsAssignableFrom (object_type))
201 public override object ChangeType (object value, Type type, CultureInfo culture)
205 Type vtype = value.GetType ();
207 type = type.GetElementType ();
208 if (vtype == type || type.IsInstanceOfType (value))
210 if (vtype.IsArray && type.IsArray){
211 if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
215 if (check_type (vtype, type))
216 return Convert.ChangeType (value, type);
220 [MonoTODO ("This method does not do anything in Mono")]
221 public override void ReorderArgumentArray (ref object[] args, object state)
223 //do nothing until we support named arguments
224 //throw new NotImplementedException ();
227 private static bool check_type (Type from, Type to) {
234 TypeCode fromt = Type.GetTypeCode (from);
235 TypeCode tot = Type.GetTypeCode (to);
237 if (to.IsByRef != from.IsByRef)
241 return to.IsAssignableFrom (from);
246 case TypeCode.UInt16:
247 case TypeCode.UInt32:
249 case TypeCode.UInt64:
251 case TypeCode.Single:
252 case TypeCode.Double:
255 return to == typeof (object);
259 case TypeCode.UInt16:
261 case TypeCode.UInt32:
263 case TypeCode.UInt64:
265 case TypeCode.Single:
266 case TypeCode.Double:
269 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
275 case TypeCode.Single:
276 case TypeCode.Double:
279 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
280 case TypeCode.UInt16:
282 case TypeCode.UInt32:
284 case TypeCode.UInt64:
286 case TypeCode.Single:
287 case TypeCode.Double:
290 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
295 case TypeCode.Single:
296 case TypeCode.Double:
299 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
300 case TypeCode.UInt32:
302 case TypeCode.UInt64:
304 case TypeCode.Single:
305 case TypeCode.Double:
308 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
312 case TypeCode.Single:
313 case TypeCode.Double:
316 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
317 case TypeCode.UInt64:
320 case TypeCode.Single:
321 case TypeCode.Double:
324 return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
325 case TypeCode.Single:
326 return tot == TypeCode.Double || to == typeof (object);
328 /* TODO: handle valuetype -> byref */
329 if (to == typeof (object) && from.IsValueType)
332 return to.IsAssignableFrom (from);
336 private static bool check_arguments (Type[] types, ParameterInfo[] args) {
337 for (int i = 0; i < types.Length; ++i) {
338 if (!check_type (types [i], args [i].ParameterType))
344 public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
350 throw new ArgumentNullException ("match");
352 /* first look for an exact match... */
353 for (i = 0; i < match.Length; ++i) {
355 ParameterInfo[] args = m.GetParameters ();
356 if (args.Length != types.Length)
358 for (j = 0; j < types.Length; ++j) {
359 if (types [j] != args [j].ParameterType)
362 if (j == types.Length)
366 /* Try methods with ParamArray attribute */
367 bool isdefParamArray = false;
368 Type elementType = null;
369 for (i = 0; i < match.Length; ++i) {
371 ParameterInfo[] args = m.GetParameters ();
372 if (args.Length > types.Length)
374 else if (args.Length == 0)
376 isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
377 if (!isdefParamArray)
379 elementType = args [args.Length - 1].ParameterType.GetElementType ();
380 for (j = 0; j < types.Length; ++j) {
381 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
383 else if (j >= (args.Length - 1) && types [j] != elementType)
386 if (j == types.Length)
390 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
393 MethodBase result = null;
394 for (i = 0; i < match.Length; ++i) {
396 ParameterInfo[] args = m.GetParameters ();
397 if (args.Length != types.Length)
399 if (!check_arguments (types, args))
403 result = GetBetterMethod (result, m, types);
411 MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
414 if (m1.IsGenericMethodDefinition &&
415 !m2.IsGenericMethodDefinition)
417 if (m2.IsGenericMethodDefinition &&
418 !m1.IsGenericMethodDefinition)
422 ParameterInfo [] pl1 = m1.GetParameters ();
423 ParameterInfo [] pl2 = m2.GetParameters ();
425 for (int i = 0; i < pl1.Length; i++) {
426 int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
427 if (cmp != 0 && prev != 0 && prev != cmp)
428 throw new AmbiguousMatchException ();
433 return prev > 0 ? m2 : m1;
435 Type dt1 = m1.DeclaringType;
436 Type dt2 = m2.DeclaringType;
438 if (dt1.IsSubclassOf(dt2))
440 if (dt2.IsSubclassOf(dt1))
444 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
445 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
451 throw new AmbiguousMatchException ();
454 int CompareCloserType (Type t1, Type t2)
459 if (t1.IsGenericParameter && !t2.IsGenericParameter)
461 if (!t1.IsGenericParameter && t2.IsGenericParameter)
464 if (t1.HasElementType && t2.HasElementType)
465 return CompareCloserType (
466 t1.GetElementType (),
467 t2.GetElementType ());
469 if (t1.IsSubclassOf (t2))
471 if (t2.IsSubclassOf (t1))
474 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
476 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
479 // What kind of cases could reach here?
483 public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
485 if (match == null || match.Length == 0)
486 throw new ArgumentException ("No properties provided", "match");
488 bool haveRet = (returnType != null);
489 int idxlen = (indexes != null) ? indexes.Length : -1;
490 PropertyInfo result = null;
492 int best_score = Int32.MaxValue - 1;
493 int fail_score = Int32.MaxValue;
496 for (i = match.Length - 1; i >= 0; i--) {
497 PropertyInfo p = match [i];
498 ParameterInfo[] args = p.GetIndexParameters ();
499 if (idxlen >= 0 && idxlen != args.Length)
502 if (haveRet && !check_type (p.PropertyType, returnType))
505 int score = Int32.MaxValue - 1;
507 score = check_arguments_with_score (indexes, args);
512 int new_level = GetDerivedLevel (p.DeclaringType);
513 if (result != null) {
514 if (best_score < score)
517 if (best_score == score) {
518 if (level == new_level) {
519 // Keep searching. May be there's something
525 if (level > new_level)
535 if (fail_score <= best_score)
536 throw new AmbiguousMatchException ();
541 static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
545 for (int i = 0; i < types.Length; ++i) {
546 int res = check_type_with_score (types [i], args [i].ParameterType);
557 // 0 -> same type or null and !valuetype
559 // 2 -> value type that don't lose data
560 // 3 -> to == IsAssignableFrom
562 static int check_type_with_score (Type from, Type to)
565 return to.IsValueType ? -1 : 0;
570 if (to == typeof (object))
573 TypeCode fromt = Type.GetTypeCode (from);
574 TypeCode tot = Type.GetTypeCode (to);
579 case TypeCode.UInt16:
582 case TypeCode.UInt32:
584 case TypeCode.UInt64:
586 case TypeCode.Single:
587 case TypeCode.Double:
594 case TypeCode.UInt16:
596 case TypeCode.UInt32:
598 case TypeCode.UInt64:
600 case TypeCode.Single:
601 case TypeCode.Double:
604 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
610 case TypeCode.Single:
611 case TypeCode.Double:
614 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
615 case TypeCode.UInt16:
617 case TypeCode.UInt32:
619 case TypeCode.UInt64:
621 case TypeCode.Single:
622 case TypeCode.Double:
625 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
630 case TypeCode.Single:
631 case TypeCode.Double:
634 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
635 case TypeCode.UInt32:
637 case TypeCode.UInt64:
639 case TypeCode.Single:
640 case TypeCode.Double:
643 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
647 case TypeCode.Single:
648 case TypeCode.Double:
651 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
652 case TypeCode.UInt64:
655 case TypeCode.Single:
656 case TypeCode.Double:
659 return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
660 case TypeCode.Single:
661 return tot == TypeCode.Double ? 2 : -1;
663 return (to.IsAssignableFrom (from)) ? 3 : -1;