# Copyright 2017, Henrik Theiling, licensed under GPL3, see gpl-3.0.txt

CC=gcc
CFLAGS=-std=c11 -O3 -g3 -Wall -Wextra -Wredundant-decls -fno-inline -Wno-error -Wno-unused-parameter

OBJ.regexp = regexp.o test.o

OBJ.regexp2 = regexp2.o test.o

OBJ.regexp3 = regexp3.o test.o

OBJ.regexp3b = regexp3b.o test.o

all: regexp regexp2 regexp3 regexp3b

.PHONY: all

.PHONY: test
test: test1 test2 test3 test3b count-tail-call

.PHONY: test1
test1: regexp
	./$<

.PHONY: test2
test2: regexp2
	./$<

.PHONY: test3
test3: regexp3
	./$<

.PHONY: test3b
test3b: regexp3b
	./$<

regexp.o:  regexp.c regexp.h regexp_internal.h

regexp2.o: regexp2.c regexp.h regexp2_internal.h

regexp3.o: regexp3.c regexp.h regexp3_internal.h

regexp3b.o: regexp3b.c regexp.h regexp3_internal.h

test.o: test.c regexp.h test/python.inc

regexp3b.c: regexp3.c
	unifdef -x2 -B -DRE_NSTAT $< -o $@

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

regexp: $(OBJ.regexp)
	$(CC) $(CFLAGS) $(OBJ.$@) -o $@

regexp2: $(OBJ.regexp2)
	$(CC) $(CFLAGS) $(OBJ.$@) -o $@

regexp3: $(OBJ.regexp3)
	$(CC) $(CFLAGS) $(OBJ.$@) -o $@

regexp3b: $(OBJ.regexp3b)
	$(CC) $(CFLAGS) $(OBJ.$@) -o $@

%.s: %.c Makefile
	$(CC) $(CFLAGS) $< -S -o $@

.PHONY: clean
clean:
	rm -f a.out regexp regexp2 regexp3 regexp3b *.o *.s

.PHONY: sweep
sweep:
	rm -f *~
	rm -f core

.PHONY: count
count: regexp3b.c
	grep ';' regexp.c   | grep -v assert | grep -v TRACE | wc -l
	grep ';' regexp2.c  | grep -v assert | grep -v TRACE | wc -l
	grep ';' regexp3b.c | grep -v assert | grep -v TRACE | wc -l

GREP_REC = grep '\([*]\|re_\)' | grep -v re_aux_

.PHONY: count-tail-call
count-tail-call: regexp2.s
	grep '^\s*jmp[^L]*$$' regexp2.s  | $(GREP_REC) | wc -l ||:
	grep '^\s*call[^L]*$$' regexp2.s | $(GREP_REC) | wc -l ||:
	grep '^\s*call[^L]*$$' regexp2.s | (! $(GREP_REC))
