# Radiance build file.

# Standard library manifest and sources. `std.lib` and `std.lib.test` list
# the same modules as the manifest for the integration checks that still
# describe packages with flags.
STD_MANIFEST := lib/std/std.manifest
STD_LIB      := $(shell cat std.lib)
STD_TEST_LIB := $(STD_LIB) $(shell cat std.lib.test)

# Compiler output.
BIN_DIR := bin
RAD_BIN := $(BIN_DIR)/radiance.rv64.dev

# Emulator that runs every image. The integration driver starts its children
# on the same emulator. seed/update reads it from the environment.
RAD_EMULATOR ?= emulator
export RAD_EMULATOR

# Command that runs hosted build tools with the memory and stack limits in
# `seed/emulator-args`.
HOSTED    := $(RAD_EMULATOR) $(shell cat seed/emulator-args) -run
RADIANCE  := $(HOSTED) $(RAD_BIN)

default: $(RAD_BIN)

# Compiler build

SEED              := seed/radiance.rv64
COMPILER_SRC      := $(wildcard compiler/radiance/*.rad) compiler/radiance/radiance.manifest
# The compiler package, which the seed builds with its dependencies.
SEED_OPTS         := compiler/radiance

$(RAD_BIN): Makefile $(SEED) $(STD_LIB) $(STD_MANIFEST) $(COMPILER_SRC) | $(BIN_DIR)
	@echo "radiance $(SEED) => $@"
	@$(HOSTED) $(SEED) $(SEED_OPTS) -o $@

# Package flags for integration checks that still describe packages on the
# command line. Their dependency lists are in `seed/dependencies`. Module
# files are in the package directory, so each module after the root is
# mapped to its logical path. `$(call modules,DIR,ROOT,FILES)` gives the
# `-mod` flags of the files FILES of the package in DIR whose root module
# is ROOT.
modules = -mod $(2) $(foreach f,$(filter-out $(2),$(filter %.rad,$(3))), \
    -mod $(patsubst $(1)/%.rad,%,$(f))=$(f)) $(patsubst %,-mod %,$(filter %.ras,$(3)))
STD               := -pkg std -manifest seed/dependencies/none \
    $(call modules,lib/std,lib/std/std.rad,$(STD_LIB))

# Compiler inputs shared by the normal build and bootstrap stages.
compiler-options:
	@printf '%s\n' '$(SEED_OPTS)'

$(BIN_DIR):
	@mkdir -p $@

include kernel/Makefile
include test/Makefile

# Format the standard library and kernel sources in place. Set `FMT_SRC` to
# format other files.
FMT_SRC ?= $(filter %.rad,$(STD_TEST_LIB)) $(shell find kernel -name '*.rad' | sort)

fmt: $(RAD_BIN) $(INTEGRATION)
	@$(call integration,format,$(FMT_SRC))

seed:
	seed/update

clean-rad:
	rm -rf bin/*
	rm -f seed/radiance.rv64.s[0-9]*

clean: clean-std-test clean-bin-test clean-rad

.PHONY: default seed clean clean-rad test fmt compiler-options
.SUFFIXES:
.DELETE_ON_ERROR:
.SILENT:
