# Makefile for creating tiler.native using ocamlbuild 
# Make sure ocamlbuild can find with: eval `opam config env`

# SDL Library
LFLAGS = $(shell sdl2-config --libs)
# Static Tiler Library in C
LFLAGS += -L./tiler-lib -ltiler

.PHONY: default
default: tilerLib tiler.native

# Cleans and builds tiler library and tiler.native (which converts .tile to .ll for LLVM)
.PHONY: all
all : clean tilerLib tiler.native

# Build using ocamlc/ocamlopt + ocamlfind to locate LLVM
.PHONY : tiler.native
tiler.native :
	ocamlbuild -use-ocamlfind -pkgs llvm,llvm.analysis -cflags -w,+a-4 tiler.native

# Removes all generated files
.PHONY : clean
clean :
	ocamlbuild -clean
	+$(MAKE) -C tiler-lib clean
	rm -rf tiler scanner.ml parser.ml parser.mli
	rm -rf *.cmx *.cmi *.cmo *.cmx *.o *.ll *.out *.exe
	rm -rf testall.log 
	rm -rf tests/*.ll tests/*.diff tests/*.exe tests/*.gen tests/*.o 

OBJS = ast.cmx codegen.cmx parser.cmx scanner.cmx semant.cmx tiler.cmx

tiler : $(OBJS)
	ocamlfind ocamlopt -linkpkg -package llvm -package llvm.analysis $(OBJS) -o tiler

tilerLib:
	+$(MAKE) -C tiler-lib

scanner.ml : scanner.mll
	ocamllex scanner.mll

parser.ml parser.mli : parser.mly
	ocamlyacc parser.mly

%.cmo : %.ml
	ocamlc -g -c -I ~/.opam/system/lib/llvm $<

%.cmi : %.mli
	ocamlc -c $<

%.cmx : %.ml
	ocamlfind ocamlopt -c -package llvm $<

# Shorthand for fully compiling .tile into .exe (adapted from Ballr's approach)
%.game: %.tile
	./tiler.native -c $(*F).tile
	clang -c $(*F).ll
	clang -g $(*F).o -o $(*F).exe $(LFLAGS)

# Shorthand for testing test cases in tests directory (adapted from Ballr's approach)
# Required for working in tests directory. Intermediate files also put in tests directory. 
%.test: 
	./tiler.native -c tests/$(*F).tile
	clang -c tests/$(*F).ll -o tests/$(*F).o
	clang -g tests/$(*F).o -o tests/$(*F).exe $(LFLAGS)

# Generated by "ocamldep *.ml *.mli" after building scanner.ml and parser.ml
ast.cmo :
ast.cmx :
codegen.cmo : ast.cmo
codegen.cmx : ast.cmx
tiler.cmo : semant.cmo scanner.cmo parser.cmi codegen.cmo ast.cmo
tiler.cmx : semant.cmx scanner.cmx parser.cmx codegen.cmx ast.cmx
parser.cmo : ast.cmo parser.cmi
parser.cmx : ast.cmx parser.cmi
scanner.cmo : parser.cmi
scanner.cmx : parser.cmx
semant.cmo : ast.cmo
semant.cmx : ast.cmx
parser.cmi : ast.cmo
