Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elide unit binding when beta-reducing #20085

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion compiler/src/dotty/tools/dotc/transform/BetaReduce.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import MegaPhase.*
import Symbols.*, Contexts.*, Types.*, Decorators.*
import StdNames.nme
import ast.TreeTypeMap
import Constants.Constant

import scala.collection.mutable.ListBuffer

Expand Down Expand Up @@ -133,7 +134,7 @@ object BetaReduce:
else if arg.tpe.dealias.isInstanceOf[ConstantType] then arg.tpe.dealias
else arg.tpe.widen
val binding = ValDef(newSymbol(ctx.owner, param.name, flags, tpe, coord = arg.span), arg).withSpan(arg.span)
if !(tpe.isInstanceOf[ConstantType] && isPureExpr(arg)) then
if !((tpe.isInstanceOf[ConstantType] || tpe.derivesFrom(defn.UnitClass)) && isPureExpr(arg)) then
bindings += binding
binding.symbol

Expand All @@ -147,6 +148,7 @@ object BetaReduce:
val expansion1 = new TreeMap {
override def transform(tree: Tree)(using Context) = tree.tpe.widenTermRefExpr match
case ConstantType(const) if isPureExpr(tree) => cpy.Literal(tree)(const)
case tpe: TypeRef if tpe.derivesFrom(defn.UnitClass) && isPureExpr(tree) => cpy.Literal(tree)(Constant(()))
case _ => super.transform(tree)
}.transform(expansion)

Expand Down
20 changes: 20 additions & 0 deletions compiler/test/dotty/tools/backend/jvm/InlineBytecodeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -765,4 +765,24 @@ class InlineBytecodeTests extends DottyBytecodeTest {
diffInstructions(instructions1, instructions2))
}
}

@Test def beta_reduce_elide_unit_binding = {
val source = """class Test:
| def test = ((u: Unit) => u).apply(())
""".stripMargin

checkBCode(source) { dir =>
val clsIn = dir.lookupName("Test.class", directory = false).input
val clsNode = loadClassNode(clsIn)

val fun = getMethod(clsNode, "test")
val instructions = instructionsFromMethod(fun)
val expected = List(Op(RETURN))

assert(instructions == expected,
"`i was not properly beta-reduced in `test`\n" + diffInstructions(instructions, expected))

}
}

}