Skip to content

Allow return in tailrec position #14067

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

Merged
merged 2 commits into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/transform/TailRec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ class TailRec extends MiniPhase {

case Return(expr, from) =>
val fromSym = from.symbol
val inTailPosition = fromSym.is(Label) && tailPositionLabeledSyms.contains(fromSym)
val inTailPosition = !fromSym.is(Label) || tailPositionLabeledSyms.contains(fromSym)
cpy.Return(tree)(transform(expr, inTailPosition), from)

case _ =>
Expand Down
2 changes: 2 additions & 0 deletions tests/run/tailrec-return.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
6
false
16 changes: 16 additions & 0 deletions tests/run/tailrec-return.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
object Test:

@annotation.tailrec
def sum(n: Int, acc: Int = 0): Int =
if n != 0 then return sum(n - 1, acc + n)
acc

@annotation.tailrec
def isEven(n: Int): Boolean =
if n != 0 && n != 1 then return isEven(n - 2)
if n == 1 then return false
true

def main(args: Array[String]): Unit =
println(sum(3))
println(isEven(5))