Skip to content

Commit 3a1c0f4

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 3a1c0f4

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-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.charValue)
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: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
object Test:
3+
4+
inline val myInt = 1 << 6
5+
6+
// toLong
7+
inline val char2Long: 99L = 'c'.toLong
8+
inline val int2Long: 0L = 0.toLong
9+
inline val long2Long: 0L = 0L.toLong
10+
inline val int2LongPropagated: 64L = myInt.toLong
11+
12+
// toInt
13+
inline val char2Int: 99 = 'c'.toInt
14+
inline val int2Int: 0 = 0.toInt
15+
inline val long2Int: 0 = 0L.toInt
16+
inline val long2IntWrapped: -2147483648 = 2147483648L.toInt
17+
inline val int2IntPropagated: 64 = myInt.toInt
18+
19+
// toChar
20+
inline val char2Char: 'c' = 'c'.toChar
21+
inline val int2Char: 'c' = 99.toChar
22+
inline val long2Char: 'c' = 99L.toChar
23+
inline val int2CharPropagated: '@' = myInt.toChar
24+
25+
// chain everything
26+
inline val wow: 1.0 = 1.toChar.toInt.toLong.toFloat.toDouble

0 commit comments

Comments
 (0)