#!/usr/bin/env bash
# Build Lua 5.1.5 for the W65816 target.  All files compile at -O2.  A
# few functions (symbexec in ldebug.c, auxsort in ltablib.c, luaV_execute
# in lvm.c, and luaO_str2d-class code in lstrlib.c under --layer2) exceed
# what greedy regalloc can do with the 65816's single accumulator and
# fall back to basic regalloc automatically -- see
# scripts/ccRegallocFallback.sh.  No hand-maintained per-file list.
# 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[@]}")
CC="$PROJECT_ROOT/scripts/ccRegallocFallback.sh"

# 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"
    echo "  CC  $f.c"
    "$CC" "$CLANG" "${CFLAGS[@]}" -c "$LUA_SRC/${f}.c" -o "$o"
done

# Stubs for libc functions Lua needs that our libc doesn't provide.
"$CC" "$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"
