2006-07-09 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                                 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                                 ParameterInfo [] plist = selected.GetParameters ();
152                                 for (int n = 0; n < names.Length; n++)
153                                         for (int p = 0; p < plist.Length; p++) {
154                                                 if (names [n] == plist [p].Name) {
155                                                         object o = args [n];
156                                                         args [n] = args [p];
157                                                         args [p] = o;
158                                                 }
159                                                 break;
160                                         }
161                         }
162
163                         static bool IsArrayAssignable (Type object_type, Type target_type)
164                         {
165                                 if (object_type.IsArray && target_type.IsArray)
166                                         return IsArrayAssignable (object_type.GetElementType (), target_type.GetElementType ());
167                                                 
168                                 if (target_type.IsAssignableFrom (object_type))
169                                         return true;
170
171                                 return false;
172                         }
173                         
174                         public override object ChangeType (object value, Type type, CultureInfo culture)
175                         {
176                                 if (value == null)
177                                         return null;
178                                 Type vtype = value.GetType ();
179                                 if (type.IsByRef)
180                                         type = type.GetElementType ();
181                                 if (vtype == type || type.IsInstanceOfType (value))
182                                         return value;
183                                 if (vtype.IsArray && type.IsArray){
184                                         if (IsArrayAssignable (vtype.GetElementType (), type.GetElementType ()))
185                                                 return value;
186                                 }
187
188                                 if (check_type (vtype, type))
189                                         return Convert.ChangeType (value, type);
190                                 return null;
191                         }
192
193                         [MonoTODO]
194                         public override void ReorderArgumentArray (ref object[] args, object state)
195                         {
196                                 //do nothing until we support named arguments
197                                 //throw new NotImplementedException ();
198                         }
199
200                         private static bool check_type (Type from, Type to) {
201                                 if (from == to)
202                                         return true;
203
204                                 if (from == null)
205                                         return true;
206
207                                 TypeCode fromt = Type.GetTypeCode (from);
208                                 TypeCode tot = Type.GetTypeCode (to);
209
210                                 if (to.IsByRef != from.IsByRef)
211                                         return false;
212
213                                 if (to.IsInterface)
214                                         return to.IsAssignableFrom (from);
215
216                                 switch (fromt) {
217                                 case TypeCode.Char:
218                                         switch (tot) {
219                                         case TypeCode.UInt16:
220                                         case TypeCode.UInt32:
221                                         case TypeCode.Int32:
222                                         case TypeCode.UInt64:
223                                         case TypeCode.Int64:
224                                         case TypeCode.Single:
225                                         case TypeCode.Double:
226                                                 return true;
227                                         }
228                                         return to == typeof (object);
229                                 case TypeCode.Byte:
230                                         switch (tot) {
231                                         case TypeCode.Char:
232                                         case TypeCode.UInt16:
233                                         case TypeCode.Int16:
234                                         case TypeCode.UInt32:
235                                         case TypeCode.Int32:
236                                         case TypeCode.UInt64:
237                                         case TypeCode.Int64:
238                                         case TypeCode.Single:
239                                         case TypeCode.Double:
240                                                 return true;
241                                         }
242                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
243                                 case TypeCode.SByte:
244                                         switch (tot) {
245                                         case TypeCode.Int16:
246                                         case TypeCode.Int32:
247                                         case TypeCode.Int64:
248                                         case TypeCode.Single:
249                                         case TypeCode.Double:
250                                                 return true;
251                                         }
252                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
253                                 case TypeCode.UInt16:
254                                         switch (tot) {
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) || (from.IsEnum && to == typeof (Enum));
264                                 case TypeCode.Int16:
265                                         switch (tot) {
266                                         case TypeCode.Int32:
267                                         case TypeCode.Int64:
268                                         case TypeCode.Single:
269                                         case TypeCode.Double:
270                                                 return true;
271                                         }
272                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
273                                 case TypeCode.UInt32:
274                                         switch (tot) {
275                                         case TypeCode.UInt64:
276                                         case TypeCode.Int64:
277                                         case TypeCode.Single:
278                                         case TypeCode.Double:
279                                                 return true;
280                                         }
281                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
282                                 case TypeCode.Int32:
283                                         switch (tot) {
284                                         case TypeCode.Int64:
285                                         case TypeCode.Single:
286                                         case TypeCode.Double:
287                                                 return true;
288                                         }
289                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
290                                 case TypeCode.UInt64:
291                                 case TypeCode.Int64:
292                                         switch (tot) {
293                                         case TypeCode.Single:
294                                         case TypeCode.Double:
295                                                 return true;
296                                         }
297                                         return to == typeof (object) || (from.IsEnum && to == typeof (Enum));
298                                 case TypeCode.Single:
299                                         return tot == TypeCode.Double || to == typeof (object);
300                                 default:
301                                         /* TODO: handle valuetype -> byref */
302                                         if (to == typeof (object) && from.IsValueType)
303                                                 return true;
304
305                                         return to.IsAssignableFrom (from);
306                                 }
307                         }
308
309                         private static bool check_arguments (Type[] types, ParameterInfo[] args) {
310                                 for (int i = 0; i < types.Length; ++i) {
311                                         if (!check_type (types [i], args [i].ParameterType))
312                                                 return false;
313                                 }
314                                 return true;
315                         }
316
317                         public override MethodBase SelectMethod (BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
318                         {
319                                 MethodBase m;
320                                 int i, j;
321
322                                 if (match == null)
323                                         throw new ArgumentNullException ("match");
324
325                                 /* first look for an exact match... */
326                                 for (i = 0; i < match.Length; ++i) {
327                                         m = match [i];
328                                         ParameterInfo[] args = m.GetParameters ();
329                                         if (args.Length != types.Length)
330                                                 continue;
331                                         for (j = 0; j < types.Length; ++j) {
332                                                 if (types [j] != args [j].ParameterType)
333                                                         break;
334                                         }
335                                         if (j == types.Length)
336                                                 return m;
337                                 }
338
339                                 if ((int)(bindingAttr & BindingFlags.ExactBinding) != 0)
340                                         return null;
341
342                                 MethodBase result = null;
343                                 for (i = 0; i < match.Length; ++i) {
344                                         m = match [i];
345                                         ParameterInfo[] args = m.GetParameters ();
346                                         if (args.Length != types.Length)
347                                                 continue;
348                                         if (!check_arguments (types, args))
349                                                 continue;
350
351                                         if (result != null)
352                                                 result = GetBetterMethod (result, m, types);
353                                         else
354                                                 result = m;
355                                 }
356
357                                 return result;
358                         }
359
360                         MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
361                         {
362 #if NET_2_0
363                                 if (m1.IsGenericMethodDefinition && 
364                                     !m2.IsGenericMethodDefinition)
365                                         return m2;
366                                 if (m2.IsGenericMethodDefinition && 
367                                     !m1.IsGenericMethodDefinition)
368                                         return m1;
369 #endif
370
371                                 ParameterInfo [] pl1 = m1.GetParameters ();
372                                 ParameterInfo [] pl2 = m2.GetParameters ();
373                                 int prev = 0;
374                                 for (int i = 0; i < pl1.Length; i++) {
375                                         int cmp = CompareCloserType (pl1 [i].ParameterType, pl2 [i].ParameterType);
376                                         if (cmp != 0 && prev != 0 && prev != cmp)
377                                                 throw new AmbiguousMatchException ();
378                                         if (cmp != 0)
379                                                 prev = cmp;
380                                 }
381                                 if (prev != 0)
382                                         return prev > 0 ? m2 : m1;
383
384                                 bool va1 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
385                                 bool va2 = (m1.CallingConvention & CallingConventions.VarArgs) != 0;
386                                 if (va1 && !va2)
387                                         return m2;
388                                 if (va2 && !va1)
389                                         return m1;
390
391                                 throw new AmbiguousMatchException ();
392                         }
393
394                         int CompareCloserType (Type t1, Type t2)
395                         {
396                                 if (t1 == t2)
397                                         return 0;
398 #if NET_2_0
399                                 if (t1.IsGenericParameter && !t2.IsGenericParameter)
400                                         return 1; // t2
401                                 if (!t1.IsGenericParameter && t2.IsGenericParameter)
402                                         return -1; // t1
403 #endif
404                                 if (t1.HasElementType && t2.HasElementType)
405                                         return CompareCloserType (
406                                                 t1.GetElementType (),
407                                                 t2.GetElementType ());
408
409                                 if (t1.IsSubclassOf (t2))
410                                         return -1; // t1
411                                 if (t2.IsSubclassOf (t1))
412                                         return 1; // t2
413
414                                 if (t1.IsInterface && Array.IndexOf (t2.GetInterfaces (), t1) >= 0)
415                                         return 1; // t2
416                                 if (t2.IsInterface && Array.IndexOf (t1.GetInterfaces (), t2) >= 0)
417                                         return -1; // t1
418
419                                 // What kind of cases could reach here?
420                                 return 0;
421                         }
422
423                         public override PropertyInfo SelectProperty (BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
424                         {
425                                 if (match == null || match.Length == 0)
426                                         throw new ArgumentException ("No properties provided", "match");
427
428                                 bool haveRet = (returnType != null);
429                                 int idxlen = (indexes != null) ? indexes.Length : -1;
430                                 PropertyInfo result = null;
431                                 int i;
432                                 int best_score = Int32.MaxValue - 1;
433                                 int fail_score = Int32.MaxValue;
434                                 int level = 0;
435                                 
436                                 for (i = match.Length - 1; i >= 0; i--) {
437                                         PropertyInfo p = match [i];
438                                         ParameterInfo[] args = p.GetIndexParameters ();
439                                         if (idxlen >= 0 && idxlen != args.Length)
440                                                 continue;
441
442                                         if (haveRet && !check_type (p.PropertyType, returnType))
443                                                 continue;
444
445                                         int score = Int32.MaxValue - 1;
446                                         if (idxlen > 0) {
447                                                 score = check_arguments_with_score (indexes, args);
448                                                 if (score == -1)
449                                                         continue;
450                                         }
451
452                                         int new_level = GetDerivedLevel (p.DeclaringType);
453                                         if (result != null) {
454                                                 if (best_score < score)
455                                                         continue;
456
457                                                 if (best_score == score) {
458                                                         if (level == new_level) {
459                                                                 // Keep searching. May be there's something
460                                                                 // better for us.
461                                                                 fail_score = score;
462                                                                 continue;
463                                                         }
464
465                                                         if (level > new_level)
466                                                                 continue;
467                                                 }
468                                         }
469
470                                         result = p;
471                                         best_score = score;
472                                         level = new_level;
473                                 }
474
475                                 if (fail_score <= best_score)
476                                         throw new AmbiguousMatchException ();
477
478                                 return result;
479                         }
480
481                         static int check_arguments_with_score (Type [] types, ParameterInfo [] args)
482                         {
483                                 int worst = -1;
484
485                                 for (int i = 0; i < types.Length; ++i) {
486                                         int res = check_type_with_score (types [i], args [i].ParameterType);
487                                         if (res == -1)
488                                                 return -1;
489
490                                         if (worst < res)
491                                                 worst = res;
492                                 }
493
494                                 return worst;
495                         }
496
497                         // 0 -> same type or null and !valuetype
498                         // 1 -> to == Enum
499                         // 2 -> value type that don't lose data
500                         // 3 -> to == IsAssignableFrom
501                         // 4 -> to == object
502                         static int check_type_with_score (Type from, Type to)
503                         {
504                                 if (from == null)
505                                         return to.IsValueType ? -1 : 0;
506
507                                 if (from == to)
508                                         return 0;
509
510                                 if (to == typeof (object))
511                                         return 4;
512
513                                 TypeCode fromt = Type.GetTypeCode (from);
514                                 TypeCode tot = Type.GetTypeCode (to);
515
516                                 switch (fromt) {
517                                 case TypeCode.Char:
518                                         switch (tot) {
519                                         case TypeCode.UInt16:
520                                                 return 0;
521
522                                         case TypeCode.UInt32:
523                                         case TypeCode.Int32:
524                                         case TypeCode.UInt64:
525                                         case TypeCode.Int64:
526                                         case TypeCode.Single:
527                                         case TypeCode.Double:
528                                                 return 2;
529                                         }
530                                         return -1;
531                                 case TypeCode.Byte:
532                                         switch (tot) {
533                                         case TypeCode.Char:
534                                         case TypeCode.UInt16:
535                                         case TypeCode.Int16:
536                                         case TypeCode.UInt32:
537                                         case TypeCode.Int32:
538                                         case TypeCode.UInt64:
539                                         case TypeCode.Int64:
540                                         case TypeCode.Single:
541                                         case TypeCode.Double:
542                                                 return 2;
543                                         }
544                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
545                                 case TypeCode.SByte:
546                                         switch (tot) {
547                                         case TypeCode.Int16:
548                                         case TypeCode.Int32:
549                                         case TypeCode.Int64:
550                                         case TypeCode.Single:
551                                         case TypeCode.Double:
552                                                 return 2;
553                                         }
554                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
555                                 case TypeCode.UInt16:
556                                         switch (tot) {
557                                         case TypeCode.UInt32:
558                                         case TypeCode.Int32:
559                                         case TypeCode.UInt64:
560                                         case TypeCode.Int64:
561                                         case TypeCode.Single:
562                                         case TypeCode.Double:
563                                                 return 2;
564                                         }
565                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
566                                 case TypeCode.Int16:
567                                         switch (tot) {
568                                         case TypeCode.Int32:
569                                         case TypeCode.Int64:
570                                         case TypeCode.Single:
571                                         case TypeCode.Double:
572                                                 return 2;
573                                         }
574                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
575                                 case TypeCode.UInt32:
576                                         switch (tot) {
577                                         case TypeCode.UInt64:
578                                         case TypeCode.Int64:
579                                         case TypeCode.Single:
580                                         case TypeCode.Double:
581                                                 return 2;
582                                         }
583                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
584                                 case TypeCode.Int32:
585                                         switch (tot) {
586                                         case TypeCode.Int64:
587                                         case TypeCode.Single:
588                                         case TypeCode.Double:
589                                                 return 2;
590                                         }
591                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
592                                 case TypeCode.UInt64:
593                                 case TypeCode.Int64:
594                                         switch (tot) {
595                                         case TypeCode.Single:
596                                         case TypeCode.Double:
597                                                 return 2;
598                                         }
599                                         return (from.IsEnum && to == typeof (Enum)) ? 1 : -1;
600                                 case TypeCode.Single:
601                                         return tot == TypeCode.Double ? 2 : -1;
602                                 default:
603                                         return (to.IsAssignableFrom (from)) ? 3 : -1;
604                                 }
605                         }
606                 }
607         }
608 }
609