# tree-sitter build infrastructure for the astparser module
#
# Build flow:
#   grammar.js → tree-sitter generate → parser.c (developer regeneration)
#   parser.c + scanner.c + tree-sitter C runtime → static libraries
#   astparser module links against these static libraries
#
# Runtime dependency: system tree-sitter when available; otherwise the
# tree-sitter runtime is fetched and linked statically for developer builds.

# tree-sitter CLI is only needed when changing grammar.js (developer workflow):
#   cd grammars/tree-sitter-qore && tree-sitter generate grammar.js
# The generated src/ files are committed to source control.

find_package(PkgConfig QUIET)
set(QORE_TREE_SITTER_VERSION "0.26.13")
if(PkgConfig_FOUND)
    pkg_check_modules(TREE_SITTER QUIET IMPORTED_TARGET "tree-sitter>=${QORE_TREE_SITTER_VERSION}")
endif()

if(TREE_SITTER_FOUND)
    message(STATUS "Found tree-sitter: ${TREE_SITTER_VERSION}")
    add_library(tree-sitter-lib INTERFACE)
    target_link_libraries(tree-sitter-lib INTERFACE PkgConfig::TREE_SITTER)
    set(TREE_SITTER_INCLUDE_DIRS_FOR_BUILD ${TREE_SITTER_INCLUDE_DIRS})
else()
    if(QORE_REQUIRE_SYSTEM_DEPENDENCIES)
        message(FATAL_ERROR "System tree-sitter >= ${QORE_TREE_SITTER_VERSION} is required; dependency downloads are disabled")
    endif()
    include(FetchContent)

    # Keep the runtime and grammar generation CLI on the same maintenance release.
    FetchContent_Declare(
        tree-sitter
        GIT_REPOSITORY https://github.com/tree-sitter/tree-sitter.git
        GIT_TAG v${QORE_TREE_SITTER_VERSION}
        GIT_SHALLOW TRUE
    )
    FetchContent_GetProperties(tree-sitter)
    if(NOT tree-sitter_POPULATED)
        # FetchContent_MakeAvailable() would call add_subdirectory() on the
        # tree-sitter source, but we only need the populated source to compile
        # lib/src/lib.c into our own static target. Setting CMP0169 to OLD is
        # the cmake-sanctioned way to keep calling FetchContent_Populate() in
        # this "sources only" case (cmake 3.30+).
        if(POLICY CMP0169)
            cmake_policy(PUSH)
            cmake_policy(SET CMP0169 OLD)
        endif()
        FetchContent_Populate(tree-sitter)
        if(POLICY CMP0169)
            cmake_policy(POP)
        endif()
    endif()

    # Build tree-sitter C runtime as a static library
    add_library(tree-sitter-lib STATIC
        ${tree-sitter_SOURCE_DIR}/lib/src/lib.c
    )
    set_property(TARGET tree-sitter-lib PROPERTY POSITION_INDEPENDENT_CODE ON)
    target_include_directories(tree-sitter-lib PUBLIC
        ${tree-sitter_SOURCE_DIR}/lib/include
        ${tree-sitter_SOURCE_DIR}/lib/src
    )
    set(TREE_SITTER_INCLUDE_DIRS_FOR_BUILD
        ${tree-sitter_SOURCE_DIR}/lib/include
        ${tree-sitter_SOURCE_DIR}/lib/src
    )
endif()

# Use pre-generated parser files from source tree.
# Developers: run "tree-sitter generate grammar.js" manually when grammar.js changes,
# then commit the updated src/ files.
set(TS_QORE_GRAMMAR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/grammars/tree-sitter-qore)
set(TS_QORE_SRC_DIR ${TS_QORE_GRAMMAR_DIR}/src)

# Build Qore grammar parser as a static library from committed generated sources
add_library(tree-sitter-qore-grammar STATIC
    ${TS_QORE_SRC_DIR}/parser.c
    ${TS_QORE_SRC_DIR}/scanner.c
)
set_property(TARGET tree-sitter-qore-grammar PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(tree-sitter-qore-grammar PUBLIC
    ${TREE_SITTER_INCLUDE_DIRS_FOR_BUILD}
    ${TS_QORE_SRC_DIR}
)

# Standalone grammar checks also permit memory testing without the Qore runtime.
add_executable(astparser-brace-regex-test EXCLUDE_FROM_ALL test/brace-regex.c)
target_link_libraries(astparser-brace-regex-test PRIVATE tree-sitter-qore-grammar tree-sitter-lib)
add_executable(astparser-keyword-identifier-test EXCLUDE_FROM_ALL test/keyword-identifier.c)
target_link_libraries(astparser-keyword-identifier-test PRIVATE tree-sitter-qore-grammar tree-sitter-lib)
add_executable(astparser-parse-directives-test EXCLUDE_FROM_ALL test/parse-directives.c)
target_link_libraries(astparser-parse-directives-test PRIVATE tree-sitter-qore-grammar tree-sitter-lib)

# start of hacks to simulate installed QoreConfig.cmake
# which cannot be available yet - the QORE_LIBRARY is missing
# as find_library does not work yet
if (NOT QORE_MODULES_DIR)
    set(QORE_MODULES_DIR ${MODULE_DIR})
endif (NOT QORE_MODULES_DIR)

if (NOT QORE_LIBRARY)
    set(QORE_LIBRARY libqore)
endif (NOT QORE_LIBRARY)

set(QORE_API_VERSION ${MODULE_API_MAJOR}.${MODULE_API_MINOR})

include(${CMAKE_SOURCE_DIR}/cmake/QoreMacros.cmake)
### end of hacks

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
include_directories(BEFORE ${CMAKE_BINARY_DIR}/include)
include_directories(BEFORE ${CMAKE_SOURCE_DIR}/include)

# Source files organized by type for proper dependency tracking.
# Direct C++ sources (no generator)
set(ASTPARSER_DIRECT_CPP_SRC
    src/astparser-module.cpp
    src/AstParser.cpp
    src/AstParserHolder.cpp
    src/AstTreeHolder.cpp
    src/AstTreePrinter.cpp
    src/CSTSearcher.cpp
    src/CSTWalk.cpp
    src/queries/GetNodesInfoQuery.cpp
)
# NOTE: The old Bison parser and AST-node searcher implementation has been
# removed.  The module parses and searches the tree-sitter CST via CSTSearcher.

# QPP sources (.qpp → .cpp via qore_wrap_qpp_value)
set(ASTPARSER_QPP_SRC
    src/QC_AstParser.qpp
    src/QC_AstTree.qpp
    src/QC_AstTreeSearcher.qpp
    src/ql_ast.qpp
)

# Combined source list for non-SCU builds (no bison/flex sources)
set(ASTPARSER_CPP_SRC
    ${ASTPARSER_DIRECT_CPP_SRC}
)

set(QORE_DOX_ASTPARSER_TMPL_SRC
    docs/mainpage.dox.tmpl
)

qore_wrap_qpp_value(ASTPARSER_QPP_SOURCES DOXLIST _dox_src METALIST ASTPARSER_QPP_META_SRC ${ASTPARSER_QPP_SRC})
add_custom_target(ASTPARSER_QPP_GENERATED_FILES DEPENDS qpp ${ASTPARSER_QPP_SOURCES})

# prepare astparser module target
set(astparser_module_name "astparser")

if (SINGLE_COMPILATION_UNIT)
    # Generate SCU file in build directory with absolute paths and explicit
    # file-level dependencies for each source category, so cmake properly
    # rebuilds when any source (.cpp, .qpp) changes.
    set(ASTPARSER_SCU_PATH ${CMAKE_CURRENT_BINARY_DIR}/astparser_scu.cpp)

    # Build the SCU content programmatically from the source lists
    set(_scu_content "// Auto-generated astparser single-compilation-unit file\n")
    set(_scu_content "${_scu_content}// Generated by cmake — do not edit manually\n\n")

    # Direct C++ sources (relative paths → absolute)
    foreach(_f ${ASTPARSER_DIRECT_CPP_SRC})
        get_filename_component(_abs ${_f} ABSOLUTE)
        set(_scu_content "${_scu_content}#include \"${_abs}\"\n")
    endforeach()
    set(_scu_content "${_scu_content}\n")

    # QPP-generated sources (already absolute paths in build dir)
    foreach(_f ${ASTPARSER_QPP_SOURCES})
        set(_scu_content "${_scu_content}#include \"${_f}\"\n")
    endforeach()

    file(WRITE ${ASTPARSER_SCU_PATH} "${_scu_content}")

    add_library(${astparser_module_name} MODULE ${ASTPARSER_SCU_PATH})

    # Declare file-level dependencies so cmake rebuilds the SCU object when
    # any generated file changes (qpp → .cpp)
    set(_scu_deps ${ASTPARSER_QPP_SOURCES})
    # Also depend on direct source files
    foreach(_f ${ASTPARSER_DIRECT_CPP_SRC})
        get_filename_component(_abs ${_f} ABSOLUTE)
        list(APPEND _scu_deps ${_abs})
    endforeach()
    set_source_files_properties(${ASTPARSER_SCU_PATH} PROPERTIES
        OBJECT_DEPENDS "${_scu_deps}"
    )
    # The grammar library is detected as an SCU dependency via
    # target_link_libraries below.  This ensures cmake relinks when
    # the grammar changes.
    set_target_properties(${astparser_module_name} PROPERTIES
        LINK_DEPENDS "$<TARGET_FILE:tree-sitter-qore-grammar>"
    )
else (SINGLE_COMPILATION_UNIT)
    add_library(${astparser_module_name} MODULE ${ASTPARSER_CPP_SRC} ${ASTPARSER_QPP_SOURCES})
endif (SINGLE_COMPILATION_UNIT)

# Link against tree-sitter libraries and add include paths
target_include_directories(${astparser_module_name} PRIVATE
    ${TREE_SITTER_INCLUDE_DIRS_FOR_BUILD}
    ${TS_QORE_SRC_DIR}
)
target_link_libraries(${astparser_module_name} tree-sitter-lib tree-sitter-qore-grammar)

add_dependencies(${astparser_module_name} libqore ASTPARSER_QPP_GENERATED_FILES)
set(MODULE_DOX_INPUT ${CMAKE_BINARY_DIR}/modules/astparser/mainpage.dox ${_dox_src})
qore_binary_module_qore(${astparser_module_name} "${VERSION}" "/${VERSION}")
qore_install_qpp_metadata(${astparser_module_name} ${ASTPARSER_QPP_META_SRC})

# Install grammar artifacts so module-treesitter can reuse them
install(FILES
    ${TS_QORE_SRC_DIR}/parser.c
    ${TS_QORE_SRC_DIR}/scanner.c
    ${TS_QORE_SRC_DIR}/grammar.json
    ${TS_QORE_SRC_DIR}/node-types.json
    DESTINATION ${CMAKE_INSTALL_DATADIR}/qore/treesitter/tree-sitter-qore/src
    COMPONENT ${QORE_BINARY_MODULE_INSTALL_COMPONENT}
)
install(FILES
    ${TS_QORE_SRC_DIR}/tree_sitter/parser.h
    DESTINATION ${CMAKE_INSTALL_DATADIR}/qore/treesitter/tree-sitter-qore/src/tree_sitter
    COMPONENT ${QORE_BINARY_MODULE_INSTALL_COMPONENT}
)
install(FILES
    ${TS_QORE_GRAMMAR_DIR}/grammar.js
    DESTINATION ${CMAKE_INSTALL_DATADIR}/qore/treesitter/tree-sitter-qore
    COMPONENT ${QORE_BINARY_MODULE_INSTALL_COMPONENT}
)

if (DOXYGEN_FOUND)
    qore_wrap_dox(QORE_DOX_ASTPARSER_SRC ${QORE_DOX_ASTPARSER_TMPL_SRC})
    add_custom_target(QORE_ASTPARSER_MOD_DOX_FILES DEPENDS ${QORE_DOX_ASTPARSER_SRC})
    add_dependencies(docs-astparser QORE_ASTPARSER_MOD_DOX_FILES)
endif()
