Aladdin - Scala Bugtracking
[#843] project: compiler priority: medium category: bug
submitter assigned to status date submitted
Martin Iulian fixed 2006-11-27 12:51:54.0
subject finally gets bypassed by tail-recursion optimizations
code
object Test extends Application {

  var cnt = 0;

  def f(n: int): int = 
    try {
      cnt = cnt + 1;
      Console.println("f "+n+" "+cnt)
      if (n == 0) 0
      else f(n-1)
    } finally {
      Console.println("finally "+cnt)
      cnt = cnt - 1
    }

  Console.println(f(10))
  Console.println(cnt)
}
    
what happened
f 10 1
f 9 2
f 8 3
f 7 4
f 6 5
f 5 6
f 4 7
f 3 8
f 2 9
f 1 10
f 0 11
finally 11
0
10
what expected Should count finally down to 1 and print `0' as last line. If you disassemble you find that method `f' has undergone tail recursion optimization. This is unsound, as before one finally is executed per recursive call; whereas after optimization only a single finally is executed.
[back to overview]
Changes of this bug report
Martin  edited on  2006-11-27 12:52:41.0
Here's the output again:
f 10 1
f 9 2
f 8 3
f 7 4
f 6 5
f 5 6
f 4 7
f 3 8
f 2 9
f 1 10
f 0 11
finally 11
0
10
Iulian  edited on  2006-11-27 14:39:44.0
Iulian  edited on  2006-11-27 14:42:11.0