2 // conversion.cs: various routines for implementing conversions.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Ravi Pratap (ravi@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
19 // A container class for all the conversion operations
21 public class Convert {
23 // This is used to prettify the code: a null argument is allowed
24 // for ImplicitStandardConversion as long as it is known that
25 // no anonymous method will play a role.
27 // FIXME: renamed from `const' to `static' to allow bootstraping from older
28 // versions of the compiler that could not cope with this construct.
30 public static EmitContext ConstantEC = null;
32 static public void Error_CannotConvertType (Location loc, Type source, Type target)
34 Report.Error (30, loc, "Cannot convert type '" +
35 TypeManager.CSharpName (source) + "' to '" +
36 TypeManager.CSharpName (target) + "'");
39 static Expression TypeParameter_to_Null (Expression expr, Type target_type,
42 if (!TypeParameter_to_Null (target_type)) {
43 Report.Error (403, loc, "Cannot convert null to the type " +
44 "parameter `{0}' becaues it could be a value " +
45 "type. Consider using `default ({0})' instead.",
50 return new NullCast (expr, target_type);
53 static bool TypeParameter_to_Null (Type target_type)
55 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
59 if (gc.HasReferenceTypeConstraint)
61 if (gc.HasClassConstraint && !TypeManager.IsValueType (gc.ClassConstraint))
67 static Type TypeParam_EffectiveBaseType (EmitContext ec, Type t)
69 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
71 return TypeManager.object_type;
73 return TypeParam_EffectiveBaseType (ec, gc);
76 static Type TypeParam_EffectiveBaseType (EmitContext ec, GenericConstraints gc)
78 ArrayList list = new ArrayList ();
79 list.Add (gc.EffectiveBaseClass);
80 foreach (Type t in gc.InterfaceConstraints) {
81 if (!t.IsGenericParameter)
84 GenericConstraints new_gc = TypeManager.GetTypeParameterConstraints (t);
86 list.Add (TypeParam_EffectiveBaseType (ec, new_gc));
88 return FindMostEncompassedType (ec, list);
91 static Expression TypeParameterConversion (Expression expr, bool is_reference, Type target_type)
94 return new EmptyCast (expr, target_type);
96 return new BoxedCast (expr, target_type);
99 static Expression ImplicitTypeParameterConversion (EmitContext ec, Expression expr,
102 Type expr_type = expr.Type;
104 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
107 if (target_type == TypeManager.object_type)
108 return new BoxedCast (expr);
113 // We're converting from a type parameter which is known to be a reference type.
114 bool is_reference = gc.IsReferenceType;
115 Type base_type = TypeParam_EffectiveBaseType (ec, gc);
117 if (TypeManager.IsSubclassOf (base_type, target_type))
118 return TypeParameterConversion (expr, is_reference, target_type);
120 if (target_type.IsInterface) {
121 if (TypeManager.ImplementsInterface (base_type, target_type))
122 return TypeParameterConversion (expr, is_reference, target_type);
124 foreach (Type t in gc.InterfaceConstraints) {
125 if (TypeManager.IsSubclassOf (t, target_type))
126 return TypeParameterConversion (expr, is_reference, target_type);
130 foreach (Type t in gc.InterfaceConstraints) {
131 if (!t.IsGenericParameter)
133 if (TypeManager.IsSubclassOf (t, target_type))
134 return TypeParameterConversion (expr, is_reference, target_type);
140 static EmptyExpression MyEmptyExpr;
141 static public Expression WideningReferenceConversion (EmitContext ec, Expression expr, Type target_type)
143 Type expr_type = expr.Type;
145 if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
146 // if we are a method group, emit a warning
151 if (expr_type == TypeManager.void_type)
154 if (expr_type.IsGenericParameter)
155 return ImplicitTypeParameterConversion (ec, expr, target_type);
158 // notice that it is possible to write "ValueType v = 1", the ValueType here
159 // is an abstract class, and not really a value type, so we apply the same rules.
161 if (target_type == TypeManager.object_type) {
163 // A pointer type cannot be converted to object
165 if (expr_type.IsPointer)
168 if (TypeManager.IsValueType (expr_type))
169 return new BoxedCast (expr);
170 if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type){
171 if (expr_type == TypeManager.anonymous_method_type)
173 return new EmptyCast (expr, target_type);
177 } else if (target_type == TypeManager.value_type) {
178 if (TypeManager.IsValueType (expr_type))
179 return new BoxedCast (expr);
180 if (expr_type == TypeManager.null_type)
181 return new NullCast (expr, target_type);
184 } else if (TypeManager.IsSubclassOf (expr_type, target_type)) {
186 // Special case: enumeration to System.Enum.
187 // System.Enum is not a value type, it is a class, so we need
188 // a boxing conversion
190 if (expr_type.IsEnum || expr_type.IsGenericParameter)
191 return new BoxedCast (expr);
193 return new EmptyCast (expr, target_type);
196 // This code is kind of mirrored inside WideningStandardConversionExists
197 // with the small distinction that we only probe there
199 // Always ensure that the code here and there is in sync
201 // from the null type to any reference-type.
202 if (expr_type == TypeManager.null_type){
203 if (target_type.IsPointer)
204 return new EmptyCast (expr, target_type);
206 if (!target_type.IsValueType)
207 return new NullCast (expr, target_type);
210 // from any class-type S to any interface-type T.
211 if (target_type.IsInterface) {
212 if (target_type != TypeManager.iconvertible_type &&
213 expr_type.IsValueType && (expr is Constant) &&
214 !(expr is IntLiteral || expr is BoolLiteral ||
215 expr is FloatLiteral || expr is DoubleLiteral ||
216 expr is LongLiteral || expr is CharLiteral ||
217 expr is StringLiteral || expr is DecimalLiteral ||
218 expr is UIntLiteral || expr is ULongLiteral)) {
222 if (TypeManager.ImplementsInterface (expr_type, target_type)){
223 if (expr_type.IsGenericParameter || TypeManager.IsValueType (expr_type))
224 return new BoxedCast (expr, target_type);
226 return new EmptyCast (expr, target_type);
230 // from any interface type S to interface-type T.
231 if (expr_type.IsInterface && target_type.IsInterface) {
232 if (TypeManager.ImplementsInterface (expr_type, target_type))
233 return new EmptyCast (expr, target_type);
238 // from an array-type S to an array-type of type T
239 if (expr_type.IsArray && target_type.IsArray) {
240 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
242 Type expr_element_type = TypeManager.GetElementType (expr_type);
244 if (MyEmptyExpr == null)
245 MyEmptyExpr = new EmptyExpression ();
247 MyEmptyExpr.SetType (expr_element_type);
248 Type target_element_type = TypeManager.GetElementType (target_type);
250 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
251 if (WideningStandardConversionExists (ConstantEC, MyEmptyExpr,
252 target_element_type))
253 return new EmptyCast (expr, target_type);
257 // from an array-type to System.Array
258 if (expr_type.IsArray && target_type == TypeManager.array_type)
259 return new EmptyCast (expr, target_type);
261 // from any delegate type to System.Delegate
262 if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
263 target_type == TypeManager.delegate_type)
264 return new EmptyCast (expr, target_type);
266 // from any array-type or delegate type into System.ICloneable.
267 if (expr_type.IsArray ||
268 expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
269 if (target_type == TypeManager.icloneable_type)
270 return new EmptyCast (expr, target_type);
272 // from a generic type definition to a generic instance.
273 if (TypeManager.IsEqual (expr_type, target_type))
274 return new EmptyCast (expr, target_type);
280 // Tests whether an implicit reference conversion exists between expr_type
283 public static bool WideningReferenceConversionExists (EmitContext ec, Expression expr, Type target_type)
285 Type expr_type = expr.Type;
287 if (expr_type.IsGenericParameter)
288 return ImplicitTypeParameterConversion (ec, expr, target_type) != null;
291 // This is the boxed case.
293 if (target_type == TypeManager.object_type) {
294 if (expr_type.IsClass || TypeManager.IsValueType (expr_type) ||
295 expr_type.IsInterface || expr_type == TypeManager.enum_type)
296 if (target_type != TypeManager.anonymous_method_type)
300 } else if (TypeManager.IsSubclassOf (expr_type, target_type))
303 // Please remember that all code below actually comes
304 // from WideningReferenceConversion so make sure code remains in sync
306 // from any class-type S to any interface-type T.
307 if (target_type.IsInterface) {
308 if (target_type != TypeManager.iconvertible_type &&
309 expr_type.IsValueType && (expr is Constant) &&
310 !(expr is IntLiteral || expr is BoolLiteral ||
311 expr is FloatLiteral || expr is DoubleLiteral ||
312 expr is LongLiteral || expr is CharLiteral ||
313 expr is StringLiteral || expr is DecimalLiteral ||
314 expr is UIntLiteral || expr is ULongLiteral)) {
318 if (TypeManager.ImplementsInterface (expr_type, target_type))
322 // from any interface type S to interface-type T.
323 if (expr_type.IsInterface && target_type.IsInterface)
324 if (TypeManager.ImplementsInterface (expr_type, target_type))
327 // from an array-type S to an array-type of type T
328 if (expr_type.IsArray && target_type.IsArray) {
329 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
331 Type expr_element_type = expr_type.GetElementType ();
333 if (MyEmptyExpr == null)
334 MyEmptyExpr = new EmptyExpression ();
336 MyEmptyExpr.SetType (expr_element_type);
337 Type target_element_type = TypeManager.GetElementType (target_type);
339 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
340 if (WideningStandardConversionExists (ConstantEC, MyEmptyExpr,
341 target_element_type))
346 // from an array-type to System.Array
347 if (expr_type.IsArray && (target_type == TypeManager.array_type))
350 // from any delegate type to System.Delegate
351 if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
352 target_type == TypeManager.delegate_type)
353 if (target_type.IsAssignableFrom (expr_type))
356 // from any array-type or delegate type into System.ICloneable.
357 if (expr_type.IsArray ||
358 expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
359 if (target_type == TypeManager.icloneable_type)
362 // from the null type to any reference-type.
363 if (expr_type == TypeManager.null_type){
364 if (target_type.IsPointer)
367 if (!target_type.IsValueType)
371 // from a generic type definition to a generic instance.
372 if (TypeManager.IsEqual (expr_type, target_type))
379 /// Implicit Numeric Conversions.
381 /// expr is the expression to convert, returns a new expression of type
382 /// target_type or null if an implicit conversion is not possible.
385 static public Expression WideningNumericConversion (EmitContext ec, Expression expr,
386 Type target_type, Location loc)
388 Type expr_type = expr.Type;
391 // Attempt to do the implicit constant expression conversions
393 if (expr is Constant){
394 if (expr is IntConstant){
397 e = TryWideningIntConversion (target_type, (IntConstant) expr);
401 } else if (expr is LongConstant && target_type == TypeManager.uint64_type){
403 // Try the implicit constant expression conversion
404 // from long to ulong, instead of a nice routine,
407 long v = ((LongConstant) expr).Value;
409 return new ULongConstant ((ulong) v);
413 Type real_target_type = target_type;
415 if (expr_type == TypeManager.byte_type){
417 // From byte to short, ushort, int, uint, long, ulong, float, double
419 if ((real_target_type == TypeManager.short_type) ||
420 (real_target_type == TypeManager.int32_type))
421 return new EmptyCast (expr, target_type);
423 if (real_target_type == TypeManager.int64_type)
424 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
425 if (real_target_type == TypeManager.float_type)
426 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
427 if (real_target_type == TypeManager.double_type)
428 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
429 if (real_target_type == TypeManager.decimal_type)
430 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
431 } else if (expr_type == TypeManager.short_type){
433 // From short to int, long, float, double
435 if (real_target_type == TypeManager.int32_type)
436 return new EmptyCast (expr, target_type);
437 if (real_target_type == TypeManager.int64_type)
438 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
439 if (real_target_type == TypeManager.double_type)
440 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
441 if (real_target_type == TypeManager.float_type)
442 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
443 if (real_target_type == TypeManager.decimal_type)
444 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
445 } else if (expr_type == TypeManager.int32_type){
447 // From int to long, float, double
449 if (real_target_type == TypeManager.int64_type)
450 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
451 if (real_target_type == TypeManager.double_type)
452 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
453 if (real_target_type == TypeManager.float_type)
454 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
455 if (real_target_type == TypeManager.decimal_type)
456 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
457 } else if (expr_type == TypeManager.int64_type){
459 // From long/ulong to float, double
461 if (real_target_type == TypeManager.double_type)
462 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
463 if (real_target_type == TypeManager.float_type)
464 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
465 if (real_target_type == TypeManager.decimal_type)
466 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
467 } else if (expr_type == TypeManager.decimal_type){
469 // From decimal to float, double
471 if (real_target_type == TypeManager.double_type)
472 return new ImplicitInvocation (ec, "System", "Convert", "ToDouble", loc, expr);
473 if (real_target_type == TypeManager.float_type)
474 return new ImplicitInvocation (ec, "System", "Convert" ,"ToSingle", loc, expr);
475 } else if (expr_type == TypeManager.float_type){
479 if (real_target_type == TypeManager.double_type)
480 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
488 /// Same as WideningStandardConversionExists except that it also looks at
489 /// implicit user defined conversions - needed for overload resolution
491 public static bool WideningConversionExists (EmitContext ec, Expression expr, Type target_type)
493 if ((expr is NullLiteral) && target_type.IsGenericParameter)
494 return TypeParameter_to_Null (target_type);
496 if (WideningStandardConversionExists (ec, expr, target_type))
500 // VB.NET has no notion of User defined conversions
503 // Expression dummy = ImplicitUserConversion (ec, expr, target_type, Location.Null);
505 // if (dummy != null)
512 // VB.NET has no notion of User defined conversions
515 // public static bool ImplicitUserConversionExists (EmitContext ec, Type source, Type target)
517 // Expression dummy = ImplicitUserConversion (
518 // ec, new EmptyExpression (source), target, Location.Null);
519 // return dummy != null;
523 /// Determines if a standard implicit conversion exists from
524 /// expr_type to target_type
526 /// ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
528 public static bool WideningStandardConversionExists (EmitContext ec, Expression expr, Type target_type)
530 Type expr_type = expr.Type;
532 if (expr_type == TypeManager.void_type)
535 //Console.WriteLine ("Expr is {0}", expr);
536 //Console.WriteLine ("{0} -> {1} ?", expr_type, target_type);
537 if (expr_type.Equals (target_type))
541 // First numeric conversions
543 if (expr_type == TypeManager.sbyte_type){
545 // From sbyte to short, int, long, float, double.
547 if ((target_type == TypeManager.int32_type) ||
548 (target_type == TypeManager.int64_type) ||
549 (target_type == TypeManager.double_type) ||
550 (target_type == TypeManager.float_type) ||
551 (target_type == TypeManager.short_type) ||
552 (target_type == TypeManager.decimal_type))
555 } else if (expr_type == TypeManager.byte_type){
557 // From byte to short, ushort, int, uint, long, ulong, float, double
559 if ((target_type == TypeManager.short_type) ||
560 (target_type == TypeManager.ushort_type) ||
561 (target_type == TypeManager.int32_type) ||
562 (target_type == TypeManager.uint32_type) ||
563 (target_type == TypeManager.uint64_type) ||
564 (target_type == TypeManager.int64_type) ||
565 (target_type == TypeManager.float_type) ||
566 (target_type == TypeManager.double_type) ||
567 (target_type == TypeManager.decimal_type))
570 } else if (expr_type == TypeManager.short_type){
572 // From short to int, long, float, double
574 if ((target_type == TypeManager.int32_type) ||
575 (target_type == TypeManager.int64_type) ||
576 (target_type == TypeManager.double_type) ||
577 (target_type == TypeManager.float_type) ||
578 (target_type == TypeManager.decimal_type))
581 } else if (expr_type == TypeManager.ushort_type){
583 // From ushort to int, uint, long, ulong, float, double
585 if ((target_type == TypeManager.uint32_type) ||
586 (target_type == TypeManager.uint64_type) ||
587 (target_type == TypeManager.int32_type) ||
588 (target_type == TypeManager.int64_type) ||
589 (target_type == TypeManager.double_type) ||
590 (target_type == TypeManager.float_type) ||
591 (target_type == TypeManager.decimal_type))
594 } else if (expr_type == TypeManager.int32_type){
596 // From int to long, float, double
598 if ((target_type == TypeManager.int64_type) ||
599 (target_type == TypeManager.double_type) ||
600 (target_type == TypeManager.float_type) ||
601 (target_type == TypeManager.decimal_type))
604 } else if (expr_type == TypeManager.uint32_type){
606 // From uint to long, ulong, float, double
608 if ((target_type == TypeManager.int64_type) ||
609 (target_type == TypeManager.uint64_type) ||
610 (target_type == TypeManager.double_type) ||
611 (target_type == TypeManager.float_type) ||
612 (target_type == TypeManager.decimal_type))
615 } else if ((expr_type == TypeManager.uint64_type) ||
616 (expr_type == TypeManager.int64_type)) {
618 // From long/ulong to float, double
620 if ((target_type == TypeManager.double_type) ||
621 (target_type == TypeManager.float_type) ||
622 (target_type == TypeManager.decimal_type))
625 } else if (expr_type == TypeManager.char_type){
627 // From char to ushort, int, uint, long, ulong, float, double
629 if ((target_type == TypeManager.ushort_type) ||
630 (target_type == TypeManager.int32_type) ||
631 (target_type == TypeManager.uint32_type) ||
632 (target_type == TypeManager.uint64_type) ||
633 (target_type == TypeManager.int64_type) ||
634 (target_type == TypeManager.float_type) ||
635 (target_type == TypeManager.double_type) ||
636 (target_type == TypeManager.decimal_type))
639 } else if (expr_type == TypeManager.float_type){
643 if (target_type == TypeManager.double_type)
647 if (expr.eclass == ExprClass.MethodGroup){
648 if (TypeManager.IsDelegateType (target_type) && RootContext.Version != LanguageVersion.ISO_1){
649 MethodGroupExpr mg = expr as MethodGroupExpr;
652 // This should not happen frequently, so we can create an object
653 // to test compatibility
655 Expression c = ImplicitDelegateCreation.Create (ec, mg, target_type, Location.Null);
661 if (WideningReferenceConversionExists (ec, expr, target_type))
665 // Implicit Constant Expression Conversions
667 if (expr is IntConstant){
668 int value = ((IntConstant) expr).Value;
670 if (target_type == TypeManager.sbyte_type){
671 if (value >= SByte.MinValue && value <= SByte.MaxValue)
673 } else if (target_type == TypeManager.byte_type){
674 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
676 } else if (target_type == TypeManager.short_type){
677 if (value >= Int16.MinValue && value <= Int16.MaxValue)
679 } else if (target_type == TypeManager.ushort_type){
680 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
682 } else if (target_type == TypeManager.uint32_type){
685 } else if (target_type == TypeManager.uint64_type){
687 // we can optimize this case: a positive int32
688 // always fits on a uint64. But we need an opcode
695 if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
699 if (expr is LongConstant && target_type == TypeManager.uint64_type){
701 // Try the implicit constant expression conversion
702 // from long to ulong, instead of a nice routine,
705 long v = ((LongConstant) expr).Value;
710 if ((target_type == TypeManager.enum_type ||
711 target_type.IsSubclassOf (TypeManager.enum_type)) &&
713 IntLiteral i = (IntLiteral) expr;
720 // If `expr_type' implements `target_type' (which is an iface)
721 // see TryWideningIntConversion
723 if (target_type.IsInterface && target_type.IsAssignableFrom (expr_type))
726 if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
729 if (expr_type == TypeManager.anonymous_method_type){
730 if (!TypeManager.IsDelegateType (target_type))
733 AnonymousMethod am = (AnonymousMethod) expr;
735 Expression conv = am.Compatible (ec, target_type, true);
744 // Used internally by FindMostEncompassedType, this is used
745 // to avoid creating lots of objects in the tight loop inside
746 // FindMostEncompassedType
748 static EmptyExpression priv_fmet_param;
751 /// Finds "most encompassed type" according to the spec (13.4.2)
752 /// amongst the methods in the MethodGroupExpr
754 static Type FindMostEncompassedType (EmitContext ec, ArrayList types)
758 if (priv_fmet_param == null)
759 priv_fmet_param = new EmptyExpression ();
761 foreach (Type t in types){
762 priv_fmet_param.SetType (t);
769 if (WideningStandardConversionExists (ec, priv_fmet_param, best))
777 // Used internally by FindMostEncompassingType, this is used
778 // to avoid creating lots of objects in the tight loop inside
779 // FindMostEncompassingType
781 static EmptyExpression priv_fmee_ret;
784 /// Finds "most encompassing type" according to the spec (13.4.2)
785 /// amongst the types in the given set
787 static Type FindMostEncompassingType (EmitContext ec, ArrayList types)
791 if (priv_fmee_ret == null)
792 priv_fmee_ret = new EmptyExpression ();
794 foreach (Type t in types){
795 priv_fmee_ret.SetType (best);
802 if (WideningStandardConversionExists (ec, priv_fmee_ret, t))
810 // Used to avoid creating too many objects
812 static EmptyExpression priv_fms_expr;
815 /// Finds the most specific source Sx according to the rules of the spec (13.4.4)
816 /// by making use of FindMostEncomp* methods. Applies the correct rules separately
817 /// for explicit and implicit conversion operators.
819 static public Type FindMostSpecificSource (EmitContext ec, MethodGroupExpr me,
820 Expression source, bool apply_explicit_conv_rules,
823 ArrayList src_types_set = new ArrayList ();
825 if (priv_fms_expr == null)
826 priv_fms_expr = new EmptyExpression ();
829 // If any operator converts from S then Sx = S
831 Type source_type = source.Type;
832 foreach (MethodBase mb in me.Methods){
833 ParameterData pd = Invocation.GetParameterData (mb);
834 Type param_type = pd.ParameterType (0);
836 if (param_type == source_type)
839 if (apply_explicit_conv_rules) {
842 // Find the set of applicable user-defined conversion operators, U. This set
844 // user-defined implicit or explicit conversion operators declared by
845 // the classes or structs in D that convert from a type encompassing
846 // or encompassed by S to a type encompassing or encompassed by T
848 priv_fms_expr.SetType (param_type);
849 if (WideningStandardConversionExists (ec, priv_fms_expr, source_type))
850 src_types_set.Add (param_type);
852 if (WideningStandardConversionExists (ec, source, param_type))
853 src_types_set.Add (param_type);
857 // Only if S is encompassed by param_type
859 if (WideningStandardConversionExists (ec, source, param_type))
860 src_types_set.Add (param_type);
865 // Explicit Conv rules
867 if (apply_explicit_conv_rules) {
868 ArrayList candidate_set = new ArrayList ();
870 foreach (Type param_type in src_types_set){
871 if (WideningStandardConversionExists (ec, source, param_type))
872 candidate_set.Add (param_type);
875 if (candidate_set.Count != 0)
876 return FindMostEncompassedType (ec, candidate_set);
882 if (apply_explicit_conv_rules)
883 return FindMostEncompassingType (ec, src_types_set);
885 return FindMostEncompassedType (ec, src_types_set);
889 // Useful in avoiding proliferation of objects
891 static EmptyExpression priv_fmt_expr;
894 /// Finds the most specific target Tx according to section 13.4.4
896 static public Type FindMostSpecificTarget (EmitContext ec, MethodGroupExpr me,
897 Type target, bool apply_explicit_conv_rules,
900 ArrayList tgt_types_set = new ArrayList ();
902 if (priv_fmt_expr == null)
903 priv_fmt_expr = new EmptyExpression ();
906 // If any operator converts to T then Tx = T
908 foreach (MethodInfo mi in me.Methods){
909 Type ret_type = mi.ReturnType;
911 if (ret_type == target)
914 if (apply_explicit_conv_rules) {
917 // Find the set of applicable user-defined conversion operators, U.
919 // This set consists of the
920 // user-defined implicit or explicit conversion operators declared by
921 // the classes or structs in D that convert from a type encompassing
922 // or encompassed by S to a type encompassing or encompassed by T
924 priv_fms_expr.SetType (ret_type);
925 if (WideningStandardConversionExists (ec, priv_fms_expr, target))
926 tgt_types_set.Add (ret_type);
928 priv_fms_expr.SetType (target);
929 if (WideningStandardConversionExists (ec, priv_fms_expr, ret_type))
930 tgt_types_set.Add (ret_type);
934 // Only if T is encompassed by param_type
936 priv_fms_expr.SetType (ret_type);
937 if (WideningStandardConversionExists (ec, priv_fms_expr, target))
938 tgt_types_set.Add (ret_type);
943 // Explicit conv rules
945 if (apply_explicit_conv_rules) {
946 ArrayList candidate_set = new ArrayList ();
948 foreach (Type ret_type in tgt_types_set){
949 priv_fmt_expr.SetType (ret_type);
951 if (WideningStandardConversionExists (ec, priv_fmt_expr, target))
952 candidate_set.Add (ret_type);
955 if (candidate_set.Count != 0)
956 return FindMostEncompassingType (ec, candidate_set);
960 // Okay, final case !
962 if (apply_explicit_conv_rules)
963 return FindMostEncompassedType (ec, tgt_types_set);
965 return FindMostEncompassingType (ec, tgt_types_set);
969 /// User-defined Implicit conversions
973 // VB.NET has no notion of User defined conversions
976 // static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
977 // Type target, Location loc)
979 // return UserDefinedConversion (ec, source, target, loc, false);
983 /// User-defined Explicit conversions
987 // VB.NET has no notion of User defined conversions
990 // static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
991 // Type target, Location loc)
993 // return UserDefinedConversion (ec, source, target, loc, true);
996 static DoubleHash explicit_conv = new DoubleHash (100);
997 static DoubleHash implicit_conv = new DoubleHash (100);
999 /// Computes the MethodGroup for the user-defined conversion
1000 /// operators from source_type to target_type. `look_for_explicit'
1001 /// controls whether we should also include the list of explicit
1004 static MethodGroupExpr GetConversionOperators (EmitContext ec,
1005 Type source_type, Type target_type,
1006 Location loc, bool look_for_explicit)
1008 Expression mg1 = null, mg2 = null;
1009 Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
1012 op_name = "op_Implicit";
1014 MethodGroupExpr union3;
1016 if ((look_for_explicit ? explicit_conv : implicit_conv).Lookup (source_type, target_type, out r))
1017 return (MethodGroupExpr) r;
1019 mg1 = Expression.MethodLookup (ec, source_type, op_name, loc);
1020 if (source_type.BaseType != null)
1021 mg2 = Expression.MethodLookup (ec, source_type.BaseType, op_name, loc);
1024 union3 = (MethodGroupExpr) mg2;
1025 else if (mg2 == null)
1026 union3 = (MethodGroupExpr) mg1;
1028 union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
1030 mg1 = Expression.MethodLookup (ec, target_type, op_name, loc);
1033 union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1035 union3 = (MethodGroupExpr) mg1;
1038 if (target_type.BaseType != null)
1039 mg1 = Expression.MethodLookup (ec, target_type.BaseType, op_name, loc);
1043 union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1045 union3 = (MethodGroupExpr) mg1;
1048 MethodGroupExpr union4 = null;
1050 if (look_for_explicit) {
1051 op_name = "op_Explicit";
1053 mg5 = Expression.MemberLookup (ec, source_type, op_name, loc);
1054 if (source_type.BaseType != null)
1055 mg6 = Expression.MethodLookup (ec, source_type.BaseType, op_name, loc);
1057 mg7 = Expression.MemberLookup (ec, target_type, op_name, loc);
1058 if (target_type.BaseType != null)
1059 mg8 = Expression.MethodLookup (ec, target_type.BaseType, op_name, loc);
1061 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
1062 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
1064 union4 = Invocation.MakeUnionSet (union5, union6, loc);
1067 MethodGroupExpr ret = Invocation.MakeUnionSet (union3, union4, loc);
1068 (look_for_explicit ? explicit_conv : implicit_conv).Insert (source_type, target_type, ret);
1073 /// User-defined conversions
1077 // VB.NET has no notion of User defined conversions. This method is not used.
1079 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1080 Type target, Location loc,
1081 bool look_for_explicit)
1083 MethodGroupExpr union;
1084 Type source_type = source.Type;
1085 MethodBase method = null;
1087 union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
1091 Type most_specific_source, most_specific_target;
1093 most_specific_source = FindMostSpecificSource (ec, union, source, look_for_explicit, loc);
1094 if (most_specific_source == null)
1097 most_specific_target = FindMostSpecificTarget (ec, union, target, look_for_explicit, loc);
1098 if (most_specific_target == null)
1104 foreach (MethodBase mb in union.Methods){
1105 ParameterData pd = Invocation.GetParameterData (mb);
1106 MethodInfo mi = (MethodInfo) mb;
1108 if (pd.ParameterType (0) == most_specific_source &&
1109 mi.ReturnType == most_specific_target) {
1115 if (method == null || count > 1)
1120 // This will do the conversion to the best match that we
1121 // found. Now we need to perform an implict standard conversion
1122 // if the best match was not the type that we were requested
1125 if (look_for_explicit)
1126 source = WideningAndNarrowingConversionStandard (ec, source, most_specific_source, loc);
1128 source = WideningConversionStandard (ec, source, most_specific_source, loc);
1134 e = new UserCast ((MethodInfo) method, source, loc);
1135 if (e.Type != target){
1136 if (!look_for_explicit)
1137 e = WideningConversionStandard (ec, e, target, loc);
1139 e = WideningAndNarrowingConversionStandard (ec, e, target, loc);
1146 /// Converts implicitly the resolved expression `expr' into the
1147 /// `target_type'. It returns a new expression that can be used
1148 /// in a context that expects a `target_type'.
1150 static public Expression WideningConversion (EmitContext ec, Expression expr,
1151 Type target_type, Location loc)
1155 if (target_type == null)
1156 throw new Exception ("Target type is null");
1158 e = WideningConversionStandard (ec, expr, target_type, loc);
1163 // VB.NET has no notion of User defined conversions
1166 // e = ImplicitUserConversion (ec, expr, target_type, loc);
1175 /// Attempts to apply the `Standard Implicit
1176 /// Conversion' rules to the expression `expr' into
1177 /// the `target_type'. It returns a new expression
1178 /// that can be used in a context that expects a
1181 /// This is different from `WideningConversion' in that the
1182 /// user defined implicit conversions are excluded.
1184 static public Expression WideningConversionStandard (EmitContext ec, Expression expr,
1185 Type target_type, Location loc)
1187 Type expr_type = expr.Type;
1190 if ((expr is NullLiteral) && target_type.IsGenericParameter)
1191 return TypeParameter_to_Null (expr, target_type, loc);
1193 if (expr.eclass == ExprClass.MethodGroup){
1194 if (!TypeManager.IsDelegateType (target_type)){
1199 // Only allow anonymous method conversions on post ISO_1
1201 if (RootContext.Version != LanguageVersion.ISO_1){
1202 MethodGroupExpr mg = expr as MethodGroupExpr;
1204 return ImplicitDelegateCreation.Create (ec, mg, target_type, loc);
1208 if (expr_type.Equals (target_type) && !TypeManager.IsNullType (expr_type))
1211 e = WideningNumericConversion (ec, expr, target_type, loc);
1215 e = WideningReferenceConversion (ec, expr, target_type);
1219 if ((target_type == TypeManager.enum_type ||
1220 target_type.IsSubclassOf (TypeManager.enum_type)) &&
1221 expr is IntLiteral){
1222 IntLiteral i = (IntLiteral) expr;
1225 return new EnumConstant ((Constant) expr, target_type);
1229 if (expr_type.IsPointer){
1230 if (target_type == TypeManager.void_ptr_type)
1231 return new EmptyCast (expr, target_type);
1234 // yep, comparing pointer types cant be done with
1235 // t1 == t2, we have to compare their element types.
1237 if (target_type.IsPointer){
1238 if (TypeManager.GetElementType(target_type) == TypeManager.GetElementType(expr_type))
1243 if (target_type.IsPointer) {
1244 if (expr_type == TypeManager.null_type)
1245 return new EmptyCast (expr, target_type);
1247 if (expr_type == TypeManager.void_ptr_type)
1248 return new EmptyCast (expr, target_type);
1252 if (expr_type == TypeManager.anonymous_method_type){
1253 if (!TypeManager.IsDelegateType (target_type)){
1254 Report.Error (1660, loc,
1255 "Cannot convert anonymous method to `{0}', since it is not a delegate",
1256 TypeManager.CSharpName (target_type));
1260 AnonymousMethod am = (AnonymousMethod) expr;
1261 int errors = Report.Errors;
1263 Expression conv = am.Compatible (ec, target_type, false);
1268 // We return something instead of null, to avoid
1269 // the duplicate error, since am.Compatible would have
1270 // reported that already
1272 if (errors != Report.Errors)
1273 return new EmptyCast (expr, target_type);
1277 // VB.NET specific conversions
1280 e = WideningStringConversions (ec, expr, target_type, loc);
1289 /// Attempts to perform an implicit constant conversion of the IntConstant
1290 /// into a different data type using casts (See Implicit Constant
1291 /// Expression Conversions)
1293 static public Expression TryWideningIntConversion (Type target_type, IntConstant ic)
1295 int value = ic.Value;
1297 if (target_type == TypeManager.sbyte_type){
1298 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1299 return new SByteConstant ((sbyte) value);
1300 } else if (target_type == TypeManager.byte_type){
1301 if (value >= Byte.MinValue && value <= Byte.MaxValue)
1302 return new ByteConstant ((byte) value);
1303 } else if (target_type == TypeManager.short_type){
1304 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1305 return new ShortConstant ((short) value);
1306 } else if (target_type == TypeManager.ushort_type){
1307 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1308 return new UShortConstant ((ushort) value);
1309 } else if (target_type == TypeManager.uint32_type){
1311 return new UIntConstant ((uint) value);
1312 } else if (target_type == TypeManager.uint64_type){
1314 // we can optimize this case: a positive int32
1315 // always fits on a uint64. But we need an opcode
1319 return new ULongConstant ((ulong) value);
1320 } else if (target_type == TypeManager.double_type)
1321 return new DoubleConstant ((double) value);
1322 else if (target_type == TypeManager.float_type)
1323 return new FloatConstant ((float) value);
1325 if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
1326 Type underlying = TypeManager.EnumToUnderlying (target_type);
1327 Constant e = (Constant) ic;
1330 // Possibly, we need to create a different 0 literal before passing
1333 if (underlying == TypeManager.int64_type)
1334 e = new LongLiteral (0);
1335 else if (underlying == TypeManager.uint64_type)
1336 e = new ULongLiteral (0);
1338 return new EnumConstant (e, target_type);
1342 // If `target_type' is an interface and the type of `ic' implements the interface
1343 // e.g. target_type is IComparable, IConvertible, IFormattable
1345 if (target_type.IsInterface && target_type.IsAssignableFrom (ic.Type))
1346 return new BoxedCast (ic);
1351 static public void Error_CannotWideningConversion (Location loc, Type source, Type target)
1353 if (source.Name == target.Name){
1354 Report.ExtraInformation (loc,
1356 "The type {0} has two conflicting definitons, one comes from {0} and the other from {1}",
1357 source.Assembly.FullName, target.Assembly.FullName));
1360 Report.Error (29, loc, "Cannot convert implicitly from {0} to `{1}'",
1361 source == TypeManager.anonymous_method_type ?
1362 "anonymous method" : "`" + TypeManager.CSharpName (source) + "'",
1363 TypeManager.CSharpName (target));
1367 /// Attempts to implicitly convert `source' into `target_type', using
1368 /// WideningConversion. If there is no implicit conversion, then
1369 /// an error is signaled
1371 static public Expression WideningConversionRequired (EmitContext ec, Expression source,
1372 Type target_type, Location loc)
1376 int errors = Report.Errors;
1377 e = WideningConversion (ec, source, target_type, loc);
1378 if (Report.Errors > errors)
1383 if (source is DoubleLiteral) {
1384 if (target_type == TypeManager.float_type) {
1385 Error_664 (loc, "float", "f");
1388 if (target_type == TypeManager.decimal_type) {
1389 Error_664 (loc, "decimal", "m");
1394 if (source is Constant){
1395 Constant c = (Constant) source;
1397 Expression.Error_ConstantValueCannotBeConverted (loc, c.AsString (), target_type);
1401 Error_CannotWideningConversion (loc, source.Type, target_type);
1406 static void Error_664 (Location loc, string type, string suffix) {
1407 Report.Error (664, loc,
1408 "Literal of type double cannot be implicitly converted to type '{0}'. Add suffix '{1}' to create a literal of this type",
1413 /// Performs the explicit numeric conversions
1417 /// Performs the explicit numeric conversions
1419 static Expression NarrowingNumericConversion (EmitContext ec, Expression expr, Type target_type, Location loc)
1421 Type expr_type = expr.Type;
1424 // If we have an enumeration, extract the underlying type,
1425 // use this during the comparison, but wrap around the original
1428 Type real_target_type = target_type;
1430 if (TypeManager.IsEnumType (real_target_type))
1431 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
1433 if (WideningStandardConversionExists (ec, expr, real_target_type)){
1434 Expression ce = WideningConversionStandard (ec, expr, real_target_type, loc);
1436 if (real_target_type != target_type)
1437 return new EmptyCast (ce, target_type);
1441 if (expr_type == TypeManager.short_type){
1443 // From short to byte
1445 if (real_target_type == TypeManager.byte_type)
1446 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
1447 } else if (expr_type == TypeManager.int32_type){
1449 // From int to byte, short
1451 if (real_target_type == TypeManager.byte_type)
1452 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
1453 if (real_target_type == TypeManager.short_type)
1454 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
1455 } else if (expr_type == TypeManager.int64_type){
1457 // From long to byte, short, int
1459 if (real_target_type == TypeManager.byte_type)
1460 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
1461 if (real_target_type == TypeManager.short_type)
1462 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
1463 if (real_target_type == TypeManager.int32_type)
1464 return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
1465 } else if (expr_type == TypeManager.decimal_type){
1467 // From decimal to byte, short, int, long
1469 if (real_target_type == TypeManager.byte_type)
1470 return new ImplicitInvocation (ec, "System", "Convert" , "ToByte", loc, expr);
1471 if (real_target_type == TypeManager.short_type)
1472 return new ImplicitInvocation (ec, "System", "Convert", "ToInt16", loc, expr);
1473 if (real_target_type == TypeManager.int32_type)
1474 return new ImplicitInvocation (ec, "System", "Convert", "ToInt32", loc, expr);
1475 if (real_target_type == TypeManager.int64_type)
1476 return new ImplicitInvocation (ec, "System", "Convert", "ToInt64", loc, expr);
1477 } else if (expr_type == TypeManager.float_type){
1479 // From float to byte, short, int, long, decimal
1481 if (real_target_type == TypeManager.byte_type)
1482 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1483 if (real_target_type == TypeManager.short_type)
1484 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1485 if (real_target_type == TypeManager.int32_type)
1486 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1487 if (real_target_type == TypeManager.int64_type)
1488 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1489 if (real_target_type == TypeManager.decimal_type)
1490 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
1491 } else if (expr_type == TypeManager.double_type){
1493 // From double to byte, short, int, long, float, decimal
1495 if (real_target_type == TypeManager.byte_type)
1496 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1497 if (real_target_type == TypeManager.short_type)
1498 return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1499 if (real_target_type == TypeManager.int32_type)
1500 return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1501 if (real_target_type == TypeManager.int64_type)
1502 return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1503 if (real_target_type == TypeManager.float_type)
1504 return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
1505 if (real_target_type == TypeManager.decimal_type)
1506 return new ImplicitNew (ec, "System", "Decimal", loc, expr);
1513 /// VB.NET specific: Convert to and from boolean
1516 static public Expression BooleanConversions (EmitContext ec, Expression expr,
1517 Type target_type, Location loc)
1519 Type expr_type = expr.Type;
1520 Type real_target_type = target_type;
1522 if (expr_type == TypeManager.bool_type) {
1525 // From boolean to byte, short, int,
1526 // long, float, double, decimal
1529 if (real_target_type == TypeManager.byte_type)
1530 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_U1);
1531 if (real_target_type == TypeManager.short_type)
1532 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I2);
1533 if (real_target_type == TypeManager.int32_type)
1534 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I4);
1535 if (real_target_type == TypeManager.int64_type)
1536 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I8);
1537 if (real_target_type == TypeManager.float_type)
1538 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_R4);
1539 if (real_target_type == TypeManager.double_type)
1540 return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_R8);
1541 if (real_target_type == TypeManager.decimal_type) {
1542 return new ImplicitInvocation (ec, "DecimalType", "FromBoolean", loc, expr);
1544 } if (real_target_type == TypeManager.bool_type) {
1547 // From byte, short, int, long, float,
1548 // double, decimal to boolean
1551 if (expr_type == TypeManager.byte_type ||
1552 expr_type == TypeManager.short_type ||
1553 expr_type == TypeManager.int32_type ||
1554 expr_type == TypeManager.int64_type ||
1555 expr_type == TypeManager.float_type ||
1556 expr_type == TypeManager.double_type)
1557 return new NumericToBooleanCast (expr, expr_type);
1558 if (expr_type == TypeManager.decimal_type) {
1559 return new ImplicitInvocation (ec, "System", "Convert", "ToBoolean", loc, expr);
1567 /// VB.NET specific: Widening conversions to string
1570 static public Expression WideningStringConversions (EmitContext ec, Expression expr,
1571 Type target_type, Location loc)
1574 Type expr_type = expr.Type;
1575 Type real_target_type = target_type;
1577 if (real_target_type == TypeManager.string_type) {
1579 // From char to string
1581 if (expr_type == TypeManager.char_type)
1582 return new ImplicitInvocation (ec, "StringType", "FromChar", loc, expr);
1585 if(expr_type.IsArray && (expr_type.GetElementType() == TypeManager.char_type)) {
1587 // From char array to string
1589 return new ImplicitNew (ec, "System", "String", loc, expr);
1596 /// VB.NET specific: Narrowing conversions involving strings
1599 static public Expression NarrowingStringConversions (EmitContext ec, Expression expr,
1600 Type target_type, Location loc)
1602 Type expr_type = expr.Type;
1603 Type real_target_type = target_type;
1605 // FIXME: Need to take care of Constants
1607 if (expr_type == TypeManager.string_type) {
1610 // From string to chararray, bool,
1611 // byte, short, char, int, long,
1612 // float, double, decimal and date
1615 if (real_target_type.IsArray && (real_target_type.GetElementType() == TypeManager.char_type))
1616 return new ImplicitInvocation (ec, "CharArrayType", "FromString", loc, expr);
1617 if (real_target_type == TypeManager.bool_type)
1618 return new ImplicitInvocation (ec, "BooleanType", "FromString", loc, expr);
1619 if (real_target_type == TypeManager.byte_type)
1620 return new ImplicitInvocation (ec, "ByteType", "FromString", loc, expr);
1621 if (real_target_type == TypeManager.short_type)
1622 return new ImplicitInvocation (ec, "ShortType", "FromString", loc, expr);
1623 if (real_target_type == TypeManager.char_type)
1624 return new ImplicitInvocation (ec, "CharType", "FromString", loc, expr);
1625 if (real_target_type == TypeManager.int32_type)
1626 return new ImplicitInvocation (ec, "IntegerType", "FromString", loc, expr);
1627 if (real_target_type == TypeManager.int64_type)
1628 return new ImplicitInvocation (ec, "LongType", "FromString", loc, expr);
1629 if (real_target_type == TypeManager.float_type)
1630 return new ImplicitInvocation (ec, "SingleType", "FromString", loc, expr);
1631 if (real_target_type == TypeManager.double_type)
1632 return new ImplicitInvocation (ec, "DoubleType", "FromString", loc, expr);
1633 if (real_target_type == TypeManager.decimal_type)
1634 return new ImplicitInvocation (ec, "DecimalType", "FromString", loc, expr);
1635 if (real_target_type == TypeManager.date_type)
1636 return new ImplicitInvocation (ec, "DateType", "FromString", loc, expr);
1637 } if (real_target_type == TypeManager.string_type) {
1640 // From bool, byte, short, char, int,
1641 // long, float, double, decimal and
1645 if (expr_type == TypeManager.bool_type)
1646 return new ImplicitInvocation (ec, "StringType", "FromBoolean", loc, expr);
1647 if (expr_type == TypeManager.byte_type)
1648 return new ImplicitInvocation (ec, "StringType", "FromByte", loc, expr);
1649 if (expr_type == TypeManager.short_type)
1650 return new ImplicitInvocation (ec, "StringType", "FromShort", loc, expr);
1651 if (expr_type == TypeManager.int32_type)
1652 return new ImplicitInvocation (ec, "StringType", "FromInteger", loc, expr);
1653 if (expr_type == TypeManager.int64_type)
1654 return new ImplicitInvocation (ec, "StringType", "FromLong", loc, expr);
1655 if (expr_type == TypeManager.float_type)
1656 return new ImplicitInvocation (ec, "StringType", "FromSingle", loc, expr);
1657 if (expr_type == TypeManager.double_type)
1658 return new ImplicitInvocation (ec, "StringType", "FromDouble", loc, expr);
1659 if (expr_type == TypeManager.decimal_type)
1660 return new ImplicitInvocation (ec, "StringType", "FromDecimal", loc, expr);
1661 if (expr_type == TypeManager.date_type)
1662 return new ImplicitInvocation (ec, "StringType", "FromDate", loc, expr);
1669 /// Returns whether an explicit reference conversion can be performed
1670 /// from source_type to target_type
1672 public static bool NarrowingReferenceConversionExists (Type source_type, Type target_type)
1674 bool target_is_type_param = target_type.IsGenericParameter;
1675 bool target_is_value_type = target_type.IsValueType;
1677 if (source_type == target_type)
1681 // From object to a generic parameter
1683 if (source_type == TypeManager.object_type && target_is_type_param)
1687 // From object to any reference type
1689 if (source_type == TypeManager.object_type && !target_is_value_type)
1693 // From any class S to any class-type T, provided S is a base class of T
1695 if (TypeManager.IsSubclassOf (target_type, source_type))
1699 // From any interface type S to any interface T provided S is not derived from T
1701 if (source_type.IsInterface && target_type.IsInterface){
1702 if (!TypeManager.IsSubclassOf (target_type, source_type))
1707 // From any class type S to any interface T, provided S is not sealed
1708 // and provided S does not implement T.
1710 if (target_type.IsInterface && !source_type.IsSealed &&
1711 !TypeManager.ImplementsInterface (source_type, target_type))
1715 // From any interface-type S to to any class type T, provided T is not
1716 // sealed, or provided T implements S.
1718 if (source_type.IsInterface &&
1719 (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
1723 // From an array type S with an element type Se to an array type T with an
1724 // element type Te provided all the following are true:
1725 // * S and T differe only in element type, in other words, S and T
1726 // have the same number of dimensions.
1727 // * Both Se and Te are reference types
1728 // * An explicit referenc conversions exist from Se to Te
1730 if (source_type.IsArray && target_type.IsArray) {
1731 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1733 Type source_element_type = TypeManager.GetElementType (source_type);
1734 Type target_element_type = TypeManager.GetElementType (target_type);
1736 if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1737 if (NarrowingReferenceConversionExists (source_element_type,
1738 target_element_type))
1744 // From System.Array to any array-type
1745 if (source_type == TypeManager.array_type &&
1746 target_type.IsArray){
1751 // From System delegate to any delegate-type
1753 if (source_type == TypeManager.delegate_type &&
1754 TypeManager.IsDelegateType (target_type))
1758 // From ICloneable to Array or Delegate types
1760 if (source_type == TypeManager.icloneable_type &&
1761 (target_type == TypeManager.array_type ||
1762 target_type == TypeManager.delegate_type))
1769 /// Implements Explicit Reference conversions
1771 static Expression NarrowingReferenceConversion (Expression source, Type target_type)
1773 Type source_type = source.Type;
1774 bool target_is_type_param = target_type.IsGenericParameter;
1775 bool target_is_value_type = target_type.IsValueType;
1778 // From object to a generic parameter
1780 if (source_type == TypeManager.object_type && target_is_type_param)
1781 return new UnboxCast (source, target_type);
1784 // From object to any reference type
1786 if (source_type == TypeManager.object_type && !target_is_value_type)
1787 return new ClassCast (source, target_type);
1790 // Unboxing conversion.
1792 if (((source_type == TypeManager.enum_type &&
1793 !(source is EmptyCast)) ||
1794 source_type == TypeManager.value_type) && target_is_value_type)
1795 return new UnboxCast (source, target_type);
1798 // From any class S to any class-type T, provided S is a base class of T
1800 if (TypeManager.IsSubclassOf (target_type, source_type))
1801 return new ClassCast (source, target_type);
1804 // From any interface type S to any interface T provided S is not derived from T
1806 if (source_type.IsInterface && target_type.IsInterface){
1807 if (TypeManager.ImplementsInterface (source_type, target_type))
1810 return new ClassCast (source, target_type);
1814 // From any class type S to any interface T, provides S is not sealed
1815 // and provided S does not implement T.
1817 if (target_type.IsInterface && !source_type.IsSealed) {
1818 if (TypeManager.ImplementsInterface (source_type, target_type))
1821 return new ClassCast (source, target_type);
1826 // From any interface-type S to to any class type T, provided T is not
1827 // sealed, or provided T implements S.
1829 if (source_type.IsInterface) {
1830 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)) {
1831 if (target_type.IsClass)
1832 return new ClassCast (source, target_type);
1834 return new UnboxCast (source, target_type);
1840 // From an array type S with an element type Se to an array type T with an
1841 // element type Te provided all the following are true:
1842 // * S and T differe only in element type, in other words, S and T
1843 // have the same number of dimensions.
1844 // * Both Se and Te are reference types
1845 // * An explicit referenc conversions exist from Se to Te
1847 if (source_type.IsArray && target_type.IsArray) {
1848 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1850 Type source_element_type = TypeManager.GetElementType (source_type);
1851 Type target_element_type = TypeManager.GetElementType (target_type);
1853 if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1854 if (NarrowingReferenceConversionExists (source_element_type,
1855 target_element_type))
1856 return new ClassCast (source, target_type);
1861 // From System.Array to any array-type
1862 if (source_type == TypeManager.array_type &&
1863 target_type.IsArray) {
1864 return new ClassCast (source, target_type);
1868 // From System delegate to any delegate-type
1870 if (source_type == TypeManager.delegate_type &&
1871 TypeManager.IsDelegateType (target_type))
1872 return new ClassCast (source, target_type);
1875 // From ICloneable to Array or Delegate types
1877 if (source_type == TypeManager.icloneable_type &&
1878 (target_type == TypeManager.array_type ||
1879 target_type == TypeManager.delegate_type))
1880 return new ClassCast (source, target_type);
1886 /// Performs an explicit conversion of the expression `expr' whose
1887 /// type is expr.Type to `target_type'.
1889 static public Expression WideningAndNarrowingConversion (EmitContext ec, Expression expr,
1890 Type target_type, Location loc)
1892 Type expr_type = expr.Type;
1893 Type original_expr_type = expr_type;
1895 if (expr_type.IsSubclassOf (TypeManager.enum_type)){
1896 if (target_type == TypeManager.enum_type ||
1897 target_type == TypeManager.object_type) {
1898 if (expr is EnumConstant)
1899 expr = ((EnumConstant) expr).Child;
1900 // We really need all these casts here .... :-(
1901 expr = new BoxedCast (new EmptyCast (expr, expr_type));
1902 return new EmptyCast (expr, target_type);
1903 } else if ((expr_type == TypeManager.enum_type) && target_type.IsValueType &&
1904 target_type.IsSubclassOf (TypeManager.enum_type))
1905 return new UnboxCast (expr, target_type);
1908 // Notice that we have kept the expr_type unmodified, which is only
1910 if (expr is EnumConstant)
1911 expr = ((EnumConstant) expr).Child;
1913 expr = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
1914 expr_type = expr.Type;
1917 int errors = Report.Errors;
1918 Expression ne = WideningConversionStandard (ec, expr, target_type, loc);
1919 if (Report.Errors > errors)
1925 ne = NarrowingNumericConversion (ec, expr, target_type, loc);
1930 // Unboxing conversion.
1932 if (expr_type == TypeManager.object_type && target_type.IsValueType)
1933 return new UnboxCast (expr, target_type);
1936 // Skip the NarrowingReferenceConversion because we can not convert
1937 // from Null to a ValueType, and ExplicitReference wont check against
1938 // null literal explicitly
1940 if (expr_type != TypeManager.null_type){
1941 ne = NarrowingReferenceConversion (expr, target_type);
1948 if (target_type.IsPointer){
1949 if (expr_type.IsPointer)
1950 return new EmptyCast (expr, target_type);
1952 if (expr_type == TypeManager.sbyte_type ||
1953 expr_type == TypeManager.byte_type ||
1954 expr_type == TypeManager.short_type ||
1955 expr_type == TypeManager.ushort_type ||
1956 expr_type == TypeManager.int32_type ||
1957 expr_type == TypeManager.uint32_type ||
1958 expr_type == TypeManager.uint64_type ||
1959 expr_type == TypeManager.int64_type)
1960 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
1962 if (expr_type.IsPointer){
1963 Expression e = null;
1965 if (target_type == TypeManager.sbyte_type)
1966 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1967 else if (target_type == TypeManager.byte_type)
1968 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1969 else if (target_type == TypeManager.short_type)
1970 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1971 else if (target_type == TypeManager.ushort_type)
1972 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1973 else if (target_type == TypeManager.int32_type)
1974 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1975 else if (target_type == TypeManager.uint32_type)
1976 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1977 else if (target_type == TypeManager.uint64_type)
1978 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1979 else if (target_type == TypeManager.int64_type){
1980 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1986 ci = WideningConversionStandard (ec, e, target_type, loc);
1991 ce = NarrowingNumericConversion (ec, e, target_type, loc);
1995 // We should always be able to go from an uint32
1996 // implicitly or explicitly to the other integral
1999 throw new Exception ("Internal compiler error");
2005 // VB.NET specific conversions
2008 ne = BooleanConversions (ec, expr, target_type, loc);
2012 ne = NarrowingStringConversions (ec, expr, target_type, loc);
2018 // VB.NET has no notion of User defined conversions
2021 // ne = ExplicitUserConversion (ec, expr, target_type, loc);
2025 if (expr is NullLiteral){
2026 Report.Error (37, loc, "Cannot convert null to value type `" +
2027 TypeManager.CSharpName (target_type) + "'");
2031 Error_CannotConvertType (loc, original_expr_type, target_type);
2036 /// Same as WideningAndNarrowingConversion, only it doesn't include user defined conversions
2038 static public Expression WideningAndNarrowingConversionStandard (EmitContext ec, Expression expr,
2039 Type target_type, Location l)
2041 int errors = Report.Errors;
2042 Expression ne = WideningConversionStandard (ec, expr, target_type, l);
2043 if (Report.Errors > errors)
2049 ne = NarrowingNumericConversion (ec, expr, target_type, l);
2053 ne = NarrowingReferenceConversion (expr, target_type);
2057 Error_CannotConvertType (l, expr.Type, target_type);