Skip to content

Commit 9a14f01

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

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@ 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.toChar, nme.toInt, nme.toFloat, nme.toLong, nme.toDouble,
28+
// toByte and toShort are NOT included because we cannot write
29+
// the type of a constant byte or short
30+
)
2731

2832
def Apply[T <: Apply](tree: T)(using Context): T =
2933
tree.fun match
@@ -89,6 +93,12 @@ object ConstFold:
8993
case (nme.UNARY_- , FloatTag ) => Constant(-x.floatValue)
9094
case (nme.UNARY_- , DoubleTag ) => Constant(-x.doubleValue)
9195

96+
case (nme.toChar , _ ) if x.isNumeric => Constant(x.byteValue)
97+
case (nme.toInt , _ ) if x.isNumeric => Constant(x.intValue)
98+
case (nme.toLong , _ ) if x.isNumeric => Constant(x.longValue)
99+
case (nme.toFloat , _ ) if x.isNumeric => Constant(x.floatValue)
100+
case (nme.toDouble, _ ) if x.isNumeric => Constant(x.doubleValue)
101+
92102
case _ => null
93103
}
94104

tests/pos/i13990.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 wow: Double = 1.toByte.toShort.toChar.toInt.toLong.toFloat.toDouble

0 commit comments

Comments
 (0)