#!/usr/bin/env bash
# Control for arity-from-header: the runtime declares its own surface, so the
# compiler does not carry a second copy of it.
set -uo pipefail
ELC="${1:?usage: arity_query.sh <elc>}"
LANG_DIR="${2:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
W=$(mktemp -d); trap 'rm -rf "$W"' EXIT; F=0
chk(){ [ "$2" = "$3" ] && printf '  ok    %s\n' "$1" || { printf '  FAIL  %s\n    expected %s got %s\n' "$1" "$2" "$3"; F=$((F+1)); }; }

printf 'fn main() {\n    println("a", "b")\n}\n' > "$W/bad.el"
EL_RELATIONS_OUT="$W/r1.txt" "$ELC" "$W/bad.el" >/dev/null 2>&1
chk "the emitter does not adjudicate arity" "0" "$("$ELC" "$W/bad.el" 2>/dev/null | grep -c 'arity error')"
out=$("$LANG_DIR/tools/check/arity.sh" "$W/r1.txt" 2>&1); rc=$?
chk "a wrong-arity call is caught" "1" "$rc"
chk "the expected count is correct" "1" "$(echo "$out" | grep -c "takes 1 arguments, called with 2")"

printf 'fn main() {\n    println("a")\n}\n' > "$W/ok.el"
EL_RELATIONS_OUT="$W/r2.txt" "$ELC" "$W/ok.el" >/dev/null 2>&1
"$LANG_DIR/tools/check/arity.sh" "$W/r2.txt" >/dev/null 2>&1
chk "a correct call is clean" "0" "$?"

# multi-line declarations must not parse as zero params
n=$("$LANG_DIR/tools/check/arity.sh" "$W/r2.txt" | grep -oE '[0-9]+ signatures')
chk "signatures parsed from the header" "503 signatures" "$n"

echo; echo "  5 assertions, $((5-F)) passed, $F failed"; exit $F
