2010-05-31 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / convert.cs
blob5035991802c07dcc7c8cd3cbe8729a46cb7cb07e
1 //
2 // conversion.cs: various routines for implementing conversions.
3 //
4 // Authors:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Ravi Pratap (ravi@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
8 //
9 // Copyright 2001, 2002, 2003 Ximian, Inc.
10 // Copyright 2003-2008 Novell, Inc.
13 using System;
14 using System.Collections.Generic;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
22 // A container class for all the conversion operations
24 static class Convert {
26 static EmptyExpression MyEmptyExpr;
27 static DoubleHash explicit_conv;
28 static DoubleHash implicit_conv;
30 static Convert ()
32 Reset ();
35 public static void Reset ()
37 MyEmptyExpr = null;
38 explicit_conv = new DoubleHash (100);
39 implicit_conv = new DoubleHash (100);
43 // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
44 // interfaces of this interface, provided there is an implicit reference conversion
45 // from S to T.
47 static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
49 if (array.Rank != 1 || !list.IsGeneric)
50 return false;
52 var open_version = list.GetDefinition ();
53 if ((open_version != TypeManager.generic_ilist_type) &&
54 (open_version != TypeManager.generic_icollection_type) &&
55 (open_version != TypeManager.generic_ienumerable_type))
56 return false;
58 var arg_type = list.TypeArguments[0];
59 if (array.Element == arg_type)
60 return true;
62 if (isExplicit)
63 return ExplicitReferenceConversionExists (array.Element, arg_type);
65 if (MyEmptyExpr == null)
66 MyEmptyExpr = new EmptyExpression (array.Element);
67 else
68 MyEmptyExpr.SetType (array.Element);
70 return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type);
73 static bool IList_To_Array(TypeSpec list, ArrayContainer array)
75 if (array.Rank != 1 || !list.IsGeneric)
76 return false;
78 var open_version = list.GetDefinition ();
79 if ((open_version != TypeManager.generic_ilist_type) &&
80 (open_version != TypeManager.generic_icollection_type) &&
81 (open_version != TypeManager.generic_ienumerable_type))
82 return false;
84 var arg_type = list.TypeArguments[0];
85 if (array.Element == arg_type)
86 return true;
88 if (MyEmptyExpr == null)
89 MyEmptyExpr = new EmptyExpression (array.Element);
90 else
91 MyEmptyExpr.SetType (array.Element);
93 return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
96 static Expression ImplicitTypeParameterConversion (Expression expr, TypeSpec target_type)
98 var expr_type = (TypeParameterSpec) expr.Type;
100 // From T to a type parameter U
102 var ttype = target_type as TypeParameterSpec;
103 if (ttype != null) {
104 if (expr_type.IsReferenceType && !ttype.IsReferenceType)
105 return new BoxedCast (expr, target_type);
107 return new ClassCast (expr, target_type);
111 // From T to its effective base class C
112 // From T to any base class of C
113 // From T to any interface implemented by C
115 var base_type = expr_type.GetEffectiveBase ();
116 if (base_type == target_type || TypeManager.IsSubclassOf (base_type, target_type) || base_type.ImplementsInterface (target_type)) {
117 if (expr_type.IsReferenceType)
118 return new ClassCast (expr, target_type);
120 return new BoxedCast (expr, target_type);
123 var effective_ifaces = expr_type.Interfaces;
124 if (effective_ifaces != null) {
125 foreach (var t in effective_ifaces) {
126 if (t == target_type || t.ImplementsInterface (target_type)) {
127 if (expr_type.IsReferenceType)
128 return new ClassCast (expr, target_type);
130 return new BoxedCast (expr, target_type);
135 return null;
138 static Expression ExplicitTypeParameterConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
140 var target_tp = target_type as TypeParameterSpec;
141 if (target_tp != null) {
142 if (target_tp.Interfaces != null) {
143 foreach (TypeSpec iface in target_tp.Interfaces) {
144 if (!TypeManager.IsGenericParameter (iface))
145 continue;
147 if (TypeManager.IsSubclassOf (source_type, iface))
148 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
152 return null;
155 if (target_type.IsInterface)
156 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
158 return null;
161 static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
163 TypeSpec expr_type = expr.Type;
165 if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
166 // if we are a method group, emit a warning
168 expr.Emit (null);
171 if (expr_type == TypeManager.void_type)
172 return null;
174 if (expr_type.Kind == MemberKind.TypeParameter)
175 return ImplicitTypeParameterConversion (expr, target_type);
178 // from the null type to any reference-type.
180 NullLiteral nl = expr as NullLiteral;
181 if (nl != null) {
182 return nl.ConvertImplicitly (null, target_type);
185 if (ImplicitReferenceConversionExists (expr, target_type)) {
187 // Avoid wrapping implicitly convertible reference type
189 if (!explicit_cast)
190 return expr;
192 return EmptyCast.Create (expr, target_type);
195 bool use_class_cast;
196 if (ImplicitBoxingConversionExists (expr_type, target_type, out use_class_cast)) {
197 if (use_class_cast)
198 return new ClassCast (expr, target_type);
199 else
200 return new BoxedCast (expr, target_type);
203 return null;
207 // 6.1.6 Implicit reference conversions
209 public static bool ImplicitReferenceConversionExists (Expression expr, TypeSpec target_type)
211 if (TypeManager.IsStruct (target_type))
212 return false;
214 TypeSpec expr_type = expr.Type;
216 // from the null type to any reference-type.
217 if (expr_type == TypeManager.null_type)
218 return target_type != InternalType.AnonymousMethod;
220 if (TypeManager.IsGenericParameter (expr_type))
221 return ImplicitTypeParameterConversion (expr, target_type) != null;
223 // This code is kind of mirrored inside ImplicitStandardConversionExists
224 // with the small distinction that we only probe there
226 // Always ensure that the code here and there is in sync
228 // from any class-type S to any interface-type T.
229 if (target_type.IsInterface) {
230 if (expr_type.ImplementsInterface (target_type)){
231 return !TypeManager.IsValueType (expr_type);
236 // notice that it is possible to write "ValueType v = 1", the ValueType here
237 // is an abstract class, and not really a value type, so we apply the same rules.
239 if (target_type == TypeManager.object_type || target_type == InternalType.Dynamic) {
241 // A pointer type cannot be converted to object
243 if (expr_type.IsPointer)
244 return false;
246 if (TypeManager.IsValueType (expr_type))
247 return false;
249 if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type || expr_type.IsDelegate) {
250 // No mcs internal types are convertible
251 return true; // expr_type.MetaInfo.Module != typeof (Convert).Module;
254 // From anything to dynamic
255 if (target_type == InternalType.Dynamic)
256 return true;
258 // From dynamic to object
259 if (expr_type == InternalType.Dynamic)
260 return true;
262 return false;
263 } else if (target_type == TypeManager.value_type) {
264 return expr_type == TypeManager.enum_type;
265 } else if (TypeManager.IsSubclassOf (expr_type, target_type)) {
267 // Special case: enumeration to System.Enum.
268 // System.Enum is not a value type, it is a class, so we need
269 // a boxing conversion
271 if (target_type == TypeManager.enum_type || TypeManager.IsGenericParameter (expr_type))
272 return false;
274 if (TypeManager.IsValueType (expr_type))
275 return false;
277 // Array type variance conversion
278 //if (target_type.IsArray != expr_type.IsArray)
279 // return false;
281 return true;
284 var expr_type_array = expr_type as ArrayContainer;
285 if (expr_type_array != null) {
286 var target_type_array = target_type as ArrayContainer;
287 // from an array-type S to an array-type of type T
288 if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {
291 // Both SE and TE are reference-types
293 TypeSpec expr_element_type = expr_type_array.Element;
294 if (!TypeManager.IsReferenceType (expr_element_type))
295 return false;
297 TypeSpec target_element_type = target_type_array.Element;
298 if (!TypeManager.IsReferenceType (target_element_type))
299 return false;
301 if (MyEmptyExpr == null)
302 MyEmptyExpr = new EmptyExpression (expr_element_type);
303 else
304 MyEmptyExpr.SetType (expr_element_type);
306 return ImplicitStandardConversionExists (MyEmptyExpr, target_element_type);
309 // from an array-type to System.Array
310 if (target_type == TypeManager.array_type)
311 return true;
313 // from an array-type of type T to IList<T>
314 if (ArrayToIList (expr_type_array, target_type, false))
315 return true;
317 return false;
320 if (TypeSpecComparer.Variant.IsEqual (expr_type, target_type))
321 return true;
323 // from any interface type S to interface-type T.
324 if (expr_type.IsInterface && target_type.IsInterface) {
325 return expr_type.ImplementsInterface (target_type);
328 // from any delegate type to System.Delegate
329 if (target_type == TypeManager.delegate_type &&
330 (expr_type == TypeManager.delegate_type || expr_type.IsDelegate))
331 return true;
333 if (TypeManager.IsEqual (expr_type, target_type))
334 return true;
336 return false;
339 public static bool ImplicitBoxingConversionExists (TypeSpec expr_type, TypeSpec target_type, out bool use_class_cast)
341 use_class_cast = false;
344 // From any value-type to the type object.
346 if (target_type == TypeManager.object_type || target_type == InternalType.Dynamic) {
348 // A pointer type cannot be converted to object
350 if (expr_type.IsPointer)
351 return false;
353 return TypeManager.IsValueType (expr_type);
357 // From any value-type to the type System.ValueType.
359 if (target_type == TypeManager.value_type)
360 return TypeManager.IsValueType (expr_type);
362 if (target_type == TypeManager.enum_type) {
364 // From any enum-type to the type System.Enum.
366 if (TypeManager.IsEnumType (expr_type))
367 return true;
371 // From a nullable-type to a reference type, if a boxing conversion exists from
372 // the underlying type to the reference type
374 if (TypeManager.IsNullableType (expr_type)) {
375 if (!TypeManager.IsReferenceType (target_type))
376 return false;
378 return ImplicitBoxingConversionExists (Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type, out use_class_cast);
381 if (TypeManager.IsSubclassOf (expr_type, target_type)) {
383 // Don't box same type arguments
385 if (TypeManager.IsGenericParameter (expr_type) && expr_type != target_type)
386 return true;
388 return false;
391 // This code is kind of mirrored inside ImplicitStandardConversionExists
392 // with the small distinction that we only probe there
394 // Always ensure that the code here and there is in sync
396 // from any class-type S to any interface-type T.
397 if (target_type.IsInterface) {
398 if (expr_type.ImplementsInterface (target_type))
399 return TypeManager.IsGenericParameter (expr_type) ||
400 TypeManager.IsValueType (expr_type);
403 return false;
406 public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
408 TypeSpec expr_type = expr.Type;
411 // From null to any nullable type
413 if (expr_type == TypeManager.null_type)
414 return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
416 // S -> T?
417 TypeSpec t_el = TypeManager.GetTypeArguments (target_type)[0];
419 // S? -> T?
420 if (TypeManager.IsNullableType (expr_type))
421 expr_type = TypeManager.GetTypeArguments (expr_type)[0];
424 // Predefined implicit identity or implicit numeric conversion
425 // has to exist between underlying type S and underlying type T
428 // Handles probing
429 if (ec == null) {
430 if (expr_type == t_el)
431 return EmptyExpression.Null;
433 return ImplicitNumericConversion (null, expr_type, t_el);
436 Expression unwrap;
437 if (expr_type != expr.Type)
438 unwrap = Nullable.Unwrap.Create (expr);
439 else
440 unwrap = expr;
442 Expression conv = expr_type == t_el ? unwrap : ImplicitNumericConversion (unwrap, expr_type, t_el);
443 if (conv == null)
444 return null;
446 if (expr_type != expr.Type)
447 return new Nullable.Lifted (conv, unwrap, target_type).Resolve (ec);
449 // Do constant optimization for S -> T?
450 if (unwrap is Constant)
451 conv = ((Constant) unwrap).ConvertImplicitly (ec, t_el);
453 return Nullable.Wrap.Create (conv, target_type);
456 /// <summary>
457 /// Implicit Numeric Conversions.
459 /// expr is the expression to convert, returns a new expression of type
460 /// target_type or null if an implicit conversion is not possible.
461 /// </summary>
462 public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
464 return ImplicitNumericConversion (expr, expr.Type, target_type);
467 static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
469 if (expr_type == TypeManager.sbyte_type){
471 // From sbyte to short, int, long, float, double, decimal
473 if (target_type == TypeManager.int32_type)
474 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
475 if (target_type == TypeManager.int64_type)
476 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
477 if (target_type == TypeManager.double_type)
478 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
479 if (target_type == TypeManager.float_type)
480 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
481 if (target_type == TypeManager.short_type)
482 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
483 if (target_type == TypeManager.decimal_type)
484 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
485 } else if (expr_type == TypeManager.byte_type){
487 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
489 if (target_type == TypeManager.int32_type || target_type == TypeManager.uint32_type ||
490 target_type == TypeManager.short_type || target_type == TypeManager.ushort_type)
491 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
493 if (target_type == TypeManager.uint64_type)
494 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
495 if (target_type == TypeManager.int64_type)
496 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
497 if (target_type == TypeManager.float_type)
498 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
499 if (target_type == TypeManager.double_type)
500 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
501 if (target_type == TypeManager.decimal_type)
502 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
504 } else if (expr_type == TypeManager.short_type){
506 // From short to int, long, float, double, decimal
508 if (target_type == TypeManager.int32_type)
509 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
510 if (target_type == TypeManager.int64_type)
511 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
512 if (target_type == TypeManager.double_type)
513 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
514 if (target_type == TypeManager.float_type)
515 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
516 if (target_type == TypeManager.decimal_type)
517 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
519 } else if (expr_type == TypeManager.ushort_type){
521 // From ushort to int, uint, long, ulong, float, double, decimal
523 if (target_type == TypeManager.int32_type || target_type == TypeManager.uint32_type)
524 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
526 if (target_type == TypeManager.uint64_type)
527 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
528 if (target_type == TypeManager.int64_type)
529 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
530 if (target_type == TypeManager.double_type)
531 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
532 if (target_type == TypeManager.float_type)
533 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
534 if (target_type == TypeManager.decimal_type)
535 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
536 } else if (expr_type == TypeManager.int32_type){
538 // From int to long, float, double, decimal
540 if (target_type == TypeManager.int64_type)
541 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
542 if (target_type == TypeManager.double_type)
543 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
544 if (target_type == TypeManager.float_type)
545 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
546 if (target_type == TypeManager.decimal_type)
547 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
548 } else if (expr_type == TypeManager.uint32_type){
550 // From uint to long, ulong, float, double, decimal
552 if (target_type == TypeManager.int64_type)
553 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
554 if (target_type == TypeManager.uint64_type)
555 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
556 if (target_type == TypeManager.double_type)
557 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R8);
558 if (target_type == TypeManager.float_type)
559 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R4);
560 if (target_type == TypeManager.decimal_type)
561 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
562 } else if (expr_type == TypeManager.int64_type){
564 // From long/ulong to float, double
566 if (target_type == TypeManager.double_type)
567 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
568 if (target_type == TypeManager.float_type)
569 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
570 if (target_type == TypeManager.decimal_type)
571 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
572 } else if (expr_type == TypeManager.uint64_type){
574 // From ulong to float, double
576 if (target_type == TypeManager.double_type)
577 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R8);
578 if (target_type == TypeManager.float_type)
579 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R4);
580 if (target_type == TypeManager.decimal_type)
581 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
582 } else if (expr_type == TypeManager.char_type){
584 // From char to ushort, int, uint, long, ulong, float, double, decimal
586 if ((target_type == TypeManager.ushort_type) ||
587 (target_type == TypeManager.int32_type) ||
588 (target_type == TypeManager.uint32_type))
589 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
590 if (target_type == TypeManager.uint64_type)
591 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
592 if (target_type == TypeManager.int64_type)
593 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
594 if (target_type == TypeManager.float_type)
595 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
596 if (target_type == TypeManager.double_type)
597 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
598 if (target_type == TypeManager.decimal_type)
599 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
600 } else if (expr_type == TypeManager.float_type){
602 // float to double
604 if (target_type == TypeManager.double_type)
605 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
608 return null;
611 /// <summary>
612 /// Same as ImplicitStandardConversionExists except that it also looks at
613 /// implicit user defined conversions - needed for overload resolution
614 /// </summary>
615 public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
617 if (ImplicitStandardConversionExists (expr, target_type))
618 return true;
620 if (expr.Type == InternalType.AnonymousMethod) {
621 if (!TypeManager.IsDelegateType (target_type) && target_type.GetDefinition () != TypeManager.expression_type)
622 return false;
624 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
625 return ame.ImplicitStandardConversionExists (ec, target_type);
628 if (expr.eclass == ExprClass.MethodGroup) {
629 if (target_type.IsDelegate && RootContext.Version != LanguageVersion.ISO_1) {
630 MethodGroupExpr mg = expr as MethodGroupExpr;
631 if (mg != null)
632 return DelegateCreation.ImplicitStandardConversionExists (ec, mg, target_type);
635 return false;
638 return ImplicitUserConversion (ec, expr, target_type, Location.Null) != null;
641 /// <summary>
642 /// Determines if a standard implicit conversion exists from
643 /// expr_type to target_type
645 /// ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
646 /// </summary>
647 public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
649 TypeSpec expr_type = expr.Type;
651 if (expr_type == TypeManager.null_type) {
652 NullLiteral nl = expr as NullLiteral;
653 if (nl != null)
654 return nl.ConvertImplicitly (null, target_type) != null;
657 if (expr_type == TypeManager.void_type)
658 return false;
660 if (TypeManager.IsEqual (expr_type, target_type))
661 return true;
663 if (TypeManager.IsNullableType (target_type)) {
664 return ImplicitNulableConversion (null, expr, target_type) != null;
667 // First numeric conversions
668 if (ImplicitNumericConversion (null, expr_type, target_type) != null)
669 return true;
671 if (ImplicitReferenceConversionExists (expr, target_type))
672 return true;
674 bool use_class_cast;
675 if (ImplicitBoxingConversionExists (expr_type, target_type, out use_class_cast))
676 return true;
679 // Implicit Constant Expression Conversions
681 if (expr is IntConstant){
682 int value = ((IntConstant) expr).Value;
684 if (target_type == TypeManager.sbyte_type){
685 if (value >= SByte.MinValue && value <= SByte.MaxValue)
686 return true;
687 } else if (target_type == TypeManager.byte_type){
688 if (value >= 0 && value <= Byte.MaxValue)
689 return true;
690 } else if (target_type == TypeManager.short_type){
691 if (value >= Int16.MinValue && value <= Int16.MaxValue)
692 return true;
693 } else if (target_type == TypeManager.ushort_type){
694 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
695 return true;
696 } else if (target_type == TypeManager.uint32_type){
697 if (value >= 0)
698 return true;
699 } else if (target_type == TypeManager.uint64_type){
701 // we can optimize this case: a positive int32
702 // always fits on a uint64. But we need an opcode
703 // to do it.
705 if (value >= 0)
706 return true;
709 if (value == 0 && target_type.IsEnum)
710 return true;
713 if (expr is LongConstant && target_type == TypeManager.uint64_type){
715 // Try the implicit constant expression conversion
716 // from long to ulong, instead of a nice routine,
717 // we just inline it
719 long v = ((LongConstant) expr).Value;
720 if (v >= 0)
721 return true;
725 // If `expr_type' implements `target_type' (which is an iface)
726 // see TryImplicitIntConversion
728 if (target_type.IsInterface && expr_type.ImplementsInterface (target_type))
729 return true;
731 if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
732 return true;
734 // Conversion from __arglist to System.ArgIterator
735 if (expr_type == InternalType.Arglist)
736 return target_type == TypeManager.arg_iterator_type;
738 return false;
741 /// <summary>
742 /// Finds "most encompassed type" according to the spec (13.4.2)
743 /// amongst the methods in the MethodGroupExpr
744 /// </summary>
745 public static TypeSpec FindMostEncompassedType (IEnumerable<TypeSpec> types)
747 TypeSpec best = null;
748 EmptyExpression expr = EmptyExpression.Grab ();
750 foreach (TypeSpec t in types) {
751 if (best == null) {
752 best = t;
753 continue;
756 expr.SetType (t);
757 if (ImplicitStandardConversionExists (expr, best))
758 best = t;
761 expr.SetType (best);
762 foreach (TypeSpec t in types) {
763 if (best == t)
764 continue;
765 if (!ImplicitStandardConversionExists (expr, t)) {
766 best = null;
767 break;
771 EmptyExpression.Release (expr);
773 return best;
776 /// <summary>
777 /// Finds "most encompassing type" according to the spec (13.4.2)
778 /// amongst the types in the given set
779 /// </summary>
780 static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
782 TypeSpec best = null;
784 if (types.Count == 0)
785 return null;
787 if (types.Count == 1)
788 return types [0];
790 EmptyExpression expr = EmptyExpression.Grab ();
792 foreach (TypeSpec t in types) {
793 if (best == null) {
794 best = t;
795 continue;
798 expr.SetType (best);
799 if (ImplicitStandardConversionExists (expr, t))
800 best = t;
803 foreach (TypeSpec t in types) {
804 if (best == t)
805 continue;
806 expr.SetType (t);
807 if (!ImplicitStandardConversionExists (expr, best)) {
808 best = null;
809 break;
813 EmptyExpression.Release (expr);
815 return best;
818 /// <summary>
819 /// Finds the most specific source Sx according to the rules of the spec (13.4.4)
820 /// by making use of FindMostEncomp* methods. Applies the correct rules separately
821 /// for explicit and implicit conversion operators.
822 /// </summary>
823 static public TypeSpec FindMostSpecificSource (IList<MethodSpec> list,
824 Expression source, bool apply_explicit_conv_rules)
826 var src_types_set = new List<TypeSpec> ();
829 // If any operator converts from S then Sx = S
831 TypeSpec source_type = source.Type;
832 foreach (var mb in list){
833 TypeSpec param_type = mb.Parameters.Types [0];
835 if (param_type == source_type)
836 return param_type;
838 src_types_set.Add (param_type);
842 // Explicit Conv rules
844 if (apply_explicit_conv_rules) {
845 var candidate_set = new List<TypeSpec> ();
847 foreach (TypeSpec param_type in src_types_set){
848 if (ImplicitStandardConversionExists (source, param_type))
849 candidate_set.Add (param_type);
852 if (candidate_set.Count != 0)
853 return FindMostEncompassedType (candidate_set);
857 // Final case
859 if (apply_explicit_conv_rules)
860 return FindMostEncompassingType (src_types_set);
861 else
862 return FindMostEncompassedType (src_types_set);
865 /// <summary>
866 /// Finds the most specific target Tx according to section 13.4.4
867 /// </summary>
868 static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
869 TypeSpec target, bool apply_explicit_conv_rules)
871 var tgt_types_set = new List<TypeSpec> ();
874 // If any operator converts to T then Tx = T
876 foreach (var mi in list){
877 TypeSpec ret_type = mi.ReturnType;
878 if (ret_type == target)
879 return ret_type;
881 tgt_types_set.Add (ret_type);
885 // Explicit conv rules
887 if (apply_explicit_conv_rules) {
888 var candidate_set = new List<TypeSpec> ();
890 EmptyExpression expr = EmptyExpression.Grab ();
892 foreach (TypeSpec ret_type in tgt_types_set){
893 expr.SetType (ret_type);
895 if (ImplicitStandardConversionExists (expr, target))
896 candidate_set.Add (ret_type);
899 EmptyExpression.Release (expr);
901 if (candidate_set.Count != 0)
902 return FindMostEncompassingType (candidate_set);
906 // Okay, final case !
908 if (apply_explicit_conv_rules)
909 return FindMostEncompassedType (tgt_types_set);
910 else
911 return FindMostEncompassingType (tgt_types_set);
914 /// <summary>
915 /// User-defined Implicit conversions
916 /// </summary>
917 static public Expression ImplicitUserConversion (ResolveContext ec, Expression source,
918 TypeSpec target, Location loc)
920 return UserDefinedConversion (ec, source, target, loc, false, true);
923 /// <summary>
924 /// User-defined Explicit conversions
925 /// </summary>
926 static Expression ExplicitUserConversion (ResolveContext ec, Expression source,
927 TypeSpec target, Location loc)
929 return UserDefinedConversion (ec, source, target, loc, true, true);
932 static void AddConversionOperators (List<MethodSpec> list,
933 Expression source, TypeSpec target_type,
934 bool look_for_explicit,
935 MethodGroupExpr mg)
937 if (mg == null)
938 return;
940 TypeSpec source_type = source.Type;
941 EmptyExpression expr = EmptyExpression.Grab ();
944 // LAMESPEC: Undocumented IntPtr/UIntPtr conversions
945 // IntPtr -> uint uses int
946 // UIntPtr -> long uses ulong
948 if (source_type == TypeManager.intptr_type) {
949 if (target_type == TypeManager.uint32_type)
950 target_type = TypeManager.int32_type;
951 } else if (source_type == TypeManager.uintptr_type) {
952 if (target_type == TypeManager.int64_type)
953 target_type = TypeManager.uint64_type;
956 foreach (MethodSpec m in mg.Methods) {
957 AParametersCollection pd = m.Parameters;
958 TypeSpec return_type = m.ReturnType;
959 TypeSpec arg_type = pd.Types [0];
961 if (source_type != arg_type) {
962 if (!ImplicitStandardConversionExists (source, arg_type)) {
963 if (!look_for_explicit)
964 continue;
965 expr.SetType (arg_type);
966 if (!ImplicitStandardConversionExists (expr, source_type))
967 continue;
971 if (target_type != return_type) {
972 expr.SetType (return_type);
973 if (!ImplicitStandardConversionExists (expr, target_type)) {
974 if (!look_for_explicit)
975 continue;
976 expr.SetType (target_type);
977 if (!ImplicitStandardConversionExists (expr, return_type))
978 continue;
982 // See LAMESPEC: Exclude IntPtr -> int conversion
983 if (source_type == TypeManager.uintptr_type && return_type == TypeManager.uint32_type)
984 continue;
986 list.Add (m);
989 EmptyExpression.Release (expr);
992 /// <summary>
993 /// Compute the user-defined conversion operator from source_type to target_type.
994 /// `look_for_explicit' controls whether we should also include the list of explicit operators
995 /// </summary>
996 static MethodSpec GetConversionOperator (CompilerContext ctx, TypeSpec container_type, Expression source, TypeSpec target_type, bool look_for_explicit)
998 var ops = new List<MethodSpec> (4);
1000 TypeSpec source_type = source.Type;
1002 if (source_type != TypeManager.decimal_type) {
1003 AddConversionOperators (ops, source, target_type, look_for_explicit,
1004 Expression.MethodLookup (ctx, container_type, source_type, MemberKind.Operator, "op_Implicit", 0, Location.Null));
1005 if (look_for_explicit) {
1006 AddConversionOperators (ops, source, target_type, look_for_explicit,
1007 Expression.MethodLookup (ctx,
1008 container_type, source_type, MemberKind.Operator, "op_Explicit", 0, Location.Null));
1012 if (target_type != TypeManager.decimal_type) {
1013 AddConversionOperators (ops, source, target_type, look_for_explicit,
1014 Expression.MethodLookup (ctx, container_type, target_type, MemberKind.Operator, "op_Implicit", 0, Location.Null));
1015 if (look_for_explicit) {
1016 AddConversionOperators (ops, source, target_type, look_for_explicit,
1017 Expression.MethodLookup (ctx,
1018 container_type, target_type, MemberKind.Operator, "op_Explicit", 0, Location.Null));
1022 if (ops.Count == 0)
1023 return null;
1025 TypeSpec most_specific_source = FindMostSpecificSource (ops, source, look_for_explicit);
1026 if (most_specific_source == null)
1027 return null;
1029 TypeSpec most_specific_target = FindMostSpecificTarget (ops, target_type, look_for_explicit);
1030 if (most_specific_target == null)
1031 return null;
1033 MethodSpec method = null;
1035 foreach (var m in ops) {
1036 if (m.ReturnType != most_specific_target)
1037 continue;
1038 if (m.Parameters.Types [0] != most_specific_source)
1039 continue;
1040 // Ambiguous: more than one conversion operator satisfies the signature.
1041 if (method != null)
1042 return null;
1043 method = m;
1046 return method;
1049 /// <summary>
1050 /// User-defined conversions
1051 /// </summary>
1052 public static Expression UserDefinedConversion (ResolveContext ec, Expression source,
1053 TypeSpec target, Location loc,
1054 bool look_for_explicit, bool return_convert)
1056 TypeSpec source_type = source.Type;
1057 MethodSpec method = null;
1058 Expression expr = null;
1060 object o;
1061 DoubleHash hash;
1062 if (look_for_explicit) {
1063 hash = explicit_conv;
1064 } else {
1065 // Implicit user operators cannot convert to interfaces
1066 if (target.IsInterface)
1067 return null;
1069 hash = implicit_conv;
1072 if (!(source is Constant) && hash.Lookup (source_type, target, out o)) {
1073 method = (MethodSpec) o;
1074 } else {
1075 if (source_type == InternalType.Dynamic)
1076 return null;
1078 method = GetConversionOperator (ec.Compiler, null, source, target, look_for_explicit);
1081 if (method != null) {
1082 TypeSpec most_specific_source = method.Parameters.Types[0];
1085 // This will do the conversion to the best match that we
1086 // found. Now we need to perform an implict standard conversion
1087 // if the best match was not the type that we were requested
1088 // by target.
1090 if (look_for_explicit) {
1091 ReportPrinter temp = new SessionReportPrinter ();
1092 ReportPrinter prev = ec.Report.SetPrinter (temp);
1094 expr = ExplicitConversionStandard (ec, source, most_specific_source, loc);
1096 ec.Report.SetPrinter (prev);
1097 if (temp.ErrorsCount != 0)
1098 expr = null;
1099 } else {
1100 if (ImplicitStandardConversionExists (source, most_specific_source))
1101 expr = ImplicitConversionStandard (ec, source, most_specific_source, loc);
1102 else
1103 expr = null;
1107 if (expr == null) {
1108 bool nullable = false;
1110 if (TypeManager.IsNullableType (source_type)) {
1111 source = Nullable.Unwrap.Create (source);
1112 nullable = true;
1115 TypeSpec target_underlying;
1116 if (TypeManager.IsNullableType (target)) {
1117 target_underlying = TypeManager.GetTypeArguments (target)[0];
1118 nullable = true;
1119 } else {
1120 // No implicit conversion S? -> T for non-reference type T
1121 if (!look_for_explicit && !TypeManager.IsReferenceType (target))
1122 nullable = false;
1124 target_underlying = target;
1127 if (nullable) {
1128 expr = UserDefinedConversion (ec, source, target_underlying, loc, look_for_explicit, return_convert);
1130 // Do result expression lifting only when it's needed
1131 if (expr != null && (!look_for_explicit || TypeManager.IsReferenceType (target)))
1132 expr = new Nullable.Lifted (expr, source, target).Resolve (ec);
1134 return expr;
1136 } else {
1137 expr = new UserCast (method, expr, loc).Resolve (ec);
1139 if (return_convert && !TypeManager.IsEqual (expr.Type, target)) {
1140 if (look_for_explicit) {
1141 expr = ExplicitConversionStandard (ec, expr, target, loc);
1142 } else {
1143 expr = ImplicitConversionStandard (ec, expr, target, loc);
1148 if (!(source is Constant))
1149 hash.Insert (source_type, target, method);
1151 return expr;
1154 /// <summary>
1155 /// Converts implicitly the resolved expression `expr' into the
1156 /// `target_type'. It returns a new expression that can be used
1157 /// in a context that expects a `target_type'.
1158 /// </summary>
1159 static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
1160 TypeSpec target_type, Location loc)
1162 Expression e;
1164 if (target_type == null)
1165 throw new Exception ("Target type is null");
1167 e = ImplicitConversionStandard (ec, expr, target_type, loc);
1168 if (e != null)
1169 return e;
1171 e = ImplicitUserConversion (ec, expr, target_type, loc);
1172 if (e != null)
1173 return e;
1175 return null;
1179 /// <summary>
1180 /// Attempts to apply the `Standard Implicit
1181 /// Conversion' rules to the expression `expr' into
1182 /// the `target_type'. It returns a new expression
1183 /// that can be used in a context that expects a
1184 /// `target_type'.
1186 /// This is different from `ImplicitConversion' in that the
1187 /// user defined implicit conversions are excluded.
1188 /// </summary>
1189 static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
1190 TypeSpec target_type, Location loc)
1192 return ImplicitConversionStandard (ec, expr, target_type, loc, false);
1195 static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
1197 if (expr.eclass == ExprClass.MethodGroup){
1198 if (!TypeManager.IsDelegateType (target_type)){
1199 return null;
1203 // Only allow anonymous method conversions on post ISO_1
1205 if (RootContext.Version != LanguageVersion.ISO_1){
1206 MethodGroupExpr mg = expr as MethodGroupExpr;
1207 if (mg != null)
1208 return ImplicitDelegateCreation.Create (
1209 ec, mg, target_type, loc);
1213 TypeSpec expr_type = expr.Type;
1214 Expression e;
1216 if (expr_type.Equals (target_type)) {
1217 if (expr_type != TypeManager.null_type && expr_type != InternalType.AnonymousMethod)
1218 return expr;
1219 return null;
1222 if (TypeSpecComparer.Variant.IsEqual (expr_type, target_type)) {
1223 return expr;
1226 if (TypeManager.IsNullableType (target_type))
1227 return ImplicitNulableConversion (ec, expr, target_type);
1230 // Attempt to do the implicit constant expression conversions
1232 Constant c = expr as Constant;
1233 if (c != null) {
1234 try {
1235 c = c.ConvertImplicitly (ec, target_type);
1236 } catch {
1237 Console.WriteLine ("Conversion error happened in line {0}", loc);
1238 throw;
1240 if (c != null)
1241 return c;
1244 e = ImplicitNumericConversion (expr, expr_type, target_type);
1245 if (e != null)
1246 return e;
1248 e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
1249 if (e != null)
1250 return e;
1252 if (expr is IntConstant && TypeManager.IsEnumType (target_type)){
1253 Constant i = (Constant) expr;
1255 // LAMESPEC: Conversion from any 0 constant is allowed
1257 // An implicit enumeration conversion permits the decimal-integer-literal 0
1258 // to be converted to any enum-type and to any nullable-type whose underlying
1259 // type is an enum-type
1261 if (i.IsDefaultValue)
1262 return new EnumConstant (i, target_type).Resolve (ec);
1265 if (ec.IsUnsafe) {
1266 if (expr_type.IsPointer){
1267 if (target_type == TypeManager.void_ptr_type)
1268 return EmptyCast.Create (expr, target_type);
1271 // yep, comparing pointer types cant be done with
1272 // t1 == t2, we have to compare their element types.
1274 if (target_type.IsPointer){
1275 if (TypeManager.GetElementType(target_type) == TypeManager.GetElementType(expr_type))
1276 return expr;
1278 //return null;
1282 if (expr_type == TypeManager.null_type && target_type.IsPointer)
1283 return EmptyCast.Create (new NullPointer (loc), target_type);
1286 if (expr_type == InternalType.AnonymousMethod){
1287 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
1288 Expression am = ame.Compatible (ec, target_type);
1289 if (am != null)
1290 return am.Resolve (ec);
1293 if (expr_type == InternalType.Arglist && target_type == TypeManager.arg_iterator_type)
1294 return expr;
1296 return null;
1299 /// <summary>
1300 /// Attempts to implicitly convert `source' into `target_type', using
1301 /// ImplicitConversion. If there is no implicit conversion, then
1302 /// an error is signaled
1303 /// </summary>
1304 static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
1305 TypeSpec target_type, Location loc)
1307 Expression e = ImplicitConversion (ec, source, target_type, loc);
1308 if (e != null)
1309 return e;
1311 if (source.Type == InternalType.Dynamic) {
1312 Arguments args = new Arguments (1);
1313 args.Add (new Argument (source));
1314 return new DynamicConversion (target_type, 0, args, loc).Resolve (ec);
1317 source.Error_ValueCannotBeConverted (ec, loc, target_type, false);
1318 return null;
1321 /// <summary>
1322 /// Performs the explicit numeric conversions
1324 /// There are a few conversions that are not part of the C# standard,
1325 /// they were interim hacks in the C# compiler that were supposed to
1326 /// become explicit operators in the UIntPtr class and IntPtr class,
1327 /// but for historical reasons it did not happen, so the C# compiler
1328 /// ended up with these special hacks.
1330 /// See bug 59800 for details.
1332 /// The conversion are:
1333 /// UIntPtr->SByte
1334 /// UIntPtr->Int16
1335 /// UIntPtr->Int32
1336 /// IntPtr->UInt64
1337 /// UInt64->IntPtr
1338 /// SByte->UIntPtr
1339 /// Int16->UIntPtr
1341 /// </summary>
1342 public static Expression ExplicitNumericConversion (Expression expr, TypeSpec target_type)
1344 TypeSpec expr_type = expr.Type;
1345 TypeSpec real_target_type = target_type;
1347 if (expr_type == TypeManager.sbyte_type){
1349 // From sbyte to byte, ushort, uint, ulong, char, uintptr
1351 if (real_target_type == TypeManager.byte_type)
1352 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
1353 if (real_target_type == TypeManager.ushort_type)
1354 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
1355 if (real_target_type == TypeManager.uint32_type)
1356 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
1357 if (real_target_type == TypeManager.uint64_type)
1358 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
1359 if (real_target_type == TypeManager.char_type)
1360 return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
1362 // One of the built-in conversions that belonged in the class library
1363 if (real_target_type == TypeManager.uintptr_type){
1364 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I1_U8);
1366 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1368 } else if (expr_type == TypeManager.byte_type){
1370 // From byte to sbyte and char
1372 if (real_target_type == TypeManager.sbyte_type)
1373 return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
1374 if (real_target_type == TypeManager.char_type)
1375 return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
1376 } else if (expr_type == TypeManager.short_type){
1378 // From short to sbyte, byte, ushort, uint, ulong, char, uintptr
1380 if (real_target_type == TypeManager.sbyte_type)
1381 return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
1382 if (real_target_type == TypeManager.byte_type)
1383 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
1384 if (real_target_type == TypeManager.ushort_type)
1385 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
1386 if (real_target_type == TypeManager.uint32_type)
1387 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
1388 if (real_target_type == TypeManager.uint64_type)
1389 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
1390 if (real_target_type == TypeManager.char_type)
1391 return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
1393 // One of the built-in conversions that belonged in the class library
1394 if (real_target_type == TypeManager.uintptr_type){
1395 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1397 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1399 } else if (expr_type == TypeManager.ushort_type){
1401 // From ushort to sbyte, byte, short, char
1403 if (real_target_type == TypeManager.sbyte_type)
1404 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
1405 if (real_target_type == TypeManager.byte_type)
1406 return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
1407 if (real_target_type == TypeManager.short_type)
1408 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
1409 if (real_target_type == TypeManager.char_type)
1410 return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
1411 } else if (expr_type == TypeManager.int32_type){
1413 // From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
1415 if (real_target_type == TypeManager.sbyte_type)
1416 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
1417 if (real_target_type == TypeManager.byte_type)
1418 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
1419 if (real_target_type == TypeManager.short_type)
1420 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
1421 if (real_target_type == TypeManager.ushort_type)
1422 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
1423 if (real_target_type == TypeManager.uint32_type)
1424 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
1425 if (real_target_type == TypeManager.uint64_type)
1426 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
1427 if (real_target_type == TypeManager.char_type)
1428 return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
1430 // One of the built-in conversions that belonged in the class library
1431 if (real_target_type == TypeManager.uintptr_type){
1432 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1434 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1436 } else if (expr_type == TypeManager.uint32_type){
1438 // From uint to sbyte, byte, short, ushort, int, char
1440 if (real_target_type == TypeManager.sbyte_type)
1441 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
1442 if (real_target_type == TypeManager.byte_type)
1443 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
1444 if (real_target_type == TypeManager.short_type)
1445 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
1446 if (real_target_type == TypeManager.ushort_type)
1447 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
1448 if (real_target_type == TypeManager.int32_type)
1449 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
1450 if (real_target_type == TypeManager.char_type)
1451 return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
1452 } else if (expr_type == TypeManager.int64_type){
1454 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1456 if (real_target_type == TypeManager.sbyte_type)
1457 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
1458 if (real_target_type == TypeManager.byte_type)
1459 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
1460 if (real_target_type == TypeManager.short_type)
1461 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
1462 if (real_target_type == TypeManager.ushort_type)
1463 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
1464 if (real_target_type == TypeManager.int32_type)
1465 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
1466 if (real_target_type == TypeManager.uint32_type)
1467 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
1468 if (real_target_type == TypeManager.uint64_type)
1469 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
1470 if (real_target_type == TypeManager.char_type)
1471 return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
1472 } else if (expr_type == TypeManager.uint64_type){
1474 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1476 if (real_target_type == TypeManager.sbyte_type)
1477 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
1478 if (real_target_type == TypeManager.byte_type)
1479 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
1480 if (real_target_type == TypeManager.short_type)
1481 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
1482 if (real_target_type == TypeManager.ushort_type)
1483 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
1484 if (real_target_type == TypeManager.int32_type)
1485 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
1486 if (real_target_type == TypeManager.uint32_type)
1487 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
1488 if (real_target_type == TypeManager.int64_type)
1489 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
1490 if (real_target_type == TypeManager.char_type)
1491 return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
1493 // One of the built-in conversions that belonged in the class library
1494 if (real_target_type == TypeManager.intptr_type){
1495 return new OperatorCast (EmptyCast.Create (expr, TypeManager.int64_type),
1496 TypeManager.intptr_type, true);
1498 } else if (expr_type == TypeManager.char_type){
1500 // From char to sbyte, byte, short
1502 if (real_target_type == TypeManager.sbyte_type)
1503 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
1504 if (real_target_type == TypeManager.byte_type)
1505 return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
1506 if (real_target_type == TypeManager.short_type)
1507 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
1508 } else if (expr_type == TypeManager.float_type){
1510 // From float to sbyte, byte, short,
1511 // ushort, int, uint, long, ulong, char
1512 // or decimal
1514 if (real_target_type == TypeManager.sbyte_type)
1515 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
1516 if (real_target_type == TypeManager.byte_type)
1517 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
1518 if (real_target_type == TypeManager.short_type)
1519 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
1520 if (real_target_type == TypeManager.ushort_type)
1521 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
1522 if (real_target_type == TypeManager.int32_type)
1523 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
1524 if (real_target_type == TypeManager.uint32_type)
1525 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
1526 if (real_target_type == TypeManager.int64_type)
1527 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
1528 if (real_target_type == TypeManager.uint64_type)
1529 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
1530 if (real_target_type == TypeManager.char_type)
1531 return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
1532 if (real_target_type == TypeManager.decimal_type)
1533 return new CastToDecimal (expr, true);
1534 } else if (expr_type == TypeManager.double_type){
1536 // From double to sbyte, byte, short,
1537 // ushort, int, uint, long, ulong,
1538 // char, float or decimal
1540 if (real_target_type == TypeManager.sbyte_type)
1541 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
1542 if (real_target_type == TypeManager.byte_type)
1543 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
1544 if (real_target_type == TypeManager.short_type)
1545 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
1546 if (real_target_type == TypeManager.ushort_type)
1547 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
1548 if (real_target_type == TypeManager.int32_type)
1549 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
1550 if (real_target_type == TypeManager.uint32_type)
1551 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
1552 if (real_target_type == TypeManager.int64_type)
1553 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
1554 if (real_target_type == TypeManager.uint64_type)
1555 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
1556 if (real_target_type == TypeManager.char_type)
1557 return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
1558 if (real_target_type == TypeManager.float_type)
1559 return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
1560 if (real_target_type == TypeManager.decimal_type)
1561 return new CastToDecimal (expr, true);
1562 } else if (expr_type == TypeManager.uintptr_type){
1564 // Various built-in conversions that belonged in the class library
1566 // from uintptr to sbyte, short, int32
1568 if (real_target_type == TypeManager.sbyte_type){
1569 Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1570 return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I1);
1572 if (real_target_type == TypeManager.short_type){
1573 Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1574 return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I2);
1576 if (real_target_type == TypeManager.int32_type){
1577 return EmptyCast.Create (new OperatorCast (expr, TypeManager.uint32_type, true),
1578 TypeManager.int32_type);
1580 } else if (expr_type == TypeManager.intptr_type){
1581 if (real_target_type == TypeManager.uint64_type){
1582 return EmptyCast.Create (new OperatorCast (expr, TypeManager.int64_type, true),
1583 TypeManager.uint64_type);
1585 } else if (expr_type == TypeManager.decimal_type) {
1586 return new CastFromDecimal (expr, target_type).Resolve ();
1588 return null;
1591 /// <summary>
1592 /// Returns whether an explicit reference conversion can be performed
1593 /// from source_type to target_type
1594 /// </summary>
1595 public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
1597 Expression e = ExplicitReferenceConversion (null, source_type, target_type);
1598 if (e == null)
1599 return false;
1601 if (e == EmptyExpression.Null)
1602 return true;
1604 throw new InternalErrorException ("Invalid probing conversion result");
1607 /// <summary>
1608 /// Implements Explicit Reference conversions
1609 /// </summary>
1610 static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
1613 // From object to a generic parameter
1615 if (source_type == TypeManager.object_type && TypeManager.IsGenericParameter (target_type))
1616 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1619 // Explicit type parameter conversion.
1621 if (TypeManager.IsGenericParameter (source_type))
1622 return ExplicitTypeParameterConversion (source, source_type, target_type);
1624 bool target_is_value_type = TypeManager.IsStruct (target_type) || TypeManager.IsEnumType (target_type);
1627 // Unboxing conversion from System.ValueType to any non-nullable-value-type
1629 if (source_type == TypeManager.value_type && target_is_value_type)
1630 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1633 // From object to any reference type or value type (unboxing)
1635 if (source_type == TypeManager.object_type)
1636 return
1637 source == null ? EmptyExpression.Null :
1638 target_is_value_type ? new UnboxCast (source, target_type) :
1639 source is Constant ? (Expression) new EmptyConstantCast ((Constant) source, target_type) :
1640 new ClassCast (source, target_type);
1643 // From any class S to any class-type T, provided S is a base class of T
1645 if (TypeManager.IsSubclassOf (target_type, source_type))
1646 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1649 // From any interface-type S to to any class type T, provided T is not
1650 // sealed, or provided T implements S.
1652 if (source_type.IsInterface) {
1653 if (!target_type.IsSealed || target_type.ImplementsInterface (source_type)) {
1654 if (target_type.IsClass)
1655 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1658 // Unboxing conversion from any interface-type to any non-nullable-value-type that
1659 // implements the interface-type
1661 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1665 // From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
1666 // array type S[], provided there is an implicit or explicit reference conversion from S to T.
1668 var target_array = target_type as ArrayContainer;
1669 if (target_array != null && IList_To_Array (source_type, target_array))
1670 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1672 return null;
1675 var source_array = source_type as ArrayContainer;
1676 if (source_array != null) {
1677 var target_array = target_type as ArrayContainer;
1678 if (target_array != null) {
1680 // From System.Array to any array-type
1682 if (source_type == TypeManager.array_type)
1683 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1686 // From an array type S with an element type Se to an array type T with an
1687 // element type Te provided all the following are true:
1688 // * S and T differe only in element type, in other words, S and T
1689 // have the same number of dimensions.
1690 // * Both Se and Te are reference types
1691 // * An explicit reference conversions exist from Se to Te
1693 if (source_array.Rank == target_array.Rank) {
1695 source_type = source_array.Element;
1696 if (!TypeManager.IsReferenceType (source_type))
1697 return null;
1699 var target_element = target_array.Element;
1700 if (!TypeManager.IsReferenceType (target_element))
1701 return null;
1703 if (ExplicitReferenceConversionExists (source_type, target_element))
1704 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1706 return null;
1711 // From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces,
1712 // provided that there is an explicit reference conversion from S to T
1714 if (ArrayToIList (source_array, target_type, true))
1715 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1717 return null;
1721 // From any class type S to any interface T, provides S is not sealed
1722 // and provided S does not implement T.
1724 if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type)) {
1725 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1729 // From System delegate to any delegate-type
1731 if (source_type == TypeManager.delegate_type && TypeManager.IsDelegateType (target_type))
1732 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1734 return null;
1737 /// <summary>
1738 /// Performs an explicit conversion of the expression `expr' whose
1739 /// type is expr.Type to `target_type'.
1740 /// </summary>
1741 static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
1742 TypeSpec target_type, Location loc)
1744 TypeSpec expr_type = expr.Type;
1746 // Explicit conversion includes implicit conversion and it used for enum underlying types too
1747 Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
1748 if (ne != null)
1749 return ne;
1751 if (TypeManager.IsEnumType (expr_type)) {
1752 TypeSpec real_target = TypeManager.IsEnumType (target_type) ? EnumSpec.GetUnderlyingType (target_type) : target_type;
1753 Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
1754 if (underlying.Type == real_target)
1755 ne = underlying;
1757 if (ne == null)
1758 ne = ImplicitNumericConversion (underlying, real_target);
1760 if (ne == null)
1761 ne = ExplicitNumericConversion (underlying, real_target);
1764 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
1766 if (ne == null && (real_target == TypeManager.intptr_type || real_target == TypeManager.uintptr_type))
1767 ne = ExplicitUserConversion (ec, underlying, real_target, loc);
1769 return ne != null ? EmptyCast.Create (ne, target_type) : null;
1772 if (TypeManager.IsEnumType (target_type)) {
1774 // System.Enum can be unboxed to any enum-type
1776 if (expr_type == TypeManager.enum_type)
1777 return new UnboxCast (expr, target_type);
1779 TypeSpec real_target = TypeManager.IsEnumType (target_type) ? EnumSpec.GetUnderlyingType (target_type) : target_type;
1781 if (expr_type == real_target)
1782 return EmptyCast.Create (expr, target_type);
1784 ne = ImplicitNumericConversion (expr, real_target);
1785 if (ne != null)
1786 return EmptyCast.Create (ne, target_type);
1788 ne = ExplicitNumericConversion (expr, real_target);
1789 if (ne != null)
1790 return EmptyCast.Create (ne, target_type);
1793 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
1795 if (expr_type == TypeManager.intptr_type || expr_type == TypeManager.uintptr_type) {
1796 ne = ExplicitUserConversion (ec, expr, real_target, loc);
1797 if (ne != null)
1798 return ExplicitConversionCore (ec, ne, target_type, loc);
1800 } else {
1801 ne = ExplicitNumericConversion (expr, target_type);
1802 if (ne != null)
1803 return ne;
1807 // Skip the ExplicitReferenceConversion because we can not convert
1808 // from Null to a ValueType, and ExplicitReference wont check against
1809 // null literal explicitly
1811 if (expr_type != TypeManager.null_type){
1812 ne = ExplicitReferenceConversion (expr, expr_type, target_type);
1813 if (ne != null)
1814 return ne;
1817 if (ec.IsUnsafe){
1818 ne = ExplicitUnsafe (expr, target_type);
1819 if (ne != null)
1820 return ne;
1823 return null;
1826 public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
1828 TypeSpec expr_type = expr.Type;
1830 if (target_type.IsPointer){
1831 if (expr_type.IsPointer)
1832 return EmptyCast.Create (expr, target_type);
1834 if (expr_type == TypeManager.sbyte_type ||
1835 expr_type == TypeManager.short_type ||
1836 expr_type == TypeManager.int32_type)
1837 return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
1839 if (expr_type == TypeManager.ushort_type ||
1840 expr_type == TypeManager.uint32_type ||
1841 expr_type == TypeManager.byte_type)
1842 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
1844 if (expr_type == TypeManager.int64_type)
1845 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);
1847 if (expr_type == TypeManager.uint64_type)
1848 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
1851 if (expr_type.IsPointer){
1852 if (target_type == TypeManager.sbyte_type)
1853 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1854 if (target_type == TypeManager.byte_type)
1855 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1856 if (target_type == TypeManager.short_type)
1857 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1858 if (target_type == TypeManager.ushort_type)
1859 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1860 if (target_type == TypeManager.int32_type)
1861 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1862 if (target_type == TypeManager.uint32_type)
1863 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1864 if (target_type == TypeManager.int64_type)
1865 return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
1866 if (target_type == TypeManager.uint64_type)
1867 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1869 return null;
1872 /// <summary>
1873 /// Same as ExplicitConversion, only it doesn't include user defined conversions
1874 /// </summary>
1875 static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
1876 TypeSpec target_type, Location l)
1878 int errors = ec.Report.Errors;
1879 Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
1880 if (ec.Report.Errors > errors)
1881 return null;
1883 if (ne != null)
1884 return ne;
1886 ne = ExplicitNumericConversion (expr, target_type);
1887 if (ne != null)
1888 return ne;
1890 ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
1891 if (ne != null)
1892 return ne;
1894 if (ec.IsUnsafe && expr.Type == TypeManager.void_ptr_type && target_type.IsPointer)
1895 return EmptyCast.Create (expr, target_type);
1897 expr.Error_ValueCannotBeConverted (ec, l, target_type, true);
1898 return null;
1901 /// <summary>
1902 /// Performs an explicit conversion of the expression `expr' whose
1903 /// type is expr.Type to `target_type'.
1904 /// </summary>
1905 static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
1906 TypeSpec target_type, Location loc)
1908 Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
1909 if (e != null) {
1911 // Don't eliminate explicit precission casts
1913 if (e == expr) {
1914 if (target_type == TypeManager.float_type)
1915 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1917 if (target_type == TypeManager.double_type)
1918 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
1921 return e;
1924 TypeSpec expr_type = expr.Type;
1925 if (TypeManager.IsNullableType (target_type)) {
1926 if (TypeManager.IsNullableType (expr_type)) {
1927 TypeSpec target = Nullable.NullableInfo.GetUnderlyingType (target_type);
1928 Expression unwrap = Nullable.Unwrap.Create (expr);
1929 e = ExplicitConversion (ec, unwrap, target, expr.Location);
1930 if (e == null)
1931 return null;
1933 return new Nullable.Lifted (e, unwrap, target_type).Resolve (ec);
1934 } else if (expr_type == TypeManager.object_type) {
1935 return new UnboxCast (expr, target_type);
1936 } else {
1937 TypeSpec target = TypeManager.GetTypeArguments (target_type) [0];
1939 e = ExplicitConversionCore (ec, expr, target, loc);
1940 if (e != null)
1941 return Nullable.Wrap.Create (e, target_type);
1943 } else if (TypeManager.IsNullableType (expr_type)) {
1944 bool use_class_cast;
1945 if (ImplicitBoxingConversionExists (Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type, out use_class_cast))
1946 return new BoxedCast (expr, target_type);
1948 e = Nullable.Unwrap.Create (expr, false);
1949 e = ExplicitConversionCore (ec, e, target_type, loc);
1950 if (e != null)
1951 return EmptyCast.Create (e, target_type);
1954 e = ExplicitUserConversion (ec, expr, target_type, loc);
1955 if (e != null)
1956 return e;
1958 expr.Error_ValueCannotBeConverted (ec, loc, target_type, true);
1959 return null;