From: Nobuyoshi Nakada <nobu@...>
Date: 2009-03-10T11:11:53+09:00
Subject: [ruby-core:22790] Re: [Feature #1256] Add constant TAILRECURSION to let a program recognize if tail recursion optimization is implemented

Hi,

At Tue, 10 Mar 2009 04:26:51 +0900,
Wolfgang N�dasi-Donner wrote in [ruby-core:22785]:
> Afterwards I rebuilt Ruby, but the stack overflow for both examples I 
> posted before are still there.
> 
> Should I change additional things in the source?

trace_instruction option prevents the optimization.

$ cat ~/tmp/tailcall.rb
#! /usr/bin/ruby
src, file, line = <<SRC, __FILE__, __LINE__+1
def a(n)
  return if (n -= 1) <= 0
  a(n)
end
SRC
tailcallopt = ARGV[0] == "true"
traceinst = ARGV[1] != "false"
puts "tailcall_optimization: #{tailcallopt}, trace_instruction: #{traceinst}"
iseq = RubyVM::InstructionSequence.new(src, file, line,
                                       tailcall_optimization: tailcallopt,
                                       trace_instruction: traceinst)
iseq.eval
begin
  a(1000000)
  puts :ok
rescue SystemStackError => e
  puts "#{e.class} #{e.backtrace.size}"
end

$ ./ruby ~/tmp/tailcall.rb 
tailcall_optimization: false, trace_instruction: true
SystemStackError 8187

$ ./ruby ~/tmp/tailcall.rb true 
tailcall_optimization: true, trace_instruction: true
SystemStackError 8187

$ ./ruby ~/tmp/tailcall.rb true false
tailcall_optimization: true, trace_instruction: false
ok

-- 
Nobu Nakada