#!/bin/sh
# Compare one package's emitted IL with its golden file and session support.
set -eu

source=$1
expected=${source%.rad}.ril
module=$(basename "${source%.rad}")
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM

set -- -pkg std
while IFS= read -r source_module; do
    set -- "$@" -mod "$source_module"
done < test/support/std.lib
set -- "$@" -pkg test -mod "$source" -entry test -dump il
for source_module in "${source%.rad}"/*.rad; do
    if [ -f "$source_module" ]; then
        set -- "$@" -mod "$source_module"
    fi
done

if ! ${RAD_EMULATOR:-emulator} -memory-size=385024 -data-size=348160 \
    -stack-size=1024 -run bin/radiance.rv64.dev "$@" >"$work/program.il" 2>"$work/compiler.log"; then
    cat "$work/compiler.log"
    cat "$work/program.il"
    exit 1
fi

# Top-level function and data definitions carry the source module's prefix.
awk -v prefix="\$\"$module::" '
    /^(fn |data )/ { keep = index($0, prefix) > 0 }
    keep { print }
    /^}/ { if (keep) print ""; keep = 0 }
' "$work/program.il" >"$work/actual.ril"
if [ ! -s "$work/actual.ril" ]; then
    echo "error: no IL definitions found for $module"
    exit 1
fi

# Golden comparisons ignore comments, indentation, and blank lines.
for kind in actual expected; do
    input=$expected
    if [ "$kind" = actual ]; then input=$work/actual.ril; fi
    awk '{ sub(/\/\/.*/, ""); gsub(/^[ \t]+|[ \t]+$/, ""); if (length) print }' \
        "$input" >"$work/$kind.normalized"
done
if ! cmp -s "$work/expected.normalized" "$work/actual.normalized"; then
    diff -u "$expected" "$work/actual.ril" || true
    exit 1
fi
