2007-11-05 Mark Probst <mark.probst@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                                         return Convert.ChangeType (value, type);
217                                 return null;
218                         }
219
220                         [MonoTODO ("This method does not do anything in Mono")]
221                         public override void ReorderArgumentArray (ref object[] args, object state)
222                         {
223                                 //do nothing until we support named arguments
224                                 //throw new NotImplementedException ();
225                         }
226
227                         private static bool check_type (Type from, Type to) {
228                                 if (from == to)
229                                         return true;
230
231                                 if (from == null)
232                                         return true;
233
234                                 TypeCode fromt = Type.GetTypeCode (from);
235                                 TypeCode tot = Type.GetTypeCode (to);
236
237                                 if (to.IsByRef != from.IsByRef)
238                                         return false;
239
240                                 if (to.IsInterface)
241                                         return to.IsAssignableFrom (from);
242
243                                 switch (fromt) {
244                                 case TypeCode.Char:
245                                         switch (tot) {
246                                         case TypeCode.UInt16:
247                                         case TypeCode.UInt32:
248                                         case TypeCode.Int32:
249                                         case TypeCode.UInt64:
250                                         case TypeCode.Int64:
251                                         case TypeCode.Single:
252                                         case TypeCode.Double:
253                                                 return true;
254                                         }
255                                         return to == typeof (object);
256                                 case TypeCode.Byte:
257                                         switch (tot) {
258                                         case TypeCode.Char:
259                                         case TypeCode.UInt16:
260                                         case TypeCode.Int16:
261                                         case TypeCode.UInt32:
262                                         case TypeCode.Int32:
263                                         case TypeCode.UInt64:
264                                         case TypeCode.Int64:
265                                         case TypeCode.Single:
266                                         case TypeCode.Double:
267                                                 return true;
268                                         }
269                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
270                                 case TypeCode.SByte:
271                                         switch (tot) {
272                                         case TypeCode.Int16:
273                                         case TypeCode.Int32:
274                                         case TypeCode.Int64:
275                                         case TypeCode.Single:
276                                         case TypeCode.Double:
277                                                 return true;
278                                         }
279                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
280                                 case TypeCode.UInt16:
281                                         switch (tot) {
282                                         case TypeCode.UInt32:
283                                         case TypeCode.Int32:
284                                         case TypeCode.UInt64:
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.Int16:
292                                         switch (tot) {
293                                         case TypeCode.Int32:
294                                         case TypeCode.Int64:
295                                         case TypeCode.Single:
296                                         case TypeCode.Double:
297                                                 return true;
298                                         }
299                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
300                                 case TypeCode.UInt32:
301                                         switch (tot) {
302                                         case TypeCode.UInt64:
303                                         case TypeCode.Int64:
304                                         case TypeCode.Single:
305                                         case TypeCode.Double:
306                                                 return true;
307                                         }
308                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
309                                 case TypeCode.Int32:
310                                         switch (tot) {
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.UInt64:
318                                 case TypeCode.Int64:
319                                         switch (tot) {
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.Single:
326                                         return tot == TypeCode.Double || to == typeof (object);
327                                 default:
328                                         /* TODO: handle valuetype -> byref */
329                                         if (to == typeof (object) && from.IsValueType)
330                                                 return true;
331
332                                         return to.IsAssignableFrom (from);
333                                 }
334                         }
335
336                         private static bool check_arguments (Type[] types, ParameterInfo[] args) {
337                                 for (int i = 0; i < types.Length; ++i) {
338                                         if (!check_type (types [i], args [i].ParameterType))
339                                                 return false;
340                                 }
341                                 return true;
342                         }
343
344                         public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
345                         {
346                                 MethodBase m;
347                                 int i, j;
348
349                                 if (match == null)
350                                         throw new ArgumentNullException ("match");
351
352                                 /* first look for an exact match... */
353                                 for (i = 0; i < match.Length; ++i) {
354                                         m = match [i];
355                                         ParameterInfo[] args = m.GetParameters ();
356                                         if (args.Length != types.Length)
357                                                 continue;
358                                         for (j = 0; j < types.Length; ++j) {
359                                                 if (types [j] != args [j].ParameterType)
360                                                         break;
361                                         }
362                                         if (j == types.Length)
363                                                 return m;
364                                 }
365
366                                 /* Try methods with ParamArray attribute */
367                                 bool isdefParamArray = false;
368                                 Type elementType = null;
369                                 for (i = 0; i < match.Length; ++i) {
370                                         m = match [i];
371                                         ParameterInfo[] args = m.GetParameters ();
372                                         if (args.Length > types.Length)
373                                                 continue;
374                                         else if (args.Length == 0)
375                                                 continue;
376                                         isdefParamArray = Attribute.IsDefined (args [args.Length - 1], typeof (ParamArrayAttribute));
377                                         if (!isdefParamArray)
378                                                 continue;
379                                         elementType = args [args.Length - 1].ParameterType.GetElementType ();
380                                         for (j = 0; j < types.Length; ++j) {
381                                                 if (j < (args.Length - 1) && types [j] != args [j].ParameterType)
382                                                         break;
383                                                 else if (j >= (args.Length - 1) && types [j] != elementType) 
384                                                         break;
385                                         }
386                                         if (j == types.Length)
387                                                 return m;
388                                 }
389
390                                 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
391                                         return null;
392
393                                 MethodBase result = null;
394                                 for (i = 0; i < match.Length; ++i) {
395                                         m = match [i];
396                                         ParameterInfo[] args = m.GetParameters ();
397                                         if (args.Length != types.Length)
398                                                 continue;
399                                         if (!check_arguments (types, args))
400                                                 continue;
401
402                                         if (result != null)
403                                                 result = GetBetterMethod (result, m, types);
404                                         else
405                                                 result = m;
406                                 }
407
408                                 return result;
409                         }
410
411                         MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
412                         {
413 #if NET_2_0
414                                 if (m1.IsGenericMethodDefinition && 
415                                     !m2.IsGenericMethodDefinition)
416                                         return m2;
417                                 if (m2.IsGenericMethodDefinition && 
418                                     !m1.IsGenericMethodDefinition)
419                                         return m1;
420 #endif
421
422                                 ParameterInfo [] pl1 = m1.GetParameters ();
423                                 ParameterInfo [] pl2 = m2.GetParameters ();
424                                 int prev = 0;
425                                 for (int i = 0; i < pl1.Length; i++) {
426                                         int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
427                                         if (cmp != 0 && prev != 0 && prev != cmp)
428                                                 throw new AmbiguousMatchException ();
429                                         if (cmp != 0)
430                                                 prev = cmp;
431                                 }
432                                 if (prev != 0)
433                                         return prev > 0 ? m2 : m1;
434
435                                 Type dt1 = m1.DeclaringType;
436                                 Type dt2 = m2.DeclaringType;
437                                 if (dt1 != dt2) {
438                                         if (dt1.IsSubclassOf(dt2))
439                                                 return m1;
440                                         if (dt2.IsSubclassOf(dt1))
441                                                 return m2;
442                                 }
443
444                                 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
445                                 bool va2 = (m2.CallingConvention & CallingConventions.VarArgs) != 0;
446                                 if (va1 && !va2)
447                                         return m2;
448                                 if (va2 && !va1)
449                                         return m1;
450
451                                 throw new AmbiguousMatchException ();
452                         }
453
454                         int CompareCloserType (Type t1, Type t2)
455                         {
456                                 if (t1 == t2)
457                                         return 0;
458 #if NET_2_0
459                                 if (t1.IsGenericParameter && !t2.IsGenericParameter)
460                                         return 1; // t2
461                                 if (!t1.IsGenericParameter && t2.IsGenericParameter)
462                                         return -1; // t1
463 #endif
464                                 if (t1.HasElementType && t2.HasElementType)
465                                         return CompareCloserType (
466                                                 t1.GetElementType (),
467                                                 t2.GetElementType ());
468
469                                 if (t1.IsSubclassOf (t2))
470                                         return -1; // t1
471                                 if (t2.IsSubclassOf (t1))
472                                         return 1; // t2
473
474                                 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
475                                         return 1; // t2
476                                 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
477                                         return -1; // t1
478
479                                 // What kind of cases could reach here?
480                                 return 0;
481                         }
482
483                         public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
484                         {
485                                 if (match == null || match.Length == 0)
486                                         throw new ArgumentException ("No properties provided", "match");
487
488                                 bool haveRet = (returnType != null);
489                                 int idxlen = (indexes != null) ? indexes.Length : -1;
490                                 PropertyInfo result = null;
491                                 int i;
492                                 int best_score = Int32.MaxValue - 1;
493                                 int fail_score = Int32.MaxValue;
494                                 int level = 0;
495                                 
496                                 for (i = match.Length - 1; i >= 0; i--) {
497                                         PropertyInfo p = match [i];
498                                         ParameterInfo[] args = p.GetIndexParameters ();
499                                         if (idxlen >= 0 && idxlen != args.Length)
500                                                 continue;
501
502                                         if (haveRet && !check_type (p.PropertyType, returnType))
503                                                 continue;
504
505                                         int score = Int32.MaxValue - 1;
506                                         if (idxlen > 0) {
507                                                 score = check_arguments_with_score (indexes, args);
508                                                 if (score == -1)
509                                                         continue;
510                                         }
511
512                                         int new_level = GetDerivedLevel (p.DeclaringType);
513                                         if (result != null) {
514                                                 if (best_score < score)
515                                                         continue;
516
517                                                 if (best_score == score) {
518                                                         if (level == new_level) {
519                                                                 // Keep searching. May be there's something
520                                                                 // better for us.
521                                                                 fail_score = score;
522                                                                 continue;
523                                                         }
524
525                                                         if (level > new_level)
526                                                                 continue;
527                                                 }
528                                         }
529
530                                         result = p;
531                                         best_score = score;
532                                         level = new_level;
533                                 }
534
535                                 if (fail_score <= best_score)
536                                         throw new AmbiguousMatchException ();
537
538                                 return result;
539                         }
540
541                         static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
542                         {
543                                 int worst = -1;
544
545                                 for (int i = 0; i < types.Length; ++i) {
546                                         int res = check_type_with_score (types [i], args [i].ParameterType);
547                                         if (res == -1)
548                                                 return -1;
549
550                                         if (worst < res)
551                                                 worst = res;
552                                 }
553
554                                 return worst;
555                         }
556
557                         // 0 -> same type or null and !valuetype
558                         // 1 -> to == Enum
559                         // 2 -> value type that don't lose data
560                         // 3 -> to == IsAssignableFrom
561                         // 4 -> to == object
562                         static int check_type_with_score (Type from, Type to)
563                         {
564                                 if (from == null)
565                                         return to.IsValueType ? -1 : 0;
566
567                                 if (from == to)
568                                         return 0;
569
570                                 if (to == typeof (object))
571                                         return 4;
572
573                                 TypeCode fromt = Type.GetTypeCode (from);
574                                 TypeCode tot = Type.GetTypeCode (to);
575
576                                 switch (fromt) {
577                                 case TypeCode.Char:
578                                         switch (tot) {
579                                         case TypeCode.UInt16:
580                                                 return 0;
581
582                                         case TypeCode.UInt32:
583                                         case TypeCode.Int32:
584                                         case TypeCode.UInt64:
585                                         case TypeCode.Int64:
586                                         case TypeCode.Single:
587                                         case TypeCode.Double:
588                                                 return 2;
589                                         }
590                                         return -1;
591                                 case TypeCode.Byte:
592                                         switch (tot) {
593                                         case TypeCode.Char:
594                                         case TypeCode.UInt16:
595                                         case TypeCode.Int16:
596                                         case TypeCode.UInt32:
597                                         case TypeCode.Int32:
598                                         case TypeCode.UInt64:
599                                         case TypeCode.Int64:
600                                         case TypeCode.Single:
601                                         case TypeCode.Double:
602                                                 return 2;
603                                         }
604                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
605                                 case TypeCode.SByte:
606                                         switch (tot) {
607                                         case TypeCode.Int16:
608                                         case TypeCode.Int32:
609                                         case TypeCode.Int64:
610                                         case TypeCode.Single:
611                                         case TypeCode.Double:
612                                                 return 2;
613                                         }
614                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
615                                 case TypeCode.UInt16:
616                                         switch (tot) {
617                                         case TypeCode.UInt32:
618                                         case TypeCode.Int32:
619                                         case TypeCode.UInt64:
620                                         case TypeCode.Int64:
621                                         case TypeCode.Single:
622                                         case TypeCode.Double:
623                                                 return 2;
624                                         }
625                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
626                                 case TypeCode.Int16:
627                                         switch (tot) {
628                                         case TypeCode.Int32:
629                                         case TypeCode.Int64:
630                                         case TypeCode.Single:
631                                         case TypeCode.Double:
632                                                 return 2;
633                                         }
634                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
635                                 case TypeCode.UInt32:
636                                         switch (tot) {
637                                         case TypeCode.UInt64:
638                                         case TypeCode.Int64:
639                                         case TypeCode.Single:
640                                         case TypeCode.Double:
641                                                 return 2;
642                                         }
643                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
644                                 case TypeCode.Int32:
645                                         switch (tot) {
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.UInt64:
653                                 case TypeCode.Int64:
654                                         switch (tot) {
655                                         case TypeCode.Single:
656                                         case TypeCode.Double:
657                                                 return 2;
658                                         }
659                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
660                                 case TypeCode.Single:
661                                         return tot == TypeCode.Double ? 2 : -1;
662                                 default:
663                                         return (to.IsAssignableFrom (from)) ? 3 : -1;
664                                 }
665                         }
666                 }
667         }
668 }
669