# Builds a ChibiOS test image for qemu-system-arm -M olimex-stm32-h405, which
# models an STM32F405 -- the part the firmware actually targets.
#
# Kernel only: no HAL, no STM32 LLD. The clock tree is whatever QEMU provides
# and SysTick is a Cortex-M core peripheral, so none of the board's peripheral
# init has to be simulated for the kernel to run.
#
#   nix-shell -p gcc-arm-embedded gnumake qemu --run 'make run'
#   nix-shell -p gcc-arm-embedded gnumake qemu --run './run.sh'

TEST   ?= test_kernel

# Named once: the FLAGKEY probe below and the compile and link rules
# must agree about which compiler this is, or the key describes a
# toolchain the objects were not built with.
CC_ARM   ?= arm-none-eabi-gcc
SIZE_ARM ?= arm-none-eabi-size

TOP     = ../..
# The package repo, for the prototype script test_garmr runs.
# Upstream's name first, then the fork's; run.sh makes the same choice and
# exports it.
PKG ?= $(firstword $(wildcard $(TOP)/../vesc_pkg $(TOP)/../pkg) $(TOP)/../vesc_pkg)
CHIBIOS = $(TOP)/ChibiOS_3.0.5

include $(CHIBIOS)/os/rt/rt.mk
include $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/mk/port_v7m.mk
include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/startup_stm32f4xx.mk

CSRC   = $(KERNSRC) $(PORTSRC) $(STARTUPSRC) qrt.c $(TEST).c

ASMSRC = $(STARTUPASM) $(PORTASM)

# $(TOP) is on the include path for bldc's own chconf.h, so the kernel here is
# configured exactly as it is in firmware -- same tick rate, same debug options.
INCDIR := . $(TOP) $(KERNINC) $(PORTINC) $(STARTUPINC) \
          $(CHIBIOS)/os/hal/osal/rt $(CHIBIOS)/os/hal/include

# test_engine links the real engine: the vendored Lua core, the container
# parser, and the CCM arena allocator. syscalls.c is what make/fw.mk gives the
# firmware for newlib's _sbrk, so malloc behaves here as it does on the board.
ENGINE_SRC = $(wildcard $(TOP)/script/lua/*.c) \
             $(TOP)/script/script_pack.c \
             $(TOP)/script/pkg_table.c \
             $(TOP)/util/crc.c \
             $(TOP)/script/script_lua.c \
             $(TOP)/script/script_alloc.c \
             $(CHIBIOS)/os/various/syscalls.c

# Every binding set luaif.c registers, with the fakes they compile against.
#
# One list rather than a per-test one, because test_luaif links luaif.c and so
# needs all of them: adding a binding set and registering it broke that test
# twice, each time caught only by run.sh's build check. Now adding one here
# fixes both at once.
BINDING_SRC = $(TOP)/script/lua_vesc_mc.c \
              $(TOP)/script/lua_vesc_conf.c \
              $(TOP)/script/lua_vesc_can.c
# fake_io.c and fake_pas.c stand in for lua_vesc_io.c and lua_vesc_pas.c,
# which cannot be linked here: they
# reach the ChibiOS HAL through conf_general.h and app.h, and these images
# have no HAL.
# See the note in fake_io.c, and tests/lua_adc for what does cover it.
BINDING_FAKES = fake/fake_mc.c fake/fake_conf.c fake/fake_can.c fake/fake_io.c \
                fake/fake_pas.c
BINDING_INC = $(TOP)/script $(TOP)/script/lua $(TOP)/util

ifeq ($(TEST),test_engine)
  CSRC += $(ENGINE_SRC)
  INCDIR += $(TOP)/script $(TOP)/script/lua
endif

# test_bindings compiles script/lua_vesc_mc.c against the fakes in fake/,
# which sit earlier on the include path than the real mc_interface.h and
# timeout.h. The bindings therefore have no test seam of their own.
ifeq ($(TEST),test_bindings)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_mc.c \
          fake/fake_mc.c
  # fake/ must come FIRST: $(TOP) also has a real timeout.h, and whichever
  # directory is earlier on the path wins.
  INCDIR := fake $(INCDIR) $(TOP)/script $(TOP)/script/lua
endif

# test_conf compiles lua_vesc_conf.c against the fakes, including the real
# datatypes.h so the configuration structs are the firmware's own -- the
# offsets in the generated table have to mean something.
ifeq ($(TEST),test_conf)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_conf.c \
          fake/fake_mc.c \
          fake/fake_conf.c
  INCDIR := fake $(INCDIR) $(TOP)/script $(TOP)/script/lua
endif

# demo_lisp is the LispBM counterpart to demo. LispBM ships its own ChibiOS
# platform layer, so its core links into this kernel-only image the same way
# the Lua core does -- no HAL, no flash driver.
ifneq ($(filter $(TEST),demo_lisp test_garmr_lisp test_pkgs_lisp),)
  # No -ffreestanding here. It makes newlib's inttypes.h withhold PRIu64 and
  # PRId64, which lispBM/src/print.c uses -- the firmware does not pass it
  # either, so this matches how LispBM is really built.
  FREESTANDING :=
  # The same LBM_USE_* set make/fw.mk passes, so this is the engine the
  # firmware builds rather than a differently-configured one.
  TESTDEFS += -DLBM_USE_DYN_FUNS -DLBM_USE_DYN_MACROS -DLBM_USE_DYN_LOOPS \
              -DLBM_USE_TIME_QUOTA -DLBM_USE_ERROR_LINENO \
              -DLBM_USE_MACRO_REST_ARGS
  LISPBM = $(TOP)/lispBM/lispBM
  # The extension list the firmware builds, not a glob: crypto_extensions.c
  # wants an external crypto.h the firmware does not provide either.
  CSRC += $(wildcard $(LISPBM)/src/*.c) \
          $(LISPBM)/src/extensions/array_extensions.c \
          $(LISPBM)/src/extensions/lbm_dyn_lib.c \
          $(LISPBM)/src/extensions/math_extensions.c \
          $(LISPBM)/src/extensions/mutex_extensions.c \
          $(LISPBM)/src/extensions/string_extensions.c \
          $(LISPBM)/platform/chibios/src/platform_mutex.c \
          $(LISPBM)/platform/chibios/src/platform_timestamp.c \
          $(CHIBIOS)/os/various/syscalls.c
  # fake/ supplies a hal.h that is only an include of ch.h; see the note in it.
  INCDIR := fake $(INCDIR) $(TOP)/lispBM $(LISPBM)/include \
            $(LISPBM)/include/extensions $(LISPBM)/platform/chibios/include
endif

# Several packages at once: the firmware's own package table and loader on
# top of the LispBM core above.
ifeq ($(TEST),test_pkgs_lisp)
  CSRC += $(TOP)/script/pkg_table.c $(TOP)/script/script_pack.c $(TOP)/script/lbm_pkgs.c \
          $(TOP)/util/crc.c
  INCDIR += $(TOP)/script
endif

# demo is not a test: it prints a console session for showing what the engine
# does. Same sources as test_script.
ifeq ($(TEST),demo)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_mc.c \
          $(TOP)/script/lua_vesc_conf.c \
          fake/fake_mc.c \
          fake/fake_io.c \
          fake/fake_conf.c
  INCDIR := fake $(INCDIR) $(BINDING_INC) .
endif

# test_script runs script/examples/bench_throttle.lua. The source is embedded
# from the real file by the rule below, so the test cannot drift from what
# gets uploaded. The io bindings here are the stand-ins in fake_io.c, not
# script/lua_vesc_io.c -- see the note in that file.
# test_garmr runs the Garmr prototype's engage logic against the fakes: the
# Schmitt trigger, the validity window, the debounce and the keepalive. The
# control it drives lives in app_pas.c and is covered by tests/app_pas; what
# is here is the decision about when to ask for it.
ifeq ($(TEST),test_garmr)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_mc.c \
          fake/fake_mc.c \
          fake/fake_io.c \
          fake/fake_pas.c
  INCDIR := fake $(INCDIR) $(BINDING_INC) .
endif

# test_cppm_lib runs the package repo's cppm_input native library: the
# binary is built here from $(PKG)/cppm_input/c_lib with the flags and link
# script of $(PKG)/c_libs/rules.mk (kept the same by hand: -fpic -Os, the
# Cortex-M4 hard-float ABI, sections collected, init kept), and included
# into the image as a byte array.
CPPM_LIB_SRC = $(addprefix $(PKG)/cppm_input/c_lib/,code.c cppm_core.c cppm_dec.c)
CPPM_LIB_CFLAGS = -fpic -Os -Wall -Wextra -std=gnu99 -I$(PKG)/c_libs \
                  -fomit-frame-pointer -falign-functions=16 -mthumb \
                  -fsingle-precision-constant -mfloat-abi=hard -mfpu=fpv4-sp-d16 \
                  -mcpu=cortex-m4 -fdata-sections -ffunction-sections -DIS_VESC_LIB \
                  -fno-tree-loop-distribute-patterns
ifeq ($(TEST),test_cppm_lib)
  CSRC += $(CHIBIOS)/os/various/syscalls.c
  INCDIR += $(PKG)/c_libs
  TESTDEFS += -DCPPM_LIB_BIN=\"obj/cppm_lib.bin\"
endif

# (not the default goal: that stays `all`, further down)
.DEFAULT_GOAL := all
obj/cppm_lib.bin: $(CPPM_LIB_SRC) $(PKG)/c_libs/vesc_c_if.h $(PKG)/c_libs/vesc_c_if_escargot.h Makefile
	@mkdir -p obj
	@$(CC_ARM) $(CPPM_LIB_CFLAGS) -nostartfiles -static -lm \
		-Wl,--gc-sections,--undefined=init,--no-warn-rwx-segments \
		-T $(PKG)/c_libs/link.ld $(CPPM_LIB_SRC) -o obj/cppm_lib.elf
	@arm-none-eabi-objcopy -O binary obj/cppm_lib.elf $@ --gap-fill 0x00
	@test -s $@ || { echo "cppm_lib.bin is empty"; rm -f $@; exit 1; }

ifeq ($(TEST),test_script)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_mc.c \
          fake/fake_mc.c \
          fake/fake_io.c \
          fake/fake_pas.c
  INCDIR := fake $(INCDIR) $(BINDING_INC) .
endif

# test_can compiles lua_vesc_can.c against a fake comm_can whose status caches
# the test fills in. It links lua_vesc_mc.c too, only for the timeout counter
# it shares with fake_mc -- the point being to prove the CAN setters do *not*
# touch it.
ifeq ($(TEST),test_can)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/lua_vesc_can.c \
          $(TOP)/script/lua_vesc_mc.c \
          fake/fake_mc.c \
          fake/fake_can.c \
          fake/fake_conf.c
  INCDIR := fake $(INCDIR) $(TOP)/script $(TOP)/script/lua $(TOP)/util
endif

# test_luaif adds the firmware adapter and the queue it drains. LUAIF_HOST_TEST
# swaps only flash_helper and the terminal for the stubs in luaif_host.h; the
# kernel, the engine, the arena and the queue are all the real thing.
ifeq ($(TEST),test_luaif)
  CSRC += $(ENGINE_SRC) \
          $(TOP)/script/script_queue.c \
          $(TOP)/script/luaif.c \
          $(TOP)/util/buffer.c \
          $(BINDING_SRC) \
          $(BINDING_FAKES)
  # fake/ first: $(TOP) also has a real timeout.h, and the earlier directory
  # on the path wins.
  INCDIR := fake $(INCDIR) $(BINDING_INC)
  # Without this luaif.c takes its firmware include path and reaches
  # flash_helper.h, which needs the HW_SOURCE/HW_HEADER defines a board build
  # supplies.
  TESTDEFS += -DLUAIF_HOST_TEST
endif


LDSCRIPT = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/ld/STM32F405xG.ld

# -DSTM32F405xx is what lets cmparams.h skip including a board.h.
# USE_FPU=hard and these two stack sizes are what make/fw.mk uses.
FREESTANDING ?= -ffreestanding
ARCH   = -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
DEFS   = -DCORTEX_USE_FPU=TRUE -DSTM32F405xx \
         -DTHUMB_PRESENT -DTHUMB_NO_INTERWORKING

# -MMD -MP emits a .d per object listing the headers it used, pulled in at the
# bottom. Without it, editing a header rebuilds nothing: a struct in fake/ was
# changed once and only half the objects picked it up, so two translation units
# disagreed about a field's offset and the test failed with values that looked
# like a logic bug.
CFLAGS = $(ARCH) $(DEFS) -O2 -g -std=gnu99 $(FREESTANDING) -MMD -MP \
         -fomit-frame-pointer -falign-functions=16 \
         -ffunction-sections -fdata-sections -fsingle-precision-constant \
         -Wall -Wextra $(TESTDEFS) $(CFLAGS_EXTRA) $(patsubst %,-I%,$(INCDIR))

# ChibiOS's .s files are macro-heavy and lowercase .s is not preprocessed
# unless asked, so assembly needs its own rule rather than riding on CFLAGS.
AFLAGS = $(ARCH) $(DEFS) -g -MMD -MP -x assembler-with-cpp $(patsubst %,-I%,$(INCDIR))

# -specs=nosys.specs is what make/fw.mk uses to satisfy newlib's syscall
# stubs; ChibiOS's syscalls.c supplies _sbrk_r over __heap_base__ beside it.
LDFLAGS = $(ARCH) -nostartfiles -specs=nosys.specs -T$(LDSCRIPT) \
          -L$(STARTUPLD) \
          -L$(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC \
          -Wl,--defsym=__process_stack_size__=0x800 \
          -Wl,--defsym=__main_stack_size__=0x800 \
          -Wl,--gc-sections,--no-warn-rwx-segments,-Map=$(TEST).map

# Object directory keyed on the extra flags. Without this, changing
# CFLAGS_EXTRA between builds silently reuses objects compiled with the old
# value -- a sweep over a -D parameter then reports the first build's number
# for every point in the sweep, which looks like a flat result rather than a
# broken one.
# The compiler is part of the key, not just the flags.
#
# Objects built by a different arm-none-eabi-gcc link against the current one
# without a word of complaint and then fail checks that pass from clean --
# which is what happened to test_luaif: run.sh reuses objects (it removes only
# the elf, which forces a relink and never a recompile), the toolchain had
# moved under them, and the result was 2 of 61 checks failing in the suite
# while 12 consecutive standalone runs from clean passed.
#
# -dumpversion rather than --version: the latter carries a store path, so on
# NixOS every rebuild of an identically-versioned toolchain would invalidate
# the objects for nothing.
CCID := $(shell $(CC_ARM) -dumpversion 2>/dev/null || echo unknown)
FLAGKEY := $(shell printf '%s' "$(CFLAGS_EXTRA)|$(CCID)" | cksum | cut -d' ' -f1)
OBJDIR  = obj/$(TEST)-$(FLAGKEY)

# Which key the current $(TEST).elf was linked from.
#
# OBJDIR being keyed is not enough on its own: switching flags back to a value
# used before finds that key's objects already present and older than the elf,
# so make reports "Nothing to be done" and leaves an elf built from the other
# key's objects in place. Rewriting this stamp whenever the key changes makes
# the elf older than one of its prerequisites, which forces the relink.
ELFKEY := .$(TEST).key
$(shell [ "$$(cat $(ELFKEY) 2>/dev/null)" = "$(FLAGKEY)" ] \
        || printf '%s' '$(FLAGKEY)' > $(ELFKEY))
OBJ    = $(addprefix $(OBJDIR)/,$(notdir $(CSRC:.c=.o)) $(notdir $(ASMSRC:.s=.o)))
VPATH  = $(sort $(dir $(CSRC) $(ASMSRC)))

QEMU     ?= qemu-system-arm
QEMUFLAGS = -M olimex-stm32-h405 -cpu cortex-m4 -nographic \
            -semihosting --semihosting-config enable=on,target=native \
            -serial mon:stdio

all: $(TEST).elf

$(OBJDIR):
	@mkdir -p $(OBJDIR)

# The example script, as a C string literal. Generated rather than pasted so
# the test runs the file that actually ships; the guard catches an empty or
# truncated conversion instead of testing nothing.
bench_throttle.inc: $(TOP)/script/examples/bench_throttle.lua Makefile
	@sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $< > $@
	@test -s $@ || { echo "bench_throttle.inc is empty"; rm -f $@; exit 1; }
	@grep -q 'M.step' $@ || { echo "bench_throttle.inc looks truncated"; \
		rm -f $@; exit 1; }

# The prototype lives in vesc_pkg, beside the package that ships it, so the
# guard checks for something only the real file has. garmr_lua, not garmr:
# that repo follows the convention where the base name is the lisp package
# and _lua is the Lua variant, and the lisp Garmr has its own test in the repl.
garmr.inc: $(PKG)/garmr_lua/garmr.lua Makefile
	@sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $< > $@
	@test -s $@ || { echo "garmr.inc is empty"; rm -f $@; exit 1; }
	@grep -q 'pas_walk_set' $@ || { echo "garmr.inc looks truncated"; \
		rm -f $@; exit 1; }

# The LispBM Garmr: the script, its stubs and its checks, all three cut from
# the package tree rather than copied. Same reasoning as garmr.inc above --
# the test runs what ships.
garmr_lisp.inc: $(PKG)/garmr/garmr.lisp Makefile
	@sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $< > $@
	@grep -q 'app-pas-walk-set' $@ || { echo "garmr_lisp.inc looks truncated"; \
		rm -f $@; exit 1; }

garmr_stubs.inc: $(PKG)/garmr/test/stubs.lisp Makefile
	@sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $< > $@
	@grep -q 'garmr-test' $@ || { echo "garmr_stubs.inc looks truncated"; \
		rm -f $@; exit 1; }

garmr_test.inc: $(PKG)/garmr/test/engage_test.lisp Makefile
	@sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $< > $@
	@grep -q 'checks, ' $@ || { echo "garmr_test.inc looks truncated"; \
		rm -f $@; exit 1; }

$(OBJDIR)/test_garmr_lisp.o: garmr_lisp.inc garmr_stubs.inc garmr_test.inc

$(OBJDIR)/test_script.o: bench_throttle.inc
$(OBJDIR)/demo.o: bench_throttle.inc
$(OBJDIR)/test_garmr.o: garmr.inc
$(OBJDIR)/test_cppm_lib.o: obj/cppm_lib.bin

$(OBJDIR)/%.o: %.c | $(OBJDIR)
	@$(CC_ARM) $(CFLAGS) -c -o $@ $<

$(OBJDIR)/%.o: %.s | $(OBJDIR)
	@$(CC_ARM) $(AFLAGS) -c -o $@ $<

$(TEST).elf: $(OBJ) $(ELFKEY)
	@$(CC_ARM) $(LDFLAGS) -o $@ $(OBJ) -lm
	@$(SIZE_ARM) $@

run: $(TEST).elf
	@timeout 60 $(QEMU) $(QEMUFLAGS) -kernel $(TEST).elf

# What a variable expands to: `make print-OBJDIR TEST=test_luaif`. Added
# because the stale-object bug above was pinned down by asking exactly this,
# and `make -p` is no help -- it prints the unexpanded recursive definition.
print-%: ; @echo '$*=$($*)'

clean:
	rm -rf obj *.elf *.map .*.key bench_throttle.inc garmr.inc \
		garmr_lisp.inc garmr_stubs.inc garmr_test.inc

-include $(OBJ:.o=.d)

.PHONY: all run clean
