From 036b86bea26c1cd082b0a9dca31fcdf2b7b7dd87 Mon Sep 17 00:00:00 2001 From: Lucy Martin Date: Wed, 19 Jun 2024 16:56:34 +0100 Subject: [PATCH] #20145 - bugfix when a return tail recurse is called inside a val definition, previously this would neither optimise nor fail. --- .../src/dotty/tools/dotc/transform/TailRec.scala | 4 ++-- tests/run/i20145.check | 1 + tests/run/i20145.scala | 15 +++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/run/i20145.check create mode 100644 tests/run/i20145.scala diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index d054c5aa6232..b8052721ff27 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -430,8 +430,8 @@ class TailRec extends MiniPhase { tree case tree: ValDef => - if (isMandatory) noTailTransform(tree.rhs) - tree + // This could contain a return statement in a code block, so we do have to go into it. + cpy.ValDef(tree)(rhs = noTailTransform(tree.rhs)) case tree: DefDef => if (isMandatory) diff --git a/tests/run/i20145.check b/tests/run/i20145.check new file mode 100644 index 000000000000..f6af6debe594 --- /dev/null +++ b/tests/run/i20145.check @@ -0,0 +1 @@ +10000001 diff --git a/tests/run/i20145.scala b/tests/run/i20145.scala new file mode 100644 index 000000000000..ea26f00e2c89 --- /dev/null +++ b/tests/run/i20145.scala @@ -0,0 +1,15 @@ +import scala.annotation.tailrec +@tailrec +def foo(i: Int): Int = { + if (i > 10000000) { + i + } else { + val bar: String = { + return foo(i + 1) + "foo" + } + -1 + } +} +@main def Test = + println(foo(0)) \ No newline at end of file