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