#!/usr/bin/env bash
# Build Lua 5.1.5 for the W65816 target.  Most files compile at -O2;
# ldebug.c (symbexec) and ltablib.c (auxsort) hit a register-allocation
# limit at -O1+ and need -O0.  Outputs object files under build/.

set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LUA_SRC="$SCRIPT_DIR/lua-5.1.5/src"
OUT="$SCRIPT_DIR/build"
CLANG="$PROJECT_ROOT/tools/llvm-mos-build/bin/clang"

mkdir -p "$OUT"

LAYER2=()
for arg in "$@"; do
    case "$arg" in
        --layer2) LAYER2=(-mllvm -w65816-dbr-safe-ptrs) ;;
    esac
done

CFLAGS=(-target w65816 -O2 -ffunction-sections -DLUA_USE_C89
        -I "$PROJECT_ROOT/runtime/include" -I "$LUA_SRC"
        "${LAYER2[@]}")
# These functions exceed greedy regalloc's complexity budget — fall back
# to basic regalloc which is simpler but always terminates.  Code is
# slower but stays at -O2 so the resulting object is ~3.5× smaller
# than -O0 (lvm.o: 220KB → 63KB).
SLOW_FILES="ldebug ltablib lvm"
if [ ${#LAYER2[@]} -gt 0 ]; then
    SLOW_FILES="$SLOW_FILES lstrlib"
fi
SLOW_FLAGS="-mllvm -regalloc=basic"

# Core Lua: VM, parser, GC, string/table libs.  Skip: liolib (no FILE*
# backing in mfs-only mode), loslib (no time), loadlib (no dlsym),
# ldblib (debug interface), linit (registers stripped libs), lua.c
# (standalone main), luac.c (compiler binary), print.c (luac aux).
CORE="lapi lcode ldebug ldo ldump lfunc lgc llex lmem lobject lopcodes
      lparser lstate lstring ltable ltm lundump lvm lzio lauxlib
      lbaselib lstrlib ltablib lmathlib"

for f in $CORE; do
    o="$OUT/${f}.o"
    cflags=("${CFLAGS[@]}")
    if echo " $SLOW_FILES " | grep -q " $f "; then
        # shellcheck disable=SC2206
        cflags=("${cflags[@]}" $SLOW_FLAGS)
        echo "  CC  $f.c (basic regalloc)"
    else
        echo "  CC  $f.c"
    fi
    "$CLANG" "${cflags[@]}" -c "$LUA_SRC/${f}.c" -o "$o"
done

# Stubs for libc functions Lua needs that our libc doesn't provide.
"$CLANG" "${CFLAGS[@]}" -c "$SCRIPT_DIR/luaStubs.c" -o "$OUT/luaStubs.o"
echo "  CC  luaStubs.c"

echo ""
echo "Lua built: $(ls "$OUT"/*.o | wc -l) objects, $(du -sh "$OUT" | cut -f1) total"
