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