cmake_minimum_required(VERSION 3.20)

project(compiler LANGUAGES C CXX)

# 统一 C++ 标准（按实验环境可调整）
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# 可执行文件输出目录：统一放到 <build>/bin 下（避免落在 build/src/ 等子目录）
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
foreach(cfg IN ITEMS Debug Release RelWithDebInfo MinSizeRel)
  string(TOUPPER "${cfg}" cfg_upper)
  set("CMAKE_RUNTIME_OUTPUT_DIRECTORY_${cfg_upper}" "${CMAKE_BINARY_DIR}/bin")
endforeach()

# ANTLR 生成代码目录约定（不进仓库，生成在构建目录）
set(ANTLR4_GENERATED_DIR "${CMAKE_BINARY_DIR}/generated/antlr4")

# 统一的编译/包含目录选项（子模块复用）
add_library(build_options INTERFACE)
target_compile_features(build_options INTERFACE cxx_std_17)
target_include_directories(build_options INTERFACE
  "${PROJECT_SOURCE_DIR}/include"
  "${PROJECT_SOURCE_DIR}/src"
  "${ANTLR4_GENERATED_DIR}"
  # 兼容未使用 -Xexact-output-dir 时 ANTLR 可能生成到的子目录结构
  "${ANTLR4_GENERATED_DIR}/src/antlr4"
)

option(COMPILER_ENABLE_WARNINGS "Enable common compiler warnings" ON)
if(COMPILER_ENABLE_WARNINGS)
  if(MSVC)
    target_compile_options(build_options INTERFACE /W4)
  else()
    target_compile_options(build_options INTERFACE -Wall -Wextra -Wpedantic)
  endif()
endif()

option(COMPILER_PARSE_ONLY "Build only the frontend parser pipeline" OFF)

# 使用仓库内 third_party 提供的 ANTLR4 C++ runtime（较新版本）
# third_party 目录结构以仓库为准：runtime 源码位于 third_party/antlr4-runtime-4.13.2/runtime/src
set(ANTLR4_RUNTIME_SRC_DIR "${PROJECT_SOURCE_DIR}/third_party/antlr4-runtime-4.13.2/runtime/src")

add_library(antlr4_runtime STATIC)
target_compile_features(antlr4_runtime PUBLIC cxx_std_17)

target_include_directories(antlr4_runtime PUBLIC
  "${ANTLR4_RUNTIME_SRC_DIR}"
  "${ANTLR4_RUNTIME_SRC_DIR}/atn"
  "${ANTLR4_RUNTIME_SRC_DIR}/dfa"
  "${ANTLR4_RUNTIME_SRC_DIR}/internal"
  "${ANTLR4_RUNTIME_SRC_DIR}/misc"
  "${ANTLR4_RUNTIME_SRC_DIR}/support"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree/pattern"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree/xpath"
)

file(GLOB_RECURSE ANTLR4_RUNTIME_SOURCES CONFIGURE_DEPENDS
  "${ANTLR4_RUNTIME_SRC_DIR}/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/atn/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/dfa/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/internal/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/misc/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/support/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree/pattern/*.cpp"
  "${ANTLR4_RUNTIME_SRC_DIR}/tree/xpath/*.cpp"
)
target_sources(antlr4_runtime PRIVATE ${ANTLR4_RUNTIME_SOURCES})

find_package(Threads REQUIRED)
target_link_libraries(antlr4_runtime PUBLIC Threads::Threads)

set(ANTLR4_RUNTIME_TARGET antlr4_runtime)

add_subdirectory(src)
