New test.
[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 #if NET_2_0
40         [ComVisible (true)]
41 #endif
42         [Serializable]
43         [ClassInterface(ClassInterfaceType.AutoDual)]
44         public abstract class Binder
45         {
46                 protected Binder () {}
47
48                 public abstract FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture);
49                 public abstract MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state);
50                 public abstract object ChangeType (object value, Type type, CultureInfo culture);
51                 public abstract void ReorderArgumentArray( ref object[] args, object state);
52                 public abstract MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers);
53                 public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers);
54
55                 static Binder default_binder = new Default ();
56
57                 internal static Binder DefaultBinder {
58                         get {
59                                 return default_binder;
60                         }
61                 }
62                 
63                 internal static bool ConvertArgs (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture) {
64                         if (args == null) {
65                                 if ( pinfo.Length == 0)
66                                         return true;
67                                 else
68                                         throw new TargetParameterCountException ();
69                         }
70                         if (pinfo.Length != args.Length)
71                                 throw new TargetParameterCountException ();
72                         for (int i = 0; i < args.Length; ++i) {
73                                 object v = binder.ChangeType (args [i], pinfo[i].ParameterType, culture);
74                                 if ((v == null) && (args [i] != null))
75                                         return false;
76                                 args [i] = v;
77                         }
78                         return true;
79                 }
80
81                 internal static int GetDerivedLevel (Type type) 
82                 {
83                         Type searchType = type;
84                         int level = 1;
85
86                         while (searchType.BaseType != null) 
87                         {
88                                 level++;
89                                 searchType = searchType.BaseType;
90                         }
91
92                         return level;
93                 }
94
95                 internal static MethodBase FindMostDerivedMatch (MethodBase [] match) 
96                 {
97                         int highLevel = 0;
98                         int matchId = -1;
99                         int count = match.Length;
100
101                         for (int current = 0; current < count; current++) 
102                         {
103                                 int level = GetDerivedLevel (match[current].DeclaringType);
104                                 if (level == highLevel)
105                                         throw new AmbiguousMatchException ();
106
107                                 if (level > highLevel) 
108                                 {
109                                         highLevel = level;
110                                         matchId = current;
111                                 }
112                         }
113
114                         return match[matchId];
115                 }
116
117                 internal sealed class Default : Binder {
118                         public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) 
119                         {
120                                 if (match == null)
121                                         throw new ArgumentNullException ("match");
122                                 foreach (FieldInfo f in match) {
123                                         if (check_type (value.GetType (), f.FieldType))
124                                                 return f;
125                                 }
126                                 return null;
127                         }
128
129                         [MonoTODO]
130                         public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
131                         {
132                                 Type[] types;
133                                 if (args == null)
134                                         types = Type.EmptyTypes;
135                                 else {
136                                         types = new Type [args.Length];
137                                         for (int i = 0; i < args.Length; ++i) {
138                                                 if (args [i] != null)
139                                                         types [i] = args [i].GetType ();
140                                         }
141                                 }
142                                 MethodBase selected = SelectMethod (bindingAttr, match, types, modifiers);
143                                 state = null;
144                                 if (names != null)
145                                         ReorderParameters (names, ref args, selected);
146                                 return selected;
147                         }
148
149                         void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
150                         {
151                                 object [] newArgs = new object [args.Length];
152                                 Array.Copy (args, newArgs, args.Length);
153                                 ParameterInfo [] plist = selected.GetParameters ();
154                                 for (int n = 0; n < names.Length; n++)
155                                         for (int p = 0; p < plist.Length; p++) {
156                                                 if (names [n] == plist [p].Name) {
157                                                         newArgs [p] = args [n];
158                                                         break;
159                                                 }
160                                         }
161                                 Array.Copy (newArgs, args, args.Length);
162                         }
163
164                         static bool IsArrayAssignable (Type object_type, Type target_type)
165                         {
166                                 if (object_type.IsArray && target_type.IsArray)
167                                         return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
168                                                 
169                                 if (target_type.IsAssignableFrom (object_type))
170                                         return true;
171
172                                 return false;
173                         }
174                         
175                         public override object ChangeType (object value, Type type, CultureInfo culture)
176                         {
177                                 if (value == null)
178                                         return null;
179                                 Type vtype = value.GetType ();
180                                 if (type.IsByRef)
181                                         type = type.GetElementType ();
182                                 if (vtype == type || type.IsInstanceOfType (value))
183                                         return value;
184                                 if (vtype.IsArray && type.IsArray){
185                                         if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
186                                                 return value;
187                                 }
188
189                                 if (check_type (vtype, type))
190                                         return Convert.ChangeType (value, type);
191                                 return null;
192                         }
193
194                         [MonoTODO]
195                         public override void ReorderArgumentArray (ref object[] args, object state)
196                         {
197                                 //do nothing until we support named arguments
198                                 //throw new NotImplementedException ();
199                         }
200
201                         private static bool check_type (Type from, Type to) {
202                                 if (from == to)
203                                         return true;
204
205                                 if (from == null)
206                                         return true;
207
208                                 TypeCode fromt = Type.GetTypeCode (from);
209                                 TypeCode tot = Type.GetTypeCode (to);
210
211                                 if (to.IsByRef != from.IsByRef)
212                                         return false;
213
214                                 if (to.IsInterface)
215                                         return to.IsAssignableFrom (from);
216
217                                 switch (fromt) {
218                                 case TypeCode.Char:
219                                         switch (tot) {
220                                         case TypeCode.UInt16:
221                                         case TypeCode.UInt32:
222                                         case TypeCode.Int32:
223                                         case TypeCode.UInt64:
224                                         case TypeCode.Int64:
225                                         case TypeCode.Single:
226                                         case TypeCode.Double:
227                                                 return true;
228                                         }
229                                         return to == typeof (object);
230                                 case TypeCode.Byte:
231                                         switch (tot) {
232                                         case TypeCode.Char:
233                                         case TypeCode.UInt16:
234                                         case TypeCode.Int16:
235                                         case TypeCode.UInt32:
236                                         case TypeCode.Int32:
237                                         case TypeCode.UInt64:
238                                         case TypeCode.Int64:
239                                         case TypeCode.Single:
240                                         case TypeCode.Double:
241                                                 return true;
242                                         }
243                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
244                                 case TypeCode.SByte:
245                                         switch (tot) {
246                                         case TypeCode.Int16:
247                                         case TypeCode.Int32:
248                                         case TypeCode.Int64:
249                                         case TypeCode.Single:
250                                         case TypeCode.Double:
251                                                 return true;
252                                         }
253                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
254                                 case TypeCode.UInt16:
255                                         switch (tot) {
256                                         case TypeCode.UInt32:
257                                         case TypeCode.Int32:
258                                         case TypeCode.UInt64:
259                                         case TypeCode.Int64:
260                                         case TypeCode.Single:
261                                         case TypeCode.Double:
262                                                 return true;
263                                         }
264                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
265                                 case TypeCode.Int16:
266                                         switch (tot) {
267                                         case TypeCode.Int32:
268                                         case TypeCode.Int64:
269                                         case TypeCode.Single:
270                                         case TypeCode.Double:
271                                                 return true;
272                                         }
273                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
274                                 case TypeCode.UInt32:
275                                         switch (tot) {
276                                         case TypeCode.UInt64:
277                                         case TypeCode.Int64:
278                                         case TypeCode.Single:
279                                         case TypeCode.Double:
280                                                 return true;
281                                         }
282                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
283                                 case TypeCode.Int32:
284                                         switch (tot) {
285                                         case TypeCode.Int64:
286                                         case TypeCode.Single:
287                                         case TypeCode.Double:
288                                                 return true;
289                                         }
290                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
291                                 case TypeCode.UInt64:
292                                 case TypeCode.Int64:
293                                         switch (tot) {
294                                         case TypeCode.Single:
295                                         case TypeCode.Double:
296                                                 return true;
297                                         }
298                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
299                                 case TypeCode.Single:
300                                         return tot == TypeCode.Double || to == typeof (object);
301                                 default:
302                                         /* TODO: handle valuetype -> byref */
303                                         if (to == typeof (object) && from.IsValueType)
304                                                 return true;
305
306                                         return to.IsAssignableFrom (from);
307                                 }
308                         }
309
310                         private static bool check_arguments (Type[] types, ParameterInfo[] args) {
311                                 for (int i = 0; i < types.Length; ++i) {
312                                         if (!check_type (types [i], args [i].ParameterType))
313                                                 return false;
314                                 }
315                                 return true;
316                         }
317
318                         public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
319                         {
320                                 MethodBase m;
321                                 int i, j;
322
323                                 if (match == null)
324                                         throw new ArgumentNullException ("match");
325
326                                 /* first look for an exact match... */
327                                 for (i = 0; i < match.Length; ++i) {
328                                         m = match [i];
329                                         ParameterInfo[] args = m.GetParameters ();
330                                         if (args.Length != types.Length)
331                                                 continue;
332                                         for (j = 0; j < types.Length; ++j) {
333                                                 if (types [j] != args [j].ParameterType)
334                                                         break;
335                                         }
336                                         if (j == types.Length)
337                                                 return m;
338                                 }
339
340                                 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
341                                         return null;
342
343                                 MethodBase result = null;
344                                 for (i = 0; i < match.Length; ++i) {
345                                         m = match [i];
346                                         ParameterInfo[] args = m.GetParameters ();
347                                         if (args.Length != types.Length)
348                                                 continue;
349                                         if (!check_arguments (types, args))
350                                                 continue;
351
352                                         if (result != null)
353                                                 result = GetBetterMethod (result, m, types);
354                                         else
355                                                 result = m;
356                                 }
357
358                                 return result;
359                         }
360
361                         MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
362                         {
363 #if NET_2_0
364                                 if (m1.IsGenericMethodDefinition && 
365                                     !m2.IsGenericMethodDefinition)
366                                         return m2;
367                                 if (m2.IsGenericMethodDefinition && 
368                                     !m1.IsGenericMethodDefinition)
369                                         return m1;
370 #endif
371
372                                 ParameterInfo [] pl1 = m1.GetParameters ();
373                                 ParameterInfo [] pl2 = m2.GetParameters ();
374                                 int prev = 0;
375                                 for (int i = 0; i < pl1.Length; i++) {
376                                         int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
377                                         if (cmp != 0 && prev != 0 && prev != cmp)
378                                                 throw new AmbiguousMatchException ();
379                                         if (cmp != 0)
380                                                 prev = cmp;
381                                 }
382                                 if (prev != 0)
383                                         return prev > 0 ? m2 : m1;
384
385                                 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
386                                 bool va2 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
387                                 if (va1 && !va2)
388                                         return m2;
389                                 if (va2 && !va1)
390                                         return m1;
391
392                                 throw new AmbiguousMatchException ();
393                         }
394
395                         int CompareCloserType (Type t1, Type t2)
396                         {
397                                 if (t1 == t2)
398                                         return 0;
399 #if NET_2_0
400                                 if (t1.IsGenericParameter && !t2.IsGenericParameter)
401                                         return 1; // t2
402                                 if (!t1.IsGenericParameter && t2.IsGenericParameter)
403                                         return -1; // t1
404 #endif
405                                 if (t1.HasElementType && t2.HasElementType)
406                                         return CompareCloserType (
407                                                 t1.GetElementType (),
408                                                 t2.GetElementType ());
409
410                                 if (t1.IsSubclassOf (t2))
411                                         return -1; // t1
412                                 if (t2.IsSubclassOf (t1))
413                                         return 1; // t2
414
415                                 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
416                                         return 1; // t2
417                                 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
418                                         return -1; // t1
419
420                                 // What kind of cases could reach here?
421                                 return 0;
422                         }
423
424                         public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
425                         {
426                                 if (match == null || match.Length == 0)
427                                         throw new ArgumentException ("No properties provided", "match");
428
429                                 bool haveRet = (returnType != null);
430                                 int idxlen = (indexes != null) ? indexes.Length : -1;
431                                 PropertyInfo result = null;
432                                 int i;
433                                 int best_score = Int32.MaxValue - 1;
434                                 int fail_score = Int32.MaxValue;
435                                 int level = 0;
436                                 
437                                 for (i = match.Length - 1; i >= 0; i--) {
438                                         PropertyInfo p = match [i];
439                                         ParameterInfo[] args = p.GetIndexParameters ();
440                                         if (idxlen >= 0 && idxlen != args.Length)
441                                                 continue;
442
443                                         if (haveRet && !check_type (p.PropertyType, returnType))
444                                                 continue;
445
446                                         int score = Int32.MaxValue - 1;
447                                         if (idxlen > 0) {
448                                                 score = check_arguments_with_score (indexes, args);
449                                                 if (score == -1)
450                                                         continue;
451                                         }
452
453                                         int new_level = GetDerivedLevel (p.DeclaringType);
454                                         if (result != null) {
455                                                 if (best_score < score)
456                                                         continue;
457
458                                                 if (best_score == score) {
459                                                         if (level == new_level) {
460                                                                 // Keep searching. May be there's something
461                                                                 // better for us.
462                                                                 fail_score = score;
463                                                                 continue;
464                                                         }
465
466                                                         if (level > new_level)
467                                                                 continue;
468                                                 }
469                                         }
470
471                                         result = p;
472                                         best_score = score;
473                                         level = new_level;
474                                 }
475
476                                 if (fail_score <= best_score)
477                                         throw new AmbiguousMatchException ();
478
479                                 return result;
480                         }
481
482                         static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
483                         {
484                                 int worst = -1;
485
486                                 for (int i = 0; i < types.Length; ++i) {
487                                         int res = check_type_with_score (types [i], args [i].ParameterType);
488                                         if (res == -1)
489                                                 return -1;
490
491                                         if (worst < res)
492                                                 worst = res;
493                                 }
494
495                                 return worst;
496                         }
497
498                         // 0 -> same type or null and !valuetype
499                         // 1 -> to == Enum
500                         // 2 -> value type that don't lose data
501                         // 3 -> to == IsAssignableFrom
502                         // 4 -> to == object
503                         static int check_type_with_score (Type from, Type to)
504                         {
505                                 if (from == null)
506                                         return to.IsValueType ? -1 : 0;
507
508                                 if (from == to)
509                                         return 0;
510
511                                 if (to == typeof (object))
512                                         return 4;
513
514                                 TypeCode fromt = Type.GetTypeCode (from);
515                                 TypeCode tot = Type.GetTypeCode (to);
516
517                                 switch (fromt) {
518                                 case TypeCode.Char:
519                                         switch (tot) {
520                                         case TypeCode.UInt16:
521                                                 return 0;
522
523                                         case TypeCode.UInt32:
524                                         case TypeCode.Int32:
525                                         case TypeCode.UInt64:
526                                         case TypeCode.Int64:
527                                         case TypeCode.Single:
528                                         case TypeCode.Double:
529                                                 return 2;
530                                         }
531                                         return -1;
532                                 case TypeCode.Byte:
533                                         switch (tot) {
534                                         case TypeCode.Char:
535                                         case TypeCode.UInt16:
536                                         case TypeCode.Int16:
537                                         case TypeCode.UInt32:
538                                         case TypeCode.Int32:
539                                         case TypeCode.UInt64:
540                                         case TypeCode.Int64:
541                                         case TypeCode.Single:
542                                         case TypeCode.Double:
543                                                 return 2;
544                                         }
545                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
546                                 case TypeCode.SByte:
547                                         switch (tot) {
548                                         case TypeCode.Int16:
549                                         case TypeCode.Int32:
550                                         case TypeCode.Int64:
551                                         case TypeCode.Single:
552                                         case TypeCode.Double:
553                                                 return 2;
554                                         }
555                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
556                                 case TypeCode.UInt16:
557                                         switch (tot) {
558                                         case TypeCode.UInt32:
559                                         case TypeCode.Int32:
560                                         case TypeCode.UInt64:
561                                         case TypeCode.Int64:
562                                         case TypeCode.Single:
563                                         case TypeCode.Double:
564                                                 return 2;
565                                         }
566                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
567                                 case TypeCode.Int16:
568                                         switch (tot) {
569                                         case TypeCode.Int32:
570                                         case TypeCode.Int64:
571                                         case TypeCode.Single:
572                                         case TypeCode.Double:
573                                                 return 2;
574                                         }
575                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
576                                 case TypeCode.UInt32:
577                                         switch (tot) {
578                                         case TypeCode.UInt64:
579                                         case TypeCode.Int64:
580                                         case TypeCode.Single:
581                                         case TypeCode.Double:
582                                                 return 2;
583                                         }
584                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
585                                 case TypeCode.Int32:
586                                         switch (tot) {
587                                         case TypeCode.Int64:
588                                         case TypeCode.Single:
589                                         case TypeCode.Double:
590                                                 return 2;
591                                         }
592                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
593                                 case TypeCode.UInt64:
594                                 case TypeCode.Int64:
595                                         switch (tot) {
596                                         case TypeCode.Single:
597                                         case TypeCode.Double:
598                                                 return 2;
599                                         }
600                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
601                                 case TypeCode.Single:
602                                         return tot == TypeCode.Double ? 2 : -1;
603                                 default:
604                                         return (to.IsAssignableFrom (from)) ? 3 : -1;
605                                 }
606                         }
607                 }
608         }
609 }
610