diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index 82807af94..d136faf6b 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux.yaml @@ -7,7 +7,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks", "headers"] + format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks", "headers"] compiler: [llvm, gcc] compiler-version: [11, 12, 13, 14, 16, 17, 18] cxx: [20, 23] diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index 8b4af4ad5..a9594f2c9 100644 --- a/.github/workflows/windows.yaml +++ b/.github/workflows/windows.yaml @@ -7,7 +7,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"] + format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"] name: "windows-msvc (${{ matrix.format }})" concurrency: group: "windows-${{ github.ref }}-${{ github.job }}-${{ matrix.format }}" @@ -76,7 +76,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML"] + format: ["JSON", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML"] name: "windows-msvc-shared (${{ matrix.format }})" runs-on: windows-latest steps: diff --git a/CMakeLists.txt b/CMakeLists.txt index aae285585..0f60d9bcd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,10 +1,19 @@ -cmake_minimum_required(VERSION 3.23) +cmake_minimum_required(VERSION 3.20) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + set(_REFLECTCPP_IS_TOP_LEVEL ON) +else () + set(_REFLECTCPP_IS_TOP_LEVEL OFF) +endif () + +if (_REFLECTCPP_IS_TOP_LEVEL AND NOT DEFINED CMAKE_EXPORT_COMPILE_COMMANDS) + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +endif () option(REFLECTCPP_BUILD_SHARED "Build shared library" ${BUILD_SHARED_LIBS}) +option(REFLECTCPP_HIDDEN_VISIBILITY "Compile static reflectcpp with hidden symbol visibility" OFF) option(REFLECTCPP_STRICT_WARNINGS "Enable strict compiler warnings" OFF) -option(REFLECTCPP_INSTALL "Install reflect cpp" OFF) +option(REFLECTCPP_INSTALL "Install reflect cpp" ${_REFLECTCPP_IS_TOP_LEVEL}) option(REFLECTCPP_ALL_FORMATS "Enable all supported formats" OFF) option(REFLECTCPP_JSON "Enable JSON support" ON) # enabled by default @@ -16,6 +25,7 @@ option(REFLECTCPP_CEREAL "Enable Cereal support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_CSV "Enable CSV support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_MSGPACK "Enable msgpack support" ${REFLECTCPP_ALL_FORMATS}) +option(REFLECTCPP_NLOHMANN "Enable nlohmann/json support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_PARQUET "Enable parquet support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_XML "Enable XML support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_TOML "Enable TOML support" ${REFLECTCPP_ALL_FORMATS}) @@ -29,25 +39,37 @@ option(REFLECTCPP_BUILD_TESTS "Build tests" OFF) option(REFLECTCPP_CHECK_HEADERS "Make sure that all headers are self-contained" OFF) option(REFLECTCPP_USE_BUNDLED_DEPENDENCIES "Use the bundled dependencies" ON) +option(REFLECTCPP_USE_BUNDLED_YYJSON "Use the bundled yyjson dependency" ${REFLECTCPP_USE_BUNDLED_DEPENDENCIES}) +if (NOT DEFINED REFLECTCPP_YYJSON_TARGET) + set(REFLECTCPP_YYJSON_TARGET "" CACHE STRING "Existing CMake target providing external yyjson (requires REFLECTCPP_USE_BUNDLED_YYJSON=OFF)") +endif () + +if (REFLECTCPP_USE_BUNDLED_YYJSON AND NOT "${REFLECTCPP_YYJSON_TARGET}" STREQUAL "") + message(FATAL_ERROR + "REFLECTCPP_YYJSON_TARGET is set to '${REFLECTCPP_YYJSON_TARGET}', but REFLECTCPP_USE_BUNDLED_YYJSON is ON. " + "Set REFLECTCPP_USE_BUNDLED_YYJSON=OFF to link against an external yyjson target.") +endif () option(REFLECTCPP_USE_CPP26_REFLECTION "Use standard C++ reflection (requires C++-26)" OFF) option(REFLECTCPP_USE_STD_EXPECTED "Use std::expected instead of the built-in Result type (requires C++-23)" OFF) -if(REFLECTCPP_USE_CPP26_REFLECTION) - if(NOT DEFINED CMAKE_CXX_STANDARD) - set(CMAKE_CXX_STANDARD 26) - endif() -elseif(REFLECTCPP_USE_STD_EXPECTED) - if(NOT DEFINED CMAKE_CXX_STANDARD) - set(CMAKE_CXX_STANDARD 23) - endif() -else() - if(NOT DEFINED CMAKE_CXX_STANDARD) - set(CMAKE_CXX_STANDARD 20) - endif() -endif() +if (_REFLECTCPP_IS_TOP_LEVEL) + if (REFLECTCPP_USE_CPP26_REFLECTION) + if (NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 26) + endif () + elseif (REFLECTCPP_USE_STD_EXPECTED) + if (NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 23) + endif () + else () + if (NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 20) + endif () + endif () -set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(CMAKE_CXX_STANDARD_REQUIRED ON) +endif () set(REFLECTCPP_USE_VCPKG_DEFAULT OFF) @@ -69,25 +91,29 @@ if(REFLECTCPP_BUILD_BENCHMARKS) endif() if ( - REFLECTCPP_BUILD_TESTS OR - REFLECTCPP_BUILD_BENCHMARKS OR - REFLECTCPP_CHECK_HEADERS OR - (REFLECTCPP_JSON AND NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) OR - REFLECTCPP_AVRO OR - REFLECTCPP_BOOST_SERIALIZATION OR - REFLECTCPP_BSON OR - REFLECTCPP_CAPNPROTO OR - REFLECTCPP_CBOR OR - REFLECTCPP_CEREAL OR - REFLECTCPP_CSV OR - REFLECTCPP_FLEXBUFFERS OR - REFLECTCPP_MSGPACK OR - REFLECTCPP_PARQUET OR - REFLECTCPP_XML OR - REFLECTCPP_TOML OR - REFLECTCPP_UBJSON OR - REFLECTCPP_YAML OR - REFLECTCPP_YAS + _REFLECTCPP_IS_TOP_LEVEL AND ( + REFLECTCPP_BUILD_TESTS OR + REFLECTCPP_BUILD_BENCHMARKS OR + REFLECTCPP_CHECK_HEADERS OR + (REFLECTCPP_JSON AND NOT REFLECTCPP_USE_BUNDLED_YYJSON) OR + NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES OR + REFLECTCPP_AVRO OR + REFLECTCPP_BOOST_SERIALIZATION OR + REFLECTCPP_BSON OR + REFLECTCPP_CAPNPROTO OR + REFLECTCPP_CBOR OR + REFLECTCPP_CEREAL OR + REFLECTCPP_CSV OR + REFLECTCPP_FLEXBUFFERS OR + REFLECTCPP_MSGPACK OR + REFLECTCPP_NLOHMANN OR + REFLECTCPP_PARQUET OR + REFLECTCPP_XML OR + REFLECTCPP_TOML OR + REFLECTCPP_UBJSON OR + REFLECTCPP_YAML OR + REFLECTCPP_YAS + ) ) # enable vcpkg per default if features other than JSON are required set(REFLECTCPP_USE_VCPKG_DEFAULT ON) @@ -101,7 +127,7 @@ endif() option(REFLECTCPP_USE_VCPKG "Use VCPKG to download and build dependencies" ${REFLECTCPP_USE_VCPKG_DEFAULT}) -if (REFLECTCPP_USE_VCPKG) +if (REFLECTCPP_USE_VCPKG AND _REFLECTCPP_IS_TOP_LEVEL) if (REFLECTCPP_AVRO OR REFLECTCPP_CHECK_HEADERS) list(APPEND VCPKG_MANIFEST_FEATURES "avro") endif() @@ -150,7 +176,7 @@ if (REFLECTCPP_USE_VCPKG) list(APPEND VCPKG_MANIFEST_FEATURES "flexbuffers") endif() - if (_REFLECTCPP_NEEDS_JSON_IMPL AND NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) + if (_REFLECTCPP_NEEDS_JSON_IMPL AND NOT REFLECTCPP_USE_BUNDLED_YYJSON) list(APPEND VCPKG_MANIFEST_FEATURES "json") endif() @@ -158,6 +184,10 @@ if (REFLECTCPP_USE_VCPKG) list(APPEND VCPKG_MANIFEST_FEATURES "msgpack") endif() + if (REFLECTCPP_NLOHMANN OR REFLECTCPP_CHECK_HEADERS) + list(APPEND VCPKG_MANIFEST_FEATURES "nlohmann") + endif() + if (REFLECTCPP_PARQUET OR REFLECTCPP_CHECK_HEADERS) list(APPEND VCPKG_MANIFEST_FEATURES "parquet") endif() @@ -182,16 +212,117 @@ if (REFLECTCPP_USE_VCPKG) list(APPEND VCPKG_MANIFEST_FEATURES "yas") endif() - set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") + if (NOT DEFINED CMAKE_TOOLCHAIN_FILE OR "${CMAKE_TOOLCHAIN_FILE}" STREQUAL "") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "") + if (DEFINED VCPKG_ROOT AND NOT "${VCPKG_ROOT}" STREQUAL "") + file(TO_CMAKE_PATH "${VCPKG_ROOT}" _REFLECTCPP_VCPKG_ROOT) + if (EXISTS "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + endif () + endif () + if (NOT _REFLECTCPP_VCPKG_TOOLCHAIN AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") + endif () + if (NOT _REFLECTCPP_VCPKG_TOOLCHAIN AND DEFINED ENV{VCPKG_ROOT} AND NOT "$ENV{VCPKG_ROOT}" STREQUAL "") + file(TO_CMAKE_PATH "$ENV{VCPKG_ROOT}" _REFLECTCPP_VCPKG_ROOT) + if (EXISTS "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + endif () + endif () + if (_REFLECTCPP_VCPKG_TOOLCHAIN) + set(CMAKE_TOOLCHAIN_FILE "${_REFLECTCPP_VCPKG_TOOLCHAIN}" CACHE STRING "Vcpkg toolchain file") + else () + set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" CACHE STRING "Vcpkg toolchain file") + endif () + endif () endif () project(reflectcpp VERSION 0.27.1 LANGUAGES CXX) -find_package(ament_cmake QUIET) +function(_reflectcpp_strip_flags_from_string _input _out_var _token_regex) + set(_val "${_input}") + if (NOT "${_val}" STREQUAL "") + set(_prev "") + while (NOT "${_val}" STREQUAL "${_prev}") + set(_prev "${_val}") + string(REGEX REPLACE "(^|[ \t])(${_token_regex})([ \t]|$)" "\\1\\3" _val "${_val}") + endwhile () + string(STRIP "${_val}" _val) + endif () + set(${_out_var} "${_val}" PARENT_SCOPE) +endfunction() -if (PROJECT_IS_TOP_LEVEL) - set(REFLECTCPP_INSTALL ON) -endif() +function(_reflectcpp_strip_msvc_warning_flags _strip_wx) + set(_rfl_token_regex "[/-]W[0-4]|[/-]Wall|[/-]w") + if (_strip_wx) + string(APPEND _rfl_token_regex "|[/-]WX-?") + endif () + if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND _strip_wx) + string(APPEND _rfl_token_regex "|-W[a-z][a-zA-Z0-9_=+-]*") + endif () + + set(_rfl_configs DEBUG RELEASE RELWITHDEBINFO MINSIZEREL) + if (DEFINED CMAKE_CONFIGURATION_TYPES) + foreach (_rfl_cfg IN LISTS CMAKE_CONFIGURATION_TYPES) + string(TOUPPER "${_rfl_cfg}" _rfl_cfg_upper) + list(APPEND _rfl_configs "${_rfl_cfg_upper}") + endforeach () + endif () + if (DEFINED CMAKE_BUILD_TYPE AND NOT "${CMAKE_BUILD_TYPE}" STREQUAL "") + string(TOUPPER "${CMAKE_BUILD_TYPE}" _rfl_cfg_upper) + list(APPEND _rfl_configs "${_rfl_cfg_upper}") + endif () + list(REMOVE_DUPLICATES _rfl_configs) + + set(_rfl_flag_vars CMAKE_CXX_FLAGS CMAKE_C_FLAGS) + foreach (_rfl_cfg IN LISTS _rfl_configs) + list(APPEND _rfl_flag_vars "CMAKE_CXX_FLAGS_${_rfl_cfg}" "CMAKE_C_FLAGS_${_rfl_cfg}") + endforeach () + foreach (_rfl_var IN LISTS _rfl_flag_vars) + if (DEFINED ${_rfl_var} AND NOT "${${_rfl_var}}" STREQUAL "") + _reflectcpp_strip_flags_from_string("${${_rfl_var}}" _rfl_cleaned "${_rfl_token_regex}") + if (NOT "${_rfl_cleaned}" STREQUAL "${${_rfl_var}}") + set(${_rfl_var} "${_rfl_cleaned}" PARENT_SCOPE) + endif () + endif () + endforeach () + + get_directory_property(_rfl_dir_opts COMPILE_OPTIONS) + if (_rfl_dir_opts) + set(_rfl_filtered_opts "") + foreach (_rfl_opt IN LISTS _rfl_dir_opts) + if ("${_rfl_opt}" MATCHES "^(${_rfl_token_regex})$") + continue() + elseif ("${_rfl_opt}" MATCHES "^\\$<([01]|BUILD_INTERFACE|INSTALL_INTERFACE|.+>):(${_rfl_token_regex})>$") + continue() + elseif ("${_rfl_opt}" MATCHES "^SHELL:(.*)$") + _reflectcpp_strip_flags_from_string("${CMAKE_MATCH_1}" _rfl_shell_cleaned "${_rfl_token_regex}") + if (NOT "${_rfl_shell_cleaned}" STREQUAL "") + list(APPEND _rfl_filtered_opts "SHELL:${_rfl_shell_cleaned}") + endif () + else () + list(APPEND _rfl_filtered_opts "${_rfl_opt}") + endif () + endforeach () + set_directory_properties(PROPERTIES COMPILE_OPTIONS "${_rfl_filtered_opts}") + endif () +endfunction() + +# Strip inherited MSVC warning flags in this directory's local scope before +# add_library(reflectcpp ...) snapshots directory COMPILE_OPTIONS, so +# reflectcpp's own /W0 or /W4 never triggers MSVC D9025 override warnings +# without mutating the parent project's flags or COMPILE_OPTIONS. +if (MSVC) + if (NOT _REFLECTCPP_IS_TOP_LEVEL AND NOT REFLECTCPP_STRICT_WARNINGS) + _reflectcpp_strip_msvc_warning_flags(ON) + elseif (REFLECTCPP_STRICT_WARNINGS) + _reflectcpp_strip_msvc_warning_flags(OFF) + endif () +endif () + +if (_REFLECTCPP_IS_TOP_LEVEL) + find_package(ament_cmake QUIET) +endif () if (REFLECTCPP_BUILD_SHARED) add_library(reflectcpp SHARED) @@ -202,13 +333,79 @@ endif() add_library(reflectcpp::reflectcpp ALIAS reflectcpp) +# Header-only interface target for TUs using pure header reflection (e.g. +# rfl::to_view, rfl::enums) or OBJECT libraries compiled before final linking. +# Propagates core reflection (ctre/enchantum) and JSON (yyjson) headers, +# compile features, and compile definitions without linking compiled objects +# (non-JSON format backend headers such as YAML/XML/TOML are not propagated); +# final binaries/DSOs using out-of-line symbols (e.g. rfl::Generic or format +# readers/writers) must link reflectcpp::reflectcpp. +add_library(reflectcpp_headers INTERFACE) +add_library(reflectcpp::headers ALIAS reflectcpp_headers) +set_target_properties(reflectcpp_headers PROPERTIES EXPORT_NAME headers) +if (REFLECTCPP_USE_CPP26_REFLECTION) + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.30) + target_compile_features(reflectcpp PUBLIC cxx_std_26) + target_compile_features(reflectcpp_headers INTERFACE cxx_std_26) + else () + target_compile_features(reflectcpp PUBLIC cxx_std_23) + target_compile_features(reflectcpp_headers INTERFACE cxx_std_23) + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.25) + set_target_properties(reflectcpp PROPERTIES CXX_STANDARD 26) + endif () + endif () +elseif (REFLECTCPP_USE_STD_EXPECTED) + target_compile_features(reflectcpp PUBLIC cxx_std_23) + target_compile_features(reflectcpp_headers INTERFACE cxx_std_23) +else () + target_compile_features(reflectcpp PUBLIC cxx_std_20) + target_compile_features(reflectcpp_headers INTERFACE cxx_std_20) +endif () +set_target_properties(reflectcpp PROPERTIES CXX_STANDARD_REQUIRED ON) + +if (REFLECTCPP_BUILD_SHARED) + if (REFLECTCPP_HIDDEN_VISIBILITY) + message(WARNING + "REFLECTCPP_HIDDEN_VISIBILITY=ON is ignored when REFLECTCPP_BUILD_SHARED=ON; " + "shared builds require default symbol visibility for exported APIs.") + endif () +else () + if (NOT _REFLECTCPP_IS_TOP_LEVEL AND NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE) + set_target_properties(reflectcpp PROPERTIES POSITION_INDEPENDENT_CODE ON) + endif () + if (REFLECTCPP_HIDDEN_VISIBILITY) + set_target_properties(reflectcpp PROPERTIES + CXX_VISIBILITY_PRESET hidden + C_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + ) + endif () +endif () + +if (NOT _REFLECTCPP_IS_TOP_LEVEL) + set_target_properties(reflectcpp PROPERTIES + CXX_CLANG_TIDY "" + C_CLANG_TIDY "" + CXX_CPPCHECK "" + C_CPPCHECK "" + CXX_INCLUDE_WHAT_YOU_USE "" + C_INCLUDE_WHAT_YOU_USE "" + ) + if (NOT REFLECTCPP_STRICT_WARNINGS) + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.24) + set_target_properties(reflectcpp PROPERTIES COMPILE_WARNING_AS_ERROR OFF) + endif () + if (MSVC) + target_compile_options(reflectcpp PRIVATE /W0) + elseif (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(reflectcpp PRIVATE -Wno-error -w) + endif () + endif () +endif () + if (MSVC) if (REFLECTCPP_STRICT_WARNINGS) - target_compile_options(reflectcpp PRIVATE - $<$: - -Wall - > - ) + target_compile_options(reflectcpp PRIVATE /W4) endif() else() if (REFLECTCPP_STRICT_WARNINGS) @@ -219,51 +416,81 @@ else() ) endif() endif() -target_compile_options(reflectcpp PRIVATE - $<$: - -DNDEBUG - > -) -if(REFLECTCPP_BUILD_SHARED AND REFLECTCPP_USE_BUNDLED_DEPENDENCIES AND _REFLECTCPP_NEEDS_JSON_IMPL) - target_compile_definitions(reflectcpp - PRIVATE - YYJSON_EXPORTS - INTERFACE - YYJSON_IMPORTS - ) -endif() +if (REFLECTCPP_USE_BUNDLED_YYJSON AND _REFLECTCPP_NEEDS_JSON_IMPL) + if (REFLECTCPP_BUILD_SHARED) + target_compile_definitions(reflectcpp + PRIVATE + YYJSON_EXPORTS + INTERFACE + YYJSON_IMPORTS + ) + target_compile_definitions(reflectcpp_headers INTERFACE YYJSON_IMPORTS) + elseif (NOT WIN32) + if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_definitions(reflectcpp PUBLIC "yyjson_api=__attribute__((visibility(\"hidden\")))") + target_compile_definitions(reflectcpp_headers INTERFACE "yyjson_api=__attribute__((visibility(\"hidden\")))") + else () + target_compile_definitions(reflectcpp PUBLIC "yyjson_api=") + target_compile_definitions(reflectcpp_headers INTERFACE "yyjson_api=") + endif () + endif () +endif () if(REFLECTCPP_BUILD_SHARED) target_compile_definitions(reflectcpp PUBLIC RFL_BUILD_SHARED) + target_compile_definitions(reflectcpp_headers INTERFACE RFL_BUILD_SHARED) endif() if(REFLECTCPP_USE_CPP26_REFLECTION) target_compile_definitions(reflectcpp PUBLIC REFLECTCPP_USE_CPP26_REFLECTION) + target_compile_definitions(reflectcpp_headers INTERFACE REFLECTCPP_USE_CPP26_REFLECTION) endif() if(REFLECTCPP_USE_STD_EXPECTED) target_compile_definitions(reflectcpp PUBLIC REFLECTCPP_USE_STD_EXPECTED) + target_compile_definitions(reflectcpp_headers INTERFACE REFLECTCPP_USE_STD_EXPECTED) endif() set(REFLECT_CPP_SOURCES src/reflectcpp.cpp ) +if (_REFLECTCPP_IS_TOP_LEVEL OR REFLECTCPP_STRICT_WARNINGS) + set(_REFLECTCPP_INCLUDE_SYSTEM "") +else () + set(_REFLECTCPP_INCLUDE_SYSTEM SYSTEM) +endif () + target_include_directories( - reflectcpp PUBLIC + reflectcpp PRIVATE + $) +target_include_directories( + reflectcpp ${_REFLECTCPP_INCLUDE_SYSTEM} INTERFACE + $ + $) +target_include_directories( + reflectcpp_headers ${_REFLECTCPP_INCLUDE_SYSTEM} INTERFACE $ $) if (REFLECTCPP_USE_BUNDLED_DEPENDENCIES) - target_include_directories( - reflectcpp PUBLIC - $) + if (REFLECTCPP_USE_BUNDLED_YYJSON AND _REFLECTCPP_NEEDS_JSON_IMPL) + target_include_directories( + reflectcpp SYSTEM PUBLIC + $ + $) + target_include_directories( + reflectcpp_headers SYSTEM INTERFACE + $ + $) + endif () else () if (NOT TARGET ctre::ctre) find_package(ctre CONFIG REQUIRED) endif () target_link_libraries(reflectcpp PUBLIC ctre::ctre) + target_link_libraries(reflectcpp_headers INTERFACE ctre::ctre) endif () if (NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) @@ -271,26 +498,71 @@ if (NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) find_package(enchantum CONFIG REQUIRED) endif () target_link_libraries(reflectcpp PUBLIC enchantum::enchantum) + target_link_libraries(reflectcpp_headers INTERFACE enchantum::enchantum) endif () if (_REFLECTCPP_NEEDS_JSON_IMPL) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_json.cpp ) - if (REFLECTCPP_USE_BUNDLED_DEPENDENCIES) + if (REFLECTCPP_USE_BUNDLED_YYJSON) list(APPEND REFLECT_CPP_SOURCES src/yyjson.c ) - set_source_files_properties(src/yyjson.c PROPERTIES LANGUAGE CXX) - - target_include_directories( - reflectcpp PUBLIC - $) + set_source_files_properties(src/yyjson.c PROPERTIES + LANGUAGE CXX + SKIP_PRECOMPILE_HEADERS ON + ) + if (MSVC) + if (REFLECTCPP_STRICT_WARNINGS) + set_property(SOURCE src/yyjson.c APPEND PROPERTY COMPILE_OPTIONS /W0) + endif () + elseif ((_REFLECTCPP_IS_TOP_LEVEL OR REFLECTCPP_STRICT_WARNINGS) AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + set_property(SOURCE src/yyjson.c APPEND PROPERTY COMPILE_OPTIONS -w) + endif () + if (NOT REFLECTCPP_BUILD_SHARED AND NOT WIN32 AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + set_property(SOURCE src/yyjson.c APPEND PROPERTY COMPILE_OPTIONS -fvisibility=hidden) + endif () + if (NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) + set_source_files_properties(src/yyjson.c PROPERTIES + INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include/rfl/thirdparty") + endif () else () - if (NOT TARGET yyjson::yyjson) - find_package(yyjson CONFIG REQUIRED) + if (DEFINED REFLECTCPP_YYJSON_TARGET AND NOT "${REFLECTCPP_YYJSON_TARGET}" STREQUAL "") + set(_REFLECTCPP_YYJSON_TARGET "${REFLECTCPP_YYJSON_TARGET}") + if (NOT TARGET "${_REFLECTCPP_YYJSON_TARGET}") + message(FATAL_ERROR + "REFLECTCPP_YYJSON_TARGET '${_REFLECTCPP_YYJSON_TARGET}' does not name an existing CMake target.") + endif () + if (REFLECTCPP_INSTALL AND NOT "${_REFLECTCPP_YYJSON_TARGET}" STREQUAL "yyjson::yyjson") + message(WARNING + "REFLECTCPP_YYJSON_TARGET='${_REFLECTCPP_YYJSON_TARGET}' is intended for subproject embedding; " + "installed reflectcpp-config.cmake resolves external yyjson via find_dependency(yyjson) (yyjson::yyjson).") + endif () + else () + set(_REFLECTCPP_YYJSON_TARGET yyjson::yyjson) + if (NOT TARGET yyjson::yyjson) + find_package(yyjson CONFIG REQUIRED) + # Promote directory-scoped imported yyjson::yyjson to global so CMake 3.20-3.25 + # resolves $ on reflectcpp::headers in parent directories. + if (TARGET yyjson::yyjson) + set(_rfl_yyjson_real yyjson::yyjson) + get_target_property(_rfl_yyjson_aliased "${_rfl_yyjson_real}" ALIASED_TARGET) + if (_rfl_yyjson_aliased) + set(_rfl_yyjson_real "${_rfl_yyjson_aliased}") + endif () + get_target_property(_rfl_yyjson_imported "${_rfl_yyjson_real}" IMPORTED) + if (_rfl_yyjson_imported) + set_target_properties("${_rfl_yyjson_real}" PROPERTIES IMPORTED_GLOBAL TRUE) + endif () + endif () + endif () endif () - target_link_libraries(reflectcpp PUBLIC yyjson::yyjson) + target_link_libraries(reflectcpp PUBLIC ${_REFLECTCPP_YYJSON_TARGET}) + target_include_directories(reflectcpp_headers SYSTEM INTERFACE + $) + target_compile_definitions(reflectcpp_headers INTERFACE + $) endif () endif () @@ -298,21 +570,31 @@ if (REFLECTCPP_AVRO OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_avro.cpp ) - find_package(jansson CONFIG REQUIRED) - if (REFLECTCPP_USE_VCPKG) + if (NOT TARGET jansson::jansson) + find_package(jansson CONFIG REQUIRED) + endif () + if (REFLECTCPP_USE_VCPKG OR VCPKG_TOOLCHAIN) target_include_directories(reflectcpp SYSTEM PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/include") if (MSVC) set(_AVRO_STATIC_LIB "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/avro${CMAKE_STATIC_LIBRARY_SUFFIX}") if(REFLECTCPP_BUILD_SHARED) message(STATUS "With whole archive ${_AVRO_STATIC_LIB}") + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.24) + set(_AVRO_WHOLE_ARCHIVE "$") + else () + set(_AVRO_WHOLE_ARCHIVE "${_AVRO_STATIC_LIB}") + endif () target_link_libraries(reflectcpp PUBLIC - $ + ${_AVRO_WHOLE_ARCHIVE} "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/snappy${CMAKE_STATIC_LIBRARY_SUFFIX}" "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/lzma${CMAKE_STATIC_LIBRARY_SUFFIX}" "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/jansson${CMAKE_STATIC_LIBRARY_SUFFIX}" "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/zlib${CMAKE_STATIC_LIBRARY_SUFFIX}" ) + if (CMAKE_VERSION VERSION_LESS 3.24) + target_link_options(reflectcpp PRIVATE "/WHOLEARCHIVE:${_AVRO_STATIC_LIB}") + endif () else() target_link_libraries(reflectcpp PUBLIC "${_AVRO_STATIC_LIB}") endif() @@ -341,7 +623,7 @@ if (REFLECTCPP_CAPNPROTO OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_capnproto.cpp ) - if (NOT TARGET CapnProto) + if (NOT TARGET CapnProto::capnp) find_package(CapnProto CONFIG REQUIRED) endif () set(CAPNPC_LIB CapnProto::capnpc) @@ -356,10 +638,18 @@ if (REFLECTCPP_CBOR OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_cbor.cpp ) - if (NOT TARGET jsoncons) - find_package(jsoncons CONFIG REQUIRED) - endif() - include_directories(PUBLIC ${jsoncons_INCLUDE_DIRS}) + if (NOT TARGET jsoncons::jsoncons AND NOT TARGET jsoncons) + find_package(jsoncons CONFIG REQUIRED) + endif () + if (TARGET jsoncons::jsoncons) + target_link_libraries(reflectcpp PUBLIC jsoncons::jsoncons) + elseif (TARGET jsoncons) + target_link_libraries(reflectcpp PUBLIC jsoncons) + elseif (DEFINED jsoncons_INCLUDE_DIRS AND NOT "${jsoncons_INCLUDE_DIRS}" STREQUAL "") + foreach (_rfl_jsoncons_inc IN LISTS jsoncons_INCLUDE_DIRS) + target_include_directories(reflectcpp SYSTEM PUBLIC "$") + endforeach () + endif () endif () if (REFLECTCPP_CEREAL OR REFLECTCPP_CHECK_HEADERS) @@ -376,7 +666,7 @@ if (REFLECTCPP_CSV OR REFLECTCPP_CHECK_HEADERS) if (NOT TARGET Arrow) find_package(Arrow CONFIG REQUIRED) endif() - if (REFLECTCPP_USE_VCPKG) + if (REFLECTCPP_USE_VCPKG OR VCPKG_TOOLCHAIN) target_link_libraries(reflectcpp PUBLIC "$,Arrow::arrow_static,Arrow::arrow_shared>") else() target_link_libraries(reflectcpp PUBLIC "arrow::arrow") @@ -387,27 +677,38 @@ if (REFLECTCPP_FLEXBUFFERS OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_flexbuf.cpp ) - if (NOT TARGET flatbuffers::flatbuffers) + if (NOT TARGET flatbuffers::flatbuffers AND NOT TARGET flatbuffers) find_package(flatbuffers CONFIG REQUIRED) endif () - target_link_libraries(reflectcpp PUBLIC flatbuffers::flatbuffers) + if (TARGET flatbuffers::flatbuffers) + target_link_libraries(reflectcpp PUBLIC flatbuffers::flatbuffers) + else () + target_link_libraries(reflectcpp PUBLIC flatbuffers) + endif () endif () if (REFLECTCPP_MSGPACK OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_msgpack.cpp ) - if (NOT TARGET msgpack-c) + if (NOT TARGET msgpack-c AND NOT TARGET msgpackc) find_package(msgpack-c CONFIG REQUIRED NAMES msgpack msgpack-c msgpackc) endif() target_link_libraries(reflectcpp PUBLIC $,msgpack-c,$,msgpackc,msgpack-c>>) endif () +if (REFLECTCPP_NLOHMANN OR REFLECTCPP_CHECK_HEADERS) + if (NOT TARGET nlohmann_json::nlohmann_json) + find_package(nlohmann_json 3.11.3 CONFIG REQUIRED) + endif () + target_link_libraries(reflectcpp PUBLIC nlohmann_json::nlohmann_json) +endif () + if (REFLECTCPP_PARQUET OR REFLECTCPP_CHECK_HEADERS) if (NOT TARGET Arrow) find_package(Arrow CONFIG REQUIRED) endif() - if (REFLECTCPP_USE_VCPKG) + if (REFLECTCPP_USE_VCPKG OR VCPKG_TOOLCHAIN) if (NOT TARGET Parquet) find_package(Parquet CONFIG REQUIRED) endif() @@ -423,8 +724,8 @@ if (REFLECTCPP_TOML OR REFLECTCPP_CHECK_HEADERS) src/reflectcpp_toml.cpp ) if (NOT TARGET tomlplusplus::tomlplusplus) - find_package(tomlplusplus) - endif() + find_package(tomlplusplus REQUIRED) + endif () target_link_libraries(reflectcpp PUBLIC tomlplusplus::tomlplusplus) endif() @@ -432,30 +733,86 @@ if (REFLECTCPP_UBJSON OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_ubjson.cpp ) - if (NOT TARGET jsoncons) - find_package(jsoncons CONFIG REQUIRED) - endif() - include_directories(PUBLIC ${jsoncons_INCLUDE_DIRS}) + if (NOT TARGET jsoncons::jsoncons AND NOT TARGET jsoncons) + find_package(jsoncons CONFIG REQUIRED) + endif () + if (TARGET jsoncons::jsoncons) + target_link_libraries(reflectcpp PUBLIC jsoncons::jsoncons) + elseif (TARGET jsoncons) + target_link_libraries(reflectcpp PUBLIC jsoncons) + elseif (DEFINED jsoncons_INCLUDE_DIRS AND NOT "${jsoncons_INCLUDE_DIRS}" STREQUAL "") + foreach (_rfl_jsoncons_inc IN LISTS jsoncons_INCLUDE_DIRS) + target_include_directories(reflectcpp SYSTEM PUBLIC "$") + endforeach () + endif () endif () if (REFLECTCPP_XML OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_xml.cpp ) - if (NOT TARGET pugixml::pugixml) + if (NOT TARGET pugixml::pugixml AND NOT TARGET pugixml) find_package(pugixml CONFIG REQUIRED) endif () - target_link_libraries(reflectcpp PUBLIC pugixml::pugixml) + if (TARGET pugixml::pugixml) + set(_rfl_pugixml_target pugixml::pugixml) + else () + set(_rfl_pugixml_target pugixml) + endif () + target_link_libraries(reflectcpp PUBLIC ${_rfl_pugixml_target}) + if (NOT _REFLECTCPP_IS_TOP_LEVEL AND NOT REFLECTCPP_STRICT_WARNINGS) + # Read-only walk over non-IMPORTED (e.g. FetchContent) pugixml targets + # so subproject builds propagate pugixml headers as SYSTEM on reflectcpp + # without mutating parent-owned pugixml targets. + set(_rfl_pugi_queue "${_rfl_pugixml_target}") + set(_rfl_pugi_visited "") + while (_rfl_pugi_queue) + list(POP_FRONT _rfl_pugi_queue _rfl_pugi_t) + if (NOT TARGET "${_rfl_pugi_t}") + continue() + endif () + get_target_property(_rfl_pugi_aliased "${_rfl_pugi_t}" ALIASED_TARGET) + if (_rfl_pugi_aliased) + set(_rfl_pugi_t "${_rfl_pugi_aliased}") + endif () + if ("${_rfl_pugi_t}" IN_LIST _rfl_pugi_visited) + continue() + endif () + list(APPEND _rfl_pugi_visited "${_rfl_pugi_t}") + get_target_property(_rfl_pugi_imported "${_rfl_pugi_t}" IMPORTED) + if (_rfl_pugi_imported) + continue() + endif () + get_target_property(_rfl_pugi_inc "${_rfl_pugi_t}" INTERFACE_INCLUDE_DIRECTORIES) + if (_rfl_pugi_inc) + foreach (_rfl_pugi_dir IN LISTS _rfl_pugi_inc) + target_include_directories(reflectcpp SYSTEM PUBLIC "$") + endforeach () + endif () + get_target_property(_rfl_pugi_links "${_rfl_pugi_t}" INTERFACE_LINK_LIBRARIES) + if (_rfl_pugi_links) + foreach (_rfl_pugi_dep IN LISTS _rfl_pugi_links) + if (TARGET "${_rfl_pugi_dep}") + list(APPEND _rfl_pugi_queue "${_rfl_pugi_dep}") + endif () + endforeach () + endif () + endwhile () + endif () endif () if (REFLECTCPP_YAML OR REFLECTCPP_CHECK_HEADERS) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_yaml.cpp ) - if (NOT TARGET yaml-cpp::yaml-cpp) + if (NOT TARGET yaml-cpp::yaml-cpp AND NOT TARGET yaml-cpp) find_package(yaml-cpp CONFIG REQUIRED) endif () - target_link_libraries(reflectcpp PUBLIC yaml-cpp::yaml-cpp) + if (TARGET yaml-cpp::yaml-cpp) + target_link_libraries(reflectcpp PUBLIC yaml-cpp::yaml-cpp) + else () + target_link_libraries(reflectcpp PUBLIC yaml-cpp) + endif () endif () if (REFLECTCPP_BOOST_SERIALIZATION OR REFLECTCPP_CHECK_HEADERS) @@ -473,7 +830,7 @@ if (REFLECTCPP_YAS OR REFLECTCPP_CHECK_HEADERS) src/reflectcpp_yas.cpp ) find_path(YAS_INCLUDE_DIRS "yas/abseil_types.hpp") - target_include_directories(reflectcpp PRIVATE ${YAS_INCLUDE_DIRS}) + target_include_directories(reflectcpp SYSTEM PRIVATE ${YAS_INCLUDE_DIRS}) endif () set_target_properties(reflectcpp PROPERTIES LINKER_LANGUAGE CXX) @@ -548,20 +905,40 @@ if (REFLECTCPP_INSTALL) DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/reflectcpp" ) - file(GLOB_RECURSE RFL_HEADERS RELATIVE ${CMAKE_CURRENT_LIST_DIR} "${CMAKE_CURRENT_LIST_DIR}/include/*" ) + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.23) + file(GLOB_RECURSE RFL_HEADERS RELATIVE ${CMAKE_CURRENT_LIST_DIR} "${CMAKE_CURRENT_LIST_DIR}/include/*" ) - target_sources(reflectcpp - PUBLIC - FILE_SET reflectcpp_headers - TYPE HEADERS - BASE_DIRS $ $ - FILES ${RFL_HEADERS} - ) + target_sources(reflectcpp + PUBLIC + FILE_SET reflectcpp_headers + TYPE HEADERS + BASE_DIRS $ $ + FILES ${RFL_HEADERS} + ) + + install( + TARGETS reflectcpp + EXPORT reflectcpp-exports + FILE_SET reflectcpp_headers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) + else () + install( + TARGETS reflectcpp + EXPORT reflectcpp-exports + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + + install( + DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/" + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) + endif () install( - TARGETS reflectcpp + TARGETS reflectcpp_headers EXPORT reflectcpp-exports - FILE_SET reflectcpp_headers DESTINATION ${INCLUDE_INSTALL_DIR} ) install( @@ -571,39 +948,41 @@ if (REFLECTCPP_INSTALL) ) endif () -# Set general package information -set(CPACK_PACKAGE_NAME "reflectcpp") -set(CPACK_PACKAGE_VENDOR "Reflect C++ Team") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Reflect C++ library") -set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) -set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") -set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") - -# Configure generators -set(CPACK_GENERATOR "TGZ;RPM;DEB") - -# DEB specific configuration -set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) -set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) -# Fix maintainer information - ensure both are set consistently -set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") -set(CPACK_DEBIAN_PACKAGE_MAINTAINER "maintainer@reflectcpp.org") -set(CPACK_DEBIAN_PACKAGE_DEPENDS "") - -# RPM specific configuration -set(CPACK_RPM_PACKAGE_REQUIRES "") -set(CPACK_RPM_FILE_NAME RPM-DEFAULT) -set(CPACK_RPM_PACKAGE_LICENSE "MIT") -set(CPACK_RPM_PACKAGE_LICENSE "MIT") -set(CPACK_RPM_PACKAGE_URL "https://munich-data-engineering.github.io/reflect-cpp") - -include(CPack) - -if (ament_cmake_FOUND) - ament_package() -endif() +if (_REFLECTCPP_IS_TOP_LEVEL) + # Set general package information + set(CPACK_PACKAGE_NAME "reflectcpp") + set(CPACK_PACKAGE_VENDOR "Reflect C++ Team") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Reflect C++ library") + set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) + set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) + set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) + set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) + set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") + set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") + set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") + + # Configure generators + set(CPACK_GENERATOR "TGZ;RPM;DEB") + + # DEB specific configuration + set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) + set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) + # Fix maintainer information - ensure both are set consistently + set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") + set(CPACK_DEBIAN_PACKAGE_MAINTAINER "maintainer@reflectcpp.org") + set(CPACK_DEBIAN_PACKAGE_DEPENDS "") + + # RPM specific configuration + set(CPACK_RPM_PACKAGE_REQUIRES "") + set(CPACK_RPM_FILE_NAME RPM-DEFAULT) + set(CPACK_RPM_PACKAGE_LICENSE "MIT") + set(CPACK_RPM_PACKAGE_LICENSE "MIT") + set(CPACK_RPM_PACKAGE_URL "https://munich-data-engineering.github.io/reflect-cpp") + + include(CPack) + + if (ament_cmake_FOUND) + ament_package() + endif() +endif () diff --git a/README.md b/README.md index 9cfdfa223..e2ce55aed 100644 --- a/README.md +++ b/README.md @@ -48,11 +48,12 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile - [Extra fields](#extra-fields) - [Reflective programming](#reflective-programming) - [Standard Library Integration](#support-for-containers) + - [Installation](#installation) - [The team behind reflect-cpp](#the-team-behind-reflect-cpp) - [License](#license) ### More in our [documentation](https://munich-data-engineering.github.io/reflect-cpp): - - [Installation ↗](https://munich-data-engineering.github.io/reflect-cpp/install/#option-2-compilation-using-cmake) + - [Installation ↗](https://munich-data-engineering.github.io/reflect-cpp/install/#option-3-compilation-using-cmake) - [C++26 reflection ↗](https://munich-data-engineering.github.io/reflect-cpp/cpp26_reflection) - [Benchmarks ↗](https://munich-data-engineering.github.io/reflect-cpp/benchmarks) - [How to contribute ↗](https://munich-data-engineering.github.io/reflect-cpp/contributing) @@ -79,6 +80,7 @@ The following table lists the serialization formats currently supported by refle | CSV | [Apache Arrow](https://arrow.apache.org/) | >= 21.0.0 | Apache 2.0 | Tabular textual format | | flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26 | Apache 2.0 | Schema-less version of flatbuffers, binary format | | msgpack | [msgpack-c](https://github.com/msgpack/msgpack-c) | >= 6.0.0 | BSL 1.0 | JSON-like binary format | +| nlohmann/json| [nlohmann/json](https://github.com/nlohmann/json) | >= 3.11.3 | MIT | Header-only DOM adapter (`nlohmann::json`, `ordered_json`) | | parquet | [Apache Arrow](https://arrow.apache.org/) | >= 21.0.0 | Apache 2.0 | Tabular binary format | | TOML | [toml++](https://github.com/marzer/tomlplusplus) | >= 3.4.0 | MIT | Textual format with an emphasis on readability | | UBJSON | [jsoncons](https://github.com/danielaparker/jsoncons)| >= 0.176.0 | BSL 1.0 | JSON-like binary format | @@ -373,6 +375,17 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`: + +```cpp +if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + // Usage: ./app -o|--output-dir= -v|--verbose[=] --count= + // + // Arguments: ... +} +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages @@ -671,6 +684,7 @@ In addition, it supports the following custom containers: - `rfl::Tuple`: An alternative to `std::tuple` that compiles considerably faster. - `rfl::Validator`: Allows for automatic input validation. - `rfl::Variant`: An alternative to `std::variant` that compiles considerably faster. +- `rfl::json::Raw`: Holds a raw JSON value for passthrough serialization and deserialization (JSON only; [details](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/json/#raw-json-passthrough-rfljsonraw)). #### Custom classes @@ -687,6 +701,29 @@ The following compilers are supported for C++-20: The following compilers are supported for C++-26: - GCC 16.2 or higher +### Using CMake FetchContent + +JSON-only (zero external dependencies — `yyjson`, `ctre`, and `enchantum` are bundled): + +```cmake +include(FetchContent) +FetchContent_Declare(reflectcpp + GIT_REPOSITORY https://github.com/munich-data-engineering/reflect-cpp.git + GIT_TAG main # replace with a release tag containing CMake 3.20 / subproject support + GIT_SHALLOW TRUE + GIT_SUBMODULES "") +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +To enable additional formats (for example YAML), set the corresponding `REFLECTCPP_*` option **before** `FetchContent_MakeAvailable(reflectcpp)` (non-JSON format libraries are resolved via `find_package` from system packages, vcpkg, or Conan because `REFLECTCPP_USE_VCPKG` defaults to `OFF` when consumed as a subproject): + +```cmake +set(REFLECTCPP_YAML ON) +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + ### Using vcpkg https://vcpkg.io/en/package/reflectcpp @@ -722,7 +759,7 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` -For other installation methods, refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/docs-readme). +For other installation methods, refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/install). ### Compiling with C++-26 reflection @@ -752,3 +789,5 @@ reflect-cpp includes [YYJSON](https://github.com/ibireme/yyjson), the fastest JS reflect-cpp includes [compile-time-regular-expressions](https://github.com/hanickadot/compile-time-regular-expressions). CTRE is written by Hana Dusíková and released under the Apache-2.0 License with LLVM exceptions. reflect-cpp includes [enchantum](https://github.com/ZXShady/enchantum/tree/main). enchantum is written by ZXShady and also released under the MIT License. + +See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for full third-party license texts, SPDX identifiers, and CMake/feature inclusion conditions. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..d8639fbb8 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,322 @@ +# Third-Party Notices + +`reflect-cpp` itself is licensed under the MIT License (see [LICENSE](LICENSE)). + +For out-of-the-box builds (`REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, the default), +this repository vendors the third-party components listed below under +`include/rfl/thirdparty/` and `src/yyjson.c`. When all bundled dependencies are +used, the composite SPDX license expression is: + +`MIT AND Apache-2.0 WITH LLVM-exception` + +Passing `-DREFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF` disables all bundled +components in CMake, resolving `ctre` and `enchantum` unconditionally via +`find_package` and resolving `yyjson` via `find_package` only when JSON, Avro, +CBOR, or UBJSON is enabled (`CMakeLists.txt`). Note that `REFLECTCPP_INSTALL=ON` +installs the entire `include/` tree, including `include/rfl/thirdparty/`. + +## Vendored Components + +| Component | Vendored Path(s) | Version | Upstream URL | SPDX License | CMake / Feature Condition | +|---|---|---|---|---|---| +| **yyjson** | `include/rfl/thirdparty/yyjson.h`, `src/yyjson.c` | `0.12.0` | | `MIT` | Compiled only when `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON` **and** at least one of `REFLECTCPP_JSON=ON` (default), `REFLECTCPP_AVRO=ON`, `REFLECTCPP_CBOR=ON`, or `REFLECTCPP_UBJSON=ON` is enabled (`_REFLECTCPP_NEEDS_JSON_IMPL` in `CMakeLists.txt`). Not compiled when all four options are `OFF`. | +| **CTRE** (compile-time-regular-expressions) | `include/rfl/thirdparty/ctre.hpp` | `3.10.0` | | `Apache-2.0 WITH LLVM-exception` | Header-only; included by `include/rfl/PatternValidator.hpp`, which is unconditionally included by `include/rfl.hpp` (and transitively every format umbrella header `include/rfl/.hpp` and `reflectcpp`'s precompiled header). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled header; installed/non-CMake builds fall back to `thirdparty/ctre.hpp` when no external `` is on the include path. | +| **enchantum** | `include/rfl/thirdparty/enchantum/` | Vendored from upstream `main` in reflect-cpp PR #441 (`750e67d6`, 2025-05-30; minor unused-include cleanup in PR #519 / `732e9fe8`; no embedded version macro; external installs require `>= 0.5.0` in `vcpkg.json`) | | `MIT` | Header-only; included by `include/rfl/internal/enums/cpp20/enchantum.hpp` for C++20 enum reflection when `REFLECTCPP_USE_CPP26_REFLECTION=OFF` (default). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled copy (installed/non-CMake builds fall back to `thirdparty/enchantum/enchantum.hpp` when no external copy is on the include path). Not included by C++ headers when `REFLECTCPP_USE_CPP26_REFLECTION=ON` (CMake still runs `find_package(enchantum)` if `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF`). | + +--- + +## yyjson + +- **Upstream:** +- **Author:** YaoYuan +- **Version:** `0.12.0` (`YYJSON_VERSION_STRING` in `include/rfl/thirdparty/yyjson.h`) +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/yyjson.h` and `src/yyjson.c` + +```text + Copyright (c) 2020 YaoYuan + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +``` + +--- + +## CTRE (compile-time-regular-expressions) + +- **Upstream:** +- **Author:** Hana Dusíková +- **Version:** `3.10.0` +- **SPDX License:** `Apache-2.0 WITH LLVM-exception` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/ctre.hpp` + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +--- + +## enchantum + +- **Upstream:** +- **Author:** ZXShady +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from upstream + (the 22 vendored header files under `include/rfl/thirdparty/enchantum/` do + not carry inline copyright or license headers). + +```text +MIT License + +Copyright (c) 2025 ZXShady + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 838fde939..9c46580fe 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -1,4 +1,9 @@ -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") +if (NOT MSVC) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") +elseif (REFLECTCPP_STRICT_WARNINGS) + # Restore /W3 for benchmark targets after top-level CMakeLists strips /W3 before setting /W4 on reflectcpp. + add_compile_options(/W3) +endif () if (MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std:c++20 -O2") diff --git a/benchmarks/all/CMakeLists.txt b/benchmarks/all/CMakeLists.txt index cbed30674..5efb69f35 100644 --- a/benchmarks/all/CMakeLists.txt +++ b/benchmarks/all/CMakeLists.txt @@ -1,4 +1,4 @@ -project(reflect-cpp-all-format-benchmarks) +project(reflect-cpp-all-format-benchmarks LANGUAGES CXX) file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") diff --git a/benchmarks/json/CMakeLists.txt b/benchmarks/json/CMakeLists.txt index 60dd74ddc..1c34e3d55 100644 --- a/benchmarks/json/CMakeLists.txt +++ b/benchmarks/json/CMakeLists.txt @@ -1,4 +1,4 @@ -project(reflect-cpp-json-benchmarks) +project(reflect-cpp-json-benchmarks LANGUAGES CXX) file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") diff --git a/conanfile.py b/conanfile.py index a6a1ade85..371985be5 100644 --- a/conanfile.py +++ b/conanfile.py @@ -45,6 +45,7 @@ class ReflectCppConan(ConanFile): "with_csv": [True, False], "with_flatbuffers": [True, False], "with_msgpack": [True, False], + "with_nlohmann": [True, False], "with_parquet": [True, False], "with_toml": [True, False], "with_ubjson": [True, False], @@ -62,6 +63,7 @@ class ReflectCppConan(ConanFile): "with_csv": False, "with_flatbuffers": False, "with_msgpack": False, + "with_nlohmann": False, "with_parquet": False, "with_toml": False, "with_ubjson": False, @@ -96,6 +98,8 @@ def requirements(self): self.requires("flatbuffers/24.3.25", transitive_headers=True) if self.options.with_msgpack: self.requires("msgpack-c/6.0.0", transitive_headers=True) + if self.options.with_nlohmann: + self.requires("nlohmann_json/3.11.3", transitive_headers=True) if self.options.with_toml: self.requires("tomlplusplus/3.4.0", transitive_headers=True) if self.options.with_xml: @@ -136,6 +140,7 @@ def generate(self): tc.cache_variables["REFLECTCPP_CSV"] = self.options.with_csv tc.cache_variables["REFLECTCPP_FLEXBUFFERS"] = self.options.with_flatbuffers tc.cache_variables["REFLECTCPP_MSGPACK"] = self.options.with_msgpack + tc.cache_variables["REFLECTCPP_NLOHMANN"] = self.options.with_nlohmann tc.cache_variables["REFLECTCPP_PARQUET"] = self.options.with_parquet tc.cache_variables["REFLECTCPP_TOML"] = self.options.with_toml tc.cache_variables["REFLECTCPP_XML"] = self.options.with_xml diff --git a/docs/content/enums.md b/docs/content/enums.md index 5ab5561af..4d972f20a 100644 --- a/docs/content/enums.md +++ b/docs/content/enums.md @@ -215,3 +215,26 @@ constexpr auto enumerator_array = rfl::get_enumerator_array(); In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also `rfl::get_underlying_enumerators()` and `rfl::get_underlying_enumerator_array()`. + +## Custom wire names (`rfl::EnumNames` and `rfl::TransformEnumNames`) + +To customize serialized enum wire names across JSON, CLI, Generic, XML, YAML, and JSON Schema without duplicating enumerators as `rfl::Literal<...>`, specialize `rfl::EnumNames` and/or pass a `rfl::TransformEnumNames<...>` processor (`rfl::EnumSnakeCaseToKebabCase`, `rfl::EnumSnakeCaseToCamelCase`, `rfl::EnumSnakeCaseToPascalCase`, `rfl::EnumCamelCaseToSnakeCase`, `rfl::EnumToLowerCase`, `rfl::EnumToUpperCase`): + +```cpp +enum class OptimizationLevel { no_opt, size_opt, speed_opt, cxx_standard }; + +template <> +struct rfl::EnumNames { + static constexpr rfl::EnumNameTransform transform = + rfl::EnumNameTransform::snake_to_kebab; + static constexpr std::array, 1> + overrides = {{ + {OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; +``` + +- `overrides` (either a static contiguous range or a static `overrides()` returning a borrowed contiguous range such as `std::span>`) takes precedence over `transform`, and also supports enumerators outside the default reflected range. +- `transform` can be either a `rfl::EnumNameTransform` constant or a static callable `transform(std::string_view)` returning `std::string` or `std::string_view`. +- If `rfl::EnumNames` only defines `overrides` (without `transform`), non-overridden enumerators still receive any `rfl::TransformEnumNames<...>` processor passed to `read`, `write`, or `to_schema`. +- Use `rfl::get_enum_wire_names()` to inspect resolved `(wire_name, enumerator)` pairs. diff --git a/docs/content/install.md b/docs/content/install.md index 5aad26843..03537420c 100644 --- a/docs/content/install.md +++ b/docs/content/install.md @@ -36,6 +36,41 @@ Simply use [this recipe](https://conan.io/center/recipes/reflect-cpp). ## Option 3: Compilation using cmake +### Using FetchContent + +To consume reflect-cpp directly from a CMake project with JSON support only (zero external dependencies — `yyjson`, `ctre`, and `enchantum` are bundled): + +```cmake +include(FetchContent) +FetchContent_Declare(reflectcpp + GIT_REPOSITORY https://github.com/munich-data-engineering/reflect-cpp.git + GIT_TAG main # replace with a release tag containing CMake 3.20 / subproject support + GIT_SHALLOW TRUE + GIT_SUBMODULES "") +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +To enable additional serialization formats (for example YAML), set the corresponding `REFLECTCPP_*` option **before** `FetchContent_MakeAvailable(reflectcpp)`: + +```cmake +set(REFLECTCPP_YAML ON) +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +When reflect-cpp is consumed as a subproject, `REFLECTCPP_USE_VCPKG` defaults to `OFF`, so each non-JSON format's underlying library (such as `yaml-cpp`) is resolved via `find_package` from your system packages, vcpkg toolchain, or Conan generator. + +### Subproject packaging options & `reflectcpp::headers` + +When embedding reflect-cpp inside larger projects or shared libraries, additional CMake controls are available: + +- **`REFLECTCPP_USE_BUNDLED_YYJSON`** (defaults to `REFLECTCPP_USE_BUNDLED_DEPENDENCIES`) and **`REFLECTCPP_YYJSON_TARGET`** (defaults to `yyjson::yyjson` when `REFLECTCPP_USE_BUNDLED_YYJSON=OFF`): reuse an existing external `yyjson` target without disabling bundled `ctre`/`enchantum`. *(Note: if you mix `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF` with `REFLECTCPP_USE_BUNDLED_YYJSON=ON`, ensure no external `` on your include path shadows the bundled header.)* +- **`REFLECTCPP_HIDDEN_VISIBILITY`** (default `OFF`): compiles static `reflectcpp` with hidden symbol visibility (`-fvisibility=hidden` / `-fvisibility-inlines-hidden`). Bundled `yyjson_*` symbols are already hidden by default on static non-Windows builds so consumer shared libraries never re-export them. +- **`reflectcpp::headers`**: an exported `INTERFACE` target propagating core reflection (`ctre`/`enchantum`) and JSON (`yyjson`) headers, compile features, and compile definitions without linking compiled `reflectcpp` objects (useful for header-only reflection or intermediate `OBJECT` libraries; final binaries/DSOs using out-of-line symbols still link `reflectcpp::reflectcpp`, and non-JSON backends are not propagated through `reflectcpp::headers`). + +### Building standalone + This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary. ```bash @@ -44,6 +79,8 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` +> **Tip (Windows multi-config installs):** When installing both `Debug` and `Release` configurations into the same prefix with Visual Studio, pass `-DCMAKE_DEBUG_POSTFIX=d` so Debug (`reflectcppd.lib`) and Release (`reflectcpp.lib`) libraries coexist without overwriting each other. + ## Option 4: Include source files into your own build Simply copy the contents of the folders `include` and `src` into your source repository or add it to your include path and also add `src/reflectcpp.cpp` and `src/reflectcpp_json.cpp` and `src/yyjson.c` to your source files for compilation. @@ -72,11 +109,9 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` -To use reflect-cpp in your project: +To use reflect-cpp in your project as a subdirectory, set any optional format flags **before** `add_subdirectory`: ```cmake -add_subdirectory(reflect-cpp) # Add this project as a subdirectory - set(REFLECTCPP_AVRO ON) # Optional set(REFLECTCPP_BSON ON) # Optional set(REFLECTCPP_CBOR ON) # Optional @@ -87,7 +122,9 @@ set(REFLECTCPP_UBJSON ON) # Optional set(REFLECTCPP_XML ON) # Optional set(REFLECTCPP_YAML ON) # Optional -target_link_libraries(your_project PRIVATE reflectcpp) # Link against the library +add_subdirectory(reflect-cpp) # Add this project as a subdirectory + +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) # Link against the library ``` ### Troubleshooting vcpkg diff --git a/docs/content/json_schema.md b/docs/content/json_schema.md index ad97d630b..21f3f034b 100644 --- a/docs/content/json_schema.md +++ b/docs/content/json_schema.md @@ -74,6 +74,31 @@ This will result in the following JSON schema: You can insert this into the tools mentioned above and see the generated code. +## Variants and tagged unions + +`rfl::TaggedUnion` becomes `oneOf`: every alternative has a different tag, so a value +matches exactly one of them. + +`rfl::Variant` and `std::variant` become `anyOf`, because their alternatives can overlap: +`1` is both an `integer` and a `number`, and `{"width": 1, "height": 2}` matches both +`Square` and `Rectangle` from the example in [variants](../variants_and_tagged_unions). +`oneOf` would reject such values, even though reflect-cpp reads them without problems. + +If you know that the alternatives of your variants never overlap, you can pass +`rfl::VariantsAsOneOf` to get `oneOf` for `rfl::Variant` and `std::variant` as well: + +```cpp +const std::string json_schema = + rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +Warning: `oneOf` rejects values that match more than one alternative, so with this +processor the schema rejects `1` for `rfl::Variant`. Structs can overlap +as well, for instance when additional properties are allowed (see `rfl::NoExtraFields`). + +`std::optional` and `rfl::Generic` stay `anyOf` either way. `std::optional` is not +a variant, and the alternatives of `rfl::Generic` overlap (`1` is both an `integer` and a `number`). + ## Adding descriptions JSON schemata also often contain descriptions. reflect-cpp supports this as well. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..366043c02 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -45,6 +45,7 @@ reflect-cpp currently supports the following processors: - `rfl::NoFieldNames` - `rfl::NoOptionals` - `rfl::UnderlyingEnums` +- `rfl::VariantsAsOneOf` - `rfl::SnakeCaseToCamelCase` - `rfl::SnakeCaseToPascalCase` @@ -492,6 +493,19 @@ The resulting JSON string looks like this: {"radius":2.0,"color":1} ``` +### `rfl::VariantsAsOneOf` + +By default, the JSON schema describes `rfl::Variant` and `std::variant` as `anyOf`. +By passing the processor `rfl::VariantsAsOneOf` to `rfl::json::to_schema`, they +become `oneOf`: + +```cpp +rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +It only changes the schema, not reading or writing. Please refer to +the [JSON schema documentation](../json_schema) for details. + ### `rfl::SnakeCaseToCamelCase` Please refer to the example above. @@ -549,6 +563,42 @@ The resulting JSON string looks like this: {"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} ``` +## `rfl::TransformEnumNames` (`EnumSnakeCaseToKebabCase`, etc.) + +Applies a whole-enum wire-name casing transform to enum fields during reading, +writing, and JSON Schema generation. Resolved wire-name tables are cached once +per `(EnumType, EnumNameTransform)` pair. + +Built-in aliases: +- `rfl::EnumSnakeCaseToKebabCase` +- `rfl::EnumSnakeCaseToCamelCase` +- `rfl::EnumSnakeCaseToPascalCase` +- `rfl::EnumCamelCaseToSnakeCase` +- `rfl::EnumToLowerCase` +- `rfl::EnumToUpperCase` + +```cpp +enum class CostModel { t_count, two_qubit_gate_count, gate_count }; +struct Config { CostModel cost_model; }; + +const auto json_str = rfl::json::write( + Config{.cost_model = CostModel::two_qubit_gate_count}); +// {"cost_model":"two-qubit-gate-count"} +``` + +## `rfl::IntegerBounds` + +Opt-in schema processor that emits C++ integer width `minimum` and `maximum` +keywords in JSON Schema for signed and unsigned integer types (`int8_t`–`int64_t`, +`uint8_t`–`uint64_t`, etc.), excluding `bool`, character types (`char`, `wchar_t`, +`char8_t`, `char16_t`, `char32_t`), and `rfl::UnderlyingEnums`. + +```cpp +struct NetConfig { uint16_t port; }; +const auto schema = rfl::json::to_schema(); +// "port": {"type":"integer","minimum":0,"maximum":65535} +``` + ## Writing your own processors In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter. diff --git a/docs/content/supported_formats/_index.md b/docs/content/supported_formats/_index.md index 91bd2e458..eb6a27749 100644 --- a/docs/content/supported_formats/_index.md +++ b/docs/content/supported_formats/_index.md @@ -18,6 +18,7 @@ Human-readable formats for configuration, data exchange, and legacy integration. {{< cards >}} {{< card link="json" title="JSON" icon="book-open" subtitle="Out-of-the-box support via yyjson. Standard for web APIs and data interchange." >}} + {{< card link="nlohmann" title="nlohmann/json" icon="book-open" subtitle="Header-only direct DOM interop with nlohmann::json and nlohmann::ordered_json." >}} {{< card link="yaml" title="YAML" icon="book-open" subtitle="Textual format with an emphasis on readability. Widely used in Docker, Kubernetes, and CI/CD configuration." >}} {{< card link="toml" title="TOML" icon="book-open" subtitle="Textual format with an emphasis on readability. Popular for application configuration in the Rust ecosystem." >}} {{< card link="csv" title="CSV" icon="book-open" subtitle="Tabular textual format. The universal interchange format for spreadsheets, databases, and ETL pipelines." >}} diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 00b4002cc..433cecb03 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -195,6 +195,80 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. +It returns an `rfl::Result`. + +```cpp +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional> + input_file; + rfl::Short<"p", rfl::Description<"Port to listen on", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", std::vector> tags; + Database database; +}; +``` + +`rfl::cli::usage("app", true).value()` is the usage line, where +optional arguments are in brackets, and one line per argument, with its +description and whether it is required. `rfl::cli::usage("app")` +gives only the usage line. + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Required. + --database.host= Required. + --database.port= Required. +``` + +Fields wrapped in `rfl::DefaultVal` are optional, and so are all fields if you +pass `rfl::DefaultIfMissing` (to both `read` and `usage`). The parser takes +the defaults of `rfl::DefaultVal` fields from a default-constructed struct. If +a struct with `rfl::DefaultVal` cannot be default-constructed (for instance +because a validator rejects another field's default value), it cannot be read, +and `usage` returns the error, as it does for two fields with the same short +name. + +Each argument is shown as the option table that `read` parses with (see +[Architecture](#architecture)) reads it: a `bool`, also inside a nested +struct, is a flag whose value can be left out (`--verbose[=]`), and +every other option takes a value (`--port=`). + +`rfl::Positional` and `rfl::Short` are found through the other wrappers, as +the parser does (see [Combining wrappers](#combining-wrappers)), so +`rfl::Description<"...", rfl::Positional>` is listed as a +positional argument. + +`read` does not handle `--help`: check `argv` for it and print `usage` +yourself: + +```cpp +int main(int argc, char* argv[]) { + if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + return 0; + } + const auto config = rfl::cli::read(argc, argv).value(); +} +``` + ## Supported types | Type | CLI format | Notes | @@ -239,6 +313,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..b1bd26bdc 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,60 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Read and write flags + +`rfl::json` provides `inline constexpr` flag constants (combinable with `|`) so you do not need to reference underlying `YYJSON_*` constants directly. + +### Read flags (`rfl::json::read` and `rfl::json::load`) + +| Flag | Description | +| --- | --- | +| `rfl::json::allow_comments` | Allow C-style single-line (`//`) and multi-line (`/* */`) comments | +| `rfl::json::allow_trailing_commas` | Allow a single trailing comma at the end of an object or array | +| `rfl::json::jsonc` | Shorthand for `allow_comments \| allow_trailing_commas` (JSONC) | +| `rfl::json::allow_bom` | Allow and skip a leading UTF-8 BOM *(requires yyjson >= 0.11.0)* | +| `rfl::json::stop_when_done` | Stop after the first JSON value and ignore trailing content | +| `rfl::json::read_allow_inf_and_nan` | Allow `Inf`, `Infinity`, and `NaN` numbers and literals | +| `rfl::json::read_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences in string values | +| `rfl::json::allow_ext_number` | Allow hex numbers, leading/trailing decimal points, and leading `+` *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_escape` | Allow extended string escape sequences *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_whitespace` | Allow extended whitespace characters *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_single_quoted_str` | Allow single-quoted strings *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_unquoted_key` | Allow unquoted object keys *(requires yyjson >= 0.12.0)* | +| `rfl::json::json5` | Allow JSON5 syntax *(requires yyjson >= 0.12.0)* | + +Example reading JSONC: + +```cpp +const auto result = rfl::json::read( + jsonc_string, rfl::json::allow_comments | rfl::json::allow_trailing_commas); + +// Or using the convenience alias: +const auto result2 = rfl::json::read(jsonc_string, rfl::json::jsonc); +``` + +### Write flags (`rfl::json::write`, `rfl::json::save`, and `rfl::json::to_schema`) + +| Flag | Description | +| --- | --- | +| `rfl::json::pretty` | Pretty-print with 4-space indentation | +| `rfl::json::pretty_two_spaces` | Pretty-print with 2-space indentation (overrides `pretty`) *(requires yyjson >= 0.7.0)* | +| `rfl::json::newline_at_end` | Append a trailing `\n` to the output *(requires yyjson >= 0.9.0)* | +| `rfl::json::escape_unicode` | Escape non-ASCII characters as `\uXXXX` for ASCII-only output | +| `rfl::json::escape_slashes` | Escape `/` as `\/` | +| `rfl::json::write_allow_inf_and_nan` | Write `Inf`/`NaN` as `Infinity`/`NaN` literals (non-standard) | +| `rfl::json::inf_and_nan_as_null` | Write `Inf`/`NaN` as `null` (overrides `write_allow_inf_and_nan`) | +| `rfl::json::write_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences when encoding strings | + +Example combining write flags: + +```cpp +const std::string json_string = rfl::json::write( + person, rfl::json::pretty_two_spaces | rfl::json::newline_at_end); +``` + +> Note: `read_allow_inf_and_nan` / `write_allow_inf_and_nan` and `read_allow_invalid_unicode` / `write_allow_invalid_unicode` are prefixed with `read_` / `write_` because the underlying read and write flag bit values differ. Low-level/unsafe read flags (`YYJSON_READ_INSITU`, `YYJSON_READ_NUMBER_AS_RAW`, `YYJSON_READ_BIGNUM_AS_RAW`) are intentionally not exposed as `rfl::json` aliases (`YYJSON_READ_INSITU` is rejected at runtime). + ## Custom constructors One of the great things about C++ is that it gives you control over @@ -118,3 +172,34 @@ rfl::Result Person::from_json_obj(const JSONVar& _obj) { This will force the compiler to only compile the JSON parsing when the source file is compiled. +## Raw JSON Passthrough (`rfl::json::Raw`) + +Use `rfl::json::Raw` when a struct contains a JSON subtree that you want to +pass through without converting into intermediate C++ types: + +```cpp +struct Envelope { + int id; + rfl::json::Raw payload; +}; + +const auto env = rfl::json::read( + R"({"id":1,"payload":{"nested":[1,2,3]}})").value(); +const auto out = rfl::json::write(env); +``` + +Construct `rfl::json::Raw` from text using the validating factory +`rfl::json::Raw::from_string(...)` (which returns `rfl::Result` +after checking strict RFC 8259 JSON). When you already hold validated JSON +(such as output from `rfl::json::write`), `rfl::json::Raw::from_trusted_string(...)` +constructs a `Raw` without re-parsing; writing emits the stored JSON text +verbatim via `yyjson_mut_rawncpy`. + +On read, `rfl::json::Raw` captures the parsed `yyjson` subtree via +`yyjson_val_write_opts` with strict RFC 8259 formatting (flag `0`), which +canonicalizes whitespace and rejects non-standard values such as `NaN` or +`Infinity` even when parsed with `YYJSON_READ_ALLOW_INF_AND_NAN`. Pass +`YYJSON_READ_BIGNUM_AS_RAW` to `rfl::json::read` if integers wider than 64 bits +must be preserved verbatim. `rfl::json::Raw` is supported with `rfl::json` +(and `rfl::Generic` conversions / JSON Schema) only. + diff --git a/docs/content/supported_formats/nlohmann.md b/docs/content/supported_formats/nlohmann.md new file mode 100644 index 000000000..1ff4d8969 --- /dev/null +++ b/docs/content/supported_formats/nlohmann.md @@ -0,0 +1,71 @@ +--- +breadcrumbs: true +--- + +# nlohmann/json + +For `nlohmann::json` interoperability, include `` and enable `-DREFLECTCPP_NLOHMANN=ON` when building reflect-cpp (or link `nlohmann_json::nlohmann_json` directly — the adapter is header-only and requires `nlohmann/json >= 3.11.3`). It has no dependency on `yyjson` and works with `-DREFLECTCPP_JSON=OFF`. + +## Reading and writing (`nlohmann::json` and `nlohmann::ordered_json`) + +Convert reflected structs directly to and from `nlohmann::basic_json` without string round-trips: + +```cpp +#include + +struct Person { + std::string first_name; + rfl::Validator> age; + std::optional nickname; +}; + +const Person src{.first_name = "Ada", .age = 36, .nickname = "countess"}; + +// Serialize to nlohmann::json (supports reflect-cpp processors) +const nlohmann::json j = rfl::nlohmann::write(src); + +// Deserialize without throwing (errors are returned via rfl::Result) +const rfl::Result res = + rfl::nlohmann::read(j); + +// Preserve struct field order with nlohmann::ordered_json +const nlohmann::ordered_json oj = rfl::nlohmann::write(src); +``` + +Note that `nlohmann::ordered_json` uses `nlohmann::ordered_map` (backed by a contiguous sequence), so key lookup and insertion are $O(N)$ per field rather than $O(\log N)$ as with `nlohmann::json`. + +## Opt-in `nlohmann::adl_serializer` + +`` always declares `rfl::nlohmann::enable_adl_serializer`. When C++ exceptions are enabled and `JSON_NOEXCEPTION` is not defined, it also defines the opt-in `nlohmann::adl_serializer` specialization. Specialize `rfl::nlohmann::enable_adl_serializer` to `std::true_type` to opt specific types into `nlohmann::json` conversions without affecting any other types: + +```cpp +struct User { + const std::string name; + rfl::Validator> age; +}; + +template <> +struct rfl::nlohmann::enable_adl_serializer : std::true_type {}; + +nlohmann::json j = User{.name = "Grace", .age = 42}; +User u = j.get(); // throws nlohmann::json::other_error (a nlohmann::json::exception) on error +``` + +Because `adl_serializer` uses the returning 1-argument `from_json` overload, `j.get()` works cleanly with `rfl::Validator`, `const` fields, and non-default-constructible structs. + +## Dynamic `nlohmann::json` fields in reflected structs + +`nlohmann::json` and `nlohmann::ordered_json` (and other `nlohmann::basic_json` specializations) can be embedded directly as fields inside reflected structs and serialized across `rfl::nlohmann`, `rfl::json`, `rfl::generic`, and other formats: + +```cpp +struct Event { + std::string kind; + nlohmann::json payload; + nlohmann::ordered_json metadata; +}; +``` + +- `rfl::Bytestring` and `rfl::Vectorstring` serialize as RFC 4648 Base64 strings and accept either Base64 strings or native `nlohmann::json::binary_t` values on read. +- When writing `nlohmann::basic_json` values containing `binary_t` to other formats, binary formats (CBOR, msgpack, flexbuffers, UBJSON, BSON, etc.) receive native `rfl::Bytestring` values, `rfl::json` Base64-encodes `rfl::Bytestring`, and text/generic formats without `Bytestring` support fall back to Base64 strings. +- Cross-`basic_json` conversions (`nlohmann::json` ↔ `nlohmann::ordered_json`) preserve exact integer signedness (`uint64_t`/`int64_t`), booleans, strings, binary payloads, and key order. +- Mirroring `rfl::Generic` in `rfl/xml/Parser.hpp`, writing `nlohmann::basic_json` fields to XML is supported, while reading XML into `nlohmann::basic_json` is rejected at compile time because XML is untyped without a schema. diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..0ed1b41d2 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -23,6 +23,7 @@ #include "rfl/DefaultVal.hpp" #include "rfl/Description.hpp" #include "rfl/DurationsAsCount.hpp" +#include "rfl/EnumNames.hpp" #include "rfl/EnumNamesOnly.hpp" #include "rfl/ExtraFields.hpp" #include "rfl/FailFast.hpp" @@ -30,6 +31,7 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/IntegerBounds.hpp" #include "rfl/Literal.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" @@ -51,12 +53,15 @@ #include "rfl/SnakeCaseToCamelCase.hpp" #include "rfl/SnakeCaseToKebabCase.hpp" #include "rfl/SnakeCaseToPascalCase.hpp" +#include "rfl/StringLiteral.hpp" #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" +#include "rfl/TransformEnumNames.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" #include "rfl/Variant.hpp" +#include "rfl/VariantsAsOneOf.hpp" #include "rfl/Vectorstring.hpp" #include "rfl/always_false.hpp" #include "rfl/apply.hpp" @@ -92,6 +97,7 @@ #include "rfl/to_named_tuple.hpp" #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" +#include "rfl/type_name.hpp" #include "rfl/type_name_t.hpp" #include "rfl/view_t.hpp" #include "rfl/visit.hpp" diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index 5b61bb2bf..0e76a6e8e 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -1,6 +1,7 @@ #ifndef RFL_ALLOF_HPP_ #define RFL_ALLOF_HPP_ +#include #include #include @@ -33,14 +34,20 @@ struct AllOf { private: template static rfl::Result validate_impl(T _value) noexcept { - if constexpr (sizeof...(Tail) == 0) { - return Head::validate(std::move(_value)); - } else { + try { auto res = Head::validate(std::move(_value)); if (!res) { return res; } - return validate_impl(std::move(*res)); + if constexpr (sizeof...(Tail) == 0) { + return res; + } else { + return validate_impl(std::move(*res)); + } + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } }; diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index eb6425401..91169998f 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ANYOF_HPP_ #define RFL_ANYOF_HPP_ -#include +#include #include #include #include @@ -37,13 +37,13 @@ struct AnyOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected at least one of the following validations to pass, but " - "none of them did:"; + std::string msg = + "Expected at least one of the following validations to pass, but " + "none of them did:"; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template diff --git a/include/rfl/EnumNames.hpp b/include/rfl/EnumNames.hpp new file mode 100644 index 000000000..3a7a2d515 --- /dev/null +++ b/include/rfl/EnumNames.hpp @@ -0,0 +1,150 @@ +#ifndef RFL_ENUMNAMES_HPP_ +#define RFL_ENUMNAMES_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Processors.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" + +namespace rfl { + +/// Pair of `(enumerator, wire_name)` for per-enumerator overrides in +/// `rfl::EnumNames`. +template +using EnumOverride = std::pair; + +/// Specialize `rfl::EnumNames` to customize wire names for enum `E` across +/// JSON, CLI, Generic, YAML, XML, and JSON Schema without duplicating +/// enumerators as `rfl::Literal<...>`. +/// +/// Supported members (individually or combined; `overrides` takes precedence): +/// - `static constexpr EnumNameTransform transform = EnumNameTransform::snake_to_kebab;` +/// OR `static std::string transform(std::string_view _raw_name);` +/// (any return type convertible or explicitly constructible into `std::string`, +/// such as `std::string_view`, is accepted) +/// - `static constexpr std::array, N> overrides = {{ ... }};` +/// OR `static std::span> overrides();` +template +struct EnumNames {}; + +namespace internal { + +template +struct is_std_span : std::false_type {}; + +template +struct is_std_span> : std::true_type {}; + +template +concept EnumOverrideContiguousRange = + (std::is_array_v> && + std::same_as< + std::remove_cv_t>>, + EnumOverride>) || + requires(const std::remove_reference_t& _r) { + { _r.data() } -> std::convertible_to*>; + { _r.size() } -> std::convertible_to; + }; + +template +concept BorrowedEnumOverridesResult = + std::is_lvalue_reference_v || + is_std_span>::value; + +template +concept HasEnumOverridesVar = requires { + requires EnumOverrideContiguousRange::overrides), E>; +}; + +template +concept HasAnyEnumOverridesFn = requires { + requires EnumOverrideContiguousRange::overrides()), E>; +}; + +template +concept HasEnumOverridesFn = + HasAnyEnumOverridesFn && + BorrowedEnumOverridesResult::overrides())>; + +template +concept HasEnumTransformConst = requires { + { EnumNames::transform } -> std::convertible_to; +}; + +template +concept HasEnumTransformFn = requires(std::string_view _s) { + requires std::constructible_from::transform(_s))>; +}; + +template +inline constexpr bool has_custom_enum_names_for_transform_v = + HasEnumOverridesVar> || + HasAnyEnumOverridesFn> || + HasEnumTransformConst> || + HasEnumTransformFn> || + (_transform != EnumNameTransform::none); + +template > +inline constexpr bool has_custom_enum_names_v = + has_custom_enum_names_for_transform_v< + E, enum_name_transform_v>; + +template +inline std::span>> +get_enum_overrides() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyEnumOverridesFn || HasEnumOverridesFn, + "rfl::EnumNames::overrides() must return a borrowed contiguous range " + "(for example, std::span> or const auto&)."); + if constexpr (HasEnumOverridesFn) { + auto&& r = EnumNames::overrides(); + return std::span>(std::data(r), std::size(r)); + } else if constexpr (HasEnumOverridesVar) { + return std::span>(std::data(EnumNames::overrides), + std::size(EnumNames::overrides)); + } else { + return {}; + } +} + +template +inline std::string resolve_enum_wire_name_for_transform( + const E _val, const std::string_view _raw_name) { + using U = std::remove_cvref_t; + for (const auto& [e, wire] : get_enum_overrides()) { + if (e == _val) { + return std::string(wire); + } + } + if constexpr (HasEnumTransformFn) { + return std::string(EnumNames::transform(_raw_name)); + } else if constexpr (HasEnumTransformConst) { + return apply_enum_name_transform(_raw_name, EnumNames::transform); + } else if constexpr (_transform != EnumNameTransform::none) { + return apply_enum_name_transform(_raw_name, _transform); + } else { + return std::string(_raw_name); + } +} + +template > +inline std::string resolve_enum_wire_name(const E _val, + const std::string_view _raw_name) { + return resolve_enum_wire_name_for_transform< + E, enum_name_transform_v>(_val, _raw_name); +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_ENUMNAMES_HPP_ diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index 46f79f65f..d266300c2 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -196,10 +196,10 @@ class RFL_API Generic { Result to_string() const noexcept; /// Returns the underlying variant. - VariantType& variant() noexcept { return value_; }; + VariantType& variant() noexcept { return value_; } /// Returns the underlying variant. - const VariantType& variant() const noexcept { return value_; }; + const VariantType& variant() const noexcept { return value_; } /// Equality comparison. Two Generics are equal if they hold the same /// alternative and the underlying values compare equal. diff --git a/include/rfl/IntegerBounds.hpp b/include/rfl/IntegerBounds.hpp new file mode 100644 index 000000000..d63b77845 --- /dev/null +++ b/include/rfl/IntegerBounds.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_INTEGERBOUNDS_HPP_ +#define RFL_INTEGERBOUNDS_HPP_ + +#include + +namespace rfl { + +/// Opt-in JSON Schema processor: emit `minimum` and `maximum` bounds matching +/// C++ integer widths (`int8_t`..`int64_t`, `uint8_t`..`uint64_t`, `short`, +/// `int`, `long`, `long long`, and their unsigned counterparts; excludes +/// `bool` and character types whose signedness is platform-dependent). +struct IntegerBounds { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif // RFL_INTEGERBOUNDS_HPP_ diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 4208d7713..e89ae0da5 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -164,12 +165,20 @@ class Literal { return Literal(_v); }; return find_value(_str).transform(to_literal); - }; + } /// The name defined by the Literal (returns the string representation). /// @return The string value of the current literal std::string name() const { return find_name(); } + /// Returns the compile-time string view for a single-value Literal. + /// @return The string_view of the single allowed literal value + static constexpr std::string_view name_view() noexcept + requires(sizeof...(fields_) == 1) + { + return tuple_element_t<0, FieldsType>::name_.string_view(); + } + /// Returns all possible values of the literal as a std::vector. /// @return A vector containing all allowed string values static std::vector names() { diff --git a/include/rfl/MetaField.hpp b/include/rfl/MetaField.hpp index 192c7e6c5..62ac12294 100644 --- a/include/rfl/MetaField.hpp +++ b/include/rfl/MetaField.hpp @@ -21,11 +21,11 @@ class MetaField { /// Returns the name of the field. /// @return The field name as it appears in the struct - const std::string& name() const { return name_; }; + const std::string& name() const { return name_; } /// Returns the type information of the field. /// @return A string describing the field's type - const std::string& type() const { return type_; }; + const std::string& type() const { return type_; } private: /// The name of the field. diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 381fe8811..9123b188d 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -716,7 +716,7 @@ class NamedTuple<> { using Values = rfl::Tuple<>; /// @brief Default constructor for empty NamedTuple. - NamedTuple(){}; + NamedTuple() {} /// @brief Destructor. ~NamedTuple() = default; diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 8b302cf13..5ef86d7b4 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ONEOF_HPP_ #define RFL_ONEOF_HPP_ -#include +#include #include #include #include @@ -39,40 +39,32 @@ struct OneOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message indicating the validation failure static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected exactly 1 out of " << sizeof...(Cs) + 1 - << " validations to pass, but " << sizeof...(Cs) + 1 - _errors.size() - << " of them did. The following errors were generated: "; + std::string msg = "Expected exactly 1 out of " + + std::to_string(sizeof...(Cs) + 1) + + " validations to pass, but " + + std::to_string(sizeof...(Cs) + 1 - _errors.size()) + + " of them did. The following errors were generated: "; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - return Head::validate(_value) - .and_then([&](auto&&) -> rfl::Result { - if constexpr (sizeof...(Tail) == 0) { - if (_errors.size() == sizeof...(Cs)) { - return _value; - // The AI suggests return std::forward(_result); - // is it correct in this context? - } - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }) - .or_else([&](auto&& _err) -> rfl::Result { - _errors.emplace_back(std::move(_err)); - if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }); + auto res = Head::validate(_value); + if (!res) { + _errors.emplace_back(std::move(res).error()); + } + if constexpr (sizeof...(Tail) == 0) { + if (_errors.size() == sizeof...(Cs)) { + return _value; + } + return error(make_error_message(_errors)); + } else { + return validate_impl(_value, std::move(_errors)); + } } }; diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index b1dcbc040..a22e569a7 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -1,7 +1,6 @@ #ifndef RFL_PATTERNVALIDATOR_HPP_ #define RFL_PATTERNVALIDATOR_HPP_ -#include #include #include @@ -35,10 +34,8 @@ struct PatternValidator { ctll::construct_from_pointer, _regex.arr_.data()}>(_str)) { return std::move(_str); } else { - std::stringstream stream; - stream << "String '" << _str << "' did not match format '" << _name.str() - << "': '" << _regex.str() << "'."; - return error(stream.str()); + return error("String '" + _str + "' did not match format '" + + _name.str() + "': '" + _regex.str() + "'."); } } diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index 5148b0b00..d3c0e0ec7 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -1,7 +1,7 @@ #ifndef RFL_SIZE_HPP_ #define RFL_SIZE_HPP_ -#include +#include #include #include "Ref.hpp" diff --git a/include/rfl/StringLiteral.hpp b/include/rfl/StringLiteral.hpp new file mode 100644 index 000000000..00f63055f --- /dev/null +++ b/include/rfl/StringLiteral.hpp @@ -0,0 +1,88 @@ +#ifndef RFL_STRINGLITERAL_HPP_ +#define RFL_STRINGLITERAL_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +namespace rfl { + +/// Normal strings cannot be used as template parameters, but this can. +/// Used for compile-time field names, literals, descriptions, and patterns. +template +struct StringLiteral { + static_assert( + N >= 1, + "rfl::StringLiteral requires N >= 1 (including the null terminator)."); + + /// Constrained via template type parameters rather than a requires-fold + /// over decltype of the function parameter pack: the latter crashes + /// clang 21/22 in C++26 mode (llvm/llvm-project#198052, #205000). + template ... Chars> + constexpr StringLiteral(const Chars... _chars) : arr_{_chars..., '\0'} {} + + constexpr StringLiteral(const std::array _arr) : arr_(_arr) {} + + constexpr StringLiteral(const char (&_str)[N]) { + std::copy_n(_str, N, std::data(arr_)); + } + + constexpr StringLiteral(const std::string_view _str) { + std::copy_n(_str.data(), std::min(_str.size(), N - 1), std::data(arr_)); + } + + template + requires(std::is_same_v || std::is_same_v) + explicit constexpr StringLiteral(T _data) { + std::copy_n(_data, N, std::data(arr_)); + } + + /// Returns the value as a string. + std::string str() const { return std::string(string_view()); } + + /// Returns the value as a string_view. + constexpr std::string_view string_view() const noexcept { + return std::string_view(std::data(arr_), N - 1); + } + + static constexpr std::size_t length = N - 1; + + std::array arr_{}; +}; + +template +constexpr inline bool operator==(const StringLiteral& _first, + const StringLiteral& _second) noexcept { + if constexpr (N1 != N2) { + return false; + } else { + return _first.string_view() == _second.string_view(); + } +} + +template +constexpr inline bool operator!=(const StringLiteral& _first, + const StringLiteral& _second) noexcept { + return !(_first == _second); +} + +/// Concatenates two StringLiterals at compile time (or runtime) into a +/// null-terminated StringLiteral of combined length. +template + requires(N1 >= 1 && N2 >= 1) +constexpr inline StringLiteral operator+( + const StringLiteral& _first, + const StringLiteral& _second) noexcept { + std::array arr{}; + std::copy_n(_first.arr_.data(), N1 - 1, arr.data()); + std::copy_n(_second.arr_.data(), N2 - 1, arr.data() + (N1 - 1)); + return StringLiteral(arr); +} + +} // namespace rfl + +#endif diff --git a/include/rfl/Timestamp.hpp b/include/rfl/Timestamp.hpp index a940e0fcb..8129848ae 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -73,8 +73,10 @@ class Timestamp { static Result from_string(const char* _str) noexcept { try { return Timestamp(_str); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while parsing timestamp."); } } @@ -82,7 +84,7 @@ class Timestamp { /// This is an alternative to the throwing constructor for error handling without exceptions. /// @param _str The string to parse in the format specified by the template parameter /// @return Result containing the Timestamp if parsing succeeded, or an error otherwise - static Result from_string(const std::string& _str) { + static Result from_string(const std::string& _str) noexcept { return from_string(_str.c_str()); } diff --git a/include/rfl/TransformEnumNames.hpp b/include/rfl/TransformEnumNames.hpp new file mode 100644 index 000000000..7aeb6d397 --- /dev/null +++ b/include/rfl/TransformEnumNames.hpp @@ -0,0 +1,54 @@ +#ifndef RFL_TRANSFORMENUMNAMES_HPP_ +#define RFL_TRANSFORMENUMNAMES_HPP_ + +#include +#include +#include + +#include "common.hpp" + +namespace rfl { + +/// Built-in wire-name transforms applicable to C++ enum enumerator names via +/// `rfl::TransformEnumNames<...>` processors. +enum class EnumNameTransform : std::uint8_t { + none = 0, + snake_to_kebab, + snake_to_camel, + snake_to_pascal, + camel_to_snake, + to_lower, + to_upper, +}; + +/// Applies a built-in ASCII `EnumNameTransform` to an enumerator identifier. +RFL_API std::string apply_enum_name_transform(std::string_view _name, + EnumNameTransform _transform); + +/// Processor that applies a whole-enum wire-name transform across read, write, +/// and schema generation. Resolved wire-name tables are cached once per +/// `(EnumType, EnumNameTransform)` pair. +template +struct TransformEnumNames { + static constexpr EnumNameTransform value = _transform; + + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +using EnumSnakeCaseToKebabCase = + TransformEnumNames; +using EnumSnakeCaseToCamelCase = + TransformEnumNames; +using EnumSnakeCaseToPascalCase = + TransformEnumNames; +using EnumCamelCaseToSnakeCase = + TransformEnumNames; +using EnumToLowerCase = TransformEnumNames; +using EnumToUpperCase = TransformEnumNames; + +} // namespace rfl + +#endif // RFL_TRANSFORMENUMNAMES_HPP_ diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 9be58bf61..4a0cd1243 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -34,8 +34,10 @@ struct Validator { static Result from_value(const T& _value) noexcept { try { return wrap_validated(ValidationType::validate(_value)); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } @@ -46,8 +48,10 @@ struct Validator { static Result from_value(T&& _value) noexcept { try { return wrap_validated(ValidationType::validate(std::move(_value))); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index 018edca72..046b5a030 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -774,7 +774,7 @@ namespace std { template void swap(rfl::Variant& _lhs, rfl::Variant& _rhs) noexcept { _lhs.swap(_rhs); -}; +} } // namespace std #endif diff --git a/include/rfl/VariantsAsOneOf.hpp b/include/rfl/VariantsAsOneOf.hpp new file mode 100644 index 000000000..0b71c9752 --- /dev/null +++ b/include/rfl/VariantsAsOneOf.hpp @@ -0,0 +1,33 @@ +#ifndef RFL_VARIANTSASONEOF_HPP_ +#define RFL_VARIANTSASONEOF_HPP_ + +#include + +namespace rfl { + +/// A processor that makes the JSON schema describe rfl::Variant and +/// std::variant as oneOf instead of anyOf. +/// This is a marker type (doesn't modify data) that changes the generated +/// schema. It has no effect on reading or writing. +/// By default, untagged variants are described as anyOf, because their +/// alternatives can overlap: 1 matches both alternatives of +/// rfl::Variant, and oneOf would reject it. rfl::TaggedUnion is +/// always described as oneOf, and std::optional and rfl::Generic always as +/// anyOf. +/// Usage: rfl::json::to_schema() +struct VariantsAsOneOf { + public: + /// Identity process function - returns the named tuple unchanged. + /// The actual change happens in the schema generation, not here. + /// @tparam StructType The struct type being processed + /// @param _named_tuple The named tuple representation of the struct + /// @return The same named tuple (unchanged) + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/atomic/is_atomic.hpp b/include/rfl/atomic/is_atomic.hpp index 93312de28..303468e3f 100644 --- a/include/rfl/atomic/is_atomic.hpp +++ b/include/rfl/atomic/is_atomic.hpp @@ -19,7 +19,7 @@ template struct is_atomic { static constexpr bool value = false; using RemoveAtomicT = T; - static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); }; + static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); } }; template @@ -28,7 +28,7 @@ struct is_atomic> { using RemoveAtomicT = T; static void set(RemoveAtomicT&& val, std::atomic* _t) { _t->store(std::forward(val), std::memory_order_relaxed); - }; + } }; template <> diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp index cad64d631..a45a4986d 100644 --- a/include/rfl/capnproto/is_named_type.hpp +++ b/include/rfl/capnproto/is_named_type.hpp @@ -1,6 +1,8 @@ #ifndef RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ #define RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ +#include + #include "../parsing/schema/Type.hpp" namespace rfl::capnproto { @@ -8,10 +10,15 @@ namespace rfl::capnproto { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same() || - std::is_same() || - std::is_same(); + if constexpr (std::is_same_v || + std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same() || + std::is_same() || + std::is_same(); + } }); } diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85881e7b9..a35b9e025 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -8,5 +8,6 @@ #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" +#include "cli/usage.hpp" #endif diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp new file mode 100644 index 000000000..4d384ab80 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,451 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../generic/Writer.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/is_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_named_tuple.hpp" +#include "../internal/no_optionals_v.hpp" +#include "../parsing/is_required.hpp" +#include "../parsing/schema/Definition.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Whether a top-level field is required, which the schema cannot tell the +/// way the parser sees it. +struct UsageFieldMeta { + bool required = true; +}; + +/// Everything usage() renders about one argument. +struct UsageArg { + /// The long name, including the path of nested objects ("database.host"). + std::string name; + std::string short_name; + bool positional = false; + /// What the option does with a value, from the parser's option table: + /// flags (`--verbose`) can be given without one. + OptionKind kind = OptionKind::value; + /// Whether the field is a list. + bool is_list = false; + bool required = true; + /// Whether `required` was taken from the parser's compile-time traits, so + /// that the schema must not override it. + bool required_is_known = false; + /// The placeholder for one value: "", "" or "". Lists + /// are rendered from it with the list delimiter. + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; +}; + +/// Whether a missing field of type `ValueType` inside root type `U` is filled +/// in by the parser's default-value path. Mirrors +/// `NamedTupleParser::handle_one_missing_field` without invoking `T{}` at +/// runtime (for structs, `schema::make` already constructs `T{}` once if and +/// only if `has_default_val_v` is true). +template +constexpr bool usage_default_val_is_optional() { + if constexpr (!rfl::internal::is_default_val_v) { + return false; + } else if constexpr (rfl::internal::is_named_tuple_v) { + using Inner = typename rfl::internal::default_val_t::Type; + return !std::is_const_v && + std::is_default_constructible_v && + std::is_default_constructible_v; + } else { + return std::is_default_constructible_v; + } +} + +template +void add_usage_field_meta(std::map* _meta) { + using Info = field_info; + using RawValueType = + std::remove_reference_t>; + using ValueType = std::remove_cvref_t; + auto& meta = (*_meta)[std::string(Info::name())]; + // The same condition as in NamedTupleParser::handle_one_missing_field. + // The schema cannot tell on its own, because it marks a DefaultVal field as + // optional even where the parser requires it. + meta.required = + !usage_default_val_is_optional() + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects whether each top-level field is required from the same +/// compile-time traits that the parser uses, so the help matches what the +/// parser accepts. Positional, Short and flags come from the parser's option +/// table (make_options). +template +std::map collect_usage_field_meta( + std::index_sequence<_is...>) { + std::map meta; + (add_usage_field_meta(&meta), ...); + return meta; +} + +/// Walks the format-agnostic schema of the struct and collects one UsageArg +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + UsageCollector(const parsing::schema::Definition* _definition, + const std::map* _meta, + const Options* _options, + const bool _optionals_are_required) + : definition_(_definition), + meta_(_meta), + options_(_options), + optionals_are_required_(_optionals_are_required) { + for (const auto& [short_name, path] : _options->short_options) { + short_names_[path] = short_name; + } + } + + /// Collects the arguments. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + std::vector collect(const bool _all_optional) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), false); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, const bool _outermost) { + _type.variant_.visit([&](const auto& _t) { + using T = std::remove_cvref_t; + // Description and Deprecated wrap the inner schema node without changing + // how the field is read. Short, Positional and Rename leave no node. + if constexpr (std::is_same_v + || std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _outermost); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + // The schema populates `default_value_` only when the parser recognizes + // the DefaultVal field and default-constructed its enclosing struct. + if (!_arg.required_is_known && _outermost && _t.default_value_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + const auto it = definition_->definitions_.find(_t.name_); + if (it == definition_->definitions_.end() + || !visiting_.insert(_t.name_).second) { + // Unknown or recursive: there is no finite set of paths to list. + add_leaf(std::move(_arg)); + return; + } + add(it->second, std::move(_arg), _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg); + + } else if constexpr (std::is_same_v) { + if (!_arg.name.empty()) { + _arg.name += path_separator; + } + _arg.name += ""; + _arg.short_name.clear(); + _arg.positional = false; + add(*_t.value_type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + _arg.kind = OptionKind::flag; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg)); + + } else if constexpr (std::is_same_v) { + auto values = std::vector(); + for (const auto& v : _t.values_) { + values.push_back(v.value_); + } + add_choices(values, std::move(_arg)); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.is_list = true; + add_leaf(std::move(_arg)); + + } else { + add_leaf(std::move(_arg)); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent) { + const bool is_root = _parent.name.empty(); + for (const auto& [name, type] : _object.types_) { + auto arg = UsageArg{}; + arg.name = is_root ? name : _parent.name + path_separator + name; + // Children of an optional object are only needed if it is given. + arg.required = _parent.required; + if (is_root) { + const auto& positionals = options_->positionals; + arg.positional = std::find(positionals.begin(), positionals.end(), + name) != positionals.end(); + const auto short_name = short_names_.find(name); + if (short_name != short_names_.end()) { + arg.short_name = short_name->second; + } + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + add(type, std::move(arg), true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg) { + _arg.choices = _values; + _arg.value = "<"; + for (size_t i = 0; i < _values.size(); ++i) { + _arg.value += (i == 0 ? "" : "|") + _values[i]; + } + _arg.value += ">"; + add_leaf(std::move(_arg)); + } + + void add_leaf(UsageArg _arg) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. Keep + // the schema-derived kind (such as OptionKind::flag for nested booleans) + // when the option table only tracks top-level paths. + const auto option = options_->find_long(_arg.name); + if (option.kind != OptionKind::unknown) { + _arg.kind = option.kind; + } + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const Options* options_; + const bool optionals_are_required_; + /// The rfl::Short aliases, by the path of their field. + std::map short_names_; + std::set visiting_; + std::vector args_; +}; + +/// The placeholder for the value of _arg: "", "", or for a list +/// "" with the list delimiter. +inline std::string usage_value_to_string(const UsageArg& _arg) { + if (!_arg.is_list) { + return _arg.value; + } + const auto d = std::string(1, array_delimiter); + return ""; +} + +/// "", "-p|--port=", "--verbose[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep) { + if (_arg.positional) { + return "<" + _arg.name + ">"; + } + auto str = _arg.short_name.empty() ? std::string() + : "-" + _arg.short_name + _short_sep; + str += "--" + _arg.name; + const auto value = usage_value_to_string(_arg); + switch (_arg.kind) { + case OptionKind::flag: + // `--verbose`: the value can be left out. + str += "[=" + value + "]"; + break; + default: + str += "=" + value; + break; + } + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + if (_arg.required) { + sentences.push_back("Required"); + } + auto text = _arg.description; + while (!text.empty() + && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' + || text.back() == '\n')) { + text.pop_back(); + } + for (const auto& s : sentences) { + if (!text.empty()) { + text += usage_ends_sentence(text) ? " " : ". "; + } + text += s; + } + if (!sentences.empty() && !usage_ends_sentence(text)) { + text += "."; + } + return text; +} + +inline std::string format_usage(const std::string& _program_name, + const std::vector& _args, + const bool _detailed) { + auto out = "Usage: " + _program_name; + for (const auto& arg : _args) { + const auto str = usage_arg_to_string(arg, "|"); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + if (!_detailed || _args.empty()) { + return out; + } + + auto rows = std::vector>(); + size_t width = 0; + for (const auto& arg : _args) { + rows.emplace_back(usage_arg_to_string(arg, ", "), usage_help_text(arg)); + width = std::max(width, rows.back().first.size()); + } + + constexpr size_t indent = 2; + constexpr size_t gap = 2; + const auto continuation = '\n' + std::string(indent + width + gap, ' '); + out += "\nArguments:\n"; + for (const auto& [left, right] : rows) { + out += std::string(indent, ' ') + left; + if (!right.empty()) { + out += std::string(width - left.size() + gap, ' '); + for (size_t i = 0; i < right.size(); ++i) { + const char c = right[i]; + if (c == '\n') { + if (i + 1 < right.size() && right[i + 1] != '\n') { + out += continuation; + } else { + out += '\n'; + } + } else { + out += c; + } + } + } + out += '\n'; + } + return out; +} + +} // namespace internal + +/// Generates the usage line, and optionally a help text with one row per +/// argument, for the struct that `rfl::cli::read()` parses into. +/// It applies the same processors as `read`, so the names always match what +/// the parser accepts (kebab-case, rfl::Rename, rfl::Flatten, nested paths). +/// +/// The help text lists the description (rfl::Description), the allowed +/// values of enums and literals and whether the argument is required. +/// @tparam T The struct type that the arguments are parsed into +/// @tparam Ps The processors passed to `rfl::cli::read` +/// @param _program_name The name shown after "Usage:", usually argv[0] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline, or an error if no read of +/// T can succeed: two fields have the same short name, or T has a bare +/// rfl::DefaultVal and default-constructing it throws. +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using U = internal::unwrapped_option_t; + // The table that read() parses with, so the help shows what the parser + // accepts. + const auto options = internal::make_options(); + return internal::check_short_names(options).and_then( + [&](auto) -> rfl::Result { + try { + std::map meta; + if constexpr (internal::is_option_struct_v) { + using NamedTupleType = + internal::option_fields_t; + meta = internal::collect_usage_field_meta( + std::make_index_sequence{}); + } + // The schema takes the default values from a default-constructed + // T, which can throw. + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v); + return internal::format_usage(_program_name, args, _detailed); + } catch (const std::exception& e) { + return error(e.what()); + } + }); +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 1233f2f09..258adf8d4 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -1,7 +1,9 @@ #ifndef RFL_COMPARISONS_HPP_ #define RFL_COMPARISONS_HPP_ -#include +#include +#include +#include #include #include "Result.hpp" @@ -9,6 +11,46 @@ namespace rfl { +namespace internal { + +template +std::string format_comparison_value(const T& _val) { + if constexpr (std::is_floating_point_v) { + char buf[64]; + const int n = [&]() { + if constexpr (std::is_same_v) { + return std::snprintf(buf, sizeof(buf), "%Lg", _val); + } else { + return std::snprintf(buf, sizeof(buf), "%g", static_cast(_val)); + } + }(); + if (n <= 0) { + return {}; + } + const auto len = static_cast(n) < sizeof(buf) + ? static_cast(n) + : sizeof(buf) - 1; + return std::string(buf, len); + } else if constexpr (std::is_same_v) { + return std::string(1, _val); + } else if constexpr (std::is_enum_v) { + return std::to_string(static_cast>(_val)); + } else { + // signed char / unsigned char (int8_t / uint8_t) intentionally format as + // decimal integers via std::to_string rather than raw characters. + return std::to_string(_val); + } +} + +template +std::string comparison_error_message(const char* _prefix, const T& _threshold, + const T& _value) { + return std::string(_prefix) + format_comparison_value(_threshold) + + ", but got " + format_comparison_value(_value) + "."; +} + +} // namespace internal + template struct EqualTo { /// @brief Validates that the given value is equal to the threshold. @@ -22,10 +64,8 @@ struct EqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value != threshold) { - std::stringstream stream; - stream << "Value expected to be equal to " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be equal to ", threshold, _value)); } return _value; } @@ -61,10 +101,8 @@ struct Minimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value < threshold) { - std::stringstream stream; - stream << "Value expected to be greater than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than or equal to ", threshold, _value)); } return _value; } @@ -100,10 +138,8 @@ struct ExclusiveMinimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value <= threshold) { - std::stringstream stream; - stream << "Value expected to be greater than " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than ", threshold, _value)); } return _value; } @@ -139,10 +175,8 @@ struct Maximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value > threshold) { - std::stringstream stream; - stream << "Value expected to be less than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than or equal to ", threshold, _value)); } return _value; } @@ -177,10 +211,8 @@ struct ExclusiveMaximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value >= threshold) { - std::stringstream stream; - stream << "Value expected to be less than " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than ", threshold, _value)); } return _value; } @@ -215,10 +247,8 @@ struct NotEqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value == threshold) { - std::stringstream stream; - stream << "Value expected not to be equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected not to be equal to ", threshold, _value)); } return _value; } diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..46c16df1e 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -1,10 +1,19 @@ #ifndef RFL_ENUMS_HPP_ #define RFL_ENUMS_HPP_ -#include +#include +#include #include +#include +#include +#include +#include +#include "EnumNames.hpp" +#include "Processors.hpp" #include "Result.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" #include "internal/enums/get_enum_range.hpp" @@ -52,94 +61,262 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// Converts an enum value to tis string representation. -template -std::string enum_to_string(const EnumType _enum) { - if constexpr (internal::enums::is_flag_enum) { +namespace internal { + +template +std::vector>> +build_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back( + resolve_enum_wire_name_for_transform(val, raw_name), + val); + } + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [val, wire] : get_enum_overrides()) { + bool already_present = false; + for (const auto& entry : out) { + if (entry.second == val) { + already_present = true; + break; + } + } + if (!already_present) { + out.emplace_back(std::string(wire), val); + } + } + } + return out; +} + +template +const std::vector>>& +get_cached_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kTable = build_enum_wire_names_with_transform(); + return kTable; +} + +template +const std::vector>>& +get_cached_unique_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kUnique = []() { + std::vector> out; + const auto& all = get_cached_enum_wire_names_with_transform(); + out.reserve(all.size()); + for (const auto& entry : all) { + bool dup = false; + for (const auto& existing : out) { + if (existing.first == entry.first) { + dup = true; + break; + } + } + if (!dup) { + out.push_back(entry); + } + } + return out; + }(); + return kUnique; +} + +template +std::string enum_to_single_wire_name(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (val == _enum) { + return wire; + } + } + return std::to_string(static_cast>(_enum)); + } else { + return internal::enums::to_string(_enum); + } +} + +template +std::string enum_to_string_with_transform(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (internal::enums::is_flag_enum) { // Iterates through the enum bit by bit and matches it against the flags. - using T = std::underlying_type_t; + using T = std::underlying_type_t; auto val = static_cast(_enum); int i = 0; std::vector flags; while (val != 0) { const auto bit = val & static_cast(1); if (bit == 1) { - auto str = internal::enums::to_string( - static_cast(static_cast(1) << i)); + auto str = enum_to_single_wire_name( + static_cast(static_cast(1) << i)); flags.emplace_back(std::move(str)); } ++i; val >>= 1; } if (flags.empty()) { - return internal::enums::to_string(static_cast(0)); + return enum_to_single_wire_name(static_cast(0)); } return internal::strings::join("|", flags); } else { - return internal::enums::to_string(_enum); + return enum_to_single_wire_name(_enum); } } -// Converts a string to a value of the given enum type. -// -// By default, numeric values are accepted in addition to the declared -// enumerator names, even when they do not correspond to a declared -// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 -// will produce the cast value 4). Pass enum_names_only = true (or use the -// EnumNamesOnly processor with a parser) to accept only the declared -// enumerator names instead. -template -Result string_to_enum(const std::string& _str) { - const auto make_error_msg = [&](const auto& name) { +template +Result> string_to_enum_with_transform( + const std::string_view _str) { + using E = std::remove_cvref_t; + const auto make_error_msg = [](const std::string_view name) { std::string msg = "Invalid enum value: '"; msg += name; msg += "'. Must be one of ["; const char* sep = ""; - for (const auto& p : get_enumerator_array()) { - msg += sep; - msg += p.first; - sep = ", "; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& p : + get_cached_unique_enum_wire_names_with_transform()) { + msg += sep; + msg += p.first; + sep = ", "; + } + } else { + for (const auto& p : get_enumerator_array()) { + msg += sep; + msg += p.first; + sep = ", "; + } } msg += "]."; return error(msg); }; const auto cast_numbers_or_names = - [&](const std::string& name) -> Result { - const auto r = internal::enums::from_string(name); - if (r) { - return *r; + [&](const std::string_view name) -> Result { + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (wire == name) { + return val; + } + } + } else { + const auto r = internal::enums::from_string(name); + if (r) { + return *r; + } } if constexpr (enum_names_only) { return make_error_msg(name); } else { - try { - const auto val = std::stoi(name); - return static_cast(val); - } catch (std::exception& exp) { + if (name.empty()) { return make_error_msg(name); } + using Underlying = std::underlying_type_t; + using ParseType = std::conditional_t< + (sizeof(Underlying) < sizeof(int)), int, + std::conditional_t< + std::is_signed_v, + std::conditional_t< + (sizeof(Underlying) <= sizeof(int)), int, + std::conditional_t<(sizeof(Underlying) <= sizeof(long)), long, + long long>>, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned int)), unsigned int, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned long)), + unsigned long, unsigned long long>>>>; + ParseType val{}; + const auto* begin = name.data(); + const auto* end = begin + name.size(); + const auto [ptr, ec] = std::from_chars(begin, end, val); + if (ec == std::errc{} && ptr == end) { + return static_cast(val); + } + return make_error_msg(name); } }; - if constexpr (internal::enums::is_flag_enum) { - using T = std::underlying_type_t; - const auto split = internal::strings::split(_str, "|"); + if constexpr (internal::enums::is_flag_enum) { + using T = std::underlying_type_t; auto res = static_cast(0); - for (const auto& s : split) { - const auto r = cast_numbers_or_names(s); - if (r) { - res |= static_cast(*r); - } else { + std::string_view remaining = _str; + while (true) { + const auto pos = remaining.find('|'); + const auto token = remaining.substr(0, pos); + const auto r = cast_numbers_or_names(token); + if (!r) { return r; } + res |= static_cast(*r); + if (pos == std::string_view::npos) { + break; + } + remaining.remove_prefix(pos + 1); } - return static_cast(res); + return static_cast(res); } else { return cast_numbers_or_names(_str); } } +template +Result> string_to_enum_with_transform_noexcept( + const std::string_view _str) noexcept { + try { + return string_to_enum_with_transform( + _str); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception thrown while parsing enum value."); + } +} + +} // namespace internal + +// Converts an enum value to its wire string representation, honoring +// `rfl::EnumNames` and any `rfl::TransformEnumNames<...>` processor +// passed in `Ps...`. +template +std::string enum_to_string(const EnumType _enum) { + return internal::enum_to_string_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(_enum); +} + +// Returns all declared enumerators (plus any explicit `rfl::EnumNames` +// overrides for values outside the reflected range) paired with their resolved +// wire names. +template +std::vector>> +get_enum_wire_names() { + return internal::get_cached_enum_wire_names_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(); +} + +// Converts a string to a value of the given enum type. +// +// By default, numeric values are accepted in addition to the declared +// enumerator names, even when they do not correspond to a declared +// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 +// will produce the cast value 4). Pass enum_names_only = true (or use the +// EnumNamesOnly processor with a parser) to accept only the declared +// enumerator names instead. +template +Result> string_to_enum( + const std::string_view _str) noexcept { + return internal::string_to_enum_with_transform_noexcept< + std::remove_cvref_t, enum_names_only, + internal::enum_name_transform_v>>(_str); +} + } // namespace rfl #endif // RFL_ENUMS_HPP_ diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..b87690baa 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -170,14 +171,13 @@ struct Reader { /// @param _var The ENV variable to check /// @return true if the variable is empty, false otherwise bool is_empty(const InputVarType& _var) const noexcept { - const auto str = std::getenv(_var.path.c_str()); - if (str != nullptr) { - return false; - } if (_var.path.empty()) { return true; } - const auto prefix = _var.path.empty() ? std::string("") : _var.path + "_"; + if (has_env_var(_var.path.c_str())) { + return false; + } + const auto prefix = _var.path + "_"; for (char** env = get_environ(); *env != nullptr; ++env) { const std::string env_entry(*env); if (env_entry.size() <= prefix.size()) { @@ -304,14 +304,41 @@ struct Reader { } private: + static bool has_env_var(const char* _name) noexcept { + if (_name == nullptr || *_name == '\0') { + return false; + } +#ifdef _MSC_VER + std::size_t required_size = 0; + return ::getenv_s(&required_size, nullptr, 0, _name) == 0 && + required_size > 0; +#else + return std::getenv(_name) != nullptr; +#endif + } + static std::optional get_value( const InputVarType& _var) noexcept { + if (_var.path.empty()) { + return std::nullopt; + } +#ifdef _MSC_VER + char* env_value = nullptr; + if (::_dupenv_s(&env_value, nullptr, _var.path.c_str()) == 0 && + env_value != nullptr) { + std::string result(env_value); + std::free(env_value); + return result; + } + return std::nullopt; +#else const char* env_value = std::getenv(_var.path.c_str()); if (env_value) { return std::string(env_value); } else { return std::nullopt; } +#endif } }; diff --git a/include/rfl/env/Writer.hpp b/include/rfl/env/Writer.hpp index 23512bb72..d0d505fd4 100644 --- a/include/rfl/env/Writer.hpp +++ b/include/rfl/env/Writer.hpp @@ -56,7 +56,7 @@ class RFL_API Writer { } template - OutputVarType value_as_root(const T& _var) const noexcept { + OutputVarType value_as_root(const T&) const noexcept { static_assert( always_false_v, "Writing basic types to ENV as root variables is not supported."); diff --git a/include/rfl/internal/StringLiteral.hpp b/include/rfl/internal/StringLiteral.hpp index 56a64e108..c8bf5d1e9 100644 --- a/include/rfl/internal/StringLiteral.hpp +++ b/include/rfl/internal/StringLiteral.hpp @@ -1,68 +1,11 @@ #ifndef RFL_INTERNAL_STRINGLITERAL_HPP_ #define RFL_INTERNAL_STRINGLITERAL_HPP_ -#include -#include -#include -#include -#include +#include "../StringLiteral.hpp" namespace rfl::internal { -/// Normal strings cannot be used as template -/// parameters, but this can. This is needed -/// for the parameters names in the NamedTuples. -template -struct StringLiteral { - /// Constrained via template type parameters rather than a requires-fold - /// over decltype of the function parameter pack: the latter crashes - /// clang 21/22 in C++26 mode (llvm/llvm-project#198052, #205000). - template ... Chars> - constexpr StringLiteral(const Chars... _chars) : arr_{_chars..., '\0'} {} - - constexpr StringLiteral(const std::array _arr) : arr_(_arr) {} - - constexpr StringLiteral(const char (&_str)[N]) { - std::copy_n(_str, N, std::data(arr_)); - } - - constexpr StringLiteral(const std::string_view _str) { - std::copy_n(_str.data(), _str.size(), std::data(arr_)); - } - - template - requires(std::is_same_v || std::is_same_v) - explicit constexpr StringLiteral(T _data) { - std::copy_n(_data, N, std::data(arr_)); - } - - /// Returns the value as a string. - std::string str() const { return std::string(string_view()); } - - /// Returns the value as a string. - constexpr std::string_view string_view() const { - return std::string_view(std::data(arr_), N - 1); - } - - static constexpr size_t length = N - 1; - - std::array arr_{}; -}; - -template -constexpr inline bool operator==(const StringLiteral& _first, - const StringLiteral& _second) { - if constexpr (N1 != N2) { - return false; - } - return _first.string_view() == _second.string_view(); -} - -template -constexpr inline bool operator!=(const StringLiteral& _first, - const StringLiteral& _second) { - return !(_first == _second); -} +using rfl::StringLiteral; } // namespace rfl::internal diff --git a/include/rfl/internal/bind_to_tuple.hpp b/include/rfl/internal/bind_to_tuple.hpp index b6a578c34..49e7333d9 100644 --- a/include/rfl/internal/bind_to_tuple.hpp +++ b/include/rfl/internal/bind_to_tuple.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_BIND_TO_TUPLE_HPP_ #define RFL_INTERNAL_BIND_TO_TUPLE_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/bind_to_tuple.hpp" #else @@ -9,6 +11,15 @@ namespace rfl::internal { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + return cpp20::apply_to_fields(_t, std::forward(_f)); +#else + return cpp26::apply_to_fields(_t, std::forward(_f)); +#endif +} + template auto bind_to_tuple(T& _t) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION diff --git a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp index 5f3a13926..32a30e737 100644 --- a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp +++ b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp @@ -10,21 +10,15 @@ namespace rfl::internal { -template -auto copy_one_element(const auto& _flattened_tuple) { - const auto name_literal = FieldNames::template name_of<_i>(); - return rfl::make_field< - lit_name_v>>( - std::get<_i>(_flattened_tuple)); -} - template auto copy_flattened_tuple_to_named_tuple(const auto& _flattened_tuple) { constexpr auto size = rfl::tuple_size_v>; return [&](std::integer_sequence) { return make_named_tuple( - copy_one_element(_flattened_tuple)...); + rfl::make_field())>>>( + std::get<_i>(_flattened_tuple))...); }(std::make_integer_sequence()); } diff --git a/include/rfl/internal/cpp20/Result.hpp b/include/rfl/internal/cpp20/Result.hpp index fb436bedb..00436331f 100644 --- a/include/rfl/internal/cpp20/Result.hpp +++ b/include/rfl/internal/cpp20/Result.hpp @@ -2,7 +2,6 @@ #define RFL_INTERNAL_CPP20_RESULT_HPP_ #include -#include #include #include #include @@ -60,7 +59,9 @@ template class Result { static_assert(!std::is_same(), "The result type cannot be Error."); - using TOrErr = std::array; + using TOrErr = + std::array sizeof(Error) ? sizeof(T) : sizeof(Error))>; public: using value_type = T; @@ -555,7 +556,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, std::move(*this).get_err())}; + return Result{std::forward(f)(std::move(*this).get_err())}; } else { return Result{std::move(*this).value()}; } @@ -584,7 +585,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, get_err())}; + return Result{std::forward(f)(get_err())}; } else { return Result{value()}; } @@ -681,7 +682,8 @@ class Result { bool success_; /// The underlying data, can either be T or Error. - alignas(std::max(alignof(T), alignof(Error))) TOrErr t_or_err_; + alignas((alignof(T) > alignof(Error) ? alignof(T) + : alignof(Error))) TOrErr t_or_err_; }; } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/bind_to_tuple.hpp b/include/rfl/internal/cpp20/bind_to_tuple.hpp index 9733f1dbe..218e34c70 100644 --- a/include/rfl/internal/cpp20/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp20/bind_to_tuple.hpp @@ -5,6 +5,7 @@ #include #include +#include #include #include "../../Tuple.hpp" @@ -16,14 +17,14 @@ namespace rfl::internal::cpp20 { #define RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS( \ n, ...) \ auto& [__VA_ARGS__] = _t; \ - return [](auto&... _refs) { return rfl::make_tuple(&_refs...); }(__VA_ARGS__); + return std::forward(_f)(__VA_ARGS__); // The following boilerplate code has been generated with -// scripts/bind_to_tuple_impl.py -template -auto bind_to_tuple_impl(auto& _t) { +// scripts/bind_to_tuple.py +template +decltype(auto) apply_to_fields_impl(T& _t, F&& _f) { if constexpr (_num_fields == 0) { - return rfl::make_tuple(); + return std::forward(_f)(); } else { if constexpr (_num_fields < 129) { if constexpr (_num_fields < 65) { @@ -4384,9 +4385,16 @@ auto bind_to_tuple_impl(auto& _t) { #undef RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { + return cpp20::apply_to_fields_impl>>( + _t, std::forward(_f)); +} + template auto bind_to_tuple(T& _t) { - return bind_to_tuple_impl>(_t); + return cpp20::apply_to_fields( + _t, [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/num_fields.hpp b/include/rfl/internal/cpp20/num_fields.hpp index 3864336e1..b2931518d 100644 --- a/include/rfl/internal/cpp20/num_fields.hpp +++ b/include/rfl/internal/cpp20/num_fields.hpp @@ -98,15 +98,60 @@ struct CountFieldsHelper { } template - static consteval std::size_t count_max_args_in_agg_init() { - static_assert(n <= static_cast(sizeof(T))); - if constexpr (constructible() && !constructible()) { + static consteval std::size_t find_first_constructible() { + if constexpr (constructible()) { return n; + } else if constexpr (n < static_cast(sizeof(T))) { + return find_first_constructible(); } else { - return count_max_args_in_agg_init(); + static_assert(n < static_cast(sizeof(T)), + "Type is not aggregate-constructible; rfl::num_fields " + "requires an aggregate type."); + return 0; } } + template + static consteval std::size_t binary_search_max() { + if constexpr (lo + 1 >= hi) { + return lo; + } else { + constexpr std::size_t mid = lo + (hi - lo) / 2; + if constexpr (constructible()) { + return binary_search_max(); + } else { + return binary_search_max(); + } + } + } + + template + static consteval std::size_t expand_and_search() { + static_assert(lo <= static_cast(sizeof(T))); + constexpr std::size_t max_possible = static_cast(sizeof(T)); + constexpr std::size_t probe = + (step > max_possible - lo) ? (max_possible + 1) : (lo + step); + if constexpr (probe <= max_possible && constructible()) { + return expand_and_search(); + } else if constexpr (probe > max_possible && constructible()) { + static_assert(probe <= max_possible, + "Type is constructible with more arguments than sizeof(T); " + "rfl::num_fields requires an aggregate type."); + return max_possible; + } else { + return binary_search_max(); + } + } + + static consteval std::size_t count_max_args_in_agg_init() { + // Once constructible() holds, constructible() is monotone + // non-increasing for k >= first (every trailing member from `first` onward + // is default-initializable), so exponential + binary search finds the + // exact maximum in O(log N) SFINAE evaluations instead of O(N). + constexpr std::size_t first = find_first_constructible<0>(); + return expand_and_search(); + } + template static consteval std::size_t get_nested_array_size() { if constexpr (size < 1) { diff --git a/include/rfl/internal/cpp26/bind_to_tuple.hpp b/include/rfl/internal/cpp26/bind_to_tuple.hpp index e98f3f2c8..050e7208c 100644 --- a/include/rfl/internal/cpp26/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp26/bind_to_tuple.hpp @@ -8,18 +8,26 @@ #include #include #include +#include +#include #include "../../Tuple.hpp" #include "get_members.hpp" namespace rfl::internal::cpp26 { -template -auto bind_to_tuple(T& _t) { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { using Type = std::remove_cvref_t; constexpr auto members = std::define_static_array(get_members()); constexpr auto [... indices] = std::make_index_sequence(); - return rfl::make_tuple(&_t.[:members[indices]:]...); + return std::forward(_f)(_t.[:members[indices]:]...); +} + +template +auto bind_to_tuple(T& _t) { + return cpp26::apply_to_fields( + _t, [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp26 diff --git a/include/rfl/internal/enum_name_transform_v.hpp b/include/rfl/internal/enum_name_transform_v.hpp new file mode 100644 index 000000000..7c4249bdd --- /dev/null +++ b/include/rfl/internal/enum_name_transform_v.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ +#define RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ + +#include + +#include "../Processors.hpp" +#include "../TransformEnumNames.hpp" + +namespace rfl::internal { + +template +struct enum_name_transform_from_processors { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = _t; +}; + +template <> +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform head_val = + enum_name_transform_from_processors< + std::remove_cvref_t>>::value; + static constexpr EnumNameTransform tail_val = + enum_name_transform_from_processors>::value; + static_assert(head_val == EnumNameTransform::none || + tail_val == EnumNameTransform::none || + head_val == tail_val, + "Conflicting rfl::TransformEnumNames processors cannot be " + "combined."); + static constexpr EnumNameTransform value = + head_val != EnumNameTransform::none ? head_val : tail_val; +}; + +template +inline constexpr EnumNameTransform enum_name_transform_v = + enum_name_transform_from_processors< + std::remove_cvref_t>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ diff --git a/include/rfl/internal/enums/cpp20/from_string.hpp b/include/rfl/internal/enums/cpp20/from_string.hpp index b14315964..1d1cec7de 100644 --- a/include/rfl/internal/enums/cpp20/from_string.hpp +++ b/include/rfl/internal/enums/cpp20/from_string.hpp @@ -3,15 +3,14 @@ #ifndef REFLECTCPP_USE_CPP26_REFLECTION -#include -#include +#include #include "enchantum.hpp" // NOLINT(unused-includes) namespace rfl::internal::enums::cpp20 { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { return enchantum::cast(_str); } diff --git a/include/rfl/internal/enums/cpp26/from_string.hpp b/include/rfl/internal/enums/cpp26/from_string.hpp index 919be47c6..1f4698529 100644 --- a/include/rfl/internal/enums/cpp26/from_string.hpp +++ b/include/rfl/internal/enums/cpp26/from_string.hpp @@ -5,13 +5,13 @@ #include #include -#include +#include #include namespace rfl::internal::enums::cpp26 { template -std::optional from_string(const std::string& _str) { +std::optional from_string(const std::string_view _str) { template for (constexpr auto e : std::define_static_array( std::meta::enumerators_of(^^EnumType))) { if (_str == std::meta::identifier_of(e)) { diff --git a/include/rfl/internal/enums/from_string.hpp b/include/rfl/internal/enums/from_string.hpp index 160363283..c966f6d36 100644 --- a/include/rfl/internal/enums/from_string.hpp +++ b/include/rfl/internal/enums/from_string.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ #define RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/from_string.hpp" #else @@ -10,7 +12,7 @@ namespace rfl::internal::enums { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION return cpp20::from_string(_str); #else diff --git a/include/rfl/internal/find_index.hpp b/include/rfl/internal/find_index.hpp index 04c524e7d..c962ae5e6 100644 --- a/include/rfl/internal/find_index.hpp +++ b/include/rfl/internal/find_index.hpp @@ -25,7 +25,7 @@ constexpr auto operator|(const FieldWrapper& _f1, template constexpr auto find_matching_field(const Head& _head, const Tail&... _tail) { return (_head | ... | _tail); -}; +} template constexpr auto wrap_fields(std::integer_sequence) { diff --git a/include/rfl/internal/has_default_val_v.hpp b/include/rfl/internal/has_default_val_v.hpp index 1d19ef96b..c47ca0cae 100644 --- a/include/rfl/internal/has_default_val_v.hpp +++ b/include/rfl/internal/has_default_val_v.hpp @@ -2,44 +2,85 @@ #define RFL_HASDEFAULTVALV_HPP_ #include +#include #include +#include -#include "../NamedTuple.hpp" -#include "../named_tuple_t.hpp" +#include "bind_to_tuple.hpp" #include "is_default_val_v.hpp" +#include "is_field.hpp" +#include "is_flatten_field.hpp" -namespace rfl::internal { +namespace rfl { -template -struct HasDefaultVal; +template +class NamedTuple; + +namespace internal { template struct HasDefaultVal { static constexpr bool value = false; }; +// NamedTupleParser invokes has_default_val_v on view NamedTuples whose fields +// hold pointers to the original members (e.g. Field*>), so +// this specialization intentionally strips one pointer level. template struct HasDefaultVal> { static constexpr bool value = (false || ... || - is_default_val_v< - std::remove_cvref_t>>); + is_default_val>>::value); }; template - requires(std::is_class_v && std::is_aggregate_v) -struct HasDefaultVal : HasDefaultVal> {}; +struct is_named_tuple_spec : std::false_type {}; + +template +struct is_named_tuple_spec> : std::true_type {}; + +template +constexpr bool has_default_val_field() { + using U = std::remove_cvref_t; + if constexpr (is_field::value) { + return is_default_val>::value; + } else if constexpr (is_flatten_field::value) { + return HasDefaultVal< + std::remove_cvref_t>>::value; + } else { + return is_default_val::value; + } +} + +struct HasDefaultValVisitor { + template + constexpr auto operator()(Fields&...) const noexcept + -> std::bool_constant<(false || ... || + has_default_val_field())> { + return {}; + } +}; + +template + requires(!is_named_tuple_spec::value && std::is_class_v && + std::is_aggregate_v) +struct HasDefaultVal { + static constexpr bool value = decltype(rfl::internal::apply_to_fields( + std::declval(), HasDefaultValVisitor{}))::value; +}; -template +template struct HasDefaultVal> : HasDefaultVal> { }; -template +template struct HasDefaultVal : HasDefaultVal> {}; template constexpr bool has_default_val_v = HasDefaultVal>::value; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/internal/integer_bounds_v.hpp b/include/rfl/internal/integer_bounds_v.hpp new file mode 100644 index 000000000..45651d293 --- /dev/null +++ b/include/rfl/internal/integer_bounds_v.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ +#define RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ + +#include + +#include "../IntegerBounds.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct integer_bounds : std::false_type {}; + +template <> +struct integer_bounds : std::true_type {}; + +template +struct integer_bounds> + : std::bool_constant< + (integer_bounds>::value || ...)> {}; + +template +inline constexpr bool integer_bounds_v = + integer_bounds>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ diff --git a/include/rfl/internal/move_from_tuple.hpp b/include/rfl/internal/move_from_tuple.hpp index c5edf9043..3855f7741 100644 --- a/include/rfl/internal/move_from_tuple.hpp +++ b/include/rfl/internal/move_from_tuple.hpp @@ -44,7 +44,7 @@ struct IndptrHelper { static constexpr auto indptr_ = ArrayType{_head, _tail...}; template - consteval auto operator+(const IndptrHelper<_is...>& _other) const { + consteval auto operator+(const IndptrHelper<_is...>&) const { constexpr auto last = std::get(indptr_); return IndptrHelper<_head, _tail..., (last + _is)...>{}; } diff --git a/include/rfl/internal/nth_element.hpp b/include/rfl/internal/nth_element.hpp index 281e5968c..c5c5c9c77 100644 --- a/include/rfl/internal/nth_element.hpp +++ b/include/rfl/internal/nth_element.hpp @@ -23,7 +23,7 @@ constexpr auto operator|(const ElementWrapper& _e1, template constexpr auto find_matching_element(const Head& _head, const Tail&... _tail) { return (_head | ... | _tail); -}; +} template constexpr auto wrap_elements(Ts... _ts, std::integer_sequence) { diff --git a/include/rfl/internal/strings/utf8_conversions.hpp b/include/rfl/internal/strings/utf8_conversions.hpp index dc24923f4..7be5e57e5 100644 --- a/include/rfl/internal/strings/utf8_conversions.hpp +++ b/include/rfl/internal/strings/utf8_conversions.hpp @@ -46,7 +46,8 @@ inline std::optional decode_utf8(const std::string& _str) { return std::nullopt; // truncated multi-byte sequence } for (int k = 1; k <= extra; ++k) { - const auto cc = static_cast(_str[i + k]); + const auto cc = + static_cast(_str[i + static_cast(k)]); if ((cc >> 6) != 0x2) { return std::nullopt; // bad continuation byte } diff --git a/include/rfl/internal/variants_as_one_of_v.hpp b/include/rfl/internal/variants_as_one_of_v.hpp new file mode 100644 index 000000000..c03d42f20 --- /dev/null +++ b/include/rfl/internal/variants_as_one_of_v.hpp @@ -0,0 +1,62 @@ +#ifndef RFL_INTERNAL_VARIANTSASONEOF_HPP_ +#define RFL_INTERNAL_VARIANTSASONEOF_HPP_ + +#include + +#include "../Processors.hpp" +#include "../VariantsAsOneOf.hpp" + +namespace rfl::internal { + +template +struct variants_as_one_of : std::false_type {}; + +template <> +struct variants_as_one_of : std::true_type {}; + +template +struct variants_as_one_of> + : std::bool_constant< + (variants_as_one_of>::value || ...)> {}; + +template +inline constexpr bool variants_as_one_of_v = + variants_as_one_of>::value; + +template +struct concat_processors; + +template +struct concat_processors, Processors> { + using type = Processors; +}; + +template +struct remove_variants_as_one_of { + using type = Processors; +}; + +template <> +struct remove_variants_as_one_of { + using type = Processors<>; +}; + +template <> +struct remove_variants_as_one_of> { + using type = Processors<>; +}; + +template +struct remove_variants_as_one_of> { + using type = typename concat_processors< + typename remove_variants_as_one_of>::type, + typename remove_variants_as_one_of>::type>::type; +}; + +template +using remove_variants_as_one_of_t = + typename remove_variants_as_one_of>::type; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index cac6b0e23..a42bd82fa 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -3,6 +3,7 @@ #include "../rfl.hpp" #include "json/Parser.hpp" +#include "json/Raw.hpp" #include "json/Reader.hpp" #include "json/Writer.hpp" #include "json/load.hpp" diff --git a/include/rfl/json/Raw.hpp b/include/rfl/json/Raw.hpp new file mode 100644 index 000000000..7543c1bad --- /dev/null +++ b/include/rfl/json/Raw.hpp @@ -0,0 +1,161 @@ +#ifndef RFL_JSON_RAW_HPP_ +#define RFL_JSON_RAW_HPP_ + +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../common.hpp" +#include "../generic/Reader.hpp" +#include "../generic/Writer.hpp" +#include "../parsing/AreReaderAndWriter.hpp" +#include "../parsing/Parent.hpp" +#include "../parsing/Parser.hpp" +#include "../parsing/schema/Type.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl::json { + +/// Holds a raw JSON value for passthrough serialization and deserialization +/// without converting into intermediate C++ structures. +/// +/// Note on reading vs. writing: +/// - Writing emits the stored JSON text verbatim via `yyjson_mut_rawncpy` +/// without re-parsing. Construct with `Raw::from_string()` so malformed or +/// non-RFC-8259 JSON is rejected up front, or use `Raw::from_trusted_string()` +/// only for already-validated JSON text (e.g., output of `rfl::json::write`). +/// - Reading captures the parsed yyjson subtree via `yyjson_val_write_opts` with +/// strict RFC 8259 formatting (flag 0), which canonicalizes whitespace and +/// rejects non-standard values such as `NaN`/`Infinity`. Pass +/// `YYJSON_READ_BIGNUM_AS_RAW` to `rfl::json::read` if you need integers +/// wider than 64 bits preserved verbatim. +class RFL_API Raw { + public: + Raw() = default; + + /// Validates that `_str` contains a single strict RFC 8259 JSON value and + /// constructs a `Raw` holding `_str` verbatim. + static Result from_string(std::string_view _str); + + /// Constructs a `Raw` from pre-validated JSON text without re-parsing. + /// Empty input becomes `"null"`. Caller must guarantee `_value` is valid + /// RFC 8259 JSON with no embedded NUL bytes. + static Raw from_trusted_string(const std::string_view _value) { + return Raw(_value.empty() ? std::string("null") : std::string(_value)); + } + + template + requires std::is_same_v + static Raw from_trusted_string(T&& _value) { + return Raw(_value.empty() ? std::string("null") : std::move(_value)); + } + + const std::string& str() const noexcept { return value_; } + + const std::string& value() const noexcept { return value_; } + + const std::string& get() const noexcept { return value_; } + + const std::string& operator*() const noexcept { return value_; } + + const std::string& operator()() const noexcept { return value_; } + + const char* c_str() const noexcept { return value_.c_str(); } + + bool operator==(const Raw&) const = default; + + static Result from_json_obj(const Reader::YYJSONInputVar& _var); + + /// Parses the stored raw JSON text into an `rfl::Generic`. + Result to_generic() const; + + /// Serializes an `rfl::Generic` into an `rfl::json::Raw`. + static Result from_generic(const Generic& _g) noexcept; + + private: + explicit Raw(std::string _value) : value_(std::move(_value)) {} + + std::string value_{"null"}; +}; + +} // namespace rfl::json + +namespace rfl::parsing { + +template + requires AreReaderAndWriter +struct Parser { + static_assert( + always_false_v, + "rfl::json::Raw is only supported with rfl::json and rfl::Generic."); +}; + +template + requires AreReaderAndWriter +struct Parser { + public: + using InputVarType = typename json::Reader::InputVarType; + using ParentType = Parent; + + static Result read(const json::Reader& _r, + const InputVarType& _var) noexcept { + return _r.template use_custom_constructor(_var); + } + + template + static void write(const json::Writer& _w, const json::Raw& _raw, + const P& _parent) { + using Type = std::remove_cvref_t

; + if constexpr (std::is_same_v) { + _w.add_raw_to_array(_raw.str(), _parent.arr_); + } else if constexpr (std::is_same_v) { + _w.add_raw_to_object(_parent.name_, _raw.str(), _parent.obj_); + } else if constexpr (std::is_same_v) { + _w.raw_as_root(_raw.str()); + } else { + static_assert(always_false_v, "Unsupported parent type."); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +template + requires AreReaderAndWriter +struct Parser { + public: + using InputVarType = typename generic::Reader::InputVarType; + + static Result read(const generic::Reader&, + const InputVarType& _var) noexcept { + return json::Raw::from_generic(_var); + } + + template + static void write(const generic::Writer& _w, const json::Raw& _raw, + const P& _parent) { + const auto g = _raw.to_generic().value(); + Parser::write( + _w, g, _parent); + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index fe4c576b3..9ea6d340e 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -185,15 +185,23 @@ struct Reader { return static_cast(value); } else if constexpr (std::is_integral>()) { - if (!yyjson_is_int(_var.val_)) { + using Target = std::remove_cvref_t; + if (yyjson_is_uint(_var.val_)) { + const auto value = yyjson_get_uint(_var.val_); + if (value > static_cast(std::numeric_limits::max())) { + return error("Integer is out of range for the target type."); + } + return static_cast(value); + } + if (!yyjson_is_sint(_var.val_)) { return error("Could not cast to int."); } const auto value = yyjson_get_sint(_var.val_); - if (value < std::numeric_limits>::min() || - value > std::numeric_limits>::max()) { + if (value < std::numeric_limits::min() || + value > std::numeric_limits::max()) { return error("Integer is out of range for the target type."); } - return static_cast(value); + return static_cast(value); } else { static_assert(rfl::always_false_v, "Unsupported type."); diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index 7530ea98c..9748279a5 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -81,6 +81,12 @@ class RFL_API Writer { /// @return An output variable representing null OutputVarType null_as_root() const noexcept; + /// Creates a raw JSON value as the root element of the output. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to write + /// @return An output variable representing the raw JSON value + OutputVarType raw_as_root(const std::string_view& _str) const noexcept; + /// Creates a value as the root element of the output. /// Supports basic types like strings, numbers, and booleans. /// @tparam T The type of the value to serialize @@ -177,6 +183,26 @@ class RFL_API Writer { OutputVarType add_null_to_object(const std::string_view& _name, OutputObjectType* _parent) const; + /// Adds a raw JSON value to a parent array. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent array to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the value cannot be added + OutputVarType add_raw_to_array(const std::string_view& _str, + OutputArrayType* _parent) const; + + /// Adds a raw JSON value to a parent object with the specified field name. + /// Emits null if _str is empty. + /// @param _name The name of the field in the parent object + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent object to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the field cannot be added + OutputVarType add_raw_to_object(const std::string_view& _name, + const std::string_view& _str, + OutputObjectType* _parent) const; + /// Finalizes a JSON array after all elements have been added. /// This is a no-op for yyjson as arrays don't need explicit finalization. /// @param Pointer to the array (unused) diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index ad3e47b1e..94d7ef06a 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -18,6 +18,61 @@ namespace rfl { namespace json { +/// Stop after parsing the first JSON value instead of issuing an error if +/// trailing content follows. +inline constexpr yyjson_read_flag stop_when_done = YYJSON_READ_STOP_WHEN_DONE; + +/// Allow a single trailing comma at the end of an object or array. +inline constexpr yyjson_read_flag allow_trailing_commas = + YYJSON_READ_ALLOW_TRAILING_COMMAS; + +/// Allow C-style single-line (//) and multi-line (/* */) comments. +inline constexpr yyjson_read_flag allow_comments = YYJSON_READ_ALLOW_COMMENTS; + +/// Allow Inf/NaN numbers and literals (e.g. 1e999, NaN, inf, -Infinity). +inline constexpr yyjson_read_flag read_allow_inf_and_nan = + YYJSON_READ_ALLOW_INF_AND_NAN; + +/// Allow invalid UTF-8 byte sequences when parsing string values. +inline constexpr yyjson_read_flag read_allow_invalid_unicode = + YYJSON_READ_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 +/// Allow and skip a leading UTF-8 BOM before parsing. +/// Requires yyjson >= 0.11.0. +inline constexpr yyjson_read_flag allow_bom = YYJSON_READ_ALLOW_BOM; +#endif + +/// Convenience flag for JSONC (comments and trailing commas). +inline constexpr yyjson_read_flag jsonc = + allow_comments | allow_trailing_commas; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 +/// Allow extended number formats (hexadecimal, leading/trailing decimal point, +/// leading plus sign). Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_number = + YYJSON_READ_ALLOW_EXT_NUMBER; + +/// Allow extended escape sequences in strings. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_escape = + YYJSON_READ_ALLOW_EXT_ESCAPE; + +/// Allow extended whitespace characters. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_whitespace = + YYJSON_READ_ALLOW_EXT_WHITESPACE; + +/// Allow strings enclosed in single quotes. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_single_quoted_str = + YYJSON_READ_ALLOW_SINGLE_QUOTED_STR; + +/// Allow unquoted object keys. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_unquoted_key = + YYJSON_READ_ALLOW_UNQUOTED_KEY; + +/// Convenience flag for JSON5. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag json5 = YYJSON_READ_JSON5; +#endif + using InputObjectType = typename Reader::InputObjectType; using InputVarType = typename Reader::InputVarType; diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index b032c83b2..3416e335c 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -1,6 +1,7 @@ #ifndef RFL_JSON_SCHEMA_TYPE_HPP_ #define RFL_JSON_SCHEMA_TYPE_HPP_ +#include #include #include #include @@ -33,6 +34,8 @@ struct Type { struct Integer { Literal<"integer"> type{}; rfl::Flatten annotations{}; + std::optional minimum{}; + std::optional maximum{}; }; struct Number { diff --git a/include/rfl/json/write.hpp b/include/rfl/json/write.hpp index 88e762aff..c3a6fa7ca 100644 --- a/include/rfl/json/write.hpp +++ b/include/rfl/json/write.hpp @@ -1,7 +1,6 @@ #ifndef RFL_JSON_WRITE_HPP_ #define RFL_JSON_WRITE_HPP_ -#include #if __has_include() #include #else @@ -19,9 +18,41 @@ namespace rfl { namespace json { -/// Convenient alias for the YYJSON pretty flag +/// Write JSON pretty-printed with 4-space indentation. inline constexpr yyjson_write_flag pretty = YYJSON_WRITE_PRETTY; +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000700 +/// Write JSON pretty-printed with 2-space indentation. +/// Overrides `pretty` if both are set. Requires yyjson >= 0.7.0. +inline constexpr yyjson_write_flag pretty_two_spaces = + YYJSON_WRITE_PRETTY_TWO_SPACES; +#endif + +/// Escape non-ASCII Unicode characters as `\uXXXX` for ASCII-only output. +inline constexpr yyjson_write_flag escape_unicode = YYJSON_WRITE_ESCAPE_UNICODE; + +/// Escape forward slashes `/` as `\/`. +inline constexpr yyjson_write_flag escape_slashes = YYJSON_WRITE_ESCAPE_SLASHES; + +/// Write Inf and NaN numbers as `Infinity` and `NaN` literals (non-standard). +inline constexpr yyjson_write_flag write_allow_inf_and_nan = + YYJSON_WRITE_ALLOW_INF_AND_NAN; + +/// Write Inf and NaN numbers as `null`. +/// Overrides `write_allow_inf_and_nan` if both are set. +inline constexpr yyjson_write_flag inf_and_nan_as_null = + YYJSON_WRITE_INF_AND_NAN_AS_NULL; + +/// Allow invalid UTF-8 byte sequences when encoding string values. +inline constexpr yyjson_write_flag write_allow_invalid_unicode = + YYJSON_WRITE_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 +/// Append a trailing newline `\n` at the end of the JSON output. +/// Requires yyjson >= 0.9.0. +inline constexpr yyjson_write_flag newline_at_end = YYJSON_WRITE_NEWLINE_AT_END; +#endif + /// Returns a JSON string representation of the object. /// Uses compile-time reflection to serialize a C++ object to JSON format. /// @tparam Ps Processors to apply during serialization (transforms the data) diff --git a/include/rfl/nlohmann.hpp b/include/rfl/nlohmann.hpp new file mode 100644 index 000000000..d8d5a1a0f --- /dev/null +++ b/include/rfl/nlohmann.hpp @@ -0,0 +1,12 @@ +#ifndef RFL_NLOHMANN_HPP_ +#define RFL_NLOHMANN_HPP_ + +#include "../rfl.hpp" +#include "nlohmann/Parser.hpp" +#include "nlohmann/Reader.hpp" +#include "nlohmann/Writer.hpp" +#include "nlohmann/adl_serializer.hpp" +#include "nlohmann/read.hpp" +#include "nlohmann/write.hpp" + +#endif diff --git a/include/rfl/nlohmann/Parser.hpp b/include/rfl/nlohmann/Parser.hpp new file mode 100644 index 000000000..24c31d9f5 --- /dev/null +++ b/include/rfl/nlohmann/Parser.hpp @@ -0,0 +1,438 @@ +#ifndef RFL_NLOHMANN_PARSER_HPP_ +#define RFL_NLOHMANN_PARSER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../internal/base64.hpp" +#include "../parsing/AreReaderAndWriter.hpp" +#include "../parsing/Parent.hpp" +#include "../parsing/Parser.hpp" +#include "../parsing/schema/Type.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl::nlohmann { + +template +using Parser = + parsing::Parser, Writer, T, ProcessorsType>; + +namespace internal { + +/// Lossless conversion between distinct nlohmann::basic_json instantiations +/// (e.g., nlohmann::json <-> nlohmann::ordered_json). +template +TargetBasicJson convert_basic_json(const SourceBasicJson& _src) { + if (_src.is_null()) { + return TargetBasicJson(nullptr); + } + if (const auto* b = _src.template get_ptr< + const typename SourceBasicJson::boolean_t*>()) { + return TargetBasicJson( + static_cast(*b)); + } + if (const auto* u = _src.template get_ptr< + const typename SourceBasicJson::number_unsigned_t*>()) { + return TargetBasicJson( + static_cast(*u)); + } + if (const auto* i = _src.template get_ptr< + const typename SourceBasicJson::number_integer_t*>()) { + return TargetBasicJson( + static_cast(*i)); + } + if (const auto* f = _src.template get_ptr< + const typename SourceBasicJson::number_float_t*>()) { + return TargetBasicJson( + static_cast(*f)); + } + if (const auto* s = _src.template get_ptr< + const typename SourceBasicJson::string_t*>()) { + return TargetBasicJson( + typename TargetBasicJson::string_t(s->data(), s->size())); + } + if (_src.is_binary()) { + const auto& src_bin = _src.get_binary(); + typename TargetBasicJson::binary_t::container_type dst_bytes; + if constexpr (requires { dst_bytes.reserve(src_bin.size()); }) { + dst_bytes.reserve(src_bin.size()); + } + using DstByte = typename TargetBasicJson::binary_t::value_type; + for (const auto b : src_bin) { + dst_bytes.push_back(static_cast(b)); + } + if (src_bin.has_subtype()) { + return TargetBasicJson::binary(std::move(dst_bytes), src_bin.subtype()); + } + return TargetBasicJson::binary(std::move(dst_bytes)); + } + if (_src.is_array()) { + auto arr = TargetBasicJson::array(); + reserve_array(arr, _src.size()); + for (const auto& elem : _src) { + arr.push_back(convert_basic_json(elem)); + } + return arr; + } + if (_src.is_object()) { + auto obj = TargetBasicJson::object(); + reserve_object(obj, _src.size()); + for (auto it = _src.begin(); it != _src.end(); ++it) { + emplace_field(obj, + typename TargetBasicJson::string_t(it.key().data(), + it.key().size()), + convert_basic_json(it.value())); + } + return obj; + } + return TargetBasicJson(nullptr); +} + +// Detects rfl::json::Reader via dependent ADL so compiles +// without or yyjson.h. +template +concept IsYYJSONReader = requires(const typename R::InputVarType& v) { + { yyjson_is_null(v.val_) } -> std::convertible_to; + { yyjson_is_uint(v.val_) } -> std::convertible_to; + { yyjson_get_uint(v.val_) } -> std::convertible_to; + { yyjson_get_sint(v.val_) } -> std::convertible_to; +}; + +// Detects rfl::xml::Reader without including or pugixml. +template +concept IsXMLReader = requires(const typename R::InputVarType& v) { + v.node_or_attribute_; +}; + +// Detects writers whose add_value_to_* rejects rfl::Bytestring via +// static_assert instead of encoding or storing bytes natively. +template +concept IsNonBytestringWriter = + std::is_same_v::OutputVarType, + rfl::Generic> || + requires { typename std::remove_cvref_t::YAMLVar; } || + requires { typename std::remove_cvref_t::XMLOutputVar; } || + requires { typename std::remove_cvref_t::TOMLVar; } || + requires { typename std::remove_cvref_t::BoostOutputVar; } || + requires(const typename std::remove_cvref_t::OutputObjectType& o) { + o.prefix; + o.fields; + }; + +template +Result read_from_yyjson(ValPtr _val) { + if (!_val || yyjson_is_null(_val)) return BasicJson(nullptr); + if (yyjson_is_bool(_val)) + return BasicJson( + static_cast(yyjson_get_bool(_val))); + if (yyjson_is_uint(_val)) + return BasicJson(static_cast( + yyjson_get_uint(_val))); + if (yyjson_is_sint(_val)) + return BasicJson(static_cast( + yyjson_get_sint(_val))); + if (yyjson_is_real(_val)) + return BasicJson(static_cast( + yyjson_get_real(_val))); + if (yyjson_is_str(_val)) + return BasicJson(typename BasicJson::string_t(yyjson_get_str(_val), + yyjson_get_len(_val))); + if (yyjson_is_arr(_val)) { + auto arr = BasicJson::array(); + reserve_array(arr, yyjson_arr_size(_val)); + auto iter = yyjson_arr_iter_with(_val); + while (auto* elem = yyjson_arr_iter_next(&iter)) { + auto res = read_from_yyjson(elem); + if (!res) return error(std::move(res.error())); + arr.push_back(std::move(*res)); + } + return arr; + } + if (yyjson_is_obj(_val)) { + auto obj = BasicJson::object(); + reserve_object(obj, yyjson_obj_size(_val)); + auto iter = yyjson_obj_iter_with(_val); + while (auto* key = yyjson_obj_iter_next(&iter)) { + auto res = read_from_yyjson(yyjson_obj_iter_get_val(key)); + if (!res) return error(std::move(res.error())); + emplace_field( + obj, + typename BasicJson::string_t(yyjson_get_str(key), yyjson_get_len(key)), + std::move(*res)); + } + return obj; + } + return error("Unsupported yyjson value type."); +} + +template +Result read_from_generic_reader( + const R& _r, const typename R::InputVarType& _var) { + if (_r.is_empty(_var)) return BasicJson(nullptr); + if (auto obj_res = _r.to_object(_var)) { + auto obj = BasicJson::object(); + std::optional first_err; + struct ObjReader { + const R& r_; + BasicJson& obj_; + std::optional& err_; + void read(const std::string_view _key, + const typename R::InputVarType& _v) const { + if (err_) return; + auto val_res = read_from_generic_reader(r_, _v); + if (!val_res) { + err_ = std::move(val_res.error()); + return; + } + emplace_field(obj_, typename BasicJson::string_t(_key), + std::move(*val_res)); + } + }; + if (auto err = _r.read_object(ObjReader{_r, obj, first_err}, *obj_res)) + return error(std::move(*err)); + if (first_err) return error(std::move(*first_err)); + return obj; + } + if (auto arr_res = _r.to_array(_var)) { + auto arr = BasicJson::array(); + struct ArrReader { + const R& r_; + BasicJson& arr_; + std::optional read(const typename R::InputVarType& _v) const { + auto val_res = read_from_generic_reader(r_, _v); + if (!val_res) return std::move(val_res.error()); + arr_.push_back(std::move(*val_res)); + return std::nullopt; + } + }; + if (auto err = _r.read_array(ArrReader{_r, arr}, *arr_res)) + return error(std::move(*err)); + return arr; + } + // Preserve explicitly quoted YAML strings (Tag() == "!") without coercing + // them into booleans or numbers. + if constexpr (requires(const typename R::InputVarType& v) { + { v.node_.Tag() == "!" } -> std::convertible_to; + }) { + if (_var.node_.Tag() == "!") { + if (auto s = _r.template to_basic_type(_var)) + return BasicJson(typename BasicJson::string_t(std::move(*s))); + } + } + if (auto b = _r.template to_basic_type(_var)) + return BasicJson(static_cast(*b)); + // Preserve native unsigned 64-bit integers in readers that distinguish them + // (jsoncons CBOR/UBJSON, msgpack-c, flexbuffers) so values > INT64_MAX do + // not wrap to negative signed integers. + if constexpr (requires(const typename R::InputVarType& v) { + { v.val_->is_uint64() } -> std::convertible_to; + }) { + if (_var.val_ && _var.val_->is_uint64()) { + if (auto u = _r.template to_basic_type(_var)) + return BasicJson( + static_cast(*u)); + } + } + if constexpr (requires(const typename R::InputVarType& v) { + { v.type } -> std::convertible_to; + { v.via.u64 } -> std::convertible_to; + { v.via.i64 } -> std::convertible_to; + { v.via.boolean } -> std::convertible_to; + }) { + // Coupled to msgpack-c v6 ABI layout: MSGPACK_OBJECT_POSITIVE_INTEGER == 0x02. + if (static_cast(_var.type) == 0x02) { + return BasicJson( + static_cast(_var.via.u64)); + } + } + if constexpr (requires(const typename R::InputVarType& v) { + { v.IsUInt() } -> std::convertible_to; + }) { + if (_var.IsUInt()) { + if constexpr (requires(const typename R::InputVarType& v) { + { v.AsUInt64() } -> std::convertible_to; + }) { + return BasicJson(static_cast( + _var.AsUInt64())); + } else if (auto u = _r.template to_basic_type(_var)) { + return BasicJson( + static_cast(*u)); + } + } + } + if (auto i = _r.template to_basic_type(_var)) { + return BasicJson(static_cast(*i)); + } + if (auto u = _r.template to_basic_type(_var)) { + return BasicJson(static_cast(*u)); + } + if (auto d = _r.template to_basic_type(_var)) + return BasicJson(static_cast(*d)); + if (auto s = _r.template to_basic_type(_var)) + return BasicJson(typename BasicJson::string_t(std::move(*s))); + return error("Could not parse value into nlohmann::basic_json."); +} + +template +void write_to_writer(const W& _w, const BasicJson& _val, const P& _parent) { + using ParentType = parsing::Parent; + if (_val.is_null()) { + ParentType::add_null(_w, _parent); + } else if (const auto* b = _val.template get_ptr< + const typename BasicJson::boolean_t*>()) { + ParentType::add_value(_w, static_cast(*b), _parent); + } else if (const auto* u = _val.template get_ptr< + const typename BasicJson::number_unsigned_t*>()) { + ParentType::add_value(_w, static_cast(*u), _parent); + } else if (const auto* i = _val.template get_ptr< + const typename BasicJson::number_integer_t*>()) { + ParentType::add_value(_w, static_cast(*i), _parent); + } else if (const auto* f = _val.template get_ptr< + const typename BasicJson::number_float_t*>()) { + ParentType::add_value(_w, static_cast(*f), _parent); + } else if (const auto* s = + _val.template get_ptr()) { + if constexpr (std::is_same_v) + ParentType::add_value(_w, *s, _parent); + else + ParentType::add_value(_w, std::string(*s), _parent); + } else if (_val.is_binary()) { + const auto& bin = _val.get_binary(); + Bytestring bytes; + bytes.reserve(bin.size()); + for (const auto b : bin) { + bytes.push_back(static_cast(b)); + } + if constexpr (IsNonBytestringWriter) { + ParentType::add_value(_w, ::rfl::internal::encode_base64(bytes), _parent); + } else { + ParentType::add_value(_w, bytes, _parent); + } + } else if (_val.is_array()) { + auto arr = ParentType::add_array(_w, _val.size(), _parent); + const auto elem_parent = typename ParentType::Array{&arr}; + for (const auto& elem : _val) write_to_writer(_w, elem, elem_parent); + _w.end_array(&arr); + } else if (_val.is_object()) { + auto obj = ParentType::add_object(_w, _val.size(), _parent); + for (auto it = _val.begin(); it != _val.end(); ++it) { + const auto field_parent = + typename ParentType::Object{std::string_view(it.key()), &obj}; + write_to_writer(_w, it.value(), field_parent); + } + _w.end_object(&obj); + } else { + ParentType::add_null(_w, _parent); + } +} + +} // namespace internal +} // namespace rfl::nlohmann + +namespace rfl::parsing { + +/// Parser specialization enabling nlohmann::basic_json as a field type inside +/// reflected structs across rfl::nlohmann, rfl::json, rfl::generic, etc. +template class ObjectType, + template class ArrayType, + class StringType, class BooleanType, class NumberIntegerType, + class NumberUnsignedType, class NumberFloatType, + template class AllocatorType, + template class JSONSerializer, + class BinaryType, class CustomBaseClass, class ProcessorsType> + requires AreReaderAndWriter< + R, W, + ::nlohmann::basic_json> +struct Parser< + R, W, + ::nlohmann::basic_json, + ProcessorsType> { + using BasicJson = + ::nlohmann::basic_json; + using InputVarType = typename R::InputVarType; + using ParentType = Parent; + + static Result read(const R& _r, const InputVarType& _var) { + if constexpr (std::is_same_v, + rfl::nlohmann::Reader>) { + return _var.val_ ? *_var.val_ : BasicJson(nullptr); + } else if constexpr (rfl::nlohmann::is_nlohmann_reader_v) { + return _var.val_ + ? rfl::nlohmann::internal::convert_basic_json( + *_var.val_) + : BasicJson(nullptr); + } else if constexpr (rfl::nlohmann::internal::IsYYJSONReader) { + return rfl::nlohmann::internal::read_from_yyjson(_var.val_); + } else if constexpr (rfl::nlohmann::internal::IsXMLReader) { + static_assert( + rfl::always_false_v, + "XML does not support reading into nlohmann::basic_json."); + return error("XML does not support reading into nlohmann::basic_json."); + } else { + return rfl::nlohmann::internal::read_from_generic_reader(_r, + _var); + } + } + + template + static void write(const W& _w, const BasicJson& _val, const P& _parent) { + using PType = std::remove_cvref_t

; + if constexpr (std::is_same_v, + rfl::nlohmann::Writer>) { + if constexpr (std::is_same_v) + _w.raw_as_root(_val); + else if constexpr (std::is_same_v) + _w.add_raw_to_array(_val, _parent.arr_); + else if constexpr (std::is_same_v) + _w.add_raw_to_object(_parent.name_, _val, _parent.obj_); + else + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } else if constexpr (rfl::nlohmann::is_nlohmann_writer_v) { + using TargetBasicJson = typename std::remove_cvref_t::BasicJsonType; + const auto converted = + rfl::nlohmann::internal::convert_basic_json(_val); + if constexpr (std::is_same_v) + _w.raw_as_root(converted); + else if constexpr (std::is_same_v) + _w.add_raw_to_array(converted, _parent.arr_); + else if constexpr (std::is_same_v) + _w.add_raw_to_object(_parent.name_, converted, _parent.obj_); + else + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } else { + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/nlohmann/Reader.hpp b/include/rfl/nlohmann/Reader.hpp new file mode 100644 index 000000000..dba523a23 --- /dev/null +++ b/include/rfl/nlohmann/Reader.hpp @@ -0,0 +1,256 @@ +#ifndef RFL_NLOHMANN_READER_HPP_ +#define RFL_NLOHMANN_READER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Result.hpp" +#include "../Vectorstring.hpp" +#include "../always_false.hpp" +#include "../internal/base64.hpp" + +static_assert( + (NLOHMANN_JSON_VERSION_MAJOR > 3) || + (NLOHMANN_JSON_VERSION_MAJOR == 3 && + NLOHMANN_JSON_VERSION_MINOR > 11) || + (NLOHMANN_JSON_VERSION_MAJOR == 3 && + NLOHMANN_JSON_VERSION_MINOR == 11 && + NLOHMANN_JSON_VERSION_PATCH >= 3), + "reflect-cpp requires nlohmann/json >= 3.11.3 (11-parameter " + "nlohmann::basic_json template with CustomBaseClass)."); + +namespace rfl::nlohmann { + +template +struct is_basic_json : std::false_type {}; + +template