Skip to content

Commit

Permalink
Constant fold (almost) all the number conversion methods
Browse files Browse the repository at this point in the history
Co-authored-by: Eugene Flesselle <[email protected]>
Co-authored-by: Martin Kucera <[email protected]>
  • Loading branch information
3 people committed May 12, 2023
1 parent ce65296 commit 3a1c0f4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
12 changes: 11 additions & 1 deletion compiler/src/dotty/tools/dotc/typer/ConstFold.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ object ConstFold:
nme.ADD, nme.SUB, nme.MUL, nme.DIV, nme.MOD)

val foldedUnops = Set[Name](
nme.UNARY_!, nme.UNARY_~, nme.UNARY_+, nme.UNARY_-)
nme.UNARY_!, nme.UNARY_~, nme.UNARY_+, nme.UNARY_-,
nme.toChar, nme.toInt, nme.toFloat, nme.toLong, nme.toDouble,
// toByte and toShort are NOT included because we cannot write
// the type of a constant byte or short
)

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

case (nme.toChar , _ ) if x.isNumeric => Constant(x.charValue)
case (nme.toInt , _ ) if x.isNumeric => Constant(x.intValue)
case (nme.toLong , _ ) if x.isNumeric => Constant(x.longValue)
case (nme.toFloat , _ ) if x.isNumeric => Constant(x.floatValue)
case (nme.toDouble, _ ) if x.isNumeric => Constant(x.doubleValue)

case _ => null
}

Expand Down
26 changes: 26 additions & 0 deletions tests/pos/i13990.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

object Test:

inline val myInt = 1 << 6

// toLong
inline val char2Long: 99L = 'c'.toLong
inline val int2Long: 0L = 0.toLong
inline val long2Long: 0L = 0L.toLong
inline val int2LongPropagated: 64L = myInt.toLong

// toInt
inline val char2Int: 99 = 'c'.toInt
inline val int2Int: 0 = 0.toInt
inline val long2Int: 0 = 0L.toInt
inline val long2IntWrapped: -2147483648 = 2147483648L.toInt
inline val int2IntPropagated: 64 = myInt.toInt

// toChar
inline val char2Char: 'c' = 'c'.toChar
inline val int2Char: 'c' = 99.toChar
inline val long2Char: 'c' = 99L.toChar
inline val int2CharPropagated: '@' = myInt.toChar

// chain everything
inline val wow: 1.0 = 1.toChar.toInt.toLong.toFloat.toDouble

0 comments on commit 3a1c0f4

Please sign in to comment.