CC=riscv64-unknown-elf-gcc
AS=riscv64-unknown-elf-as
ASFLAGS=-g -mabi=ilp32e -march=rv32ec
CFLAGS=$(ASFLAGS) -Os -Wall -std=c99
LD=riscv64-unknown-elf-ld
export JQ?=jaq
export QEMU?=qemu-riscv32

TEST_SRC := $(shell find tests -name '*.s')

# Replace .s with .elf
TESTS := $(patsubst %.s,%.elf,$(TEST_SRC))

all: calc.elf tests

check: tests
	@tests/unittest

clean:
	rm -f *.o tests/*.o *.elf tests/*.elf

hello.elf: hello.o
	$(LD) -m elf32lriscv $^ -o $@

calc.elf: mem.o hex.o debug.o math.o calc.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests: $(TESTS)

tests/math_add64.elf: hex.o math.o tests/math_add64.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/math_mul.elf: hex.o math.o tests/math_mul.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/math_div.elf: hex.o math.o tests/math_div.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/math_divmod.elf: hex.o math.o tests/math_divmod.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/math_mod.elf: hex.o math.o tests/math_mod.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/math_clz.elf: hex.o math.o tests/math_clz.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/fmt_count_digits.elf: hex.o math.o fmt.o tests/fmt_count_digits.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/fmt_decimal.elf: math.o fmt.o tests/fmt_decimal.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/btohex.elf: mem.o hex.o debug.o tests/btohex.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/tohex.elf: hex.o tests/tohex.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

tests/harness.elf: tests/harness.o tests/charness.o
	$(LD) -m elf32lriscv -T link.ld $^ -o $@

%.o : %.s
	$(AS) $(ASFLAGS) $< -o $@

.PHONY: check tests