#
# makefile for generating a config file for the installed Clang version
#

# PUMA root
PUMA    ?= ../../Puma

# default target
TARGET  ?= linux-release

# include the PUMA configuration variables
# => set _TARGET, RELEASE, CFLAGS, CXXFLAGS, CPPFLAGS, etc.
include $(PUMA)/vars.mk

PLATFORM := $(shell echo $(_TARGET) | cut -d _ -f1)

# ******************************
# *       S E T T I N G S      *
# ******************************

# check whether llvm-config is available
ifeq ($(shell which $(LLVMCONF)),)
  $(error LLVMCONF ($(LLVMCONF)) is not found)
endif

LLVM_VERSION := $(shell $(LLVMCONF) --version)

LLVM_LIBDIR  := $(shell $(LLVMCONF) --libdir)
ifeq ($(PLATFORM),win) # handle '\' in path name
  LLVM_LIBDIR := $(subst \,/,$(LLVM_LIBDIR))
endif
LLVM_LIBS :=  $(LLVM_LIBDIR)/libclang*.a
# These functions need to be wrapped:
#   Parameters are omitted to be more version independent
LLVM_KEYS := _ZN5clang4Sema19canSkipFunctionBody \
             _ZN5clang4Sema21ProcessStmtAttributes

ifeq ($(PLATFORM),macos) # on macOS the symbols have an additional '_'
  LLVM_KEYS := $(patsubst %, _%, $(LLVM_KEYS))
endif

# command to generate LLVM_SYMBOLS (a recursive variable!)
LLVM_SYMBOLS_GEN = $(foreach LLVM_LIB, $(LLVM_LIBS), $(foreach LLVM_KEY, $(LLVM_KEYS), $(filter _%, $(shell nm --defined-only $(LLVM_LIB) | grep "T $(LLVM_KEY)"))))

ifeq ($(PLATFORM),macos) # on macOS the symbols have an additional '_'
  LLVM_SYMBOLS_GEN := $(patsubst _%, %, $(LLVM_SYMBOLS_GEN))
endif

# ******************************
# *       R U L E S            *
# ******************************

clang: clang-$(LLVM_VERSION).mk

# find the exact symbols using the keys in the clang libraries
clang-$(LLVM_VERSION).mk:
	@echo Generating config file for Clang $(LLVM_VERSION)
	@echo LLVM_SYMBOLS := $(LLVM_SYMBOLS_GEN) > $@
