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