Skip to content

Commit 495573e

Browse files
TheElectronWillEugene FlesselleKuceraMartin
committed
Constant fold all the number conversion methods
Co-authored-by: Eugene Flesselle <[email protected]> Co-authored-by: Martin Kucera <[email protected]>
1 parent ce65296 commit 495573e

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

compiler/src/dotty/tools/dotc/typer/ConstFold.scala

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ object ConstFold:
2323
nme.ADD, nme.SUB, nme.MUL, nme.DIV, nme.MOD)
2424

2525
val foldedUnops = Set[Name](
26-
nme.UNARY_!, nme.UNARY_~, nme.UNARY_+, nme.UNARY_-)
26+
nme.UNARY_!, nme.UNARY_~, nme.UNARY_+, nme.UNARY_-,
27+
nme.toByte, nme.toChar, nme.toShort, nme.toInt, nme.toFloat,
28+
nme.toLong, nme.toDouble
29+
)
2730

2831
def Apply[T <: Apply](tree: T)(using Context): T =
2932
tree.fun match
@@ -89,6 +92,14 @@ object ConstFold:
8992
case (nme.UNARY_- , FloatTag ) => Constant(-x.floatValue)
9093
case (nme.UNARY_- , DoubleTag ) => Constant(-x.doubleValue)
9194

95+
case (nme.toByte , _ ) if x.isNumeric => Constant(x.byteValue)
96+
case (nme.toChar , _ ) if x.isNumeric => Constant(x.charValue)
97+
case (nme.toShort , _ ) if x.isNumeric => Constant(x.shortValue)
98+
case (nme.toInt , _ ) if x.isNumeric => Constant(x.intValue)
99+
case (nme.toLong , _ ) if x.isNumeric => Constant(x.longValue)
100+
case (nme.toFloat , _ ) if x.isNumeric => Constant(x.floatValue)
101+
case (nme.toDouble, _ ) if x.isNumeric => Constant(x.doubleValue)
102+
92103
case _ => null
93104
}
94105

tests/pos/13990.scala

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
object Test:
3+
4+
inline val myInt = 1 << 4
5+
6+
// toLong
7+
inline val byte2Long = 0.toByte.toLong
8+
inline val char2Long = 'c'.toLong
9+
inline val short2Long = 0.toShort.toLong
10+
inline val int2Long = 0.toLong
11+
inline val long2Long = 0L.toLong
12+
inline val int2LongPropagated = myInt.toLong
13+
14+
// toInt
15+
inline val byte2Int = 0.toByte.toInt
16+
inline val char2Int = 'c'.toInt
17+
inline val short2Int = 0.toShort.toInt
18+
inline val int2Int = 0.toInt
19+
inline val long2Int = 0L.toInt
20+
inline val int2IntPropagated = myInt.toInt
21+
22+
// toByte
23+
inline val byte2Byte = 0.toByte.toByte
24+
inline val char2Byte = 'c'.toByte
25+
inline val short2Byte = 0.toShort.toByte
26+
inline val int2Byte = 0.toByte
27+
inline val long2Byte = 0L.toByte
28+
inline val int2BytePropagated = myInt.toByte
29+
30+
// chain everything
31+
inline val one: 1.0 = 1.toByte.toShort.toChar.toInt.toLong.toFloat.toDouble

0 commit comments

Comments
 (0)