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