# The Jlt linter in the build (#1060): `lint` lints the whole scope in one pass
# once everything is built, into build/jlt-lint/report.txt; lint-<part> lints
# one part of it (a layer, or the fixtures).  Which line belongs to which part, jlt_lint.py
# says (part_of); the build only names the parts.
option(DEDEKIND_JLT_LINT "Lint the tree with tools/jlt-lint once it is built" ON)
if(NOT DEDEKIND_JLT_LINT)
    return()
endif()

# The LLVM that compiles the tree: its CMake packages, for the linter's binary,
# which runs every rule (-DClang_DIR, -DLLVM_DIR name them instead).
file(REAL_PATH "${CMAKE_CXX_COMPILER}" _jlt_compiler)
cmake_path(GET _jlt_compiler PARENT_PATH _jlt_bin)
cmake_path(GET _jlt_bin PARENT_PATH _jlt_llvm)
find_path(Clang_DIR ClangConfig.cmake HINTS ${_jlt_llvm}/lib/cmake/clang NO_DEFAULT_PATH)
find_path(LLVM_DIR LLVMConfig.cmake HINTS ${_jlt_llvm}/lib/cmake/llvm NO_DEFAULT_PATH)

# Not found: `lint` says so and fails, rather than pass having linted nothing.
if(NOT Clang_DIR OR NOT LLVM_DIR)
    set(_jlt_missing "jlt-lint: no Clang/LLVM CMake packages next to ${_jlt_compiler} (Clang_DIR=${Clang_DIR}, LLVM_DIR=${LLVM_DIR}); name them, or configure with -DDEDEKIND_JLT_LINT=OFF")
    message(WARNING "${_jlt_missing}")
    add_custom_target(lint
        COMMAND ${CMAKE_COMMAND} -E echo "${_jlt_missing}"
        COMMAND ${CMAKE_COMMAND} -E false
        VERBATIM)
    return()
endif()

# The linter's binary (tool/), a project of its own on LLVM's flags, built by
# the same compiler as the tree.
include(ExternalProject)
set(_jlt_tool ${CMAKE_BINARY_DIR}/jlt-lint/jlt-lint)
set(_jlt_tool_args
    -DCMAKE_BUILD_TYPE=Release
    -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
    -DClang_DIR=${Clang_DIR}
    -DLLVM_DIR=${LLVM_DIR})
if(CMAKE_C_COMPILER)
    list(APPEND _jlt_tool_args -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER})
endif()
ExternalProject_Add(jlt-lint-tool
    SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/tool
    BINARY_DIR ${CMAKE_BINARY_DIR}/jlt-lint
    CMAKE_ARGS ${_jlt_tool_args}
    INSTALL_COMMAND ""
    BUILD_ALWAYS ON
    BUILD_BYPRODUCTS ${_jlt_tool}
    EXCLUDE_FROM_ALL ON)

if(NOT Python_EXECUTABLE)
    find_package(Python COMPONENTS Interpreter REQUIRED)
endif()

# One part at a time (each parses NCPU files at once), beside the compiler.
set_property(GLOBAL APPEND PROPERTY JOB_POOLS jlt_lint=1)
set(_jlt_parts ${CMAKE_BINARY_DIR}/jlt-lint/parts)

# lint-<PART>, after the targets whose module maps its files are parsed with.
function(add_jlt_lint_part PART)
    add_custom_target(lint-${PART}
        COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/jlt_lint.py
                ${CMAKE_BINARY_DIR} ${_jlt_tool}
                --part ${PART} --out ${_jlt_parts}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        JOB_POOL jlt_lint
        VERBATIM)
    add_dependencies(lint-${PART} jlt-lint-tool ${ARGN})
    set_property(GLOBAL APPEND PROPERTY DEDEKIND_LINT_PARTS lint-${PART})
endfunction()

# A layer's files: its library, and its tests where it has them.  lint-<PART>
# lints one part, for a look at one layer.
set(_jlt_all_built)
get_property(_jlt_layers GLOBAL PROPERTY DEDEKIND_LAYERS)
foreach(layer IN LISTS _jlt_layers)
    set(_jlt_built dedekind_${layer})
    if(TARGET test_${layer})
        list(APPEND _jlt_built test_${layer})
    endif()
    add_jlt_lint_part(${layer} ${_jlt_built})
    list(APPEND _jlt_all_built ${_jlt_built})
endforeach()
# The fixtures are standalone: they need only the linter.
add_jlt_lint_part(fixtures)

# The whole scope in one pass, once everything is built: one pool of NCPU
# workers over every file, so no part waits for another part's last files.
# (Part by part, in sequence, the lint took four times as long: each part's
# pool idled on its tail, and a small layer used few of the cores.)
# The paper's generated tables are compared on Linux, the platform CI decides
# on; on macOS they are printed only, so that a difference between the two
# standard libraries shows in the log without failing the build (one unit has
# a definition more under libc++).
if(APPLE)
  set(_jlt_summary_check)
  set(_jlt_table_check)
else()
  set(_jlt_summary_check --check ${CMAKE_SOURCE_DIR}/docs/paper/jlt/generated/summary-table.tex
      --check-facts ${CMAKE_SOURCE_DIR}/docs/paper/jlt/generated/summary-facts.tex
      --check-counts ${CMAKE_SOURCE_DIR}/tools/jlt-lint/levels.counts)
  set(_jlt_table_check --check ${CMAKE_SOURCE_DIR}/docs/paper/jlt/generated/lint-table.tex)
endif()
add_custom_target(lint
    # The report is this run's or none: an earlier pass's report goes first.
    COMMAND ${CMAKE_COMMAND} -E rm -f ${CMAKE_BINARY_DIR}/jlt-lint/report.txt
    # A second control beside Catch2: the ranges library of libc++, the standard
    # library that ships with the compiler, staged where the scope can name
    # its headers.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/stage_stdlib.py
            ${CMAKE_CXX_COMPILER} ${CMAKE_BINARY_DIR}/_deps/stdlib-ranges
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/jlt_lint.py
            ${CMAKE_BINARY_DIR} ${_jlt_tool} --out ${_jlt_parts}
    COMMAND ${CMAKE_COMMAND} -E copy ${_jlt_parts}/all.txt ${CMAKE_BINARY_DIR}/jlt-lint/report.txt
    # The paper's table of the listings' levels is the linter's: regenerated
    # and compared, so it cannot drift from the code.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/levels.py
            ${CMAKE_BINARY_DIR} ${_jlt_tool} paper_listings
            src/test/cpp/modules/dedekind/category/jlt_listings_test.cpp
            --check ${CMAKE_SOURCE_DIR}/docs/paper/jlt/generated/levels-table.tex
    # The level of every definition of the fixtures for local state and for
    # the conditions of the derived forms, definition by definition.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/levels.py
            ${CMAKE_BINARY_DIR} ${_jlt_tool} jlt_listing
            tools/jlt-lint/fixtures/local-state.cpp
            --expect ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/local-state.levels
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/levels.py
            ${CMAKE_BINARY_DIR} ${_jlt_tool} jlt_listing
            tools/jlt-lint/fixtures/derived-conditions.cpp
            --expect ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/derived-conditions.levels
    # The fixture's outcome for every template, not only their count.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/outcomes.py
            ${_jlt_tool} ${CMAKE_SOURCE_DIR}/tools/jlt-lint/fixtures/rule2-by-type.cpp
    # Both generated tables are printed first, so that one run's log has
    # what both checks below would ask for.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/summary.py
            --levels ${_jlt_parts}/all-levels.json
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/table.py
            --report ${CMAKE_BINARY_DIR}/jlt-lint/report.txt
    # The paper's summary of the levels over the listings, the library and
    # Catch2: compared, so that it cannot drift from the code.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/summary.py
            --levels ${_jlt_parts}/all-levels.json ${_jlt_summary_check}
    # The paper's table of the checks on the library is the report's: compared,
    # so that it cannot drift from the code.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/table.py
            --report ${CMAKE_BINARY_DIR}/jlt-lint/report.txt ${_jlt_table_check}
    # The shallow scan's premise, tested on the fixtures: both scans agree.
    COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scan.py ${_jlt_tool}
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    # In Ninja's console pool, which also runs one job at a time: its output
    # streams as it comes, so the driver's progress shows which files finished
    # even in a job that is cancelled or times out (a pool of its own would
    # buffer it to the end).
    USES_TERMINAL
    VERBATIM)
add_dependencies(lint jlt-lint-tool ${_jlt_all_built})
