From c50d0a3bca6e6a75d71608aa068e21df7e2cae5d Mon Sep 17 00:00:00 2001 From: Lucy Martin Date: Wed, 19 Jun 2024 16:56:34 +0100 Subject: [PATCH 1/2] #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..0235aba32635 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. + noTailTransform(tree) 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 From 8215d011b76527601a53d0fed3c75a3000a8af46 Mon Sep 17 00:00:00 2001 From: Lucy Martin Date: Wed, 19 Jun 2024 17:33:11 +0100 Subject: [PATCH 2/2] #20145 - bugfix when a return tail recurse is called inside a val definition, previously this would neither optimise nor fail. --- compiler/src/dotty/tools/dotc/transform/TailRec.scala | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index 0235aba32635..5cc50f220eaf 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -431,7 +431,10 @@ class TailRec extends MiniPhase { case tree: ValDef => // This could contain a return statement in a code block, so we do have to go into it. - noTailTransform(tree) + cpy.ValDef(tree)( + tree.name, + noTailTransform(tree.rhs) + ) case tree: DefDef => if (isMandatory)