Optimize parameters handling to do much less allocation
[mono.git] / mcs / class / corlib / System.Reflection / Binder.cs
1 // System.Reflection.Binder
2 //
3 // Authors:
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)
8 //
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)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 using System.Globalization;
34 using System.Runtime.InteropServices;
35
36 namespace System.Reflection
37 {
38         [ComVisible (true)]
39         [Serializable]
40         [ClassInterface(ClassInterfaceType.AutoDual)]
41         public abstract class Binder
42         {
43                 protected Binder () {}
44
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);
51
52                 static readonly Binder default_binder = new Default ();
53
54                 internal static Binder DefaultBinder {
55                         get {
56                                 return default_binder;
57                         }
58                 }
59                 
60                 internal bool ConvertArgs (object[] args, ParameterInfo[] pinfo, CultureInfo culture, bool exactMatch)
61                 {
62                         if (args == null) {
63                                 if (pinfo.Length == 0)
64                                         return true;
65                                 
66                                 throw new TargetParameterCountException ();
67                         }
68
69                         if (pinfo.Length != args.Length)
70                                 throw new TargetParameterCountException ();
71                         
72                         for (int i = 0; i < args.Length; ++i) {
73                                 var arg = args [i];
74                                 var pi = pinfo [i];
75                                 if (arg == Type.Missing) {
76                                         args [i] = pi.DefaultValue;
77                                         continue;
78                                 }
79
80                                 if (arg != null && arg.GetType () == pi.ParameterType)
81                                         continue;
82
83                                 if (exactMatch)
84                                         return false;
85
86                                 object v = ChangeType (arg, pi.ParameterType, culture);
87                                 if (v == null && args [i] != null)
88                                         return false;
89         
90                                 args [i] = v;
91                         }
92
93                         return true;
94                 }
95
96                 internal static int GetDerivedLevel (Type type) 
97                 {
98                         Type searchType = type;
99                         int level = 1;
100
101                         while (searchType.BaseType != null) 
102                         {
103                                 level++;
104                                 searchType = searchType.BaseType;
105                         }
106
107                         return level;
108                 }
109
110                 internal static MethodBase FindMostDerivedMatch (MethodBase [] match) 
111                 {
112                         int highLevel = 0;
113                         int matchId = -1;
114                         int count = match.Length;
115
116                         for (int current = 0; current < count; current++) 
117                         {
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
124                                 if (matchId >= 0) {
125                                         ParameterInfo[] p1 = m.GetParametersInternal ();
126                                         ParameterInfo[] p2 = match [matchId].GetParametersInternal ();
127                                         bool equal = true;
128
129                                         if (p1.Length != p2.Length)
130                                                 equal = false;
131                                         else {
132                                                 int i;
133
134                                                 for (i = 0; i < p1.Length; ++i) {
135                                                         if (p1 [i].ParameterType != p2 [i].ParameterType) {
136                                                                 equal = false;
137                                                                 break;
138                                                         }
139                                                 }
140                                         }
141
142                                         if (!equal)
143                                                 throw new AmbiguousMatchException ();
144                                 }
145
146                                 if (level > highLevel) 
147                                 {
148                                         highLevel = level;
149                                         matchId = current;
150                                 }
151                         }
152
153                         return match[matchId];
154                 }
155
156                 internal sealed class Default : Binder {
157                         public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) 
158                         {
159                                 if (match == null)
160                                         throw new ArgumentNullException ("match");
161                                 foreach (FieldInfo f in match) {
162                                         if (check_type (value.GetType (), f.FieldType))
163                                                 return f;
164                                 }
165                                 return null;
166                         }
167
168                         public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
169                         {
170                                 Type[] types;
171                                 if (args == null)
172                                         types = Type.EmptyTypes;
173                                 else {
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 ();
178                                         }
179                                 }
180
181                                 MethodBase selected = null;
182                                 if (names != null) {
183                                         foreach (var m in match) {
184                                                 var parameters = m.GetParametersInternal ();
185                                                 int i;
186
187                                                 /*
188                                                  * Find the corresponding parameter for each parameter name,
189                                                  * reorder types/modifiers array during the search.
190                                                  */
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 */
195                                                         int nindex = -1;
196                                                         for (int j = 0; j < parameters.Length; ++j) {
197                                                                 if (parameters [j].Name == names [i]) {
198                                                                         nindex = j;
199                                                                         break;
200                                                                 }
201                                                         }
202                                                         if (nindex == -1)
203                                                                 break;
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];
208                                                 }
209                                                 if (i < names.Length)
210                                                         continue;
211
212                                                 selected = SelectMethod (bindingAttr, new MethodBase [] { m }, newTypes, newModifiers, true, args);
213                                                 if (selected != null)
214                                                         break;
215                                         }
216                                 } else {
217                                         selected = SelectMethod (bindingAttr, match, types, modifiers, true, args);
218                                 }
219
220                                 state = null;
221                                 if (selected != null && names != null)
222                                         ReorderParameters (names, ref args, selected);
223
224                                 if (selected != null) {
225                                         if (args == null)
226                                                 args = EmptyArray<object>.Value;
227         
228                                         AdjustArguments (selected, ref args);
229                                 }
230
231                                 return selected;
232                         }
233
234                         // probably belongs in ReorderArgumentArray
235                         static void AdjustArguments (MethodBase selected, ref object [] args)
236                         {
237                                 var parameters = selected.GetParametersInternal ();
238                                 var parameters_length = parameters.Length;
239                                 if (parameters_length == 0)
240                                         return;
241
242                                 var last_parameter = parameters [parameters.Length - 1];
243                                 Type last_parameter_type = last_parameter.ParameterType;
244                                 if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
245                                         return;
246
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)
253                                                 return;
254                                 }
255                                 
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);
259
260                                 var adjusted = new object [parameters_length];
261                                 Array.Copy (args, adjusted, parameters_length - 1);
262                                 
263                                 adjusted [adjusted.Length - 1] = params_args;
264                                 args = adjusted;
265                         }
266
267                         void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
268                         {
269                                 object [] newArgs = new object [args.Length];
270                                 Array.Copy (args, newArgs, args.Length);
271                                 ParameterInfo [] plist = selected.GetParametersInternal ();
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];
276                                                         break;
277                                                 }
278                                         }
279                                 Array.Copy (newArgs, args, args.Length);
280                         }
281
282                         static bool IsArrayAssignable (Type object_type, Type target_type)
283                         {
284                                 if (object_type.IsArray && target_type.IsArray)
285                                         return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
286                                                 
287                                 if (target_type.IsAssignableFrom (object_type))
288                                         return true;
289
290                                 return false;
291                         }
292                         
293                         public override object ChangeType (object value, Type type, CultureInfo culture)
294                         {
295                                 if (value == null)
296                                         return null;
297                                 Type vtype = value.GetType ();
298                                 if (type.IsByRef)
299                                         type = type.GetElementType ();
300                                 if (vtype == type || type.IsInstanceOfType (value))
301                                         return value;
302                                 if (vtype.IsArray && type.IsArray){
303                                         if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
304                                                 return value;
305                                 }
306
307                                 if (check_type (vtype, type)) {
308                                         // These are not supported by Convert
309                                         if (type.IsEnum)
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;
316                                         }
317                                         if (vtype == typeof (IntPtr) && type.IsPointer)
318                                                 return value;
319                                         return Convert.ChangeType (value, type);
320                                 }
321                                 return null;
322                         }
323
324                         [MonoTODO ("This method does not do anything in Mono")]
325                         public override void ReorderArgumentArray (ref object[] args, object state)
326                         {
327                                 //do nothing until we support named arguments
328                                 //throw new NotImplementedException ();
329                         }
330
331                         private static bool check_type (Type from, Type to) {
332                                 if (from == to)
333                                         return true;
334
335                                 if (from == null)
336                                         return true;
337
338                                 if (to.IsByRef != from.IsByRef)
339                                         return false;
340
341                                 if (to.IsInterface)
342                                         return to.IsAssignableFrom (from);
343
344                                 if (to.IsEnum) {
345                                         to = Enum.GetUnderlyingType (to);
346                                         if (from == to)
347                                                 return true;
348                                 }
349
350                                 if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
351                                         return true;
352
353                                 TypeCode fromt = Type.GetTypeCode (from);
354                                 TypeCode tot = Type.GetTypeCode (to);
355
356                                 switch (fromt) {
357                                 case TypeCode.Char:
358                                         switch (tot) {
359                                         case TypeCode.UInt16:
360                                         case TypeCode.UInt32:
361                                         case TypeCode.Int32:
362                                         case TypeCode.UInt64:
363                                         case TypeCode.Int64:
364                                         case TypeCode.Single:
365                                         case TypeCode.Double:
366                                                 return true;
367                                         }
368                                         return to == typeof (object);
369                                 case TypeCode.Byte:
370                                         switch (tot) {
371                                         case TypeCode.Char:
372                                         case TypeCode.UInt16:
373                                         case TypeCode.Int16:
374                                         case TypeCode.UInt32:
375                                         case TypeCode.Int32:
376                                         case TypeCode.UInt64:
377                                         case TypeCode.Int64:
378                                         case TypeCode.Single:
379                                         case TypeCode.Double:
380                                                 return true;
381                                         }
382                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
383                                 case TypeCode.SByte:
384                                         switch (tot) {
385                                         case TypeCode.Int16:
386                                         case TypeCode.Int32:
387                                         case TypeCode.Int64:
388                                         case TypeCode.Single:
389                                         case TypeCode.Double:
390                                                 return true;
391                                         }
392                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
393                                 case TypeCode.UInt16:
394                                         switch (tot) {
395                                         case TypeCode.UInt32:
396                                         case TypeCode.Int32:
397                                         case TypeCode.UInt64:
398                                         case TypeCode.Int64:
399                                         case TypeCode.Single:
400                                         case TypeCode.Double:
401                                                 return true;
402                                         }
403                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
404                                 case TypeCode.Int16:
405                                         switch (tot) {
406                                         case TypeCode.Int32:
407                                         case TypeCode.Int64:
408                                         case TypeCode.Single:
409                                         case TypeCode.Double:
410                                                 return true;
411                                         }
412                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
413                                 case TypeCode.UInt32:
414                                         switch (tot) {
415                                         case TypeCode.UInt64:
416                                         case TypeCode.Int64:
417                                         case TypeCode.Single:
418                                         case TypeCode.Double:
419                                                 return true;
420                                         }
421                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
422                                 case TypeCode.Int32:
423                                         switch (tot) {
424                                         case TypeCode.Int64:
425                                         case TypeCode.Single:
426                                         case TypeCode.Double:
427                                                 return true;
428                                         }
429                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
430                                 case TypeCode.UInt64:
431                                 case TypeCode.Int64:
432                                         switch (tot) {
433                                         case TypeCode.Single:
434                                         case TypeCode.Double:
435                                                 return true;
436                                         }
437                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
438                                 case TypeCode.Single:
439                                         return tot == TypeCode.Double || to == typeof (object);
440                                 default:
441                                         /* TODO: handle valuetype -> byref */
442                                         if (to == typeof (object) && from.IsValueType)
443                                                 return true;
444                                         if (to.IsPointer && from == typeof (IntPtr))
445                                                 return true;
446
447                                         return to.IsAssignableFrom (from);
448                                 }
449                         }
450
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 ());
458                                         }
459                                         if (!match)
460                                                 return false;
461                                 }
462                                 return true;
463                         }
464
465                         public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
466                         {
467                                 return SelectMethod (bindingAttr, match, types, modifiers,
468                                         false, null);
469                         }
470
471                         MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch, object[] arguments)
472                         {
473                                 MethodBase m;
474                                 int i, j;
475
476                                 if (match == null)
477                                         throw new ArgumentNullException ("match");
478
479                                 /* first look for an exact match... */
480                                 MethodBase exact_match = null;
481                                 for (i = 0; i < match.Length; ++i) {
482                                         m = match [i];
483                                         if (m.GetParametersCount () != types.Length)
484                                                 continue;
485
486                                         ParameterInfo[] args = m.GetParametersInternal ();
487                                         for (j = 0; j < types.Length; ++j) {
488                                                 if (types [j] != args [j].ParameterType)
489                                                         break;
490                                         }
491                                         if (j == types.Length) {
492                                                 if (exact_match != null) {
493                                                         exact_match = null;
494                                                         break;
495                                                 } else {
496                                                         exact_match = m;
497                                                 }
498                                         }
499                                 }
500                                 if (exact_match != null)
501                                         return exact_match;
502
503                                 /* Try methods with ParamArray attribute */
504                                 if (arguments != null) {
505                                         for (i = 0; i < match.Length; ++i) {
506                                                 m = match [i];
507
508                                                 var count = m.GetParametersCount ();
509                                                 if (count == 0 || count > types.Length + 1)
510                                                         continue;
511
512                                                 var pi = m.GetParametersInternal ();
513                                                 if (!Attribute.IsDefined (pi [pi.Length - 1], typeof (ParamArrayAttribute)))
514                                                         continue;
515
516                                                 var elementType = pi [pi.Length - 1].ParameterType.GetElementType ();
517                                                 for (j = 0; j < types.Length; ++j) {
518                                                         if (j < (pi.Length - 1) && types [j] != pi [j].ParameterType)
519                                                                 break;
520                                                         
521                                                         if (j >= (pi.Length - 1) && types [j] != elementType) 
522                                                                 break;
523                                                 }
524
525                                                 if (j == types.Length)
526                                                         return m;
527                                         }
528                                 }
529
530                                 if ((bindingAttr & BindingFlags.ExactBinding) != 0)
531                                         return null;
532
533                                 MethodBase result = null;
534                                 for (i = 0; i < match.Length; ++i) {
535                                         m = match [i];
536                                         ParameterInfo[] args = m.GetParametersInternal ();
537                                         if (args.Length != types.Length)
538                                                 continue;
539                                         if (!check_arguments (types, args, allowByRefMatch))
540                                                 continue;
541
542                                         if (result != null)
543                                                 result = GetBetterMethod (result, m, types);
544                                         else
545                                                 result = m;
546                                 }
547
548                                 if (result != null || arguments == null || types.Length != arguments.Length)
549                                         return result;
550
551                                 // Xamarin-5278: try with parameters that are COM objects
552                                 // REVIEW: do we also need to implement best method match?
553                                 for (i = 0; i < match.Length; ++i) {
554                                         m = match [i];
555                                         ParameterInfo[] methodArgs = m.GetParametersInternal ();
556                                         if (methodArgs.Length != types.Length)
557                                                 continue;
558                                         for (j = 0; j < types.Length; ++j) {
559                                                 var requiredType = methodArgs [j].ParameterType;
560                                                 if (types [j] == requiredType)
561                                                         continue;
562 #if !MOBILE
563                                                 if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
564                                                         var iface = Marshal.GetComInterfaceForObject (arguments [j], requiredType);
565                                                         if (iface != IntPtr.Zero) {
566                                                                 // the COM object implements the desired interface
567                                                                 Marshal.Release (iface);
568                                                                 continue;
569                                                         }
570                                                 }
571 #endif
572                                                 break;
573                                         }
574
575                                         if (j == types.Length)
576                                                 return m;
577                                 }
578                                 return null;
579                         }
580
581                         MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
582                         {
583                                 ParameterInfo [] pl1 = m1.GetParametersInternal ();
584                                 ParameterInfo [] pl2 = m2.GetParametersInternal ();
585                                 int prev = 0;
586                                 for (int i = 0; i < pl1.Length; i++) {
587                                         int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
588                                         if (cmp != 0 && prev != 0 && prev != cmp)
589                                                 throw new AmbiguousMatchException ();
590                                         if (cmp != 0)
591                                                 prev = cmp;
592                                 }
593                                 if (prev != 0)
594                                         return prev > 0 ? m2 : m1;
595
596                                 Type dt1 = m1.DeclaringType;
597                                 Type dt2 = m2.DeclaringType;
598                                 if (dt1 != dt2) {
599                                         if (dt1.IsSubclassOf(dt2))
600                                                 return m1;
601                                         if (dt2.IsSubclassOf(dt1))
602                                                 return m2;
603                                 }
604
605                                 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
606                                 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
607                                 if (va1 && !va2)
608                                         return m2;
609                                 if (va2 && !va1)
610                                         return m1;
611
612                                 throw new AmbiguousMatchException ();
613                         }
614
615                         int CompareCloserType (Type t1, Type t2)
616                         {
617                                 if (t1 == t2)
618                                         return 0;
619                                 if (t1.IsGenericParameter && !t2.IsGenericParameter)
620                                         return 1; // t2
621                                 if (!t1.IsGenericParameter && t2.IsGenericParameter)
622                                         return -1; // t1
623                                 if (t1.HasElementType && t2.HasElementType)
624                                         return CompareCloserType (
625                                                 t1.GetElementType (),
626                                                 t2.GetElementType ());
627
628                                 if (t1.IsSubclassOf (t2))
629                                         return -1; // t1
630                                 if (t2.IsSubclassOf (t1))
631                                         return 1; // t2
632
633                                 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
634                                         return 1; // t2
635                                 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
636                                         return -1; // t1
637
638                                 // What kind of cases could reach here?
639                                 return 0;
640                         }
641
642                         public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
643                         {
644                                 if (match == null || match.Length == 0)
645                                         throw new ArgumentException ("No properties provided", "match");
646
647                                 bool haveRet = (returnType != null);
648                                 int idxlen = (indexes != null) ? indexes.Length : -1;
649                                 PropertyInfo result = null;
650                                 int i;
651                                 int best_score = Int32.MaxValue - 1;
652                                 int fail_score = Int32.MaxValue;
653                                 int level = 0;
654                                 
655                                 for (i = match.Length - 1; i >= 0; i--) {
656                                         PropertyInfo p = match [i];
657                                         ParameterInfo[] args = p.GetIndexParameters ();
658                                         if (idxlen >= 0 && idxlen != args.Length)
659                                                 continue;
660
661                                         if (haveRet && p.PropertyType != returnType)
662                                                 continue;
663
664                                         int score = Int32.MaxValue - 1;
665                                         if (idxlen > 0) {
666                                                 score = check_arguments_with_score (indexes, args);
667                                                 if (score == -1)
668                                                         continue;
669                                         }
670
671                                         int new_level = GetDerivedLevel (p.DeclaringType);
672                                         if (result != null) {
673                                                 if (best_score < score)
674                                                         continue;
675
676                                                 if (best_score == score) {
677                                                         if (level == new_level) {
678                                                                 // Keep searching. May be there's something
679                                                                 // better for us.
680                                                                 fail_score = score;
681                                                                 continue;
682                                                         }
683
684                                                         if (level > new_level)
685                                                                 continue;
686                                                 }
687                                         }
688
689                                         result = p;
690                                         best_score = score;
691                                         level = new_level;
692                                 }
693
694                                 if (fail_score <= best_score)
695                                         throw new AmbiguousMatchException ();
696
697                                 return result;
698                         }
699
700                         static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
701                         {
702                                 int worst = -1;
703
704                                 for (int i = 0; i < types.Length; ++i) {
705                                         int res = check_type_with_score (types [i], args [i].ParameterType);
706                                         if (res == -1)
707                                                 return -1;
708
709                                         if (worst < res)
710                                                 worst = res;
711                                 }
712
713                                 return worst;
714                         }
715
716                         // 0 -> same type or null and !valuetype
717                         // 1 -> to == Enum
718                         // 2 -> value type that don't lose data
719                         // 3 -> to == IsAssignableFrom
720                         // 4 -> to == object
721                         static int check_type_with_score (Type from, Type to)
722                         {
723                                 if (from == null)
724                                         return to.IsValueType ? -1 : 0;
725
726                                 if (from == to)
727                                         return 0;
728
729                                 if (to == typeof (object))
730                                         return 4;
731
732                                 TypeCode fromt = Type.GetTypeCode (from);
733                                 TypeCode tot = Type.GetTypeCode (to);
734
735                                 switch (fromt) {
736                                 case TypeCode.Char:
737                                         switch (tot) {
738                                         case TypeCode.UInt16:
739                                                 return 0;
740
741                                         case TypeCode.UInt32:
742                                         case TypeCode.Int32:
743                                         case TypeCode.UInt64:
744                                         case TypeCode.Int64:
745                                         case TypeCode.Single:
746                                         case TypeCode.Double:
747                                                 return 2;
748                                         }
749                                         return -1;
750                                 case TypeCode.Byte:
751                                         switch (tot) {
752                                         case TypeCode.Char:
753                                         case TypeCode.UInt16:
754                                         case TypeCode.Int16:
755                                         case TypeCode.UInt32:
756                                         case TypeCode.Int32:
757                                         case TypeCode.UInt64:
758                                         case TypeCode.Int64:
759                                         case TypeCode.Single:
760                                         case TypeCode.Double:
761                                                 return 2;
762                                         }
763                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
764                                 case TypeCode.SByte:
765                                         switch (tot) {
766                                         case TypeCode.Int16:
767                                         case TypeCode.Int32:
768                                         case TypeCode.Int64:
769                                         case TypeCode.Single:
770                                         case TypeCode.Double:
771                                                 return 2;
772                                         }
773                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
774                                 case TypeCode.UInt16:
775                                         switch (tot) {
776                                         case TypeCode.UInt32:
777                                         case TypeCode.Int32:
778                                         case TypeCode.UInt64:
779                                         case TypeCode.Int64:
780                                         case TypeCode.Single:
781                                         case TypeCode.Double:
782                                                 return 2;
783                                         }
784                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
785                                 case TypeCode.Int16:
786                                         switch (tot) {
787                                         case TypeCode.Int32:
788                                         case TypeCode.Int64:
789                                         case TypeCode.Single:
790                                         case TypeCode.Double:
791                                                 return 2;
792                                         }
793                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
794                                 case TypeCode.UInt32:
795                                         switch (tot) {
796                                         case TypeCode.UInt64:
797                                         case TypeCode.Int64:
798                                         case TypeCode.Single:
799                                         case TypeCode.Double:
800                                                 return 2;
801                                         }
802                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
803                                 case TypeCode.Int32:
804                                         switch (tot) {
805                                         case TypeCode.Int64:
806                                         case TypeCode.Single:
807                                         case TypeCode.Double:
808                                                 return 2;
809                                         }
810                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
811                                 case TypeCode.UInt64:
812                                 case TypeCode.Int64:
813                                         switch (tot) {
814                                         case TypeCode.Single:
815                                         case TypeCode.Double:
816                                                 return 2;
817                                         }
818                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
819                                 case TypeCode.Single:
820                                         return tot == TypeCode.Double ? 2 : -1;
821                                 default:
822                                         return (to.IsAssignableFrom (from)) ? 3 : -1;
823                                 }
824                         }
825                 }
826         }
827 }
828