require "./test/collect_tests.rb"
require "./run.rb"
require "stringio"

`ghc -O engine.hs`

tests = collect_tests

tests.filter!{|source,expected,from,input,no_pp|
  !expected[/ERROR|stack level too deep/] && !source[/version/] && (input=="" || input=="777" || input==nil)
}

def output s
  $out << s
end

pass = 0
tests.each{|source,expected,from,input,no_pp|
  File.open("input.txt", "w"){|f| f << input }
  size = if expected[/\.\.\./]
    expected = $`
    $`.size
  else
    1000
  end
  begin
    $out = ""
    to_engine(source,no_pp ? nil : " ")
    last_inst = $out.lines.to_a.size - 2
    outputn 'Data (S %d) "int"' % size
    outputn 'Op "take" [%d,%d] 0 "[char]"' % [last_inst, last_inst+1]

    File.open("prog.ism", "w"){|f| f << $out }
    found = `engine prog.ism < input.txt 2>&1`.strip

    expected.gsub!("WARNING: ","WARNING: ".red)

    if expected == "RANK ERROR" && found[/arg \d rank too low/]
    elsif found != expected
      STDERR.puts "FAIL: #{from}"
      STDERR.puts source
      STDERR.puts "expected:"
      STDERR.puts expected
      STDERR.puts "found:"
      STDERR.puts found
      $stderr = STDERR
      exit(1)
    end

  rescue IogiiError => e
    STDERR.puts "failed to generate ism for: " + source
    raise e
  end
  pass += 1
}

puts "PASS #{pass} tests"