#!/bin/sh
# Run assembly generation tests.
# Usage: test/asm/run <test.rad>..
#
# Each test is compiled to a binary and run with the emulator.

EMU="${RAD_EMULATOR:-emulator} -run"

if [ $# -eq 0 ]; then
  echo "error: no tests specified" >&2
  exit 1
fi

# Disable core dumps for tests.
ulimit -c 0

passed=0
failed=0

# Run each test.
for test in "$@"; do
  bin="${test%.rad}.rv64"
  echo -n "test $test ... "

  if [ ! -f "$bin" ]; then
    echo "FAILED (binary not found: $bin)"
    failed=$((failed + 1))
    continue
  fi

  # Parse expected return code from `//! returns: N` header (default 0).
  expected=0
  line=$(grep -m1 '^//! returns:' "$test" | sed 's/^\/\/! returns: *//')
  if [ -n "$line" ]; then
    expected="$line"
  fi

  $EMU "$bin" >/dev/null 2>&1
  ret=$?

  if [ "$ret" -eq "$expected" ]; then
    echo "ok"
    passed=$((passed + 1))
  else
    echo "FAILED (expected: $expected, got: $ret)"
    failed=$((failed + 1))
  fi
done
echo

if [ "$failed" -eq 0 ]; then
  echo "test result: ok. $passed passed; $failed failed"
  exit 0
else
  echo "test result: FAILED. $passed passed; $failed failed"
  exit 1
fi
