if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR WIN32)
  message(FATAL_ERROR "CSV fuzzers require native Unix Clang with libFuzzer")
endif()
if(NOT CSV_ENABLE_THREADS)
  message(FATAL_ERROR "CSV fuzzers require CSV_ENABLE_THREADS=ON; runtime synchronous mode is also tested")
endif()
set(CSV_FUZZ_SANITIZER "address,undefined" CACHE STRING "Fuzzer sanitizers (or thread for deterministic replay)")
get_target_property(_sources csv SOURCES)
get_target_property(_source_dir csv SOURCE_DIR)
set(_absolute_sources)
foreach(_source IN LISTS _sources)
  if(_source MATCHES "\\.cpp$")
    list(APPEND _absolute_sources "${_source_dir}/${_source}")
  endif()
endforeach()
add_library(csv_fuzz_parser STATIC ${_absolute_sources})
target_include_directories(csv_fuzz_parser PUBLIC ${CSV_INCLUDE_DIR} ${CSV_TEST_DIR})
target_compile_features(csv_fuzz_parser PUBLIC cxx_std_20)
# Mirror the shipped library's configuration (SIMD, threads, float parsing,
# exception mode) instead of restating it, so new csv settings reach the fuzzers.
foreach(_property COMPILE_DEFINITIONS COMPILE_OPTIONS
                  INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_OPTIONS)
  get_target_property(_values csv ${_property})
  if(_values)
    set_property(TARGET csv_fuzz_parser APPEND PROPERTY ${_property} ${_values})
  endif()
endforeach()
find_package(Threads REQUIRED)
target_link_libraries(csv_fuzz_parser PUBLIC Threads::Threads)
# Compile parser implementation AND template/header code with coverage and sanitizers.
target_compile_options(csv_fuzz_parser PUBLIC -g -O1 -fno-omit-frame-pointer
  -fsanitize=${CSV_FUZZ_SANITIZER})
if(NOT CSV_FUZZ_SANITIZER STREQUAL "thread")
  target_compile_options(csv_fuzz_parser PUBLIC -fsanitize=fuzzer-no-link)
endif()
foreach(_kind stream differential boundary)
  add_executable(csv_fuzz_${_kind} ${_kind}.cpp)
  target_link_libraries(csv_fuzz_${_kind} PRIVATE csv_fuzz_parser)
  if(CSV_FUZZ_SANITIZER STREQUAL "thread")
    target_sources(csv_fuzz_${_kind} PRIVATE replay.cpp)
    target_link_options(csv_fuzz_${_kind} PRIVATE -fsanitize=thread)
  else()
    target_link_options(csv_fuzz_${_kind} PRIVATE -fsanitize=fuzzer,${CSV_FUZZ_SANITIZER})
  endif()
endforeach()
