#
# YARV benchmark driver
#

require 'yarvutil'
require 'benchmark'
require 'rbconfig'

$bench = false

puts "ruby #{RUBY_VERSION} #{RUBY_PLATFORM}(#{RUBY_RELEASE_DATE})"
puts YARVCore::VERSION + " rev: #{YARVCore::REV} (#{YARVCore::DATE})"
puts YARVCore::OPTS
puts

def bm file
  prog = File.read(file).map{|e| e.rstrip}.join("\n")
  return if prog.empty?

  /bm_(.+)\.rb/ =~ file
  puts '-----------------------------------------------------------' unless $bench
  puts "#{$1}: "
  
  
puts <<EOS unless $bench
#{prog}
--
EOS
  #iseq = YARVUtil.parse(File.read(file))
  #vm   = YARVCore::VM.new
  begin
    Benchmark.bm{|x|
    # x.report("yarv"){ YARVUtil.load_bm(file) }
    } unless $bench

    ruby_exec(file) unless $bench
    yarv_exec(file)
    # puts YARVUtil.parse(File.read(file), file, 1).disasm
    
    # x.report("ruby"){ load(file, false)    }
    # x.report("yarv"){ vm.eval iseq }
  rescue Exception => e
    puts
    puts "** benchmark failure: #{e}"
    puts e.backtrace
  end
end

def exec_command type, file, w
  <<-EOP
  $DRIVER_PATH = '#{File.dirname($0)}'
  $LOAD_PATH.replace $LOAD_PATH | #{$LOAD_PATH.inspect}
  require 'benchmark'
  require 'yarvutil'
  print '#{type}'
  begin
    puts Benchmark.measure{
      #{w}('#{file}')
    }
  rescue Exception => exec_command_error_variable
    puts "\t" + exec_command_error_variable.message
  end
  EOP
end

def benchmark cmd
  rubybin = ENV['RUBY'] || File.join(
    Config::CONFIG["bindir"],
    Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"])
    
  IO.popen(rubybin, 'r+'){|io|
    io.write cmd
    io.close_write
    puts io.gets
  }
end

def ruby_exec file
  prog = exec_command 'ruby', file, 'load'
  benchmark prog
end

def yarv_exec file
  prog = exec_command 'yarv', file, 'YARVUtil.load_bm'
  benchmark prog
end

if $0 == __FILE__
  if ARGV.empty?
    Dir.glob(File.dirname(__FILE__) + '/bm_*.rb').sort.each{|file|
      bm file
    }
  else
    ARGV.each{|file|
      file = "#{File.dirname(__FILE__)}/#{file}.rb"
      bm file
    }
  end
end


