# Go vs. MaPLe vs. ParlayLib vs. Rust/Rayon vs. Java on the `tokens` benchmark
# (from parallel-ml-bench).
#
#   make            # build bin/tokens.{go,mpl,parlay,rust,java}
#   make input      # generate bin/words256.txt (~150MB)
#
#   bin/tokens.go  -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5
#   bin/tokens.go  -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5 -impl slices
#   bin/tokens.go  -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5 -impl bytearrays
#   bin/tokens.mpl @mpl procs 8 -- -infile bin/words256.txt -repeat 10 -warmup 5
#   bin/tokens.parlay -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5
#   bin/tokens.rust -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5
#   bin/tokens.rust -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5 -impl manual
#   bin/tokens.java -infile bin/words256.txt -procs 8 -repeat 10 -warmup 5

GO ?= go
CARGO ?= cargo
JAVAC ?= javac
JAR ?= jar
MPL ?= mpl
SMLPKG ?= smlpkg
MPL_FLAGS ?= -default-type int64 -default-type word64
CXX ?= c++
CXXFLAGS ?= -std=c++17 -O3 -DNDEBUG -pthread

PARLAY_REPO = https://github.com/cmuparlay/parlaylib.git
PARLAY_COMMIT = 51017699dcc421f80479cdb238d3092233ad0d26
PARLAY_DIR = parlay/parlaylib

MPLLIB = mpl/lib/github.com/mpllang/mpllib/sources.mpl.mlb

.PHONY: all input clean realclean

all: bin/tokens.go bin/tokens.mpl bin/tokens.parlay bin/tokens.rust bin/tokens.java

bin/tokens.go: go/go.mod $(wildcard go/*.go)
	@mkdir -p bin
	cd go && $(GO) build -o ../bin/tokens.go .

bin/tokens.mpl: $(MPLLIB) mpl/main.mlb $(wildcard mpl/*.sml)
	@mkdir -p bin
	$(MPL) $(MPL_FLAGS) -output $@ mpl/main.mlb

$(MPLLIB): mpl/sml.pkg
	cd mpl && $(SMLPKG) sync
	@touch $@

bin/tokens.parlay: $(PARLAY_DIR)/.fetched parlay/main.cpp parlay/tokens.h
	@mkdir -p bin
	$(CXX) $(CXXFLAGS) -I$(PARLAY_DIR)/include -o $@ parlay/main.cpp

$(PARLAY_DIR)/.fetched:
	rm -rf $(PARLAY_DIR)
	git clone -q $(PARLAY_REPO) $(PARLAY_DIR)
	cd $(PARLAY_DIR) && git checkout -q $(PARLAY_COMMIT)
	@touch $@

bin/tokens.rust: rust/Cargo.toml rust/Cargo.lock $(wildcard rust/src/*.rs)
	@mkdir -p bin
	$(CARGO) build --release --manifest-path rust/Cargo.toml --target-dir bin/rust-target
	cp bin/rust-target/release/tokens $@

# bin/tokens.java is a small wrapper script that runs bin/tokens.jar.
# Extra JVM options can be passed with JAVA_OPTS, e.g. JAVA_OPTS=-Xmx16g
bin/tokens.java: bin/tokens.jar
	printf '#!/bin/sh\nexec java $$JAVA_OPTS -cp "$$(dirname "$$0")/tokens.jar" Tokens "$$@"\n' > $@
	chmod +x $@

bin/tokens.jar: $(wildcard java/*.java)
	@mkdir -p bin/java-classes
	$(JAVAC) -d bin/java-classes $^
	$(JAR) cf $@ -C bin/java-classes .

# words.txt concatenated 256 times (same as parallel-ml-bench's words256.txt)
input: bin/words256.txt

bin/words256.txt: inputs/words.txt
	@mkdir -p bin
	for i in $$(seq 256); do cat $<; done > $@

clean:
	rm -rf bin

realclean: clean
	rm -rf mpl/lib $(PARLAY_DIR)
