Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Binder.cs « System.Reflection « corlib « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6d186c73eddc21f2895a4b86fdcc62c099a1616f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// System.Reflection.Binder
//
// Authors:
// 	Sean MacIsaac (macisaac@ximian.com)
// 	Paolo Molaro (lupus@ximian.com)
//	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//	Marek Safar (marek.safar@gmail.com)
//
// (C) Ximian, Inc. 2001 - 2003
// (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Globalization;
using System.Runtime.InteropServices;

namespace System.Reflection
{
	[ComVisible (true)]
	[Serializable]
	[ClassInterface(ClassInterfaceType.AutoDual)]
	public abstract class Binder
	{
		protected Binder () {}

		public abstract FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture);
		public abstract MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state);
		public abstract object ChangeType (object value, Type type, CultureInfo culture);
		public abstract void ReorderArgumentArray( ref object[] args, object state);
		public abstract MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers);
		public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers);

		static readonly Binder default_binder = new Default ();

		internal static Binder DefaultBinder {
			get {
				return default_binder;
			}
		}
		
		internal bool ConvertArgs (object[] args, ParameterInfo[] pinfo, CultureInfo culture, bool exactMatch)
		{
			if (args == null) {
				if (pinfo.Length == 0)
					return true;
				
				throw new TargetParameterCountException ();
			}

			if (pinfo.Length != args.Length)
				throw new TargetParameterCountException ();
			
			for (int i = 0; i < args.Length; ++i) {
				var arg = args [i];
				var pi = pinfo [i];
				if (arg == Type.Missing) {
					args [i] = pi.DefaultValue;
					continue;
				}

				if (arg != null && arg.GetType () == pi.ParameterType)
					continue;

				if (exactMatch)
					return false;

				object v = ChangeType (arg, pi.ParameterType, culture);
				if (v == null && args [i] != null)
					return false;
	
				args [i] = v;
			}

			return true;
		}

		internal static int GetDerivedLevel (Type type) 
		{
			Type searchType = type;
			int level = 1;

			while (searchType.BaseType != null) 
			{
				level++;
				searchType = searchType.BaseType;
			}

			return level;
		}

		internal static MethodBase FindMostDerivedMatch (MethodBase [] match) 
		{
			int highLevel = 0;
			int matchId = -1;
			int count = match.Length;

			for (int current = 0; current < count; current++) 
			{
				MethodBase m = match [current];
				int level = GetDerivedLevel (m.DeclaringType);
				if (level == highLevel)
					throw new AmbiguousMatchException ();
				// If the argument types differ we
				// have an ambigous match, as well
				if (matchId >= 0) {
					ParameterInfo[] p1 = m.GetParameters ();
					ParameterInfo[] p2 = match [matchId].GetParameters ();
					bool equal = true;

					if (p1.Length != p2.Length)
						equal = false;
					else {
						int i;

						for (i = 0; i < p1.Length; ++i) {
							if (p1 [i].ParameterType != p2 [i].ParameterType) {
								equal = false;
								break;
							}
						}
					}

					if (!equal)
						throw new AmbiguousMatchException ();
				}

				if (level > highLevel) 
				{
					highLevel = level;
					matchId = current;
				}
			}

			return match[matchId];
		}

		internal sealed class Default : Binder {
			public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) 
			{
				if (match == null)
					throw new ArgumentNullException ("match");
				foreach (FieldInfo f in match) {
					if (check_type (value.GetType (), f.FieldType))
						return f;
				}
				return null;
			}

			public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
			{
				Type[] types;
				if (args == null)
					types = Type.EmptyTypes;
				else {
					types = new Type [args.Length];
					for (int i = 0; i < args.Length; ++i) {
						if (args [i] != null)
							types [i] = args [i].GetType ();
					}
				}

				MethodBase selected = null;
				if (names != null) {
					foreach (var m in match) {
						var parameters = m.GetParameters ();
						int i;

						/*
						 * Find the corresponding parameter for each parameter name,
						 * reorder types/modifiers array during the search.
						 */
						Type[] newTypes = (Type[])types.Clone ();
						ParameterModifier[] newModifiers = modifiers != null ? (ParameterModifier[])modifiers.Clone () : null;
						for (i = 0; i < names.Length; ++i) {
							/* Find the corresponding parameter */
							int nindex = -1;
							for (int j = 0; j < parameters.Length; ++j) {
								if (parameters [j].Name == names [i]) {
									nindex = j;
									break;
								}
							}
							if (nindex == -1)
								break;
							if (i < newTypes.Length && nindex < types.Length)
								newTypes [i] = types [nindex];
							if (modifiers != null && i < newModifiers.Length && nindex < modifiers.Length)
								newModifiers [i] = modifiers [nindex];
						}
						if (i < names.Length)
							continue;

						selected = SelectMethod (bindingAttr, new MethodBase [] { m }, newTypes, newModifiers, true, args);
						if (selected != null)
							break;
					}
				} else {
					selected = SelectMethod (bindingAttr, match, types, modifiers, true, args);
				}

				state = null;
				if (selected != null && names != null)
					ReorderParameters (names, ref args, selected);

				if (selected != null) {
					if (args == null)
						args = EmptyArray<object>.Value;
	
					AdjustArguments (selected, ref args);
				}

				return selected;
			}

			// probably belongs in ReorderArgumentArray
			static void AdjustArguments (MethodBase selected, ref object [] args)
			{
				var parameters = selected.GetParameters ();
				var parameters_length = parameters.Length;
				if (parameters_length == 0)
					return;

				var last_parameter = parameters [parameters.Length - 1];
				Type last_parameter_type = last_parameter.ParameterType;
				if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
					return;

				var args_length = args.Length;
				var param_args_count = args_length + 1 - parameters_length;
				var first_vararg_index = args_length - param_args_count;
				if (first_vararg_index < args_length) {
					var first_vararg = args [first_vararg_index];
					if (first_vararg != null && first_vararg.GetType () == last_parameter_type)
						return;
				}
				
				var params_args = Array.CreateInstance (last_parameter_type.GetElementType (), param_args_count);
				for (int i = 0; i < param_args_count; i++)
					params_args.SetValue (args [first_vararg_index + i], i);

				var adjusted = new object [parameters_length];
				Array.Copy (args, adjusted, parameters_length - 1);
				
				adjusted [adjusted.Length - 1] = params_args;
				args = adjusted;
			}

			void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
			{
				object [] newArgs = new object [args.Length];
				Array.Copy (args, newArgs, args.Length);
				ParameterInfo [] plist = selected.GetParameters ();
				for (int n = 0; n < names.Length; n++)
					for (int p = 0; p < plist.Length; p++) {
						if (names [n] == plist [p].Name) {
							newArgs [p] = args [n];
							break;
						}
					}
				Array.Copy (newArgs, args, args.Length);
			}

			static bool IsArrayAssignable (Type object_type, Type target_type)
			{
				if (object_type.IsArray && target_type.IsArray)
					return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
						
				if (target_type.IsAssignableFrom (object_type))
					return true;

				return false;
			}
			
			public override object ChangeType (object value, Type type, CultureInfo culture)
			{
				if (value == null)
					return null;
				Type vtype = value.GetType ();
				if (type.IsByRef)
					type = type.GetElementType ();
				if (vtype == type || type.IsInstanceOfType (value))
					return value;
				if (vtype.IsArray && type.IsArray){
					if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
						return value;
				}

				if (check_type (vtype, type)) {
					// These are not supported by Convert
					if (type.IsEnum)
						return Enum.ToObject (type, value);
					if (vtype == typeof (Char)) {
						if (type == typeof (double))
							return (double)(char)value;
						if (type == typeof (float))
							return (float)(char)value;
					}
					if (vtype == typeof (IntPtr) && type.IsPointer)
						return value;
					return Convert.ChangeType (value, type);
				}
				return null;
			}

			[MonoTODO ("This method does not do anything in Mono")]
			public override void ReorderArgumentArray (ref object[] args, object state)
			{
				//do nothing until we support named arguments
				//throw new NotImplementedException ();
			}

			private static bool check_type (Type from, Type to) {
				if (from == to)
					return true;

				if (from == null)
					return true;

				if (to.IsByRef != from.IsByRef)
					return false;

				if (to.IsInterface)
					return to.IsAssignableFrom (from);

				if (to.IsEnum) {
					to = Enum.GetUnderlyingType (to);
					if (from == to)
						return true;
				}

				if (to.IsGenericType && to.GetGenericTypeDefinition () == typeof (Nullable<>) && to.GetGenericArguments ()[0] == from)
					return true;

				TypeCode fromt = Type.GetTypeCode (from);
				TypeCode tot = Type.GetTypeCode (to);

				switch (fromt) {
				case TypeCode.Char:
					switch (tot) {
					case TypeCode.UInt16:
					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object);
				case TypeCode.Byte:
					switch (tot) {
					case TypeCode.Char:
					case TypeCode.UInt16:
					case TypeCode.Int16:
					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.SByte:
					switch (tot) {
					case TypeCode.Int16:
					case TypeCode.Int32:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.UInt16:
					switch (tot) {
					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.Int16:
					switch (tot) {
					case TypeCode.Int32:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.UInt32:
					switch (tot) {
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.Int32:
					switch (tot) {
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.UInt64:
				case TypeCode.Int64:
					switch (tot) {
					case TypeCode.Single:
					case TypeCode.Double:
						return true;
					}
					return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
				case TypeCode.Single:
					return tot == TypeCode.Double || to == typeof (object);
				default:
					/* TODO: handle valuetype -> byref */
					if (to == typeof (object) && from.IsValueType)
						return true;
					if (to.IsPointer && from == typeof (IntPtr))
						return true;

					return to.IsAssignableFrom (from);
				}
			}

			private static bool check_arguments (Type[] types, ParameterInfo[] args, bool allowByRefMatch) {
				for (int i = 0; i < types.Length; ++i) {
					bool match = check_type (types [i], args [i].ParameterType);
					if (!match && allowByRefMatch) {
						Type param_type = args [i].ParameterType;
						if (param_type.IsByRef)
							match = check_type (types [i], param_type.GetElementType ());
					}
					if (!match)
						return false;
				}
				return true;
			}

			public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase [] match, Type [] types, ParameterModifier [] modifiers)
			{
				return SelectMethod (bindingAttr, match, types, modifiers,
					false, null);
			}

			MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers, bool allowByRefMatch, object[] arguments)
			{
				MethodBase m;
				int i, j;

				if (match == null)
					throw new ArgumentNullException ("match");

				/* first look for an exact match... */
				MethodBase exact_match = null;
				for (i = 0; i < match.Length; ++i) {
					m = match [i];
					ParameterInfo[] args = m.GetParameters ();
					if (args.Length != types.Length)
						continue;
					for (j = 0; j < types.Length; ++j) {
						if (types [j] != args [j].ParameterType)
							break;
					}
					if (j == types.Length) {
						if (exact_match != null) {
							exact_match = null;
							break;
						} else {
							exact_match = m;
						}
					}
				}
				if (exact_match != null)
					return exact_match;

				/* Try methods with ParamArray attribute */
				if (arguments != null) {
					for (i = 0; i < match.Length; ++i) {
						m = match [i];

						var pi = m.GetParameters ();
						if (pi.Length == 0 || pi.Length > types.Length + 1)
							continue;

						if (!Attribute.IsDefined (pi [pi.Length - 1], typeof (ParamArrayAttribute)))
							continue;

						var elementType = pi [pi.Length - 1].ParameterType.GetElementType ();
						for (j = 0; j < types.Length; ++j) {
							if (j < (pi.Length - 1) && types [j] != pi [j].ParameterType)
								break;
							
							if (j >= (pi.Length - 1) && types [j] != elementType) 
								break;
						}

						if (j == types.Length)
							return m;
					}
				}

				if ((bindingAttr & BindingFlags.ExactBinding) != 0)
					return null;

				MethodBase result = null;
				for (i = 0; i < match.Length; ++i) {
					m = match [i];
					ParameterInfo[] args = m.GetParameters ();
					if (args.Length != types.Length)
						continue;
					if (!check_arguments (types, args, allowByRefMatch))
						continue;

					if (result != null)
						result = GetBetterMethod (result, m, types);
					else
						result = m;
				}

				if (result != null || arguments == null || types.Length != arguments.Length)
					return result;

				// Xamarin-5278: try with parameters that are COM objects
				// REVIEW: do we also need to implement best method match?
				for (i = 0; i < match.Length; ++i) {
					m = match [i];
					ParameterInfo[] methodArgs = m.GetParameters ();
					if (methodArgs.Length != types.Length)
						continue;
					for (j = 0; j < types.Length; ++j) {
						var requiredType = methodArgs [j].ParameterType;
						if (types [j] == requiredType)
							continue;
#if !MOBILE
						if (types [j] == typeof (__ComObject) && requiredType.IsInterface) {
							var iface = Marshal.GetComInterfaceForObject (arguments [j], requiredType);
							if (iface != IntPtr.Zero) {
								// the COM object implements the desired interface
								Marshal.Release (iface);
								continue;
							}
						}
#endif
						break;
					}

					if (j == types.Length)
						return m;
				}
				return null;
			}

			MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
			{
				ParameterInfo [] pl1 = m1.GetParameters ();
				ParameterInfo [] pl2 = m2.GetParameters ();
				int prev = 0;
				for (int i = 0; i < pl1.Length; i++) {
					int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
					if (cmp != 0 && prev != 0 && prev != cmp)
						throw new AmbiguousMatchException ();
					if (cmp != 0)
						prev = cmp;
				}
				if (prev != 0)
					return prev > 0 ? m2 : m1;

				Type dt1 = m1.DeclaringType;
				Type dt2 = m2.DeclaringType;
				if (dt1 != dt2) {
					if (dt1.IsSubclassOf(dt2))
						return m1;
					if (dt2.IsSubclassOf(dt1))
						return m2;
				}

				bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
				bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
				if (va1 && !va2)
					return m2;
				if (va2 && !va1)
					return m1;

				throw new AmbiguousMatchException ();
			}

			int CompareCloserType (Type t1, Type t2)
			{
				if (t1 == t2)
					return 0;
				if (t1.IsGenericParameter && !t2.IsGenericParameter)
					return 1; // t2
				if (!t1.IsGenericParameter && t2.IsGenericParameter)
					return -1; // t1
				if (t1.HasElementType && t2.HasElementType)
					return CompareCloserType (
						t1.GetElementType (),
						t2.GetElementType ());

				if (t1.IsSubclassOf (t2))
					return -1; // t1
				if (t2.IsSubclassOf (t1))
					return 1; // t2

				if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
					return 1; // t2
				if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
					return -1; // t1

				// What kind of cases could reach here?
				return 0;
			}

			public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
			{
				if (match == null || match.Length == 0)
					throw new ArgumentException ("No properties provided", "match");

				bool haveRet = (returnType != null);
				int idxlen = (indexes != null) ? indexes.Length : -1;
				PropertyInfo result = null;
				int i;
				int best_score = Int32.MaxValue - 1;
				int fail_score = Int32.MaxValue;
				int level = 0;
				
				for (i = match.Length - 1; i >= 0; i--) {
					PropertyInfo p = match [i];
					ParameterInfo[] args = p.GetIndexParameters ();
					if (idxlen >= 0 && idxlen != args.Length)
						continue;

					if (haveRet && p.PropertyType != returnType)
						continue;

					int score = Int32.MaxValue - 1;
					if (idxlen > 0) {
						score = check_arguments_with_score (indexes, args);
						if (score == -1)
							continue;
					}

					int new_level = GetDerivedLevel (p.DeclaringType);
					if (result != null) {
						if (best_score < score)
							continue;

						if (best_score == score) {
							if (level == new_level) {
								// Keep searching. May be there's something
								// better for us.
								fail_score = score;
								continue;
							}

							if (level > new_level)
								continue;
						}
					}

					result = p;
					best_score = score;
					level = new_level;
				}

				if (fail_score <= best_score)
					throw new AmbiguousMatchException ();

				return result;
			}

			static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
			{
				int worst = -1;

				for (int i = 0; i < types.Length; ++i) {
					int res = check_type_with_score (types [i], args [i].ParameterType);
					if (res == -1)
						return -1;

					if (worst < res)
						worst = res;
				}

				return worst;
			}

			// 0 -> same type or null and !valuetype
			// 1 -> to == Enum
			// 2 -> value type that don't lose data
			// 3 -> to == IsAssignableFrom
			// 4 -> to == object
			static int check_type_with_score (Type from, Type to)
			{
				if (from == null)
					return to.IsValueType ? -1 : 0;

				if (from == to)
					return 0;

				if (to == typeof (object))
					return 4;

				TypeCode fromt = Type.GetTypeCode (from);
				TypeCode tot = Type.GetTypeCode (to);

				switch (fromt) {
				case TypeCode.Char:
					switch (tot) {
					case TypeCode.UInt16:
						return 0;

					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return -1;
				case TypeCode.Byte:
					switch (tot) {
					case TypeCode.Char:
					case TypeCode.UInt16:
					case TypeCode.Int16:
					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.SByte:
					switch (tot) {
					case TypeCode.Int16:
					case TypeCode.Int32:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.UInt16:
					switch (tot) {
					case TypeCode.UInt32:
					case TypeCode.Int32:
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.Int16:
					switch (tot) {
					case TypeCode.Int32:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.UInt32:
					switch (tot) {
					case TypeCode.UInt64:
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.Int32:
					switch (tot) {
					case TypeCode.Int64:
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.UInt64:
				case TypeCode.Int64:
					switch (tot) {
					case TypeCode.Single:
					case TypeCode.Double:
						return 2;
					}
					return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
				case TypeCode.Single:
					return tot == TypeCode.Double ? 2 : -1;
				default:
					return (to.IsAssignableFrom (from)) ? 3 : -1;
				}
			}
		}
	}
}