2009-12-09 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / convert.cs
blobc1e9980f2931e3930c3e6599ac6f30e20cc45093
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);
42 static Type TypeParam_EffectiveBaseType (GenericConstraints gc)
44 var list = new List<Type> ();
45 list.Add (gc.EffectiveBaseClass);
46 foreach (Type t in gc.InterfaceConstraints) {
47 if (!TypeManager.IsGenericParameter (t))
48 continue;
50 GenericConstraints new_gc = TypeManager.GetTypeParameterConstraints (t);
51 if (new_gc != null)
52 list.Add (TypeParam_EffectiveBaseType (new_gc));
54 return FindMostEncompassedType (list);
58 // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
59 // interfaces of this interface, provided there is an implicit reference conversion
60 // from S to T.
62 static bool Array_To_IList (Type array, Type list, bool isExplicit)
64 if ((array.GetArrayRank () != 1) || !TypeManager.IsGenericType (list))
65 return false;
67 Type gt = TypeManager.DropGenericTypeArguments (list);
68 if ((gt != TypeManager.generic_ilist_type) &&
69 (gt != TypeManager.generic_icollection_type) &&
70 (gt != TypeManager.generic_ienumerable_type))
71 return false;
73 Type element_type = TypeManager.GetElementType (array);
74 Type arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (list) [0]);
76 if (element_type == arg_type)
77 return true;
79 if (isExplicit)
80 return ExplicitReferenceConversionExists (element_type, arg_type);
82 Type t = TypeManager.GetElementType (array);
83 if (MyEmptyExpr == null)
84 MyEmptyExpr = new EmptyExpression (t);
85 else
86 MyEmptyExpr.SetType (t);
88 return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type);
91 static bool IList_To_Array(Type list, Type array)
93 if (!TypeManager.IsGenericType (list) || !array.IsArray || array.GetArrayRank() != 1)
94 return false;
96 Type gt = TypeManager.DropGenericTypeArguments (list);
97 if (gt != TypeManager.generic_ilist_type &&
98 gt != TypeManager.generic_icollection_type &&
99 gt != TypeManager.generic_ienumerable_type)
100 return false;
102 Type arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments(list)[0]);
103 Type element_type = TypeManager.GetElementType(array);
105 if (element_type == arg_type)
106 return true;
108 if (MyEmptyExpr == null)
109 MyEmptyExpr = new EmptyExpression(element_type);
110 else
111 MyEmptyExpr.SetType(element_type);
113 return ImplicitReferenceConversionExists(MyEmptyExpr, arg_type) || ExplicitReferenceConversionExists(element_type, arg_type);
116 static Expression ImplicitTypeParameterConversion (Expression expr,
117 Type target_type)
119 Type expr_type = expr.Type;
121 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
123 if (gc == null) {
124 if (target_type == TypeManager.object_type)
125 return new BoxedCast (expr, target_type);
127 return null;
130 // We're converting from a type parameter which is known to be a reference type.
131 Type base_type = TypeParam_EffectiveBaseType (gc);
133 if (TypeManager.IsSubclassOf (base_type, target_type))
134 return new ClassCast (expr, target_type);
136 if (target_type.IsInterface) {
137 if (TypeManager.ImplementsInterface (base_type, target_type))
138 return new ClassCast (expr, target_type);
140 foreach (Type t in gc.InterfaceConstraints) {
141 if (TypeManager.IsSubclassOf (t, target_type))
142 return new ClassCast (expr, target_type);
143 if (TypeManager.ImplementsInterface (t, target_type))
144 return new ClassCast (expr, target_type);
148 foreach (Type t in gc.InterfaceConstraints) {
149 if (!TypeManager.IsGenericParameter (t))
150 continue;
151 if (TypeManager.IsSubclassOf (t, target_type))
152 return new ClassCast (expr, target_type);
153 if (TypeManager.ImplementsInterface (t, target_type))
154 return new ClassCast (expr, target_type);
157 return null;
160 static bool ImplicitTypeParameterBoxingConversion (Type expr_type, Type target_type,
161 out bool use_class_cast)
163 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
165 if (gc == null) {
166 use_class_cast = false;
167 return target_type == TypeManager.object_type;
170 use_class_cast = true;
172 if (!gc.HasReferenceTypeConstraint)
173 return false;
175 // We're converting from a type parameter which is known to be a reference type.
176 Type base_type = TypeParam_EffectiveBaseType (gc);
178 if (TypeManager.IsSubclassOf (base_type, target_type))
179 return true;
181 if (target_type.IsInterface) {
182 if (TypeManager.ImplementsInterface (base_type, target_type))
183 return true;
185 foreach (Type t in gc.InterfaceConstraints) {
186 if (TypeManager.IsSubclassOf (t, target_type))
187 return true;
188 if (TypeManager.ImplementsInterface (t, target_type))
189 return true;
193 foreach (Type t in gc.InterfaceConstraints) {
194 if (!TypeManager.IsGenericParameter (t))
195 continue;
196 if (TypeManager.IsSubclassOf (t, target_type))
197 return true;
198 if (TypeManager.ImplementsInterface (t, target_type))
199 return true;
202 use_class_cast = false;
203 return false;
206 static Expression ExplicitTypeParameterConversion (Expression source, Type source_type, Type target_type)
208 if (TypeManager.IsGenericParameter (target_type)) {
209 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
210 if (gc == null)
211 return null;
213 foreach (Type iface in gc.InterfaceConstraints) {
214 if (!TypeManager.IsGenericParameter (iface))
215 continue;
217 if (TypeManager.IsSubclassOf (source_type, iface))
218 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
222 if (target_type.IsInterface)
223 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
225 return null;
228 static Expression ImplicitReferenceConversion (Expression expr, Type target_type, bool explicit_cast)
230 Type expr_type = expr.Type;
232 if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
233 // if we are a method group, emit a warning
235 expr.Emit (null);
238 if (expr_type == TypeManager.void_type)
239 return null;
241 if (TypeManager.IsGenericParameter (expr_type))
242 return ImplicitTypeParameterConversion (expr, target_type);
245 // from the null type to any reference-type.
247 NullLiteral nl = expr as NullLiteral;
248 if (nl != null) {
249 return nl.ConvertImplicitly (null, target_type);
252 if (ImplicitReferenceConversionExists (expr, target_type)) {
254 // Avoid wrapping implicitly convertible reference type
256 if (!explicit_cast)
257 return expr;
259 return EmptyCast.Create (expr, target_type);
262 bool use_class_cast;
263 if (ImplicitBoxingConversionExists (expr, target_type, out use_class_cast)) {
264 if (use_class_cast)
265 return new ClassCast (expr, target_type);
266 else
267 return new BoxedCast (expr, target_type);
270 return null;
274 // 6.1.6 Implicit reference conversions
276 public static bool ImplicitReferenceConversionExists (Expression expr, Type target_type)
278 if (TypeManager.IsStruct (target_type))
279 return false;
281 Type expr_type = expr.Type;
283 // from the null type to any reference-type.
284 if (expr_type == TypeManager.null_type)
285 return target_type != InternalType.AnonymousMethod;
287 if (TypeManager.IsGenericParameter (expr_type))
288 return ImplicitTypeParameterConversion (expr, target_type) != null;
291 // notice that it is possible to write "ValueType v = 1", the ValueType here
292 // is an abstract class, and not really a value type, so we apply the same rules.
294 if (target_type == TypeManager.object_type || TypeManager.IsDynamicType (target_type)) {
296 // A pointer type cannot be converted to object
298 if (expr_type.IsPointer)
299 return false;
301 if (TypeManager.IsValueType (expr_type))
302 return false;
304 if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type){
305 // No mcs internal types are convertible
306 return expr_type.Module != typeof (Convert).Module;
309 return false;
310 } else if (target_type == TypeManager.value_type) {
311 return expr_type == TypeManager.enum_type;
312 } else if (TypeManager.IsSubclassOf (expr_type, target_type)) {
314 // Special case: enumeration to System.Enum.
315 // System.Enum is not a value type, it is a class, so we need
316 // a boxing conversion
318 if (target_type == TypeManager.enum_type || TypeManager.IsGenericParameter (expr_type))
319 return false;
321 return true;
324 // This code is kind of mirrored inside ImplicitStandardConversionExists
325 // with the small distinction that we only probe there
327 // Always ensure that the code here and there is in sync
329 // from any class-type S to any interface-type T.
330 if (target_type.IsInterface) {
331 if (TypeManager.ImplementsInterface (expr_type, target_type)){
332 return !TypeManager.IsGenericParameter (expr_type) &&
333 !TypeManager.IsValueType (expr_type);
337 if (expr_type.IsArray) {
338 // from an array-type S to an array-type of type T
339 if (target_type.IsArray && expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
342 // Both SE and TE are reference-types
344 Type expr_element_type = TypeManager.GetElementType (expr_type);
345 if (!TypeManager.IsReferenceType (expr_element_type))
346 return false;
348 Type target_element_type = TypeManager.GetElementType (target_type);
349 if (!TypeManager.IsReferenceType (target_element_type))
350 return false;
352 if (MyEmptyExpr == null)
353 MyEmptyExpr = new EmptyExpression (expr_element_type);
354 else
355 MyEmptyExpr.SetType (expr_element_type);
357 return ImplicitStandardConversionExists (MyEmptyExpr, target_element_type);
360 // from an array-type to System.Array
361 if (target_type == TypeManager.array_type)
362 return true;
364 // from an array-type of type T to IList<T>
365 if (Array_To_IList (expr_type, target_type, false))
366 return true;
368 return false;
371 if (TypeManager.IsVariantOf (expr_type, target_type))
372 return true;
374 // from any interface type S to interface-type T.
375 if (expr_type.IsInterface && target_type.IsInterface) {
376 return TypeManager.ImplementsInterface (expr_type, target_type);
379 // from any delegate type to System.Delegate
380 if (target_type == TypeManager.delegate_type &&
381 (expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)))
382 return true;
384 if (TypeManager.IsEqual (expr_type, target_type))
385 return true;
387 return false;
390 public static bool ImplicitBoxingConversionExists (Expression expr, Type target_type,
391 out bool use_class_cast)
393 Type expr_type = expr.Type;
394 use_class_cast = false;
397 // From any value-type to the type object.
399 if (target_type == TypeManager.object_type || TypeManager.IsDynamicType (target_type)) {
401 // A pointer type cannot be converted to object
403 if (expr_type.IsPointer)
404 return false;
406 return TypeManager.IsValueType (expr_type);
410 // From any value-type to the type System.ValueType.
412 if (target_type == TypeManager.value_type)
413 return TypeManager.IsValueType (expr_type);
415 if (target_type == TypeManager.enum_type) {
417 // From any enum-type to the type System.Enum.
419 if (TypeManager.IsEnumType (expr_type))
420 return true;
422 // From any nullable-type with an underlying enum-type to the type System.Enum
424 if (TypeManager.IsNullableType (expr_type))
425 return TypeManager.IsEnumType (TypeManager.GetTypeArguments (expr_type) [0]);
428 if (TypeManager.IsSubclassOf (expr_type, target_type)) {
430 // Don't box same type arguments
432 if (TypeManager.IsGenericParameter (expr_type) && expr_type != target_type)
433 return true;
435 return false;
438 // This code is kind of mirrored inside ImplicitStandardConversionExists
439 // with the small distinction that we only probe there
441 // Always ensure that the code here and there is in sync
443 // from any class-type S to any interface-type T.
444 if (target_type.IsInterface) {
445 if (TypeManager.ImplementsInterface (expr_type, target_type))
446 return TypeManager.IsGenericParameter (expr_type) ||
447 TypeManager.IsValueType (expr_type);
450 if (TypeManager.IsGenericParameter (expr_type))
451 return ImplicitTypeParameterBoxingConversion (
452 expr_type, target_type, out use_class_cast);
454 return false;
457 public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, Type target_type)
459 Type expr_type = expr.Type;
462 // From null to any nullable type
464 if (expr_type == TypeManager.null_type)
465 return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
467 // S -> T?
468 Type t_el = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type)[0]);
470 // S? -> T?
471 if (TypeManager.IsNullableType (expr_type))
472 expr_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (expr_type)[0]);
475 // Predefined implicit identity or implicit numeric conversion
476 // has to exist between underlying type S and underlying type T
479 // Handles probing
480 if (ec == null) {
481 if (expr_type == t_el)
482 return EmptyExpression.Null;
484 return ImplicitNumericConversion (null, expr_type, t_el);
487 Expression unwrap;
488 if (expr_type != expr.Type)
489 unwrap = Nullable.Unwrap.Create (expr);
490 else
491 unwrap = expr;
493 Expression conv = expr_type == t_el ? unwrap : ImplicitNumericConversion (unwrap, expr_type, t_el);
494 if (conv == null)
495 return null;
497 if (expr_type != expr.Type)
498 return new Nullable.Lifted (conv, unwrap, target_type).Resolve (ec);
500 // Do constant optimization for S -> T?
501 if (unwrap is Constant)
502 conv = ((Constant) unwrap).ConvertImplicitly (ec, t_el);
504 return Nullable.Wrap.Create (conv, target_type);
507 /// <summary>
508 /// Implicit Numeric Conversions.
510 /// expr is the expression to convert, returns a new expression of type
511 /// target_type or null if an implicit conversion is not possible.
512 /// </summary>
513 public static Expression ImplicitNumericConversion (Expression expr, Type target_type)
515 return ImplicitNumericConversion (expr, expr.Type, target_type);
518 static Expression ImplicitNumericConversion (Expression expr, Type expr_type, Type target_type)
520 if (expr_type == TypeManager.sbyte_type){
522 // From sbyte to short, int, long, float, double, decimal
524 if (target_type == TypeManager.int32_type)
525 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
526 if (target_type == TypeManager.int64_type)
527 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
528 if (target_type == TypeManager.double_type)
529 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
530 if (target_type == TypeManager.float_type)
531 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
532 if (target_type == TypeManager.short_type)
533 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
534 if (target_type == TypeManager.decimal_type)
535 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
536 } else if (expr_type == TypeManager.byte_type){
538 // From byte to short, ushort, int, uint, long, ulong, float, double, decimal
540 if (target_type == TypeManager.int32_type || target_type == TypeManager.uint32_type ||
541 target_type == TypeManager.short_type || target_type == TypeManager.ushort_type)
542 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
544 if (target_type == TypeManager.uint64_type)
545 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
546 if (target_type == TypeManager.int64_type)
547 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
548 if (target_type == TypeManager.float_type)
549 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
550 if (target_type == TypeManager.double_type)
551 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
552 if (target_type == TypeManager.decimal_type)
553 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
555 } else if (expr_type == TypeManager.short_type){
557 // From short to int, long, float, double, decimal
559 if (target_type == TypeManager.int32_type)
560 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
561 if (target_type == TypeManager.int64_type)
562 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
563 if (target_type == TypeManager.double_type)
564 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
565 if (target_type == TypeManager.float_type)
566 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
567 if (target_type == TypeManager.decimal_type)
568 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
570 } else if (expr_type == TypeManager.ushort_type){
572 // From ushort to int, uint, long, ulong, float, double, decimal
574 if (target_type == TypeManager.int32_type || target_type == TypeManager.uint32_type)
575 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
577 if (target_type == TypeManager.uint64_type)
578 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
579 if (target_type == TypeManager.int64_type)
580 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
581 if (target_type == TypeManager.double_type)
582 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
583 if (target_type == TypeManager.float_type)
584 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
585 if (target_type == TypeManager.decimal_type)
586 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
587 } else if (expr_type == TypeManager.int32_type){
589 // From int to long, float, double, decimal
591 if (target_type == TypeManager.int64_type)
592 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
593 if (target_type == TypeManager.double_type)
594 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
595 if (target_type == TypeManager.float_type)
596 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
597 if (target_type == TypeManager.decimal_type)
598 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
599 } else if (expr_type == TypeManager.uint32_type){
601 // From uint to long, ulong, float, double, decimal
603 if (target_type == TypeManager.int64_type)
604 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
605 if (target_type == TypeManager.uint64_type)
606 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
607 if (target_type == TypeManager.double_type)
608 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R8);
609 if (target_type == TypeManager.float_type)
610 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R4);
611 if (target_type == TypeManager.decimal_type)
612 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
613 } else if (expr_type == TypeManager.int64_type){
615 // From long/ulong to float, double
617 if (target_type == TypeManager.double_type)
618 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
619 if (target_type == TypeManager.float_type)
620 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
621 if (target_type == TypeManager.decimal_type)
622 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
623 } else if (expr_type == TypeManager.uint64_type){
625 // From ulong to float, double
627 if (target_type == TypeManager.double_type)
628 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R8);
629 if (target_type == TypeManager.float_type)
630 return expr == null ? EmptyExpression.Null : new OpcodeCast (new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un), target_type, OpCodes.Conv_R4);
631 if (target_type == TypeManager.decimal_type)
632 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
633 } else if (expr_type == TypeManager.char_type){
635 // From char to ushort, int, uint, long, ulong, float, double, decimal
637 if ((target_type == TypeManager.ushort_type) ||
638 (target_type == TypeManager.int32_type) ||
639 (target_type == TypeManager.uint32_type))
640 return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
641 if (target_type == TypeManager.uint64_type)
642 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
643 if (target_type == TypeManager.int64_type)
644 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
645 if (target_type == TypeManager.float_type)
646 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
647 if (target_type == TypeManager.double_type)
648 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
649 if (target_type == TypeManager.decimal_type)
650 return expr == null ? EmptyExpression.Null : new CastToDecimal (expr);
651 } else if (expr_type == TypeManager.float_type){
653 // float to double
655 if (target_type == TypeManager.double_type)
656 return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
659 return null;
662 /// <summary>
663 /// Same as ImplicitStandardConversionExists except that it also looks at
664 /// implicit user defined conversions - needed for overload resolution
665 /// </summary>
666 public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, Type target_type)
668 if (ImplicitStandardConversionExists (expr, target_type))
669 return true;
671 if (expr.Type == InternalType.AnonymousMethod) {
672 if (!TypeManager.IsDelegateType (target_type) &&
673 TypeManager.DropGenericTypeArguments (target_type) != TypeManager.expression_type)
674 return false;
676 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
677 return ame.ImplicitStandardConversionExists (ec, target_type);
680 if (expr.eclass == ExprClass.MethodGroup) {
681 if (TypeManager.IsDelegateType (target_type) && RootContext.Version != LanguageVersion.ISO_1) {
682 MethodGroupExpr mg = expr as MethodGroupExpr;
683 if (mg != null)
684 return DelegateCreation.ImplicitStandardConversionExists (ec, mg, target_type);
687 return false;
690 return ImplicitUserConversion (ec, expr, target_type, Location.Null) != null;
693 /// <summary>
694 /// Determines if a standard implicit conversion exists from
695 /// expr_type to target_type
697 /// ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
698 /// </summary>
699 public static bool ImplicitStandardConversionExists (Expression expr, Type target_type)
701 Type expr_type = expr.Type;
703 if (expr_type == TypeManager.null_type) {
704 NullLiteral nl = expr as NullLiteral;
705 if (nl != null)
706 return nl.ConvertImplicitly (null, target_type) != null;
709 if (expr_type == TypeManager.void_type)
710 return false;
712 if (TypeManager.IsEqual (expr_type, target_type))
713 return true;
715 if (TypeManager.IsNullableType (target_type)) {
716 return ImplicitNulableConversion (null, expr, target_type) != null;
719 // First numeric conversions
720 if (ImplicitNumericConversion (null, expr_type, target_type) != null)
721 return true;
723 if (ImplicitReferenceConversionExists (expr, target_type))
724 return true;
726 bool use_class_cast;
727 if (ImplicitBoxingConversionExists (expr, target_type, out use_class_cast))
728 return true;
731 // Implicit Constant Expression Conversions
733 if (expr is IntConstant){
734 int value = ((IntConstant) expr).Value;
736 if (target_type == TypeManager.sbyte_type){
737 if (value >= SByte.MinValue && value <= SByte.MaxValue)
738 return true;
739 } else if (target_type == TypeManager.byte_type){
740 if (value >= 0 && value <= Byte.MaxValue)
741 return true;
742 } else if (target_type == TypeManager.short_type){
743 if (value >= Int16.MinValue && value <= Int16.MaxValue)
744 return true;
745 } else if (target_type == TypeManager.ushort_type){
746 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
747 return true;
748 } else if (target_type == TypeManager.uint32_type){
749 if (value >= 0)
750 return true;
751 } else if (target_type == TypeManager.uint64_type){
753 // we can optimize this case: a positive int32
754 // always fits on a uint64. But we need an opcode
755 // to do it.
757 if (value >= 0)
758 return true;
761 if (value == 0 && TypeManager.IsEnumType (target_type))
762 return true;
765 if (expr is LongConstant && target_type == TypeManager.uint64_type){
767 // Try the implicit constant expression conversion
768 // from long to ulong, instead of a nice routine,
769 // we just inline it
771 long v = ((LongConstant) expr).Value;
772 if (v >= 0)
773 return true;
777 // If `expr_type' implements `target_type' (which is an iface)
778 // see TryImplicitIntConversion
780 if (target_type.IsInterface && TypeManager.ImplementsInterface (expr_type, target_type))
781 return true;
783 if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
784 return true;
786 // Conversion from __arglist to System.ArgIterator
787 if (expr_type == InternalType.Arglist)
788 return target_type == TypeManager.arg_iterator_type;
790 return false;
793 /// <summary>
794 /// Finds "most encompassed type" according to the spec (13.4.2)
795 /// amongst the methods in the MethodGroupExpr
796 /// </summary>
797 static Type FindMostEncompassedType (IList<Type> types)
799 Type best = null;
801 if (types.Count == 0)
802 return null;
804 if (types.Count == 1)
805 return (Type) types [0];
807 EmptyExpression expr = EmptyExpression.Grab ();
809 foreach (Type t in types) {
810 if (best == null) {
811 best = t;
812 continue;
815 expr.SetType (t);
816 if (ImplicitStandardConversionExists (expr, best))
817 best = t;
820 expr.SetType (best);
821 foreach (Type t in types) {
822 if (best == t)
823 continue;
824 if (!ImplicitStandardConversionExists (expr, t)) {
825 best = null;
826 break;
830 EmptyExpression.Release (expr);
832 return best;
835 /// <summary>
836 /// Finds "most encompassing type" according to the spec (13.4.2)
837 /// amongst the types in the given set
838 /// </summary>
839 static Type FindMostEncompassingType (IList<Type> types)
841 Type best = null;
843 if (types.Count == 0)
844 return null;
846 if (types.Count == 1)
847 return types [0];
849 EmptyExpression expr = EmptyExpression.Grab ();
851 foreach (Type t in types) {
852 if (best == null) {
853 best = t;
854 continue;
857 expr.SetType (best);
858 if (ImplicitStandardConversionExists (expr, t))
859 best = t;
862 foreach (Type t in types) {
863 if (best == t)
864 continue;
865 expr.SetType (t);
866 if (!ImplicitStandardConversionExists (expr, best)) {
867 best = null;
868 break;
872 EmptyExpression.Release (expr);
874 return best;
877 /// <summary>
878 /// Finds the most specific source Sx according to the rules of the spec (13.4.4)
879 /// by making use of FindMostEncomp* methods. Applies the correct rules separately
880 /// for explicit and implicit conversion operators.
881 /// </summary>
882 static public Type FindMostSpecificSource (IList<MethodInfo> list,
883 Expression source, bool apply_explicit_conv_rules)
885 var src_types_set = new List<Type> ();
888 // If any operator converts from S then Sx = S
890 Type source_type = source.Type;
891 foreach (MethodBase mb in list){
892 AParametersCollection pd = TypeManager.GetParameterData (mb);
893 Type param_type = pd.Types [0];
895 if (param_type == source_type)
896 return param_type;
898 src_types_set.Add (param_type);
902 // Explicit Conv rules
904 if (apply_explicit_conv_rules) {
905 var candidate_set = new List<Type> ();
907 foreach (Type param_type in src_types_set){
908 if (ImplicitStandardConversionExists (source, param_type))
909 candidate_set.Add (param_type);
912 if (candidate_set.Count != 0)
913 return FindMostEncompassedType (candidate_set);
917 // Final case
919 if (apply_explicit_conv_rules)
920 return FindMostEncompassingType (src_types_set);
921 else
922 return FindMostEncompassedType (src_types_set);
925 /// <summary>
926 /// Finds the most specific target Tx according to section 13.4.4
927 /// </summary>
928 static public Type FindMostSpecificTarget (IList<MethodInfo> list,
929 Type target, bool apply_explicit_conv_rules)
931 var tgt_types_set = new List<Type> ();
934 // If any operator converts to T then Tx = T
936 foreach (MethodInfo mi in list){
937 Type ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
938 if (ret_type == target)
939 return ret_type;
941 tgt_types_set.Add (ret_type);
945 // Explicit conv rules
947 if (apply_explicit_conv_rules) {
948 var candidate_set = new List<Type> ();
950 EmptyExpression expr = EmptyExpression.Grab ();
952 foreach (Type ret_type in tgt_types_set){
953 expr.SetType (ret_type);
955 if (ImplicitStandardConversionExists (expr, target))
956 candidate_set.Add (ret_type);
959 EmptyExpression.Release (expr);
961 if (candidate_set.Count != 0)
962 return FindMostEncompassingType (candidate_set);
966 // Okay, final case !
968 if (apply_explicit_conv_rules)
969 return FindMostEncompassedType (tgt_types_set);
970 else
971 return FindMostEncompassingType (tgt_types_set);
974 /// <summary>
975 /// User-defined Implicit conversions
976 /// </summary>
977 static public Expression ImplicitUserConversion (ResolveContext ec, Expression source,
978 Type target, Location loc)
980 return UserDefinedConversion (ec, source, target, loc, false, true);
983 /// <summary>
984 /// User-defined Explicit conversions
985 /// </summary>
986 static Expression ExplicitUserConversion (ResolveContext ec, Expression source,
987 Type target, Location loc)
989 return UserDefinedConversion (ec, source, target, loc, true, true);
992 static void AddConversionOperators (List<MethodInfo> list,
993 Expression source, Type target_type,
994 bool look_for_explicit,
995 MethodGroupExpr mg)
997 if (mg == null)
998 return;
1000 Type source_type = source.Type;
1001 EmptyExpression expr = EmptyExpression.Grab ();
1004 // LAMESPEC: Undocumented IntPtr/UIntPtr conversions
1005 // IntPtr -> uint uses int
1006 // UIntPtr -> long uses ulong
1008 if (source_type == TypeManager.intptr_type) {
1009 if (target_type == TypeManager.uint32_type)
1010 target_type = TypeManager.int32_type;
1011 } else if (source_type == TypeManager.uintptr_type) {
1012 if (target_type == TypeManager.int64_type)
1013 target_type = TypeManager.uint64_type;
1016 foreach (MethodInfo m in mg.Methods) {
1017 AParametersCollection pd = TypeManager.GetParameterData (m);
1018 Type return_type = TypeManager.TypeToCoreType (m.ReturnType);
1019 Type arg_type = pd.Types [0];
1021 if (source_type != arg_type) {
1022 if (!ImplicitStandardConversionExists (source, arg_type)) {
1023 if (!look_for_explicit)
1024 continue;
1025 expr.SetType (arg_type);
1026 if (!ImplicitStandardConversionExists (expr, source_type))
1027 continue;
1031 if (target_type != return_type) {
1032 expr.SetType (return_type);
1033 if (!ImplicitStandardConversionExists (expr, target_type)) {
1034 if (!look_for_explicit)
1035 continue;
1036 expr.SetType (target_type);
1037 if (!ImplicitStandardConversionExists (expr, return_type))
1038 continue;
1042 // See LAMESPEC: Exclude IntPtr -> int conversion
1043 if (source_type == TypeManager.uintptr_type && return_type == TypeManager.uint32_type)
1044 continue;
1046 list.Add (m);
1049 EmptyExpression.Release (expr);
1052 /// <summary>
1053 /// Compute the user-defined conversion operator from source_type to target_type.
1054 /// `look_for_explicit' controls whether we should also include the list of explicit operators
1055 /// </summary>
1056 static MethodInfo GetConversionOperator (CompilerContext ctx, Type container_type, Expression source, Type target_type, bool look_for_explicit)
1058 var ops = new List<MethodInfo> (4);
1060 Type source_type = source.Type;
1062 if (source_type != TypeManager.decimal_type) {
1063 AddConversionOperators (ops, source, target_type, look_for_explicit,
1064 Expression.MethodLookup (ctx, container_type, source_type, "op_Implicit", Location.Null) as MethodGroupExpr);
1065 if (look_for_explicit) {
1066 AddConversionOperators (ops, source, target_type, look_for_explicit,
1067 Expression.MethodLookup (ctx,
1068 container_type, source_type, "op_Explicit", Location.Null) as MethodGroupExpr);
1072 if (target_type != TypeManager.decimal_type) {
1073 AddConversionOperators (ops, source, target_type, look_for_explicit,
1074 Expression.MethodLookup (ctx, container_type, target_type, "op_Implicit", Location.Null) as MethodGroupExpr);
1075 if (look_for_explicit) {
1076 AddConversionOperators (ops, source, target_type, look_for_explicit,
1077 Expression.MethodLookup (ctx,
1078 container_type, target_type, "op_Explicit", Location.Null) as MethodGroupExpr);
1082 if (ops.Count == 0)
1083 return null;
1085 Type most_specific_source = FindMostSpecificSource (ops, source, look_for_explicit);
1086 if (most_specific_source == null)
1087 return null;
1089 Type most_specific_target = FindMostSpecificTarget (ops, target_type, look_for_explicit);
1090 if (most_specific_target == null)
1091 return null;
1093 MethodInfo method = null;
1095 foreach (MethodInfo m in ops) {
1096 if (TypeManager.TypeToCoreType (m.ReturnType) != most_specific_target)
1097 continue;
1098 if (TypeManager.GetParameterData (m).Types [0] != most_specific_source)
1099 continue;
1100 // Ambiguous: more than one conversion operator satisfies the signature.
1101 if (method != null)
1102 return null;
1103 method = m;
1106 return method;
1109 /// <summary>
1110 /// User-defined conversions
1111 /// </summary>
1112 public static Expression UserDefinedConversion (ResolveContext ec, Expression source,
1113 Type target, Location loc,
1114 bool look_for_explicit, bool return_convert)
1116 Type source_type = source.Type;
1117 MethodInfo method = null;
1118 Expression expr = null;
1120 object o;
1121 DoubleHash hash;
1122 if (look_for_explicit) {
1123 hash = explicit_conv;
1124 } else {
1125 // Implicit user operators cannot convert to interfaces
1126 if (target.IsInterface)
1127 return null;
1129 hash = implicit_conv;
1132 if (!(source is Constant) && hash.Lookup (source_type, target, out o)) {
1133 method = (MethodInfo) o;
1134 } else {
1135 if (TypeManager.IsDynamicType (source_type))
1136 return null;
1138 method = GetConversionOperator (ec.Compiler, null, source, target, look_for_explicit);
1141 if (method != null) {
1142 Type most_specific_source = TypeManager.GetParameterData (method).Types[0];
1145 // This will do the conversion to the best match that we
1146 // found. Now we need to perform an implict standard conversion
1147 // if the best match was not the type that we were requested
1148 // by target.
1150 if (look_for_explicit) {
1151 ReportPrinter temp = new SessionReportPrinter ();
1152 ReportPrinter prev = ec.Report.SetPrinter (temp);
1154 expr = ExplicitConversionStandard (ec, source, most_specific_source, loc);
1156 ec.Report.SetPrinter (prev);
1157 if (temp.ErrorsCount != 0)
1158 expr = null;
1159 } else {
1160 if (ImplicitStandardConversionExists (source, most_specific_source))
1161 expr = ImplicitConversionStandard (ec, source, most_specific_source, loc);
1162 else
1163 expr = null;
1167 if (expr == null) {
1168 bool nullable = false;
1170 if (TypeManager.IsNullableType (source_type)) {
1171 source = Nullable.Unwrap.Create (source);
1172 nullable = true;
1175 Type target_underlying;
1176 if (TypeManager.IsNullableType (target)) {
1177 target_underlying = TypeManager.GetTypeArguments (target)[0];
1178 nullable = true;
1179 } else {
1180 // No implicit conversion S? -> T for non-reference type T
1181 if (!look_for_explicit && !TypeManager.IsReferenceType (target))
1182 nullable = false;
1184 target_underlying = target;
1187 if (nullable) {
1188 expr = UserDefinedConversion (ec, source, target_underlying, loc, look_for_explicit, return_convert);
1190 // Do result expression lifting only when it's needed
1191 if (expr != null && (!look_for_explicit || TypeManager.IsReferenceType (target)))
1192 expr = new Nullable.Lifted (expr, source, target).Resolve (ec);
1194 return expr;
1196 } else {
1197 expr = new UserCast (method, expr, loc).Resolve (ec);
1199 if (return_convert && !TypeManager.IsEqual (expr.Type, target)) {
1200 if (look_for_explicit) {
1201 expr = ExplicitConversionStandard (ec, expr, target, loc);
1202 } else {
1203 expr = ImplicitConversionStandard (ec, expr, target, loc);
1208 if (!(source is Constant))
1209 hash.Insert (source_type, target, method);
1211 return expr;
1214 /// <summary>
1215 /// Converts implicitly the resolved expression `expr' into the
1216 /// `target_type'. It returns a new expression that can be used
1217 /// in a context that expects a `target_type'.
1218 /// </summary>
1219 static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
1220 Type target_type, Location loc)
1222 Expression e;
1224 if (target_type == null)
1225 throw new Exception ("Target type is null");
1227 e = ImplicitConversionStandard (ec, expr, target_type, loc);
1228 if (e != null)
1229 return e;
1231 e = ImplicitUserConversion (ec, expr, target_type, loc);
1232 if (e != null)
1233 return e;
1235 return null;
1239 /// <summary>
1240 /// Attempts to apply the `Standard Implicit
1241 /// Conversion' rules to the expression `expr' into
1242 /// the `target_type'. It returns a new expression
1243 /// that can be used in a context that expects a
1244 /// `target_type'.
1246 /// This is different from `ImplicitConversion' in that the
1247 /// user defined implicit conversions are excluded.
1248 /// </summary>
1249 static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
1250 Type target_type, Location loc)
1252 return ImplicitConversionStandard (ec, expr, target_type, loc, false);
1255 static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, Type target_type, Location loc, bool explicit_cast)
1257 if (expr.eclass == ExprClass.MethodGroup){
1258 if (!TypeManager.IsDelegateType (target_type)){
1259 return null;
1263 // Only allow anonymous method conversions on post ISO_1
1265 if (RootContext.Version != LanguageVersion.ISO_1){
1266 MethodGroupExpr mg = expr as MethodGroupExpr;
1267 if (mg != null)
1268 return ImplicitDelegateCreation.Create (
1269 ec, mg, target_type, loc);
1273 Type expr_type = expr.Type;
1274 Expression e;
1276 if (expr_type.Equals (target_type)) {
1277 if (expr_type != TypeManager.null_type && expr_type != InternalType.AnonymousMethod)
1278 return expr;
1279 return null;
1282 if (TypeManager.IsVariantOf (expr_type, target_type)) {
1283 return expr;
1286 if (TypeManager.IsNullableType (target_type))
1287 return ImplicitNulableConversion (ec, expr, target_type);
1290 // Attempt to do the implicit constant expression conversions
1292 Constant c = expr as Constant;
1293 if (c != null) {
1294 try {
1295 c = c.ConvertImplicitly (ec, target_type);
1296 } catch {
1297 Console.WriteLine ("Conversion error happened in line {0}", loc);
1298 throw;
1300 if (c != null)
1301 return c;
1304 e = ImplicitNumericConversion (expr, expr_type, target_type);
1305 if (e != null)
1306 return e;
1308 e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
1309 if (e != null)
1310 return e;
1312 if (expr is IntConstant && TypeManager.IsEnumType (target_type)){
1313 Constant i = (Constant) expr;
1315 // LAMESPEC: Conversion from any 0 constant is allowed
1317 // An implicit enumeration conversion permits the decimal-integer-literal 0
1318 // to be converted to any enum-type and to any nullable-type whose underlying
1319 // type is an enum-type
1321 if (i.IsDefaultValue)
1322 return new EnumConstant (i, target_type).Resolve (ec);
1325 if (ec.IsUnsafe) {
1326 if (expr_type.IsPointer){
1327 if (target_type == TypeManager.void_ptr_type)
1328 return EmptyCast.Create (expr, target_type);
1331 // yep, comparing pointer types cant be done with
1332 // t1 == t2, we have to compare their element types.
1334 if (target_type.IsPointer){
1335 if (TypeManager.GetElementType(target_type) == TypeManager.GetElementType(expr_type))
1336 return expr;
1338 //return null;
1342 if (expr_type == TypeManager.null_type && target_type.IsPointer)
1343 return EmptyCast.Create (new NullPointer (loc), target_type);
1346 if (expr_type == InternalType.AnonymousMethod){
1347 AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
1348 Expression am = ame.Compatible (ec, target_type);
1349 if (am != null)
1350 return am.Resolve (ec);
1353 if (expr_type == InternalType.Arglist && target_type == TypeManager.arg_iterator_type)
1354 return expr;
1356 return null;
1359 /// <summary>
1360 /// Attempts to implicitly convert `source' into `target_type', using
1361 /// ImplicitConversion. If there is no implicit conversion, then
1362 /// an error is signaled
1363 /// </summary>
1364 static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
1365 Type target_type, Location loc)
1367 Expression e = ImplicitConversion (ec, source, target_type, loc);
1368 if (e != null)
1369 return e;
1371 if (TypeManager.IsDynamicType (source.Type)) {
1372 Arguments args = new Arguments (1);
1373 args.Add (new Argument (source));
1374 return new DynamicConversion (target_type, 0, args, loc).Resolve (ec);
1377 source.Error_ValueCannotBeConverted (ec, loc, target_type, false);
1378 return null;
1381 /// <summary>
1382 /// Performs the explicit numeric conversions
1384 /// There are a few conversions that are not part of the C# standard,
1385 /// they were interim hacks in the C# compiler that were supposed to
1386 /// become explicit operators in the UIntPtr class and IntPtr class,
1387 /// but for historical reasons it did not happen, so the C# compiler
1388 /// ended up with these special hacks.
1390 /// See bug 59800 for details.
1392 /// The conversion are:
1393 /// UIntPtr->SByte
1394 /// UIntPtr->Int16
1395 /// UIntPtr->Int32
1396 /// IntPtr->UInt64
1397 /// UInt64->IntPtr
1398 /// SByte->UIntPtr
1399 /// Int16->UIntPtr
1401 /// </summary>
1402 public static Expression ExplicitNumericConversion (Expression expr, Type target_type)
1404 Type expr_type = expr.Type;
1405 Type real_target_type = target_type;
1407 if (expr_type == TypeManager.sbyte_type){
1409 // From sbyte to byte, ushort, uint, ulong, char, uintptr
1411 if (real_target_type == TypeManager.byte_type)
1412 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
1413 if (real_target_type == TypeManager.ushort_type)
1414 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
1415 if (real_target_type == TypeManager.uint32_type)
1416 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
1417 if (real_target_type == TypeManager.uint64_type)
1418 return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
1419 if (real_target_type == TypeManager.char_type)
1420 return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
1422 // One of the built-in conversions that belonged in the class library
1423 if (real_target_type == TypeManager.uintptr_type){
1424 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I1_U8);
1426 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1428 } else if (expr_type == TypeManager.byte_type){
1430 // From byte to sbyte and char
1432 if (real_target_type == TypeManager.sbyte_type)
1433 return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
1434 if (real_target_type == TypeManager.char_type)
1435 return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
1436 } else if (expr_type == TypeManager.short_type){
1438 // From short to sbyte, byte, ushort, uint, ulong, char, uintptr
1440 if (real_target_type == TypeManager.sbyte_type)
1441 return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
1442 if (real_target_type == TypeManager.byte_type)
1443 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
1444 if (real_target_type == TypeManager.ushort_type)
1445 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
1446 if (real_target_type == TypeManager.uint32_type)
1447 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
1448 if (real_target_type == TypeManager.uint64_type)
1449 return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
1450 if (real_target_type == TypeManager.char_type)
1451 return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
1453 // One of the built-in conversions that belonged in the class library
1454 if (real_target_type == TypeManager.uintptr_type){
1455 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1457 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1459 } else if (expr_type == TypeManager.ushort_type){
1461 // From ushort to sbyte, byte, short, char
1463 if (real_target_type == TypeManager.sbyte_type)
1464 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
1465 if (real_target_type == TypeManager.byte_type)
1466 return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
1467 if (real_target_type == TypeManager.short_type)
1468 return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
1469 if (real_target_type == TypeManager.char_type)
1470 return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
1471 } else if (expr_type == TypeManager.int32_type){
1473 // From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
1475 if (real_target_type == TypeManager.sbyte_type)
1476 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
1477 if (real_target_type == TypeManager.byte_type)
1478 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
1479 if (real_target_type == TypeManager.short_type)
1480 return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
1481 if (real_target_type == TypeManager.ushort_type)
1482 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
1483 if (real_target_type == TypeManager.uint32_type)
1484 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
1485 if (real_target_type == TypeManager.uint64_type)
1486 return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
1487 if (real_target_type == TypeManager.char_type)
1488 return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
1490 // One of the built-in conversions that belonged in the class library
1491 if (real_target_type == TypeManager.uintptr_type){
1492 Expression u8e = new ConvCast (expr, TypeManager.uint64_type, ConvCast.Mode.I2_U8);
1494 return new OperatorCast (u8e, TypeManager.uintptr_type, true);
1496 } else if (expr_type == TypeManager.uint32_type){
1498 // From uint to sbyte, byte, short, ushort, int, char
1500 if (real_target_type == TypeManager.sbyte_type)
1501 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
1502 if (real_target_type == TypeManager.byte_type)
1503 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
1504 if (real_target_type == TypeManager.short_type)
1505 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
1506 if (real_target_type == TypeManager.ushort_type)
1507 return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
1508 if (real_target_type == TypeManager.int32_type)
1509 return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
1510 if (real_target_type == TypeManager.char_type)
1511 return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
1512 } else if (expr_type == TypeManager.int64_type){
1514 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1516 if (real_target_type == TypeManager.sbyte_type)
1517 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
1518 if (real_target_type == TypeManager.byte_type)
1519 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
1520 if (real_target_type == TypeManager.short_type)
1521 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
1522 if (real_target_type == TypeManager.ushort_type)
1523 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
1524 if (real_target_type == TypeManager.int32_type)
1525 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
1526 if (real_target_type == TypeManager.uint32_type)
1527 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
1528 if (real_target_type == TypeManager.uint64_type)
1529 return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
1530 if (real_target_type == TypeManager.char_type)
1531 return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
1532 } else if (expr_type == TypeManager.uint64_type){
1534 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1536 if (real_target_type == TypeManager.sbyte_type)
1537 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
1538 if (real_target_type == TypeManager.byte_type)
1539 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
1540 if (real_target_type == TypeManager.short_type)
1541 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
1542 if (real_target_type == TypeManager.ushort_type)
1543 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
1544 if (real_target_type == TypeManager.int32_type)
1545 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
1546 if (real_target_type == TypeManager.uint32_type)
1547 return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
1548 if (real_target_type == TypeManager.int64_type)
1549 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
1550 if (real_target_type == TypeManager.char_type)
1551 return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
1553 // One of the built-in conversions that belonged in the class library
1554 if (real_target_type == TypeManager.intptr_type){
1555 return new OperatorCast (EmptyCast.Create (expr, TypeManager.int64_type),
1556 TypeManager.intptr_type, true);
1558 } else if (expr_type == TypeManager.char_type){
1560 // From char to sbyte, byte, short
1562 if (real_target_type == TypeManager.sbyte_type)
1563 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
1564 if (real_target_type == TypeManager.byte_type)
1565 return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
1566 if (real_target_type == TypeManager.short_type)
1567 return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
1568 } else if (expr_type == TypeManager.float_type){
1570 // From float to sbyte, byte, short,
1571 // ushort, int, uint, long, ulong, char
1572 // or decimal
1574 if (real_target_type == TypeManager.sbyte_type)
1575 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
1576 if (real_target_type == TypeManager.byte_type)
1577 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
1578 if (real_target_type == TypeManager.short_type)
1579 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
1580 if (real_target_type == TypeManager.ushort_type)
1581 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
1582 if (real_target_type == TypeManager.int32_type)
1583 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
1584 if (real_target_type == TypeManager.uint32_type)
1585 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
1586 if (real_target_type == TypeManager.int64_type)
1587 return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
1588 if (real_target_type == TypeManager.uint64_type)
1589 return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
1590 if (real_target_type == TypeManager.char_type)
1591 return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
1592 if (real_target_type == TypeManager.decimal_type)
1593 return new CastToDecimal (expr, true);
1594 } else if (expr_type == TypeManager.double_type){
1596 // From double to sbyte, byte, short,
1597 // ushort, int, uint, long, ulong,
1598 // char, float or decimal
1600 if (real_target_type == TypeManager.sbyte_type)
1601 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
1602 if (real_target_type == TypeManager.byte_type)
1603 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
1604 if (real_target_type == TypeManager.short_type)
1605 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
1606 if (real_target_type == TypeManager.ushort_type)
1607 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
1608 if (real_target_type == TypeManager.int32_type)
1609 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
1610 if (real_target_type == TypeManager.uint32_type)
1611 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
1612 if (real_target_type == TypeManager.int64_type)
1613 return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
1614 if (real_target_type == TypeManager.uint64_type)
1615 return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
1616 if (real_target_type == TypeManager.char_type)
1617 return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
1618 if (real_target_type == TypeManager.float_type)
1619 return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
1620 if (real_target_type == TypeManager.decimal_type)
1621 return new CastToDecimal (expr, true);
1622 } else if (expr_type == TypeManager.uintptr_type){
1624 // Various built-in conversions that belonged in the class library
1626 // from uintptr to sbyte, short, int32
1628 if (real_target_type == TypeManager.sbyte_type){
1629 Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1630 return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I1);
1632 if (real_target_type == TypeManager.short_type){
1633 Expression uint32e = new OperatorCast (expr, TypeManager.uint32_type, true);
1634 return new ConvCast (uint32e, TypeManager.sbyte_type, ConvCast.Mode.U4_I2);
1636 if (real_target_type == TypeManager.int32_type){
1637 return EmptyCast.Create (new OperatorCast (expr, TypeManager.uint32_type, true),
1638 TypeManager.int32_type);
1640 } else if (expr_type == TypeManager.intptr_type){
1641 if (real_target_type == TypeManager.uint64_type){
1642 return EmptyCast.Create (new OperatorCast (expr, TypeManager.int64_type, true),
1643 TypeManager.uint64_type);
1645 } else if (expr_type == TypeManager.decimal_type) {
1646 return new CastFromDecimal (expr, target_type).Resolve ();
1648 return null;
1651 /// <summary>
1652 /// Returns whether an explicit reference conversion can be performed
1653 /// from source_type to target_type
1654 /// </summary>
1655 public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1657 Expression e = ExplicitReferenceConversion (null, source_type, target_type);
1658 if (e == null)
1659 return false;
1661 if (e == EmptyExpression.Null)
1662 return true;
1664 throw new InternalErrorException ("Invalid probing conversion result");
1667 /// <summary>
1668 /// Implements Explicit Reference conversions
1669 /// </summary>
1670 static Expression ExplicitReferenceConversion (Expression source, Type source_type, Type target_type)
1672 bool target_is_value_type = TypeManager.IsStruct (target_type);
1675 // From object to a generic parameter
1677 if (source_type == TypeManager.object_type && TypeManager.IsGenericParameter (target_type))
1678 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1681 // Explicit type parameter conversion.
1683 if (TypeManager.IsGenericParameter (source_type))
1684 return ExplicitTypeParameterConversion (source, source_type, target_type);
1687 // From object to any reference type or value type (unboxing)
1689 if (source_type == TypeManager.object_type)
1690 return source == null ? EmptyExpression.Null :
1691 target_is_value_type ? (Expression) new UnboxCast (source, target_type) : new ClassCast (source, target_type);
1694 // Unboxing conversion from the types object and System.ValueType to any non-nullable-value-type
1696 if (source_type == TypeManager.value_type && target_is_value_type)
1697 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1700 // From any class S to any class-type T, provided S is a base class of T
1702 if (TypeManager.IsSubclassOf (target_type, source_type))
1703 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1706 // From any class type S to any interface T, provides S is not sealed
1707 // and provided S does not implement T.
1709 if (target_type.IsInterface && !source_type.IsSealed &&
1710 !TypeManager.ImplementsInterface (source_type, target_type)) {
1711 return source == null ? EmptyExpression.Null : new ClassCast (source, 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 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)) {
1720 if (target_type.IsClass)
1721 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1724 // Unboxing conversion from any interface-type to any non-nullable-value-type that
1725 // implements the interface-type
1727 return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
1731 // From System.Collecitons.Generic.IList<T> and its base interfaces to a one-dimensional
1732 // array type S[], provided there is an implicit or explicit reference conversion from S to T.
1734 if (IList_To_Array (source_type, target_type))
1735 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1737 return null;
1740 if (source_type.IsArray) {
1741 if (target_type.IsArray) {
1743 // From System.Array to any array-type
1745 if (source_type == TypeManager.array_type)
1746 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1749 // From an array type S with an element type Se to an array type T with an
1750 // element type Te provided all the following are true:
1751 // * S and T differe only in element type, in other words, S and T
1752 // have the same number of dimensions.
1753 // * Both Se and Te are reference types
1754 // * An explicit reference conversions exist from Se to Te
1756 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1758 source_type = TypeManager.GetElementType (source_type);
1759 if (!TypeManager.IsReferenceType (source_type))
1760 return null;
1762 Type target_type_element = TypeManager.GetElementType (target_type);
1763 if (!TypeManager.IsReferenceType (target_type_element))
1764 return null;
1766 if (ExplicitReferenceConversionExists (source_type, target_type_element))
1767 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1769 return null;
1774 // From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces,
1775 // provided that there is an explicit reference conversion from S to T
1777 if (Array_To_IList (source_type, target_type, true))
1778 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1780 return null;
1784 // From System delegate to any delegate-type
1786 if (source_type == TypeManager.delegate_type && TypeManager.IsDelegateType (target_type))
1787 return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
1789 return null;
1792 /// <summary>
1793 /// Performs an explicit conversion of the expression `expr' whose
1794 /// type is expr.Type to `target_type'.
1795 /// </summary>
1796 static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
1797 Type target_type, Location loc)
1799 Type expr_type = expr.Type;
1801 // Explicit conversion includes implicit conversion and it used for enum underlying types too
1802 Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
1803 if (ne != null)
1804 return ne;
1806 if (TypeManager.IsEnumType (expr_type)) {
1807 Expression underlying = EmptyCast.Create (expr, TypeManager.GetEnumUnderlyingType (expr_type));
1808 expr = ExplicitConversionCore (ec, underlying, target_type, loc);
1809 if (expr != null)
1810 return expr;
1812 return ExplicitUserConversion (ec, underlying, target_type, loc);
1815 if (TypeManager.IsEnumType (target_type)){
1817 // Type System.Enum can be unboxed to any enum-type
1819 if (expr_type == TypeManager.enum_type)
1820 return new UnboxCast (expr, target_type);
1822 Expression ce = ExplicitConversionCore (ec, expr, TypeManager.GetEnumUnderlyingType (target_type), loc);
1823 if (ce != null)
1824 return EmptyCast.Create (ce, target_type);
1827 // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
1829 if (expr_type == TypeManager.intptr_type || expr_type == TypeManager.uintptr_type) {
1830 ne = ExplicitUserConversion (ec, expr, TypeManager.GetEnumUnderlyingType (target_type), loc);
1831 if (ne != null)
1832 return ExplicitConversionCore (ec, ne, target_type, loc);
1835 return null;
1838 ne = ExplicitNumericConversion (expr, target_type);
1839 if (ne != null)
1840 return ne;
1843 // Skip the ExplicitReferenceConversion because we can not convert
1844 // from Null to a ValueType, and ExplicitReference wont check against
1845 // null literal explicitly
1847 if (expr_type != TypeManager.null_type){
1848 ne = ExplicitReferenceConversion (expr, expr_type, target_type);
1849 if (ne != null)
1850 return ne;
1853 if (ec.IsUnsafe){
1854 ne = ExplicitUnsafe (expr, target_type);
1855 if (ne != null)
1856 return ne;
1859 return null;
1862 public static Expression ExplicitUnsafe (Expression expr, Type target_type)
1864 Type expr_type = expr.Type;
1866 if (target_type.IsPointer){
1867 if (expr_type.IsPointer)
1868 return EmptyCast.Create (expr, target_type);
1870 if (expr_type == TypeManager.sbyte_type ||
1871 expr_type == TypeManager.short_type ||
1872 expr_type == TypeManager.int32_type)
1873 return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
1875 if (expr_type == TypeManager.ushort_type ||
1876 expr_type == TypeManager.uint32_type ||
1877 expr_type == TypeManager.byte_type)
1878 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
1880 if (expr_type == TypeManager.int64_type)
1881 return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);
1883 if (expr_type == TypeManager.uint64_type)
1884 return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
1887 if (expr_type.IsPointer){
1888 if (target_type == TypeManager.sbyte_type)
1889 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1890 if (target_type == TypeManager.byte_type)
1891 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1892 if (target_type == TypeManager.short_type)
1893 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1894 if (target_type == TypeManager.ushort_type)
1895 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1896 if (target_type == TypeManager.int32_type)
1897 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1898 if (target_type == TypeManager.uint32_type)
1899 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1900 if (target_type == TypeManager.int64_type)
1901 return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
1902 if (target_type == TypeManager.uint64_type)
1903 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1905 return null;
1908 /// <summary>
1909 /// Same as ExplicitConversion, only it doesn't include user defined conversions
1910 /// </summary>
1911 static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
1912 Type target_type, Location l)
1914 int errors = ec.Report.Errors;
1915 Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
1916 if (ec.Report.Errors > errors)
1917 return null;
1919 if (ne != null)
1920 return ne;
1922 ne = ExplicitNumericConversion (expr, target_type);
1923 if (ne != null)
1924 return ne;
1926 ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
1927 if (ne != null)
1928 return ne;
1930 if (ec.IsUnsafe && expr.Type == TypeManager.void_ptr_type && target_type.IsPointer)
1931 return EmptyCast.Create (expr, target_type);
1933 expr.Error_ValueCannotBeConverted (ec, l, target_type, true);
1934 return null;
1937 /// <summary>
1938 /// Performs an explicit conversion of the expression `expr' whose
1939 /// type is expr.Type to `target_type'.
1940 /// </summary>
1941 static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
1942 Type target_type, Location loc)
1944 Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
1945 if (e != null) {
1947 // Don't eliminate explicit precission casts
1949 if (e == expr) {
1950 if (target_type == TypeManager.float_type)
1951 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1953 if (target_type == TypeManager.double_type)
1954 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
1957 return e;
1960 Type expr_type = expr.Type;
1961 if (TypeManager.IsNullableType (target_type)) {
1962 if (TypeManager.IsNullableType (expr_type)) {
1963 Type target = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type)[0]);
1964 Expression unwrap = Nullable.Unwrap.Create (expr);
1965 e = ExplicitConversion (ec, unwrap, target, expr.Location);
1966 if (e == null)
1967 return null;
1969 return new Nullable.Lifted (e, unwrap, target_type).Resolve (ec);
1970 } else if (expr_type == TypeManager.object_type) {
1971 return new UnboxCast (expr, target_type);
1972 } else {
1973 Type target = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type) [0]);
1975 e = ExplicitConversionCore (ec, expr, target, loc);
1976 if (e != null)
1977 return Nullable.Wrap.Create (e, target_type);
1979 } else if (TypeManager.IsNullableType (expr_type)) {
1980 e = Nullable.Unwrap.Create (expr, false);
1982 bool use_class_cast;
1983 if (ImplicitBoxingConversionExists (e, target_type, out use_class_cast))
1984 return new BoxedCast (expr, target_type);
1986 e = ExplicitConversionCore (ec, e, target_type, loc);
1987 if (e != null)
1988 return EmptyCast.Create (e, target_type);
1991 e = ExplicitUserConversion (ec, expr, target_type, loc);
1992 if (e != null)
1993 return e;
1995 expr.Error_ValueCannotBeConverted (ec, loc, target_type, true);
1996 return null;