# Copyright (c) 2018 Simon Hudon. All rights reserved.
# Released under Apache 2.0 license as described in the file LICENSE.
# Authors: Simon Hudon, Sebastian Ullrich, Leonardo de Moura
LEAN = ../bin/lean
SRCS = $(shell find . -name '*.lean')
OBJS = $(SRCS:.lean=.olean)
DEPS = $(SRCS:.lean=.depend)
OPTS = @LEAN_EXTRA_MAKE_OPTS@
STAGE0_DIR = ../src/stage0
STAGE1_DIR = ../src/stage1
ifndef STAGE1_OUT
$(error "`STAGE1_OUT` must be set (use cmake)")
endif
CPPS = $(addprefix $(STAGE1_DIR)/,$(patsubst %.lean,%.cpp,$(SRCS)))
# ensure deterministic ordering
CPPS_CORE=$(sort $(patsubst %.lean,%.cpp,$(SRCS)))

.PHONY: all clean

all: $(OBJS)

depends: $(DEPS)

%.depend: %.lean
	@echo $(<:.lean=.olean): `$(LEAN) --deps $< | python relative.py` > $@

%.olean: %.lean %.depend
	@mkdir -p $(STAGE1_DIR)/$(@D)
	$(LEAN) $(OPTS) --make --cpp="$(STAGE1_DIR)/$*.cpp.tmp" $<
# create the .cpp file atomically
	mv "$(STAGE1_DIR)/$*.cpp.tmp" "$(STAGE1_DIR)/$*.cpp"
# make sure the .olean file is newer than the .depend file to prevent infinite make cycles
	@touch $*.olean

clean:
	find . -name *.olean -delete
	find . -name *.depend -delete
	-rm -r "$(STAGE1_DIR)" "$(STAGE1_OUT)"

$(STAGE1_DIR)/%.cpp: %.olean
	@

$(STAGE1_OUT)/%.o: $(STAGE1_DIR)/%.cpp
	@mkdir -p "$(@D)"
	../bin/leanc -c -o $@ $< $(LEANC_OPTS)

$(STAGE1_OUT)/libleanstdlib.a: $(addprefix $(STAGE1_OUT)/,$(patsubst %.lean,%.o,$(SRCS)))
	@rm -f $@
	@ar rcs $@ $^

update-stage0:
	rm -r $(STAGE0_DIR)/init
	cp -R $(STAGE1_DIR)/init $(STAGE0_DIR)/init
	echo "add_library (stage0 OBJECT $(CPPS_CORE))" > $(STAGE0_DIR)/CMakeLists.txt

.PRECIOUS: %.depend $(STAGE1_DIR)/%.cpp

include $(DEPS)
