2008-03-14 Zoltan Varga <vargaz@gmail.com>
[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                                 MethodBase m = match [current];
104                                 int level = GetDerivedLevel (m.DeclaringType);
105                                 if (level == highLevel)
106                                         throw new AmbiguousMatchException ();
107                                 // If the argument types differ we
108                                 // have an ambigous match, as well
109                                 if (matchId >= 0) {
110                                         ParameterInfo[] p1 = m.GetParameters ();
111                                         ParameterInfo[] p2 = match [matchId].GetParameters ();
112                                         bool equal = true;
113
114                                         if (p1.Length != p2.Length)
115                                                 equal = false;
116                                         else {
117                                                 int i;
118
119                                                 for (i = 0; i < p1.Length; ++i) {
120                                                         if (p1 [i].ParameterType != p2 [i].ParameterType) {
121                                                                 equal = false;
122                                                                 break;
123                                                         }
124                                                 }
125                                         }
126
127                                         if (!equal)
128                                                 throw new AmbiguousMatchException ();
129                                 }
130
131                                 if (level > highLevel) 
132                                 {
133                                         highLevel = level;
134                                         matchId = current;
135                                 }
136                         }
137
138                         return match[matchId];
139                 }
140
141                 internal sealed class Default : Binder {
142                         public override FieldInfo BindToField (BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) 
143                         {
144                                 if (match == null)
145                                         throw new ArgumentNullException ("match");
146                                 foreach (FieldInfo f in match) {
147                                         if (check_type (value.GetType (), f.FieldType))
148                                                 return f;
149                                 }
150                                 return null;
151                         }
152
153                         //
154                         // FIXME: There was a MonoTODO, but it does not explain what the problem is
155                         // 
156                         public override MethodBase BindToMethod (BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
157                         {
158                                 Type[] types;
159                                 if (args == null)
160                                         types = Type.EmptyTypes;
161                                 else {
162                                         types = new Type [args.Length];
163                                         for (int i = 0; i < args.Length; ++i) {
164                                                 if (args [i] != null)
165                                                         types [i] = args [i].GetType ();
166                                         }
167                                 }
168                                 MethodBase selected = SelectMethod (bindingAttr, match, types, modifiers);
169                                 state = null;
170                                 if (names != null)
171                                         ReorderParameters (names, ref args, selected);
172                                 return selected;
173                         }
174
175                         void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
176                         {
177                                 object [] newArgs = new object [args.Length];
178                                 Array.Copy (args, newArgs, args.Length);
179                                 ParameterInfo [] plist = selected.GetParameters ();
180                                 for (int n = 0; n < names.Length; n++)
181                                         for (int p = 0; p < plist.Length; p++) {
182                                                 if (names [n] == plist [p].Name) {
183                                                         newArgs [p] = args [n];
184                                                         break;
185                                                 }
186                                         }
187                                 Array.Copy (newArgs, args, args.Length);
188                         }
189
190                         static bool IsArrayAssignable (Type object_type, Type target_type)
191                         {
192                                 if (object_type.IsArray && target_type.IsArray)
193                                         return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
194                                                 
195                                 if (target_type.IsAssignableFrom (object_type))
196                                         return true;
197
198                                 return false;
199                         }
200                         
201                         public override object ChangeType (object value, Type type, CultureInfo culture)
202                         {
203                                 if (value == null)
204                                         return null;
205                                 Type vtype = value.GetType ();
206                                 if (type.IsByRef)
207                                         type = type.GetElementType ();
208                                 if (vtype == type || type.IsInstanceOfType (value))
209                                         return value;
210                                 if (vtype.IsArray && type.IsArray){
211                                         if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
212                                                 return value;
213                                 }
214
215                                 if (check_type (vtype, type)) {
216                                         // These are not supported by Convert
217                                         if (vtype == typeof (Char)) {
218                                                 if (type == typeof (double))
219                                                         return (double)(char)value;
220                                                 if (type == typeof (float))
221                                                         return (float)(char)value;
222                                         }
223                                         return Convert.ChangeType (value, type);
224                                 }
225                                 return null;
226                         }
227
228                         [MonoTODO ("This method does not do anything in Mono")]
229                         public override void ReorderArgumentArray (ref object[] args, object state)
230                         {
231                                 //do nothing until we support named arguments
232                                 //throw new NotImplementedException ();
233                         }
234
235                         private static bool check_type (Type from, Type to) {
236                                 if (from == to)
237                                         return true;
238
239                                 if (from == null)
240                                         return true;
241
242                                 TypeCode fromt = Type.GetTypeCode (from);
243                                 TypeCode tot = Type.GetTypeCode (to);
244
245                                 if (to.IsByRef != from.IsByRef)
246                                         return false;
247
248                                 if (to.IsInterface)
249                                         return to.IsAssignableFrom (from);
250
251                                 switch (fromt) {
252                                 case TypeCode.Char:
253                                         switch (tot) {
254                                         case TypeCode.UInt16:
255                                         case TypeCode.UInt32:
256                                         case TypeCode.Int32:
257                                         case TypeCode.UInt64:
258                                         case TypeCode.Int64:
259                                         case TypeCode.Single:
260                                         case TypeCode.Double:
261                                                 return true;
262                                         }
263                                         return to == typeof (object);
264                                 case TypeCode.Byte:
265                                         switch (tot) {
266                                         case TypeCode.Char:
267                                         case TypeCode.UInt16:
268                                         case TypeCode.Int16:
269                                         case TypeCode.UInt32:
270                                         case TypeCode.Int32:
271                                         case TypeCode.UInt64:
272                                         case TypeCode.Int64:
273                                         case TypeCode.Single:
274                                         case TypeCode.Double:
275                                                 return true;
276                                         }
277                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
278                                 case TypeCode.SByte:
279                                         switch (tot) {
280                                         case TypeCode.Int16:
281                                         case TypeCode.Int32:
282                                         case TypeCode.Int64:
283                                         case TypeCode.Single:
284                                         case TypeCode.Double:
285                                                 return true;
286                                         }
287                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
288                                 case TypeCode.UInt16:
289                                         switch (tot) {
290                                         case TypeCode.UInt32:
291                                         case TypeCode.Int32:
292                                         case TypeCode.UInt64:
293                                         case TypeCode.Int64:
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.Int16:
300                                         switch (tot) {
301                                         case TypeCode.Int32:
302                                         case TypeCode.Int64:
303                                         case TypeCode.Single:
304                                         case TypeCode.Double:
305                                                 return true;
306                                         }
307                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
308                                 case TypeCode.UInt32:
309                                         switch (tot) {
310                                         case TypeCode.UInt64:
311                                         case TypeCode.Int64:
312                                         case TypeCode.Single:
313                                         case TypeCode.Double:
314                                                 return true;
315                                         }
316                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
317                                 case TypeCode.Int32:
318                                         switch (tot) {
319                                         case TypeCode.Int64:
320                                         case TypeCode.Single:
321                                         case TypeCode.Double:
322                                                 return true;
323                                         }
324                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
325                                 case TypeCode.UInt64:
326                                 case TypeCode.Int64:
327                                         switch (tot) {
328                                         case TypeCode.Single:
329                                         case TypeCode.Double:
330                                                 return true;
331                                         }
332                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
333                                 case TypeCode.Single:
334                                         return tot == TypeCode.Double || to == typeof (object);
335                                 default:
336                                         /* TODO: handle valuetype -> byref */
337                                         if (to == typeof (object) && from.IsValueType)
338                                                 return true;
339
340                                         return to.IsAssignableFrom (from);
341                                 }
342                         }
343
344                         private static bool check_arguments (Type[] types, ParameterInfo[] args) {
345                                 for (int i = 0; i < types.Length; ++i) {
346                                         if (!check_type (types [i], args [i].ParameterType))
347                                                 return false;
348                                 }
349                                 return true;
350                         }
351
352                         public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
353                         {
354                                 MethodBase m;
355                                 int i, j;
356
357                                 if (match == null)
358                                         throw new ArgumentNullException ("match");
359
360                                 /* first look for an exact match... */
361                                 for (i = 0; i < match.Length; ++i) {
362                                         m = match [i];
363                                         ParameterInfo[] args = m.GetParameters ();
364                                         if (args.Length != types.Length)
365                                                 continue;
366                                         for (j = 0; j < types.Length; ++j) {
367                                                 if (types [j] != args [j].ParameterType)
368                                                         break;
369                                         }
370                                         if (j == types.Length)
371                                                 return m;
372                                 }
373
374                                 /* Try methods with ParamArray attribute */
375                                 bool isdefParamArray = false;
376                                 Type elementType = null;
377                                 for (i = 0; i < match.Length; ++i) {
378                                         m = match [i];
379                                         ParameterInfo[] args = m.GetParameters ();
380                                         if (args.Length > types.Length)
381                                                 continue;
382                                         else if (args.Length == 0)
383                                                 continue;
384                                         isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
385                                         if (!isdefParamArray)
386                                                 continue;
387                                         elementType = args [args.Length - 1].ParameterType.GetElementType ();
388                                         for (j = 0; j < types.Length; ++j) {
389                                                 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
390                                                         break;
391                                                 else if (j >= (args.Length - 1) && types [j] != elementType) 
392                                                         break;
393                                         }
394                                         if (j == types.Length)
395                                                 return m;
396                                 }
397
398                                 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
399                                         return null;
400
401                                 MethodBase result = null;
402                                 for (i = 0; i < match.Length; ++i) {
403                                         m = match [i];
404                                         ParameterInfo[] args = m.GetParameters ();
405                                         if (args.Length != types.Length)
406                                                 continue;
407                                         if (!check_arguments (types, args))
408                                                 continue;
409
410                                         if (result != null)
411                                                 result = GetBetterMethod (result, m, types);
412                                         else
413                                                 result = m;
414                                 }
415
416                                 return result;
417                         }
418
419                         MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
420                         {
421 #if NET_2_0
422                                 if (m1.IsGenericMethodDefinition && 
423                                     !m2.IsGenericMethodDefinition)
424                                         return m2;
425                                 if (m2.IsGenericMethodDefinition && 
426                                     !m1.IsGenericMethodDefinition)
427                                         return m1;
428 #endif
429
430                                 ParameterInfo [] pl1 = m1.GetParameters ();
431                                 ParameterInfo [] pl2 = m2.GetParameters ();
432                                 int prev = 0;
433                                 for (int i = 0; i < pl1.Length; i++) {
434                                         int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
435                                         if (cmp != 0 && prev != 0 && prev != cmp)
436                                                 throw new AmbiguousMatchException ();
437                                         if (cmp != 0)
438                                                 prev = cmp;
439                                 }
440                                 if (prev != 0)
441                                         return prev > 0 ? m2 : m1;
442
443                                 Type dt1 = m1.DeclaringType;
444                                 Type dt2 = m2.DeclaringType;
445                                 if (dt1 != dt2) {
446                                         if (dt1.IsSubclassOf(dt2))
447                                                 return m1;
448                                         if (dt2.IsSubclassOf(dt1))
449                                                 return m2;
450                                 }
451
452                                 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
453                                 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
454                                 if (va1 && !va2)
455                                         return m2;
456                                 if (va2 && !va1)
457                                         return m1;
458
459                                 throw new AmbiguousMatchException ();
460                         }
461
462                         int CompareCloserType (Type t1, Type t2)
463                         {
464                                 if (t1 == t2)
465                                         return 0;
466 #if NET_2_0
467                                 if (t1.IsGenericParameter && !t2.IsGenericParameter)
468                                         return 1; // t2
469                                 if (!t1.IsGenericParameter && t2.IsGenericParameter)
470                                         return -1; // t1
471 #endif
472                                 if (t1.HasElementType && t2.HasElementType)
473                                         return CompareCloserType (
474                                                 t1.GetElementType (),
475                                                 t2.GetElementType ());
476
477                                 if (t1.IsSubclassOf (t2))
478                                         return -1; // t1
479                                 if (t2.IsSubclassOf (t1))
480                                         return 1; // t2
481
482                                 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
483                                         return 1; // t2
484                                 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
485                                         return -1; // t1
486
487                                 // What kind of cases could reach here?
488                                 return 0;
489                         }
490
491                         public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
492                         {
493                                 if (match == null || match.Length == 0)
494                                         throw new ArgumentException ("No properties provided", "match");
495
496                                 bool haveRet = (returnType != null);
497                                 int idxlen = (indexes != null) ? indexes.Length : -1;
498                                 PropertyInfo result = null;
499                                 int i;
500                                 int best_score = Int32.MaxValue - 1;
501                                 int fail_score = Int32.MaxValue;
502                                 int level = 0;
503                                 
504                                 for (i = match.Length - 1; i >= 0; i--) {
505                                         PropertyInfo p = match [i];
506                                         ParameterInfo[] args = p.GetIndexParameters ();
507                                         if (idxlen >= 0 && idxlen != args.Length)
508                                                 continue;
509
510                                         if (haveRet && !check_type (p.PropertyType, returnType))
511                                                 continue;
512
513                                         int score = Int32.MaxValue - 1;
514                                         if (idxlen > 0) {
515                                                 score = check_arguments_with_score (indexes, args);
516                                                 if (score == -1)
517                                                         continue;
518                                         }
519
520                                         int new_level = GetDerivedLevel (p.DeclaringType);
521                                         if (result != null) {
522                                                 if (best_score < score)
523                                                         continue;
524
525                                                 if (best_score == score) {
526                                                         if (level == new_level) {
527                                                                 // Keep searching. May be there's something
528                                                                 // better for us.
529                                                                 fail_score = score;
530                                                                 continue;
531                                                         }
532
533                                                         if (level > new_level)
534                                                                 continue;
535                                                 }
536                                         }
537
538                                         result = p;
539                                         best_score = score;
540                                         level = new_level;
541                                 }
542
543                                 if (fail_score <= best_score)
544                                         throw new AmbiguousMatchException ();
545
546                                 return result;
547                         }
548
549                         static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
550                         {
551                                 int worst = -1;
552
553                                 for (int i = 0; i < types.Length; ++i) {
554                                         int res = check_type_with_score (types [i], args [i].ParameterType);
555                                         if (res == -1)
556                                                 return -1;
557
558                                         if (worst < res)
559                                                 worst = res;
560                                 }
561
562                                 return worst;
563                         }
564
565                         // 0 -> same type or null and !valuetype
566                         // 1 -> to == Enum
567                         // 2 -> value type that don't lose data
568                         // 3 -> to == IsAssignableFrom
569                         // 4 -> to == object
570                         static int check_type_with_score (Type from, Type to)
571                         {
572                                 if (from == null)
573                                         return to.IsValueType ? -1 : 0;
574
575                                 if (from == to)
576                                         return 0;
577
578                                 if (to == typeof (object))
579                                         return 4;
580
581                                 TypeCode fromt = Type.GetTypeCode (from);
582                                 TypeCode tot = Type.GetTypeCode (to);
583
584                                 switch (fromt) {
585                                 case TypeCode.Char:
586                                         switch (tot) {
587                                         case TypeCode.UInt16:
588                                                 return 0;
589
590                                         case TypeCode.UInt32:
591                                         case TypeCode.Int32:
592                                         case TypeCode.UInt64:
593                                         case TypeCode.Int64:
594                                         case TypeCode.Single:
595                                         case TypeCode.Double:
596                                                 return 2;
597                                         }
598                                         return -1;
599                                 case TypeCode.Byte:
600                                         switch (tot) {
601                                         case TypeCode.Char:
602                                         case TypeCode.UInt16:
603                                         case TypeCode.Int16:
604                                         case TypeCode.UInt32:
605                                         case TypeCode.Int32:
606                                         case TypeCode.UInt64:
607                                         case TypeCode.Int64:
608                                         case TypeCode.Single:
609                                         case TypeCode.Double:
610                                                 return 2;
611                                         }
612                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
613                                 case TypeCode.SByte:
614                                         switch (tot) {
615                                         case TypeCode.Int16:
616                                         case TypeCode.Int32:
617                                         case TypeCode.Int64:
618                                         case TypeCode.Single:
619                                         case TypeCode.Double:
620                                                 return 2;
621                                         }
622                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
623                                 case TypeCode.UInt16:
624                                         switch (tot) {
625                                         case TypeCode.UInt32:
626                                         case TypeCode.Int32:
627                                         case TypeCode.UInt64:
628                                         case TypeCode.Int64:
629                                         case TypeCode.Single:
630                                         case TypeCode.Double:
631                                                 return 2;
632                                         }
633                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
634                                 case TypeCode.Int16:
635                                         switch (tot) {
636                                         case TypeCode.Int32:
637                                         case TypeCode.Int64:
638                                         case TypeCode.Single:
639                                         case TypeCode.Double:
640                                                 return 2;
641                                         }
642                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
643                                 case TypeCode.UInt32:
644                                         switch (tot) {
645                                         case TypeCode.UInt64:
646                                         case TypeCode.Int64:
647                                         case TypeCode.Single:
648                                         case TypeCode.Double:
649                                                 return 2;
650                                         }
651                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
652                                 case TypeCode.Int32:
653                                         switch (tot) {
654                                         case TypeCode.Int64:
655                                         case TypeCode.Single:
656                                         case TypeCode.Double:
657                                                 return 2;
658                                         }
659                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
660                                 case TypeCode.UInt64:
661                                 case TypeCode.Int64:
662                                         switch (tot) {
663                                         case TypeCode.Single:
664                                         case TypeCode.Double:
665                                                 return 2;
666                                         }
667                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
668                                 case TypeCode.Single:
669                                         return tot == TypeCode.Double ? 2 : -1;
670                                 default:
671                                         return (to.IsAssignableFrom (from)) ? 3 : -1;
672                                 }
673                         }
674                 }
675         }
676 }
677