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