Merge pull request #3137 from BrzVlad/fix-sgen-critical-region
[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 // Copyright 2001, 2002, 2003 Ximian, Inc.
10 // Copyright 2003-2008 Novell, Inc.
11 // Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 //
13
14 using System;
15 using System.Collections.Generic;
16
17 #if STATIC
18 using IKVM.Reflection.Emit;
19 #else
20 using System.Reflection.Emit;
21 #endif
22
23 namespace Mono.CSharp {
24
25         //
26         // A container class for all the conversion operations
27         //
28         static class Convert
29         {
30                 [Flags]
31                 public enum UserConversionRestriction
32                 {
33                         None = 0,
34                         ImplicitOnly = 1,
35                         ProbingOnly = 1 << 1,
36                         NullableSourceOnly = 1 << 2
37
38                 }
39                 //
40                 // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
41                 // interfaces of this interface, provided there is an implicit reference conversion
42                 // from S to T.
43                 //
44                 static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
45                 {
46                         if (array.Rank != 1 || !list.IsArrayGenericInterface)
47                                 return false;
48
49                         var arg_type = list.TypeArguments[0];
50                         if (array.Element == arg_type)
51                                 return true;
52
53                         //
54                         // Reject conversion from T[] to IList<U> even if T has U dependency
55                         //
56                         if (arg_type.IsGenericParameter)
57                                 return false;
58
59                         if (isExplicit)
60                                 return ExplicitReferenceConversionExists (array.Element, arg_type);
61
62                         return ImplicitReferenceConversionExists (array.Element, arg_type);
63                 }
64                 
65                 static bool IList_To_Array(TypeSpec list, ArrayContainer array)
66                 {
67                         if (array.Rank != 1 || !list.IsArrayGenericInterface)
68                                 return false;
69
70                         var arg_type = list.TypeArguments[0];
71                         if (array.Element == arg_type)
72                                 return true;
73                         
74                         return ImplicitReferenceConversionExists (array.Element, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
75                 }
76
77                 public static Expression ImplicitTypeParameterConversion (Expression expr, TypeParameterSpec expr_type, TypeSpec target_type)
78                 {
79                         //
80                         // From T to a type parameter U, provided T depends on U
81                         //
82                         if (target_type.IsGenericParameter) {
83                                 if (expr_type.TypeArguments != null && expr_type.HasDependencyOn (target_type)) {
84                                         if (expr == null)
85                                                 return EmptyExpression.Null;
86
87                                         if (expr_type.IsReferenceType && !((TypeParameterSpec) target_type).IsReferenceType)
88                                                 return new BoxedCast (expr, target_type);
89
90                                         return new ClassCast (expr, target_type);
91                                 }
92
93                                 return null;
94                         }
95
96                         //
97                         // LAMESPEC: From T to dynamic type because it's like T to object
98                         //
99                         if (target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
100                                 if (expr == null)
101                                         return EmptyExpression.Null;
102
103                                 if (expr_type.IsReferenceType)
104                                         return new ClassCast (expr, target_type);
105
106                                 return new BoxedCast (expr, target_type);
107                         }
108
109                         //
110                         // From T to its effective base class C
111                         // From T to any base class of C (it cannot contain dynamic or be of dynamic type)
112                         // From T to any interface implemented by C
113                         //
114                         var base_type = expr_type.GetEffectiveBase ();
115                         if (base_type == target_type || TypeSpec.IsBaseClass (base_type, target_type, false) || base_type.ImplementsInterface (target_type, true)) {
116                                 if (expr == null)
117                                         return EmptyExpression.Null;
118
119                                 if (expr_type.IsReferenceType)
120                                         return new ClassCast (expr, target_type);
121
122                                 return new BoxedCast (expr, target_type);
123                         }
124
125                         if (target_type.IsInterface && expr_type.IsConvertibleToInterface (target_type)) {
126                                 if (expr == null)
127                                         return EmptyExpression.Null;
128
129                                 if (expr_type.IsReferenceType)
130                                         return new ClassCast (expr, target_type);
131
132                                 return new BoxedCast (expr, target_type);
133                         }
134
135                         return null;
136                 }
137
138                 static Expression ExplicitTypeParameterConversionFromT (Expression source, TypeSpec source_type, TypeSpec target_type)
139                 {
140                         var target_tp = target_type as TypeParameterSpec;
141                         if (target_tp != null) {
142                                 //
143                                 // From a type parameter U to T, provided T depends on U
144                                 //
145                                 if (target_tp.TypeArguments != null && target_tp.HasDependencyOn (source_type)) {
146                                         return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
147                                 }
148                         }
149
150                         //
151                         // From T to any interface-type I provided there is not already an implicit conversion from T to I
152                         //
153                         if (target_type.IsInterface)
154                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
155
156                         return null;
157                 }
158
159                 static Expression ExplicitTypeParameterConversionToT (Expression source, TypeSpec source_type, TypeParameterSpec target_type)
160                 {
161                         //
162                         // From the effective base class C of T to T and from any base class of C to T
163                         //
164                         var effective = target_type.GetEffectiveBase ();
165                         if (TypeSpecComparer.IsEqual (effective, source_type) || TypeSpec.IsBaseClass (effective, source_type, false))
166                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
167
168                         return null;
169                 }
170
171                 public static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
172                 {
173                         TypeSpec expr_type = expr.Type;
174
175                         if (expr_type.Kind == MemberKind.TypeParameter)
176                                 return ImplicitTypeParameterConversion (expr, (TypeParameterSpec) expr.Type, target_type);
177
178                         //
179                         // from the null type to any reference-type.
180                         //
181                         NullLiteral nl = expr as NullLiteral;
182                         if (nl != null) {
183                                 return nl.ConvertImplicitly (target_type);
184                         }
185
186                         if (ImplicitReferenceConversionExists (expr_type, target_type)) {
187                                 // 
188                                 // Avoid wrapping implicitly convertible reference type
189                                 //
190                                 if (!explicit_cast)
191                                         return expr;
192
193                                 return EmptyCast.Create (expr, target_type);
194                         }
195
196                         return null;
197                 }
198
199                 //
200                 // Implicit reference conversions
201                 //
202                 public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type)
203                 {
204                         return ImplicitReferenceConversionExists (expr_type, target_type, true);
205                 }
206
207                 public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type, bool refOnlyTypeParameter)
208                 {
209                         // It's here only to speed things up
210                         if (target_type.IsStruct)
211                                 return false;
212
213                         switch (expr_type.Kind) {
214                         case MemberKind.TypeParameter:
215                                 return ImplicitTypeParameterConversion (null, (TypeParameterSpec) expr_type, target_type) != null &&
216                                         (!refOnlyTypeParameter || TypeSpec.IsReferenceType (expr_type));
217
218                         case MemberKind.Class:
219                                 //
220                                 // From any class-type to dynamic (+object to speed up common path)
221                                 //
222                                 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
223                                         return true;
224
225                                 if (target_type.IsClass) {
226                                         //
227                                         // Identity conversion, including dynamic erasure
228                                         //
229                                         if (TypeSpecComparer.IsEqual (expr_type, target_type))
230                                                 return true;
231
232                                         //
233                                         // From any class-type S to any class-type T, provided S is derived from T
234                                         //
235                                         return TypeSpec.IsBaseClass (expr_type, target_type, true);
236                                 }
237
238                                 //
239                                 // From any class-type S to any interface-type T, provided S implements T
240                                 //
241                                 if (target_type.IsInterface)
242                                         return expr_type.ImplementsInterface (target_type, true);
243
244                                 return false;
245
246                         case MemberKind.ArrayType:
247                                 //
248                                 // Identity array conversion
249                                 //
250                                 if (expr_type == target_type)
251                                         return true;
252
253                                 //
254                                 // From any array-type to System.Array
255                                 //
256                                 switch (target_type.BuiltinType) {
257                                 case BuiltinTypeSpec.Type.Array:
258                                 case BuiltinTypeSpec.Type.Object:
259                                 case BuiltinTypeSpec.Type.Dynamic:
260                                         return true;
261                                 }
262
263                                 var expr_type_array = (ArrayContainer) expr_type;
264                                 var target_type_array = target_type as ArrayContainer;
265
266                                 //
267                                 // From an array-type S to an array-type of type T
268                                 //
269                                 if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {
270
271                                         //
272                                         // Both SE and TE are reference-types. TE check is defered
273                                         // to ImplicitReferenceConversionExists
274                                         //
275                                         TypeSpec expr_element_type = expr_type_array.Element;
276                                         if (!TypeSpec.IsReferenceType (expr_element_type))
277                                                 return false;
278
279                                         //
280                                         // An implicit reference conversion exists from SE to TE
281                                         //
282                                         return ImplicitReferenceConversionExists (expr_element_type, target_type_array.Element);
283                                 }
284
285                                 //
286                                 // From any array-type to the interfaces it implements
287                                 //
288                                 if (target_type.IsInterface) {
289                                         if (expr_type.ImplementsInterface (target_type, false))
290                                                 return true;
291
292                                         // from an array-type of type T to IList<T>
293                                         if (ArrayToIList (expr_type_array, target_type, false))
294                                                 return true;
295                                 }
296
297                                 return false;
298
299                         case MemberKind.Delegate:
300                                 //
301                                 // From any delegate-type to System.Delegate (and its base types)
302                                 //
303                                 switch (target_type.BuiltinType) {
304                                 case BuiltinTypeSpec.Type.Delegate:
305                                 case BuiltinTypeSpec.Type.MulticastDelegate:
306                                 case BuiltinTypeSpec.Type.Object:
307                                 case BuiltinTypeSpec.Type.Dynamic:
308                                         return true;
309                                 }
310
311                                 //
312                                 // Identity conversion, including dynamic erasure
313                                 //
314                                 if (TypeSpecComparer.IsEqual (expr_type, target_type))
315                                         return true;
316
317                                 //
318                                 // From any delegate-type to the interfaces it implements
319                                 // From any reference-type to an delegate type if is variance-convertible
320                                 //
321                                 return expr_type.ImplementsInterface (target_type, false) || TypeSpecComparer.Variant.IsEqual (expr_type, target_type);
322
323                         case MemberKind.Interface:
324                                 //
325                                 // Identity conversion, including dynamic erasure
326                                 //
327                                 if (TypeSpecComparer.IsEqual (expr_type, target_type))
328                                         return true;
329
330                                 //
331                                 // From any interface type S to interface-type T
332                                 // From any reference-type to an interface if is variance-convertible
333                                 //
334                                 if (target_type.IsInterface)
335                                         return TypeSpecComparer.Variant.IsEqual (expr_type, target_type) || expr_type.ImplementsInterface (target_type, true);
336
337                                 return target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
338
339                         case MemberKind.InternalCompilerType:
340                                 //
341                                 // from the null literal to any reference-type.
342                                 //
343                                 if (expr_type == InternalType.NullLiteral) {
344                                         // Exlude internal compiler types
345                                         if (target_type.Kind == MemberKind.InternalCompilerType)
346                                                 return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
347
348                                         return TypeSpec.IsReferenceType (target_type) || target_type.Kind == MemberKind.PointerType;
349                                 }
350
351                                 //
352                                 // Implicit dynamic conversion
353                                 //
354                                 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
355                                         switch (target_type.Kind) {
356                                         case MemberKind.ArrayType:
357                                         case MemberKind.Class:
358                                         case MemberKind.Delegate:
359                                         case MemberKind.Interface:
360                                         case MemberKind.TypeParameter:
361                                                 return true;
362                                         }
363
364                                         // dynamic to __arglist
365                                         if (target_type == InternalType.Arglist)
366                                                 return true;
367
368                                         return false;
369                                 }
370
371                                 break;
372                         }
373
374                         return false;
375                 }
376
377                 public static Expression ImplicitBoxingConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
378                 {
379                         switch (target_type.BuiltinType) {
380                         //
381                         // From any non-nullable-value-type to the type object and dynamic
382                         //
383                         case BuiltinTypeSpec.Type.Object:
384                         case BuiltinTypeSpec.Type.Dynamic:
385                         //
386                         // From any non-nullable-value-type to the type System.ValueType
387                         //
388                         case BuiltinTypeSpec.Type.ValueType:
389                                 //
390                                 // No ned to check for nullable type as underlying type is always convertible
391                                 //
392                                 if (!TypeSpec.IsValueType (expr_type))
393                                         return null;
394
395                                 return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
396
397                         case BuiltinTypeSpec.Type.Enum:
398                                 //
399                                 // From any enum-type to the type System.Enum.
400                                 //
401                                 if (expr_type.IsEnum)
402                                         return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
403
404                                 break;
405                         }
406
407                         //
408                         // From a nullable-type to a reference type, if a boxing conversion exists from
409                         // the underlying type to the reference type
410                         //
411                         if (expr_type.IsNullableType) {
412                                 if (!TypeSpec.IsReferenceType (target_type))
413                                         return null;
414
415                                 var res = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
416
417                                 // "cast" underlying type to target type to emit correct InvalidCastException when
418                                 // underlying hierarchy changes without recompilation
419                                 if (res != null && expr != null)
420                                         res = new UnboxCast (res, target_type);
421
422                                 return res;
423                         }
424
425                         //
426                         // A value type has a boxing conversion to an interface type I if it has a boxing conversion
427                         // to an interface or delegate type I0 and I0 is variance-convertible to I
428                         //
429                         if (target_type.IsInterface && TypeSpec.IsValueType (expr_type) && expr_type.ImplementsInterface (target_type, true)) {
430                                 return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
431                         }
432
433                         return null;
434                 }
435
436                 public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
437                 {
438                         TypeSpec expr_type = expr.Type;
439
440                         //
441                         // From null to any nullable type
442                         //
443                         if (expr_type == InternalType.NullLiteral)
444                                 return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
445
446                         // S -> T?
447                         TypeSpec t_el = Nullable.NullableInfo.GetUnderlyingType (target_type);
448
449                         // S? -> T?
450                         if (expr_type.IsNullableType)
451                                 expr_type = Nullable.NullableInfo.GetUnderlyingType (expr_type);
452
453                         //
454                         // Predefined implicit identity or implicit numeric conversion
455                         // has to exist between underlying type S and underlying type T
456                         //
457
458                         // conversion exists only mode
459                         if (ec == null) {
460                                 if (TypeSpecComparer.IsEqual (expr_type, t_el))
461                                         return EmptyExpression.Null;
462
463                                 if (expr is Constant)
464                                         return ((Constant) expr).ConvertImplicitly (t_el);
465
466                                 return ImplicitNumericConversion (null, expr_type, t_el);
467                         }
468
469                         Expression unwrap;
470                         if (expr_type != expr.Type)
471                                 unwrap = Nullable.Unwrap.Create (expr);
472                         else
473                                 unwrap = expr;
474
475                         Expression conv = unwrap;
476                         if (!TypeSpecComparer.IsEqual (expr_type, t_el)) {
477                                 if (conv is Constant)
478                                         conv = ((Constant)conv).ConvertImplicitly (t_el);
479                                 else
480                                         conv = ImplicitNumericConversion (conv, expr_type, t_el);
481
482                                 if (conv == null)
483                                         return null;
484                         }
485                         
486                         if (expr_type != expr.Type)
487                                 return new Nullable.LiftedConversion (conv, unwrap, target_type).Resolve (ec);
488
489                         return Nullable.Wrap.Create (conv, target_type);
490                 }
491
492                 /// <summary>
493                 ///   Implicit Numeric Conversions.
494                 ///
495                 ///   expr is the expression to convert, returns a new expression of type
496                 ///   target_type or null if an implicit conversion is not possible.
497                 /// </summary>
498                 public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
499                 {
500                         return ImplicitNumericConversion (expr, expr.Type, target_type);
501                 }
502
503                 public static bool ImplicitNumericConversionExists (TypeSpec expr_type, TypeSpec target_type)
504                 {
505                         return ImplicitNumericConversion (null, expr_type, target_type) != null;
506                 }
507
508                 static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
509                 {
510                         switch (expr_type.BuiltinType) {
511                         case BuiltinTypeSpec.Type.SByte:
512                                 //
513                                 // From sbyte to short, int, long, float, double, decimal
514                                 //
515                                 switch (target_type.BuiltinType) {
516                                 case BuiltinTypeSpec.Type.Int:
517                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
518                                 case BuiltinTypeSpec.Type.Long:
519                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
520                                 case BuiltinTypeSpec.Type.Double:
521                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
522                                 case BuiltinTypeSpec.Type.Float:
523                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
524                                 case BuiltinTypeSpec.Type.Short:
525                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
526                                 case BuiltinTypeSpec.Type.Decimal:
527                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
528
529                                 }
530
531                                 break;
532                         case BuiltinTypeSpec.Type.Byte:
533                                 //
534                                 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
535                                 //
536                                 switch (target_type.BuiltinType) {
537                                 case BuiltinTypeSpec.Type.Int:
538                                 case BuiltinTypeSpec.Type.UInt:
539                                 case BuiltinTypeSpec.Type.Short:
540                                 case BuiltinTypeSpec.Type.UShort:
541                                         return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
542                                 case BuiltinTypeSpec.Type.ULong:
543                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
544                                 case BuiltinTypeSpec.Type.Long:
545                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
546                                 case BuiltinTypeSpec.Type.Float:
547                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
548                                 case BuiltinTypeSpec.Type.Double:
549                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
550                                 case BuiltinTypeSpec.Type.Decimal:
551                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
552                                 }
553                                 break;
554                         case BuiltinTypeSpec.Type.Short:
555                                 //
556                                 // From short to int, long, float, double, decimal
557                                 //
558                                 switch (target_type.BuiltinType) {
559                                 case BuiltinTypeSpec.Type.Int:
560                                         return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
561                                 case BuiltinTypeSpec.Type.Long:
562                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
563                                 case BuiltinTypeSpec.Type.Double:
564                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
565                                 case BuiltinTypeSpec.Type.Float:
566                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
567                                 case BuiltinTypeSpec.Type.Decimal:
568                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
569                                 }
570                                 break;
571                         case BuiltinTypeSpec.Type.UShort:
572                                 //
573                                 // From ushort to int, uint, long, ulong, float, double, decimal
574                                 //
575                                 switch (target_type.BuiltinType) {
576                                 case BuiltinTypeSpec.Type.Int:
577                                 case BuiltinTypeSpec.Type.UInt:
578                                         return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
579                                 case BuiltinTypeSpec.Type.ULong:
580                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
581                                 case BuiltinTypeSpec.Type.Long:
582                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
583                                 case BuiltinTypeSpec.Type.Double:
584                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
585                                 case BuiltinTypeSpec.Type.Float:
586                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
587                                 case BuiltinTypeSpec.Type.Decimal:
588                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
589                                 }
590                                 break;
591                         case BuiltinTypeSpec.Type.Int:
592                                 //
593                                 // From int to long, float, double, decimal
594                                 //
595                                 switch (target_type.BuiltinType) {
596                                 case BuiltinTypeSpec.Type.Long:
597                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
598                                 case BuiltinTypeSpec.Type.Double:
599                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
600                                 case BuiltinTypeSpec.Type.Float:
601                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
602                                 case BuiltinTypeSpec.Type.Decimal:
603                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
604                                 }
605                                 break;
606                         case BuiltinTypeSpec.Type.UInt:
607                                 //
608                                 // From uint to long, ulong, float, double, decimal
609                                 //
610                                 switch (target_type.BuiltinType) {
611                                 case BuiltinTypeSpec.Type.Long:
612                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
613                                 case BuiltinTypeSpec.Type.ULong:
614                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
615                                 case BuiltinTypeSpec.Type.Double:
616                                         return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
617                                 case BuiltinTypeSpec.Type.Float:
618                                         return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
619                                 case BuiltinTypeSpec.Type.Decimal:
620                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
621                                 }
622                                 break;
623                         case BuiltinTypeSpec.Type.Long:
624                                 //
625                                 // From long to float, double, decimal
626                                 //
627                                 switch (target_type.BuiltinType) {
628                                 case BuiltinTypeSpec.Type.Double:
629                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
630                                 case BuiltinTypeSpec.Type.Float:
631                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
632                                 case BuiltinTypeSpec.Type.Decimal:
633                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
634                                 }
635                                 break;
636                         case BuiltinTypeSpec.Type.ULong:
637                                 //
638                                 // From ulong to float, double, decimal
639                                 //
640                                 switch (target_type.BuiltinType) {
641                                 case BuiltinTypeSpec.Type.Double:
642                                         return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
643                                 case BuiltinTypeSpec.Type.Float:
644                                         return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
645                                 case BuiltinTypeSpec.Type.Decimal:
646                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
647                                 }
648                                 break;
649                         case BuiltinTypeSpec.Type.Char:
650                                 //
651                                 // From char to ushort, int, uint, long, ulong, float, double, decimal
652                                 //
653                                 switch (target_type.BuiltinType) {
654                                 case BuiltinTypeSpec.Type.UShort:
655                                 case BuiltinTypeSpec.Type.Int:
656                                 case BuiltinTypeSpec.Type.UInt:
657                                         return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
658                                 case BuiltinTypeSpec.Type.ULong:
659                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
660                                 case BuiltinTypeSpec.Type.Long:
661                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
662                                 case BuiltinTypeSpec.Type.Float:
663                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
664                                 case BuiltinTypeSpec.Type.Double:
665                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
666                                 case BuiltinTypeSpec.Type.Decimal:
667                                         return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
668                                 }
669                                 break;
670                         case BuiltinTypeSpec.Type.Float:
671                                 //
672                                 // float to double
673                                 //
674                                 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
675                                         return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
676                                 break;
677                         }
678
679                         return null;
680                 }
681
682                 //
683                 // Full version of implicit conversion
684                 //
685                 public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
686                 {
687                         if (ImplicitStandardConversionExists (ec, expr, target_type))
688                                 return true;
689
690                         if (expr.Type == InternalType.AnonymousMethod) {
691                                 if (!target_type.IsDelegate && !target_type.IsExpressionTreeType)
692                                         return false;
693
694                                 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
695                                 return ame.ImplicitStandardConversionExists (ec, target_type);
696                         }
697                         
698                         // Conversion from __arglist to System.ArgIterator
699                         if (expr.Type == InternalType.Arglist)
700                                 return target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec;
701
702                         return UserDefinedConversion (ec, expr, target_type,
703                                 UserConversionRestriction.ImplicitOnly | UserConversionRestriction.ProbingOnly, Location.Null) != null;
704                 }
705
706                 public static bool ImplicitStandardConversionExists (ResolveContext rc, Expression expr, TypeSpec target_type)
707                 {
708                         if (expr.eclass == ExprClass.MethodGroup) {
709                                 if (target_type.IsDelegate && rc.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
710                                         MethodGroupExpr mg = expr as MethodGroupExpr;
711                                         if (mg != null)
712                                                 return DelegateCreation.ImplicitStandardConversionExists (rc, mg, target_type);
713                                 }
714
715                                 return false;
716                         }
717
718                         var interpolated_string = expr as InterpolatedString;
719                         if (interpolated_string != null) {
720                                 if (target_type == rc.Module.PredefinedTypes.IFormattable.TypeSpec || target_type == rc.Module.PredefinedTypes.FormattableString.TypeSpec)
721                                         return true;
722                         }
723
724                         return ImplicitStandardConversionExists (expr, target_type);
725                 }
726
727                 //
728                 // Implicit standard conversion (only core conversions are used here)
729                 //
730                 public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
731                 {
732                         //
733                         // Identity conversions
734                         // Implicit numeric conversions
735                         // Implicit nullable conversions
736                         // Implicit reference conversions
737                         // Boxing conversions
738                         // Implicit constant expression conversions
739                         // Implicit conversions involving type parameters
740                         //
741
742                         TypeSpec expr_type = expr.Type;
743
744                         if (expr_type == target_type)
745                                 return true;
746
747                         if (target_type.IsNullableType)
748                                 return ImplicitNulableConversion (null, expr, target_type) != null;
749
750                         if (ImplicitNumericConversion (null, expr_type, target_type) != null)
751                                 return true;
752
753                         if (ImplicitReferenceConversionExists (expr_type, target_type, false))
754                                 return true;
755
756                         if (ImplicitBoxingConversion (null, expr_type, target_type) != null)
757                                 return true;
758                         
759                         //
760                         // Implicit Constant Expression Conversions
761                         //
762                         if (expr is IntConstant){
763                                 int value = ((IntConstant) expr).Value;
764                                 switch (target_type.BuiltinType) {
765                                 case BuiltinTypeSpec.Type.SByte:
766                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
767                                                 return true;
768                                         break;
769                                 case BuiltinTypeSpec.Type.Byte:
770                                         if (value >= 0 && value <= Byte.MaxValue)
771                                                 return true;
772                                         break;
773                                 case BuiltinTypeSpec.Type.Short:
774                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
775                                                 return true;
776                                         break;
777                                 case BuiltinTypeSpec.Type.UShort:
778                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
779                                                 return true;
780                                         break;
781                                 case BuiltinTypeSpec.Type.UInt:
782                                         if (value >= 0)
783                                                 return true;
784                                         break;
785                                 case BuiltinTypeSpec.Type.ULong:
786                                          //
787                                          // we can optimize this case: a positive int32
788                                          // always fits on a uint64.  But we need an opcode
789                                          // to do it.
790                                          //
791                                         if (value >= 0)
792                                                 return true;
793
794                                         break;
795                                 }
796                         }
797
798                         if (expr is LongConstant && target_type.BuiltinType == BuiltinTypeSpec.Type.ULong){
799                                 //
800                                 // Try the implicit constant expression conversion
801                                 // from long to ulong, instead of a nice routine,
802                                 // we just inline it
803                                 //
804                                 long v = ((LongConstant) expr).Value;
805                                 if (v >= 0)
806                                         return true;
807                         }
808
809                         if (expr is IntegralConstant && target_type.IsEnum) {
810                                 var i = (IntegralConstant) expr;
811                                 //
812                                 // LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
813                                 //
814                                 // An implicit enumeration conversion permits the decimal-integer-literal 0
815                                 // to be converted to any enum-type and to any nullable-type whose underlying
816                                 // type is an enum-type
817                                 //
818                                 return i.IsZeroInteger;
819                         }
820
821                         //
822                         // Implicit dynamic conversion for remaining value types. It should probably
823                         // go somewhere else
824                         //
825                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
826                                 switch (target_type.Kind) {
827                                 case MemberKind.Struct:
828                                 case MemberKind.Enum:
829                                         return true;
830                                 }
831
832                                 return false;
833                         }
834
835                         //
836                         // In an unsafe context implicit conversions is extended to include
837                         //
838                         // From any pointer-type to the type void*
839                         // From the null literal to any pointer-type.
840                         //
841                         // LAMESPEC: The specification claims this conversion is allowed in implicit conversion but
842                         // in reality implicit standard conversion uses it
843                         //
844                         if (target_type.IsPointer && expr.Type.IsPointer && ((PointerContainer) target_type).Element.Kind == MemberKind.Void)
845                                 return true;
846
847                         //
848                         // Struct identity conversion, including dynamic erasure
849                         //
850                         if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
851                                 return true;
852
853                         return false;
854                 }
855
856                 /// <summary>
857                 ///  Finds "most encompassed type" according to the spec (13.4.2)
858                 ///  amongst the methods in the MethodGroupExpr
859                 /// </summary>
860                 public static TypeSpec FindMostEncompassedType (IList<TypeSpec> types)
861                 {
862                         TypeSpec best = null;
863                         EmptyExpression expr;
864
865                         foreach (TypeSpec t in types) {
866                                 if (best == null) {
867                                         best = t;
868                                         continue;
869                                 }
870
871                                 expr = new EmptyExpression (t);
872                                 if (ImplicitStandardConversionExists (expr, best))
873                                         best = t;
874                         }
875
876                         expr = new EmptyExpression (best);
877                         foreach (TypeSpec t in types) {
878                                 if (best == t)
879                                         continue;
880                                 if (!ImplicitStandardConversionExists (expr, t)) {
881                                         best = null;
882                                         break;
883                                 }
884                         }
885
886                         return best;
887                 }
888
889                 //
890                 // Finds the most encompassing type (type into which all other
891                 // types can convert to) amongst the types in the given set
892                 //
893                 static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
894                 {
895                         if (types.Count == 0)
896                                 return null;
897
898                         if (types.Count == 1)
899                                 return types [0];
900
901                         TypeSpec best = null;
902                         for (int i = 0; i < types.Count; ++i) {
903                                 int ii = 0;
904                                 for (; ii < types.Count; ++ii) {
905                                         if (ii == i)
906                                                 continue;
907
908                                         var expr = new EmptyExpression (types[ii]);
909                                         if (!ImplicitStandardConversionExists (expr, types [i])) {
910                                                 ii = 0;
911                                                 break;
912                                         }
913                                 }
914
915                                 if (ii == 0)
916                                         continue;
917
918                                 if (best == null) {
919                                         best = types[i];
920                                         continue;
921                                 }
922
923                                 // Indicates multiple best types
924                                 return InternalType.FakeInternalType;
925                         }
926
927                         return best;
928                 }
929
930                 //
931                 // Finds the most specific source Sx according to the rules of the spec (13.4.4)
932                 // by making use of FindMostEncomp* methods. Applies the correct rules separately
933                 // for explicit and implicit conversion operators.
934                 //
935                 static TypeSpec FindMostSpecificSource (ResolveContext rc, List<MethodSpec> list, TypeSpec sourceType, Expression source, bool apply_explicit_conv_rules)
936                 {
937                         TypeSpec[] src_types_set = null;
938
939                         //
940                         // Try exact match first, if any operator converts from S then Sx = S
941                         //
942                         for (int i = 0; i < list.Count; ++i) {
943                                 TypeSpec param_type = list [i].Parameters.Types [0];
944
945                                 if (param_type == sourceType)
946                                         return param_type;
947
948                                 if (src_types_set == null)
949                                         src_types_set = new TypeSpec [list.Count];
950
951                                 src_types_set [i] = param_type;
952                         }
953
954                         //
955                         // Explicit Conv rules
956                         //
957                         if (apply_explicit_conv_rules) {
958                                 var candidate_set = new List<TypeSpec> ();
959
960                                 foreach (TypeSpec param_type in src_types_set){
961                                         if (ImplicitStandardConversionExists (rc, source, param_type))
962                                                 candidate_set.Add (param_type);
963                                 }
964
965                                 if (candidate_set.Count != 0) {
966                                         if (source.eclass == ExprClass.MethodGroup)
967                                                 return InternalType.FakeInternalType;
968
969                                         return FindMostEncompassedType (candidate_set);
970                                 }
971                         }
972
973                         //
974                         // Final case
975                         //
976                         if (apply_explicit_conv_rules)
977                                 return FindMostEncompassingType (src_types_set);
978                         else
979                                 return FindMostEncompassedType (src_types_set);
980                 }
981
982                 /// <summary>
983                 ///  Finds the most specific target Tx according to section 13.4.4
984                 /// </summary>
985                 static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
986                                                            TypeSpec target, bool apply_explicit_conv_rules)
987                 {
988                         List<TypeSpec> tgt_types_set = null;
989
990                         //
991                         // If any operator converts to T then Tx = T
992                         //
993                         foreach (var mi in list){
994                                 TypeSpec ret_type = mi.ReturnType;
995                                 if (ret_type == target)
996                                         return ret_type;
997
998                                 if (tgt_types_set == null) {
999                                         tgt_types_set = new List<TypeSpec> (list.Count);
1000                                 } else if (tgt_types_set.Contains (ret_type)) {
1001                                         continue;
1002                                 }
1003
1004                                 tgt_types_set.Add (ret_type);
1005                         }
1006
1007                         //
1008                         // Explicit conv rules
1009                         //
1010                         if (apply_explicit_conv_rules) {
1011                                 var candidate_set = new List<TypeSpec> ();
1012
1013                                 foreach (TypeSpec ret_type in tgt_types_set) {
1014                                         var expr = new EmptyExpression (ret_type);
1015
1016                                         if (ImplicitStandardConversionExists (expr, target))
1017                                                 candidate_set.Add (ret_type);
1018                                 }
1019
1020                                 if (candidate_set.Count != 0)
1021                                         return FindMostEncompassingType (candidate_set);
1022                         }
1023
1024                         //
1025                         // Okay, final case !
1026                         //
1027                         if (apply_explicit_conv_rules)
1028                                 return FindMostEncompassedType (tgt_types_set);
1029                         else
1030                                 return FindMostEncompassingType (tgt_types_set);
1031                 }
1032
1033                 /// <summary>
1034                 ///  User-defined Implicit conversions
1035                 /// </summary>
1036                 static public Expression ImplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
1037                 {
1038                         return UserDefinedConversion (ec, source, target, UserConversionRestriction.ImplicitOnly, loc);
1039                 }
1040
1041                 /// <summary>
1042                 ///  User-defined Explicit conversions
1043                 /// </summary>
1044                 static Expression ExplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
1045                 {
1046                         return UserDefinedConversion (ec, source, target, 0, loc);
1047                 }
1048
1049                 static void FindApplicableUserDefinedConversionOperators (ResolveContext rc, IList<MemberSpec> operators, Expression source, TypeSpec target, UserConversionRestriction restr, ref List<MethodSpec> candidates)
1050                 {
1051                         if (source.Type.IsInterface) {
1052                                 // Neither A nor B are interface-types
1053                                 return;
1054                         }
1055
1056                         // For a conversion operator to be applicable, it must be possible
1057                         // to perform a standard conversion from the source type to
1058                         // the operand type of the operator, and it must be possible
1059                         // to perform a standard conversion from the result type of
1060                         // the operator to the target type.
1061
1062                         Expression texpr = null;
1063
1064                         foreach (MethodSpec op in operators) {
1065                                 
1066                                 // Can be null because MemberCache.GetUserOperator does not resize the array
1067                                 if (op == null)
1068                                         continue;
1069
1070                                 var t = op.Parameters.Types[0];
1071                                 if (source.Type != t && !ImplicitStandardConversionExists (rc, source, t)) {
1072                                         if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
1073                                                 continue;
1074
1075                                         if (!ImplicitStandardConversionExists (new EmptyExpression (t), source.Type))
1076                                                         continue;
1077                                 }
1078
1079                                 if ((restr & UserConversionRestriction.NullableSourceOnly) != 0 && !t.IsNullableType)
1080                                         continue;
1081
1082                                 t = op.ReturnType;
1083
1084                                 if (t.IsInterface)
1085                                         continue;
1086
1087                                 if (target != t) {
1088                                         if (t.IsNullableType)
1089                                                 t = Nullable.NullableInfo.GetUnderlyingType (t);
1090
1091                                         if (!ImplicitStandardConversionExists (new EmptyExpression (t), target)) {
1092                                                 if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
1093                                                         continue;
1094
1095                                                 if (texpr == null)
1096                                                         texpr = new EmptyExpression (target);
1097
1098                                                 if (!ImplicitStandardConversionExists (texpr, t))
1099                                                         continue;
1100                                         }
1101                                 }
1102
1103                                 if (candidates == null)
1104                                         candidates = new List<MethodSpec> ();
1105
1106                                 candidates.Add (op);
1107                         }
1108                 }
1109
1110                 //
1111                 // User-defined conversions
1112                 //
1113                 public static Expression UserDefinedConversion (ResolveContext rc, Expression source, TypeSpec target, UserConversionRestriction restr, Location loc)
1114                 {
1115                         List<MethodSpec> candidates = null;
1116
1117                         //
1118                         // If S or T are nullable types, source_type and target_type are their underlying types
1119                         // otherwise source_type and target_type are equal to S and T respectively.
1120                         //
1121                         TypeSpec source_type = source.Type;
1122                         TypeSpec target_type = target;
1123                         Expression source_type_expr;
1124                         bool nullable_source = false;
1125                         var implicitOnly = (restr & UserConversionRestriction.ImplicitOnly) != 0;
1126
1127                         if (source_type.IsNullableType) {
1128                                 // No unwrapping conversion S? -> T for non-reference types
1129                                 if (implicitOnly && !TypeSpec.IsReferenceType (target_type) && !target_type.IsNullableType) {
1130                                         source_type_expr = source;
1131                                 } else {
1132                                         source_type_expr = Nullable.Unwrap.CreateUnwrapped (source);
1133                                         source_type = source_type_expr.Type;
1134                                         nullable_source = true;
1135                                 }
1136                         } else {
1137                                 source_type_expr = source;
1138                         }
1139
1140                         if (target_type.IsNullableType)
1141                                 target_type = Nullable.NullableInfo.GetUnderlyingType (target_type);
1142
1143                         // Only these containers can contain a user defined implicit or explicit operators
1144                         const MemberKind user_conversion_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.TypeParameter;
1145
1146                         if ((source_type.Kind & user_conversion_kinds) != 0 && source_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
1147                                 bool declared_only = source_type.IsStruct;
1148
1149                                 var operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Implicit, declared_only);
1150                                 if (operators != null) {
1151                                         FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1152                                 }
1153
1154                                 if (!implicitOnly) {
1155                                         operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Explicit, declared_only);
1156                                         if (operators != null) {
1157                                                 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1158                                         }
1159                                 }
1160                         }
1161
1162                         if ((target.Kind & user_conversion_kinds) != 0 && target_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
1163                                 bool declared_only = target.IsStruct || implicitOnly;
1164
1165                                 var operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Implicit, declared_only);
1166                                 if (operators != null) {
1167                                         FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1168                                 }
1169
1170                                 if (!implicitOnly) {
1171                                         operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Explicit, declared_only);
1172                                         if (operators != null) {
1173                                                 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1174                                         }
1175                                 }
1176                         }
1177
1178                         if (candidates == null)
1179                                 return null;
1180
1181                         //
1182                         // Find the most specific conversion operator
1183                         //
1184                         MethodSpec most_specific_operator;
1185                         TypeSpec s_x, t_x;
1186                         if (candidates.Count == 1) {
1187                                 most_specific_operator = candidates[0];
1188                                 s_x = most_specific_operator.Parameters.Types[0];
1189                                 t_x = most_specific_operator.ReturnType;
1190                         } else {
1191                                 //
1192                                 // Pass original source type to find the best match against input type and
1193                                 // not the unwrapped expression
1194                                 //
1195                                 s_x = FindMostSpecificSource (rc, candidates, source.Type, source_type_expr, !implicitOnly);
1196                                 if (s_x == null)
1197                                         return null;
1198
1199                                 t_x = FindMostSpecificTarget (candidates, target, !implicitOnly);
1200                                 if (t_x == null)
1201                                         return null;
1202
1203                                 most_specific_operator = null;
1204                                 for (int i = 0; i < candidates.Count; ++i) {
1205                                         if (candidates[i].ReturnType == t_x && candidates[i].Parameters.Types[0] == s_x) {
1206                                                 most_specific_operator = candidates[i];
1207                                                 break;
1208                                         }
1209                                 }
1210
1211                                 if (most_specific_operator == null) {
1212                                         //
1213                                         // Unless running in probing more
1214                                         //
1215                                         if ((restr & UserConversionRestriction.ProbingOnly) == 0) {
1216                                                 MethodSpec ambig_arg = candidates [0];
1217                                                 most_specific_operator = candidates [1];
1218                                                 /*
1219                                                 foreach (var candidate in candidates) {
1220                                                         if (candidate.ReturnType == t_x)
1221                                                                 most_specific_operator = candidate;
1222                                                         else if (candidate.Parameters.Types[0] == s_x)
1223                                                                 ambig_arg = candidate;
1224                                                 }
1225                                                 */
1226                                                 rc.Report.Error (457, loc,
1227                                                         "Ambiguous user defined operators `{0}' and `{1}' when converting from `{2}' to `{3}'",
1228                                                         ambig_arg.GetSignatureForError (), most_specific_operator.GetSignatureForError (),
1229                                                         source.Type.GetSignatureForError (), target.GetSignatureForError ());
1230                                         }
1231
1232                                         return ErrorExpression.Instance;
1233                                 }
1234                         }
1235
1236                         //
1237                         // Convert input type when it's different to best operator argument
1238                         //
1239                         if (s_x != source_type) {
1240                                 var c = source as Constant;
1241                                 if (c != null) {
1242                                         source = c.Reduce (rc, s_x);
1243                                         if (source == null)
1244                                                 c = null;
1245                                 }
1246
1247                                 if (c == null) {
1248                                         source = implicitOnly ?
1249                                                 ImplicitConversionStandard (rc, source_type_expr, s_x, loc) :
1250                                                 ExplicitConversionStandard (rc, source_type_expr, s_x, loc);
1251                                 }
1252                         } else {
1253                                 source = source_type_expr;
1254                         }
1255
1256                         source = new UserCast (most_specific_operator, source, loc).Resolve (rc);
1257
1258                         //
1259                         // Convert result type when it's different to best operator return type
1260                         //
1261                         if (t_x != target_type) {
1262                                 //
1263                                 // User operator is of T?
1264                                 //
1265                                 if (t_x.IsNullableType && (target.IsNullableType || !implicitOnly)) {
1266                                         //
1267                                         // User operator return type does not match target type we need
1268                                         // yet another conversion. This should happen for promoted numeric
1269                                         // types only
1270                                         //
1271                                         if (t_x != target) {
1272                                                 var unwrap = Nullable.Unwrap.CreateUnwrapped (source);
1273
1274                                                 source = implicitOnly ?
1275                                                         ImplicitConversionStandard (rc, unwrap, target_type, loc) :
1276                                                         ExplicitConversionStandard (rc, unwrap, target_type, loc);
1277
1278                                                 if (source == null)
1279                                                         return null;
1280
1281                                                 if (target.IsNullableType)
1282                                                         source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (rc);
1283                                         }
1284                                 } else {
1285                                         source = implicitOnly ?
1286                                                 ImplicitConversionStandard (rc, source, target_type, loc) :
1287                                                 ExplicitConversionStandard (rc, source, target_type, loc);
1288
1289                                         if (source == null)
1290                                                 return null;
1291                                 }
1292                         }
1293
1294
1295                         //
1296                         // Source expression is of nullable type and underlying conversion returns
1297                         // only non-nullable type we need to lift it manually
1298                         //
1299                         if (nullable_source && !s_x.IsNullableType)
1300                                 return new Nullable.LiftedConversion (source, source_type_expr, target).Resolve (rc);
1301
1302                         //
1303                         // Target is of nullable type but source type is not, wrap the result expression
1304                         //
1305                         if (target.IsNullableType && !t_x.IsNullableType)
1306                                 source = Nullable.Wrap.Create (source, target);
1307
1308                         return source;
1309                 }
1310
1311                 /// <summary>
1312                 ///   Converts implicitly the resolved expression `expr' into the
1313                 ///   `target_type'.  It returns a new expression that can be used
1314                 ///   in a context that expects a `target_type'.
1315                 /// </summary>
1316                 static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
1317                                                              TypeSpec target_type, Location loc)
1318                 {
1319                         Expression e;
1320
1321                         if (target_type == null)
1322                                 throw new Exception ("Target type is null");
1323
1324                         e = ImplicitConversionStandard (ec, expr, target_type, loc);
1325                         if (e != null)
1326                                 return e;
1327
1328                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1329                         if (e != null)
1330                                 return e;
1331
1332                         return null;
1333                 }
1334
1335
1336                 /// <summary>
1337                 ///   Attempts to apply the `Standard Implicit
1338                 ///   Conversion' rules to the expression `expr' into
1339                 ///   the `target_type'.  It returns a new expression
1340                 ///   that can be used in a context that expects a
1341                 ///   `target_type'.
1342                 ///
1343                 ///   This is different from `ImplicitConversion' in that the
1344                 ///   user defined implicit conversions are excluded.
1345                 /// </summary>
1346                 static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
1347                                                                      TypeSpec target_type, Location loc)
1348                 {
1349                         return ImplicitConversionStandard (ec, expr, target_type, loc, false);
1350                 }
1351
1352                 static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
1353                 {
1354                         if (expr.eclass == ExprClass.MethodGroup){
1355                                 if (!target_type.IsDelegate){
1356                                         return null;
1357                                 }
1358
1359                                 //
1360                                 // Only allow anonymous method conversions on post ISO_1
1361                                 //
1362                                 if (ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1){
1363                                         MethodGroupExpr mg = expr as MethodGroupExpr;
1364                                         if (mg != null)
1365                                                 return new ImplicitDelegateCreation (target_type, mg, loc).Resolve (ec);
1366                                 }
1367                         }
1368
1369                         TypeSpec expr_type = expr.Type;
1370                         Expression e;
1371
1372                         if (expr_type == target_type) {
1373                                 if (expr_type != InternalType.NullLiteral && expr_type != InternalType.AnonymousMethod)
1374                                         return expr;
1375                                 return null;
1376                         }
1377
1378                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1379                                 switch (target_type.Kind) {
1380                                 case MemberKind.ArrayType:
1381                                 case MemberKind.Class:
1382                                         if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object)
1383                                                 return EmptyCast.Create (expr, target_type);
1384
1385                                         goto case MemberKind.Struct;
1386                                 case MemberKind.Struct:
1387                                 case MemberKind.Delegate:
1388                                 case MemberKind.Enum:
1389                                 case MemberKind.Interface:
1390                                 case MemberKind.TypeParameter:
1391                                         Arguments args = new Arguments (1);
1392                                         args.Add (new Argument (expr));
1393                                         return new DynamicConversion (target_type, explicit_cast ? CSharpBinderFlags.ConvertExplicit : 0, args, loc).Resolve (ec);
1394                                 }
1395
1396                                 return null;
1397                         }
1398
1399                         if (target_type.IsNullableType)
1400                                 return ImplicitNulableConversion (ec, expr, target_type);
1401
1402                         //
1403                         // Attempt to do the implicit constant expression conversions
1404                         //
1405                         Constant c = expr as Constant;
1406                         if (c != null) {
1407                                 try {
1408                                         c = c.ConvertImplicitly (target_type);
1409                                 } catch {
1410                                         throw new InternalErrorException ("Conversion error", loc);
1411                                 }
1412                                 if (c != null)
1413                                         return c;
1414                         }
1415
1416                         e = ImplicitNumericConversion (expr, expr_type, target_type);
1417                         if (e != null)
1418                                 return e;
1419
1420                         e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
1421                         if (e != null)
1422                                 return e;
1423
1424                         e = ImplicitBoxingConversion (expr, expr_type, target_type);
1425                         if (e != null)
1426                                 return e;
1427
1428                         if (expr is IntegralConstant && target_type.IsEnum){
1429                                 var i = (IntegralConstant) expr;
1430                                 //
1431                                 // LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
1432                                 //
1433                                 // An implicit enumeration conversion permits the decimal-integer-literal 0
1434                                 // to be converted to any enum-type and to any nullable-type whose underlying
1435                                 // type is an enum-type
1436                                 //
1437                                 if (i.IsZeroInteger) {
1438                                         // Recreate 0 literal to remove any collected conversions
1439                                         return new EnumConstant (new IntLiteral (ec.BuiltinTypes, 0, i.Location), target_type);
1440                                 }
1441                         }
1442
1443                         var target_pc = target_type as PointerContainer;
1444                         if (target_pc != null) {
1445                                 if (expr_type.IsPointer) {
1446                                         //
1447                                         // Pointer types are same when they have same element types
1448                                         //
1449                                         if (expr_type == target_pc)
1450                                                 return expr;
1451
1452                                         if (target_pc.Element.Kind == MemberKind.Void)
1453                                                 return EmptyCast.Create (expr, target_type);
1454
1455                                                 //return null;
1456                                 }
1457
1458                                 if (expr_type == InternalType.NullLiteral)
1459                                         return new NullPointer (target_type, loc);
1460                         }
1461
1462                         if (expr_type == InternalType.AnonymousMethod){
1463                                 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
1464                                 Expression am = ame.Compatible (ec, target_type);
1465                                 if (am != null)
1466                                         return am.Resolve (ec);
1467
1468                                 // Avoid CS1503 after CS1661
1469                                 return ErrorExpression.Instance;
1470                         }
1471
1472                         if (expr_type == InternalType.Arglist && target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec)
1473                                 return expr;
1474
1475                         //
1476                         // dynamic erasure conversion on value types
1477                         //
1478                         if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
1479                                 return expr_type == target_type ? expr : EmptyCast.Create (expr, target_type);
1480
1481                         var interpolated_string = expr as InterpolatedString;
1482                         if (interpolated_string != null) {
1483                                 if (target_type == ec.Module.PredefinedTypes.IFormattable.TypeSpec || target_type == ec.Module.PredefinedTypes.FormattableString.TypeSpec)
1484                                         return interpolated_string.ConvertTo (ec, target_type);
1485                         }
1486
1487                         return null;
1488                 }
1489
1490                 /// <summary>
1491                 ///   Attempts to implicitly convert `source' into `target_type', using
1492                 ///   ImplicitConversion.  If there is no implicit conversion, then
1493                 ///   an error is signaled
1494                 /// </summary>
1495                 static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
1496                                                                      TypeSpec target_type, Location loc)
1497                 {
1498                         Expression e = ImplicitConversion (ec, source, target_type, loc);
1499                         if (e != null)
1500                                 return e;
1501
1502                         source.Error_ValueCannotBeConverted (ec, target_type, false);
1503
1504                         return null;
1505                 }
1506
1507                 /// <summary>
1508                 ///   Performs the explicit numeric conversions
1509                 ///
1510                 /// There are a few conversions that are not part of the C# standard,
1511                 /// they were interim hacks in the C# compiler that were supposed to
1512                 /// become explicit operators in the UIntPtr class and IntPtr class,
1513                 /// but for historical reasons it did not happen, so the C# compiler
1514                 /// ended up with these special hacks.
1515                 ///
1516                 /// See bug 59800 for details.
1517                 ///
1518                 /// The conversion are:
1519                 ///   UIntPtr->SByte
1520                 ///   UIntPtr->Int16
1521                 ///   UIntPtr->Int32
1522                 ///   IntPtr->UInt64
1523                 ///   UInt64->IntPtr
1524                 ///   SByte->UIntPtr
1525                 ///   Int16->UIntPtr
1526                 ///
1527                 /// </summary>
1528                 public static Expression ExplicitNumericConversion (ResolveContext rc, Expression expr, TypeSpec target_type)
1529                 {
1530                         // Not all predefined explicit numeric conversion are
1531                         // defined here, for some of them (mostly IntPtr/UIntPtr) we
1532                         // defer to user-operator handling which is now perfect but
1533                         // works for now
1534                         //
1535                         // LAMESPEC: Undocumented IntPtr/UIntPtr conversions
1536                         // IntPtr -> uint uses int
1537                         // UIntPtr -> long uses ulong
1538                         //
1539
1540                         switch (expr.Type.BuiltinType) {
1541                         case BuiltinTypeSpec.Type.SByte:
1542                                 //
1543                                 // From sbyte to byte, ushort, uint, ulong, char, uintptr
1544                                 //
1545                                 switch (target_type.BuiltinType) {
1546                                 case BuiltinTypeSpec.Type.Byte:
1547                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
1548                                 case BuiltinTypeSpec.Type.UShort:
1549                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
1550                                 case BuiltinTypeSpec.Type.UInt:
1551                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
1552                                 case BuiltinTypeSpec.Type.ULong:
1553                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
1554                                 case BuiltinTypeSpec.Type.Char:
1555                                         return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
1556
1557                                 // One of the built-in conversions that belonged in the class library
1558                                 case BuiltinTypeSpec.Type.UIntPtr:
1559                                         return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I1_U8), target_type, target_type, true);
1560                                 }
1561                                 break;
1562                         case BuiltinTypeSpec.Type.Byte:
1563                                 //
1564                                 // From byte to sbyte and char
1565                                 //
1566                                 switch (target_type.BuiltinType) {
1567                                 case BuiltinTypeSpec.Type.SByte:
1568                                         return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
1569                                 case BuiltinTypeSpec.Type.Char:
1570                                         return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
1571                                 }
1572                                 break;
1573                         case BuiltinTypeSpec.Type.Short:
1574                                 //
1575                                 // From short to sbyte, byte, ushort, uint, ulong, char, uintptr
1576                                 //
1577                                 switch (target_type.BuiltinType) {
1578                                 case BuiltinTypeSpec.Type.SByte:
1579                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
1580                                 case BuiltinTypeSpec.Type.Byte:
1581                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
1582                                 case BuiltinTypeSpec.Type.UShort:
1583                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
1584                                 case BuiltinTypeSpec.Type.UInt:
1585                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
1586                                 case BuiltinTypeSpec.Type.ULong:
1587                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
1588                                 case BuiltinTypeSpec.Type.Char:
1589                                         return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
1590
1591                                 // One of the built-in conversions that belonged in the class library
1592                                 case BuiltinTypeSpec.Type.UIntPtr:
1593                                         return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
1594                                 }
1595                                 break;
1596                         case BuiltinTypeSpec.Type.UShort:
1597                                 //
1598                                 // From ushort to sbyte, byte, short, char
1599                                 //
1600                                 switch (target_type.BuiltinType) {
1601                                 case BuiltinTypeSpec.Type.SByte:
1602                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
1603                                 case BuiltinTypeSpec.Type.Byte:
1604                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
1605                                 case BuiltinTypeSpec.Type.Short:
1606                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
1607                                 case BuiltinTypeSpec.Type.Char:
1608                                         return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
1609                                 }
1610                                 break;
1611                         case BuiltinTypeSpec.Type.Int:
1612                                 //
1613                                 // From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
1614                                 //
1615                                 switch (target_type.BuiltinType) {
1616                                 case BuiltinTypeSpec.Type.SByte:
1617                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
1618                                 case BuiltinTypeSpec.Type.Byte:
1619                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
1620                                 case BuiltinTypeSpec.Type.Short:
1621                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
1622                                 case BuiltinTypeSpec.Type.UShort:
1623                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
1624                                 case BuiltinTypeSpec.Type.UInt:
1625                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
1626                                 case BuiltinTypeSpec.Type.ULong:
1627                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
1628                                 case BuiltinTypeSpec.Type.Char:
1629                                         return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
1630
1631                                 // One of the built-in conversions that belonged in the class library
1632                                 case BuiltinTypeSpec.Type.UIntPtr:
1633                                         return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
1634                                 }
1635                                 break;
1636                         case BuiltinTypeSpec.Type.UInt:
1637                                 //
1638                                 // From uint to sbyte, byte, short, ushort, int, char
1639                                 //
1640                                 switch (target_type.BuiltinType) {
1641                                 case BuiltinTypeSpec.Type.SByte:
1642                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
1643                                 case BuiltinTypeSpec.Type.Byte:
1644                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
1645                                 case BuiltinTypeSpec.Type.Short:
1646                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
1647                                 case BuiltinTypeSpec.Type.UShort:
1648                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
1649                                 case BuiltinTypeSpec.Type.Int:
1650                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
1651                                 case BuiltinTypeSpec.Type.Char:
1652                                         return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
1653                                 }
1654                                 break;
1655                         case BuiltinTypeSpec.Type.Long:
1656                                 //
1657                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1658                                 //
1659                                 switch (target_type.BuiltinType) {
1660                                 case BuiltinTypeSpec.Type.SByte:
1661                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
1662                                 case BuiltinTypeSpec.Type.Byte:
1663                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
1664                                 case BuiltinTypeSpec.Type.Short:
1665                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
1666                                 case BuiltinTypeSpec.Type.UShort:
1667                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
1668                                 case BuiltinTypeSpec.Type.Int:
1669                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
1670                                 case BuiltinTypeSpec.Type.UInt:
1671                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
1672                                 case BuiltinTypeSpec.Type.ULong:
1673                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
1674                                 case BuiltinTypeSpec.Type.Char:
1675                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
1676                                 }
1677                                 break;
1678                         case BuiltinTypeSpec.Type.ULong:
1679                                 //
1680                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1681                                 //
1682                                 switch (target_type.BuiltinType) {
1683                                 case BuiltinTypeSpec.Type.SByte:
1684                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
1685                                 case BuiltinTypeSpec.Type.Byte:
1686                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
1687                                 case BuiltinTypeSpec.Type.Short:
1688                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
1689                                 case BuiltinTypeSpec.Type.UShort:
1690                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
1691                                 case BuiltinTypeSpec.Type.Int:
1692                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
1693                                 case BuiltinTypeSpec.Type.UInt:
1694                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
1695                                 case BuiltinTypeSpec.Type.Long:
1696                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
1697                                 case BuiltinTypeSpec.Type.Char:
1698                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
1699
1700                                 // One of the built-in conversions that belonged in the class library
1701                                 case BuiltinTypeSpec.Type.IntPtr:
1702                                         return new OperatorCast (EmptyCast.Create (expr, rc.BuiltinTypes.Long), target_type, true);
1703                                 }
1704                                 break;
1705                         case BuiltinTypeSpec.Type.Char:
1706                                 //
1707                                 // From char to sbyte, byte, short
1708                                 //
1709                                 switch (target_type.BuiltinType) {
1710                                 case BuiltinTypeSpec.Type.SByte:
1711                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
1712                                 case BuiltinTypeSpec.Type.Byte:
1713                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
1714                                 case BuiltinTypeSpec.Type.Short:
1715                                         return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
1716                                 }
1717                                 break;
1718                         case BuiltinTypeSpec.Type.Float:
1719                                 //
1720                                 // From float to sbyte, byte, short,
1721                                 // ushort, int, uint, long, ulong, char
1722                                 // or decimal
1723                                 //
1724                                 switch (target_type.BuiltinType) {
1725                                 case BuiltinTypeSpec.Type.SByte:
1726                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
1727                                 case BuiltinTypeSpec.Type.Byte:
1728                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
1729                                 case BuiltinTypeSpec.Type.Short:
1730                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
1731                                 case BuiltinTypeSpec.Type.UShort:
1732                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
1733                                 case BuiltinTypeSpec.Type.Int:
1734                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
1735                                 case BuiltinTypeSpec.Type.UInt:
1736                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
1737                                 case BuiltinTypeSpec.Type.Long:
1738                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
1739                                 case BuiltinTypeSpec.Type.ULong:
1740                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
1741                                 case BuiltinTypeSpec.Type.Char:
1742                                         return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
1743                                 case BuiltinTypeSpec.Type.Decimal:
1744                                         return new OperatorCast (expr, target_type, true);
1745                                 }
1746                                 break;
1747                         case BuiltinTypeSpec.Type.Double:
1748                                 //
1749                                 // From double to sbyte, byte, short,
1750                                 // ushort, int, uint, long, ulong,
1751                                 // char, float or decimal
1752                                 //
1753                                 switch (target_type.BuiltinType) {
1754                                 case BuiltinTypeSpec.Type.SByte:
1755                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
1756                                 case BuiltinTypeSpec.Type.Byte:
1757                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
1758                                 case BuiltinTypeSpec.Type.Short:
1759                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
1760                                 case BuiltinTypeSpec.Type.UShort:
1761                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
1762                                 case BuiltinTypeSpec.Type.Int:
1763                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
1764                                 case BuiltinTypeSpec.Type.UInt:
1765                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
1766                                 case BuiltinTypeSpec.Type.Long:
1767                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
1768                                 case BuiltinTypeSpec.Type.ULong:
1769                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
1770                                 case BuiltinTypeSpec.Type.Char:
1771                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
1772                                 case BuiltinTypeSpec.Type.Float:
1773                                         return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
1774                                 case BuiltinTypeSpec.Type.Decimal:
1775                                         return new OperatorCast (expr, target_type, true);
1776                                 }
1777                                 break;
1778                         case BuiltinTypeSpec.Type.UIntPtr:
1779                                 //
1780                                 // Various built-in conversions that belonged in the class library
1781                                 //
1782                                 // from uintptr to sbyte, short, int32
1783                                 //
1784                                 switch (target_type.BuiltinType) {
1785                                 case BuiltinTypeSpec.Type.SByte:
1786                                         return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I1);
1787                                 case BuiltinTypeSpec.Type.Short:
1788                                         return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I2);
1789                                 case BuiltinTypeSpec.Type.Int:
1790                                         return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type);
1791                                 case BuiltinTypeSpec.Type.UInt:
1792                                         return new OperatorCast (expr, expr.Type, target_type, true);
1793                                 case BuiltinTypeSpec.Type.Long:
1794                                         return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.ULong, true), target_type);
1795                                 }
1796                                 break;
1797                         case BuiltinTypeSpec.Type.IntPtr:
1798                                 if (target_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
1799                                         return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Int, true), target_type);
1800                                 if (target_type.BuiltinType == BuiltinTypeSpec.Type.ULong)
1801                                         return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Long, true), target_type);
1802                                 
1803                                 break;
1804                         case BuiltinTypeSpec.Type.Decimal:
1805                                 // From decimal to sbyte, byte, short,
1806                                 // ushort, int, uint, long, ulong, char,
1807                                 // float, or double
1808                                 switch (target_type.BuiltinType) {
1809                                 case BuiltinTypeSpec.Type.SByte:
1810                                 case BuiltinTypeSpec.Type.Byte:
1811                                 case BuiltinTypeSpec.Type.Short:
1812                                 case BuiltinTypeSpec.Type.UShort:
1813                                 case BuiltinTypeSpec.Type.Int:
1814                                 case BuiltinTypeSpec.Type.UInt:
1815                                 case BuiltinTypeSpec.Type.Long:
1816                                 case BuiltinTypeSpec.Type.ULong:
1817                                 case BuiltinTypeSpec.Type.Char:
1818                                 case BuiltinTypeSpec.Type.Float:
1819                                 case BuiltinTypeSpec.Type.Double:
1820                                         return new OperatorCast (expr, expr.Type, target_type, true);
1821                                 }
1822
1823                                 break;
1824                         }
1825
1826                         return null;
1827                 }
1828
1829                 /// <summary>
1830                 ///  Returns whether an explicit reference conversion can be performed
1831                 ///  from source_type to target_type
1832                 /// </summary>
1833                 public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
1834                 {
1835                         Expression e = ExplicitReferenceConversion (null, source_type, target_type);
1836                         if (e == null)
1837                                 return false;
1838
1839                         if (e == EmptyExpression.Null)
1840                                 return true;
1841
1842                         throw new InternalErrorException ("Invalid probing conversion result");
1843                 }
1844
1845                 /// <summary>
1846                 ///   Implements Explicit Reference conversions
1847                 /// </summary>
1848                 static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
1849                 {
1850                         //
1851                         // From object to a generic parameter
1852                         //
1853                         if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object && TypeManager.IsGenericParameter (target_type))
1854                                 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1855
1856                         //
1857                         // Explicit type parameter conversion from T
1858                         //
1859                         if (source_type.Kind == MemberKind.TypeParameter)
1860                                 return ExplicitTypeParameterConversionFromT (source, source_type, target_type);
1861
1862                         bool target_is_value_type = target_type.Kind == MemberKind.Struct || target_type.Kind == MemberKind.Enum;
1863
1864                         //
1865                         // Unboxing conversion from System.ValueType to any non-nullable-value-type
1866                         //
1867                         if (source_type.BuiltinType == BuiltinTypeSpec.Type.ValueType && target_is_value_type)
1868                                 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1869
1870                         //
1871                         // From object or dynamic to any reference type or value type (unboxing)
1872                         //
1873                         if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object || source_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1874                                 if (target_type.IsPointer)
1875                                         return null;
1876
1877                                 return
1878                                         source == null ? EmptyExpression.Null :
1879                                         target_is_value_type ? new UnboxCast (source, target_type) :
1880                                         source is Constant ? (Expression) new EmptyConstantCast ((Constant) source, target_type) :
1881                                         new ClassCast (source, target_type);
1882                         }
1883
1884                         //
1885                         // From any class S to any class-type T, provided S is a base class of T
1886                         //
1887                         if (source_type.Kind == MemberKind.Class && TypeSpec.IsBaseClass (target_type, source_type, true))
1888                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1889
1890                         //
1891                         // From any interface-type S to to any class type T, provided T is not
1892                         // sealed, or provided T implements S.
1893                         //
1894                         // This also covers Explicit conversions involving type parameters
1895                         // section From any interface type to T
1896                         //
1897                         if (source_type.Kind == MemberKind.Interface) {
1898                                 if (!target_type.IsSealed || target_type.ImplementsInterface (source_type, true)) {
1899                                         if (source == null)
1900                                                 return EmptyExpression.Null;
1901
1902                                         //
1903                                         // Unboxing conversion from any interface-type to any non-nullable-value-type that
1904                                         // implements the interface-type
1905                                         //
1906                                         return target_is_value_type ? new UnboxCast (source, target_type) : (Expression) new ClassCast (source, target_type);
1907                                 }
1908
1909                                 //
1910                                 // From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
1911                                 // array type S[], provided there is an implicit or explicit reference conversion from S to T.
1912                                 //
1913                                 var target_array = target_type as ArrayContainer;
1914                                 if (target_array != null && IList_To_Array (source_type, target_array))
1915                                         return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1916
1917                                 return null;
1918                         }
1919
1920                         var source_array = source_type as ArrayContainer;
1921                         if (source_array != null) {
1922                                 var target_array = target_type as ArrayContainer;
1923                                 if (target_array != null) {
1924                                         //
1925                                         // From System.Array to any array-type
1926                                         //
1927                                         if (source_type.BuiltinType == BuiltinTypeSpec.Type.Array)
1928                                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1929
1930                                         //
1931                                         // From an array type S with an element type Se to an array type T with an
1932                                         // element type Te provided all the following are true:
1933                                         //     * S and T differe only in element type, in other words, S and T
1934                                         //       have the same number of dimensions.
1935                                         //     * Both Se and Te are reference types
1936                                         //     * An explicit reference conversions exist from Se to Te
1937                                         //
1938                                         if (source_array.Rank == target_array.Rank) {
1939
1940                                                 source_type = source_array.Element;
1941                                                 var target_element = target_array.Element;
1942
1943                                                 //
1944                                                 // LAMESPEC: Type parameters are special cased somehow but
1945                                                 // only when both source and target elements are type parameters
1946                                                 //
1947                                                 if ((source_type.Kind & target_element.Kind & MemberKind.TypeParameter) == MemberKind.TypeParameter) {
1948                                                         //
1949                                                         // Conversion is allowed unless source element type has struct constrain
1950                                                         //
1951                                                         if (TypeSpec.IsValueType (source_type))
1952                                                                 return null;
1953                                                 } else {
1954                                                         if (!TypeSpec.IsReferenceType (source_type))
1955                                                                 return null;
1956                                                 }
1957
1958                                                 if (!TypeSpec.IsReferenceType (target_element))
1959                                                         return null;
1960
1961                                                 if (ExplicitReferenceConversionExists (source_type, target_element))
1962                                                         return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1963                                                         
1964                                                 return null;
1965                                         }
1966                                 }
1967
1968                                 //
1969                                 // From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces, 
1970                                 // provided that there is an explicit reference conversion from S to T
1971                                 //
1972                                 if (ArrayToIList (source_array, target_type, true))
1973                                         return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1974
1975                                 return null;
1976                         }
1977
1978                         //
1979                         // From any class type S to any interface T, provides S is not sealed
1980                         // and provided S does not implement T.
1981                         //
1982                         if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type, true)) {
1983                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1984                         }
1985
1986                         //
1987                         // From System delegate to any delegate-type
1988                         //
1989                         if (source_type.BuiltinType == BuiltinTypeSpec.Type.Delegate && target_type.IsDelegate)
1990                                 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1991
1992                         //
1993                         // From variant generic delegate to same variant generic delegate type
1994                         //
1995                         if (source_type.IsDelegate && target_type.IsDelegate && source_type.MemberDefinition == target_type.MemberDefinition) {
1996                                 var tparams = source_type.MemberDefinition.TypeParameters;
1997                                 var targs_src = source_type.TypeArguments;
1998                                 var targs_dst = target_type.TypeArguments;
1999                                 int i;
2000                                 for (i = 0; i < tparams.Length; ++i) {
2001                                         //
2002                                         // If TP is invariant, types have to be identical
2003                                         //
2004                                         if (TypeSpecComparer.IsEqual (targs_src[i], targs_dst[i]))
2005                                                 continue;
2006
2007                                         if (tparams[i].Variance == Variance.Covariant) {
2008                                                 //
2009                                                 //If TP is covariant, an implicit or explicit identity or reference conversion is required
2010                                                 //
2011                                                 if (ImplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
2012                                                         continue;
2013
2014                                                 if (ExplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
2015                                                         continue;
2016
2017                                         } else if (tparams[i].Variance == Variance.Contravariant) {
2018                                                 //
2019                                                 //If TP is contravariant, both are either identical or reference types
2020                                                 //
2021                                                 if (TypeSpec.IsReferenceType (targs_src[i]) && TypeSpec.IsReferenceType (targs_dst[i]))
2022                                                         continue;
2023                                         }
2024
2025                                         break;
2026                                 }
2027
2028                                 if (i == tparams.Length)
2029                                         return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2030                         }
2031
2032                         var tps = target_type as TypeParameterSpec;
2033                         if (tps != null)
2034                                 return ExplicitTypeParameterConversionToT (source, source_type, tps);
2035
2036                         return null;
2037                 }
2038
2039                 /// <summary>
2040                 ///   Performs an explicit conversion of the expression `expr' whose
2041                 ///   type is expr.Type to `target_type'.
2042                 /// </summary>
2043                 static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
2044                                                                  TypeSpec target_type, Location loc)
2045                 {
2046                         TypeSpec expr_type = expr.Type;
2047
2048                         // Explicit conversion includes implicit conversion and it used for enum underlying types too
2049                         Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
2050                         if (ne != null)
2051                                 return ne;
2052
2053                         if (expr_type.IsEnum) {
2054                                 TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
2055                                 Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
2056                                 if (underlying.Type == real_target)
2057                                         ne = underlying;
2058
2059                                 if (ne == null)
2060                                         ne = ImplicitNumericConversion (underlying, real_target);
2061
2062                                 if (ne == null)
2063                                         ne = ExplicitNumericConversion (ec, underlying, real_target);
2064
2065                                 //
2066                                 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
2067                                 //
2068                                 if (ne == null && (real_target.BuiltinType == BuiltinTypeSpec.Type.IntPtr || real_target.BuiltinType == BuiltinTypeSpec.Type.UIntPtr))
2069                                         ne = ExplicitUserConversion (ec, underlying, real_target, loc);
2070
2071                                 return ne != null ? EmptyCast.Create (ne, target_type) : null;
2072                         }
2073
2074                         if (target_type.IsEnum) {
2075                                 //
2076                                 // System.Enum can be unboxed to any enum-type
2077                                 //
2078                                 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Enum)
2079                                         return new UnboxCast (expr, target_type);
2080
2081                                 TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
2082
2083                                 if (expr_type == real_target)
2084                                         return EmptyCast.Create (expr, target_type);
2085
2086                                 Constant c = expr as Constant;
2087                                 if (c != null) {
2088                                         c = c.TryReduce (ec, real_target);
2089                                         if (c != null)
2090                                                 return c;
2091                                 } else {
2092                                         ne = ImplicitNumericConversion (expr, real_target);
2093                                         if (ne != null)
2094                                                 return EmptyCast.Create (ne, target_type);
2095
2096                                         ne = ExplicitNumericConversion (ec, expr, real_target);
2097                                         if (ne != null)
2098                                                 return EmptyCast.Create (ne, target_type);
2099
2100                                         //
2101                                         // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
2102                                         //
2103                                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.IntPtr || expr_type.BuiltinType == BuiltinTypeSpec.Type.UIntPtr) {
2104                                                 ne = ExplicitUserConversion (ec, expr, real_target, loc);
2105                                                 if (ne != null)
2106                                                         return ExplicitConversionCore (ec, ne, target_type, loc);
2107                                         }
2108                                 }
2109                         } else {
2110                                 ne = ExplicitNumericConversion (ec, expr, target_type);
2111                                 if (ne != null)
2112                                         return ne;
2113                         }
2114
2115                         //
2116                         // Skip the ExplicitReferenceConversion because we can not convert
2117                         // from Null to a ValueType, and ExplicitReference wont check against
2118                         // null literal explicitly
2119                         //
2120                         if (expr_type != InternalType.NullLiteral) {
2121                                 ne = ExplicitReferenceConversion (expr, expr_type, target_type);
2122                                 if (ne != null)
2123                                         return ne;
2124                         }
2125
2126                         if (ec.IsUnsafe){
2127                                 ne = ExplicitUnsafe (expr, target_type);
2128                                 if (ne != null)
2129                                         return ne;
2130                         }
2131                         
2132                         return null;
2133                 }
2134
2135                 public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
2136                 {
2137                         TypeSpec expr_type = expr.Type;
2138
2139                         if (target_type.IsPointer){
2140                                 if (expr_type.IsPointer)
2141                                         return EmptyCast.Create (expr, target_type);
2142
2143                                 switch (expr_type.BuiltinType) {
2144                                 case BuiltinTypeSpec.Type.SByte:
2145                                 case BuiltinTypeSpec.Type.Short:
2146                                 case BuiltinTypeSpec.Type.Int:
2147                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
2148
2149                                 case BuiltinTypeSpec.Type.UShort:
2150                                 case BuiltinTypeSpec.Type.UInt:
2151                                 case BuiltinTypeSpec.Type.Byte:
2152                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2153
2154                                 case BuiltinTypeSpec.Type.Long:
2155                                         return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);
2156
2157                                 case BuiltinTypeSpec.Type.ULong:
2158                                         return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
2159                                 }
2160                         }
2161
2162                         if (expr_type.IsPointer){
2163                                 switch (target_type.BuiltinType) {
2164                                 case BuiltinTypeSpec.Type.SByte:
2165                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
2166                                 case BuiltinTypeSpec.Type.Byte:
2167                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
2168                                 case BuiltinTypeSpec.Type.Short:
2169                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
2170                                 case BuiltinTypeSpec.Type.UShort:
2171                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
2172                                 case BuiltinTypeSpec.Type.Int:
2173                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
2174                                 case BuiltinTypeSpec.Type.UInt:
2175                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
2176                                 case BuiltinTypeSpec.Type.Long:
2177                                         return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
2178                                 case BuiltinTypeSpec.Type.ULong:
2179                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
2180                                 }
2181                         }
2182                         return null;
2183                 }
2184
2185                 /// <summary>
2186                 ///   Same as ExplicitConversion, only it doesn't include user defined conversions
2187                 /// </summary>
2188                 static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
2189                                                                      TypeSpec target_type, Location l)
2190                 {
2191                         int errors = ec.Report.Errors;
2192                         Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
2193                         if (ec.Report.Errors > errors)
2194                                 return null;
2195
2196                         if (ne != null)
2197                                 return ne;
2198
2199                         ne = ExplicitNumericConversion (ec, expr, target_type);
2200                         if (ne != null)
2201                                 return ne;
2202
2203                         ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
2204                         if (ne != null)
2205                                 return ne;
2206
2207                         if (ec.IsUnsafe && expr.Type.IsPointer && target_type.IsPointer && ((PointerContainer)expr.Type).Element.Kind == MemberKind.Void)
2208                                 return EmptyCast.Create (expr, target_type);
2209
2210                         expr.Error_ValueCannotBeConverted (ec, target_type, true);
2211                         return null;
2212                 }
2213
2214                 /// <summary>
2215                 ///   Performs an explicit conversion of the expression `expr' whose
2216                 ///   type is expr.Type to `target_type'.
2217                 /// </summary>
2218                 static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
2219                         TypeSpec target_type, Location loc)
2220                 {
2221                         Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
2222                         if (e != null) {
2223                                 //
2224                                 // Don't eliminate explicit precission casts
2225                                 //
2226                                 if (e == expr) {
2227                                         if (target_type.BuiltinType == BuiltinTypeSpec.Type.Float)
2228                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
2229                                         
2230                                         if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
2231                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
2232                                 }
2233                                         
2234                                 return e;
2235                         }
2236
2237                         TypeSpec expr_type = expr.Type;
2238                         if (target_type.IsNullableType) {
2239                                 TypeSpec target;
2240
2241                                 if (expr_type.IsNullableType) {
2242                                         target = Nullable.NullableInfo.GetUnderlyingType (target_type);
2243                                         Expression unwrap = Nullable.Unwrap.Create (expr);
2244                                         e = ExplicitConversion (ec, unwrap, target, expr.Location);
2245                                         if (e == null)
2246                                                 return null;
2247
2248                                         return new Nullable.LiftedConversion (e, unwrap, target_type).Resolve (ec);
2249                                 }
2250                                 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
2251                                         return new UnboxCast (expr, target_type);
2252                                 }
2253
2254                                 target = TypeManager.GetTypeArguments (target_type) [0];
2255                                 e = ExplicitConversionCore (ec, expr, target, loc);
2256                                 if (e != null)
2257                                         return TypeSpec.IsReferenceType (expr.Type) ? new UnboxCast (expr, target_type) : Nullable.Wrap.Create (e, target_type);
2258                         } else if (expr_type.IsNullableType) {
2259                                 e = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
2260                                 if (e != null)
2261                                         return e;
2262
2263                                 e = Nullable.Unwrap.Create (expr, false);                       
2264                                 e = ExplicitConversionCore (ec, e, target_type, loc);
2265                                 if (e != null)
2266                                         return EmptyCast.Create (e, target_type);
2267                         }
2268                         
2269                         e = ExplicitUserConversion (ec, expr, target_type, loc);
2270
2271                         if (e != null)
2272                                 return e;                       
2273
2274                         expr.Error_ValueCannotBeConverted (ec, target_type, true);
2275                         return null;
2276                 }
2277         }
2278 }