CC ?= cc
CFLAGS ?= -O3 -DNDEBUG
CFLAGS += -std=c11 -Wall -Wextra -Wpedantic
DEPS ?= $(CURDIR)/.native-deps
Z3_PREFIX ?= $(DEPS)
WASMTIME_PREFIX ?= $(DEPS)
UNAME := $(shell uname -s)
ifneq ($(wildcard $(DEPS)/include/json-c/json.h),)
JSON_PREFIX ?= $(DEPS)
endif
ifeq ($(UNAME),Darwin)
LOADER := @loader_path
ifndef JSON_PREFIX
JSON_PREFIX := $(shell brew --prefix json-c)
endif
CPPFLAGS += -D_DARWIN_C_SOURCE
else
LOADER := '$$ORIGIN'
JSON_PREFIX ?= /usr
CPPFLAGS += -D_POSIX_C_SOURCE=200809L
LDLIBS += -lcrypto
endif
CPPFLAGS += $(addprefix -isystem ,$(sort $(Z3_PREFIX)/include $(WASMTIME_PREFIX)/include $(JSON_PREFIX)/include))
LDFLAGS += $(addprefix -L,$(sort $(Z3_PREFIX)/lib $(WASMTIME_PREFIX)/lib $(JSON_PREFIX)/lib)) -Wl,-rpath,$(LOADER)/../.native-deps/lib $(foreach dir,$(filter-out $(CURDIR)/.native-deps/lib,$(sort $(Z3_PREFIX)/lib $(WASMTIME_PREFIX)/lib $(JSON_PREFIX)/lib)),-Wl,-rpath,$(dir))
LDLIBS += -lwasmtime -lz3 -ljson-c
SRC := $(wildcard native/*.c)
OBJ := $(SRC:native/%.c=bin/obj/%.o)
all: bin/weft
bin/weft: $(OBJ) Makefile
	$(CC) $(CFLAGS) $(OBJ) $(LDFLAGS) $(LDLIBS) -o $@
bin/obj/%.o: native/%.c native/weft.h native/proof.h
	@mkdir -p bin/obj
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
.PHONY: all test
test: all
	sh tests/native.sh

bin/chrome-test: tests/chrome.c bin/obj/common.o Makefile
	$(CC) $(CPPFLAGS) $(CFLAGS) tests/chrome.c bin/obj/common.o $(LDFLAGS) -ljson-c -o $@
.PHONY: browser-test
browser-test: all bin/chrome-test
	sh tests/browser.sh

bin/bench-frontend: tools/bench-frontend.c bin/obj/parser.o bin/obj/compiler.o bin/obj/common.o Makefile
	$(CC) $(CPPFLAGS) $(CFLAGS) tools/bench-frontend.c bin/obj/parser.o bin/obj/compiler.o bin/obj/common.o $(LDFLAGS) -ljson-c -o $@
.PHONY: bench
bench: all bin/bench-frontend
	bin/bench-frontend examples/ballot.weft
	WEFT_TIMING=1 bin/weft build examples/ballot.weft
	bin/weft bench examples/ballot.weft choose

bin/obj/page_adapter.inc: browser/page.mjs
	@mkdir -p bin/obj
	xxd -i -n page_adapter $< > $@
bin/obj/page.o: bin/obj/page_adapter.inc
