scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Constant folding for `final val` is not folding unary operators such as `!` and `~` #12792

Closed j-mie6 closed 1 year ago

j-mie6 commented 1 year ago

Reproduction steps

Scala version: 2.13.10, 2.12.17

object Foo {
    final val u = 1 << (java.lang.Integer.SIZE - 1)
    final val x = 1 << (java.lang.Integer.SIZE - 2)
    final val y = 1 << (java.lang.Integer.SIZE - 3)
    final val z = 1 << (java.lang.Integer.SIZE - 4)
    final val c = 0xffffffff & ~u & ~x & ~y & ~z // should fold to 268435455 or 0x0fffffff
}

Problem

When examining the bytecode generated for this, the first 4 constants are folded as expected, however the final one, c, is not folded. On further investigation a final val imm = ~x will also not be folded, which suggesting folding with ~ is the problem.

Note that this is not an issue on 3.3.0

SethTisue commented 9 months ago

I've broadened the issue title, because a far more commonly used operator, !, was affected

% cat C.scala
class C { def x = !true }
% /usr/local/scala/scala-2.13.11/bin/scalac -Vprint:typer C.scala
...
    def x: Boolean = true.unary_!
...
% /usr/local/scala/scala-2.13.12/bin/scalac -Vprint:typer C.scala
...
    def x: Boolean = false
...