# protocol/: dwcore (the rules, C99), its Python binding, the test vectors and their proofs.
# Run inside `nix-shell` (protocol/shell.nix): gcc, python3, and for the ROM proofs cc65, rgbds,
# Mesen 2 (tools/mesen.sh finds or fetches it), xvfb-run, appimage-run, dotnet.
#
#   make               libdwcore.so (the Python binding's), the tools, the strict-C99 check
#   make test          dwcore's own tests (C + Python): maps vs the vectors, rules, messages, fixes
#   make vectors       (re)write vectors/maps and vectors/traces from dwcore
#   make prove-maps    vectors/maps == dwcore == the Famicom ROM == the Game Boy ROM (Mesen)
#   make prove-trace   the trace vectors on the Famicom and Game Boy ROMs vs dwcore (Mesen): README.md
#   make tables        regenerate dwcore/dw_tables.h from the Famicom port's generators

CC      ?= gcc
CFLAGS  ?= -O2
WARN    := -std=c99 -Wall -Wextra -pedantic -Werror -Wconversion -Wno-sign-conversion
B       := build
CORE    := dwcore/dwcore.c dwcore/dwcore.h dwcore/dw_tables.h
SEEDS   := 0x5AA5 0x1234 0xBEEF 0x0001

.PHONY: all test vectors prove-maps prove-trace tables clean

all: $(B)/libdwcore.so $(B)/dumpmap $(B)/ctest $(B)/freestanding.o

$(B)/libdwcore.so: $(CORE)
	@mkdir -p $(B)
	$(CC) $(WARN) $(CFLAGS) -shared -fPIC -o $@ dwcore/dwcore.c

# the core alone, freestanding (no libc headers but string.h's memset/memcpy): what consoles get
$(B)/freestanding.o: $(CORE)
	@mkdir -p $(B)
	$(CC) $(WARN) $(CFLAGS) -ffreestanding -fno-builtin -fno-stack-protector -c -o $@ dwcore/dwcore.c
	@! nm $@ | grep ' U ' | grep -v -E ' (memset|memcpy)$$' || (echo "dwcore needs more than memset/memcpy" && false)

$(B)/%: tools/%.c $(CORE)
	@mkdir -p $(B)
	$(CC) $(WARN) $(CFLAGS) -Idwcore -o $@ dwcore/dwcore.c $<

test: all
	$(B)/ctest vectors
	python3 -m unittest discover -s tests -v

vectors: $(B)/dumpmap $(B)/libdwcore.so
	for s in $(SEEDS); do $(B)/dumpmap $$s vectors/maps/$$s.bin; done
	python3 vectors/tools/make_traces.py

prove-maps: $(B)/dumpmap
	vectors/tools/prove-maps.sh $(SEEDS)

prove-trace: $(B)/libdwcore.so
	python3 vectors/tools/rom_trace.py both

tables:
	python3 dwcore/tools/gen_tables.py .. dwcore/dw_tables.h

clean:
	rm -rf $(B)
