2006-10-10 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / mcs / convert.cs
1 //
2 // conversion.cs: various routines for implementing conversions.
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Ravi Pratap (ravi@ximian.com)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 //
10
11 namespace Mono.CSharp {
12         using System;
13         using System.Collections;
14         using System.Diagnostics;
15         using System.Reflection;
16         using System.Reflection.Emit;
17
18         //
19         // A container class for all the conversion operations
20         //
21         public class Convert {
22 #if GMCS_SOURCE
23                 static bool TypeParameter_to_Null (Type target_type)
24                 {
25                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
26                         if (gc == null)
27                                 return false;
28
29                         if (gc.HasReferenceTypeConstraint)
30                                 return true;
31                         if (gc.HasClassConstraint && !TypeManager.IsValueType (gc.ClassConstraint))
32                                 return true;
33
34                         return false;
35                 }
36
37                 static Type TypeParam_EffectiveBaseType (GenericConstraints gc)
38                 {
39                         ArrayList list = new ArrayList ();
40                         list.Add (gc.EffectiveBaseClass);
41                         foreach (Type t in gc.InterfaceConstraints) {
42                                 if (!TypeManager.IsGenericParameter (t))
43                                         continue;
44
45                                 GenericConstraints new_gc = TypeManager.GetTypeParameterConstraints (t);
46                                 if (new_gc != null)
47                                         list.Add (TypeParam_EffectiveBaseType (new_gc));
48                         }
49                         return FindMostEncompassedType (list);
50                 }
51 #endif
52
53                 //
54                 // From a one-dimensional array-type S[] to System.Collections.IList<S> and base
55                 // interfaces of this interface.
56                 //
57                 // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
58                 // interfaces of this interface, provided there is an implicit reference conversion
59                 // from S to T.
60                 //
61                 static bool Array_To_IList (Type array, Type list)
62                 {
63 #if GMCS_SOURCE
64                         if (!array.IsArray || (array.GetArrayRank () != 1) || !list.IsGenericType)
65                                 return false;
66
67                         Type gt = list.GetGenericTypeDefinition ();
68                         if ((gt != TypeManager.generic_ilist_type) &&
69                             (gt != TypeManager.generic_icollection_type) &&
70                             (gt != TypeManager.generic_ienumerable_type))
71                                 return false;
72
73                         Type element_type = TypeManager.GetElementType (array);
74                         Type arg_type = TypeManager.GetTypeArguments (list) [0];
75
76                         if (element_type == arg_type)
77                                 return true;
78
79                         if (MyEmptyExpr == null)
80                                 MyEmptyExpr = new EmptyExpression ();
81                         MyEmptyExpr.SetType (TypeManager.GetElementType (array));
82
83                         return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type);
84 #else
85                         return false;
86 #endif
87                 }
88
89                 static Expression ImplicitTypeParameterConversion (Expression expr,
90                                                                    Type target_type)
91                 {
92 #if GMCS_SOURCE
93                         Type expr_type = expr.Type;
94
95                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
96
97                         if (gc == null) {
98                                 if (target_type == TypeManager.object_type)
99                                         return new BoxedCast (expr, target_type);
100
101                                 return null;
102                         }
103
104                         // We're converting from a type parameter which is known to be a reference type.
105                         Type base_type = TypeParam_EffectiveBaseType (gc);
106
107                         if (TypeManager.IsSubclassOf (base_type, target_type))
108                                 return new ClassCast (expr, target_type);
109
110                         if (target_type.IsInterface) {
111                                 if (TypeManager.ImplementsInterface (base_type, target_type))
112                                         return new ClassCast (expr, target_type);
113
114                                 foreach (Type t in gc.InterfaceConstraints) {
115                                         if (TypeManager.IsSubclassOf (t, target_type))
116                                                 return new ClassCast (expr, target_type);
117                                         if (TypeManager.ImplementsInterface (t, target_type))
118                                                 return new ClassCast (expr, target_type);
119                                 }
120                         }
121
122                         foreach (Type t in gc.InterfaceConstraints) {
123                                 if (!TypeManager.IsGenericParameter (t))
124                                         continue;
125                                 if (TypeManager.IsSubclassOf (t, target_type))
126                                         return new ClassCast (expr, target_type);
127                                 if (TypeManager.ImplementsInterface (t, target_type))
128                                         return new ClassCast (expr, target_type);
129                         }
130 #endif
131                         return null;
132                 }
133
134                 static bool ExplicitTypeParameterConversionExists (Type source_type, Type target_type)
135                 {
136 #if GMCS_SOURCE
137                         if (target_type.IsInterface)
138                                 return true;
139
140                         if (TypeManager.IsGenericParameter (target_type)) {
141                                 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
142                                 if (gc == null)
143                                         return false;
144
145                                 foreach (Type iface in gc.InterfaceConstraints) {
146                                         if (!TypeManager.IsGenericParameter (iface))
147                                                 continue;
148
149                                         if (TypeManager.IsSubclassOf (source_type, iface))
150                                                 return true;
151                                 }
152                         }
153 #endif
154                         return false;
155                 }
156
157                 static Expression ExplicitTypeParameterConversion (Expression source, Type target_type)
158                 {
159 #if GMCS_SOURCE
160                         Type source_type = source.Type;
161
162                         if (target_type.IsInterface)
163                                 return new ClassCast (source, target_type);
164
165                         if (TypeManager.IsGenericParameter (target_type)) {
166                                 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
167                                 if (gc == null)
168                                         return null;
169
170                                 foreach (Type iface in gc.InterfaceConstraints) {
171                                         if (!TypeManager.IsGenericParameter (iface))
172                                                 continue;
173
174                                         if (TypeManager.IsSubclassOf (source_type, iface))
175                                                 return new ClassCast (source, target_type);
176                                 }
177                         }
178 #endif
179                         return null;
180                 }
181
182                 static EmptyExpression MyEmptyExpr;
183                 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
184                 {
185                         Type expr_type = expr.Type;
186
187                         if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
188                                 // if we are a method group, emit a warning
189
190                                 expr.Emit (null);
191                         }
192
193                         if (expr_type == TypeManager.void_type)
194                                 return null;
195
196                         if (TypeManager.IsGenericParameter (expr_type))
197                                 return ImplicitTypeParameterConversion (expr, target_type);
198
199                         //
200                         // notice that it is possible to write "ValueType v = 1", the ValueType here
201                         // is an abstract class, and not really a value type, so we apply the same rules.
202                         //
203                         if (target_type == TypeManager.object_type) {
204                                 //
205                                 // A pointer type cannot be converted to object
206                                 //
207                                 if (expr_type.IsPointer)
208                                         return null;
209
210                                 if (TypeManager.IsValueType (expr_type))
211                                         return new BoxedCast (expr, target_type);
212                                 if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type){
213                                         if (expr_type == TypeManager.anonymous_method_type)
214                                                 return null;
215                                         return new EmptyCast (expr, target_type);
216                                 }
217
218                                 return null;
219                         } else if (target_type == TypeManager.value_type) {
220                                 if (TypeManager.IsValueType (expr_type))
221                                         return new BoxedCast (expr, target_type);
222                                 if (expr_type == TypeManager.null_type)
223                                         return new EmptyConstantCast ((Constant)expr, target_type);
224
225                                 return null;
226                         } else if (TypeManager.IsSubclassOf (expr_type, target_type)) {
227                                 //
228                                 // Special case: enumeration to System.Enum.
229                                 // System.Enum is not a value type, it is a class, so we need
230                                 // a boxing conversion
231                                 //
232                                 if (expr_type.IsEnum || TypeManager.IsGenericParameter (expr_type))
233                                         return new BoxedCast (expr, target_type);
234
235                                 return new EmptyCast (expr, target_type);
236                         }
237
238                         // This code is kind of mirrored inside ImplicitStandardConversionExists
239                         // with the small distinction that we only probe there
240                         //
241                         // Always ensure that the code here and there is in sync
242
243                         // from the null type to any reference-type.
244                         if (expr_type == TypeManager.null_type) {
245                                 NullConstant nc = (NullConstant)expr;
246                                 return nc.ToType(target_type);
247                         }
248
249                         // from any class-type S to any interface-type T.
250                         if (target_type.IsInterface) {
251                                 if (target_type != TypeManager.iconvertible_type &&
252                                     expr_type.IsValueType && (expr is Constant) &&
253                                     !(expr is IntLiteral || expr is BoolLiteral ||
254                                       expr is FloatLiteral || expr is DoubleLiteral ||
255                                       expr is LongLiteral || expr is CharLiteral ||
256                                       expr is StringLiteral || expr is DecimalLiteral ||
257                                       expr is UIntLiteral || expr is ULongLiteral)) {
258                                         return null;
259                                 }
260
261                                 if (TypeManager.ImplementsInterface (expr_type, target_type)){
262                                         if (TypeManager.IsGenericParameter (expr_type) || TypeManager.IsValueType (expr_type))
263                                                 return new BoxedCast (expr, target_type);
264                                         else
265                                                 return new EmptyCast (expr, target_type);
266                                 }
267                         }
268
269                         // from any interface type S to interface-type T.
270                         if (expr_type.IsInterface && target_type.IsInterface) {
271                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
272                                         return new EmptyCast (expr, target_type);
273                                 else
274                                         return null;
275                         }
276
277                         // from an array-type S to an array-type of type T
278                         if (expr_type.IsArray && target_type.IsArray) {
279                                 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
280
281                                         Type expr_element_type = TypeManager.GetElementType (expr_type);
282
283                                         if (MyEmptyExpr == null)
284                                                 MyEmptyExpr = new EmptyExpression ();
285
286                                         MyEmptyExpr.SetType (expr_element_type);
287                                         Type target_element_type = TypeManager.GetElementType (target_type);
288
289                                         if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
290                                                 if (ImplicitStandardConversionExists (MyEmptyExpr,
291                                                                                       target_element_type))
292                                                         return new EmptyCast (expr, target_type);
293                                 }
294                         }
295
296                         // from an array-type to System.Array
297                         if (expr_type.IsArray && target_type == TypeManager.array_type)
298                                 return new EmptyCast (expr, target_type);
299
300                         // from an array-type of type T to IList<T>
301                         if (expr_type.IsArray && Array_To_IList (expr_type, target_type))
302                                 return new EmptyCast (expr, target_type);
303
304                         // from any delegate type to System.Delegate
305                         if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
306                             target_type == TypeManager.delegate_type)
307                                 return new EmptyCast (expr, target_type);
308
309                         // from any array-type or delegate type into System.ICloneable.
310                         if (expr_type.IsArray ||
311                             expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
312                                 if (target_type == TypeManager.icloneable_type)
313                                         return new EmptyCast (expr, target_type);
314
315                         // from a generic type definition to a generic instance.
316                         if (TypeManager.IsEqual (expr_type, target_type))
317                                 return new EmptyCast (expr, target_type);
318
319                         return null;
320                 }
321
322                 //
323                 // Tests whether an implicit reference conversion exists between expr_type
324                 // and target_type
325                 //
326                 public static bool ImplicitReferenceConversionExists (Expression expr, Type target_type)
327                 {
328                         if (target_type.IsValueType)
329                                 return false;
330
331                         Type expr_type = expr.Type;
332
333                         if (TypeManager.IsGenericParameter (expr_type))
334                                 return ImplicitTypeParameterConversion (expr, target_type) != null;
335
336                         //
337                         // This is the boxed case.
338                         //
339                         if (target_type == TypeManager.object_type) {
340                                 if (expr_type.IsClass || TypeManager.IsValueType (expr_type) ||
341                                     expr_type.IsInterface || expr_type == TypeManager.enum_type)
342                                         if (target_type != TypeManager.anonymous_method_type)
343                                         return true;
344
345                                 return false;
346                         } else if (TypeManager.IsSubclassOf (expr_type, target_type))
347                                 return true;
348
349                         // Please remember that all code below actually comes
350                         // from ImplicitReferenceConversion so make sure code remains in sync
351
352                         // from any class-type S to any interface-type T.
353                         if (target_type.IsInterface) {
354                                 if (target_type != TypeManager.iconvertible_type &&
355                                     expr_type.IsValueType && (expr is Constant) &&
356                                     !(expr is IntLiteral || expr is BoolLiteral ||
357                                       expr is FloatLiteral || expr is DoubleLiteral ||
358                                       expr is LongLiteral || expr is CharLiteral ||
359                                       expr is StringLiteral || expr is DecimalLiteral ||
360                                       expr is UIntLiteral || expr is ULongLiteral)) {
361                                         return false;
362                                 }
363
364                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
365                                         return true;
366                         }
367
368                         // from any interface type S to interface-type T.
369                         if (expr_type.IsInterface && target_type.IsInterface)
370                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
371                                         return true;
372
373                         // from an array-type S to an array-type of type T
374                         if (expr_type.IsArray && target_type.IsArray) {
375                                 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
376
377                                         Type expr_element_type = expr_type.GetElementType ();
378
379                                         if (MyEmptyExpr == null)
380                                                 MyEmptyExpr = new EmptyExpression ();
381
382                                         MyEmptyExpr.SetType (expr_element_type);
383                                         Type target_element_type = TypeManager.GetElementType (target_type);
384
385                                         if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
386                                                 if (ImplicitStandardConversionExists (MyEmptyExpr,
387                                                                                       target_element_type))
388                                                         return true;
389                                 }
390                         }
391
392                         // from an array-type to System.Array
393                         if (expr_type.IsArray && (target_type == TypeManager.array_type))
394                                 return true;
395
396                         // from an array-type of type T to IList<T>
397                         if (expr_type.IsArray && Array_To_IList (expr_type, target_type))
398                                 return true;
399
400                         // from any delegate type to System.Delegate
401                         if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
402                             target_type == TypeManager.delegate_type)
403                                 if (target_type.IsAssignableFrom (expr_type))
404                                         return true;
405
406                         // from any array-type or delegate type into System.ICloneable.
407                         if (expr_type.IsArray ||
408                             expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
409                                 if (target_type == TypeManager.icloneable_type)
410                                         return true;
411
412                         // from the null type to any reference-type.
413                         if (expr_type == TypeManager.null_type){
414                                 if (target_type.IsPointer)
415                                         return true;
416
417                                 if (!target_type.IsValueType)
418                                         return true;
419                         }
420
421                         // from a generic type definition to a generic instance.
422                         if (TypeManager.IsEqual (expr_type, target_type))
423                                 return true;
424
425                         return false;
426                 }
427
428                 /// <summary>
429                 ///   Implicit Numeric Conversions.
430                 ///
431                 ///   expr is the expression to convert, returns a new expression of type
432                 ///   target_type or null if an implicit conversion is not possible.
433                 /// </summary>
434                 static public Expression ImplicitNumericConversion (Expression expr,
435                                                                     Type target_type)
436                 {
437                         Type expr_type = expr.Type;
438
439                         //
440                         // Attempt to do the implicit constant expression conversions
441
442                         if (expr is Constant){
443                                 if (expr is IntConstant){
444                                         Expression e;
445
446                                         e = TryImplicitIntConversion (target_type, (IntConstant) expr);
447
448                                         if (e != null)
449                                                 return e;
450                                 } else if (expr is LongConstant && target_type == TypeManager.uint64_type){
451                                         //
452                                         // Try the implicit constant expression conversion
453                                         // from long to ulong, instead of a nice routine,
454                                         // we just inline it
455                                         //
456                                         long v = ((LongConstant) expr).Value;
457                                         if (v >= 0)
458                                                 return new ULongConstant ((ulong) v, expr.Location);
459                                 }
460                         }
461
462                         Type real_target_type = target_type;
463
464                         if (expr_type == TypeManager.sbyte_type){
465                                 //
466                                 // From sbyte to short, int, long, float, double, decimal
467                                 //
468                                 if (real_target_type == TypeManager.int32_type)
469                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
470                                 if (real_target_type == TypeManager.int64_type)
471                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
472                                 if (real_target_type == TypeManager.double_type)
473                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
474                                 if (real_target_type == TypeManager.float_type)
475                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
476                                 if (real_target_type == TypeManager.short_type)
477                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
478                                 if (real_target_type == TypeManager.decimal_type)
479                                         return new CastToDecimal (expr);
480                         } else if (expr_type == TypeManager.byte_type){
481                                 //
482                                 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
483                                 //
484                                 if ((real_target_type == TypeManager.short_type) ||
485                                     (real_target_type == TypeManager.ushort_type) ||
486                                     (real_target_type == TypeManager.int32_type) ||
487                                     (real_target_type == TypeManager.uint32_type))
488                                         return new EmptyCast (expr, target_type);
489
490                                 if (real_target_type == TypeManager.uint64_type)
491                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
492                                 if (real_target_type == TypeManager.int64_type)
493                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
494                                 if (real_target_type == TypeManager.float_type)
495                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
496                                 if (real_target_type == TypeManager.double_type)
497                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
498                                 if (real_target_type == TypeManager.decimal_type)
499                                         return new CastToDecimal (expr);
500
501                         } else if (expr_type == TypeManager.short_type){
502                                 //
503                                 // From short to int, long, float, double, decimal
504                                 //
505                                 if (real_target_type == TypeManager.int32_type)
506                                         return new EmptyCast (expr, target_type);
507                                 if (real_target_type == TypeManager.int64_type)
508                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
509                                 if (real_target_type == TypeManager.double_type)
510                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
511                                 if (real_target_type == TypeManager.float_type)
512                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
513                                 if (real_target_type == TypeManager.decimal_type)
514                                         return new CastToDecimal (expr);
515
516                         } else if (expr_type == TypeManager.ushort_type){
517                                 //
518                                 // From ushort to int, uint, long, ulong, float, double, decimal
519                                 //
520                                 if (real_target_type == TypeManager.uint32_type)
521                                         return new EmptyCast (expr, target_type);
522
523                                 if (real_target_type == TypeManager.uint64_type)
524                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
525                                 if (real_target_type == TypeManager.int32_type)
526                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
527                                 if (real_target_type == TypeManager.int64_type)
528                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
529                                 if (real_target_type == TypeManager.double_type)
530                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
531                                 if (real_target_type == TypeManager.float_type)
532                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
533                                 if (real_target_type == TypeManager.decimal_type)
534                                         return new CastToDecimal (expr);
535                         } else if (expr_type == TypeManager.int32_type){
536                                 //
537                                 // From int to long, float, double, decimal
538                                 //
539                                 if (real_target_type == TypeManager.int64_type)
540                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
541                                 if (real_target_type == TypeManager.double_type)
542                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
543                                 if (real_target_type == TypeManager.float_type)
544                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
545                                 if (real_target_type == TypeManager.decimal_type)
546                                         return new CastToDecimal (expr);
547                         } else if (expr_type == TypeManager.uint32_type){
548                                 //
549                                 // From uint to long, ulong, float, double, decimal
550                                 //
551                                 if (real_target_type == TypeManager.int64_type)
552                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
553                                 if (real_target_type == TypeManager.uint64_type)
554                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
555                                 if (real_target_type == TypeManager.double_type)
556                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
557                                                                OpCodes.Conv_R8);
558                                 if (real_target_type == TypeManager.float_type)
559                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
560                                                                OpCodes.Conv_R4);
561                                 if (real_target_type == TypeManager.decimal_type)
562                                         return new CastToDecimal (expr);
563                         } else if (expr_type == TypeManager.int64_type){
564                                 //
565                                 // From long/ulong to float, double
566                                 //
567                                 if (real_target_type == TypeManager.double_type)
568                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
569                                 if (real_target_type == TypeManager.float_type)
570                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
571                                 if (real_target_type == TypeManager.decimal_type)
572                                         return new CastToDecimal (expr);
573                         } else if (expr_type == TypeManager.uint64_type){
574                                 //
575                                 // From ulong to float, double
576                                 //
577                                 if (real_target_type == TypeManager.double_type)
578                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
579                                                                OpCodes.Conv_R8);
580                                 if (real_target_type == TypeManager.float_type)
581                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
582                                                                OpCodes.Conv_R4);
583                                 if (real_target_type == TypeManager.decimal_type)
584                                         return new CastToDecimal (expr);
585                         } else if (expr_type == TypeManager.char_type){
586                                 //
587                                 // From char to ushort, int, uint, long, ulong, float, double, decimal
588                                 //
589                                 if ((real_target_type == TypeManager.ushort_type) ||
590                                     (real_target_type == TypeManager.int32_type) ||
591                                     (real_target_type == TypeManager.uint32_type))
592                                         return new EmptyCast (expr, target_type);
593                                 if (real_target_type == TypeManager.uint64_type)
594                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
595                                 if (real_target_type == TypeManager.int64_type)
596                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
597                                 if (real_target_type == TypeManager.float_type)
598                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
599                                 if (real_target_type == TypeManager.double_type)
600                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
601                                 if (real_target_type == TypeManager.decimal_type)
602                                         return new CastToDecimal (expr);
603                         } else if (expr_type == TypeManager.float_type){
604                                 //
605                                 // float to double
606                                 //
607                                 if (real_target_type == TypeManager.double_type)
608                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
609                         }
610
611                         return null;
612                 }
613
614                 /// <summary>
615                 ///  Same as ImplicitStandardConversionExists except that it also looks at
616                 ///  implicit user defined conversions - needed for overload resolution
617                 /// </summary>
618                 public static bool ImplicitConversionExists (EmitContext ec, Expression expr, Type target_type)
619                 {
620 #if GMCS_SOURCE
621                         if (expr is NullLiteral) {
622                                 if (TypeManager.IsGenericParameter (target_type))
623                                         return TypeParameter_to_Null (target_type);
624
625                                 if (TypeManager.IsNullableType (target_type))
626                                         return true;
627                         }
628 #endif
629                         if (ImplicitStandardConversionExists (expr, target_type))
630                                 return true;
631
632                         return ImplicitUserConversion (ec, expr, target_type, Location.Null) != null;
633                 }
634
635                 public static bool ImplicitUserConversionExists (EmitContext ec, Type source, Type target)
636                 {
637                         return ImplicitUserConversion (ec, new EmptyExpression (source), target, Location.Null) != null;
638                 }
639
640                 /// <summary>
641                 ///  Determines if a standard implicit conversion exists from
642                 ///  expr_type to target_type
643                 ///
644                 ///  ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
645                 /// </summary>
646                 public static bool ImplicitStandardConversionExists (Expression expr, Type target_type)
647                 {
648                         Type expr_type = expr.Type;
649 #if GMCS_SOURCE
650                         if (TypeManager.IsNullableType (target_type)) {
651                                 // if implicit standard conversion S -> T exists, S -> T? and S? -> T? also exists
652                                 target_type = TypeManager.GetTypeArguments (target_type) [0];
653
654                                 // S? -> T?
655                                 if (TypeManager.IsNullableType (expr_type)) {
656                                         EmptyExpression new_expr = EmptyExpression.Grab ();
657                                         new_expr.SetType (TypeManager.GetTypeArguments (expr_type) [0]);
658                                         bool retval = ImplicitStandardConversionExists (new_expr, target_type);
659                                         EmptyExpression.Release (new_expr);
660                                         return retval;
661                                 }
662                         }
663 #endif
664                         if (expr_type == TypeManager.void_type)
665                                 return false;
666
667                         //Console.WriteLine ("Expr is {0}", expr);
668                         //Console.WriteLine ("{0} -> {1} ?", expr_type, target_type);
669                         if (expr_type.Equals (target_type))
670                                 return true;
671
672
673                         // First numeric conversions
674
675                         if (expr_type == TypeManager.sbyte_type){
676                                 //
677                                 // From sbyte to short, int, long, float, double, uintptr, decimal
678                                 //
679                                 if ((target_type == TypeManager.int32_type) ||
680                                     (target_type == TypeManager.int64_type) ||
681                                     (target_type == TypeManager.double_type) ||
682                                     (target_type == TypeManager.float_type)  ||
683                                     (target_type == TypeManager.short_type) ||
684                                     (target_type == TypeManager.uintptr_type) ||
685                                     (target_type == TypeManager.decimal_type))
686                                         return true;
687
688                         } else if (expr_type == TypeManager.byte_type){
689                                 //
690                                 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
691                                 //
692                                 if ((target_type == TypeManager.short_type) ||
693                                     (target_type == TypeManager.ushort_type) ||
694                                     (target_type == TypeManager.int32_type) ||
695                                     (target_type == TypeManager.uint32_type) ||
696                                     (target_type == TypeManager.uint64_type) ||
697                                     (target_type == TypeManager.int64_type) ||
698                                     (target_type == TypeManager.float_type) ||
699                                     (target_type == TypeManager.double_type) ||
700                                     (target_type == TypeManager.decimal_type))
701                                         return true;
702
703                         } else if (expr_type == TypeManager.short_type){
704                                 //
705                                 // From short to int, long, double, float, decimal and uintptr
706                                 //
707                                 if ((target_type == TypeManager.int32_type) ||
708                                     (target_type == TypeManager.int64_type) ||
709                                     (target_type == TypeManager.double_type) ||
710                                     (target_type == TypeManager.float_type) ||
711                                     (target_type == TypeManager.uintptr_type) ||
712                                     (target_type == TypeManager.decimal_type))
713                                         return true;
714
715                         } else if (expr_type == TypeManager.ushort_type){
716                                 //
717                                 // From ushort to int, uint, long, ulong, double, float, decimal
718                                 //
719                                 if ((target_type == TypeManager.uint32_type) ||
720                                     (target_type == TypeManager.uint64_type) ||
721                                     (target_type == TypeManager.int32_type) ||
722                                     (target_type == TypeManager.int64_type) ||
723                                     (target_type == TypeManager.double_type) ||
724                                     (target_type == TypeManager.float_type) ||
725                                     (target_type == TypeManager.decimal_type))
726                                         return true;
727
728                         } else if (expr_type == TypeManager.int32_type){
729                                 //
730                                 // From int to long, double, float, decimal, uintptr
731                                 //
732                                 if ((target_type == TypeManager.int64_type) ||
733                                     (target_type == TypeManager.double_type) ||
734                                     (target_type == TypeManager.float_type) ||
735                                     (target_type == TypeManager.uintptr_type) ||
736                                     (target_type == TypeManager.decimal_type))
737                                         return true;
738
739                         } else if (expr_type == TypeManager.uint32_type){
740                                 //
741                                 // From uint to long, ulong, double, float, decimal
742                                 //
743                                 if ((target_type == TypeManager.int64_type) ||
744                                     (target_type == TypeManager.uint64_type) ||
745                                     (target_type == TypeManager.double_type) ||
746                                     (target_type == TypeManager.float_type) ||
747                                     (target_type == TypeManager.decimal_type))
748                                         return true;
749
750                         } else if ((expr_type == TypeManager.uint64_type) ||
751                                    (expr_type == TypeManager.int64_type)) {
752                                 //
753                                 // From long/ulong to double, float, decimal
754                                 //
755                                 if ((target_type == TypeManager.double_type) ||
756                                     (target_type == TypeManager.float_type) ||
757                                     (target_type == TypeManager.decimal_type))
758                                         return true;
759
760                                 //
761                                 // From uint64 to IntPtr, from the extra conversions.
762                                 //
763                                 if (target_type == TypeManager.intptr_type && expr_type == TypeManager.uint64_type)
764                                         return true;
765                                 
766                         } else if (expr_type == TypeManager.char_type){
767                                 //
768                                 // From char to ushort, int, uint, ulong, long, float, double, decimal
769                                 //
770                                 if ((target_type == TypeManager.ushort_type) ||
771                                     (target_type == TypeManager.int32_type) ||
772                                     (target_type == TypeManager.uint32_type) ||
773                                     (target_type == TypeManager.uint64_type) ||
774                                     (target_type == TypeManager.int64_type) ||
775                                     (target_type == TypeManager.float_type) ||
776                                     (target_type == TypeManager.double_type) ||
777                                     (target_type == TypeManager.decimal_type))
778                                         return true;
779
780                         } else if (expr_type == TypeManager.float_type){
781                                 //
782                                 // float to double
783                                 //
784                                 if (target_type == TypeManager.double_type)
785                                         return true;
786                         } else if (expr_type == TypeManager.uintptr_type){
787                                 if ((target_type == TypeManager.sbyte_type) ||
788                                     (target_type == TypeManager.short_type) ||
789                                     (target_type == TypeManager.int32_type))
790                                         return true;
791                         } else if (expr_type == TypeManager.intptr_type){
792                                 if (target_type == TypeManager.uint64_type)
793                                         return true;
794                         }
795
796                         if (expr.eclass == ExprClass.MethodGroup){
797                                 if (TypeManager.IsDelegateType (target_type) && RootContext.Version != LanguageVersion.ISO_1){
798                                         MethodGroupExpr mg = expr as MethodGroupExpr;
799                                         if (mg != null){
800                                                 return DelegateCreation.ImplicitStandardConversionExists (mg, target_type) != null;
801                                         }
802                                 }
803                         }
804
805                         if (ImplicitReferenceConversionExists (expr, target_type))
806                                 return true;
807
808                         //
809                         // Implicit Constant Expression Conversions
810                         //
811                         if (expr is IntConstant){
812                                 int value = ((IntConstant) expr).Value;
813
814                                 if (target_type == TypeManager.sbyte_type){
815                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
816                                                 return true;
817                                 } else if (target_type == TypeManager.byte_type){
818                                         if (value >= 0 && value <= Byte.MaxValue)
819                                                 return true;
820                                 } else if (target_type == TypeManager.short_type){
821                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
822                                                 return true;
823                                 } else if (target_type == TypeManager.ushort_type){
824                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
825                                                 return true;
826                                 } else if (target_type == TypeManager.uint32_type){
827                                         if (value >= 0)
828                                                 return true;
829                                 } else if (target_type == TypeManager.uint64_type){
830                                          //
831                                          // we can optimize this case: a positive int32
832                                          // always fits on a uint64.  But we need an opcode
833                                          // to do it.
834                                          //
835                                         if (value >= 0)
836                                                 return true;
837                                 }
838
839                                 if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
840                                         return true;
841                         }
842
843                         if (expr is LongConstant && target_type == TypeManager.uint64_type){
844                                 //
845                                 // Try the implicit constant expression conversion
846                                 // from long to ulong, instead of a nice routine,
847                                 // we just inline it
848                                 //
849                                 long v = ((LongConstant) expr).Value;
850                                 if (v >= 0)
851                                         return true;
852                         }
853
854                         if ((target_type == TypeManager.enum_type ||
855                              target_type.IsSubclassOf (TypeManager.enum_type)) &&
856                              expr is IntLiteral){
857                                 IntLiteral i = (IntLiteral) expr;
858
859                                 if (i.Value == 0)
860                                         return true;
861                         }
862
863                         //
864                         // If `expr_type' implements `target_type' (which is an iface)
865                         // see TryImplicitIntConversion
866                         //
867                         if (target_type.IsInterface && target_type.IsAssignableFrom (expr_type))
868                                 return true;
869
870                         if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
871                                 return true;
872
873                         if (expr_type == TypeManager.anonymous_method_type){
874                                 if (!TypeManager.IsDelegateType (target_type))
875                                         return false;
876
877                                 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
878                                 return ame.ImplicitStandardConversionExists (target_type);
879                         }
880
881                         return false;
882                 }
883
884                 /// <summary>
885                 ///  Finds "most encompassed type" according to the spec (13.4.2)
886                 ///  amongst the methods in the MethodGroupExpr
887                 /// </summary>
888                 static Type FindMostEncompassedType (ArrayList types)
889                 {
890                         Type best = null;
891
892                         if (types.Count == 0)
893                                 return null;
894
895                         if (types.Count == 1)
896                                 return (Type) types [0];
897
898                         EmptyExpression expr = EmptyExpression.Grab ();
899
900                         foreach (Type t in types) {
901                                 if (best == null) {
902                                         best = t;
903                                         continue;
904                                 }
905
906                                 expr.SetType (t);
907                                 if (ImplicitStandardConversionExists (expr, best))
908                                         best = t;
909                         }
910
911                         expr.SetType (best);
912                         foreach (Type t in types) {
913                                 if (best == t)
914                                         continue;
915                                 if (!ImplicitStandardConversionExists (expr, t)) {
916                                         best = null;
917                                         break;
918                                 }
919                         }
920
921                         EmptyExpression.Release (expr);
922
923                         return best;
924                 }
925
926                 /// <summary>
927                 ///  Finds "most encompassing type" according to the spec (13.4.2)
928                 ///  amongst the types in the given set
929                 /// </summary>
930                 static Type FindMostEncompassingType (ArrayList types)
931                 {
932                         Type best = null;
933
934                         if (types.Count == 0)
935                                 return null;
936
937                         if (types.Count == 1)
938                                 return (Type) types [0];
939
940                         EmptyExpression expr = EmptyExpression.Grab ();
941
942                         foreach (Type t in types) {
943                                 if (best == null) {
944                                         best = t;
945                                         continue;
946                                 }
947
948                                 expr.SetType (best);
949                                 if (ImplicitStandardConversionExists (expr, t))
950                                         best = t;
951                         }
952
953                         foreach (Type t in types) {
954                                 if (best == t)
955                                         continue;
956                                 expr.SetType (t);
957                                 if (!ImplicitStandardConversionExists (expr, best)) {
958                                         best = null;
959                                         break;
960                                 }
961                         }
962
963                         EmptyExpression.Release (expr);
964
965                         return best;
966                 }
967
968                 /// <summary>
969                 ///   Finds the most specific source Sx according to the rules of the spec (13.4.4)
970                 ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
971                 ///   for explicit and implicit conversion operators.
972                 /// </summary>
973                 static public Type FindMostSpecificSource (IList list,
974                                                            Expression source, bool apply_explicit_conv_rules)
975                 {
976                         ArrayList src_types_set = new ArrayList ();
977
978                         //
979                         // If any operator converts from S then Sx = S
980                         //
981                         Type source_type = source.Type;
982                         foreach (MethodBase mb in list){
983                                 ParameterData pd = TypeManager.GetParameterData (mb);
984                                 Type param_type = pd.ParameterType (0);
985
986                                 if (param_type == source_type)
987                                         return param_type;
988
989                                 src_types_set.Add (param_type);
990                         }
991
992                         //
993                         // Explicit Conv rules
994                         //
995                         if (apply_explicit_conv_rules) {
996                                 ArrayList candidate_set = new ArrayList ();
997
998                                 foreach (Type param_type in src_types_set){
999                                         if (ImplicitStandardConversionExists (source, param_type))
1000                                                 candidate_set.Add (param_type);
1001                                 }
1002
1003                                 if (candidate_set.Count != 0)
1004                                         return FindMostEncompassedType (candidate_set);
1005                         }
1006
1007                         //
1008                         // Final case
1009                         //
1010                         if (apply_explicit_conv_rules)
1011                                 return FindMostEncompassingType (src_types_set);
1012                         else
1013                                 return FindMostEncompassedType (src_types_set);
1014                 }
1015
1016                 /// <summary>
1017                 ///  Finds the most specific target Tx according to section 13.4.4
1018                 /// </summary>
1019                 static public Type FindMostSpecificTarget (IList list,
1020                                                            Type target, bool apply_explicit_conv_rules)
1021                 {
1022                         ArrayList tgt_types_set = new ArrayList ();
1023
1024                         //
1025                         // If any operator converts to T then Tx = T
1026                         //
1027                         foreach (MethodInfo mi in list){
1028                                 Type ret_type = mi.ReturnType;
1029                                 if (ret_type == target)
1030                                         return ret_type;
1031
1032                                 tgt_types_set.Add (ret_type);
1033                         }
1034
1035                         //
1036                         // Explicit conv rules
1037                         //
1038                         if (apply_explicit_conv_rules) {
1039                                 ArrayList candidate_set = new ArrayList ();
1040
1041                                 EmptyExpression expr = EmptyExpression.Grab ();
1042
1043                                 foreach (Type ret_type in tgt_types_set){
1044                                         expr.SetType (ret_type);
1045
1046                                         if (ImplicitStandardConversionExists (expr, target))
1047                                                 candidate_set.Add (ret_type);
1048                                 }
1049
1050                                 EmptyExpression.Release (expr);
1051
1052                                 if (candidate_set.Count != 0)
1053                                         return FindMostEncompassingType (candidate_set);
1054                         }
1055
1056                         //
1057                         // Okay, final case !
1058                         //
1059                         if (apply_explicit_conv_rules)
1060                                 return FindMostEncompassedType (tgt_types_set);
1061                         else
1062                                 return FindMostEncompassingType (tgt_types_set);
1063                 }
1064
1065                 /// <summary>
1066                 ///  User-defined Implicit conversions
1067                 /// </summary>
1068                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
1069                                                                  Type target, Location loc)
1070                 {
1071                         return UserDefinedConversion (ec, source, target, loc, false);
1072                 }
1073
1074                 /// <summary>
1075                 ///  User-defined Explicit conversions
1076                 /// </summary>
1077                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
1078                                                                  Type target, Location loc)
1079                 {
1080                         return UserDefinedConversion (ec, source, target, loc, true);
1081                 }
1082
1083                 static void AddConversionOperators (ArrayList list,
1084                                                     Expression source, Type target_type,
1085                                                     bool look_for_explicit,
1086                                                     MethodGroupExpr mg)
1087                 {
1088                         if (mg == null)
1089                                 return;
1090
1091                         Type source_type = source.Type;
1092                         EmptyExpression expr = EmptyExpression.Grab ();
1093                         foreach (MethodInfo m in mg.Methods) {
1094                                 ParameterData pd = TypeManager.GetParameterData (m);
1095                                 Type return_type = m.ReturnType;
1096                                 Type arg_type = pd.ParameterType (0);
1097
1098                                 if (source_type != arg_type) {
1099                                         if (!ImplicitStandardConversionExists (source, arg_type)) {
1100                                                 if (!look_for_explicit)
1101                                                         continue;
1102                                                 expr.SetType (arg_type);
1103                                                 if (!ImplicitStandardConversionExists (expr, source_type))
1104                                                         continue;
1105                                         }
1106                                 }
1107
1108                                 if (target_type != return_type) {
1109                                         expr.SetType (return_type);
1110                                         if (!ImplicitStandardConversionExists (expr, target_type)) {
1111                                                 if (!look_for_explicit)
1112                                                         continue;
1113                                                 expr.SetType (target_type);
1114                                                 if (!ImplicitStandardConversionExists (expr, return_type))
1115                                                         continue;
1116                                         }
1117                                 }
1118
1119                                 list.Add (m);
1120                         }
1121
1122                         EmptyExpression.Release (expr);
1123                 }
1124
1125                 /// <summary>
1126                 ///   Compute the user-defined conversion operator from source_type to target_type.
1127                 ///   `look_for_explicit' controls whether we should also include the list of explicit operators
1128                 /// </summary>
1129                 static MethodInfo GetConversionOperator (EmitContext ec, Expression source, Type target_type, bool look_for_explicit)
1130                 {
1131                         ArrayList ops = new ArrayList (4);
1132
1133                         Type source_type = source.Type;
1134
1135                         if (source_type != TypeManager.decimal_type) {
1136                                 AddConversionOperators (ops, source, target_type, look_for_explicit,
1137                                         Expression.MethodLookup (ec, source_type, "op_Implicit", Location.Null) as MethodGroupExpr);
1138                                 if (look_for_explicit) {
1139                                         AddConversionOperators (ops, source, target_type, look_for_explicit,
1140                                                 Expression.MethodLookup (
1141                                                         ec, source_type, "op_Explicit", Location.Null) as MethodGroupExpr);
1142                                 }
1143                         }
1144
1145                         if (target_type != TypeManager.decimal_type) {
1146                                 AddConversionOperators (ops, source, target_type, look_for_explicit,
1147                                         Expression.MethodLookup (ec, target_type, "op_Implicit", Location.Null) as MethodGroupExpr);
1148                                 if (look_for_explicit) {
1149                                         AddConversionOperators (ops, source, target_type, look_for_explicit,
1150                                                 Expression.MethodLookup (
1151                                                         ec, target_type, "op_Explicit", Location.Null) as MethodGroupExpr);
1152                                 }
1153                         }
1154
1155                         if (ops.Count == 0)
1156                                 return null;
1157
1158                         Type most_specific_source = FindMostSpecificSource (ops, source, look_for_explicit);
1159                         if (most_specific_source == null)
1160                                 return null;
1161
1162                         Type most_specific_target = FindMostSpecificTarget (ops, target_type, look_for_explicit);
1163                         if (most_specific_target == null)
1164                                 return null;
1165
1166                         MethodInfo method = null;
1167
1168                         foreach (MethodInfo m in ops) {
1169                                 if (m.ReturnType != most_specific_target)
1170                                         continue;
1171                                 if (TypeManager.GetParameterData (m).ParameterType (0) != most_specific_source)
1172                                         continue;
1173                                 // Ambiguous: more than one conversion operator satisfies the signature.
1174                                 if (method != null)
1175                                         return null;
1176                                 method = m;
1177                         }
1178
1179                         return method;
1180                 }
1181
1182                 static DoubleHash explicit_conv = new DoubleHash (100);
1183                 static DoubleHash implicit_conv = new DoubleHash (100);
1184
1185                 /// <summary>
1186                 ///   User-defined conversions
1187                 /// </summary>
1188                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1189                                                                 Type target, Location loc,
1190                                                                 bool look_for_explicit)
1191                 {
1192                         Type source_type = source.Type;
1193                         MethodInfo method = null;
1194
1195                         object o;
1196                         DoubleHash hash = look_for_explicit ? explicit_conv : implicit_conv;
1197
1198                         if (!(source is Constant) && hash.Lookup (source_type, target, out o)) {
1199                                 method = (MethodInfo) o;
1200                         } else {
1201                                 method = GetConversionOperator (ec, source, target, look_for_explicit);
1202                                 if (!(source is Constant))
1203                                         hash.Insert (source_type, target, method);
1204                         }
1205
1206                         if (method == null)
1207                                 return null;
1208
1209                         Type most_specific_source = TypeManager.GetParameterData (method).ParameterType (0);
1210
1211                         //
1212                         // This will do the conversion to the best match that we
1213                         // found.  Now we need to perform an implict standard conversion
1214                         // if the best match was not the type that we were requested
1215                         // by target.
1216                         //
1217                         if (look_for_explicit)
1218                                 source = ExplicitConversionStandard (ec, source, most_specific_source, loc);
1219                         else
1220                                 source = ImplicitConversionStandard (ec, source, most_specific_source, loc);
1221
1222                         if (source == null)
1223                                 return null;
1224
1225                         Expression e;
1226                         e =  new UserCast (method, source, loc);
1227                         if (e.Type != target){
1228                                 if (!look_for_explicit)
1229                                         e = ImplicitConversionStandard (ec, e, target, loc);
1230                                 else
1231                                         e = ExplicitConversionStandard (ec, e, target, loc);
1232                         }
1233
1234                         return e;
1235                 }
1236
1237                 /// <summary>
1238                 ///   Converts implicitly the resolved expression `expr' into the
1239                 ///   `target_type'.  It returns a new expression that can be used
1240                 ///   in a context that expects a `target_type'.
1241                 /// </summary>
1242                 static public Expression ImplicitConversion (EmitContext ec, Expression expr,
1243                                                              Type target_type, Location loc)
1244                 {
1245                         Expression e;
1246
1247                         if (target_type == null)
1248                                 throw new Exception ("Target type is null");
1249
1250                         e = ImplicitConversionStandard (ec, expr, target_type, loc);
1251                         if (e != null)
1252                                 return e;
1253
1254                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1255                         if (e != null)
1256                                 return e;
1257
1258                         return null;
1259                 }
1260
1261
1262                 /// <summary>
1263                 ///   Attempts to apply the `Standard Implicit
1264                 ///   Conversion' rules to the expression `expr' into
1265                 ///   the `target_type'.  It returns a new expression
1266                 ///   that can be used in a context that expects a
1267                 ///   `target_type'.
1268                 ///
1269                 ///   This is different from `ImplicitConversion' in that the
1270                 ///   user defined implicit conversions are excluded.
1271                 /// </summary>
1272                 static public Expression ImplicitConversionStandard (EmitContext ec, Expression expr,
1273                                                                      Type target_type, Location loc)
1274                 {
1275                         Type expr_type = expr.Type;
1276                         Expression e;
1277 #if GMCS_SOURCE
1278                         // TODO: refactor to be a part of constant infrastructure
1279                         if (expr is NullLiteral) {
1280                             if (TypeManager.IsNullableType (target_type))
1281                                 return new Nullable.NullableLiteral (target_type, loc);
1282                         }
1283
1284                         if (TypeManager.IsNullableType (target_type)) {
1285                                 Type target = TypeManager.GetTypeArguments (target_type) [0];
1286
1287                                 if (TypeManager.IsNullableType (expr.Type)) {
1288                                         e = new Nullable.LiftedConversion (
1289                                                 expr, target_type, false, false, loc).Resolve (ec);
1290                                         if (e != null)
1291                                                 return e;
1292                                 } else {
1293                                         e = ImplicitConversion (ec, expr, target, loc);
1294                                         if (e != null)
1295                                                 return Nullable.Wrap.Create (e, ec);
1296                                 }
1297                         }
1298 #endif
1299                         if (expr.eclass == ExprClass.MethodGroup){
1300                                 if (!TypeManager.IsDelegateType (target_type)){
1301                                         return null;
1302                                 }
1303
1304                                 //
1305                                 // Only allow anonymous method conversions on post ISO_1
1306                                 //
1307                                 if (RootContext.Version != LanguageVersion.ISO_1){
1308                                         MethodGroupExpr mg = expr as MethodGroupExpr;
1309                                         if (mg != null)
1310                                                 return ImplicitDelegateCreation.Create (
1311                                                         ec, mg, target_type, loc);
1312                                 }
1313                         }
1314
1315                         if (expr_type.Equals (target_type) && !TypeManager.IsNullType (expr_type))
1316                                 return expr;
1317
1318                         e = ImplicitNumericConversion (expr, target_type);
1319                         if (e != null)
1320                                 return e;
1321
1322                         e = ImplicitReferenceConversion (expr, target_type);
1323                         if (e != null)
1324                                 return e;
1325
1326                         if (TypeManager.IsEnumType (target_type) && expr is IntLiteral){
1327                                 IntLiteral i = (IntLiteral) expr;
1328
1329                                 if (i.Value == 0)
1330                                         return new EnumConstant ((Constant) expr, target_type);
1331                         }
1332
1333                         if (ec.InUnsafe) {
1334                                 if (expr_type.IsPointer){
1335                                         if (target_type == TypeManager.void_ptr_type)
1336                                                 return new EmptyCast (expr, target_type);
1337
1338                                         //
1339                                         // yep, comparing pointer types cant be done with
1340                                         // t1 == t2, we have to compare their element types.
1341                                         //
1342                                         if (target_type.IsPointer){
1343                                                 if (TypeManager.GetElementType(target_type) == TypeManager.GetElementType(expr_type))
1344                                                         return expr;
1345
1346                                                 //return null;
1347                                         }
1348                                 }
1349
1350                                 if (expr_type == TypeManager.null_type && target_type.IsPointer)
1351                                         return new EmptyCast (NullPointer.Null, target_type);
1352                         }
1353
1354                         if (expr_type == TypeManager.anonymous_method_type){
1355                                 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
1356
1357                                 int errors = Report.Errors;
1358
1359                                 Expression conv = ame.Compatible (ec, target_type);
1360                                 if (conv != null)
1361                                         return conv;
1362                                 
1363                                 //
1364                                 // We return something instead of null, to avoid
1365                                 // the duplicate error, since am.Compatible would have
1366                                 // reported that already
1367                                 //
1368                                 if (errors != Report.Errors)
1369                                         return new EmptyCast (expr, target_type);
1370                         }
1371
1372                         return null;
1373                 }
1374
1375                 /// <summary>
1376                 ///   Attempts to perform an implicit constant conversion of the IntConstant
1377                 ///   into a different data type using casts (See Implicit Constant
1378                 ///   Expression Conversions)
1379                 /// </summary>
1380                 static public Expression TryImplicitIntConversion (Type target_type, IntConstant ic)
1381                 {
1382                         int value = ic.Value;
1383
1384                         if (target_type == TypeManager.sbyte_type){
1385                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1386                                         return new SByteConstant ((sbyte) value, ic.Location);
1387                         } else if (target_type == TypeManager.byte_type){
1388                                 if (value >= Byte.MinValue && value <= Byte.MaxValue)
1389                                         return new ByteConstant ((byte) value, ic.Location);
1390                         } else if (target_type == TypeManager.short_type){
1391                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1392                                         return new ShortConstant ((short) value, ic.Location);
1393                         } else if (target_type == TypeManager.ushort_type){
1394                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1395                                         return new UShortConstant ((ushort) value, ic.Location);
1396                         } else if (target_type == TypeManager.uint32_type){
1397                                 if (value >= 0)
1398                                         return new UIntConstant ((uint) value, ic.Location);
1399                         } else if (target_type == TypeManager.uint64_type){
1400                                 //
1401                                 // we can optimize this case: a positive int32
1402                                 // always fits on a uint64.  But we need an opcode
1403                                 // to do it.
1404                                 //
1405                                 if (value >= 0)
1406                                         return new ULongConstant ((ulong) value, ic.Location);
1407                         } else if (target_type == TypeManager.double_type)
1408                                 return new DoubleConstant ((double) value, ic.Location);
1409                         else if (target_type == TypeManager.float_type)
1410                                 return new FloatConstant ((float) value, ic.Location);
1411
1412                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
1413                                 Type underlying = TypeManager.EnumToUnderlying (target_type);
1414                                 Constant e = (Constant) ic;
1415
1416                                 //
1417                                 // Possibly, we need to create a different 0 literal before passing
1418                                 // to EnumConstant
1419                                 //
1420                                 if (underlying == TypeManager.int64_type)
1421                                         e = new LongLiteral (0, ic.Location);
1422                                 else if (underlying == TypeManager.uint64_type)
1423                                         e = new ULongLiteral (0, ic.Location);
1424
1425                                 return new EnumConstant (e, target_type);
1426                         }
1427
1428                         //
1429                         // If `target_type' is an interface and the type of `ic' implements the interface
1430                         // e.g. target_type is IComparable, IConvertible, IFormattable
1431                         //
1432                         if (target_type.IsInterface && target_type.IsAssignableFrom (ic.Type))
1433                                 return new BoxedCast (ic, target_type);
1434
1435                         return null;
1436                 }
1437
1438                 /// <summary>
1439                 ///   Attempts to implicitly convert `source' into `target_type', using
1440                 ///   ImplicitConversion.  If there is no implicit conversion, then
1441                 ///   an error is signaled
1442                 /// </summary>
1443                 static public Expression ImplicitConversionRequired (EmitContext ec, Expression source,
1444                                                                      Type target_type, Location loc)
1445                 {
1446                         Expression e = ImplicitConversion (ec, source, target_type, loc);
1447                         if (e != null)
1448                                 return e;
1449
1450                         source.Error_ValueCannotBeConverted (loc, target_type, false);
1451                         return null;
1452                 }
1453
1454                 /// <summary>
1455                 ///   Performs the explicit numeric conversions
1456                 ///
1457                 /// There are a few conversions that are not part of the C# standard,
1458                 /// they were interim hacks in the C# compiler that were supposed to
1459                 /// become explicit operators in the UIntPtr class and IntPtr class,
1460                 /// but for historical reasons it did not happen, so the C# compiler
1461                 /// ended up with these special hacks.
1462                 ///
1463                 /// See bug 59800 for details.
1464                 ///
1465                 /// The conversion are:
1466                 ///   UIntPtr->SByte
1467                 ///   UIntPtr->Int16
1468                 ///   UIntPtr->Int32
1469                 ///   IntPtr->UInt64
1470                 ///   UInt64->IntPtr
1471                 ///   SByte->UIntPtr
1472                 ///   Int16->UIntPtr
1473                 ///
1474                 /// </summary>
1475                 public static Expression ExplicitNumericConversion (Expression expr, Type target_type)
1476                 {
1477                         Type expr_type = expr.Type;
1478                         Type real_target_type = target_type;
1479
1480                         if (expr_type == TypeManager.sbyte_type){
1481                                 //
1482                                 // From sbyte to byte, ushort, uint, ulong, char, uintptr
1483                                 //
1484                                 if (real_target_type == TypeManager.byte_type)
1485                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
1486                                 if (real_target_type == TypeManager.ushort_type)
1487                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
1488                                 if (real_target_type == TypeManager.uint32_type)
1489                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
1490                                 if (real_target_type == TypeManager.uint64_type)
1491                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
1492                                 if (real_target_type == TypeManager.char_type)
1493                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
1494
1495                                 // One of the built-in conversions that belonged in the class library
1496                                 if (real_target_type == TypeManager.uintptr_type){
1497                                         Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I1_U8);
1498
1499                                         return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1500                                 }
1501                         } else if (expr_type == TypeManager.byte_type){
1502                                 //
1503                                 // From byte to sbyte and char
1504                                 //
1505                                 if (real_target_type == TypeManager.sbyte_type)
1506                                         return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
1507                                 if (real_target_type == TypeManager.char_type)
1508                                         return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
1509                         } else if (expr_type == TypeManager.short_type){
1510                                 //
1511                                 // From short to sbyte, byte, ushort, uint, ulong, char, uintptr
1512                                 //
1513                                 if (real_target_type == TypeManager.sbyte_type)
1514                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
1515                                 if (real_target_type == TypeManager.byte_type)
1516                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
1517                                 if (real_target_type == TypeManager.ushort_type)
1518                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
1519                                 if (real_target_type == TypeManager.uint32_type)
1520                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
1521                                 if (real_target_type == TypeManager.uint64_type)
1522                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
1523                                 if (real_target_type == TypeManager.char_type)
1524                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
1525
1526                                 // One of the built-in conversions that belonged in the class library
1527                                 if (real_target_type == TypeManager.uintptr_type){
1528                                         Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1529
1530                                         return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1531                                 }
1532                         } else if (expr_type == TypeManager.ushort_type){
1533                                 //
1534                                 // From ushort to sbyte, byte, short, char
1535                                 //
1536                                 if (real_target_type == TypeManager.sbyte_type)
1537                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
1538                                 if (real_target_type == TypeManager.byte_type)
1539                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
1540                                 if (real_target_type == TypeManager.short_type)
1541                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
1542                                 if (real_target_type == TypeManager.char_type)
1543                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
1544                         } else if (expr_type == TypeManager.int32_type){
1545                                 //
1546                                 // From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
1547                                 //
1548                                 if (real_target_type == TypeManager.sbyte_type)
1549                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
1550                                 if (real_target_type == TypeManager.byte_type)
1551                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
1552                                 if (real_target_type == TypeManager.short_type)
1553                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
1554                                 if (real_target_type == TypeManager.ushort_type)
1555                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
1556                                 if (real_target_type == TypeManager.uint32_type)
1557                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
1558                                 if (real_target_type == TypeManager.uint64_type)
1559                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
1560                                 if (real_target_type == TypeManager.char_type)
1561                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
1562
1563                                 // One of the built-in conversions that belonged in the class library
1564                                 if (real_target_type == TypeManager.uintptr_type){
1565                                         Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1566
1567                                         return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1568                                 }
1569                         } else if (expr_type == TypeManager.uint32_type){
1570                                 //
1571                                 // From uint to sbyte, byte, short, ushort, int, char
1572                                 //
1573                                 if (real_target_type == TypeManager.sbyte_type)
1574                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
1575                                 if (real_target_type == TypeManager.byte_type)
1576                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
1577                                 if (real_target_type == TypeManager.short_type)
1578                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
1579                                 if (real_target_type == TypeManager.ushort_type)
1580                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
1581                                 if (real_target_type == TypeManager.int32_type)
1582                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
1583                                 if (real_target_type == TypeManager.char_type)
1584                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
1585                         } else if (expr_type == TypeManager.int64_type){
1586                                 //
1587                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1588                                 //
1589                                 if (real_target_type == TypeManager.sbyte_type)
1590                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
1591                                 if (real_target_type == TypeManager.byte_type)
1592                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
1593                                 if (real_target_type == TypeManager.short_type)
1594                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
1595                                 if (real_target_type == TypeManager.ushort_type)
1596                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
1597                                 if (real_target_type == TypeManager.int32_type)
1598                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
1599                                 if (real_target_type == TypeManager.uint32_type)
1600                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
1601                                 if (real_target_type == TypeManager.uint64_type)
1602                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
1603                                 if (real_target_type == TypeManager.char_type)
1604                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
1605                         } else if (expr_type == TypeManager.uint64_type){
1606                                 //
1607                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1608                                 //
1609                                 if (real_target_type == TypeManager.sbyte_type)
1610                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
1611                                 if (real_target_type == TypeManager.byte_type)
1612                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
1613                                 if (real_target_type == TypeManager.short_type)
1614                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
1615                                 if (real_target_type == TypeManager.ushort_type)
1616                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
1617                                 if (real_target_type == TypeManager.int32_type)
1618                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
1619                                 if (real_target_type == TypeManager.uint32_type)
1620                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
1621                                 if (real_target_type == TypeManager.int64_type)
1622                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
1623                                 if (real_target_type == TypeManager.char_type)
1624                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
1625
1626                                 // One of the built-in conversions that belonged in the class library
1627                                 if (real_target_type == TypeManager.intptr_type){
1628                                         return new OperatorCast (new EmptyCast (expr, TypeManager.int64_type),
1629                                                                  TypeManager.intptr_type, true);
1630                                 }
1631                         } else if (expr_type == TypeManager.char_type){
1632                                 //
1633                                 // From char to sbyte, byte, short
1634                                 //
1635                                 if (real_target_type == TypeManager.sbyte_type)
1636                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
1637                                 if (real_target_type == TypeManager.byte_type)
1638                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
1639                                 if (real_target_type == TypeManager.short_type)
1640                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
1641                         } else if (expr_type == TypeManager.float_type){
1642                                 //
1643                                 // From float to sbyte, byte, short,
1644                                 // ushort, int, uint, long, ulong, char
1645                                 // or decimal
1646                                 //
1647                                 if (real_target_type == TypeManager.sbyte_type)
1648                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
1649                                 if (real_target_type == TypeManager.byte_type)
1650                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
1651                                 if (real_target_type == TypeManager.short_type)
1652                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
1653                                 if (real_target_type == TypeManager.ushort_type)
1654                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
1655                                 if (real_target_type == TypeManager.int32_type)
1656                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
1657                                 if (real_target_type == TypeManager.uint32_type)
1658                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
1659                                 if (real_target_type == TypeManager.int64_type)
1660                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
1661                                 if (real_target_type == TypeManager.uint64_type)
1662                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
1663                                 if (real_target_type == TypeManager.char_type)
1664                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
1665                                 if (real_target_type == TypeManager.decimal_type)
1666                                         return new CastToDecimal (expr, true);
1667                         } else if (expr_type == TypeManager.double_type){
1668                                 //
1669                                 // From double to sbyte, byte, short,
1670                                 // ushort, int, uint, long, ulong,
1671                                 // char, float or decimal
1672                                 //
1673                                 if (real_target_type == TypeManager.sbyte_type)
1674                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
1675                                 if (real_target_type == TypeManager.byte_type)
1676                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
1677                                 if (real_target_type == TypeManager.short_type)
1678                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
1679                                 if (real_target_type == TypeManager.ushort_type)
1680                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
1681                                 if (real_target_type == TypeManager.int32_type)
1682                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
1683                                 if (real_target_type == TypeManager.uint32_type)
1684                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
1685                                 if (real_target_type == TypeManager.int64_type)
1686                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
1687                                 if (real_target_type == TypeManager.uint64_type)
1688                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
1689                                 if (real_target_type == TypeManager.char_type)
1690                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
1691                                 if (real_target_type == TypeManager.float_type)
1692                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
1693                                 if (real_target_type == TypeManager.decimal_type)
1694                                         return new CastToDecimal (expr, true);
1695                         } else if (expr_type == TypeManager.uintptr_type){
1696                                 //
1697                                 // Various built-in conversions that belonged in the class library
1698                                 //
1699                                 // from uintptr to sbyte, short, int32
1700                                 //
1701                                 if (real_target_type == TypeManager.sbyte_type){
1702                                         Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1703                                         return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I1);
1704                                 }
1705                                 if (real_target_type == TypeManager.short_type){
1706                                         Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1707                                         return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I2);
1708                                 }
1709                                 if (real_target_type == TypeManager.int32_type)
1710                                         return new EmptyCast (new OperatorCast (expr, TypeManager.uint64_type, true),
1711                                                               TypeManager.int32_type);
1712                         } else if (expr_type == TypeManager.intptr_type){
1713                                 if (real_target_type == TypeManager.uint64_type){
1714                                         return new EmptyCast (new OperatorCast (expr, TypeManager.int64_type, true),
1715                                                               TypeManager.uint64_type);
1716                                 }
1717                         } else if (expr_type == TypeManager.decimal_type) {
1718                                 return new CastFromDecimal (expr, target_type).Resolve ();
1719                         }
1720                         return null;
1721                 }
1722
1723                 /// <summary>
1724                 ///  Returns whether an explicit reference conversion can be performed
1725                 ///  from source_type to target_type
1726                 /// </summary>
1727                 public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1728                 {
1729                         bool target_is_type_param = TypeManager.IsGenericParameter (target_type);
1730                         bool target_is_value_type = target_type.IsValueType;
1731
1732                         if (source_type == target_type)
1733                                 return true;
1734
1735                         //
1736                         // From generic parameter to any type
1737                         //
1738                         if (TypeManager.IsGenericParameter (source_type))
1739                                 return ExplicitTypeParameterConversionExists (source_type, target_type);
1740
1741                         //
1742                         // From object to a generic parameter
1743                         //
1744                         if (source_type == TypeManager.object_type && target_is_type_param)
1745                                 return true;
1746
1747                         //
1748                         // From object to any reference type
1749                         //
1750                         if (source_type == TypeManager.object_type && !target_is_value_type)
1751                                 return true;
1752
1753                         //
1754                         // From any class S to any class-type T, provided S is a base class of T
1755                         //
1756                         if (TypeManager.IsSubclassOf (target_type, source_type))
1757                                 return true;
1758
1759                         //
1760                         // From any interface type S to any interface T provided S is not derived from T
1761                         //
1762                         if (source_type.IsInterface && target_type.IsInterface){
1763                                 if (!TypeManager.IsSubclassOf (target_type, source_type))
1764                                         return true;
1765                         }
1766
1767                         //
1768                         // From any class type S to any interface T, provided S is not sealed
1769                         // and provided S does not implement T.
1770                         //
1771                         if (target_type.IsInterface && !source_type.IsSealed &&
1772                             !TypeManager.ImplementsInterface (source_type, target_type))
1773                                 return true;
1774
1775                         //
1776                         // From any interface-type S to to any class type T, provided T is not
1777                         // sealed, or provided T implements S.
1778                         //
1779                         if (source_type.IsInterface &&
1780                             (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
1781                                 return true;
1782
1783
1784                         // From an array type S with an element type Se to an array type T with an
1785                         // element type Te provided all the following are true:
1786                         //     * S and T differe only in element type, in other words, S and T
1787                         //       have the same number of dimensions.
1788                         //     * Both Se and Te are reference types
1789                         //     * An explicit referenc conversions exist from Se to Te
1790                         //
1791                         if (source_type.IsArray && target_type.IsArray) {
1792                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1793
1794                                         Type source_element_type = TypeManager.GetElementType (source_type);
1795                                         Type target_element_type = TypeManager.GetElementType (target_type);
1796
1797                                         if (TypeManager.IsGenericParameter (source_element_type) ||
1798                                             (!source_element_type.IsValueType && !target_element_type.IsValueType))
1799                                                 if (ExplicitReferenceConversionExists (source_element_type,
1800                                                                                        target_element_type))
1801                                                         return true;
1802                                 }
1803                         }
1804
1805
1806                         // From System.Array to any array-type
1807                         if (source_type == TypeManager.array_type &&
1808                             target_type.IsArray){
1809                                 return true;
1810                         }
1811
1812                         //
1813                         // From System delegate to any delegate-type
1814                         //
1815                         if (source_type == TypeManager.delegate_type &&
1816                             TypeManager.IsDelegateType (target_type))
1817                                 return true;
1818
1819                         //
1820                         // From ICloneable to Array or Delegate types
1821                         //
1822                         if (source_type == TypeManager.icloneable_type &&
1823                             (target_type == TypeManager.array_type ||
1824                              target_type == TypeManager.delegate_type))
1825                                 return true;
1826
1827                         return false;
1828                 }
1829
1830                 /// <summary>
1831                 ///   Implements Explicit Reference conversions
1832                 /// </summary>
1833                 static Expression ExplicitReferenceConversion (Expression source, Type target_type)
1834                 {
1835                         Type source_type = source.Type;
1836                         bool target_is_type_param = TypeManager.IsGenericParameter (target_type);
1837                         bool target_is_value_type = target_type.IsValueType;
1838
1839                         //
1840                         // From object to a generic parameter
1841                         //
1842                         if (source_type == TypeManager.object_type && target_is_type_param)
1843                                 return new UnboxCast (source, target_type);
1844
1845                         //
1846                         // Explicit type parameter conversion.
1847                         //
1848
1849                         if (TypeManager.IsGenericParameter (source_type))
1850                                 return ExplicitTypeParameterConversion (source, target_type);
1851
1852                         //
1853                         // From object to any reference type
1854                         //
1855                         if (source_type == TypeManager.object_type && !target_is_value_type)
1856                                 return new ClassCast (source, target_type);
1857
1858                         //
1859                         // Unboxing conversion.
1860                         //
1861                         if (((source_type == TypeManager.enum_type &&
1862                                 !(source is EmptyCast)) ||
1863                                 source_type == TypeManager.value_type) && target_is_value_type)
1864                                 return new UnboxCast (source, target_type);
1865
1866                         //
1867                         // From any class S to any class-type T, provided S is a base class of T
1868                         //
1869                         if (TypeManager.IsSubclassOf (target_type, source_type))
1870                                 return new ClassCast (source, target_type);
1871
1872                         //
1873                         // From any interface type S to any interface T provided S is not derived from T
1874                         //
1875                         if (source_type.IsInterface && target_type.IsInterface){
1876                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1877                                         return null;
1878                                 else
1879                                         return new ClassCast (source, target_type);
1880                         }
1881
1882                         //
1883                         // From any class type S to any interface T, provides S is not sealed
1884                         // and provided S does not implement T.
1885                         //
1886                         if (target_type.IsInterface && !source_type.IsSealed) {
1887                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1888                                         return null;
1889                                 else
1890                                         return new ClassCast (source, target_type);
1891
1892                         }
1893
1894                         //
1895                         // From any interface-type S to to any class type T, provided T is not
1896                         // sealed, or provided T implements S.
1897                         //
1898                         if (source_type.IsInterface) {
1899                                 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)) {
1900                                         if (target_type.IsClass)
1901                                                 return new ClassCast (source, target_type);
1902                                         else
1903                                                 return new UnboxCast (source, target_type);
1904                                 }
1905
1906                                 return null;
1907                         }
1908
1909                         // From an array type S with an element type Se to an array type T with an
1910                         // element type Te provided all the following are true:
1911                         //     * S and T differe only in element type, in other words, S and T
1912                         //       have the same number of dimensions.
1913                         //     * Both Se and Te are reference types
1914                         //     * An explicit referenc conversions exist from Se to Te
1915                         //
1916                         if (source_type.IsArray && target_type.IsArray) {
1917                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1918
1919                                         Type source_element_type = TypeManager.GetElementType (source_type);
1920                                         Type target_element_type = TypeManager.GetElementType (target_type);
1921
1922                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1923                                                 if (ExplicitReferenceConversionExists (source_element_type,
1924                                                                                        target_element_type))
1925                                                         return new ClassCast (source, target_type);
1926                                 }
1927                         }
1928
1929
1930                         // From System.Array to any array-type
1931                         if (source_type == TypeManager.array_type &&
1932                             target_type.IsArray) {
1933                                 return new ClassCast (source, target_type);
1934                         }
1935
1936                         //
1937                         // From System delegate to any delegate-type
1938                         //
1939                         if (source_type == TypeManager.delegate_type &&
1940                             TypeManager.IsDelegateType (target_type))
1941                                 return new ClassCast (source, target_type);
1942
1943                         //
1944                         // From ICloneable to Array or Delegate types
1945                         //
1946                         if (source_type == TypeManager.icloneable_type &&
1947                             (target_type == TypeManager.array_type ||
1948                              target_type == TypeManager.delegate_type))
1949                                 return new ClassCast (source, target_type);
1950
1951                         return null;
1952                 }
1953
1954                 /// <summary>
1955                 ///   Performs an explicit conversion of the expression `expr' whose
1956                 ///   type is expr.Type to `target_type'.
1957                 /// </summary>
1958                 static public Expression ExplicitConversionCore (EmitContext ec, Expression expr,
1959                                                                  Type target_type, Location loc)
1960                 {
1961                         Type expr_type = expr.Type;
1962
1963                         // Explicit conversion includes implicit conversion and it used for enum underlying types too
1964                         Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc);
1965                         if (ne != null)
1966                                 return ne;
1967
1968                         //
1969                         // Unboxing conversions; only object types can be convertible to enum
1970                         //
1971                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
1972                                 return new UnboxCast (expr, target_type);
1973
1974                         if (TypeManager.IsEnumType (expr_type)) {
1975                                 if (expr is EnumConstant)
1976                                         return ExplicitConversionCore (ec, ((EnumConstant) expr).Child, target_type, loc);
1977
1978                                 return ExplicitConversionCore (ec, new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type)), target_type, loc);
1979                         }
1980
1981                         if (TypeManager.IsEnumType (target_type)){
1982                                 if (expr_type == TypeManager.enum_type)
1983                                         return new UnboxCast (expr, target_type);
1984
1985                                 Expression ce = ExplicitConversionCore (ec, expr, TypeManager.EnumToUnderlying (target_type), loc);
1986                                 if (ce != null)
1987                                         return new EmptyCast (ce, target_type);
1988                         }
1989
1990                         ne = ExplicitNumericConversion (expr, target_type);
1991                         if (ne != null)
1992                                 return ne;
1993
1994                         //
1995                         // Skip the ExplicitReferenceConversion because we can not convert
1996                         // from Null to a ValueType, and ExplicitReference wont check against
1997                         // null literal explicitly
1998                         //
1999                         if (expr_type != TypeManager.null_type){
2000                                 ne = ExplicitReferenceConversion (expr, target_type);
2001                                 if (ne != null)
2002                                         return ne;
2003                         }
2004
2005                         if (ec.InUnsafe){
2006                                 ne = ExplicitUnsafe (expr, target_type);
2007                                 if (ne != null)
2008                                         return ne;
2009                         }
2010
2011                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
2012                         if (ne != null)
2013                                 return ne;
2014
2015                         return null;
2016                 }
2017
2018                 public static Expression ExplicitUnsafe (Expression expr, Type target_type)
2019                 {
2020                         Type expr_type = expr.Type;
2021
2022                         if (target_type.IsPointer){
2023                                 if (expr_type.IsPointer)
2024                                         return new EmptyCast (expr, target_type);
2025
2026                                 if (expr_type == TypeManager.sbyte_type ||
2027                                         expr_type == TypeManager.short_type ||
2028                                         expr_type == TypeManager.int32_type ||
2029                                         expr_type == TypeManager.int64_type)
2030                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
2031
2032                                 if (expr_type == TypeManager.ushort_type ||
2033                                         expr_type == TypeManager.uint32_type ||
2034                                         expr_type == TypeManager.uint64_type ||
2035                                         expr_type == TypeManager.byte_type)
2036                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2037                         }
2038
2039                         if (expr_type.IsPointer){
2040                                 if (target_type == TypeManager.sbyte_type)
2041                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
2042                                 else if (target_type == TypeManager.byte_type)
2043                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
2044                                 else if (target_type == TypeManager.short_type)
2045                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
2046                                 else if (target_type == TypeManager.ushort_type)
2047                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
2048                                 else if (target_type == TypeManager.int32_type)
2049                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
2050                                 else if (target_type == TypeManager.uint32_type)
2051                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
2052                                 else if (target_type == TypeManager.uint64_type)
2053                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
2054                                 else if (target_type == TypeManager.int64_type){
2055                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
2056                                 }
2057                         }
2058                         return null;
2059                 }
2060
2061                 /// <summary>
2062                 ///   Same as ExplicitConversion, only it doesn't include user defined conversions
2063                 /// </summary>
2064                 static public Expression ExplicitConversionStandard (EmitContext ec, Expression expr,
2065                                                                      Type target_type, Location l)
2066                 {
2067                         int errors = Report.Errors;
2068                         Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
2069                         if (Report.Errors > errors)
2070                                 return null;
2071
2072                         if (ne != null)
2073                                 return ne;
2074
2075                         ne = ExplicitNumericConversion (expr, target_type);
2076                         if (ne != null)
2077                                 return ne;
2078
2079                         ne = ExplicitReferenceConversion (expr, target_type);
2080                         if (ne != null)
2081                                 return ne;
2082
2083                         if (ec.InUnsafe && expr.Type == TypeManager.void_ptr_type && target_type.IsPointer)
2084                                 return new EmptyCast (expr, target_type);
2085
2086                         expr.Error_ValueCannotBeConverted (l, target_type, true);
2087                         return null;
2088                 }
2089
2090                 /// <summary>
2091                 ///   Performs an explicit conversion of the expression `expr' whose
2092                 ///   type is expr.Type to `target_type'.
2093                 /// </summary>
2094                 static public Expression ExplicitConversion (EmitContext ec, Expression expr,
2095                         Type target_type, Location loc)
2096                 {
2097                         Expression e;
2098 #if GMCS_SOURCE
2099                         Type expr_type = expr.Type;
2100                         if (TypeManager.IsNullableType (target_type)) {
2101                                 if (TypeManager.IsNullableType (expr_type)) {
2102                                         e = new Nullable.LiftedConversion (
2103                                                 expr, target_type, false, true, loc).Resolve (ec);
2104                                         if (e != null)
2105                                                 return e;
2106                                 } else if (expr_type == TypeManager.object_type) {
2107                                         return new UnboxCast (expr, target_type);
2108                                 } else {
2109                                         Type target = TypeManager.GetTypeArguments (target_type) [0];
2110
2111                                         e = ExplicitConversionCore (ec, expr, target, loc);
2112                                         if (e != null)
2113                                                 return Nullable.Wrap.Create (e, ec);
2114                                 }
2115                         } else if (TypeManager.IsNullableType (expr_type)) {
2116                                 Expression source = Nullable.Unwrap.Create (expr, ec);
2117                                 if (source != null) {
2118                                         e = ExplicitConversionCore (ec, source, target_type, loc);
2119                                         if (e != null)
2120                                                 return e;
2121                                 }
2122                         }
2123 #endif
2124                         e = ExplicitConversionCore (ec, expr, target_type, loc);
2125                         if (e != null)
2126                                 return e;
2127
2128                         expr.Error_ValueCannotBeConverted (loc, target_type, true);
2129                         return null;
2130                 }
2131         }
2132 }