2 // conversion.cs: various routines for implementing conversions.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Ravi Pratap (ravi@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Copyright 2001, 2002, 2003 Ximian, Inc.
10 // Copyright 2003-2008 Novell, Inc.
11 // Copyright 2011 Xamarin Inc (http://www.xamarin.com)
15 using System.Collections.Generic;
18 using IKVM.Reflection.Emit;
20 using System.Reflection.Emit;
23 namespace Mono.CSharp {
26 // A container class for all the conversion operations
31 public enum UserConversionRestriction
36 NullableSourceOnly = 1 << 2
40 // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
41 // interfaces of this interface, provided there is an implicit reference conversion
44 static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
46 if (array.Rank != 1 || !list.IsArrayGenericInterface)
49 var arg_type = list.TypeArguments[0];
50 if (array.Element == arg_type)
54 // Reject conversion from T[] to IList<U> even if T has U dependency
56 if (arg_type.IsGenericParameter)
60 return ExplicitReferenceConversionExists (array.Element, arg_type);
62 return ImplicitReferenceConversionExists (array.Element, arg_type);
65 static bool IList_To_Array(TypeSpec list, ArrayContainer array)
67 if (array.Rank != 1 || !list.IsArrayGenericInterface)
70 var arg_type = list.TypeArguments[0];
71 if (array.Element == arg_type)
74 return ImplicitReferenceConversionExists (array.Element, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
77 public static Expression ImplicitTypeParameterConversion (Expression expr, TypeParameterSpec expr_type, TypeSpec target_type)
80 // From T to a type parameter U, provided T depends on U
82 if (target_type.IsGenericParameter) {
83 if (expr_type.TypeArguments != null && expr_type.HasDependencyOn (target_type)) {
85 return EmptyExpression.Null;
87 if (expr_type.IsReferenceType && !((TypeParameterSpec) target_type).IsReferenceType)
88 return new BoxedCast (expr, target_type);
90 return new ClassCast (expr, target_type);
97 // LAMESPEC: From T to dynamic type because it's like T to object
99 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
101 return EmptyExpression.Null;
103 if (expr_type.IsReferenceType)
104 return new ClassCast (expr, target_type);
106 return new BoxedCast (expr, target_type);
110 // From T to its effective base class C
111 // From T to any base class of C (it cannot contain dynamic or be of dynamic type)
112 // From T to any interface implemented by C
114 var base_type = expr_type.GetEffectiveBase ();
115 if (base_type == target_type || TypeSpec.IsBaseClass (base_type, target_type, false) || base_type.ImplementsInterface (target_type, true)) {
117 return EmptyExpression.Null;
119 if (expr_type.IsReferenceType)
120 return new ClassCast (expr, target_type);
122 return new BoxedCast (expr, target_type);
125 if (target_type.IsInterface && expr_type.IsConvertibleToInterface (target_type)) {
127 return EmptyExpression.Null;
129 if (expr_type.IsReferenceType)
130 return new ClassCast (expr, target_type);
132 return new BoxedCast (expr, target_type);
138 static Expression ExplicitTypeParameterConversionFromT (Expression source, TypeSpec source_type, TypeSpec target_type)
140 var target_tp = target_type as TypeParameterSpec;
141 if (target_tp != null) {
143 // From a type parameter U to T, provided T depends on U
145 if (target_tp.TypeArguments != null && target_tp.HasDependencyOn (source_type)) {
146 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
151 // From T to any interface-type I provided there is not already an implicit conversion from T to I
153 if (target_type.IsInterface)
154 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
159 static Expression ExplicitTypeParameterConversionToT (Expression source, TypeSpec source_type, TypeParameterSpec target_type)
162 // From the effective base class C of T to T and from any base class of C to T
164 var effective = target_type.GetEffectiveBase ();
165 if (TypeSpecComparer.IsEqual (effective, source_type) || TypeSpec.IsBaseClass (effective, source_type, false))
166 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
171 public static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
173 TypeSpec expr_type = expr.Type;
175 if (expr_type.Kind == MemberKind.TypeParameter)
176 return ImplicitTypeParameterConversion (expr, (TypeParameterSpec) expr.Type, target_type);
179 // from the null type to any reference-type.
181 NullLiteral nl = expr as NullLiteral;
183 return nl.ConvertImplicitly (target_type);
186 if (ImplicitReferenceConversionExists (expr_type, target_type)) {
188 // Avoid wrapping implicitly convertible reference type
193 return EmptyCast.Create (expr, target_type);
200 // Implicit reference conversions
202 public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type)
204 return ImplicitReferenceConversionExists (expr_type, target_type, true);
207 public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type, bool refOnlyTypeParameter)
209 // It's here only to speed things up
210 if (target_type.IsStruct)
213 switch (expr_type.Kind) {
214 case MemberKind.TypeParameter:
215 return ImplicitTypeParameterConversion (null, (TypeParameterSpec) expr_type, target_type) != null &&
216 (!refOnlyTypeParameter || TypeSpec.IsReferenceType (expr_type));
218 case MemberKind.Class:
220 // From any class-type to dynamic (+object to speed up common path)
222 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
225 if (target_type.IsClass) {
227 // Identity conversion, including dynamic erasure
229 if (TypeSpecComparer.IsEqual (expr_type, target_type))
233 // From any class-type S to any class-type T, provided S is derived from T
235 return TypeSpec.IsBaseClass (expr_type, target_type, true);
239 // From any class-type S to any interface-type T, provided S implements T
241 if (target_type.IsInterface)
242 return expr_type.ImplementsInterface (target_type, true);
246 case MemberKind.ArrayType:
248 // Identity array conversion
250 if (expr_type == target_type)
254 // From any array-type to System.Array
256 switch (target_type.BuiltinType) {
257 case BuiltinTypeSpec.Type.Array:
258 case BuiltinTypeSpec.Type.Object:
259 case BuiltinTypeSpec.Type.Dynamic:
263 var expr_type_array = (ArrayContainer) expr_type;
264 var target_type_array = target_type as ArrayContainer;
267 // From an array-type S to an array-type of type T
269 if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {
272 // Both SE and TE are reference-types. TE check is defered
273 // to ImplicitReferenceConversionExists
275 TypeSpec expr_element_type = expr_type_array.Element;
276 if (!TypeSpec.IsReferenceType (expr_element_type))
280 // An implicit reference conversion exists from SE to TE
282 return ImplicitReferenceConversionExists (expr_element_type, target_type_array.Element);
286 // From any array-type to the interfaces it implements
288 if (target_type.IsInterface) {
289 if (expr_type.ImplementsInterface (target_type, false))
292 // from an array-type of type T to IList<T>
293 if (ArrayToIList (expr_type_array, target_type, false))
299 case MemberKind.Delegate:
301 // From any delegate-type to System.Delegate (and its base types)
303 switch (target_type.BuiltinType) {
304 case BuiltinTypeSpec.Type.Delegate:
305 case BuiltinTypeSpec.Type.MulticastDelegate:
306 case BuiltinTypeSpec.Type.Object:
307 case BuiltinTypeSpec.Type.Dynamic:
312 // Identity conversion, including dynamic erasure
314 if (TypeSpecComparer.IsEqual (expr_type, target_type))
318 // From any delegate-type to the interfaces it implements
319 // From any reference-type to an delegate type if is variance-convertible
321 return expr_type.ImplementsInterface (target_type, false) || TypeSpecComparer.Variant.IsEqual (expr_type, target_type);
323 case MemberKind.Interface:
325 // Identity conversion, including dynamic erasure
327 if (TypeSpecComparer.IsEqual (expr_type, target_type))
331 // From any interface type S to interface-type T
332 // From any reference-type to an interface if is variance-convertible
334 if (target_type.IsInterface)
335 return TypeSpecComparer.Variant.IsEqual (expr_type, target_type) || expr_type.ImplementsInterface (target_type, true);
337 return target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
339 case MemberKind.InternalCompilerType:
341 // from the null literal to any reference-type.
343 if (expr_type == InternalType.NullLiteral) {
344 // Exlude internal compiler types
345 if (target_type.Kind == MemberKind.InternalCompilerType)
346 return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
348 return TypeSpec.IsReferenceType (target_type) || target_type.Kind == MemberKind.PointerType;
352 // Implicit dynamic conversion
354 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
355 switch (target_type.Kind) {
356 case MemberKind.ArrayType:
357 case MemberKind.Class:
358 case MemberKind.Delegate:
359 case MemberKind.Interface:
360 case MemberKind.TypeParameter:
364 // dynamic to __arglist
365 if (target_type == InternalType.Arglist)
377 public static Expression ImplicitBoxingConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
379 switch (target_type.BuiltinType) {
381 // From any non-nullable-value-type to the type object and dynamic
383 case BuiltinTypeSpec.Type.Object:
384 case BuiltinTypeSpec.Type.Dynamic:
386 // From any non-nullable-value-type to the type System.ValueType
388 case BuiltinTypeSpec.Type.ValueType:
390 // No ned to check for nullable type as underlying type is always convertible
392 if (!TypeSpec.IsValueType (expr_type))
395 return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
397 case BuiltinTypeSpec.Type.Enum:
399 // From any enum-type to the type System.Enum.
401 if (expr_type.IsEnum)
402 return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
408 // From a nullable-type to a reference type, if a boxing conversion exists from
409 // the underlying type to the reference type
411 if (expr_type.IsNullableType) {
412 if (!TypeSpec.IsReferenceType (target_type))
415 var res = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
417 // "cast" underlying type to target type to emit correct InvalidCastException when
418 // underlying hierarchy changes without recompilation
419 if (res != null && expr != null)
420 res = new UnboxCast (res, target_type);
426 // A value type has a boxing conversion to an interface type I if it has a boxing conversion
427 // to an interface or delegate type I0 and I0 is variance-convertible to I
429 if (target_type.IsInterface && TypeSpec.IsValueType (expr_type) && expr_type.ImplementsInterface (target_type, true)) {
430 return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
436 public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
438 TypeSpec expr_type = expr.Type;
441 // From null to any nullable type
443 if (expr_type == InternalType.NullLiteral)
444 return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
447 TypeSpec t_el = Nullable.NullableInfo.GetUnderlyingType (target_type);
450 if (expr_type.IsNullableType)
451 expr_type = Nullable.NullableInfo.GetUnderlyingType (expr_type);
454 // Predefined implicit identity or implicit numeric conversion
455 // has to exist between underlying type S and underlying type T
458 // conversion exists only mode
460 if (TypeSpecComparer.IsEqual (expr_type, t_el))
461 return EmptyExpression.Null;
463 if (expr is Constant)
464 return ((Constant) expr).ConvertImplicitly (t_el);
466 return ImplicitNumericConversion (null, expr_type, t_el);
470 if (expr_type != expr.Type)
471 unwrap = Nullable.Unwrap.Create (expr);
475 Expression conv = unwrap;
476 if (!TypeSpecComparer.IsEqual (expr_type, t_el)) {
477 if (conv is Constant)
478 conv = ((Constant)conv).ConvertImplicitly (t_el);
480 conv = ImplicitNumericConversion (conv, expr_type, t_el);
486 if (expr_type != expr.Type)
487 return new Nullable.LiftedConversion (conv, unwrap, target_type).Resolve (ec);
489 return Nullable.Wrap.Create (conv, target_type);
493 /// Implicit Numeric Conversions.
495 /// expr is the expression to convert, returns a new expression of type
496 /// target_type or null if an implicit conversion is not possible.
498 public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
500 return ImplicitNumericConversion (expr, expr.Type, target_type);
503 public static bool ImplicitNumericConversionExists (TypeSpec expr_type, TypeSpec target_type)
505 return ImplicitNumericConversion (null, expr_type, target_type) != null;
508 static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
510 switch (expr_type.BuiltinType) {
511 case BuiltinTypeSpec.Type.SByte:
513 // From sbyte to short, int, long, float, double, decimal
515 switch (target_type.BuiltinType) {
516 case BuiltinTypeSpec.Type.Int:
517 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
518 case BuiltinTypeSpec.Type.Long:
519 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
520 case BuiltinTypeSpec.Type.Double:
521 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
522 case BuiltinTypeSpec.Type.Float:
523 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
524 case BuiltinTypeSpec.Type.Short:
525 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
526 case BuiltinTypeSpec.Type.Decimal:
527 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
532 case BuiltinTypeSpec.Type.Byte:
534 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
536 switch (target_type.BuiltinType) {
537 case BuiltinTypeSpec.Type.Int:
538 case BuiltinTypeSpec.Type.UInt:
539 case BuiltinTypeSpec.Type.Short:
540 case BuiltinTypeSpec.Type.UShort:
541 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
542 case BuiltinTypeSpec.Type.ULong:
543 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
544 case BuiltinTypeSpec.Type.Long:
545 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
546 case BuiltinTypeSpec.Type.Float:
547 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
548 case BuiltinTypeSpec.Type.Double:
549 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
550 case BuiltinTypeSpec.Type.Decimal:
551 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
554 case BuiltinTypeSpec.Type.Short:
556 // From short to int, long, float, double, decimal
558 switch (target_type.BuiltinType) {
559 case BuiltinTypeSpec.Type.Int:
560 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
561 case BuiltinTypeSpec.Type.Long:
562 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
563 case BuiltinTypeSpec.Type.Double:
564 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
565 case BuiltinTypeSpec.Type.Float:
566 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
567 case BuiltinTypeSpec.Type.Decimal:
568 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
571 case BuiltinTypeSpec.Type.UShort:
573 // From ushort to int, uint, long, ulong, float, double, decimal
575 switch (target_type.BuiltinType) {
576 case BuiltinTypeSpec.Type.Int:
577 case BuiltinTypeSpec.Type.UInt:
578 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
579 case BuiltinTypeSpec.Type.ULong:
580 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
581 case BuiltinTypeSpec.Type.Long:
582 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
583 case BuiltinTypeSpec.Type.Double:
584 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
585 case BuiltinTypeSpec.Type.Float:
586 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
587 case BuiltinTypeSpec.Type.Decimal:
588 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
591 case BuiltinTypeSpec.Type.Int:
593 // From int to long, float, double, decimal
595 switch (target_type.BuiltinType) {
596 case BuiltinTypeSpec.Type.Long:
597 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
598 case BuiltinTypeSpec.Type.Double:
599 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
600 case BuiltinTypeSpec.Type.Float:
601 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
602 case BuiltinTypeSpec.Type.Decimal:
603 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
606 case BuiltinTypeSpec.Type.UInt:
608 // From uint to long, ulong, float, double, decimal
610 switch (target_type.BuiltinType) {
611 case BuiltinTypeSpec.Type.Long:
612 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
613 case BuiltinTypeSpec.Type.ULong:
614 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
615 case BuiltinTypeSpec.Type.Double:
616 return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
617 case BuiltinTypeSpec.Type.Float:
618 return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
619 case BuiltinTypeSpec.Type.Decimal:
620 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
623 case BuiltinTypeSpec.Type.Long:
625 // From long to float, double, decimal
627 switch (target_type.BuiltinType) {
628 case BuiltinTypeSpec.Type.Double:
629 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
630 case BuiltinTypeSpec.Type.Float:
631 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
632 case BuiltinTypeSpec.Type.Decimal:
633 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
636 case BuiltinTypeSpec.Type.ULong:
638 // From ulong to float, double, decimal
640 switch (target_type.BuiltinType) {
641 case BuiltinTypeSpec.Type.Double:
642 return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
643 case BuiltinTypeSpec.Type.Float:
644 return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
645 case BuiltinTypeSpec.Type.Decimal:
646 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
649 case BuiltinTypeSpec.Type.Char:
651 // From char to ushort, int, uint, long, ulong, float, double, decimal
653 switch (target_type.BuiltinType) {
654 case BuiltinTypeSpec.Type.UShort:
655 case BuiltinTypeSpec.Type.Int:
656 case BuiltinTypeSpec.Type.UInt:
657 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
658 case BuiltinTypeSpec.Type.ULong:
659 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
660 case BuiltinTypeSpec.Type.Long:
661 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
662 case BuiltinTypeSpec.Type.Float:
663 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
664 case BuiltinTypeSpec.Type.Double:
665 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
666 case BuiltinTypeSpec.Type.Decimal:
667 return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
670 case BuiltinTypeSpec.Type.Float:
674 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
675 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
682 static Expression ImplicitTupleLiteralConversion (ResolveContext rc, Expression source, TypeSpec targetType, Location loc)
684 var targetTypeArgument = targetType.TypeArguments;
685 if (source.Type.Arity != targetTypeArgument.Length)
688 var namedTarget = targetType as NamedTupleSpec;
689 var tupleLiteral = source as TupleLiteral;
692 if (tupleLiteral == null && !ExpressionAnalyzer.IsInexpensiveLoad (source)) {
693 var expr_variable = LocalVariable.CreateCompilerGenerated (source.Type, rc.CurrentBlock, loc);
694 source = new CompilerAssign (expr_variable.CreateReferenceExpression (rc, loc), source, loc);
695 instance = expr_variable.CreateReferenceExpression (rc, loc);
700 var converted = new List<Expression> (targetType.Arity);
701 for (int i = 0; i < targetType.Arity; ++i) {
702 Expression elementSrc;
703 if (tupleLiteral != null) {
704 elementSrc = tupleLiteral.Elements [i].Expr;
706 if (namedTarget != null) {
707 var elementSrcName = tupleLiteral.Elements [i].Name;
708 if (elementSrcName != null && elementSrcName != namedTarget.Elements [i]) {
709 rc.Report.Warning (8123, 1, loc,
710 "The tuple element name `{0}' is ignored because a different name or no name is specified by the target type `{1}'",
711 elementSrcName, namedTarget.GetSignatureForErrorWithNames ());
715 elementSrc = new MemberAccess (instance, NamedTupleSpec.GetElementPropertyName (i)).Resolve (rc);
718 var res = ImplicitConversionStandard (rc, elementSrc, targetTypeArgument [i], loc);
725 return new TupleLiteralConversion (source, targetType, converted, loc);
728 static bool ImplicitTupleLiteralConversionExists (Expression source, TypeSpec targetType)
730 if (source.Type.Arity != targetType.Arity)
733 var srcTypeArgument = source.Type.TypeArguments;
734 var targetTypeArgument = targetType.TypeArguments;
736 var tupleLiteralElements = (source as TupleLiteral)?.Elements;
738 for (int i = 0; i < targetType.Arity; ++i) {
739 var elementType = srcTypeArgument [i];
741 if (tupleLiteralElements != null) {
742 if (!ImplicitStandardConversionExists (tupleLiteralElements[i].Expr, targetTypeArgument [i])) {
746 if (!ImplicitStandardConversionExists (new EmptyExpression (srcTypeArgument [i]), targetTypeArgument [i])) {
757 // Full version of implicit conversion
759 public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
761 if (ImplicitStandardConversionExists (ec, expr, target_type))
764 if (expr.Type == InternalType.AnonymousMethod) {
765 if (!target_type.IsDelegate && !target_type.IsExpressionTreeType)
768 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
769 return ame.ImplicitStandardConversionExists (ec, target_type);
772 // Conversion from __arglist to System.ArgIterator
773 if (expr.Type == InternalType.Arglist)
774 return target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec;
776 return UserDefinedConversion (ec, expr, target_type,
777 UserConversionRestriction.ImplicitOnly | UserConversionRestriction.ProbingOnly, Location.Null) != null;
780 public static bool ImplicitStandardConversionExists (ResolveContext rc, Expression expr, TypeSpec target_type)
782 if (expr.eclass == ExprClass.MethodGroup) {
783 if (target_type.IsDelegate && rc.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
784 MethodGroupExpr mg = expr as MethodGroupExpr;
786 return DelegateCreation.ImplicitStandardConversionExists (rc, mg, target_type);
792 var interpolated_string = expr as InterpolatedString;
793 if (interpolated_string != null) {
794 if (target_type == rc.Module.PredefinedTypes.IFormattable.TypeSpec || target_type == rc.Module.PredefinedTypes.FormattableString.TypeSpec)
798 return ImplicitStandardConversionExists (expr, target_type);
802 // Implicit standard conversion (only core conversions are used here)
804 public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
807 // Identity conversions
808 // Implicit numeric conversions
809 // Implicit nullable conversions
810 // Implicit reference conversions
811 // Boxing conversions
812 // Implicit constant expression conversions
813 // Implicit conversions involving type parameters
816 TypeSpec expr_type = expr.Type;
818 if (expr_type == target_type)
821 if (expr_type == InternalType.ThrowExpr)
822 return target_type.Kind != MemberKind.InternalCompilerType;
824 if (target_type.IsNullableType)
825 return ImplicitNulableConversion (null, expr, target_type) != null;
827 if (ImplicitNumericConversion (null, expr_type, target_type) != null)
830 if (ImplicitReferenceConversionExists (expr_type, target_type, false))
833 if (ImplicitBoxingConversion (null, expr_type, target_type) != null)
836 if (expr_type.IsTupleType && target_type.IsTupleType)
837 return ImplicitTupleLiteralConversionExists (expr, target_type);
840 // Implicit Constant Expression Conversions
842 if (expr is IntConstant){
843 int value = ((IntConstant) expr).Value;
844 switch (target_type.BuiltinType) {
845 case BuiltinTypeSpec.Type.SByte:
846 if (value >= SByte.MinValue && value <= SByte.MaxValue)
849 case BuiltinTypeSpec.Type.Byte:
850 if (value >= 0 && value <= Byte.MaxValue)
853 case BuiltinTypeSpec.Type.Short:
854 if (value >= Int16.MinValue && value <= Int16.MaxValue)
857 case BuiltinTypeSpec.Type.UShort:
858 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
861 case BuiltinTypeSpec.Type.UInt:
865 case BuiltinTypeSpec.Type.ULong:
867 // we can optimize this case: a positive int32
868 // always fits on a uint64. But we need an opcode
878 if (expr is LongConstant && target_type.BuiltinType == BuiltinTypeSpec.Type.ULong){
880 // Try the implicit constant expression conversion
881 // from long to ulong, instead of a nice routine,
884 long v = ((LongConstant) expr).Value;
889 if (expr is IntegralConstant && target_type.IsEnum) {
890 var i = (IntegralConstant) expr;
892 // LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
894 // An implicit enumeration conversion permits the decimal-integer-literal 0
895 // to be converted to any enum-type and to any nullable-type whose underlying
896 // type is an enum-type
898 return i.IsZeroInteger;
902 // Implicit dynamic conversion for remaining value types. It should probably
905 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
906 switch (target_type.Kind) {
907 case MemberKind.Struct:
908 case MemberKind.Enum:
916 // In an unsafe context implicit conversions is extended to include
918 // From any pointer-type to the type void*
919 // From the null literal to any pointer-type.
921 // LAMESPEC: The specification claims this conversion is allowed in implicit conversion but
922 // in reality implicit standard conversion uses it
924 if (target_type.IsPointer && expr.Type.IsPointer && ((PointerContainer) target_type).Element.Kind == MemberKind.Void)
928 // Struct identity conversion, including dynamic erasure
930 if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
937 /// Finds "most encompassed type" according to the spec (13.4.2)
938 /// amongst the methods in the MethodGroupExpr
940 public static TypeSpec FindMostEncompassedType (IList<TypeSpec> types)
942 TypeSpec best = null;
943 EmptyExpression expr;
945 foreach (TypeSpec t in types) {
951 expr = new EmptyExpression (t);
952 if (ImplicitStandardConversionExists (expr, best))
956 expr = new EmptyExpression (best);
957 foreach (TypeSpec t in types) {
960 if (!ImplicitStandardConversionExists (expr, t)) {
970 // Finds the most encompassing type (type into which all other
971 // types can convert to) amongst the types in the given set
973 static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
975 if (types.Count == 0)
978 if (types.Count == 1)
981 TypeSpec best = null;
982 for (int i = 0; i < types.Count; ++i) {
984 for (; ii < types.Count; ++ii) {
988 var expr = new EmptyExpression (types[ii]);
989 if (!ImplicitStandardConversionExists (expr, types [i])) {
1003 // Indicates multiple best types
1004 return InternalType.FakeInternalType;
1011 // Finds the most specific source Sx according to the rules of the spec (13.4.4)
1012 // by making use of FindMostEncomp* methods. Applies the correct rules separately
1013 // for explicit and implicit conversion operators.
1015 static TypeSpec FindMostSpecificSource (ResolveContext rc, List<MethodSpec> list, TypeSpec sourceType, Expression source, bool apply_explicit_conv_rules)
1017 TypeSpec[] src_types_set = null;
1020 // Try exact match first, if any operator converts from S then Sx = S
1022 for (int i = 0; i < list.Count; ++i) {
1023 TypeSpec param_type = list [i].Parameters.Types [0];
1025 if (param_type == sourceType)
1028 if (src_types_set == null)
1029 src_types_set = new TypeSpec [list.Count];
1031 src_types_set [i] = param_type;
1035 // Explicit Conv rules
1037 if (apply_explicit_conv_rules) {
1038 var candidate_set = new List<TypeSpec> ();
1040 foreach (TypeSpec param_type in src_types_set){
1041 if (ImplicitStandardConversionExists (rc, source, param_type))
1042 candidate_set.Add (param_type);
1045 if (candidate_set.Count != 0) {
1046 if (source.eclass == ExprClass.MethodGroup)
1047 return InternalType.FakeInternalType;
1049 return FindMostEncompassedType (candidate_set);
1056 if (apply_explicit_conv_rules)
1057 return FindMostEncompassingType (src_types_set);
1059 return FindMostEncompassedType (src_types_set);
1063 /// Finds the most specific target Tx according to section 13.4.4
1065 static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
1066 TypeSpec target, bool apply_explicit_conv_rules)
1068 List<TypeSpec> tgt_types_set = null;
1071 // If any operator converts to T then Tx = T
1073 foreach (var mi in list){
1074 TypeSpec ret_type = mi.ReturnType;
1075 if (ret_type == target)
1078 if (tgt_types_set == null) {
1079 tgt_types_set = new List<TypeSpec> (list.Count);
1080 } else if (tgt_types_set.Contains (ret_type)) {
1084 tgt_types_set.Add (ret_type);
1088 // Explicit conv rules
1090 if (apply_explicit_conv_rules) {
1091 var candidate_set = new List<TypeSpec> ();
1093 foreach (TypeSpec ret_type in tgt_types_set) {
1094 var expr = new EmptyExpression (ret_type);
1096 if (ImplicitStandardConversionExists (expr, target))
1097 candidate_set.Add (ret_type);
1100 if (candidate_set.Count != 0)
1101 return FindMostEncompassingType (candidate_set);
1105 // Okay, final case !
1107 if (apply_explicit_conv_rules)
1108 return FindMostEncompassedType (tgt_types_set);
1110 return FindMostEncompassingType (tgt_types_set);
1114 /// User-defined Implicit conversions
1116 static public Expression ImplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
1118 return UserDefinedConversion (ec, source, target, UserConversionRestriction.ImplicitOnly, loc);
1122 /// User-defined Explicit conversions
1124 static Expression ExplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
1126 return UserDefinedConversion (ec, source, target, 0, loc);
1129 static void FindApplicableUserDefinedConversionOperators (ResolveContext rc, IList<MemberSpec> operators, Expression source, TypeSpec target, UserConversionRestriction restr, ref List<MethodSpec> candidates)
1131 if (source.Type.IsInterface) {
1132 // Neither A nor B are interface-types
1136 // For a conversion operator to be applicable, it must be possible
1137 // to perform a standard conversion from the source type to
1138 // the operand type of the operator, and it must be possible
1139 // to perform a standard conversion from the result type of
1140 // the operator to the target type.
1142 Expression texpr = null;
1144 foreach (MethodSpec op in operators) {
1146 // Can be null because MemberCache.GetUserOperator does not resize the array
1150 var t = op.Parameters.Types[0];
1151 if (source.Type != t && !ImplicitStandardConversionExists (rc, source, t)) {
1152 if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
1155 if (!ImplicitStandardConversionExists (new EmptyExpression (t), source.Type))
1159 if ((restr & UserConversionRestriction.NullableSourceOnly) != 0 && !t.IsNullableType)
1168 if (t.IsNullableType)
1169 t = Nullable.NullableInfo.GetUnderlyingType (t);
1171 if (!ImplicitStandardConversionExists (new EmptyExpression (t), target)) {
1172 if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
1176 texpr = new EmptyExpression (target);
1178 if (!ImplicitStandardConversionExists (texpr, t))
1183 if (candidates == null)
1184 candidates = new List<MethodSpec> ();
1186 candidates.Add (op);
1191 // User-defined conversions
1193 public static Expression UserDefinedConversion (ResolveContext rc, Expression source, TypeSpec target, UserConversionRestriction restr, Location loc)
1195 List<MethodSpec> candidates = null;
1198 // If S or T are nullable types, source_type and target_type are their underlying types
1199 // otherwise source_type and target_type are equal to S and T respectively.
1201 TypeSpec source_type = source.Type;
1202 TypeSpec target_type = target;
1203 Expression source_type_expr;
1204 bool nullable_source = false;
1205 var implicitOnly = (restr & UserConversionRestriction.ImplicitOnly) != 0;
1207 if (source_type.IsNullableType) {
1208 // No unwrapping conversion S? -> T for non-reference types
1209 if (implicitOnly && !TypeSpec.IsReferenceType (target_type) && !target_type.IsNullableType) {
1210 source_type_expr = source;
1212 source_type_expr = Nullable.Unwrap.CreateUnwrapped (source);
1213 source_type = source_type_expr.Type;
1214 nullable_source = true;
1217 source_type_expr = source;
1220 if (target_type.IsNullableType)
1221 target_type = Nullable.NullableInfo.GetUnderlyingType (target_type);
1223 // Only these containers can contain a user defined implicit or explicit operators
1224 const MemberKind user_conversion_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.TypeParameter;
1226 if ((source_type.Kind & user_conversion_kinds) != 0 && source_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
1227 bool declared_only = source_type.IsStruct;
1229 var operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Implicit, declared_only);
1230 if (operators != null) {
1231 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1234 if (!implicitOnly) {
1235 operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Explicit, declared_only);
1236 if (operators != null) {
1237 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1242 if ((target.Kind & user_conversion_kinds) != 0 && target_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
1243 bool declared_only = target.IsStruct || implicitOnly;
1245 var operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Implicit, declared_only);
1246 if (operators != null) {
1247 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1250 if (!implicitOnly) {
1251 operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Explicit, declared_only);
1252 if (operators != null) {
1253 FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
1258 if (candidates == null)
1262 // Find the most specific conversion operator
1264 MethodSpec most_specific_operator;
1266 if (candidates.Count == 1) {
1267 most_specific_operator = candidates[0];
1268 s_x = most_specific_operator.Parameters.Types[0];
1269 t_x = most_specific_operator.ReturnType;
1272 // Pass original source type to find the best match against input type and
1273 // not the unwrapped expression
1275 s_x = FindMostSpecificSource (rc, candidates, source.Type, source_type_expr, !implicitOnly);
1279 t_x = FindMostSpecificTarget (candidates, target, !implicitOnly);
1283 most_specific_operator = null;
1284 for (int i = 0; i < candidates.Count; ++i) {
1285 if (candidates[i].ReturnType == t_x && candidates[i].Parameters.Types[0] == s_x) {
1286 most_specific_operator = candidates[i];
1291 if (most_specific_operator == null) {
1293 // Unless running in probing more
1295 if ((restr & UserConversionRestriction.ProbingOnly) == 0) {
1296 MethodSpec ambig_arg = candidates [0];
1297 most_specific_operator = candidates [1];
1299 foreach (var candidate in candidates) {
1300 if (candidate.ReturnType == t_x)
1301 most_specific_operator = candidate;
1302 else if (candidate.Parameters.Types[0] == s_x)
1303 ambig_arg = candidate;
1306 rc.Report.Error (457, loc,
1307 "Ambiguous user defined operators `{0}' and `{1}' when converting from `{2}' to `{3}'",
1308 ambig_arg.GetSignatureForError (), most_specific_operator.GetSignatureForError (),
1309 source.Type.GetSignatureForError (), target.GetSignatureForError ());
1312 return ErrorExpression.Instance;
1317 // Convert input type when it's different to best operator argument
1319 if (s_x != source_type) {
1320 var c = source as Constant;
1322 source = c.Reduce (rc, s_x);
1328 source = implicitOnly ?
1329 ImplicitConversionStandard (rc, source_type_expr, s_x, loc) :
1330 ExplicitConversionStandard (rc, source_type_expr, s_x, loc);
1333 source = source_type_expr;
1336 source = new UserCast (most_specific_operator, source, loc).Resolve (rc);
1339 // Convert result type when it's different to best operator return type
1341 if (t_x != target_type) {
1343 // User operator is of T?
1345 if (t_x.IsNullableType && (target.IsNullableType || !implicitOnly)) {
1347 // User operator return type does not match target type we need
1348 // yet another conversion. This should happen for promoted numeric
1351 if (t_x != target) {
1352 var unwrap = Nullable.Unwrap.CreateUnwrapped (source);
1354 source = implicitOnly ?
1355 ImplicitConversionStandard (rc, unwrap, target_type, loc) :
1356 ExplicitConversionStandard (rc, unwrap, target_type, loc);
1361 if (target.IsNullableType)
1362 source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (rc);
1365 source = implicitOnly ?
1366 ImplicitConversionStandard (rc, source, target_type, loc) :
1367 ExplicitConversionStandard (rc, source, target_type, loc);
1376 // Source expression is of nullable type and underlying conversion returns
1377 // only non-nullable type we need to lift it manually
1379 if (nullable_source && !s_x.IsNullableType)
1380 return new Nullable.LiftedConversion (source, source_type_expr, target).Resolve (rc);
1383 // Target is of nullable type but source type is not, wrap the result expression
1385 if (target.IsNullableType && !t_x.IsNullableType)
1386 source = Nullable.Wrap.Create (source, target);
1392 /// Converts implicitly the resolved expression `expr' into the
1393 /// `target_type'. It returns a new expression that can be used
1394 /// in a context that expects a `target_type'.
1396 static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
1397 TypeSpec target_type, Location loc)
1401 if (target_type == null)
1402 throw new Exception ("Target type is null");
1404 e = ImplicitConversionStandard (ec, expr, target_type, loc);
1408 e = ImplicitUserConversion (ec, expr, target_type, loc);
1417 /// Attempts to apply the `Standard Implicit
1418 /// Conversion' rules to the expression `expr' into
1419 /// the `target_type'. It returns a new expression
1420 /// that can be used in a context that expects a
1423 /// This is different from `ImplicitConversion' in that the
1424 /// user defined implicit conversions are excluded.
1426 static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
1427 TypeSpec target_type, Location loc)
1429 return ImplicitConversionStandard (ec, expr, target_type, loc, false);
1432 static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
1434 if (expr.eclass == ExprClass.MethodGroup){
1435 if (!target_type.IsDelegate){
1440 // Only allow anonymous method conversions on post ISO_1
1442 if (ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1){
1443 MethodGroupExpr mg = expr as MethodGroupExpr;
1445 return new ImplicitDelegateCreation (target_type, mg, loc).Resolve (ec);
1449 TypeSpec expr_type = expr.Type;
1452 if (expr_type == target_type) {
1453 if (expr_type != InternalType.NullLiteral && expr_type != InternalType.AnonymousMethod && expr_type != InternalType.ThrowExpr)
1458 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1459 switch (target_type.Kind) {
1460 case MemberKind.ArrayType:
1461 case MemberKind.Class:
1462 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object)
1463 return EmptyCast.Create (expr, target_type);
1465 goto case MemberKind.Struct;
1466 case MemberKind.Struct:
1467 case MemberKind.Delegate:
1468 case MemberKind.Enum:
1469 case MemberKind.Interface:
1470 case MemberKind.TypeParameter:
1471 Arguments args = new Arguments (1);
1472 args.Add (new Argument (expr));
1473 return new DynamicConversion (target_type, explicit_cast ? CSharpBinderFlags.ConvertExplicit : 0, args, loc).Resolve (ec);
1479 if (expr_type == InternalType.ThrowExpr) {
1480 return target_type.Kind == MemberKind.InternalCompilerType ? null : EmptyCast.Create (expr, target_type);
1483 if (target_type.IsNullableType)
1484 return ImplicitNulableConversion (ec, expr, target_type);
1487 // Attempt to do the implicit constant expression conversions
1489 Constant c = expr as Constant;
1492 c = c.ConvertImplicitly (target_type);
1494 throw new InternalErrorException ("Conversion error", loc);
1500 if (expr_type.IsTupleType) {
1501 if (target_type.IsTupleType)
1502 return ImplicitTupleLiteralConversion (ec, expr, target_type, loc);
1504 if (expr is TupleLiteral && TupleLiteral.ContainsNoTypeElement (expr_type))
1508 e = ImplicitNumericConversion (expr, expr_type, target_type);
1512 e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
1516 e = ImplicitBoxingConversion (expr, expr_type, target_type);
1520 if (expr is IntegralConstant && target_type.IsEnum){
1521 var i = (IntegralConstant) expr;
1523 // LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
1525 // An implicit enumeration conversion permits the decimal-integer-literal 0
1526 // to be converted to any enum-type and to any nullable-type whose underlying
1527 // type is an enum-type
1529 if (i.IsZeroInteger) {
1530 // Recreate 0 literal to remove any collected conversions
1531 return new EnumConstant (new IntLiteral (ec.BuiltinTypes, 0, i.Location), target_type);
1535 var target_pc = target_type as PointerContainer;
1536 if (target_pc != null) {
1537 if (expr_type.IsPointer) {
1539 // Pointer types are same when they have same element types
1541 if (expr_type == target_pc)
1544 if (target_pc.Element.Kind == MemberKind.Void)
1545 return EmptyCast.Create (expr, target_type);
1550 if (expr_type == InternalType.NullLiteral)
1551 return new NullPointer (target_type, loc);
1554 if (expr_type == InternalType.AnonymousMethod){
1555 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
1556 Expression am = ame.Compatible (ec, target_type);
1558 return am.Resolve (ec);
1560 // Avoid CS1503 after CS1661
1561 return ErrorExpression.Instance;
1564 if (expr_type == InternalType.Arglist && target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec)
1568 // dynamic erasure conversion on value types
1570 if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
1571 return expr_type == target_type ? expr : EmptyCast.Create (expr, target_type);
1573 var interpolated_string = expr as InterpolatedString;
1574 if (interpolated_string != null) {
1575 if (target_type == ec.Module.PredefinedTypes.IFormattable.TypeSpec || target_type == ec.Module.PredefinedTypes.FormattableString.TypeSpec)
1576 return interpolated_string.ConvertTo (ec, target_type);
1583 /// Attempts to implicitly convert `source' into `target_type', using
1584 /// ImplicitConversion. If there is no implicit conversion, then
1585 /// an error is signaled
1587 public static Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
1588 TypeSpec target_type, Location loc)
1590 Expression e = ImplicitConversion (ec, source, target_type, loc);
1594 if (target_type != InternalType.ErrorType)
1595 source.Error_ValueCannotBeConverted (ec, target_type, false);
1601 /// Performs the explicit numeric conversions
1603 /// There are a few conversions that are not part of the C# standard,
1604 /// they were interim hacks in the C# compiler that were supposed to
1605 /// become explicit operators in the UIntPtr class and IntPtr class,
1606 /// but for historical reasons it did not happen, so the C# compiler
1607 /// ended up with these special hacks.
1609 /// See bug 59800 for details.
1611 /// The conversion are:
1621 public static Expression ExplicitNumericConversion (ResolveContext rc, Expression expr, TypeSpec target_type)
1623 // Not all predefined explicit numeric conversion are
1624 // defined here, for some of them (mostly IntPtr/UIntPtr) we
1625 // defer to user-operator handling which is now perfect but
1628 // LAMESPEC: Undocumented IntPtr/UIntPtr conversions
1629 // IntPtr -> uint uses int
1630 // UIntPtr -> long uses ulong
1633 switch (expr.Type.BuiltinType) {
1634 case BuiltinTypeSpec.Type.SByte:
1636 // From sbyte to byte, ushort, uint, ulong, char, uintptr
1638 switch (target_type.BuiltinType) {
1639 case BuiltinTypeSpec.Type.Byte:
1640 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
1641 case BuiltinTypeSpec.Type.UShort:
1642 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
1643 case BuiltinTypeSpec.Type.UInt:
1644 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
1645 case BuiltinTypeSpec.Type.ULong:
1646 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
1647 case BuiltinTypeSpec.Type.Char:
1648 return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
1650 // One of the built-in conversions that belonged in the class library
1651 case BuiltinTypeSpec.Type.UIntPtr:
1652 return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I1_U8), target_type, target_type, true);
1655 case BuiltinTypeSpec.Type.Byte:
1657 // From byte to sbyte and char
1659 switch (target_type.BuiltinType) {
1660 case BuiltinTypeSpec.Type.SByte:
1661 return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
1662 case BuiltinTypeSpec.Type.Char:
1663 return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
1666 case BuiltinTypeSpec.Type.Short:
1668 // From short to sbyte, byte, ushort, uint, ulong, char, uintptr
1670 switch (target_type.BuiltinType) {
1671 case BuiltinTypeSpec.Type.SByte:
1672 return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
1673 case BuiltinTypeSpec.Type.Byte:
1674 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
1675 case BuiltinTypeSpec.Type.UShort:
1676 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
1677 case BuiltinTypeSpec.Type.UInt:
1678 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
1679 case BuiltinTypeSpec.Type.ULong:
1680 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
1681 case BuiltinTypeSpec.Type.Char:
1682 return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
1684 // One of the built-in conversions that belonged in the class library
1685 case BuiltinTypeSpec.Type.UIntPtr:
1686 return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
1689 case BuiltinTypeSpec.Type.UShort:
1691 // From ushort to sbyte, byte, short, char
1693 switch (target_type.BuiltinType) {
1694 case BuiltinTypeSpec.Type.SByte:
1695 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
1696 case BuiltinTypeSpec.Type.Byte:
1697 return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
1698 case BuiltinTypeSpec.Type.Short:
1699 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
1700 case BuiltinTypeSpec.Type.Char:
1701 return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
1704 case BuiltinTypeSpec.Type.Int:
1706 // From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
1708 switch (target_type.BuiltinType) {
1709 case BuiltinTypeSpec.Type.SByte:
1710 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
1711 case BuiltinTypeSpec.Type.Byte:
1712 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
1713 case BuiltinTypeSpec.Type.Short:
1714 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
1715 case BuiltinTypeSpec.Type.UShort:
1716 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
1717 case BuiltinTypeSpec.Type.UInt:
1718 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
1719 case BuiltinTypeSpec.Type.ULong:
1720 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
1721 case BuiltinTypeSpec.Type.Char:
1722 return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
1724 // One of the built-in conversions that belonged in the class library
1725 case BuiltinTypeSpec.Type.UIntPtr:
1726 return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
1729 case BuiltinTypeSpec.Type.UInt:
1731 // From uint to sbyte, byte, short, ushort, int, char
1733 switch (target_type.BuiltinType) {
1734 case BuiltinTypeSpec.Type.SByte:
1735 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
1736 case BuiltinTypeSpec.Type.Byte:
1737 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
1738 case BuiltinTypeSpec.Type.Short:
1739 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
1740 case BuiltinTypeSpec.Type.UShort:
1741 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
1742 case BuiltinTypeSpec.Type.Int:
1743 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
1744 case BuiltinTypeSpec.Type.Char:
1745 return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
1748 case BuiltinTypeSpec.Type.Long:
1750 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1752 switch (target_type.BuiltinType) {
1753 case BuiltinTypeSpec.Type.SByte:
1754 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
1755 case BuiltinTypeSpec.Type.Byte:
1756 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
1757 case BuiltinTypeSpec.Type.Short:
1758 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
1759 case BuiltinTypeSpec.Type.UShort:
1760 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
1761 case BuiltinTypeSpec.Type.Int:
1762 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
1763 case BuiltinTypeSpec.Type.UInt:
1764 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
1765 case BuiltinTypeSpec.Type.ULong:
1766 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
1767 case BuiltinTypeSpec.Type.Char:
1768 return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
1771 case BuiltinTypeSpec.Type.ULong:
1773 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1775 switch (target_type.BuiltinType) {
1776 case BuiltinTypeSpec.Type.SByte:
1777 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
1778 case BuiltinTypeSpec.Type.Byte:
1779 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
1780 case BuiltinTypeSpec.Type.Short:
1781 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
1782 case BuiltinTypeSpec.Type.UShort:
1783 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
1784 case BuiltinTypeSpec.Type.Int:
1785 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
1786 case BuiltinTypeSpec.Type.UInt:
1787 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
1788 case BuiltinTypeSpec.Type.Long:
1789 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
1790 case BuiltinTypeSpec.Type.Char:
1791 return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
1793 // One of the built-in conversions that belonged in the class library
1794 case BuiltinTypeSpec.Type.IntPtr:
1795 return new OperatorCast (EmptyCast.Create (expr, rc.BuiltinTypes.Long), target_type, true);
1798 case BuiltinTypeSpec.Type.Char:
1800 // From char to sbyte, byte, short
1802 switch (target_type.BuiltinType) {
1803 case BuiltinTypeSpec.Type.SByte:
1804 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
1805 case BuiltinTypeSpec.Type.Byte:
1806 return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
1807 case BuiltinTypeSpec.Type.Short:
1808 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
1811 case BuiltinTypeSpec.Type.Float:
1813 // From float to sbyte, byte, short,
1814 // ushort, int, uint, long, ulong, char
1817 switch (target_type.BuiltinType) {
1818 case BuiltinTypeSpec.Type.SByte:
1819 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
1820 case BuiltinTypeSpec.Type.Byte:
1821 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
1822 case BuiltinTypeSpec.Type.Short:
1823 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
1824 case BuiltinTypeSpec.Type.UShort:
1825 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
1826 case BuiltinTypeSpec.Type.Int:
1827 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
1828 case BuiltinTypeSpec.Type.UInt:
1829 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
1830 case BuiltinTypeSpec.Type.Long:
1831 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
1832 case BuiltinTypeSpec.Type.ULong:
1833 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
1834 case BuiltinTypeSpec.Type.Char:
1835 return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
1836 case BuiltinTypeSpec.Type.Decimal:
1837 return new OperatorCast (expr, target_type, true);
1840 case BuiltinTypeSpec.Type.Double:
1842 // From double to sbyte, byte, short,
1843 // ushort, int, uint, long, ulong,
1844 // char, float or decimal
1846 switch (target_type.BuiltinType) {
1847 case BuiltinTypeSpec.Type.SByte:
1848 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
1849 case BuiltinTypeSpec.Type.Byte:
1850 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
1851 case BuiltinTypeSpec.Type.Short:
1852 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
1853 case BuiltinTypeSpec.Type.UShort:
1854 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
1855 case BuiltinTypeSpec.Type.Int:
1856 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
1857 case BuiltinTypeSpec.Type.UInt:
1858 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
1859 case BuiltinTypeSpec.Type.Long:
1860 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
1861 case BuiltinTypeSpec.Type.ULong:
1862 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
1863 case BuiltinTypeSpec.Type.Char:
1864 return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
1865 case BuiltinTypeSpec.Type.Float:
1866 return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
1867 case BuiltinTypeSpec.Type.Decimal:
1868 return new OperatorCast (expr, target_type, true);
1871 case BuiltinTypeSpec.Type.UIntPtr:
1873 // Various built-in conversions that belonged in the class library
1875 // from uintptr to sbyte, short, int32
1877 switch (target_type.BuiltinType) {
1878 case BuiltinTypeSpec.Type.SByte:
1879 return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I1);
1880 case BuiltinTypeSpec.Type.Short:
1881 return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I2);
1882 case BuiltinTypeSpec.Type.Int:
1883 return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type);
1884 case BuiltinTypeSpec.Type.UInt:
1885 return new OperatorCast (expr, expr.Type, target_type, true);
1886 case BuiltinTypeSpec.Type.Long:
1887 return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.ULong, true), target_type);
1890 case BuiltinTypeSpec.Type.IntPtr:
1891 if (target_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
1892 return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Int, true), target_type);
1893 if (target_type.BuiltinType == BuiltinTypeSpec.Type.ULong)
1894 return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Long, true), target_type);
1897 case BuiltinTypeSpec.Type.Decimal:
1898 // From decimal to sbyte, byte, short,
1899 // ushort, int, uint, long, ulong, char,
1901 switch (target_type.BuiltinType) {
1902 case BuiltinTypeSpec.Type.SByte:
1903 case BuiltinTypeSpec.Type.Byte:
1904 case BuiltinTypeSpec.Type.Short:
1905 case BuiltinTypeSpec.Type.UShort:
1906 case BuiltinTypeSpec.Type.Int:
1907 case BuiltinTypeSpec.Type.UInt:
1908 case BuiltinTypeSpec.Type.Long:
1909 case BuiltinTypeSpec.Type.ULong:
1910 case BuiltinTypeSpec.Type.Char:
1911 case BuiltinTypeSpec.Type.Float:
1912 case BuiltinTypeSpec.Type.Double:
1913 return new OperatorCast (expr, expr.Type, target_type, true);
1923 /// Returns whether an explicit reference conversion can be performed
1924 /// from source_type to target_type
1926 public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
1928 Expression e = ExplicitReferenceConversion (null, source_type, target_type);
1932 if (e == EmptyExpression.Null)
1935 throw new InternalErrorException ("Invalid probing conversion result");
1939 /// Implements Explicit Reference conversions
1941 static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
1944 // From object to a generic parameter
1946 if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object && TypeManager.IsGenericParameter (target_type))
1947 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1950 // Explicit type parameter conversion from T
1952 if (source_type.Kind == MemberKind.TypeParameter)
1953 return ExplicitTypeParameterConversionFromT (source, source_type, target_type);
1955 bool target_is_value_type = target_type.Kind == MemberKind.Struct || target_type.Kind == MemberKind.Enum;
1958 // Unboxing conversion from System.ValueType to any non-nullable-value-type
1960 if (source_type.BuiltinType == BuiltinTypeSpec.Type.ValueType && target_is_value_type)
1961 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1964 // From object or dynamic to any reference type or value type (unboxing)
1966 if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object || source_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1967 if (target_type.IsPointer)
1971 source == null ? EmptyExpression.Null :
1972 target_is_value_type ? new UnboxCast (source, target_type) :
1973 source is Constant ? (Expression) new EmptyConstantCast ((Constant) source, target_type) :
1974 new ClassCast (source, target_type);
1978 // From any class S to any class-type T, provided S is a base class of T
1980 if (source_type.Kind == MemberKind.Class && TypeSpec.IsBaseClass (target_type, source_type, true))
1981 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1984 // From any interface-type S to to any class type T, provided T is not
1985 // sealed, or provided T implements S.
1987 // This also covers Explicit conversions involving type parameters
1988 // section From any interface type to T
1990 if (source_type.Kind == MemberKind.Interface) {
1991 if (!target_type.IsSealed || target_type.ImplementsInterface (source_type, true)) {
1993 return EmptyExpression.Null;
1996 // Unboxing conversion from any interface-type to any non-nullable-value-type that
1997 // implements the interface-type
1999 return target_is_value_type ? new UnboxCast (source, target_type) : (Expression) new ClassCast (source, target_type);
2003 // From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
2004 // array type S[], provided there is an implicit or explicit reference conversion from S to T.
2006 var target_array = target_type as ArrayContainer;
2007 if (target_array != null && IList_To_Array (source_type, target_array))
2008 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2013 var source_array = source_type as ArrayContainer;
2014 if (source_array != null) {
2015 var target_array = target_type as ArrayContainer;
2016 if (target_array != null) {
2018 // From System.Array to any array-type
2020 if (source_type.BuiltinType == BuiltinTypeSpec.Type.Array)
2021 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2024 // From an array type S with an element type Se to an array type T with an
2025 // element type Te provided all the following are true:
2026 // * S and T differe only in element type, in other words, S and T
2027 // have the same number of dimensions.
2028 // * Both Se and Te are reference types
2029 // * An explicit reference conversions exist from Se to Te
2031 if (source_array.Rank == target_array.Rank) {
2033 source_type = source_array.Element;
2034 var target_element = target_array.Element;
2037 // LAMESPEC: Type parameters are special cased somehow but
2038 // only when both source and target elements are type parameters
2040 if ((source_type.Kind & target_element.Kind & MemberKind.TypeParameter) == MemberKind.TypeParameter) {
2042 // Conversion is allowed unless source element type has struct constrain
2044 if (TypeSpec.IsValueType (source_type))
2047 if (!TypeSpec.IsReferenceType (source_type))
2051 if (!TypeSpec.IsReferenceType (target_element))
2054 if (ExplicitReferenceConversionExists (source_type, target_element))
2055 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2062 // From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces,
2063 // provided that there is an explicit reference conversion from S to T
2065 if (ArrayToIList (source_array, target_type, true))
2066 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2072 // From any class type S to any interface T, provides S is not sealed
2073 // and provided S does not implement T.
2075 if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type, true)) {
2076 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2080 // From System delegate to any delegate-type
2082 if (source_type.BuiltinType == BuiltinTypeSpec.Type.Delegate && target_type.IsDelegate)
2083 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2086 // From variant generic delegate to same variant generic delegate type
2088 if (source_type.IsDelegate && target_type.IsDelegate && source_type.MemberDefinition == target_type.MemberDefinition) {
2089 var tparams = source_type.MemberDefinition.TypeParameters;
2090 var targs_src = source_type.TypeArguments;
2091 var targs_dst = target_type.TypeArguments;
2093 for (i = 0; i < tparams.Length; ++i) {
2095 // If TP is invariant, types have to be identical
2097 if (TypeSpecComparer.IsEqual (targs_src[i], targs_dst[i]))
2100 if (tparams[i].Variance == Variance.Covariant) {
2102 //If TP is covariant, an implicit or explicit identity or reference conversion is required
2104 if (ImplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
2107 if (ExplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
2110 } else if (tparams[i].Variance == Variance.Contravariant) {
2112 //If TP is contravariant, both are either identical or reference types
2114 if (TypeSpec.IsReferenceType (targs_src[i]) && TypeSpec.IsReferenceType (targs_dst[i]))
2121 if (i == tparams.Length)
2122 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
2125 var tps = target_type as TypeParameterSpec;
2127 return ExplicitTypeParameterConversionToT (source, source_type, tps);
2133 /// Performs an explicit conversion of the expression `expr' whose
2134 /// type is expr.Type to `target_type'.
2136 static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
2137 TypeSpec target_type, Location loc)
2139 TypeSpec expr_type = expr.Type;
2141 // Explicit conversion includes implicit conversion and it used for enum underlying types too
2142 Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
2146 if (expr_type.IsEnum) {
2147 TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
2148 Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
2149 if (underlying.Type == real_target)
2153 ne = ImplicitNumericConversion (underlying, real_target);
2156 ne = ExplicitNumericConversion (ec, underlying, real_target);
2159 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
2161 if (ne == null && (real_target.BuiltinType == BuiltinTypeSpec.Type.IntPtr || real_target.BuiltinType == BuiltinTypeSpec.Type.UIntPtr))
2162 ne = ExplicitUserConversion (ec, underlying, real_target, loc);
2164 return ne != null ? EmptyCast.Create (ne, target_type) : null;
2167 if (target_type.IsEnum) {
2169 // System.Enum can be unboxed to any enum-type
2171 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Enum)
2172 return new UnboxCast (expr, target_type);
2174 TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
2176 if (expr_type == real_target)
2177 return EmptyCast.Create (expr, target_type);
2179 Constant c = expr as Constant;
2181 c = c.TryReduce (ec, real_target);
2185 ne = ImplicitNumericConversion (expr, real_target);
2187 return EmptyCast.Create (ne, target_type);
2189 ne = ExplicitNumericConversion (ec, expr, real_target);
2191 return EmptyCast.Create (ne, target_type);
2194 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
2196 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.IntPtr || expr_type.BuiltinType == BuiltinTypeSpec.Type.UIntPtr) {
2197 ne = ExplicitUserConversion (ec, expr, real_target, loc);
2199 return ExplicitConversionCore (ec, ne, target_type, loc);
2203 ne = ExplicitNumericConversion (ec, expr, target_type);
2209 // Skip the ExplicitReferenceConversion because we can not convert
2210 // from Null to a ValueType, and ExplicitReference wont check against
2211 // null literal explicitly
2213 if (expr_type != InternalType.NullLiteral) {
2214 ne = ExplicitReferenceConversion (expr, expr_type, target_type);
2220 ne = ExplicitUnsafe (expr, target_type);
2228 public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
2230 TypeSpec expr_type = expr.Type;
2232 if (target_type.IsPointer){
2233 if (expr_type.IsPointer)
2234 return EmptyCast.Create (expr, target_type);
2236 switch (expr_type.BuiltinType) {
2237 case BuiltinTypeSpec.Type.SByte:
2238 case BuiltinTypeSpec.Type.Short:
2239 case BuiltinTypeSpec.Type.Int:
2240 return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
2242 case BuiltinTypeSpec.Type.UShort:
2243 case BuiltinTypeSpec.Type.UInt:
2244 case BuiltinTypeSpec.Type.Byte:
2245 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2247 case BuiltinTypeSpec.Type.Long:
2248 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);
2250 case BuiltinTypeSpec.Type.ULong:
2251 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
2255 if (expr_type.IsPointer){
2256 switch (target_type.BuiltinType) {
2257 case BuiltinTypeSpec.Type.SByte:
2258 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
2259 case BuiltinTypeSpec.Type.Byte:
2260 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
2261 case BuiltinTypeSpec.Type.Short:
2262 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
2263 case BuiltinTypeSpec.Type.UShort:
2264 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
2265 case BuiltinTypeSpec.Type.Int:
2266 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
2267 case BuiltinTypeSpec.Type.UInt:
2268 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
2269 case BuiltinTypeSpec.Type.Long:
2270 return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
2271 case BuiltinTypeSpec.Type.ULong:
2272 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
2279 /// Same as ExplicitConversion, only it doesn't include user defined conversions
2281 static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
2282 TypeSpec target_type, Location l)
2284 int errors = ec.Report.Errors;
2285 Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
2286 if (ec.Report.Errors > errors)
2292 ne = ExplicitNumericConversion (ec, expr, target_type);
2296 ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
2300 if (ec.IsUnsafe && expr.Type.IsPointer && target_type.IsPointer && ((PointerContainer)expr.Type).Element.Kind == MemberKind.Void)
2301 return EmptyCast.Create (expr, target_type);
2303 expr.Error_ValueCannotBeConverted (ec, target_type, true);
2308 /// Performs an explicit conversion of the expression `expr' whose
2309 /// type is expr.Type to `target_type'.
2311 static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
2312 TypeSpec target_type, Location loc)
2314 Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
2317 // Don't eliminate explicit precission casts
2320 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Float)
2321 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
2323 if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
2324 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
2330 TypeSpec expr_type = expr.Type;
2331 if (target_type.IsNullableType) {
2334 if (expr_type.IsNullableType) {
2335 target = Nullable.NullableInfo.GetUnderlyingType (target_type);
2336 Expression unwrap = Nullable.Unwrap.Create (expr);
2337 e = ExplicitConversion (ec, unwrap, target, expr.Location);
2341 return new Nullable.LiftedConversion (e, unwrap, target_type).Resolve (ec);
2343 if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
2344 return new UnboxCast (expr, target_type);
2347 target = TypeManager.GetTypeArguments (target_type) [0];
2348 e = ExplicitConversionCore (ec, expr, target, loc);
2350 return TypeSpec.IsReferenceType (expr.Type) ? new UnboxCast (expr, target_type) : Nullable.Wrap.Create (e, target_type);
2351 } else if (expr_type.IsNullableType) {
2352 e = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
2356 e = Nullable.Unwrap.Create (expr, false);
2357 e = ExplicitConversionCore (ec, e, target_type, loc);
2359 return EmptyCast.Create (e, target_type);
2362 e = ExplicitUserConversion (ec, expr, target_type, loc);
2367 expr.Error_ValueCannotBeConverted (ec, target_type, true);