diff --git a/.github/actions/setup-vcpkg/action.yml b/.github/actions/setup-vcpkg/action.yml index 65292cb28..06f2d2efa 100644 --- a/.github/actions/setup-vcpkg/action.yml +++ b/.github/actions/setup-vcpkg/action.yml @@ -20,16 +20,25 @@ runs: --retry-delay 10 --connect-timeout 30 --output {dst} {url} run: | cache_dir="${RUNNER_TEMP//\\//}/vcpkg-binary-cache" + vcpkg_dir="${RUNNER_TEMP//\\//}/vcpkg" mkdir -p "$cache_dir" + vcpkg_commit=$(sed -n 's/.*"baseline"[[:space:]]*:[[:space:]]*"\([0-9a-f]\{40\}\)".*/\1/p' vcpkg-configuration.json | head -n 1) + if [ -z "$vcpkg_commit" ]; then + echo "::error::Failed to read vcpkg baseline from vcpkg-configuration.json" + exit 1 + fi echo "VCPKG_BINARY_SOURCES=clear;files,$cache_dir,readwrite" >> "$GITHUB_ENV" echo "X_VCPKG_ASSET_SOURCES=$X_VCPKG_ASSET_SOURCES" >> "$GITHUB_ENV" echo "cache-path=$cache_dir" >> "$GITHUB_OUTPUT" - echo "vcpkg-revision=$(git rev-parse HEAD:vcpkg)" >> "$GITHUB_OUTPUT" + echo "vcpkg-dir=$vcpkg_dir" >> "$GITHUB_OUTPUT" + echo "vcpkg-revision=$vcpkg_commit" >> "$GITHUB_OUTPUT" echo "image-version=${ImageVersion:-unknown}" >> "$GITHUB_OUTPUT" # run-vcpkg requires binaryCachePath to exist before the action starts. - uses: lukka/run-vcpkg@v11 with: + vcpkgDirectory: ${{ steps.config.outputs.vcpkg-dir }} + vcpkgGitCommitId: ${{ steps.config.outputs.vcpkg-revision }} binaryCachePath: ${{ steps.config.outputs.cache-path }} - name: Cache vcpkg binaries diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index c3c82dc2d..99050fef8 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -32,7 +32,6 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 # fetch all history for .GitInfo and .Lastmod - submodules: recursive - name: Setup Go uses: actions/setup-go@v5 with: diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index 82807af94..5a07ece58 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] @@ -60,7 +60,6 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - submodules: recursive fetch-depth: 0 - name: Set up vcpkg uses: ./.github/actions/setup-vcpkg diff --git a/.github/workflows/macos.yaml b/.github/workflows/macos.yaml index 2f5fba43e..bae24d383 100644 --- a/.github/workflows/macos.yaml +++ b/.github/workflows/macos.yaml @@ -18,7 +18,6 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - submodules: recursive fetch-depth: 0 - name: Set up vcpkg uses: ./.github/actions/setup-vcpkg diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index 8b4af4ad5..b4b4b9e83 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 }}" @@ -17,7 +17,6 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - submodules: recursive fetch-depth: 0 - uses: ilammy/msvc-dev-cmd@v1 - name: Set up vcpkg @@ -76,14 +75,13 @@ 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: - name: Checkout uses: actions/checkout@v4 with: - submodules: recursive fetch-depth: 0 - uses: ilammy/msvc-dev-cmd@v1 - name: Set up vcpkg diff --git a/.gitignore b/.gitignore index f0dd1b30c..84a854d3c 100644 --- a/.gitignore +++ b/.gitignore @@ -61,6 +61,7 @@ *.yas !vcpkg.json +!vcpkg-configuration.json !.github/**/*.yml !.github/**/*.yaml !benchmarks/**/*.json @@ -90,6 +91,7 @@ lib64/ parts/ sdist/ var/ +/vcpkg/ vcpkg_installed/ wheels/ share/python-wheels/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index a0a57f3d7..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vcpkg"] - path = vcpkg - url = https://github.com/microsoft/vcpkg.git diff --git a/CMakeLists.txt b/CMakeLists.txt index aae285585..cccf7dbb9 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,120 @@ 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 () + message(FATAL_ERROR + "REFLECTCPP_USE_VCPKG is ON, but vcpkg was not found. " + "Set VCPKG_ROOT or CMAKE_TOOLCHAIN_FILE to your vcpkg installation, " + "or pass -DREFLECTCPP_USE_VCPKG=OFF to use external/system dependencies.") + 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 +336,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 +419,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 +501,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 +573,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 +626,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 +641,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 +669,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 +680,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 +727,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 +736,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 +833,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 +908,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 +951,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 183c917d7..72ff6374c 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile - Simple [installation](https://munich-data-engineering.github.io/reflect-cpp/install) - Simple extendability to [other serialization formats](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/supporting_your_own_format) - Simple extendability to [custom classes](https://munich-data-engineering.github.io/reflect-cpp/concepts/custom_classes) +- Read-only field aliases via [`rfl::Alias`](https://munich-data-engineering.github.io/reflect-cpp/alias) for backwards-compatible schema and config migration - Being one of the fastest serialization libraries in existence, as demonstrated by our [benchmarks](https://munich-data-engineering.github.io/reflect-cpp/benchmarks)
@@ -48,11 +49,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 +81,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 | @@ -437,6 +440,8 @@ The resulting JSON schema looks like this: Note that this is currently supported for JSON only, since most other formats do not support schemata in the first place. +If you prefer not to embed long description strings into your field types, you can also attach struct-level and per-field descriptions and deprecation messages out of band by specializing `rfl::Metadata` ([details](https://munich-data-engineering.github.io/reflect-cpp/json_schema/#out-of-band-metadata-rflmetadata)). + ### Enums reflect-cpp supports scoped enumerations: @@ -682,6 +687,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 @@ -698,6 +704,28 @@ 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) +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 @@ -716,12 +744,13 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` -To install all supported serialization formats, first install vcpkg: +To install all supported serialization formats, first install vcpkg and set `VCPKG_ROOT`: ```bash -git submodule update --init +git clone https://github.com/microsoft/vcpkg.git ./vcpkg/bootstrap-vcpkg.sh # Linux, macOS ./vcpkg/bootstrap-vcpkg.bat # Windows +export VCPKG_ROOT="$PWD/vcpkg" # Linux, macOS (or set VCPKG_ROOT on Windows) # You may be prompted to install additional dependencies. ``` @@ -733,7 +762,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 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/_index.md b/docs/content/_index.md index 056abfd96..89bff4427 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -16,6 +16,7 @@ {{< card link="rfl_ref" title="rfl::Box and rfl::Ref" icon="book-open" subtitle="For defining recursive structures.">}} {{< card link="timestamps" title="rfl::Timestamp and std::chrono::duration" icon="book-open" subtitle="For serializing and deserializing timestamps and durations.">}} {{< card link="rfl_skip" title="rfl::Skip" icon="book-open" subtitle="For skipping fields during serialization and/or deserialization.">}} + {{< card link="alias" title="rfl::Alias" icon="book-open" subtitle="For accepting read-only field aliases during deserialization.">}} {{< card link="commented" title="rfl::Commented" icon="book-open" subtitle="For adding comments to your serialized format.">}} {{< card link="result" title="rfl::Result" icon="book-open" subtitle="For error handling without exceptions.">}} {{< card link="standard_containers" title="Standard containers" icon="book-open" subtitle="How reflect-cpp treats containers in the standard library.">}} diff --git a/docs/content/alias.md b/docs/content/alias.md new file mode 100644 index 000000000..09ce84ec6 --- /dev/null +++ b/docs/content/alias.md @@ -0,0 +1,64 @@ +# Read-only field aliases (`rfl::Alias`) + +The `rfl::Alias<"old-name", T>` wrapper declares a read-only alias for a struct field. During deserialization, `reflect-cpp` accepts **either** the canonical primary wire name **or** any declared alias. During serialization and JSON Schema generation, `reflect-cpp` **always** emits the canonical primary wire name. + +This is especially useful when evolving an API or configuration format (for example, migrating legacy `kebab-case` or `camelCase` RPC keys to `snake_case`) without maintaining manual key-translation tables. + +## Basic usage + +```cpp +#include +#include + +struct Settings { + rfl::Alias<"download-dir", std::string> download_dir; + rfl::Alias<"speedLimitDown", int> speed_limit_down; +}; + +// Accepted on read (alias or canonical name): +const auto s = rfl::json::read( + R"({"download-dir":"/downloads","speedLimitDown":250})").value(); + +// Always serialized using the canonical primary names: +const auto out = rfl::json::write(s); +// {"download_dir":"/downloads","speed_limit_down":250} +``` + +## Multiple aliases + +Nest `rfl::Alias` wrappers to accept multiple legacy names for the same field: + +```cpp +struct Settings { + rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>> + download_dir; +}; +``` + +Reading `{"download_dir": "/dl"}`, `{"download-dir": "/dl"}`, or `{"downloadDir": "/dl"}` all populate `download_dir`, and writing always emits `{"download_dir":"/dl"}`. + +## Semantics + +- **Primary wire name:** Unchanged. It comes from the C++ field name (transformed by naming processors such as `rfl::SnakeCaseToCamelCase` or `rfl::SnakeCaseToKebabCase`, or overridden by `rfl::Rename<"canonical", ...>`). +- **Serialization (write):** Always writes the canonical primary wire name. +- **JSON Schema (`to_schema`):** Emits only the canonical primary property name (preserving inner `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, and `rfl::Validator` metadata). +- **`rfl::NoExtraFields`:** Aliases are recognized as valid field names and are not rejected as unknown extra fields. +- **Conflicting / duplicate input:** If an input object specifies both the primary name and an alias (or two different aliases for the same field), deserialization fails with an error instead of silently overwriting. +- **Compile-time collision check:** If an alias on one field equals the primary wire name or an alias of a different field, compilation fails with a `static_assert`. + +## Composing with other wrappers and processors + +`rfl::Alias` is transparent and composes cleanly with `rfl::Rename`, `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, `rfl::DefaultIfMissing`, `std::optional`, `rfl::Validator`, and case-transforming processors: + +```cpp +struct Config { + rfl::Rename<"download_dir", rfl::Alias<"download-dir", std::string>> dir; + rfl::Alias<"old-port", rfl::DefaultVal> port = 8080; + rfl::Description<"Timeout in seconds", rfl::Alias<"timeoutSec", std::optional>> + timeout_sec; +}; +``` + +## Wrapper ergonomics + +`rfl::Alias` provides `.value()`, `.get()`, `operator*`, `operator->`, `operator()`, implicit construction from convertible values, implicit conversion to `T&` / `const T&`, `==`, `<=>`, and `std::hash` specialization. Its default constructor is constrained on `std::is_default_constructible_v`. diff --git a/docs/content/atomic.md b/docs/content/atomic.md index 88e5ae2a7..21995f2f2 100644 --- a/docs/content/atomic.md +++ b/docs/content/atomic.md @@ -66,7 +66,7 @@ if (!res) { ## Limitations and notes - Structs containing atomic fields must be default-constructible. -- Atomic types cannot be mixed with `rfl::DefaultVal` or the `rfl::DefaultIfMissing` processor; attempting to do so triggers a static assertion at compile-time (see parser implementations). +- Atomic types cannot be mixed with `rfl::DefaultVal`, `rfl::DefaultIfMissing`, or `rfl::DefaultIfNull`; attempting to do so triggers a static assertion at compile-time (see parser implementations). - The semantics used for setting atomic values use relaxed memory order (`std::memory_order_relaxed`). - For complex aggregates, `rfl::atomic` will recurse into nested fields and arrays to set atomic members. diff --git a/docs/content/contributing.md b/docs/content/contributing.md index 74ac75fbc..796ceb4d9 100644 --- a/docs/content/contributing.md +++ b/docs/content/contributing.md @@ -24,10 +24,11 @@ reflect-cpp uses vcpkg for dependency management, including gtest, which is required for the tests. ```bash -# bootstrap vcpkg if you haven't done so already -git submodule update --init +# clone and bootstrap vcpkg if you haven't done so already (or set VCPKG_ROOT) +git clone https://github.com/microsoft/vcpkg.git ./vcpkg/bootstrap-vcpkg.sh # Linux, macOS ./vcpkg/bootstrap-vcpkg.bat # Windows +export VCPKG_ROOT="$PWD/vcpkg" # Linux, macOS (or set VCPKG_ROOT on Windows) # You may be prompted to install additional dependencies. ``` 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..e4d168e60 100644 --- a/docs/content/install.md +++ b/docs/content/install.md @@ -36,6 +36,40 @@ 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) +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 +78,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. @@ -55,12 +91,13 @@ If you need support for other serialization formats like flexbuffers or XML, you If you want serialization formats other than JSON, you can either install them manually or use vcpkg. -To install vcpkg: +To install vcpkg and set `VCPKG_ROOT`: ```bash -git submodule update --init +git clone https://github.com/microsoft/vcpkg.git ./vcpkg/bootstrap-vcpkg.sh # Linux, macOS ./vcpkg/bootstrap-vcpkg.bat # Windows +export VCPKG_ROOT="$PWD/vcpkg" # Linux, macOS (or set VCPKG_ROOT on Windows) # You may be prompted to install additional dependencies. ``` @@ -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 681813d98..68771cfdd 100644 --- a/docs/content/json_schema.md +++ b/docs/content/json_schema.md @@ -84,6 +84,21 @@ matches exactly one of them. `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. @@ -254,3 +269,112 @@ const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); ``` `rfl::Deprecated` behaves like a thin wrapper around the underlying type, just like `rfl::Description`. You can access the underlying value using `.get()`, `.value()`, `operator()()`, `operator*()`, `operator->()`, or the assignment operator. + +## Default values with `rfl::DefaultIfMissing` + +When you generate a schema with the `rfl::DefaultIfMissing` processor, all fields are omitted from `"required"` and—whenever the struct is default-constructible—each field's default value from `T{}` is emitted as a JSON Schema `"default"` annotation: + +```cpp +struct Config { + int port = 8080; + std::string host = "localhost"; + bool verbose = true; + std::optional tls_cert; + std::optional timeout = 30; +}; + +const std::string json_schema = + rfl::json::to_schema(rfl::json::pretty); +``` + +This produces: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/Config", + "$defs": { + "Config": { + "type": "object", + "properties": { + "port": { + "type": "integer", + "default": 8080 + }, + "host": { + "type": "string", + "default": "localhost" + }, + "verbose": { + "default": true, + "type": "boolean" + }, + "tls_cert": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "timeout": { + "default": 30, + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ] + } + }, + "required": [] + } + } +} +``` + +A few details to keep in mind: + +- Empty nullable fields (`std::optional`, `std::shared_ptr`, `std::unique_ptr` initialized to `std::nullopt` / `nullptr`) do not emit `"default": null`; initialized ones (like `timeout = 30`) emit their default value. +- If a struct is not default-constructible, or if default-constructing it throws an exception (for example, an uninitialized `rfl::Validator` field whose zero value is invalid), schema generation still succeeds and simply omits `"default"` annotations for that struct. +- Without `rfl::DefaultIfMissing`, plain fields do not emit `"default"` annotations (use `rfl::DefaultVal` for per-field defaults). + +## Out-of-band metadata (`rfl::Metadata`) + +When you have many documented fields or long descriptions, wrapping every field in `rfl::Description<"...", T>` or `rfl::Deprecated<"...">` embeds long string literals into your C++ field types, which can increase compile times and symbol sizes. As an opt-in alternative, you can specialize `rfl::Metadata` to attach struct-level and per-field descriptions and deprecation messages out of band without changing the struct definition: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Email email; + std::optional wage; +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = + "Attributes describing a person."; + static constexpr std::array fields = {{ + {.name = "email", + .description = "Must be a proper email in the form xxx@xxx.xxx."}, + {.name = "wage", + .description = "Wage in dollars", + .deprecation_message = "Use salary instead."}, + }}; +}; +``` + +You can also provide `static std::span fields()` (or return a `const` lvalue reference to a contiguous container) and `static std::string_view description()`, and define them out-of-line in a `.cpp` file so schema prose is kept out of headers entirely. Returning a container by value (such as `std::vector`) is rejected at compile time to prevent dangling views. + +### Lookup rules and limitations + +- **Name matching:** Each `rfl::FieldMeta::name` is matched against the processed wire field name first (for example, `firstName` under `rfl::SnakeCaseToCamelCase`), falling back to the pre-processor field name (the C++ member name or explicit `rfl::Rename` name). +- **Silent misses on typos:** Because `rfl::Metadata` keeps field names out of C++ template signatures, a misspelled `FieldMeta::name` is not checked at compile time and is silently ignored when generating the schema. +- **`rfl::Flatten`:** `rfl::Metadata` attaches to `Inner`'s own schema definition (`$defs/Inner`). When `Inner` is flattened into `Outer` via `rfl::Flatten`, flattened fields are looked up on `rfl::Metadata`, not on `rfl::Metadata`. +- **Enums:** `rfl::Metadata` is ignored for enums. Use [`rfl::config::enum_descriptions`](../enum_descriptions/) to document enum values instead. +- **`rfl::TaggedUnion`:** Specializing `rfl::Metadata` on a tagged-union alternative struct is picked up automatically. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..c719c459b 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -33,18 +33,24 @@ The resulting JSON string looks like this: reflect-cpp currently supports the following processors: +- `rfl::AddNullFields` - `rfl::AddStructName` - `rfl::AddTagsToVariants` - `rfl::AddNamespacedTagsToVariants` - `rfl::AllowRawPtrs` - `rfl::DefaultIfMissing` +- `rfl::DefaultIfNull` +- `rfl::DefaultTag` - `rfl::DurationsAsCount` - `rfl::EnumNamesOnly` - `rfl::FailFast` +- `rfl::MaxDepth` +- `rfl::NoDuplicateKeys` - `rfl::NoExtraFields` - `rfl::NoFieldNames` - `rfl::NoOptionals` - `rfl::UnderlyingEnums` +- `rfl::VariantsAsOneOf` - `rfl::SnakeCaseToCamelCase` - `rfl::SnakeCaseToPascalCase` @@ -314,6 +320,54 @@ Note that the struct is default-constructed before it is read. Every field therefore needs a valid default value, even if the field is in the input. This is explained in the documentation on `rfl::DefaultVal`. +### `rfl::DefaultIfNull` + +The `rfl::DefaultIfNull` processor is only relevant for reading data. For writing data, it will make no difference. + +Usually, when a non-nullable value is `null` or empty in the input (for example, an empty or comment-only YAML document, a YAML key with no value such as `tags:` or `logging:`, or a JSON `null`), reading fails with a parse error. +If you pass `rfl::DefaultIfNull`, null/empty values are replaced by the target's default value instead (when the target type is default-constructible): + +```cpp +struct Logging { + std::string level = "info"; +}; + +struct Config { + int port = 8080; + std::string host = "localhost"; + std::vector tags; + std::map env; + Logging logging; + std::map modules; +}; +``` + +```yaml +port: null +host: +tags: +env: +logging: +modules: + network: +``` + +```cpp +const auto cfg = rfl::yaml::read(yaml_str).value(); +// cfg.port == 8080, cfg.host == "localhost", cfg.tags.empty(), cfg.env.empty(), +// cfg.logging.level == "info", cfg.modules["network"].level == "info" +``` + +Empty or comment-only YAML documents (and root `null` in JSON) also produce a default-constructed `Config{}`. + +Key details: + +- **In-class member initializers are preserved:** For default-constructible structs, `port: null` preserves `8080` rather than overwriting it with `0`. +- **Nullable types still decode `null` as empty:** `std::optional`, `std::unique_ptr`, `std::shared_ptr`, raw pointers, and `rfl::Generic` always decode an explicit `null` as `std::nullopt` / `nullptr` / `rfl::Generic::Null` — even if the field has a non-null in-class initializer such as `std::optional x = 5`. +- **Missing fields remain required unless combined with `rfl::DefaultIfMissing`:** `rfl::DefaultIfNull` only applies to null/empty values that are present (or a null root document). Combine `rfl::DefaultIfMissing, rfl::DefaultIfNull` when you want both missing fields and null values to fall back to defaults. +- **Non-default-constructible types:** If a type is not default-constructible, encountering `null` falls back to normal error reporting rather than failing to compile. +- **Default-constructible structs are default-constructed before reading:** To preserve in-class member initializers, default-constructible structs are default-constructed before their fields are read. Every field of such a struct therefore needs a valid default value (for example, a `rfl::Validator` whose default constructor throws will cause reading to return an error, even if the field is present in the input). This is explained in the documentation on `rfl::DefaultVal`. + ### `rfl::DurationsAsCount` By default, `std::chrono::duration` types are written as an object containing @@ -366,6 +420,61 @@ Failed to parse field 'color': Invalid enum value: '2'. Must be one of [red, gre This processor only affects reading. Enum values that cannot be matched to a declared name are still written as their integer representation. +### `rfl::DefaultTag` + +By default, reading an `rfl::TaggedUnion` fails if the discriminator field is +missing from the input object. Pass `rfl::DefaultTag<"_discriminator", "_tag">` +to fall back to a specific tag when that discriminator field is absent: + +```cpp +using Schema = rfl::TaggedUnion<"version", ConfigV1, ConfigV2>; + +// Unversioned input defaults to ConfigV1 ("1"); explicit "version" still +// dispatches (and rejects invalid/non-string values). +const auto cfg = + rfl::yaml::read>(yaml_str); +``` + +The default tag is validated at compile time against the union's allowed tags. +`DefaultTag` is a read-side fallback: writing always emits the explicit +discriminator field (and `to_schema` keeps it required). Multiple +`rfl::DefaultTag` processors with distinct discriminators may be combined in one +`rfl::Processors<...>` bundle. + +### `rfl::MaxDepth` + +By default, deserialization does not enforce a nesting depth limit. Pass +`rfl::MaxDepth` to bound container and struct nesting depth and return an +`rfl::Error` instead of overflowing the C++ call stack on deeply nested +untrusted inputs (such as `rfl::Generic` or recursive `rfl::Box` structs): + +```cpp +const auto result = + rfl::json::read>(untrusted_json); +``` + +When `rfl::MaxDepth` is not passed, there is zero runtime overhead. Note that +`MaxDepth` guards reflect-cpp's own parser walk (effective for iterative +readers such as `yyjson`); formats backed by recursive third-party parsers +(`yaml-cpp`, `pugixml`, `toml++`) may still hit stack limits inside the +underlying parser before reflect-cpp walks the DOM. + +### `rfl::NoDuplicateKeys` + +By default, `rfl::json::read` and `rfl::yaml::read` keep their existing behavior +when an input object or mapping contains repeated keys. Pass +`rfl::NoDuplicateKeys` to reject duplicate keys and report each repeated key as +an error. Works across structs, maps, `rfl::Object`, `rfl::Generic`, +`rfl::FieldVariant`, and `rfl::TaggedUnion`. Passing `rfl::NoDuplicateKeys` to a +reader that does not support duplicate-key detection fails at compile time +(`static_assert`): + +```cpp +const auto json_res = + rfl::json::read(json_str); +const auto yaml_res = + rfl::yaml::read(yaml_str); +``` ### `rfl::NoExtraFields` When reading an object and the object contains a field that cannot be @@ -492,6 +601,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. @@ -514,6 +636,26 @@ The resulting JSON string looks like this: {"FirstName":"Homer","LastName":"Simpson","Age":45} ``` +## `rfl::Int64AsString` + +Passing `rfl::Int64AsString` serializes and deserializes 64-bit (and wider) integer fields (`int64_t`, `uint64_t`, etc.) as base-10 strings while keeping narrower integers (`int32_t`, `uint32_t`, etc.) as numbers. This lets you share one plain C++ struct across binary/columnar formats (CBOR, MsgPack, Parquet, Arrow) and JavaScript/Protobuf-JSON APIs that lose integer precision above `2^53 - 1`. + +```cpp +struct Trade { + int64_t trade_id; + uint64_t sequence; + int32_t quantity; +}; + +const auto json_string = rfl::json::write( + Trade{.trade_id = 9007199254740993LL, .sequence = 18446744073709551615ULL, .quantity = 5}); +// {"trade_id":"9007199254740993","sequence":"18446744073709551615","quantity":5} + +const auto trade = rfl::json::read(json_string).value(); +``` + +`rfl::json::to_schema()` emits `{"type":"string","format":"int64"}` / `{"type":"string","format":"uint64"}` for 64-bit integer fields and `{"type":"integer"}` for narrower integers. + ## Combining several processors You can combine several processors: @@ -549,6 +691,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/result.md b/docs/content/result.md index fb59c2280..f2ed1059c 100644 --- a/docs/content/result.md +++ b/docs/content/result.md @@ -154,9 +154,32 @@ struct ErrorDetail { // The message, without the "Failed to parse field '...': " prefixes. std::string message; + + // Coarse, format-agnostic category of this failure. + rfl::ErrorKind kind = rfl::ErrorKind::other; + + // Optional machine-readable rule or error code (e.g. "minimum", + // "size.minimum", "pattern", or a custom validator code). Empty when unset. + std::string code = {}; + + bool operator==(const ErrorDetail&) const = default; }; ``` +`rfl::ErrorKind` (`enum class ErrorKind : std::uint8_t`) classifies input and I/O failures across formats without requiring callers to parse error message strings. It is an open enum (new enumerators may be added in minor releases; `switch` statements should include a `default:` branch): + +- `rfl::ErrorKind::other` – unclassified error (custom parsers/reflectors, caller bugs, or formats not yet tagged; default for plain-string `rfl::Error`). +- `rfl::ErrorKind::io_error` – input could not be obtained or output could not be emitted (file open/read/write/close or stream I/O failure). +- `rfl::ErrorKind::syntax_error` – malformed input syntax (for example invalid JSON). +- `rfl::ErrorKind::missing_field` – a declared, individually-required slot has no entry (required struct field, tuple element, or tagged-union discriminator). +- `rfl::ErrorKind::unknown_field` – an undeclared or ambiguous key/field was encountered (for example under `rfl::NoExtraFields`). +- `rfl::ErrorKind::invalid_length` – element or value count violated a bound fixed by the C++ type or option arity (for example `std::array` size mismatch, tuple overflow, or `inplace_vector` capacity). +- `rfl::ErrorKind::invalid_type` – the node's native wire or structural type was incompatible with the target type (for example a string where an integer was expected, or an array where an object was expected). +- `rfl::ErrorKind::invalid_value` – the wire type was right (or a string-only format token), but domain or lexical conversion failed (for example an out-of-range integer, a negative integer for an unsigned target, an unknown enum or `rfl::Literal` value, an invalid timestamp/Base64/bitset, or an unknown union discriminator). +- `rfl::ErrorKind::constraint_violation` – the value parsed to the target C++ type, but violated a declared check such as `rfl::Validator<...>`. + +`Error::kind()` returns the error's `rfl::ErrorKind` directly, and `Error::code()` returns its machine-readable rule code (`std::string_view`, empty when unset; for multi-error results, both return the first entry in `.details()`). Built-in validators populate canonical codes (`"equal_to"`, `"not_equal_to"`, `"minimum"`, `"exclusive_minimum"`, `"maximum"`, `"exclusive_maximum"`, `"pattern"`, `"any_of"`, `"one_of"`, `"size"` / `"size.*"`, and `"code_points"` / `"code_points.*"`). Custom validators can attach codes either per-error via `rfl::error(msg, rfl::ErrorKind::constraint_violation, "my_code")` or declaratively via a `static constexpr` `code` member convertible to `std::string_view` (note: any custom validator defining a string-convertible `static` `code` member automatically opts into this). Note that `ErrorDetail::operator==` compares `kind` and `code` in addition to `path` and `message`. + Field names are spelled as they appear in the input, that is, after processors such as `rfl::SnakeCaseToCamelCase` or `rfl::SnakeCaseToKebabCase` (which `rfl::cli::read` uses) have been applied. This means the paths line up with the JSON schema generated by `rfl::json::to_schema`. ```cpp @@ -174,8 +197,12 @@ const auto result = rfl::json::read( for (const auto& detail : result.error().details()) { // First iteration: path = {"files", 1, "inputFile"}, + // kind = rfl::ErrorKind::constraint_violation, + // code = "size.minimum", // message = "Size validation failed: ..." // Second iteration: path = {"files", 1, "outputFile"}, + // kind = rfl::ErrorKind::missing_field, + // code = "", // message = "Field named 'outputFile' not found." } ``` @@ -184,7 +211,14 @@ An error that does not belong to any particular field, such as a syntax error in ## `rfl::error` -`rfl::error("error message")` is a simple utility function for `rfl::Unexpected(Error("error message"))`. +`rfl::error("error message")` is a simple utility function for `rfl::Unexpected(Error("error message"))`. You can also pass an `rfl::ErrorKind`, an optional `std::vector` path, and an optional machine-readable code: + +```cpp +rfl::error("Port out of range", rfl::ErrorKind::invalid_value); +rfl::error("Port out of range", rfl::ErrorKind::invalid_value, {"port"}); +rfl::error("Must be even", rfl::ErrorKind::constraint_violation, "even"); +rfl::error("Must be even", rfl::ErrorKind::constraint_violation, {"port"}, "even"); +``` ## `.or_else(...)`, `.transform_error(...)` 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/json.md b/docs/content/supported_formats/json.md index 139be756c..b1bd26bdc 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -172,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/docs/content/supported_formats/parquet.md b/docs/content/supported_formats/parquet.md index 622d1df32..c46549b06 100644 --- a/docs/content/supported_formats/parquet.md +++ b/docs/content/supported_formats/parquet.md @@ -148,6 +148,7 @@ The following processors are **NOT supported** and will cause compilation errors - `rfl::AddTagsToVariants` - Cannot be used for tabular data - `rfl::NoOptionals` - Cannot be used for tabular data - `rfl::DefaultIfMissing` - Cannot be used for tabular data +- `rfl::DefaultIfNull` - Cannot be used for tabular data - `rfl::NoExtraFields` - Cannot be used for tabular data - `rfl::NoFieldNames` - Cannot be used for tabular data diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..a3f6925d1 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -7,8 +7,10 @@ #pragma warning(disable : 4101) #endif +#include "rfl/AddNullFields.hpp" #include "rfl/AddStructName.hpp" #include "rfl/AddTagsToVariants.hpp" +#include "rfl/Alias.hpp" #include "rfl/AllOf.hpp" #include "rfl/AllowRawPtrs.hpp" #include "rfl/AnyOf.hpp" @@ -20,9 +22,12 @@ #include "rfl/CodePoints.hpp" #include "rfl/Commented.hpp" #include "rfl/DefaultIfMissing.hpp" +#include "rfl/DefaultIfNull.hpp" +#include "rfl/DefaultTag.hpp" #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,11 +35,17 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/Int64AsString.hpp" +#include "rfl/IntegerBounds.hpp" #include "rfl/Literal.hpp" +#include "rfl/MaxDepth.hpp" +#include "rfl/Metadata.hpp" #include "rfl/NamedTuple.hpp" +#include "rfl/NoDuplicateKeys.hpp" #include "rfl/NoExtraFields.hpp" #include "rfl/NoFieldNames.hpp" #include "rfl/NoOptionals.hpp" +#include "rfl/Nullable.hpp" #include "rfl/Object.hpp" #include "rfl/Oct.hpp" #include "rfl/OneOf.hpp" @@ -44,6 +55,8 @@ #include "rfl/Processors.hpp" #include "rfl/Ref.hpp" #include "rfl/Rename.hpp" +#include "rfl/SchemaExtension.hpp" +#include "rfl/SchemaName.hpp" #include "rfl/Settings.hpp" #include "rfl/Short.hpp" #include "rfl/Size.hpp" @@ -51,12 +64,16 @@ #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/TriState.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 +109,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/AddNullFields.hpp b/include/rfl/AddNullFields.hpp new file mode 100644 index 000000000..c4fac405e --- /dev/null +++ b/include/rfl/AddNullFields.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_ADDNULLFIELDS_HPP_ +#define RFL_ADDNULLFIELDS_HPP_ + +namespace rfl { + +/// A write-side processor that instructs serializers to emit `"field": null` +/// for empty optional/nullable fields (`std::optional`, `std::shared_ptr`, +/// `std::unique_ptr`, raw pointers) instead of omitting them, while keeping +/// them optional on read (unlike `rfl::NoOptionals`, which also makes them +/// mandatory on read). +struct AddNullFields { + public: + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Alias.hpp b/include/rfl/Alias.hpp new file mode 100644 index 000000000..cf7144a29 --- /dev/null +++ b/include/rfl/Alias.hpp @@ -0,0 +1,245 @@ +#ifndef RFL_ALIAS_HPP_ +#define RFL_ALIAS_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "default.hpp" +#include "internal/StringLiteral.hpp" +#include "internal/is_alias.hpp" + +namespace rfl { + +/// Declares a read-only field alias accepted during deserialization while +/// always serializing (and generating schemas) under the canonical primary +/// field name. +/// +/// Multiple aliases can be declared by nesting `rfl::Alias`: +/// `rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>>` +/// +/// @tparam _name The compile-time string literal alias name accepted on read +/// @tparam T The underlying value (or wrapped field) type +template +struct Alias { + /// The underlying type. + using Type = T; + + /// The alias name as a compile-time string literal. + static constexpr internal::StringLiteral alias_name_ = _name; + + /// Returns the alias name as a string_view. + static constexpr std::string_view alias_name() noexcept { + return alias_name_.string_view(); + } + + /// Default constructor - enabled only when Type is default-constructible. + template + requires std::is_default_constructible_v + constexpr Alias() noexcept(std::is_nothrow_default_constructible_v) + : value_() {} + + /// Constructs from a const reference to the value. + constexpr Alias(const Type& _value) : value_(_value) {} + + /// Constructs from an rvalue reference to the value. + constexpr Alias(Type&& _value) noexcept( + std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + /// Move constructor. + Alias(Alias&& _field) = default; + + /// Copy constructor. + Alias(const Alias& _field) = default; + + /// Copy constructor from Alias with the same alias name and a compatible + /// underlying type. + template + requires(!std::is_same_v && std::is_convertible_v) + constexpr Alias(const Alias<_name, U>& _field) : value_(_field.get()) {} + + /// Move constructor from Alias with the same alias name and a compatible + /// underlying type. + template + requires(!std::is_same_v && std::is_convertible_v) + constexpr Alias(Alias<_name, U>&& _field) noexcept( + std::is_nothrow_constructible_v) + : value_(std::move(_field.value_)) {} + + /// Constructs from any type convertible to Type. + template + requires(!std::is_same_v, Alias> && + !std::is_same_v, Type> && + !std::is_same_v, Default> && + std::is_convertible_v) + constexpr Alias(U&& _value) noexcept( + std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + /// Initializes the underlying object to its default value using the Default + /// sentinel. + template + requires std::is_default_constructible_v + constexpr Alias(const Default&) noexcept( + std::is_nothrow_default_constructible_v) + : value_() {} + + /// Destructor. + ~Alias() = default; + + /// Returns a const reference to the underlying value. + constexpr const Type& get() const noexcept { return value_; } + + /// Returns a reference to the underlying value. + constexpr Type& get() noexcept { return value_; } + + /// Dereference operator - returns the underlying value. + constexpr Type& operator*() noexcept { return value_; } + + /// Dereference operator (const) - returns the underlying value. + constexpr const Type& operator*() const noexcept { return value_; } + + /// Function call operator - returns the underlying value. + constexpr Type& operator()() noexcept { return value_; } + + /// Function call operator (const) - returns the underlying value. + constexpr const Type& operator()() const noexcept { return value_; } + + /// Pointer to the underlying value. + constexpr Type* operator->() noexcept { return &value_; } + + /// Pointer to the underlying value (const). + constexpr const Type* operator->() const noexcept { return &value_; } + + /// Implicit conversion to a mutable reference to the underlying value. + constexpr operator Type&() noexcept { return value_; } + + /// Implicit conversion to a const reference to the underlying value. + constexpr operator const Type&() const noexcept { return value_; } + + /// Assigns a new value (copy). + auto& operator=(const Type& _value) { + value_ = _value; + return *this; + } + + /// Assigns a new value (move). + auto& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return *this; + } + + /// Assigns from any type convertible to the underlying type. + template + requires(!std::is_same_v, Alias> && + !std::is_same_v, Type> && + !std::is_same_v, Default> && + std::is_convertible_v) + auto& operator=(U&& _value) { + value_ = std::forward(_value); + return *this; + } + + /// Assigns the value to its default using the Default sentinel. + template + requires std::is_default_constructible_v + auto& operator=(const Default&) { + value_ = Type(); + return *this; + } + + /// Copy assignment operator. + Alias& operator=(const Alias& _field) = default; + + /// Move assignment operator. + Alias& operator=(Alias&& _field) = default; + + /// Assigns from another Alias with compatible underlying type (copy). + template + requires(!std::is_same_v && std::is_convertible_v) + auto& operator=(const Alias<_name, U>& _field) { + value_ = _field.get(); + return *this; + } + + /// Assigns from another Alias with compatible underlying type (move). + template + requires(!std::is_same_v && std::is_convertible_v) + auto& operator=(Alias<_name, U>&& _field) { + value_ = std::move(_field.value_); + return *this; + } + + /// Sets the value (copy). + void set(const Type& _value) { value_ = _value; } + + /// Sets the value (move). + void set(Type&& _value) noexcept(std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + } + + /// Returns a reference to the underlying value. + constexpr Type& value() noexcept { return value_; } + + /// Returns a const reference to the underlying value. + constexpr const Type& value() const noexcept { return value_; } + + /// The underlying value. + Type value_; +}; + +/// Equality comparison between two Alias wrappers. +template + requires requires(const T1& _a, const T2& _b) { _a == _b; } +constexpr bool operator==(const Alias<_n1, T1>& _lhs, + const Alias<_n2, T2>& _rhs) { + return _lhs.value() == _rhs.value(); +} + +/// Three-way comparison between two Alias wrappers. +template + requires requires(const T1& _a, const T2& _b) { _a <=> _b; } +constexpr auto operator<=>(const Alias<_n1, T1>& _lhs, + const Alias<_n2, T2>& _rhs) { + return _lhs.value() <=> _rhs.value(); +} + +/// Equality comparison between an Alias wrapper and a non-Alias value. +template + requires(!internal::is_alias>::value && + requires(const T& _a, const U& _b) { _a == _b; }) +constexpr bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { + return _lhs.value() == _rhs; +} + +/// Three-way comparison between an Alias wrapper and a non-Alias value. +template + requires(!internal::is_alias>::value && + requires(const T& _a, const U& _b) { _a <=> _b; }) +constexpr auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) { + return _lhs.value() <=> _rhs; +} + +} // namespace rfl + +namespace std { + +/// Specialization of std::hash for rfl::Alias. +template + requires requires(const T& _v) { std::hash{}(_v); } +struct hash> { + size_t operator()(const rfl::Alias<_name, T>& _a) const { + return hash{}(_a.value()); + } +}; + +} // namespace std + +#endif diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index 0e76a6e8e..4029976cf 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -6,6 +6,7 @@ #include #include "Result.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -37,7 +38,10 @@ struct AllOf { try { auto res = Head::validate(std::move(_value)); if (!res) { - return res; + auto err = std::move(res).error(); + internal::set_error_kind_if_other(err, ErrorKind::constraint_violation); + internal::set_error_code_if_empty(err, internal::validator_code()); + return error(std::move(err)); } if constexpr (sizeof...(Tail) == 0) { return res; @@ -45,9 +49,12 @@ struct AllOf { return validate_impl(std::move(*res)); } } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::constraint_violation, + internal::validator_code()); } catch (...) { - return error("Unknown exception during validation."); + return error("Unknown exception during validation.", + ErrorKind::constraint_violation, + internal::validator_code()); } } }; diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index 91169998f..f74e4f98b 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -52,7 +52,9 @@ struct AnyOf { const auto handle_err = [&](Error&& _err) -> rfl::Result { _errors.push_back(std::forward(_err)); if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); + return error(Error(make_error_message(_errors), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::any_of)); } else { return validate_impl( _value, std::forward>(_errors)); diff --git a/include/rfl/Attribute.hpp b/include/rfl/Attribute.hpp index e277323bf..a54928d32 100644 --- a/include/rfl/Attribute.hpp +++ b/include/rfl/Attribute.hpp @@ -24,6 +24,8 @@ struct Attribute { using ReflectionType = T; /// Default constructor. + template + requires std::is_default_constructible_v Attribute() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/CamelCaseToSnakeCase.hpp b/include/rfl/CamelCaseToSnakeCase.hpp index dcc15d9e8..40753f789 100644 --- a/include/rfl/CamelCaseToSnakeCase.hpp +++ b/include/rfl/CamelCaseToSnakeCase.hpp @@ -1,8 +1,8 @@ #ifndef RFL_CAMELCASETOSNAKECASE_HPP_ #define RFL_CAMELCASETOSNAKECASE_HPP_ -#include "Field.hpp" -#include "internal/is_rename.hpp" +#include + #include "internal/transform_case.hpp" namespace rfl { @@ -15,28 +15,10 @@ struct CamelCaseToSnakeCase { /// @param _named_tuple The named tuple containing the struct's fields /// @return A new named tuple with field names converted to snake_case template - static auto process(const auto& _named_tuple) { - return _named_tuple.transform([](const FieldType& _f) { - if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { - return handle_one_field(_f); - } else { - return _f; - } - }); - } - - private: - /// Applies the camelCase to snake_case transformation to a single field. - /// @tparam FieldType The type of the field being transformed - /// @param _f The field to transform - /// @return A new field with the transformed name and the same value - template - static auto handle_one_field(const FieldType& _f) { - using NewFieldType = - Field(), - typename FieldType::Type>; - return NewFieldType(_f.value()); + static auto process(auto&& _named_tuple) { + return internal::transform_named_tuple_case< + internal::CamelCaseToSnakeCaseTransform>( + std::forward(_named_tuple)); } }; diff --git a/include/rfl/CodePoints.hpp b/include/rfl/CodePoints.hpp index edbadb986..093c8a72a 100644 --- a/include/rfl/CodePoints.hpp +++ b/include/rfl/CodePoints.hpp @@ -7,6 +7,7 @@ #include "Result.hpp" #include "Size.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -41,8 +42,11 @@ struct CodePoints { } auto res = V::validate(n); if (!res) { - return error("Code point count validation failed: " + - res.error().what()); + return error(internal::compose_prefixed_validator_error( + std::move(res).error(), + "Code point count validation failed: ", "code_points.", + internal::BuiltinErrorCode::code_points, + internal::compose_code_points_code)); } return std::move(_t); } diff --git a/include/rfl/Commented.hpp b/include/rfl/Commented.hpp index def8e58e4..9dba62aee 100644 --- a/include/rfl/Commented.hpp +++ b/include/rfl/Commented.hpp @@ -24,6 +24,8 @@ struct Commented { /// Default constructor - initializes with default-constructed value and no /// comment. + template + requires std::is_default_constructible_v Commented() : value_(Type()) {} /// Constructs from a value without a comment. diff --git a/include/rfl/DefaultIfNull.hpp b/include/rfl/DefaultIfNull.hpp new file mode 100644 index 000000000..c328692b9 --- /dev/null +++ b/include/rfl/DefaultIfNull.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_DEFAULTIFNULL_HPP_ +#define RFL_DEFAULTIFNULL_HPP_ + +namespace rfl { + +/// A processor that instructs parsers to use default values when encountering +/// null or empty input values. +/// This is a marker type (doesn't modify data) that changes parser behavior. +/// When an input value is null/empty (for example, `null`, `~`, or an empty +/// scalar in YAML, or `null` in JSON) and the target type is +/// default-constructible, the default value is used instead of treating it as +/// an error. On struct fields, in-class member initializers are preserved. +/// Nullable types such as `std::optional`, `std::unique_ptr`, +/// `std::shared_ptr`, and raw pointers continue to decode `null` as empty +/// (`std::nullopt` / `nullptr`). +/// Usage: rfl::yaml::read(yaml_str) +struct DefaultIfNull { + public: + /// Identity process function - returns the named tuple unchanged. + /// The actual default value application happens in the parser, 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 _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/DefaultTag.hpp b/include/rfl/DefaultTag.hpp new file mode 100644 index 000000000..3f94c4635 --- /dev/null +++ b/include/rfl/DefaultTag.hpp @@ -0,0 +1,41 @@ +#ifndef RFL_DEFAULTTAG_HPP_ +#define RFL_DEFAULTTAG_HPP_ + +#include + +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Opt-in processor that supplies a default discriminator tag value when a +/// `rfl::TaggedUnion<_discriminator, ...>` is deserialized from an object +/// whose `_discriminator` field is absent. +/// +/// Behavior: +/// - Only applies when the discriminator field is missing from the input object +/// (present non-string or unknown discriminator values still fail as usual). +/// - Writing always emits the explicit discriminator field. +/// - Validated at compile time: `_default_tag` must match one of the union's +/// allowed tags, and at most one `DefaultTag` may be specified per +/// `_discriminator`. +/// - Multiple `DefaultTag` processors with distinct discriminators may be +/// combined in a single `rfl::Processors<...>` bundle. +/// +/// Example: +/// using Schema = rfl::TaggedUnion<"version", ConfigV1, ConfigV2>; +/// auto cfg = rfl::yaml::read>(yaml); +template +struct DefaultTag { + static constexpr internal::StringLiteral discriminator_ = _discriminator; + static constexpr internal::StringLiteral default_tag_ = _default_tag; + + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/DefaultVal.hpp b/include/rfl/DefaultVal.hpp index d3c2edc4d..0cb34c423 100644 --- a/include/rfl/DefaultVal.hpp +++ b/include/rfl/DefaultVal.hpp @@ -19,6 +19,8 @@ struct DefaultVal { using Type = std::remove_cvref_t; /// Default constructor - initializes with default-constructed value. + template + requires std::is_default_constructible_v DefaultVal() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Deprecated.hpp b/include/rfl/Deprecated.hpp index e1cd712fb..dc0c4a5c2 100644 --- a/include/rfl/Deprecated.hpp +++ b/include/rfl/Deprecated.hpp @@ -36,6 +36,8 @@ struct Deprecated { using ReflectionType = Type; /// Default constructor. + template + requires std::is_default_constructible_v Deprecated() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Description.hpp b/include/rfl/Description.hpp index 37fc84092..8fc6b4869 100644 --- a/include/rfl/Description.hpp +++ b/include/rfl/Description.hpp @@ -30,6 +30,8 @@ struct Description { using ReflectionType = Type; /// Default constructor. + template + requires std::is_default_constructible_v Description() : value_(Type()) {} /// Constructs from a const reference to the value. 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 d266300c2..1dfdd94c7 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -1,12 +1,13 @@ #ifndef RFL_GENERIC_HPP_ #define RFL_GENERIC_HPP_ +#include #include #include #include +#include #include #include -#include #include "Object.hpp" #include "Result.hpp" @@ -62,6 +63,10 @@ class RFL_API Generic { /// @param _value The reflection type value (optional variant) Generic(const ReflectionType& _value); + /// Constructs from a reflection type (move). + /// @param _value The reflection type value (optional variant, will be moved) + Generic(ReflectionType&& _value) noexcept; + /// Constructs from any type convertible to VariantType (copy). /// @tparam T The type to convert from /// @param _value The value to convert and wrap @@ -118,6 +123,16 @@ class RFL_API Generic { /// @return Reference to this object Generic& operator=(VariantType&& _value) noexcept; + /// Assigns from a reflection type. + /// @param _value The reflection type value to assign + /// @return Reference to this object + Generic& operator=(const ReflectionType& _value); + + /// Assigns from a reflection type (move). + /// @param _value The reflection type value to assign (will be moved) + /// @return Reference to this object + Generic& operator=(ReflectionType&& _value) noexcept; + /// Assigns from any type convertible to VariantType. /// Handles special conversions for numeric types to ensure proper variant /// alternative selection. @@ -140,6 +155,32 @@ class RFL_API Generic { return *this; } + /// Assigns from any rvalue type convertible to VariantType (move). + /// Handles special conversions for numeric types to ensure proper variant + /// alternative selection. + /// @tparam T The type to convert from + /// @param _value The value to move-assign + /// @return Reference to this object + template + requires(!std::is_lvalue_reference_v && !std::is_const_v && + !std::is_same_v, Generic> && + !std::is_same_v, VariantType> && + !std::is_same_v, ReflectionType> && + std::is_convertible_v) + auto& operator=(T&& _value) { + using Type = std::remove_cvref_t; + if constexpr (std::is_same_v) { + value_.emplace<0>(_value); + } else if constexpr (std::is_integral_v) { + value_.emplace<1>(static_cast(_value)); + } else if constexpr (std::is_floating_point_v) { + value_.emplace<2>(static_cast(_value)); + } else { + value_ = std::move(_value); + } + return *this; + } + /// Copy assignment operator. /// @param _other The Generic to copy from /// @return Reference to this object @@ -159,7 +200,8 @@ class RFL_API Generic { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( "rfl::Generic: Could not cast the underlying value to an " - "rfl::Generic::Array."); + "rfl::Generic::Array.", + ErrorKind::invalid_type); } /// Casts the underlying value to a boolean or returns an rfl::Error, if the @@ -167,7 +209,8 @@ class RFL_API Generic { Result to_bool() const noexcept { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( - "rfl::Generic: Could not cast the underlying value to a boolean."); + "rfl::Generic: Could not cast the underlying value to a boolean.", + ErrorKind::invalid_type); } /// Casts the underlying value to a double or returns an rfl::Error, if the @@ -216,6 +259,11 @@ class RFL_API Generic { /// @return The converted variant type static VariantType from_reflection_type(const ReflectionType& _r) noexcept; + /// Converts a ReflectionType to a VariantType by moving the contained value. + /// @param _r The reflection type (optional variant) to move from + /// @return The converted variant type + static VariantType from_reflection_type(ReflectionType&& _r) noexcept; + /// Checks if two Generic instances are equal by comparing their type indices /// and their underlying values. This is used to implement the equality /// operator for the Generic class. diff --git a/include/rfl/Int64AsString.hpp b/include/rfl/Int64AsString.hpp new file mode 100644 index 000000000..80ba46158 --- /dev/null +++ b/include/rfl/Int64AsString.hpp @@ -0,0 +1,22 @@ +#ifndef RFL_INT64ASSTRING_HPP_ +#define RFL_INT64ASSTRING_HPP_ + +#include + +namespace rfl { + +/// Opt-in processor instructing parsers to serialize and deserialize 64-bit +/// (and wider) integer types as base-10 strings instead of format numbers. +/// Useful when sharing one pure C++ struct (plain int64_t / uint64_t) across +/// binary/columnar formats (Arrow, CBOR, MsgPack, Parquet) and JS/Protobuf-JSON +/// APIs that lose integer precision above 2^53 - 1. +struct Int64AsString { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif 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 161dc9f79..c5da2eb9e 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -1,20 +1,22 @@ #ifndef RFL_LITERAL_HPP_ #define RFL_LITERAL_HPP_ +#include #include +#include #include #include #include +#include #include +#include #include #include #include #include "Result.hpp" -#include "Tuple.hpp" #include "internal/StringLiteral.hpp" -#include "internal/find_index.hpp" -#include "internal/no_duplicate_field_names.hpp" +#include "internal/cold.hpp" namespace rfl { @@ -24,15 +26,287 @@ struct LiteralHelper { constexpr static internal::StringLiteral name_ = _name; }; +template +class Literal; + +namespace internal { + +template +struct is_literal_type : std::false_type {}; + +template +struct is_literal_type> : std::true_type {}; + +template +inline constexpr bool is_literal_type_v = is_literal_type::value; + +struct LiteralNameEntry { + std::string_view name; + int idx; +}; + +/// Strict total order on string_view (length first, then unsigned-byte +/// lexicographical). Comparing length and first byte before full byte compare +/// avoids memcmp calls on most binary-search steps while staying 100% +/// constexpr-consistent between table construction and runtime lookup. +constexpr bool literal_name_less(const std::string_view _a, + const std::string_view _b) noexcept { + if (_a.size() != _b.size()) { + return _a.size() < _b.size(); + } + if (_a.empty()) { + return false; + } + if (_a[0] != _b[0]) { + return static_cast(_a[0]) < + static_cast(_b[0]); + } + return _a < _b; +} + +constexpr bool literal_entry_less(const LiteralNameEntry& _a, + const LiteralNameEntry& _b) noexcept { + if (_a.name.size() != _b.name.size()) { + return _a.name.size() < _b.name.size(); + } + const int cmp = _a.name.compare(_b.name); + return cmp < 0 || (cmp == 0 && _a.idx < _b.idx); +} + +/// O(N log N) constexpr heapsort for Literal name tables (avoids relying on +/// C++20 constexpr std::sort support in older libc++ releases). Tie-breaks +/// duplicate strings by ascending original index so lower_bound preserves +/// first-match semantics. +template +constexpr std::array make_sorted_literal_table( + const std::array& _names) noexcept { + std::array table{}; + for (std::size_t i = 0; i < _n; ++i) { + table[i] = LiteralNameEntry{_names[i], static_cast(i)}; + } + auto sift_down = [&](std::size_t _root, const std::size_t _end) { + while (true) { + std::size_t child = _root * 2 + 1; + if (child >= _end) { + break; + } + if (child + 1 < _end && + literal_entry_less(table[child], table[child + 1])) { + ++child; + } + if (literal_entry_less(table[_root], table[child])) { + const auto tmp = table[_root]; + table[_root] = table[child]; + table[child] = tmp; + _root = child; + } else { + break; + } + } + }; + for (std::size_t start = _n / 2; start > 0; --start) { + sift_down(start - 1, _n); + } + for (std::size_t end = _n; end > 1; --end) { + const auto tmp = table[0]; + table[0] = table[end - 1]; + table[end - 1] = tmp; + sift_down(0, end - 1); + } + return table; +} + +constexpr int find_literal_index_linear( + const std::span _names, + const std::string_view _target) noexcept { + for (std::size_t i = 0; i < _names.size(); ++i) { + if (_names[i] == _target) { + return static_cast(i); + } + } + return -1; +} + +constexpr int find_literal_index_binary( + const std::span _table, + const std::string_view _target) noexcept { + if (_table.empty()) { + return -1; + } + std::size_t base = 0; + std::size_t len = _table.size(); + while (len > 1) { + const std::size_t half = len >> 1; + base += + literal_name_less(_table[base + half - 1].name, _target) ? half : 0; + len -= half; + } + if (_table[base].name == _target) { + return _table[base].idx; + } + return -1; +} + +consteval bool literal_contains_any_linear( + const std::span _a, + const std::span _b) noexcept { + for (const auto name : _a) { + if (find_literal_index_linear(_b, name) >= 0) { + return true; + } + } + return false; +} + +consteval bool literal_contains_any_lookup( + const std::span _a, + const std::span _b_sorted) noexcept { + for (const auto name : _a) { + if (find_literal_index_binary(_b_sorted, name) >= 0) { + return true; + } + } + return false; +} + +consteval bool literal_contains_any_sorted( + const std::span _a_sorted, + const std::span _b_sorted) noexcept { + std::size_t i = 0; + std::size_t j = 0; + while (i < _a_sorted.size() && j < _b_sorted.size()) { + if (_a_sorted[i].name == _b_sorted[j].name) { + return true; + } + if (literal_name_less(_a_sorted[i].name, _b_sorted[j].name)) { + ++i; + } else { + ++j; + } + } + return false; +} + +consteval bool literal_contains_all_linear( + const std::span _a, + const std::span _b) noexcept { + for (const auto name : _a) { + if (find_literal_index_linear(_b, name) < 0) { + return false; + } + } + return true; +} + +consteval bool literal_contains_all_lookup( + const std::span _a, + const std::span _b_sorted) noexcept { + for (const auto name : _a) { + if (find_literal_index_binary(_b_sorted, name) < 0) { + return false; + } + } + return true; +} + +consteval bool literal_contains_all_sorted( + const std::span _a_sorted, + const std::span _b_sorted) noexcept { + std::size_t i = 0; + std::size_t j = 0; + while (i < _a_sorted.size()) { + while (j < _b_sorted.size() && + literal_name_less(_b_sorted[j].name, _a_sorted[i].name)) { + ++j; + } + if (j == _b_sorted.size() || _b_sorted[j].name != _a_sorted[i].name) { + return false; + } + ++i; + } + return true; +} + +consteval bool literal_has_duplicates_linear( + const std::span _names) noexcept { + for (std::size_t i = 0; i < _names.size(); ++i) { + for (std::size_t j = i + 1; j < _names.size(); ++j) { + if (_names[i] == _names[j]) { + return true; + } + } + } + return false; +} + +consteval bool literal_has_duplicates_sorted( + const std::span _table) noexcept { + for (std::size_t i = 1; i < _table.size(); ++i) { + if (_table[i].name == _table[i - 1].name) { + return true; + } + } + return false; +} + +constexpr std::strong_ordering compare_literal_sv( + const std::string_view _a, const std::string_view _b) noexcept { +#if __cpp_lib_three_way_comparison >= 201907L + return _a <=> _b; +#else + const int cmp = _a.compare(_b); + if (cmp < 0) { + return std::strong_ordering::less; + } + if (cmp > 0) { + return std::strong_ordering::greater; + } + return std::strong_ordering::equal; +#endif +} + +inline std::vector literal_allowed_strings_vec( + const std::span _names) { + std::vector values; + values.reserve(_names.size()); + for (const auto name : _names) { + values.emplace_back(name); + } + return values; +} + +RFL_COLD inline Unexpected make_unsupported_literal_error( + const std::string_view _str, + const std::span _names) { + std::string msg; + msg.reserve(80 + _str.size() + _names.size() * 8); + msg += "Literal does not support string '"; + msg += _str; + msg += "'. The following strings are supported: "; + for (std::size_t i = 0; i < _names.size(); ++i) { + if (i != 0) { + msg += ", "; + } + msg += '\''; + msg += _names[i]; + msg += '\''; + } + msg += '.'; + return rfl::error(std::move(msg), ErrorKind::invalid_value); +} + +} // namespace internal + /// A type-safe representation of a fixed set of string values known at compile /// time. Similar to an enum but with string values. Useful for representing /// discriminators, status values, or any fixed set of string constants with /// compile-time validation. /// @tparam fields_ The compile-time string literals that this Literal can /// represent -template +template class Literal { - using FieldsType = rfl::Tuple...>; + template + friend class Literal; public: using ValueType = std::conditional_t - static Literal make() { + static constexpr Literal make() { return Literal(Literal::template value_of<_name>()); } @@ -79,7 +353,7 @@ class Literal { /// @tparam _name The compile-time string literal to create a Literal for /// @return A Literal representing the specified name template - static Literal from_name() { + static constexpr Literal from_name() { return Literal::template make<_name>(); } @@ -97,20 +371,20 @@ class Literal { /// @param _value The index of the value /// @return Result containing the Literal or an error if the value is out of /// range - static Result> from_value(ValueType _value) { - if (_value >= num_fields_) { - return error("Value cannot exceed number of fields."); + static Result> from_value(const ValueType _value) { + if constexpr (num_fields_ > 0) { + if (_value < num_fields_) { + return Literal(_value); + } } - return Literal(_value); + return error("Value cannot exceed number of fields.", ErrorKind::invalid_value); } /// Determines whether the literal contains the string (runtime check). /// @param _str The string to check for /// @return true if the string is one of the allowed values, false otherwise - static bool contains(const std::string& _str) { - bool found = false; - has_value(_str, &found); - return found; + static constexpr bool contains(const std::string_view _str) noexcept { + return find_index_runtime(_str) >= 0; } /// Determines whether the literal contains the string at compile time. @@ -127,31 +401,64 @@ class Literal { /// @return true if there is any overlap between the two literal types template static constexpr bool contains_any() { - return [](const std::integer_sequence&) { - return (false || ... || - OtherLiteralType::template contains< - find_name_within_own_fields<_is>()>()); - }(std::make_integer_sequence()); + if constexpr (num_fields_ == 0 || OtherLiteralType::num_fields_ == 0) { + return false; + } else if constexpr (num_fields_ > 8 && + OtherLiteralType::num_fields_ > 8) { + constexpr bool result = internal::literal_contains_any_sorted( + SortedTable::value, OtherLiteralType::SortedTable::value); + return result; + } else if constexpr (OtherLiteralType::num_fields_ > 8) { + constexpr bool result = internal::literal_contains_any_lookup( + kNames, OtherLiteralType::SortedTable::value); + return result; + } else { + constexpr bool result = internal::literal_contains_any_linear( + kNames, OtherLiteralType::kNames); + return result; + } } /// Determines whether the literal contains all of the strings in the other /// literal at compile time. /// @tparam OtherLiteralType Another Literal type to check against - /// @return true if this literal contains all values from the other literal + /// @return true if all values of this literal exist in the other literal template static constexpr bool contains_all() { - return [](const std::integer_sequence&) { - return (true && ... && - OtherLiteralType::template contains< - find_name_within_own_fields<_is>()>()); - }(std::make_integer_sequence()); + if constexpr (num_fields_ == 0) { + return true; + } else if constexpr (OtherLiteralType::num_fields_ == 0) { + return false; + } else if constexpr (num_fields_ > 8 && + OtherLiteralType::num_fields_ > 8) { + constexpr bool result = internal::literal_contains_all_sorted( + SortedTable::value, OtherLiteralType::SortedTable::value); + return result; + } else if constexpr (OtherLiteralType::num_fields_ > 8) { + constexpr bool result = internal::literal_contains_all_lookup( + kNames, OtherLiteralType::SortedTable::value); + return result; + } else { + constexpr bool result = internal::literal_contains_all_linear( + kNames, OtherLiteralType::kNames); + return result; + } } /// Determines whether the literal has duplicate strings at compile time. /// This is useful for checking collections of strings in other contexts. /// @return true if there are duplicate values in the literal static constexpr bool has_duplicates() { - return !internal::no_duplicate_field_names(); + if constexpr (num_fields_ <= 1) { + return false; + } else if constexpr (num_fields_ <= 8) { + constexpr bool result = internal::literal_has_duplicates_linear(kNames); + return result; + } else { + constexpr bool result = + internal::literal_has_duplicates_sorted(SortedTable::value); + return result; + } } /// Constructs a Literal from a string. Returns an error if the string @@ -159,21 +466,39 @@ class Literal { /// @param _str The string to convert to a Literal /// @return Result containing the Literal or an error if the string is not /// recognized - static Result from_string(const std::string& _str) { - const auto to_literal = [](const auto& _v) { - return Literal(_v); - }; - return find_value(_str).transform(to_literal); + static Result from_string(const std::string_view _str) { + if constexpr (num_fields_ == 0) { + return internal::make_unsupported_literal_error( + _str, std::span{}); + } else { + const int idx = find_index_runtime(_str); + if (idx < 0) [[unlikely]] { + return internal::make_unsupported_literal_error(_str, kNames); + } + return Literal(static_cast(idx)); + } } /// 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(); } + std::string name() const { return std::string(name_sv()); } + + /// 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 kNames[0]; + } /// Returns all possible values of the literal as a std::vector. /// @return A vector containing all allowed string values static std::vector names() { - return allowed_strings_vec(std::make_integer_sequence()); + if constexpr (num_fields_ == 0) { + return {}; + } else { + return internal::literal_allowed_strings_vec(kNames); + } } /// Helper function to retrieve a name at compile time. @@ -188,13 +513,14 @@ class Literal { /// Copy assignment operator - assigns from another literal. /// @param _other The literal to copy from /// @return Reference to this literal - Literal& operator=(const Literal& _other) = default; + constexpr Literal& operator=( + const Literal& _other) = default; /// Move assignment operator - assigns from another literal. /// @param _other The literal to move from /// @return Reference to this literal - Literal& operator=(Literal&& _other) noexcept = - default; + constexpr Literal& operator=( + Literal&& _other) noexcept = default; /// Assigns the literal from a string. /// @param _str The string to assign (must be one of the allowed values) @@ -210,7 +536,7 @@ class Literal { /// Compares by internal value index. /// @param _other The other literal to compare with /// @return The ordering relationship between the two literals - auto operator<=>(const Literal& _other) const { + constexpr auto operator<=>(const Literal& _other) const noexcept { return value() <=> _other.value(); } @@ -220,47 +546,32 @@ class Literal { /// @param _l2 The other literal to compare with /// @return The ordering relationship between the string values template - inline auto operator<=>(const Literal<_fields...>& _l2) const { - return name() <=> _l2.name(); + constexpr auto operator<=>(const Literal<_fields...>& _l2) const noexcept { + return internal::compare_literal_sv(name_sv(), _l2.name_sv()); + } + + /// Three-way comparison operator for string_view. + /// @param _str The string_view to compare with + /// @return The ordering relationship between the literal's value and the + /// string_view + constexpr auto operator<=>(const std::string_view _str) const noexcept { + return internal::compare_literal_sv(name_sv(), _str); } /// Three-way comparison operator for strings. /// @param _str The string to compare with /// @return The ordering relationship between the literal's value and the /// string - inline auto operator<=>(const std::string& _str) const { -#if __cpp_lib_three_way_comparison >= 201907L - return name() <=> _str; -#else - auto const& const_name = name(); - if (const_name < _str) { - return std::strong_ordering::less; - } - if (const_name == _str) { - return std::strong_ordering::equal; - } - return std::strong_ordering::greater; -#endif + auto operator<=>(const std::string& _str) const noexcept { + return internal::compare_literal_sv(name_sv(), _str); } /// Three-way comparison operator for const char*. - /// @tparam other_fields Template parameter for compatibility /// @param _str The C-string to compare with /// @return The ordering relationship between the literal's value and the /// string - inline auto operator<=>(const char* _str) const { -#if __cpp_lib_three_way_comparison >= 201907L - return name() <=> _str; -#else - auto const& const_name = name(); - if (const_name < _str) { - return std::strong_ordering::less; - } - if (const_name == _str) { - return std::strong_ordering::equal; - } - return std::strong_ordering::greater; -#endif + constexpr auto operator<=>(const char* _str) const noexcept { + return internal::compare_literal_sv(name_sv(), std::string_view(_str)); } /// Equality operator - works with Literals, strings, and other comparable @@ -269,8 +580,20 @@ class Literal { /// @param _other The value to compare with /// @return true if the values are equal template - bool operator==(const Other& _other) const { - return (*this <=> _other) == 0; + constexpr bool operator==(const Other& _other) const { + if constexpr (std::is_same_v>) { + return value_ == _other.value_; + } else if constexpr (internal::is_literal_type_v) { + return name_sv() == _other.name_sv(); + } else if constexpr (std::is_same_v || + std::is_same_v) { + return name_sv() == _other; + } else if constexpr (std::is_same_v, const char*> || + std::is_same_v, char*>) { + return name_sv() == std::string_view(_other); + } else { + return (*this <=> _other) == 0; + } } /// Alias for .name() - returns the string representation for reflection. @@ -287,13 +610,11 @@ class Literal { /// Alias for .names() - returns all possible string values. /// @return A vector containing all allowed string values - static std::vector strings() { - return allowed_strings_vec(std::make_integer_sequence()); - } + static std::vector strings() { return names(); } /// Returns the value actually contained in the Literal (the internal index). /// @return The index representing the current value - ValueType value() const { return value_; } + constexpr ValueType value() const noexcept { return value_; } /// Returns the value index of the string literal in the template at compile /// time. @@ -301,113 +622,84 @@ class Literal { /// @return The index of the specified name template static constexpr ValueType value_of() { - constexpr auto value = find_value_of<_name>(); + constexpr int value = find_value_of<_name>(); static_assert(value >= 0, "String not supported."); - return value; + return static_cast(value); } private: - /// Only the static methods are allowed to access this constructor. - /// @param _value The internal value index - Literal(const ValueType _value) : value_(_value) {} - - /// Returns all of the allowed fields. - static std::string allowed_strings() { - const auto vec = - allowed_strings_vec(std::make_integer_sequence()); - std::string str; - for (size_t i = 0; i < vec.size(); ++i) { - const auto head = "'" + vec[i] + "'"; - str += i == 0 ? head : (", " + head); - } - return str; - } - - /// Returns all of the allowed fields. - template - static std::vector allowed_strings_vec( - std::integer_sequence) { - std::vector values; - (allowed_strings_vec_add_one<_is>(&values), ...); - return values; - } - - template - static void allowed_strings_vec_add_one(std::vector* _values) { - using FieldType = tuple_element_t<_i, FieldsType>; - _values->emplace_back(FieldType::name_.str()); - } - - /// Finds the correct index associated with - /// the string at run time. - std::string find_name() const { - return find_name_set_str(std::make_integer_sequence()); - } + static constexpr std::array kNames = { + fields_.string_view()...}; - template - std::string find_name_set_str(std::integer_sequence) const { - std::string name; - (find_name_set_if_matches<_is>(&name), ...); - return name; - } + struct SortedTable { + static constexpr std::array value = + internal::make_sorted_literal_table(kNames); + }; - template - void find_name_set_if_matches(std::string* _name) const { - if (_i == value_) { - using FieldType = tuple_element_t<_i, FieldsType>; - *_name = FieldType::name_.str(); + /// Only the static methods are allowed to access this constructor. + /// @param _value The internal value index + constexpr Literal(const ValueType _value) noexcept : value_(_value) {} + + /// Returns the string_view of the current value in O(1) without allocation. + constexpr std::string_view name_sv() const noexcept { + if constexpr (num_fields_ == 0) { + return std::string_view{}; + } else { + return value_ < num_fields_ ? kNames[value_] : std::string_view{}; } } - /// Finds the correct index associated with - /// the string at compile time within the Literal's own fields. + /// Finds the name at index _i at compile time within the Literal's own + /// fields. template constexpr static auto find_name_within_own_fields() { - return tuple_element_t<_i, FieldsType>::name_; + static_assert(_i >= 0 && _i < static_cast(num_fields_), + "Index out of bounds."); + constexpr std::string_view sv = kNames[static_cast(_i)]; + return internal::StringLiteral(sv); + } + + /// Finds the index associated with the string, or -1 if not found. + static constexpr int find_index_runtime( + const std::string_view _str) noexcept { + if constexpr (num_fields_ == 0) { + return -1; + } else if constexpr (num_fields_ <= 8) { + return internal::find_literal_index_linear(kNames, _str); + } else { + return internal::find_literal_index_binary(SortedTable::value, _str); + } } /// Finds the correct value associated with /// the string at run time. - static Result find_value(const std::string& _str) { - bool found = false; - const auto idx = find_value_set_idx( - _str, &found, std::make_integer_sequence()); - if (!found) { - return error( - "Literal does not support string '" + _str + - "'. The following strings are supported: " + allowed_strings() + "."); - } - return idx; - } - - template - static int find_value_set_idx(const std::string& _str, bool* _found, - std::integer_sequence) { - int idx = 0; - (find_value_set_if_matches<_is>(_str, _found, &idx), ...); - return idx; - } - - template - static void find_value_set_if_matches(const std::string& _str, bool* _found, - int* _idx) { - using FieldType = tuple_element_t<_i, FieldsType>; - if (!*_found && FieldType::name_.string_view() == _str) { - *_idx = _i; - *_found = true; + static Result find_value(const std::string_view _str) { + if constexpr (num_fields_ == 0) { + return internal::make_unsupported_literal_error( + _str, std::span{}); + } else { + const int idx = find_index_runtime(_str); + if (idx < 0) [[unlikely]] { + return internal::make_unsupported_literal_error(_str, kNames); + } + return static_cast(idx); } } /// Finds the value of a string literal at compile time. template static constexpr int find_value_of() { - return internal::find_index_or_minus_one<_name, FieldsType>(); - } - - /// Whether the literal contains this string. - static void has_value(const std::string& _str, bool* _found) { - find_value_set_idx(_str, _found, - std::make_integer_sequence()); + if constexpr (num_fields_ == 0) { + return -1; + } else if constexpr (num_fields_ <= 8) { + constexpr int idx = + internal::find_literal_index_linear(kNames, _name.string_view()); + return idx; + } else { + constexpr int idx = internal::find_literal_index_binary( + SortedTable::value, _name.string_view()); + return idx; + } } static_assert(sizeof...(fields_) <= std::numeric_limits::max(), diff --git a/include/rfl/MaxDepth.hpp b/include/rfl/MaxDepth.hpp new file mode 100644 index 000000000..0b3ef7109 --- /dev/null +++ b/include/rfl/MaxDepth.hpp @@ -0,0 +1,37 @@ +#ifndef RFL_MAXDEPTH_HPP_ +#define RFL_MAXDEPTH_HPP_ + +#include +#include + +namespace rfl { + +/// Opt-in processor that bounds container and struct nesting depth during +/// deserialization to prevent stack-overflow DoS on deeply nested untrusted +/// inputs (such as `rfl::Generic` or recursive `rfl::Box` structs). +/// +/// Behavior: +/// - Zero runtime overhead when not passed (`if constexpr`). +/// - Applies uniformly across all formats (JSON, YAML, TOML, XML, CBOR, etc.). +/// - Returns an `rfl::Error` ("Maximum nesting depth of N exceeded.") instead +/// of overflowing the C++ call stack. +/// - Thread-safe and exception-safe (uses a thread-local RAII depth counter). +/// +/// Example: +/// auto res = rfl::json::read>(untrusted); +template +struct MaxDepth { + static_assert(_max_depth > 0, + "rfl::MaxDepth requires a positive depth limit."); + + static constexpr std::size_t value = _max_depth; + + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Metadata.hpp b/include/rfl/Metadata.hpp new file mode 100644 index 000000000..21c5cd786 --- /dev/null +++ b/include/rfl/Metadata.hpp @@ -0,0 +1,203 @@ +#ifndef RFL_METADATA_HPP_ +#define RFL_METADATA_HPP_ + +#include +#include +#include +#include +#include +#include + +namespace rfl { + +/// Out-of-band per-field metadata (description and optional deprecation) that +/// attaches schema/documentation prose to a reflected struct WITHOUT embedding +/// long `StringLiteral` non-type template parameters into C++ field types. +struct FieldMeta { + /// Processed wire field name, or pre-processor field name (C++ member name, + /// or explicit `rfl::Rename` name when renamed). Exact wire-name matches + /// take precedence over pre-processor names. + std::string_view name; + + /// Optional human-readable description emitted in generated schemas. + std::string_view description = {}; + + /// Optional deprecation message. When non-empty, marks the field deprecated + /// in generated schemas (with `description`, matching `rfl::Deprecated`). + std::string_view deprecation_message = {}; +}; + +/// Specialize `rfl::Metadata` to attach zero-bloat out-of-band metadata to +/// struct `T` without wrapping its fields in `rfl::Description` / +/// `rfl::Deprecated`. +/// +/// Supported members on a specialization `rfl::Metadata`: +/// - `static constexpr std::array fields = ...;` +/// (or any contiguous collection / `std::span`), OR +/// - `static std::span fields();` (or returning a +/// `const` lvalue reference to a contiguous collection; may be defined +/// out-of-line in a `.cpp` file for complete compile-time isolation). +/// - Optional struct-level description: +/// `static constexpr std::string_view description = "...";` (or a `const +/// char*`; `nullptr` is treated as empty) or +/// `static std::string_view description();` +/// +/// Notes: +/// - `rfl::Metadata` attaches to `Inner`'s own schema definition +/// (`$defs/Inner`); fields flattened via `rfl::Flatten` are looked up +/// on the enclosing struct's `rfl::Metadata`. +/// - For `rfl::TaggedUnion` alternatives wrapped in an internal tagged-union +/// wrapper, `rfl::Metadata` is consulted automatically. +/// - For custom types with `ReflectionType` or `rfl::Reflector`, +/// struct-level `Metadata::description` is honored; `Metadata::fields` +/// applies to reflected aggregate structs. +template +struct Metadata {}; + +namespace internal { + +template +struct is_field_meta_span : std::false_type {}; + +template +struct is_field_meta_span> + : std::true_type {}; + +template +struct is_field_meta_span> : std::true_type {}; + +template +struct is_field_meta_c_array : std::false_type {}; + +template +struct is_field_meta_c_array : std::true_type {}; + +template +struct is_field_meta_c_array : std::true_type {}; + +template +concept ContiguousFieldMetaCollection = + is_field_meta_c_array>::value || + requires(const std::remove_reference_t& _r) { + { _r.data() }; + { _r.size() }; + requires std::is_pointer_v; + requires std::is_same_v< + std::remove_cv_t>, + FieldMeta>; + requires std::is_convertible_v; + }; + +template +constexpr std::span to_field_meta_span(const R& _r) noexcept { + if constexpr (is_field_meta_c_array>::value) { + return std::span( + _r, std::extent_v>); + } else { + return std::span(_r.data(), + static_cast(_r.size())); + } +} + +template +concept HasFieldMetaVar = requires { + { Metadata::fields } -> ContiguousFieldMetaCollection; + requires !std::is_member_object_pointer_v::fields)>; +}; + +template +concept HasAnyFieldMetaFn = requires { + { Metadata::fields() } -> ContiguousFieldMetaCollection; +}; + +template +concept HasFieldMetaFn = + HasAnyFieldMetaFn && + (std::is_lvalue_reference_v::fields())> || + is_field_meta_span< + std::remove_cvref_t::fields())>>::value); + +template +constexpr bool has_field_metadata_v = HasFieldMetaVar> || + HasAnyFieldMetaFn>; + +template +std::span get_field_metadata() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyFieldMetaFn || HasFieldMetaFn, + "rfl::Metadata::fields() must return a borrowed contiguous range " + "(for example, std::span or const auto&) so the " + "returned view does not dangle."); + if constexpr (HasFieldMetaFn) { + auto&& r = Metadata::fields(); + return to_field_meta_span(r); + } else if constexpr (HasFieldMetaVar) { + return to_field_meta_span(Metadata::fields); + } else { + return {}; + } +} + +template +concept HasStructDescriptionVar = requires { + Metadata::description; + requires std::is_convertible_v::description), + std::string_view>; + requires !std::is_member_object_pointer_v< + decltype(&Metadata::description)>; +}; + +template +concept HasStructDescriptionFn = requires { + Metadata::description(); + requires std::is_convertible_v::description()), + std::string_view>; +}; + +template +constexpr bool has_struct_description_v = + HasStructDescriptionVar> || + HasStructDescriptionFn>; + +template +std::string get_struct_description() { + using U = std::remove_cvref_t; + auto to_sv = [](const auto& _d) -> std::string_view { + if constexpr (std::is_pointer_v>) { + return _d ? std::string_view(_d) : std::string_view{}; + } else { + return std::string_view(_d); + } + }; + if constexpr (HasStructDescriptionFn) { + return std::string(to_sv(Metadata::description())); + } else if constexpr (HasStructDescriptionVar) { + return std::string(to_sv(Metadata::description)); + } else { + return {}; + } +} + +inline std::optional find_field_metadata( + const std::span _meta, const std::string_view _wire_name, + const std::string_view _raw_name = {}) noexcept { + for (const auto& entry : _meta) { + if (entry.name == _wire_name) { + return entry; + } + } + if (!_raw_name.empty() && _raw_name != _wire_name) { + for (const auto& entry : _meta) { + if (entry.name == _raw_name) { + return entry; + } + } + } + return std::nullopt; +} + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 9123b188d..fb6e7da08 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -2,6 +2,8 @@ #define RFL_NAMEDTUPLE_HPP_ #include +#include +#include #include #include #include @@ -20,6 +22,38 @@ namespace rfl { +namespace internal { + +struct from_values_tuple_t { + explicit from_values_tuple_t() = default; +}; + +inline constexpr from_values_tuple_t from_values_tuple{}; + +/// Finds the position of rfl::ExtraFields in a field pack, returning -1 if none +/// is present or -2 if more than one is present. +template +consteval int find_extra_fields() noexcept { + if constexpr (sizeof...(FieldTypes) == 0) { + return -1; + } else { + constexpr std::array flags{ + is_extra_fields_v::Type>...}; + int idx = -1; + for (std::size_t i = 0; i < flags.size(); ++i) { + if (flags[i]) { + if (idx != -1) { + return -2; + } + idx = static_cast(i); + } + } + return idx; + } +} + +} // namespace internal + /// A named tuple behaves like a tuple, /// but the fields have explicit names, which /// allows for reflection. @@ -81,6 +115,15 @@ class NamedTuple { NamedTuple(const rfl::Tuple& _tup) : NamedTuple(rfl::make_from_tuple>(_tup)) {} + /// @brief Construct NamedTuple directly from its Values tuple (rvalue). + explicit NamedTuple(internal::from_values_tuple_t, Values&& _values) noexcept( + std::is_nothrow_move_constructible_v) + : values_(std::move(_values)) {} + + /// @brief Construct NamedTuple directly from its Values tuple (const lvalue). + explicit NamedTuple(internal::from_values_tuple_t, const Values& _values) + : values_(_values) {} + /// @brief Copy constructor. /// @param _other Another NamedTuple to copy from. NamedTuple(const NamedTuple& _other) = default; @@ -547,29 +590,6 @@ class NamedTuple { } } - /// @brief Finds the position of the extra fields, or -1 if there aren't any. - /// @tparam _i Current index. - /// @tparam _idx Index of ExtraFields found so far. - /// @return Position of ExtraFields or -1. - template - constexpr static int find_extra_fields() { - if constexpr (_i == size()) { - return _idx; - } else { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - constexpr bool is_extra_fields = - internal::is_extra_fields_v; - static_assert(_idx == -1 || !is_extra_fields, - "There can only be one rfl::ExtraFields in any struct or " - "named tuple."); - if constexpr (is_extra_fields) { - return find_extra_fields<_i + 1, _i>(); - } else { - return find_extra_fields<_i + 1, _idx>(); - } - } - } - /// @brief Generates the fields for the NamedTuple (rvalue overload). /// @tparam _is Indices of the fields. /// @tparam AdditionalArgs Additional arguments to append. @@ -578,12 +598,9 @@ class NamedTuple { template auto make_fields(std::integer_sequence, AdditionalArgs&&... _args) && { - const auto wrap = [this](Index<_i>) { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - return FieldType(std::move(rfl::get<_i>(values_))); - }; - return rfl::make_tuple(wrap(Index<_is>{})..., - std::forward(_args)...); + return rfl::make_tuple( + std::remove_cvref_t(std::move(rfl::get<_is>(values_)))..., + std::forward(_args)...); } /// @brief Generates the fields for the NamedTuple (const lvalue overload). @@ -594,11 +611,8 @@ class NamedTuple { template auto make_fields(std::integer_sequence, AdditionalArgs... _args) const& { - const auto wrap = [this](Index<_i>) { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - return FieldType(rfl::get<_i>(values_)); - }; - return rfl::make_tuple(wrap(Index<_is>{})..., _args...); + return rfl::make_tuple( + std::remove_cvref_t(rfl::get<_is>(values_))..., _args...); } /// @brief Generates a new NamedTuple with one value replaced with a new @@ -702,7 +716,12 @@ class NamedTuple { Values values_; /// @brief The position of rfl::ExtraFields, or -1 if there aren't any. - constexpr static int pos_extra_fields_ = find_extra_fields(); + constexpr static int pos_extra_fields_ = + internal::find_extra_fields(); + + static_assert(pos_extra_fields_ != -2, + "There can only be one rfl::ExtraFields in any struct or " + "named tuple."); }; // ---------------------------------------------------------------------------- @@ -718,6 +737,13 @@ class NamedTuple<> { /// @brief Default constructor for empty NamedTuple. NamedTuple() {} + /// @brief Construct empty NamedTuple directly from its Values tuple (rvalue). + explicit NamedTuple(internal::from_values_tuple_t, Values&&) noexcept {} + + /// @brief Construct empty NamedTuple directly from its Values tuple (const + /// lvalue). + explicit NamedTuple(internal::from_values_tuple_t, const Values&) noexcept {} + /// @brief Destructor. ~NamedTuple() = default; diff --git a/include/rfl/NoDuplicateKeys.hpp b/include/rfl/NoDuplicateKeys.hpp new file mode 100644 index 000000000..0663ee0d4 --- /dev/null +++ b/include/rfl/NoDuplicateKeys.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_NODUPLICATEKEYS_HPP_ +#define RFL_NODUPLICATEKEYS_HPP_ + +#include + +namespace rfl { + +/// Reject duplicate keys in input objects/mappings for readers that support +/// duplicate-key detection (JSON and YAML). +/// +/// By default, duplicate keys keep existing reader behavior for backwards +/// compatibility. Pass rfl::NoDuplicateKeys to report each repeated key as an +/// error: +/// rfl::json::read(json) +/// rfl::yaml::read(yaml) +struct NoDuplicateKeys { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Nullable.hpp b/include/rfl/Nullable.hpp new file mode 100644 index 000000000..4009feae4 --- /dev/null +++ b/include/rfl/Nullable.hpp @@ -0,0 +1,224 @@ +#ifndef RFL_NULLABLE_HPP_ +#define RFL_NULLABLE_HPP_ + +#include +#include +#include +#include + +namespace rfl { + +template +class Nullable; + +template +class TriState; + +namespace internal { + +template +struct is_nullable_wrapper : std::false_type {}; + +template +struct is_nullable_wrapper> : std::true_type {}; + +template +constexpr bool is_nullable_wrapper_v = + is_nullable_wrapper>::value; + +/// Trait identifying types that explicitly represent null values (`std::optional`, +/// `rfl::Nullable`, `rfl::TriState`). Downstream processors such as +/// `DefaultIfNull` can query this trait to preserve explicit `null` semantics. +template +struct is_nullable_type : std::false_type {}; + +template +struct is_nullable_type> : std::true_type {}; + +template +struct is_nullable_type> : std::true_type {}; + +template +struct is_nullable_type> : std::true_type {}; + +template +constexpr bool is_nullable_type_v = + is_nullable_type>::value; + +template +struct is_std_optional_type : std::false_type {}; + +template +struct is_std_optional_type> : std::true_type {}; + +template +struct is_tri_state_fwd : std::false_type {}; + +template +struct is_tri_state_fwd> : std::true_type {}; + +template +constexpr bool is_bool_optional_like_conversion_v = + std::is_same_v, bool> && + (is_std_optional_type>::value || + is_nullable_wrapper>::value || + is_tri_state_fwd>::value); + +} // namespace internal + +/// A nullable field wrapper that ALWAYS serializes explicitly (`"field": null` +/// when empty, `"field": ` when present), unlike `std::optional` +/// which omits empty keys by default. +/// +/// On `read`, `rfl::Nullable` accepts an omitted key (becoming null), an +/// explicit `null` (becoming null), or a value of type `T`; with +/// `rfl::NoOptionals`, an omitted key fails to parse. In JSON Schema +/// (Draft 2020-12), it emits a nullable schema (`anyOf: [, {"type": +/// "null"}]`) and is not placed in `required`. +/// +/// Note: Formats without a native null representation (TOML, XML) serialize +/// null via their writer's fallback; `rfl::Nullable` is intended for formats +/// with native null values (JSON, YAML, Generic, CBOR, MsgPack, etc.). +template +class Nullable { + public: + using value_type = T; + using Type = T; + static constexpr bool is_nullable = true; + + constexpr Nullable() noexcept = default; + constexpr Nullable(std::nullopt_t) noexcept : value_(std::nullopt) {} + + constexpr Nullable(const T& _val) + requires std::is_copy_constructible_v + : value_(_val) {} + + constexpr Nullable(T&& _val) noexcept(std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_val)) {} + + constexpr Nullable(const std::optional& _opt) + requires std::is_copy_constructible_v + : value_(_opt) {} + + constexpr Nullable(std::optional&& _opt) noexcept( + std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_opt)) {} + + template + requires(!std::is_same_v, Nullable> && + !std::is_same_v, std::optional> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v) + explicit(!std::is_convertible_v) constexpr Nullable(U&& _val) + : value_(std::in_place, std::forward(_val)) {} + + constexpr Nullable(const Nullable&) = default; + constexpr Nullable(Nullable&&) noexcept( + std::is_nothrow_move_constructible_v) = default; + constexpr Nullable& operator=(const Nullable&) = default; + constexpr Nullable& operator=(Nullable&&) noexcept( + std::is_nothrow_move_assignable_v && + std::is_nothrow_move_constructible_v) = default; + + constexpr Nullable& operator=(std::nullopt_t) noexcept { + value_.reset(); + return *this; + } + + template + requires(std::is_same_v, std::optional> && + ((std::is_lvalue_reference_v && + std::is_copy_constructible_v && std::is_copy_assignable_v) || + (!std::is_lvalue_reference_v && + std::is_move_constructible_v && std::is_move_assignable_v))) + constexpr Nullable& operator=(Opt&& _opt) { + value_ = std::forward(_opt); + return *this; + } + + template + requires(!std::is_same_v, Nullable> && + !std::is_same_v, std::optional> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v && std::is_assignable_v) + constexpr Nullable& operator=(U&& _val) { + value_ = std::forward(_val); + return *this; + } + + constexpr bool has_value() const noexcept { return value_.has_value(); } + constexpr bool is_null() const noexcept { return !value_.has_value(); } + constexpr explicit operator bool() const noexcept { + return value_.has_value(); + } + + constexpr T& value() & { return value_.value(); } + constexpr const T& value() const& { return value_.value(); } + constexpr T&& value() && { return std::move(value_).value(); } + constexpr const T&& value() const&& { return std::move(value_).value(); } + + template + constexpr T value_or(U&& _default) const& { + return value_.value_or(std::forward(_default)); + } + + template + constexpr T value_or(U&& _default) && { + return std::move(value_).value_or(std::forward(_default)); + } + + constexpr T& operator*() & noexcept { return *value_; } + constexpr const T& operator*() const& noexcept { return *value_; } + constexpr T&& operator*() && noexcept { return std::move(*value_); } + constexpr const T&& operator*() const&& noexcept { return std::move(*value_); } + + constexpr T* operator->() noexcept { return value_.operator->(); } + constexpr const T* operator->() const noexcept { return value_.operator->(); } + + constexpr std::optional& optional() & noexcept { return value_; } + constexpr const std::optional& optional() const& noexcept { + return value_; + } + constexpr std::optional&& optional() && noexcept { + return std::move(value_); + } + + constexpr void reset() noexcept { value_.reset(); } + + template + constexpr T& emplace(Args&&... _args) { + return value_.emplace(std::forward(_args)...); + } + + constexpr bool operator==(const Nullable& _other) const = default; + + constexpr bool operator==(std::nullopt_t) const noexcept { + return !value_.has_value(); + } + + constexpr bool operator==(const std::optional& _other) const { + return value_ == _other; + } + + template + requires(!internal::is_nullable_wrapper_v && + !internal::is_std_optional_type>::value && + !std::is_same_v, std::nullopt_t> && + requires(const T& _a, const U& _b) { + { _a == _b } -> std::convertible_to; + }) + constexpr bool operator==(const U& _other) const { + return value_.has_value() && (*value_ == _other); + } + + private: + std::optional value_{}; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Object.hpp b/include/rfl/Object.hpp index 7c36cb5b0..87e2cb2a1 100644 --- a/include/rfl/Object.hpp +++ b/include/rfl/Object.hpp @@ -2,6 +2,7 @@ #define RFL_OBJECT_HPP_ #include +#include #include #include #include @@ -128,6 +129,10 @@ class Object { /// @return The maximum number of elements that can be stored auto max_size() const { return data_.max_size(); } + /// Reserves storage for at least the specified number of elements. + /// @param _n The minimum number of elements to allocate storage for + void reserve(const std::size_t _n) { data_.reserve(_n); } + /// Inserts new elements at the end (variadic copy version). /// @tparam Args Types of the values to insert /// @param _values The key-value pairs to insert @@ -285,7 +290,8 @@ class Object { Result get(const std::string& _key) const noexcept { const auto i = find(_key); if (i == size()) { - return error("Key named '" + _key + "' not found."); + return error("Key named '" + _key + "' not found.", + ErrorKind::missing_field); } return data_[i].second; } diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 5ef86d7b4..9db76ad86 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -61,7 +61,9 @@ struct OneOf { if (_errors.size() == sizeof...(Cs)) { return _value; } - return error(make_error_message(_errors)); + return error(Error(make_error_message(_errors), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::one_of)); } else { return validate_impl(_value, std::move(_errors)); } diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index a22e569a7..ebbc01bb9 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -34,8 +34,10 @@ struct PatternValidator { ctll::construct_from_pointer, _regex.arr_.data()}>(_str)) { return std::move(_str); } else { - return error("String '" + _str + "' did not match format '" + - _name.str() + "': '" + _regex.str() + "'."); + return error(Error("String '" + _str + "' did not match format '" + + _name.str() + "': '" + _regex.str() + "'.", + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::pattern)); } } diff --git a/include/rfl/Rename.hpp b/include/rfl/Rename.hpp index c92ecf5fb..a7cfd3b33 100644 --- a/include/rfl/Rename.hpp +++ b/include/rfl/Rename.hpp @@ -29,6 +29,8 @@ struct Rename { using Name = rfl::Literal<_name>; /// Default constructor - creates a Rename with a default-constructed value. + template + requires std::is_default_constructible_v Rename() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 08d01fc1f..22e171cd8 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -7,12 +7,18 @@ #include "internal/cpp20/Result.hpp" #endif +#include +#include +#include +#include + #include "internal/Error.hpp" namespace rfl { using Error = rfl::internal::Error; using ErrorDetail = rfl::internal::ErrorDetail; +using ErrorKind = rfl::internal::ErrorKind; /// To be returned when there is nothing to return, but there might be an error. struct Nothing {}; @@ -56,6 +62,78 @@ inline Unexpected error(Error&& _err) { return Unexpected(std::move(_err)); } +/// Shorthand for a classified unexpected error (leaf error, no detail +/// allocation). +inline Unexpected error(const std::string& _what, + const ErrorKind _kind) { + return Unexpected(Error(_what, _kind)); +} + +inline Unexpected error(std::string&& _what, const ErrorKind _kind) { + return Unexpected(Error(std::move(_what), _kind)); +} + +/// Shorthand for a classified unexpected error at a nested path. Allocates +/// explicit details only when _path is non-empty. +inline Unexpected error(std::string _what, const ErrorKind _kind, + std::vector _path) { + if (_path.empty()) { + return Unexpected(Error(std::move(_what), _kind)); + } + std::vector details; + details.push_back(ErrorDetail{ + .path = std::move(_path), + .message = _what, + .kind = _kind, + }); + return Unexpected(Error(std::move(_what), std::move(details))); +} + +/// Shorthand for a classified unexpected error with a machine-readable code. +/// Constrained template so braced-init path calls such as +/// `rfl::error("msg", kind, {"field"})` and `rfl::error("msg", kind, {})` +/// remain unambiguously resolved to the path overload above. +template + requires(std::convertible_to && + !std::is_null_pointer_v>) +inline Unexpected error(std::string _what, const ErrorKind _kind, + Code&& _code) { + std::string_view code_view; + if constexpr (std::is_pointer_v>) { + code_view = _code ? std::string_view(_code) : std::string_view{}; + } else { + code_view = std::string_view(std::forward(_code)); + } + return Unexpected(Error(std::move(_what), _kind, code_view)); +} + +/// Shorthand for a classified unexpected error at a nested path with a +/// machine-readable code. +template + requires(std::convertible_to && + !std::is_null_pointer_v>) +inline Unexpected error(std::string _what, const ErrorKind _kind, + std::vector _path, + Code&& _code) { + std::string_view code_view; + if constexpr (std::is_pointer_v>) { + code_view = _code ? std::string_view(_code) : std::string_view{}; + } else { + code_view = std::string_view(std::forward(_code)); + } + if (_path.empty()) { + return Unexpected(Error(std::move(_what), _kind, code_view)); + } + std::vector details; + details.push_back(ErrorDetail{ + .path = std::move(_path), + .message = _what, + .kind = _kind, + .code = std::string(code_view), + }); + return Unexpected(Error(std::move(_what), std::move(details))); +} + } // namespace rfl #ifdef REFLECTCPP_USE_STD_EXPECTED diff --git a/include/rfl/SchemaExtension.hpp b/include/rfl/SchemaExtension.hpp new file mode 100644 index 000000000..eead22329 --- /dev/null +++ b/include/rfl/SchemaExtension.hpp @@ -0,0 +1,102 @@ +#ifndef RFL_SCHEMAEXTENSION_HPP_ +#define RFL_SCHEMAEXTENSION_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "Generic.hpp" +#include "Object.hpp" + +namespace rfl { + +/// Optional Draft 2020-12 JSON Schema annotations (`title`, `examples`, and +/// arbitrary `x-*` extension properties) attachable via `rfl::SchemaExtension`. +struct SchemaAnnotations { + std::optional title = std::nullopt; + std::optional> examples = std::nullopt; + Object extensions = {}; + + bool empty() const noexcept { + return (!title.has_value() || title->empty()) && + (!examples.has_value() || examples->empty()) && + extensions.empty(); + } +}; + +/// Specialize `rfl::SchemaExtension` on a custom wrapper type (such as +/// `ConfigOption`) or struct to attach `title`, `examples`, and arbitrary +/// `x-*` extension keywords to its generated JSON Schema node. +/// +/// Supported members: +/// - `static rfl::SchemaAnnotations annotations();` AND/OR +/// - `static rfl::Object extensions();` +/// - `static constexpr bool inline_schema = true;` (optional, for reflection +/// wrappers that should emit their schema inline rather than via `$defs`). +template +struct SchemaExtension {}; + +namespace internal { + +template +concept HasSchemaExtensionAnnotationsFn = requires { + { SchemaExtension::annotations() } -> std::convertible_to; +}; + +template +concept HasSchemaExtensionExtensionsFn = requires { + { SchemaExtension::extensions() } -> std::convertible_to>; +}; + +template +concept HasSchemaExtensionInlineFlag = requires { + { SchemaExtension::inline_schema } -> std::convertible_to; +}; + +template +consteval bool schema_extension_inline() { + using U = std::remove_cvref_t; + if constexpr (HasSchemaExtensionInlineFlag) { + return static_cast(SchemaExtension::inline_schema); + } else { + return false; + } +} + +template +inline constexpr bool schema_extension_inline_v = schema_extension_inline(); + +template +inline constexpr bool has_schema_annotations_v = + HasSchemaExtensionAnnotationsFn> || + HasSchemaExtensionExtensionsFn>; + +template +inline SchemaAnnotations get_schema_annotations() { + using U = std::remove_cvref_t; + SchemaAnnotations out; + if constexpr (HasSchemaExtensionAnnotationsFn) { + auto ext = SchemaExtension::annotations(); + if (ext.title && !ext.title->empty()) out.title = std::move(ext.title); + if (ext.examples && !ext.examples->empty()) { + out.examples = std::move(ext.examples); + } + for (const auto& [k, v] : ext.extensions) { + out.extensions[k] = v; + } + } + if constexpr (HasSchemaExtensionExtensionsFn) { + for (const auto& [k, v] : SchemaExtension::extensions()) { + out.extensions[k] = v; + } + } + return out; +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_SCHEMAEXTENSION_HPP_ diff --git a/include/rfl/SchemaName.hpp b/include/rfl/SchemaName.hpp new file mode 100644 index 000000000..69089a4fb --- /dev/null +++ b/include/rfl/SchemaName.hpp @@ -0,0 +1,58 @@ +#ifndef RFL_SCHEMANAME_HPP_ +#define RFL_SCHEMANAME_HPP_ + +#include +#include +#include +#include + +namespace rfl { + +/// Specialize `rfl::SchemaName` to override the `$defs` identifier emitted +/// for type `T` (instead of the default mangled C++ type name). +/// +/// Supported members: +/// - `static constexpr std::string_view value = "ExportConfig";` OR +/// - `static std::string_view value();` (or returning `std::string`). +template +struct SchemaName {}; + +namespace internal { + +template +concept HasSchemaNameTraitVar = requires { + { SchemaName::value } -> std::convertible_to; +}; + +template +concept HasSchemaNameTraitFn = requires { + { SchemaName::value() } -> std::convertible_to; +}; + +template +inline constexpr bool has_schema_name_v = + HasSchemaNameTraitVar> || + HasSchemaNameTraitFn>; + +template +inline std::string get_schema_name() { + using U = std::remove_cvref_t; + if constexpr (HasSchemaNameTraitFn) { + if constexpr (std::is_same_v< + std::remove_cvref_t::value())>, + std::string>) { + return SchemaName::value(); + } else { + return std::string(std::string_view(SchemaName::value())); + } + } else if constexpr (HasSchemaNameTraitVar) { + return std::string(std::string_view(SchemaName::value)); + } else { + return {}; + } +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_SCHEMANAME_HPP_ diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index d3c0e0ec7..1360a654d 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -6,6 +6,7 @@ #include "Ref.hpp" #include "Result.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -22,7 +23,9 @@ struct Size { static rfl::Result validate(T _t) { auto res = V::validate(_t.size()); if (!res) { - return error("Size validation failed: " + res.error().what()); + return error(internal::compose_prefixed_validator_error( + std::move(res).error(), "Size validation failed: ", "size.", + internal::BuiltinErrorCode::size, internal::compose_size_code)); } return std::move(_t); } diff --git a/include/rfl/SnakeCaseToCamelCase.hpp b/include/rfl/SnakeCaseToCamelCase.hpp index d073b0b4a..ecf8c96b1 100644 --- a/include/rfl/SnakeCaseToCamelCase.hpp +++ b/include/rfl/SnakeCaseToCamelCase.hpp @@ -1,8 +1,8 @@ #ifndef RFL_SNAKECASETOCAMELCASE_HPP_ #define RFL_SNAKECASETOCAMELCASE_HPP_ -#include "Field.hpp" -#include "internal/is_rename.hpp" +#include + #include "internal/transform_case.hpp" namespace rfl { @@ -15,29 +15,10 @@ struct SnakeCaseToCamelCase { /// @param _named_tuple The named tuple containing the struct's fields /// @return A new named tuple with field names converted to camelCase template - static auto process(const auto& _named_tuple) { - return _named_tuple.transform([](const FieldType& _f) { - if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { - return handle_one_field(_f); - } else { - return _f; - } - }); - } - - private: - /// Applies the snake_case to camelCase transformation to a single field. - /// @tparam FieldType The type of the field being transformed - /// @param _f The field to transform - /// @return A new field with the transformed name and the same value - template - static auto handle_one_field(const FieldType& _f) { - using NewFieldType = - Field(), - typename FieldType::Type>; - return NewFieldType(_f.value()); + static auto process(auto&& _named_tuple) { + return internal::transform_named_tuple_case< + internal::SnakeCaseToCamelCaseTransform>( + std::forward(_named_tuple)); } }; diff --git a/include/rfl/SnakeCaseToKebabCase.hpp b/include/rfl/SnakeCaseToKebabCase.hpp index 4b9d09a6f..48554aa1d 100644 --- a/include/rfl/SnakeCaseToKebabCase.hpp +++ b/include/rfl/SnakeCaseToKebabCase.hpp @@ -1,8 +1,8 @@ #ifndef RFL_SNAKECASETOKEBABCASE_HPP_ #define RFL_SNAKECASETOKEBABCASE_HPP_ -#include "Field.hpp" -#include "internal/is_rename.hpp" +#include + #include "internal/transform_case.hpp" namespace rfl { @@ -15,30 +15,13 @@ struct SnakeCaseToKebabCase { /// @param _named_tuple The named tuple containing the struct's fields /// @return A new named tuple with field names converted to kebab-case template - static auto process(const auto& _named_tuple) { - return _named_tuple.transform([](const FieldType& _f) { - // "xml_content" is a reserved name used by the XML Reader/Writer; - // all case-transform processors must leave it unchanged. - if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { - return handle_one_field(_f); - } else { - return _f; - } - }); - } - - private: - /// Applies the snake_case to kebab-case transformation to a single field. - /// @tparam FieldType The type of the field being transformed - /// @param _f The field to transform - /// @return A new field with the transformed name and the same value - template - static auto handle_one_field(const FieldType& _f) { - using NewFieldType = - Field(), - typename FieldType::Type>; - return NewFieldType(_f.value()); + static auto process(auto&& _named_tuple) { + // "xml_content" is a reserved name used by the XML Reader/Writer; + // all case-transform processors leave it unchanged via + // transform_case_field. + return internal::transform_named_tuple_case< + internal::SnakeCaseToKebabCaseTransform>( + std::forward(_named_tuple)); } }; diff --git a/include/rfl/SnakeCaseToPascalCase.hpp b/include/rfl/SnakeCaseToPascalCase.hpp index f10361da0..101673937 100644 --- a/include/rfl/SnakeCaseToPascalCase.hpp +++ b/include/rfl/SnakeCaseToPascalCase.hpp @@ -1,8 +1,8 @@ #ifndef RFL_SNAKECASETOPASCALCASE_HPP_ #define RFL_SNAKECASETOPASCALCASE_HPP_ -#include "Field.hpp" -#include "internal/is_rename.hpp" +#include + #include "internal/transform_case.hpp" namespace rfl { @@ -15,30 +15,10 @@ struct SnakeCaseToPascalCase { /// @param _named_tuple The named tuple containing the struct's fields /// @return A new named tuple with field names converted to PascalCase template - static auto process(const auto& _named_tuple) { - const auto handle_one = [](const FieldType& _f) { - if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { - return handle_one_field(_f); - } else { - return _f; - } - }; - return _named_tuple.transform(handle_one); - } - - private: - /// Applies the snake_case to PascalCase transformation to a single field. - /// @tparam FieldType The type of the field being transformed - /// @param _f The field to transform - /// @return A new field with the transformed name and the same value - template - static auto handle_one_field(const FieldType& _f) { - using NewFieldType = - Field(), - typename FieldType::Type>; - return NewFieldType(_f.value()); + static auto process(auto&& _named_tuple) { + return internal::transform_named_tuple_case< + internal::SnakeCaseToPascalCaseTransform>( + std::forward(_named_tuple)); } }; 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/TaggedUnion.hpp b/include/rfl/TaggedUnion.hpp index 52b08914a..afa048f50 100644 --- a/include/rfl/TaggedUnion.hpp +++ b/include/rfl/TaggedUnion.hpp @@ -107,7 +107,7 @@ struct TaggedUnion { /// @return The result of applying _f to the active alternative template auto visit(F&& _f) - -> decltype(std::declval().visit(std::declval())) { + -> decltype(std::declval().visit(std::declval())) { return variant_.visit(std::forward(_f)); } @@ -117,8 +117,10 @@ struct TaggedUnion { /// @param _f The function to apply to the active alternative /// @return The result of applying _f to the active alternative template - auto visit(F&& _f) const - -> decltype(std::declval().visit(std::declval())) { + requires requires(VariantType& _v, F&& _f) { + _v.visit(std::forward(_f)); + } + decltype(auto) visit(F&& _f) const { return variant_.visit(std::forward(_f)); } @@ -160,16 +162,7 @@ using possible_tags_t = typename PossibleTags::Type; template bool operator==(const TaggedUnion<_discriminator, Ts...>& lhs, const TaggedUnion<_discriminator, Ts...>& rhs) { - return (lhs.variant().index() == rhs.variant().index()) && - lhs.variant().visit([&rhs](const auto& l) { - return rhs.variant().visit([&l](const auto& r) -> bool { - if constexpr (std::is_same_v, - std::decay_t>) - return l == r; - else - return false; - }); - }); + return internal::variant::Access::equals(lhs.variant(), rhs.variant()); } } // namespace rfl diff --git a/include/rfl/Timestamp.hpp b/include/rfl/Timestamp.hpp index 8129848ae..34c520818 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -74,9 +74,10 @@ class Timestamp { try { return Timestamp(_str); } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::invalid_value); } catch (...) { - return error("Unknown exception while parsing timestamp."); + return error("Unknown exception while parsing timestamp.", + ErrorKind::invalid_value); } } @@ -88,6 +89,11 @@ class Timestamp { return from_string(_str.c_str()); } + /// Exception-free reflection hook for parsers. + static Result from_reflection(const std::string& _str) noexcept { + return from_string(_str); + } + /// Generic factory method for creating a Timestamp from a string. /// Returns a result containing the timestamp when successful or an Error otherwise. /// @param _str The string to parse (can be const char* or std::string) diff --git a/include/rfl/ToAllCaps.hpp b/include/rfl/ToAllCaps.hpp index c86bad16b..b858998fd 100644 --- a/include/rfl/ToAllCaps.hpp +++ b/include/rfl/ToAllCaps.hpp @@ -1,8 +1,8 @@ #ifndef RFL_TOALLCAPS_HPP_ #define RFL_TOALLCAPS_HPP_ -#include "Field.hpp" -#include "internal/is_rename.hpp" +#include + #include "internal/transform_case.hpp" namespace rfl { @@ -15,27 +15,9 @@ struct ToAllCaps { /// @param _named_tuple The named tuple containing the struct's fields /// @return A new named tuple with field names converted to all uppercase template - static auto process(const auto& _named_tuple) { - return _named_tuple.transform([](const FieldType& _f) { - if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { - return handle_one_field(_f); - } else { - return _f; - } - }); - } - - private: - /// Applies the all-uppercase transformation to a single field. - /// @tparam FieldType The type of the field being transformed - /// @param _f The field to transform - /// @return A new field with the transformed name and the same value - template - static auto handle_one_field(const FieldType& _f) { - using NewFieldType = Field(), - typename FieldType::Type>; - return NewFieldType(_f.value()); + static auto process(auto&& _named_tuple) { + return internal::transform_named_tuple_case( + std::forward(_named_tuple)); } }; 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/TriState.hpp b/include/rfl/TriState.hpp new file mode 100644 index 000000000..7204f8f01 --- /dev/null +++ b/include/rfl/TriState.hpp @@ -0,0 +1,211 @@ +#ifndef RFL_TRISTATE_HPP_ +#define RFL_TRISTATE_HPP_ + +#include +#include +#include +#include + +#include "Nullable.hpp" + +namespace rfl { + +/// Tag value representing an omitted (absent) field in `rfl::TriState`. +struct OmittedTag { + struct Tag {}; + explicit constexpr OmittedTag(Tag) noexcept {} +}; + +inline constexpr OmittedTag omitted{OmittedTag::Tag{}}; + +namespace internal { + +template +struct is_tri_state : std::false_type {}; + +template +struct is_tri_state> : std::true_type {}; + +template +constexpr bool is_tri_state_v = is_tri_state>::value; + +} // namespace internal + +/// Tri-state field presence wrapper distinguishing: +/// 1. `State::omitted` — key was absent from input (default-constructed; +/// omitted on serialization unless `rfl::NoOptionals` is used). +/// 2. `State::null` — key was explicitly present as `null` (serializes as +/// `"field": null`). +/// 3. `State::value` — key was explicitly present with a value of type `T` +/// (serializes as `"field": `). +/// +/// Works across `read`, `write`, and Draft 2020-12 JSON Schema generation. +/// +/// Note: `rfl::TriState` is intended for formats with native null values +/// (JSON, YAML, Generic, CBOR, MsgPack, etc.). +template +class TriState { + public: + using value_type = T; + using Type = T; + static constexpr bool is_nullable = true; + + enum class State : uint8_t { + omitted = 0, + null = 1, + value = 2, + }; + + constexpr TriState() noexcept = default; + constexpr TriState(OmittedTag) noexcept + : value_(std::nullopt), state_(State::omitted) {} + constexpr TriState(std::nullopt_t) noexcept + : value_(std::nullopt), state_(State::null) {} + + constexpr TriState(const T& _val) + requires std::is_copy_constructible_v + : value_(_val), state_(State::value) {} + + constexpr TriState(T&& _val) noexcept(std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_val)), state_(State::value) {} + + template + requires(!std::is_same_v, TriState> && + !std::is_same_v, OmittedTag> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v) + explicit(!std::is_convertible_v) constexpr TriState(U&& _val) + : value_(std::in_place, std::forward(_val)), state_(State::value) {} + + constexpr TriState(const TriState&) = default; + constexpr TriState(TriState&&) noexcept( + std::is_nothrow_move_constructible_v) = default; + constexpr TriState& operator=(const TriState&) = default; + constexpr TriState& operator=(TriState&&) noexcept( + std::is_nothrow_move_assignable_v && + std::is_nothrow_move_constructible_v) = default; + + constexpr TriState& operator=(OmittedTag) noexcept { + value_.reset(); + state_ = State::omitted; + return *this; + } + + constexpr TriState& operator=(std::nullopt_t) noexcept { + value_.reset(); + state_ = State::null; + return *this; + } + + template + requires(!std::is_same_v, TriState> && + !std::is_same_v, OmittedTag> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v && std::is_assignable_v) + constexpr TriState& operator=(U&& _val) { + value_ = std::forward(_val); + state_ = State::value; + return *this; + } + + static constexpr TriState omitted() noexcept { return TriState(rfl::omitted); } + static constexpr TriState null() noexcept { return TriState(std::nullopt); } + + template + static constexpr TriState of(Args&&... _args) { + TriState ts; + ts.emplace(std::forward(_args)...); + return ts; + } + + constexpr State state() const noexcept { return state_; } + constexpr bool is_omitted() const noexcept { + return state_ == State::omitted; + } + constexpr bool is_present() const noexcept { + return state_ != State::omitted; + } + constexpr bool is_null() const noexcept { return state_ == State::null; } + constexpr bool has_value() const noexcept { return state_ == State::value; } + constexpr explicit operator bool() const noexcept { return has_value(); } + + constexpr T& value() & { return value_.value(); } + constexpr const T& value() const& { return value_.value(); } + constexpr T&& value() && { return std::move(value_).value(); } + constexpr const T&& value() const&& { return std::move(value_).value(); } + + template + constexpr T value_or(U&& _default) const& { + return has_value() ? *value_ : static_cast(std::forward(_default)); + } + + template + constexpr T value_or(U&& _default) && { + return has_value() ? std::move(*value_) + : static_cast(std::forward(_default)); + } + + constexpr T& operator*() & noexcept { return *value_; } + constexpr const T& operator*() const& noexcept { return *value_; } + constexpr T&& operator*() && noexcept { return std::move(*value_); } + constexpr const T&& operator*() const&& noexcept { return std::move(*value_); } + + constexpr T* operator->() noexcept { return value_.operator->(); } + constexpr const T* operator->() const noexcept { return value_.operator->(); } + + constexpr std::optional to_optional() const& + requires std::is_copy_constructible_v + { + return value_; + } + constexpr std::optional to_optional() && noexcept( + std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + { + return std::move(value_); + } + + constexpr void reset() noexcept { + value_.reset(); + state_ = State::omitted; + } + + constexpr void set_omitted() noexcept { reset(); } + + constexpr void set_null() noexcept { + value_.reset(); + state_ = State::null; + } + + template + constexpr T& emplace(Args&&... _args) { + // Preserve invariant (state_ == State::value) == value_.has_value() if + // T's constructor throws after std::optional::emplace destroys the old T. + state_ = State::omitted; + T& ref = value_.emplace(std::forward(_args)...); + state_ = State::value; + return ref; + } + + constexpr bool operator==(const TriState& _other) const + requires requires(const T& _a, const T& _b) { + { _a == _b } -> std::convertible_to; + } + { + if (state_ != _other.state_) { + return false; + } + return state_ != State::value || *value_ == *_other.value_; + } + + private: + std::optional value_{}; + State state_ = State::omitted; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Tuple.hpp b/include/rfl/Tuple.hpp index ee12e54c2..846c1665d 100644 --- a/include/rfl/Tuple.hpp +++ b/include/rfl/Tuple.hpp @@ -2,7 +2,9 @@ #define RFL_TUPLE_HPP_ #include +#include #include +#include #include #include #include @@ -13,6 +15,23 @@ namespace rfl { +namespace internal::tuple { + +template + requires(std::is_trivially_destructible_v> || + !std::is_destructible_v>) +inline void destroy_element(unsigned char*) noexcept {} + +template + requires(std::is_destructible_v> && + !std::is_trivially_destructible_v>) +inline void destroy_element(unsigned char* _ptr) noexcept { + using RawT = std::remove_cv_t; + internal::ptr_cast(_ptr)->~RawT(); +} + +} // namespace internal::tuple + template class Tuple; @@ -27,14 +46,17 @@ class Tuple<> { /// Tuple class template for arbitrary types. template class Tuple { + template + friend class Tuple; + static constexpr size_t size_ = sizeof...(Types); static constexpr auto positions_ = internal::tuple::calculate_positions(); - static constexpr auto seq_ = std::make_integer_sequence{}; + static constexpr auto seq_ = std::make_index_sequence{}; - static constexpr unsigned int num_bytes_ = std::get(positions_); + static constexpr size_t num_bytes_ = positions_[size_]; using DataType = unsigned char[num_bytes_]; @@ -49,6 +71,10 @@ class Tuple { /// Default constructor. Initializes each element with its default /// constructor. + template + requires(std::is_default_constructible_v< + std::conditional_t, Types, void>> && + ...) Tuple() : Tuple(Types()...) {} /// Copy constructor. Copies all elements from another Tuple. @@ -59,16 +85,28 @@ class Tuple { /// @param _other The Tuple to move from. Tuple(Tuple&& _other) noexcept { move_from_other(std::move(_other), seq_); } + /// Destructor. Trivial when all elements are trivially destructible. + ~Tuple() + requires(std::is_trivially_destructible_v && ...) + = default; + /// Destructor. Destroys all elements if necessary. - ~Tuple() { destroy_if_necessary(seq_); } + ~Tuple() + requires(!(std::is_trivially_destructible_v && ...)) + { + destroy_if_necessary(seq_); + } /// Gets an element by index (mutable). /// @tparam _index The index of the element to access. /// @return Reference to the element at the specified index. template constexpr auto& get() { + static_assert(_index >= 0 && static_cast(_index) < size_, + "Tuple index out of bounds."); using Type = internal::nth_element_t<_index, Types...>; - return *internal::ptr_cast(data_ + pos<_index>()); + return *internal::ptr_cast(data_ + + positions_[static_cast(_index)]); } /// Gets an element by index (const). @@ -76,8 +114,11 @@ class Tuple { /// @return Const reference to the element at the specified index. template constexpr const auto& get() const { + static_assert(_index >= 0 && static_cast(_index) < size_, + "Tuple index out of bounds."); using Type = internal::nth_element_t<_index, Types...>; - return *internal::ptr_cast(data_ + pos<_index>()); + return *internal::ptr_cast( + data_ + positions_[static_cast(_index)]); } /// Copy assignment operator. Assigns from another Tuple by copy. @@ -113,12 +154,11 @@ class Tuple { bool operator==(const Tuple& _other) const noexcept { static_assert(sizeof...(Types) == sizeof...(OtherTypes), "The size of the two tuples must be the same."); - const auto is_same = [&](std::integral_constant) -> bool { - return this->get<_i>() == _other.template get<_i>(); - }; - return [&](std::integer_sequence) { - return (true && ... && is_same(std::integral_constant{})); - }(std::make_integer_sequence()); + if constexpr (sizeof...(Types) == sizeof...(OtherTypes)) { + return is_equal(_other, seq_); + } else { + return false; + } } /// Three-way comparison operator. Compares two Tuples lexicographically. @@ -129,100 +169,126 @@ class Tuple { auto operator<=>(const Tuple& _other) const noexcept { static_assert(sizeof...(Types) == sizeof...(OtherTypes), "The size of the two tuples must be the same."); + if constexpr (sizeof...(Types) == sizeof...(OtherTypes)) { + return compare_three_way(_other, seq_); + } + } + + private: + /// Compares all elements for equality with another Tuple. + template + bool is_equal(const Tuple& _other, + std::index_sequence<_is...>) const noexcept { + return (static_cast( + *internal::ptr_cast(data_ + positions_[_is]) == + *internal::ptr_cast( + _other.data_ + Tuple::positions_[_is])) && + ...); + } + /// Compares all elements three-way with another Tuple. + template + auto compare_three_way(const Tuple& _other, + std::index_sequence<_is...>) const noexcept { using OrderingType = std::common_comparison_category_t< - decltype(std::declval() <=> std::declval())...>; + decltype(std::declval() <=> + std::declval())...>; auto ordering = OrderingType::equivalent; - - const auto compare = [&](std::integral_constant) { - ordering = static_cast(this->get<_i>() <=> - _other.template get<_i>()); - return ordering != 0; - }; - - return [&](std::integer_sequence) { - (compare(std::integral_constant{}) || ...); - return ordering; - }(std::make_integer_sequence()); + static_cast( + (((ordering = static_cast( + *internal::ptr_cast(data_ + positions_[_is]) <=> + *internal::ptr_cast( + _other.data_ + Tuple::positions_[_is]))) != + 0) || + ...)); + return ordering; } - private: /// Copies all elements from another Tuple. - /// @param _other The Tuple to copy from. - /// @param seq_ Integer sequence for element indices. - template - void copy_from_other(const Tuple& _other, - std::integer_sequence) { - const auto copy_one = [this](const auto& _other, - std::integral_constant) { - using Type = internal::nth_element_t<_i, Types...>; - ::new (static_cast(data_ + pos<_i>())) - Type(_other.template get<_i>()); - }; - (copy_one(_other, std::integral_constant{}), ...); + template + void copy_from_other(const Tuple& _other, std::index_sequence<_is...>) { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + if constexpr (size_ > 1 && + !(std::is_nothrow_copy_constructible_v && ...) && + !(std::is_trivially_destructible_v && ...)) { + size_t constructed = 0; + try { + ((::new (static_cast(data_ + positions_[_is])) + Types(*internal::ptr_cast(_other.data_ + + positions_[_is])), + ++constructed), + ...); + } catch (...) { + destroy_prefix(constructed, seq_); + throw; + } + } else +#endif + { + (::new (static_cast(data_ + positions_[_is])) + Types(*internal::ptr_cast(_other.data_ + + positions_[_is])), + ...); + } } /// Copies all elements from provided arguments. - /// @param _types The values to copy. - /// @param seq_ Integer sequence for element indices. - template - void copy_from_types(const Types&... _types, - std::integer_sequence) { - const auto copy_one = [this](const auto& _t, - std::integral_constant) { - using Type = internal::nth_element_t<_i, Types...>; - ::new (static_cast(data_ + pos<_i>())) Type(_t); - }; - (copy_one(_types, std::integral_constant{}), ...); + template + void copy_from_types(const Types&... _types, std::index_sequence<_is...>) { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + if constexpr (size_ > 1 && + !(std::is_nothrow_copy_constructible_v && ...) && + !(std::is_trivially_destructible_v && ...)) { + size_t constructed = 0; + try { + ((::new (static_cast(data_ + positions_[_is])) Types(_types), + ++constructed), + ...); + } catch (...) { + destroy_prefix(constructed, seq_); + throw; + } + } else +#endif + { + (::new (static_cast(data_ + positions_[_is])) Types(_types), ...); + } } - /// Destroys all elements if they are destructible. - /// @param seq_ Integer sequence for element indices. - template - void destroy_if_necessary(std::integer_sequence) { - const auto destroy_one = [](auto& _t) { - using Type = std::remove_cvref_t; - if constexpr (std::is_destructible_v) { - _t.~Type(); - } - }; - (destroy_one(get<_is>()), ...); + /// Destroys all elements if they are non-trivially destructible. + template + void destroy_if_necessary(std::index_sequence<_is...>) noexcept { + if constexpr (!(std::is_trivially_destructible_v && ...)) { + (internal::tuple::destroy_element(data_ + positions_[_is]), ...); + } } - /// Moves all elements from another Tuple. - /// @param _other The Tuple to move from. - /// @param seq_ Integer sequence for element indices. - template - void move_from_other(Tuple&& _other, std::integer_sequence) { - const auto move_one = [this](auto&& _other, - std::integral_constant) { - using Type = internal::nth_element_t<_i, Types...>; - ::new (static_cast(data_ + pos<_i>())) - Type(std::move(_other.template get<_i>())); - }; - (move_one(_other, std::integral_constant{}), ...); + /// Destroys the first _count elements during exception rollback. + template + void destroy_prefix(size_t _count, std::index_sequence<_is...>) noexcept { + ((_is < _count + ? internal::tuple::destroy_element(data_ + positions_[_is]) + : void()), + ...); } - /// Moves all elements from provided arguments. - /// @param _types The values to move. - /// @param seq_ Integer sequence for element indices. - template - void move_from_types(Types&&... _types, std::integer_sequence) { - const auto move_one = [this](auto&& _t, - std::integral_constant) { - using Type = internal::nth_element_t<_i, Types...>; - ::new (static_cast(data_ + pos<_i>())) Type(std::move(_t)); - }; - (move_one(std::move(_types), std::integral_constant{}), ...); + /// Moves all elements from another Tuple. + template + void move_from_other(Tuple&& _other, std::index_sequence<_is...>) noexcept { + (::new (static_cast(data_ + positions_[_is])) + Types(std::move(*internal::ptr_cast(_other.data_ + + positions_[_is]))), + ...); } - /// Returns the byte offset of the element at index _i. - /// @tparam _i The index of the element. - /// @return The byte offset of the element. - template - static consteval unsigned int pos() { - return std::get<_i>(positions_); + /// Moves all elements from provided arguments. + template + void move_from_types(Types&&... _types, + std::index_sequence<_is...>) noexcept { + (::new (static_cast(data_ + positions_[_is])) + Types(std::move(_types)), + ...); } private: diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 4a0cd1243..776a6d327 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -10,6 +10,7 @@ #include "AllOf.hpp" #include "Result.hpp" #include "internal/HasValidation.hpp" +#include "internal/validator_code.hpp" namespace rfl { @@ -35,9 +36,12 @@ struct Validator { try { return wrap_validated(ValidationType::validate(_value)); } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::constraint_violation, + internal::validator_code()); } catch (...) { - return error("Unknown exception during validation."); + return error("Unknown exception during validation.", + ErrorKind::constraint_violation, + internal::validator_code()); } } @@ -49,14 +53,19 @@ struct Validator { try { return wrap_validated(ValidationType::validate(std::move(_value))); } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::constraint_violation, + internal::validator_code()); } catch (...) { - return error("Unknown exception during validation."); + return error("Unknown exception during validation.", + ErrorKind::constraint_violation, + internal::validator_code()); } } /// Default constructor - validates a default-constructed T. /// @throws std::exception if validation of the default value fails + template + requires std::is_default_constructible_v Validator() : value_(ValidationType::validate(T()).value()) {} /// Move constructor. @@ -203,8 +212,14 @@ struct Validator { /// Wraps the result of a validation without throwing if it failed. static Result wrap_validated(Result&& _res) { - return std::move(_res).transform( - [](T&& _v) { return Validator(AlreadyValidated{}, std::move(_v)); }); + if (!_res) { + Error err = std::move(_res).error(); + internal::set_error_kind_if_other(err, ErrorKind::constraint_violation); + internal::set_error_code_if_empty( + err, internal::validator_code()); + return error(std::move(err)); + } + return Validator(AlreadyValidated{}, std::move(*_res)); } private: diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index 046b5a030..244121cc1 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -2,9 +2,10 @@ #define RFL_VARIANT_HPP_ #include +#include #include #include -#include +#include #include #include #include @@ -12,6 +13,7 @@ #include "internal/element_index.hpp" #include "internal/nth_element_t.hpp" #include "internal/ptr_cast.hpp" +#include "internal/variant/dispatch.hpp" #include "internal/variant/find_max_size.hpp" #include "internal/variant/is_alternative_type.hpp" #include "internal/variant/result_t.hpp" @@ -19,10 +21,11 @@ namespace rfl { template class Variant { - static constexpr auto max_size_wrapper_ = - internal::variant::find_max_size(); + static_assert(sizeof...(AlternativeTypes) > 0, + "Variant must have at least one alternative type."); - static constexpr unsigned long num_bytes_ = max_size_wrapper_.size_; + static constexpr std::size_t num_bytes_ = + internal::variant::find_max_size(); using DataType = std::array; @@ -33,38 +36,32 @@ class Variant { static constexpr IndexType size_ = sizeof...(AlternativeTypes); - template - using result_t = internal::variant::result_t; + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; - template - using Index = std::integral_constant; - - template - struct TypeWrapper {}; + friend struct internal::variant::Access; public: /// @brief Default-constructs the Variant, initializing it with the first /// alternative type. /// @details The first alternative type is default-constructed and stored in /// the variant. - Variant() : index_(IndexType()), data_(DataType()) { - using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; - move_from_type(FirstAlternative()); + template + requires std::is_default_constructible_v + Variant() : index_(0) { + ::new (static_cast(data_.data())) FirstAlt(); } /// @brief Copy-constructs the Variant from another Variant. /// @param _other The Variant to copy from. /// @details The contained value is copied from the other Variant, preserving /// the alternative type. - Variant(const Variant& _other) : index_(IndexType()), data_(DataType()) { - copy_from_other(_other); - } + Variant(const Variant& _other) : index_(0) { copy_from_other(_other); } /// @brief Move-constructs the Variant from another Variant. /// @param _other The Variant to move from. /// @details The contained value is moved from the other Variant, preserving /// the alternative type. - Variant(Variant&& _other) noexcept : index_(IndexType()), data_(DataType()) { + Variant(Variant&& _other) noexcept : index_(0) { move_from_other(std::move(_other)); } @@ -74,7 +71,7 @@ class Variant { /// @details Only enabled if T is one of the alternative types. template requires internal::variant::is_alternative_type_v - Variant(const T& _t) : index_(IndexType()), data_(DataType()) { + Variant(const T& _t) : index_(0) { copy_from_type(_t); } @@ -83,8 +80,11 @@ class Variant { /// @param _t The value to move into the Variant. /// @details Only enabled if T is one of the alternative types. template - requires internal::variant::is_alternative_type_v - Variant(T&& _t) noexcept : index_(IndexType()), data_(DataType()) { + requires(!std::is_lvalue_reference_v && !std::is_const_v && + internal::variant::is_alternative_type_v) + Variant(T&& _t) noexcept( + std::is_nothrow_constructible_v, T&&>) + : index_(0) { move_from_type(std::forward(_t)); } @@ -114,8 +114,14 @@ class Variant { /// @return Reference to the newly emplaced value. template constexpr auto& emplace(Args&&... _args) { + static_assert(_i >= 0 && _i < static_cast(sizeof...(AlternativeTypes)), + "Index out of bounds."); using T = internal::nth_element_t<_i, AlternativeTypes...>; - return emplace(std::move(_args)...); + auto t = T{std::forward(_args)...}; + destroy_if_necessary(); + index_ = static_cast(_i); + ::new (static_cast(data_.data())) T(std::move(t)); + return *internal::ptr_cast(data_.data()); } /// @brief Returns the index of the currently held alternative. @@ -140,7 +146,8 @@ class Variant { /// @param _t The value to assign. /// @return Reference to this Variant. template - requires internal::variant::is_alternative_type_v + requires(!std::is_lvalue_reference_v && !std::is_const_v && + internal::variant::is_alternative_type_v) Variant& operator=(T&& _t) noexcept { destroy_if_necessary(); move_from_type(std::forward(_t)); @@ -181,7 +188,7 @@ class Variant { return; } auto temp = Variant(std::move(*this)); - move_from_other(std::move(_other)); + *this = std::move(_other); _other = std::move(temp); } @@ -190,23 +197,13 @@ class Variant { /// @param _f The visitor function or functor. /// @return The result of the visitor, or void. template - result_t visit(F&& _f) { - using ResultType = result_t; - if constexpr (std::is_same_v) { - bool visited = false; - do_visit_no_result(std::forward(_f), &visited, - std::make_integer_sequence()); - } else if constexpr (std::is_reference_v) { - std::remove_reference_t* res = nullptr; - do_visit_with_reference(std::forward(_f), &res, - std::make_integer_sequence()); - return *res; - } else { - auto res = std::optional(); - do_visit_with_result(std::forward(_f), &res, - std::make_integer_sequence()); - return std::move(*res); - } + requires internal::variant::visit_invocable + internal::variant::visit_result_t visit(F&& _f) { + using ResultType = internal::variant::visit_result_t; + return internal::variant::SwitchDispatch< + false, internal::variant::VisitAction, ResultType, 0, + AlternativeTypes...>::apply(static_cast(index_), + data_.data(), std::forward(_f)); } /// @brief Visits the contained value with a visitor function (const @@ -215,299 +212,56 @@ class Variant { /// @param _f The visitor function or functor. /// @return The result of the visitor, or void. template - result_t visit(F&& _f) const { - using ResultType = result_t; - if constexpr (std::is_same_v) { - bool visited = false; - do_visit_no_result(std::forward(_f), &visited, - std::make_integer_sequence()); - } else if constexpr (std::is_reference_v) { - std::remove_reference_t* res = nullptr; - do_visit_with_reference(std::forward(_f), &res, - std::make_integer_sequence()); - return *res; - } else { - auto res = std::optional(); - do_visit_with_result(std::forward(_f), &res, - std::make_integer_sequence()); - return std::move(*res); - } + requires internal::variant::visit_const_invocable + decltype(auto) visit(F&& _f) const { + using ResultType = + internal::variant::visit_result_t; + return internal::variant::SwitchDispatch< + false, internal::variant::VisitAction, ResultType, 0, + AlternativeTypes...>::apply(static_cast(index_), + data_.data(), std::forward(_f)); } private: /// @brief Copies the value from another Variant. /// @param _other The Variant to copy from. void copy_from_other(const Variant& _other) { - const auto copy_one = [this](const auto& _t) { this->copy_from_type(_t); }; - _other.visit(copy_one); - } - - /// @brief Copies a value of type T from another type. - /// @tparam T The type to copy from. - /// @param _t The value to copy. - /// @details Tries to copy the value from T to each alternative type, and if - /// successful, stores it in the Variant. Only the first successful copy is - /// performed. - template - void copy_from_other_type(const T& _t) { - bool set = false; - const auto copy_one = [&, this](const T& _t, - const TypeWrapper) { - if constexpr (std::is_convertible_v) { - if (!set) { - move_from_type(AltType(_t)); - set = true; - } - } - }; - (copy_one(_t, TypeWrapper{}), ...); + internal::variant::SwitchDispatch< + false, internal::variant::CopyAction, void, 0, + AlternativeTypes...>::apply(static_cast(_other.index_), + data_.data(), _other.data_.data()); + index_ = _other.index_; } /// @brief Copies a value of type T into the Variant. /// @tparam T The type to copy from. /// @param _t The value to copy. template - void copy_from_type(const T& _t) noexcept { + void copy_from_type(const T& _t) { using CurrentType = std::remove_cvref_t; - index_ = - internal::element_index...>(); - new (data_.data()) CurrentType(_t); + constexpr int ix = internal::element_index< + CurrentType, std::remove_cvref_t...>(); + static_assert(ix != -1, "Type not supported."); + ::new (static_cast(data_.data())) CurrentType(_t); + index_ = static_cast(ix); } /// @brief Destroys the contained value if it is destructible. - void destroy_if_necessary() { - const auto destroy_one = [](auto& _t) { - using T = std::remove_cvref_t; - if constexpr (std::is_destructible_v) { - _t.~T(); - } - }; - visit(destroy_one); - } - - /// @brief Helper for visiting without result (non-const). - /// @tparam F The visitor type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _visited Pointer to visitation flag. - template - void do_visit_no_result(F& _f, bool* _visited, - std::integer_sequence) { - auto visit_one = [this](F& _f, bool* _visited, Index<_i>) { - if (!*_visited && index_ == _i) { - _f(get_alternative<_i>()); - *_visited = true; - } - }; - (visit_one(_f, _visited, Index<_is>{}), ...); - } - - /// @brief Helper for visiting without result (const). - /// @tparam F The visitor type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _visited Pointer to visitation flag. - template - void do_visit_no_result(F& _f, bool* _visited, - std::integer_sequence) const { - auto visit_one = [this](F& _f, bool* _visited, Index<_i>) { - if (!*_visited && index_ == _i) { - _f(get_alternative<_i>()); - *_visited = true; - } - }; - (visit_one(_f, _visited, Index<_is>{}), ...); - } - - /// @brief Helper for visiting without result (non-const, const visitor). - /// @tparam F The visitor type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _visited Pointer to visitation flag. - template - void do_visit_no_result(const F& _f, bool* _visited, - std::integer_sequence) { - const auto visit_one = [this](const F& _f, bool* _visited, - Index<_i>) { - if (!*_visited && index_ == _i) { - _f(get_alternative<_i>()); - *_visited = true; - } - }; - (visit_one(_f, _visited, Index<_is>{}), ...); - } - - /// @brief Helper for visiting without result (const, const visitor). - /// @tparam F The visitor type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _visited Pointer to visitation flag. - template - void do_visit_no_result(const F& _f, bool* _visited, - std::integer_sequence) const { - const auto visit_one = [this](const F& _f, bool* _visited, - Index<_i>) { - if (!*_visited && index_ == _i) { - _f(get_alternative<_i>()); - *_visited = true; - } - }; - (visit_one(_f, _visited, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with result (non-const). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to optional result. - template - void do_visit_with_result(F& _f, std::optional* _result, - std::integer_sequence) { - auto visit_one = [this]( - F& _f, std::optional* _result, Index<_i>) { - if (!*_result && index_ == _i) { - _result->emplace(_f(get_alternative<_i>())); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with result (const). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to optional result. - template - void do_visit_with_result(F& _f, std::optional* _result, - std::integer_sequence) const { - auto visit_one = [this]( - F& _f, std::optional* _result, Index<_i>) { - if (!*_result && index_ == _i) { - _result->emplace(_f(get_alternative<_i>())); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with result (non-const, const visitor). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to optional result. - template - void do_visit_with_result(const F& _f, std::optional* _result, - std::integer_sequence) { - const auto visit_one = [this]( - const F& _f, std::optional* _result, - Index<_i>) { - if (!*_result && index_ == _i) { - _result->emplace(_f(get_alternative<_i>())); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with result (const, const visitor). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to optional result. - template - void do_visit_with_result(const F& _f, std::optional* _result, - std::integer_sequence) const { - const auto visit_one = [this]( - const F& _f, std::optional* _result, - Index<_i>) { - if (!*_result && index_ == _i) { - _result->emplace(_f(get_alternative<_i>())); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with reference result (non-const). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to result pointer. - template - void do_visit_with_reference(F& _f, ResultType** _result, - std::integer_sequence) { - const auto visit_one = [this](F& _f, ResultType** _result, - Index<_i>) { - if (!*_result && index_ == _i) { - *_result = &_f(get_alternative<_i>()); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with reference result (const). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to result pointer. - template - void do_visit_with_reference(F& _f, ResultType** _result, - std::integer_sequence) const { - const auto visit_one = [this](F& _f, ResultType** _result, - Index<_i>) { - if (!*_result && index_ == _i) { - *_result = &_f(get_alternative<_i>()); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with reference result (non-const, const - /// visitor). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to result pointer. - template - void do_visit_with_reference(const F& _f, ResultType** _result, - std::integer_sequence) { - const auto visit_one = [this]( - const F& _f, ResultType** _result, Index<_i>) { - if (!*_result && index_ == _i) { - *_result = &_f(get_alternative<_i>()); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); - } - - /// @brief Helper for visiting with reference result (const, const visitor). - /// @tparam F The visitor type. - /// @tparam ResultType The result type. - /// @tparam _is Index sequence. - /// @param _f The visitor. - /// @param _result Pointer to result pointer. - template - void do_visit_with_reference(const F& _f, ResultType** _result, - std::integer_sequence) const { - const auto visit_one = [this]( - const F& _f, ResultType** _result, Index<_i>) { - if (!*_result && index_ == _i) { - *_result = &_f(get_alternative<_i>()); - } - }; - (visit_one(_f, _result, Index<_is>{}), ...); + void destroy_if_necessary() noexcept { + if constexpr (!(std::is_trivially_destructible_v && + ...)) { + internal::variant::SwitchDispatch< + true, internal::variant::DestroyAction, void, 0, + AlternativeTypes...>::apply(static_cast(index_), + data_.data()); + } } /// @brief Returns a reference to the contained value of the _i-th alternative /// type. /// @tparam _i The index of the alternative type. /// @return Reference to the contained value. - template + template auto& get_alternative() noexcept { using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>; return *internal::ptr_cast(data_.data()); @@ -517,7 +271,7 @@ class Variant { /// alternative type. /// @tparam _i The index of the alternative type. /// @return Const reference to the contained value. - template + template const auto& get_alternative() const noexcept { using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>; return *internal::ptr_cast(data_.data()); @@ -526,22 +280,25 @@ class Variant { /// @brief Moves the value from another Variant into this Variant. /// @param _other The Variant to move from. void move_from_other(Variant&& _other) noexcept { - const auto move_one = [this](auto&& _t) { - this->move_from_type(std::forward>(_t)); - }; - std::move(_other).visit(move_one); + internal::variant::SwitchDispatch< + true, internal::variant::MoveAction, void, 0, + AlternativeTypes...>::apply(static_cast(_other.index_), + data_.data(), _other.data_.data()); + index_ = _other.index_; } /// @brief Moves a value of type T into the Variant. /// @tparam T The type to move from. /// @param _t The value to move. template - void move_from_type(T&& _t) noexcept { + void move_from_type(T&& _t) noexcept( + std::is_nothrow_constructible_v, T&&>) { using CurrentType = std::remove_cvref_t; - index_ = - internal::element_index...>(); - new (data_.data()) CurrentType(std::forward(_t)); + constexpr int ix = internal::element_index< + CurrentType, std::remove_cvref_t...>(); + static_assert(ix != -1, "Type not supported."); + ::new (static_cast(data_.data())) CurrentType(std::forward(_t)); + index_ = static_cast(ix); } private: @@ -553,6 +310,43 @@ class Variant { alignas(AlternativeTypes...) DataType data_; }; +namespace internal::variant { + +struct Access { + template + static auto& get_alternative(Variant& _v) noexcept { + return _v.template get_alternative<_i>(); + } + + template + static const auto& get_alternative(const Variant& _v) noexcept { + return _v.template get_alternative<_i>(); + } + + template + static T* ptr_as(Variant& _v) noexcept { + return internal::ptr_cast(_v.data_.data()); + } + + template + static const T* ptr_as(const Variant& _v) noexcept { + return internal::ptr_cast(_v.data_.data()); + } + + template + static bool equals(const Variant& _lhs, + const Variant& _rhs) { + if (_lhs.index_ != _rhs.index_) { + return false; + } + return SwitchDispatch::apply( + static_cast(_lhs.index_), _lhs.data_.data(), + _rhs.data_.data()); + } +}; + +} // namespace internal::variant + /// @brief Concept to check if a type is Variant-based. /// @tparam V The type to check. template @@ -568,15 +362,27 @@ concept VariantBased = requires(std::decay_t v) { /// @return Pointer to the contained value or nullptr. template constexpr T* get_if(Variant* _v) noexcept { - const auto get = [](auto& _v) -> T* { - using Type = std::remove_cvref_t; - if constexpr (std::is_same>()) { - return &_v; - } else { - return nullptr; + if (!_v) { + return nullptr; + } + constexpr auto matches = + internal::variant::get_if_matches(); + constexpr auto plan = internal::variant::analyze_get_if_matches(matches); + if constexpr (plan.count == 0) { + return nullptr; + } else if constexpr (plan.count == 1) { + return _v->index() == plan.first_index + ? &internal::variant::Access::template get_alternative< + plan.first_index>(*_v) + : nullptr; + } else { + const int idx = _v->index(); + if (idx >= 0 && static_cast(idx) < matches.size() && + matches[static_cast(idx)]) { + return internal::variant::Access::template ptr_as(*_v); } - }; - return _v->visit(get); + return nullptr; + } } /// @brief Returns a const pointer to the contained value if it is of type T, @@ -587,15 +393,27 @@ constexpr T* get_if(Variant* _v) noexcept { /// @return Const pointer to the contained value or nullptr. template constexpr const T* get_if(const Variant* _v) noexcept { - const auto get = [](const auto& _v) -> const T* { - using Type = std::remove_cvref_t; - if constexpr (std::is_same>()) { - return &_v; - } else { - return nullptr; + if (!_v) { + return nullptr; + } + constexpr auto matches = + internal::variant::get_if_matches(); + constexpr auto plan = internal::variant::analyze_get_if_matches(matches); + if constexpr (plan.count == 0) { + return nullptr; + } else if constexpr (plan.count == 1) { + return _v->index() == plan.first_index + ? &internal::variant::Access::template get_alternative< + plan.first_index>(*_v) + : nullptr; + } else { + const int idx = _v->index(); + if (idx >= 0 && static_cast(idx) < matches.size() && + matches[static_cast(idx)]) { + return internal::variant::Access::template ptr_as(*_v); } - }; - return _v->visit(get); + return nullptr; + } } /// @brief Returns a pointer to the contained value if it is of the N-th @@ -606,8 +424,11 @@ constexpr const T* get_if(const Variant* _v) noexcept { /// @return Pointer to the contained value or nullptr. template constexpr auto* get_if(Variant* _v) noexcept { - using T = internal::nth_element_t<_i, Types...>; - return get_if(_v); + static_assert(_i >= 0 && _i < static_cast(sizeof...(Types)), + "Index out of bounds."); + return (_v && _v->index() == _i) + ? &internal::variant::Access::template get_alternative<_i>(*_v) + : nullptr; } /// @brief Returns a const pointer to the contained value if it is of the N-th @@ -618,8 +439,11 @@ constexpr auto* get_if(Variant* _v) noexcept { /// @return Const pointer to the contained value or nullptr. template constexpr auto* get_if(const Variant* _v) noexcept { - using T = internal::nth_element_t<_i, Types...>; - return get_if(_v); + static_assert(_i >= 0 && _i < static_cast(sizeof...(Types)), + "Index out of bounds."); + return (_v && _v->index() == _i) + ? &internal::variant::Access::template get_alternative<_i>(*_v) + : nullptr; } /// @brief Returns a reference to the contained value if it is of type T, throws 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/avro/Reader.hpp b/include/rfl/avro/Reader.hpp index 902550517..b5afe90be 100644 --- a/include/rfl/avro/Reader.hpp +++ b/include/rfl/avro/Reader.hpp @@ -14,6 +14,7 @@ #include "../always_false.hpp" #include "../concepts.hpp" #include "../internal/is_literal.hpp" +#include "../internal/ptr_cast.hpp" #include "../parsing/schemaful/IsSchemafulReader.hpp" namespace rfl::avro { diff --git a/include/rfl/bson/Writer.hpp b/include/rfl/bson/Writer.hpp index ab95ebcc6..6158f8011 100644 --- a/include/rfl/bson/Writer.hpp +++ b/include/rfl/bson/Writer.hpp @@ -4,14 +4,13 @@ #include #include +#include #include #include #include #include #include -#include -#include "../Box.hpp" #include "../Ref.hpp" #include "../always_false.hpp" #include "../common.hpp" @@ -71,7 +70,7 @@ class RFL_API Writer { OutputVarType null_as_root() const noexcept; template - OutputVarType value_as_root(const T& _var) const noexcept { + OutputVarType value_as_root(const T&) const noexcept { static_assert(rfl::always_false_v, "BSON only allows arrays or objects as its root."); return OutputVarType{}; @@ -237,8 +236,8 @@ class RFL_API Writer { /// called objects. bson_t* const doc_; - /// Contain all of the subdocuments. - const rfl::Ref>> subdocs_; + /// Stack of active subdocuments (pointer-stable across push/pop). + const rfl::Ref> subdocs_; }; } // namespace bson diff --git a/include/rfl/capnproto/Writer.hpp b/include/rfl/capnproto/Writer.hpp index f61967714..315fd6c2e 100644 --- a/include/rfl/capnproto/Writer.hpp +++ b/include/rfl/capnproto/Writer.hpp @@ -15,6 +15,7 @@ #include "../always_false.hpp" #include "../common.hpp" #include "../internal/is_literal.hpp" +#include "../internal/ptr_cast.hpp" namespace rfl::capnproto { diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp index cad64d631..f282a08c7 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,16 @@ 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 || + 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/cbor/Reader.hpp b/include/rfl/cbor/Reader.hpp index 62fcfa4fa..aa96a5b7d 100644 --- a/include/rfl/cbor/Reader.hpp +++ b/include/rfl/cbor/Reader.hpp @@ -93,10 +93,12 @@ class Reader { /// found rfl::Result get_field_from_object( const std::string& _name, const InputObjectType& _obj) const noexcept { - for (auto& kv : _obj.val_->object_range()) { - if (kv.key() == _name) { - return InputVarType{&kv.value()}; - }; + if (!_obj.val_->is_object()) { + return error("Field name '" + _name + "' not found."); + } + const auto it = _obj.val_->find(_name); + if (it != _obj.val_->object_range().end()) { + return InputVarType{&it->value()}; } return error("Field name '" + _name + "' not found."); } diff --git a/include/rfl/cli/Reader.hpp b/include/rfl/cli/Reader.hpp index 58c16d37b..08c73a287 100644 --- a/include/rfl/cli/Reader.hpp +++ b/include/rfl/cli/Reader.hpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -181,13 +180,12 @@ struct Reader { if (!_var.args) { return true; } - if (_var.args->count(_var.path)) { + if (_var.args->contains(_var.path)) { return false; } const auto prefix = _var.path + path_separator; const auto it = _var.args->lower_bound(prefix); - return it == _var.args->end() - || it->first.substr(0, prefix.size()) != prefix; + return it == _var.args->end() || !it->first.starts_with(prefix); } /// Reads all elements from a CLI array using the provided array reader. @@ -211,7 +209,8 @@ struct Reader { } /// Reads all fields from a CLI object using the provided object reader. - /// Iterates through all arguments with the object's prefix and extracts child field names. + /// Iterates through arguments matching the object's prefix, extracting + /// direct child field names and skipping nested subtrees via lower_bound. /// @tparam ObjectReader The type of reader that processes individual object fields /// @param _object_reader The reader object that processes each field /// @param _obj The CLI object to read from @@ -221,28 +220,48 @@ struct Reader { const ObjectReader& _object_reader, const InputObjectType& _obj ) const noexcept { - std::set seen; + if (!_obj.args) { + return std::nullopt; + } + static_assert( + static_cast(path_separator) < 255, + "path_separator must allow incrementing for range skipping."); + constexpr char after_separator = + static_cast(static_cast(path_separator) + 1); auto it = _obj.prefix.empty() ? _obj.args->begin() : _obj.args->lower_bound(_obj.prefix); while (it != _obj.args->end()) { - if (!_obj.prefix.empty() - && it->first.substr(0, _obj.prefix.size()) != _obj.prefix) { + if (!_obj.prefix.empty() && !it->first.starts_with(_obj.prefix)) { break; } const auto rest = std::string_view(it->first).substr(_obj.prefix.size()); const auto separator_pos = rest.find(path_separator); - const auto child = std::string( - separator_pos == std::string_view::npos - ? rest - : rest.substr(0, separator_pos)); - if (!child.empty() && seen.insert(child).second) { - const auto child_path = _obj.prefix + child; + if (separator_pos == std::string_view::npos) { + if (!rest.empty()) { + _object_reader.read( + rest, + InputVarType{_obj.args, it->first, std::nullopt}); + } + ++it; + continue; + } + const auto child = rest.substr(0, separator_pos); + std::string sub_prefix; + sub_prefix.reserve(_obj.prefix.size() + child.size() + 1); + sub_prefix.append(_obj.prefix); + sub_prefix.append(child); + if (!child.empty() && !_obj.args->contains(sub_prefix)) { _object_reader.read( - std::string_view(child), - InputVarType{_obj.args, child_path, std::nullopt}); + child, + InputVarType{_obj.args, sub_prefix, std::nullopt}); } + sub_prefix.push_back(path_separator); ++it; + if (it != _obj.args->end() && it->first.starts_with(sub_prefix)) { + sub_prefix.back() = after_separator; + it = _obj.args->lower_bound(sub_prefix); + } } return std::nullopt; } diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index bfa62c928..e9b700f43 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -1,22 +1,24 @@ #ifndef RFL_CLI_OPTIONS_HPP_ #define RFL_CLI_OPTIONS_HPP_ +#include #include #include #include #include #include #include -#include #include #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../NamedTuple.hpp" +#include "../Nullable.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" -#include "../Tuple.hpp" +#include "../TriState.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" @@ -129,6 +131,12 @@ struct cli_annotations> : cli_annotations_t {}; template struct cli_annotations> : cli_annotations_t {}; +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t {}; + template struct cli_annotations> : cli_annotations_t {}; @@ -155,11 +163,10 @@ struct cli_annotations> : cli_annotations_t { static constexpr int count = cli_annotations_t::count + 1; }; -/// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the +/// The CLI metadata of a single NamedTuple field. InnerType is the /// declared type of the field, whichever wrappers it consists of. -template +template struct field_info { - using FieldType = rfl::tuple_element_t<_i, typename NamedTupleType::Fields>; using InnerType = typename FieldType::Type; using OuterType = std::remove_pointer_t>; using Annotations = cli_annotations_t; @@ -174,18 +181,6 @@ struct field_info { static constexpr std::string_view name() { return FieldType::name(); } }; -/// The short name of the _i-th field, or an empty string if it has none. -template -constexpr auto get_short_name() { - using Info = field_info; - if constexpr (Info::is_short) { - return Info::Annotations::short_name; - } - else { - return rfl::internal::StringLiteral<1>(""); - } -} - /// Strips everything that does not change how a field is written on the /// command line: optionals, pointers, rfl::Short, rfl::Positional, /// rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a @@ -197,7 +192,9 @@ auto unwrap_option_type() { if constexpr (std::is_pointer_v) { return unwrap_option_type, ProcessorsType>(); } - else if constexpr (parsing::is_optional_v) { + else if constexpr (parsing::is_optional_v || + rfl::internal::is_nullable_wrapper_v || + rfl::internal::is_tri_state_v) { return unwrap_option_type(); } else if constexpr (parsing::is_unique_ptr_v @@ -267,67 +264,99 @@ using option_fields_t = typename std::conditional_t< rfl::internal::is_named_tuple_v, std::type_identity, rfl::internal::Processed>::type; -/// Adds the option of the top-level field `_name` of type T. +/// Compile-time metadata for one top-level field of a target struct. +struct OptionFieldDescriptor { + std::string_view name; + std::string_view short_name; + OptionKind kind = OptionKind::unknown; + bool has_long_option = false; + bool is_short = false; + bool is_positional = false; +}; + +/// Returns the OptionKind of a field type T after unwrapping CLI wrappers. template -void add_option(const std::string& _name, Options* _options) { +constexpr OptionKind option_kind_for_type() { using U = unwrapped_option_t; if constexpr (std::is_same_v) { - _options->long_options[_name] = Option{OptionKind::flag}; - } - else if constexpr (is_open_option_v || parsing::is_string_map_v - || is_option_struct_v) { - _options->long_options[_name] = Option{OptionKind::other}; - } - else { - _options->long_options[_name] = Option{OptionKind::value}; + return OptionKind::flag; + } else if constexpr (is_open_option_v || parsing::is_string_map_v + || is_option_struct_v) { + return OptionKind::other; + } else { + return OptionKind::value; } } +/// Builds the compile-time option descriptor for a single field. +/// Parameterized only on (FieldType, ProcessorsType) — never the enclosing +/// NamedTuple or struct type — so template instantiations stay O(F). template -void add_option_for_field(Options* _options) { +constexpr OptionFieldDescriptor make_option_field_descriptor() { using T = std::remove_cvref_t; + using Info = field_info; + OptionFieldDescriptor desc{}; + desc.name = Info::name(); + desc.is_short = Info::is_short; + desc.is_positional = Info::is_positional; if constexpr (!rfl::internal::is_extra_fields_v) { - add_option(std::string(FieldType::name()), _options); + desc.has_long_option = true; + desc.kind = option_kind_for_type(); + } + if constexpr (Info::is_short) { + desc.short_name = Info::Annotations::short_name.string_view(); } + return desc; } -/// Adds the options of the top-level fields of T. -template -void collect_options(Options* _options) { - using NT = option_fields_t; - [&](std::index_sequence<_is...>) { - (add_option_for_field, - ProcessorsType>(_options), - ...); - }(std::make_index_sequence()); +template +constexpr std::array +make_option_descriptors(const NamedTuple*) { + return std::array{{ + make_option_field_descriptor, + ProcessorsType>()...}}; } -/// Adds the short alias and the positional slot of the _i-th top-level -/// field, if it has them. Two fields with the same short name are kept as -/// an error (Options::duplicate_short_name). -template -void add_short_and_positional(Options* _options) { - using Info = field_info; - if constexpr (Info::is_short) { - const auto name = - std::string(get_short_name().string_view()); - if (!_options->short_options.emplace(name, std::string(Info::name())) - .second - && _options->duplicate_short_name.empty()) { - _options->duplicate_short_name = name; +/// Populates Options from a flat table of compile-time field descriptors. +/// Two fields with the same short name are kept as an error +/// (Options::duplicate_short_name). +inline void populate_options(const OptionFieldDescriptor* _descriptors, + const size_t _count, Options* _options) { + for (size_t i = 0; i < _count; ++i) { + const auto& desc = _descriptors[i]; + if (desc.has_long_option) { + _options->long_options[std::string(desc.name)] = Option{desc.kind}; + } + if (desc.is_short) { + const auto short_name = std::string(desc.short_name); + if (!_options->short_options + .emplace(short_name, std::string(desc.name)) + .second + && _options->duplicate_short_name.empty()) { + _options->duplicate_short_name = short_name; + } + if (!short_name.empty() + && ((short_name[0] >= '0' && short_name[0] <= '9') + || short_name[0] == '.')) { + _options->negative_numbers_are_options = true; + } + } + if (desc.is_positional) { + _options->positionals.emplace_back(desc.name); } - } - if constexpr (Info::is_positional) { - _options->positionals.emplace_back(Info::name()); } } +/// Adds the options, short aliases, and positional slots of the top-level +/// fields of T. template -void collect_short_and_positional(Options* _options) { +void collect_options(Options* _options) { using NT = option_fields_t; - [&](std::index_sequence<_is...>) { - (add_short_and_positional(_options), ...); - }(std::make_index_sequence()); + if constexpr (NT::size() > 0) { + static constexpr auto descriptors = make_option_descriptors( + static_cast(nullptr)); + populate_options(descriptors.data(), descriptors.size(), _options); + } } /// Derives the options that T accepts from its fields: the option of every @@ -340,19 +369,12 @@ template Options make_options() { Options options; options.group_short_options = true; - using U = unwrapped_option_t; - if constexpr (is_option_struct_v) { - collect_options(&options); - collect_short_and_positional(&options); - } // As in argparse, -5 is a negative number unless a short option's name // looks like a number (-1). options.negative_numbers_are_options = false; - for (const auto& [name, path] : options.short_options) { - if (!name.empty() - && ((name[0] >= '0' && name[0] <= '9') || name[0] == '.')) { - options.negative_numbers_are_options = true; - } + using U = unwrapped_option_t; + if constexpr (is_option_struct_v) { + collect_options(&options); } return options; } diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 4d384ab80..524de010a 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -2,15 +2,19 @@ #define RFL_CLI_USAGE_HPP_ #include +#include #include #include -#include #include #include +#include #include +#include +#include #include #include +#include "../NamedTuple.hpp" #include "../Processors.hpp" #include "../Result.hpp" #include "../SnakeCaseToKebabCase.hpp" @@ -62,52 +66,92 @@ struct UsageArg { 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 +/// Compile-time metadata for one top-level field used by usage(). +struct UsageFieldDescriptor { + std::string_view name; + bool required = true; +}; + +/// Whether a missing field of type `ValueType` inside a root type described by +/// `(_is_named_tuple, _is_default_constructible)` 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) { + } else if constexpr (_is_named_tuple) { 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; + return _is_default_constructible; } } -template -void add_usage_field_meta(std::map* _meta) { - using Info = field_info; +/// Builds the compile-time usage descriptor for a single field. +/// Parameterized only on (FieldType, ProcessorsType) and root-type flags +/// (never the enclosing NamedTuple or struct type) so instantiations stay O(F). +template +constexpr UsageFieldDescriptor make_usage_field_descriptor() { + 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() + constexpr bool required = + !usage_default_val_is_optional<_is_named_tuple, _is_default_constructible, + RawValueType>() && !rfl::internal::is_extra_fields_v && (rfl::internal::no_optionals_v || parsing::is_required()); + return UsageFieldDescriptor{Info::name(), required}; +} + +template +constexpr std::array +make_usage_field_descriptors(const NamedTuple*) { + return std::array{{ + make_usage_field_descriptor, + ProcessorsType, _is_named_tuple, + _is_default_constructible>()...}}; +} + +/// Populates the top-level usage metadata map from a flat table of compile-time +/// field descriptors. +inline std::unordered_map +populate_usage_field_meta(const UsageFieldDescriptor* _descriptors, + const size_t _count) { + std::unordered_map meta; + meta.reserve(_count); + for (size_t i = 0; i < _count; ++i) { + meta[_descriptors[i].name].required = _descriptors[i].required; + } + return meta; } /// 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; +template +std::unordered_map +collect_usage_field_meta() { + using NT = option_fields_t; + if constexpr (NT::size() == 0) { + return {}; + } else { + static constexpr auto descriptors = make_usage_field_descriptors< + ProcessorsType, rfl::internal::is_named_tuple_v, + std::is_default_constructible_v>(static_cast(nullptr)); + return populate_usage_field_meta(descriptors.data(), descriptors.size()); + } } /// Walks the format-agnostic schema of the struct and collects one UsageArg @@ -116,17 +160,22 @@ 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) + UsageCollector( + const parsing::schema::Definition* _definition, + const std::unordered_map* _meta, + const Options* _options, const bool _optionals_are_required) : definition_(_definition), meta_(_meta), options_(_options), optionals_are_required_(_optionals_are_required) { + short_names_.reserve(_options->short_options.size()); for (const auto& [short_name, path] : _options->short_options) { short_names_[path] = short_name; } + positionals_.reserve(_options->positionals.size()); + for (const auto& name : _options->positionals) { + positionals_.emplace(name); + } } /// Collects the arguments. @@ -146,13 +195,21 @@ class UsageCollector { 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 constexpr (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.description.empty() && _t.description_.has_value()) { + _arg.description = *_t.description_; + } + add(*_t.type_, std::move(_arg), _outermost); + + } else if constexpr (std::is_same_v) { + 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; @@ -228,12 +285,10 @@ class UsageCollector { // 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(); + arg.positional = positionals_.contains(name); const auto short_name = short_names_.find(name); if (short_name != short_names_.end()) { - arg.short_name = short_name->second; + arg.short_name = std::string(short_name->second); } const auto it = meta_->find(name); if (it != meta_->end()) { @@ -271,11 +326,13 @@ class UsageCollector { private: const parsing::schema::Definition* definition_; - const std::map* meta_; + const std::unordered_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::unordered_map short_names_; + /// The rfl::Positional top-level field names for O(1) lookup. + std::unordered_set positionals_; std::set visiting_; std::vector args_; }; @@ -421,13 +478,9 @@ rfl::Result usage(const std::string& _program_name, return internal::check_short_names(options).and_then( [&](auto) -> rfl::Result { try { - std::map meta; + std::unordered_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{}); + meta = internal::collect_usage_field_meta(); } // The schema takes the default values from a default-constructed // T, which can throw. diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 258adf8d4..8dfda4f63 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -64,8 +64,11 @@ struct EqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value != threshold) { - return error(internal::comparison_error_message( - "Value expected to be equal to ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected to be equal to ", threshold, + _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::equal_to)); } return _value; } @@ -101,8 +104,11 @@ struct Minimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value < threshold) { - return error(internal::comparison_error_message( - "Value expected to be greater than or equal to ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected to be greater than or equal to ", + threshold, _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::minimum)); } return _value; } @@ -138,8 +144,11 @@ struct ExclusiveMinimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value <= threshold) { - return error(internal::comparison_error_message( - "Value expected to be greater than ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected to be greater than ", threshold, + _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::exclusive_minimum)); } return _value; } @@ -175,8 +184,11 @@ struct Maximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value > threshold) { - return error(internal::comparison_error_message( - "Value expected to be less than or equal to ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected to be less than or equal to ", + threshold, _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::maximum)); } return _value; } @@ -211,8 +223,11 @@ struct ExclusiveMaximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value >= threshold) { - return error(internal::comparison_error_message( - "Value expected to be less than ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected to be less than ", threshold, + _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::exclusive_maximum)); } return _value; } @@ -247,8 +262,11 @@ struct NotEqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value == threshold) { - return error(internal::comparison_error_message( - "Value expected not to be equal to ", threshold, _value)); + return error(Error(internal::comparison_error_message( + "Value expected not to be equal to ", threshold, + _value), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::not_equal_to)); } return _value; } diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 133791b2f..68b1964fc 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -2,13 +2,18 @@ #define RFL_ENUMS_HPP_ #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" @@ -56,63 +61,155 @@ 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_view _str) { +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); + return error(std::move(msg), ErrorKind::invalid_value); }; const auto cast_numbers_or_names = - [&](const std::string_view 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); @@ -120,7 +217,7 @@ Result string_to_enum(const std::string_view _str) { if (name.empty()) { return make_error_msg(name); } - using Underlying = std::underlying_type_t; + using Underlying = std::underlying_type_t; using ParseType = std::conditional_t< (sizeof(Underlying) < sizeof(int)), int, std::conditional_t< @@ -139,14 +236,14 @@ Result string_to_enum(const std::string_view _str) { 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 static_cast(val); } return make_error_msg(name); } }; - if constexpr (internal::enums::is_flag_enum) { - using T = std::underlying_type_t; + if constexpr (internal::enums::is_flag_enum) { + using T = std::underlying_type_t; auto res = static_cast(0); std::string_view remaining = _str; while (true) { @@ -162,12 +259,64 @@ Result string_to_enum(const std::string_view _str) { } 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 b87690baa..af9d7a96b 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -76,8 +76,9 @@ rfl::Result parse_value(const std::string& _str, if (_str == "false" || _str == "0") { return false; } - return error("Could not cast '" + _str + "' to boolean for key '" + _path + - "'."); + return error( + "Could not cast '" + _str + "' to boolean for key '" + _path + "'.", + ErrorKind::invalid_value); } /// Parses a string value to a floating-point number. @@ -107,7 +108,8 @@ rfl::Result parse_value(const std::string& _str, #endif if (end != _str.c_str() + _str.size()) { return error("Could not cast '" + _str + "' to floating point for key '" + - _path + "'."); + _path + "'.", + ErrorKind::invalid_value); } return static_cast(value); } @@ -127,7 +129,8 @@ rfl::Result parse_value(const std::string& _str, std::from_chars(_str.data(), _str.data() + _str.size(), value); if (ec != std::errc() || ptr != _str.data() + _str.size()) { return error("Could not cast '" + _str + "' to integer for key '" + _path + - "'."); + "'.", + ErrorKind::invalid_value); } return value; } @@ -270,7 +273,8 @@ struct Reader { rfl::Result to_basic_type(const InputVarType& _var) const noexcept { const auto str = get_value(_var); if (!str) { - return error("No value for key '" + _var.path + "'."); + return error("No value for key '" + _var.path + "'.", + ErrorKind::missing_field); } return parse_value(*str, _var.path); } diff --git a/include/rfl/flexbuf/Reader.hpp b/include/rfl/flexbuf/Reader.hpp index 8ef601d5e..f0901e9c2 100644 --- a/include/rfl/flexbuf/Reader.hpp +++ b/include/rfl/flexbuf/Reader.hpp @@ -3,7 +3,9 @@ #include +#include #include +#include #include #include #include @@ -39,9 +41,22 @@ struct Reader { rfl::Result get_field_from_object( const std::string& _name, const InputObjectType& _obj) const noexcept { const auto keys = _obj.Keys(); - for (size_t i = 0; i < keys.size(); ++i) { - if (_name == keys[i].AsString().c_str()) { - return _obj.Values()[i]; + const auto values = _obj.Values(); + size_t lo = 0; + size_t hi = std::min(keys.size(), values.size()); + while (lo < hi) { + const size_t mid = lo + (hi - lo) / 2; + const char* const key = keys[mid].AsKey(); + const int cmp = std::strcmp(key, _name.c_str()); + if (cmp < 0) { + lo = mid + 1; + } else if (cmp > 0) { + hi = mid; + } else { + if (_name == key) { + return values[mid]; + } + break; } } return error("Map does not contain any element called '" + _name + "'."); diff --git a/include/rfl/generic/Reader.hpp b/include/rfl/generic/Reader.hpp index db9631800..b5f9b8dd2 100644 --- a/include/rfl/generic/Reader.hpp +++ b/include/rfl/generic/Reader.hpp @@ -30,7 +30,8 @@ struct Reader { rfl::Result get_field_from_array( const size_t _idx, const InputArrayType& _arr) const noexcept { if (_idx >= _arr.size()) { - return error("Index " + std::to_string(_idx) + " of of bounds."); + return error("Index " + std::to_string(_idx) + " of of bounds.", + ErrorKind::missing_field); } return _arr[_idx]; } diff --git a/include/rfl/generic/write.hpp b/include/rfl/generic/write.hpp index f6668ce8a..2c6c15000 100644 --- a/include/rfl/generic/write.hpp +++ b/include/rfl/generic/write.hpp @@ -1,6 +1,8 @@ #ifndef GENERIC_WRITE_HPP_ #define GENERIC_WRITE_HPP_ +#include + #include "../Generic.hpp" #include "../parsing/Parent.hpp" #include "Parser.hpp" @@ -20,7 +22,7 @@ Generic write(const auto& _t) { using ParentType = parsing::Parent; auto w = Writer(); Parser>::write(w, _t, typename ParentType::Root{}); - return w.root(); + return std::move(w.root()); } } // namespace generic diff --git a/include/rfl/internal/Error.hpp b/include/rfl/internal/Error.hpp index f8797c1f0..d2e5b0e4b 100644 --- a/include/rfl/internal/Error.hpp +++ b/include/rfl/internal/Error.hpp @@ -2,16 +2,119 @@ #define RFL_INTERNAL_ERROR_HPP_ #include +#include #include #include +#include #include #include #include +#include "../common.hpp" #include "cold.hpp" namespace rfl::internal { +/// Coarse, format-agnostic classification of an ErrorDetail failure. +/// Classifies the input (or I/O environment), never caller/programmer bugs. +/// Open enum: new enumerators may be added in minor releases; switch +/// statements over ErrorKind should include a `default:` branch. +enum class ErrorKind : std::uint8_t { + /// Unclassified: custom parsers/reflectors, caller/programmer bugs, + /// and formats not yet tagged. + other = 0, + + /// Input could not be obtained or output could not be emitted + /// (file open/read/write/close, stream badbit/failbit, directory/size I/O). + io_error, + + /// Bytes or tokens cannot form the format's data model regardless of target + /// type (malformed/truncated JSON/YAML/TOML, invalid UTF-8/UTF-16, depth + /// limit, recursive YAML alias, malformed CLI token such as `--=val`). + syntax_error, + + /// A declared, individually-required slot has no entry + /// (required struct field, tuple element, required positional, or + /// tagged-union discriminator key). + missing_field, + + /// A key, option, or argv token resolves to no declared slot—or ambiguously + /// to more than one (under NoExtraFields, extra CLI positionals, or + /// ambiguous CLI option abbreviations). + unknown_field, + + /// Element or value count violates a count fixed by the C++ type or option + /// arity (std::array size mismatch, tuple overflow, inplace_vector + /// capacity, CLI option arity mismatch). + invalid_length, + + /// The node's native wire class is incompatible with the target type + /// (null/bool/integer/float/string/bytes/array/object mismatch). + invalid_type, + + /// Right wire class (or string-only format token), but domain/lexical + /// conversion to the C++ type failed (numeric range/sign overflow including + /// negative int for unsigned, unknown enum/tag/FieldVariant key, bad + /// timestamp/base64/bitset, no matching variant). + invalid_value, + + /// Value successfully converted to the target C++ type, then a declared + /// check rejected it (rfl::Validator<...>, AllOf/AnyOf/OneOf, Size, Pattern, + /// Minimum, CLI constraints). + constraint_violation, +}; + +/// Internal compact tags for built-in validator rule codes so leaf validator +/// errors carry a machine-readable code inline in Error without increasing +/// sizeof(Error) or allocating OptionalDetails. +enum class BuiltinErrorCode : std::uint8_t { + none = 0, + equal_to, + not_equal_to, + minimum, + exclusive_minimum, + maximum, + exclusive_maximum, + pattern, + any_of, + one_of, + size, + size_equal_to, + size_not_equal_to, + size_minimum, + size_exclusive_minimum, + size_maximum, + size_exclusive_maximum, + size_any_of, + size_one_of, + code_points, + code_points_equal_to, + code_points_not_equal_to, + code_points_minimum, + code_points_exclusive_minimum, + code_points_maximum, + code_points_exclusive_maximum, + code_points_any_of, + code_points_one_of, +}; + +/// Returns the canonical wire string for a BuiltinErrorCode, or empty if none. +RFL_API std::string_view builtin_error_code_str( + BuiltinErrorCode _code) noexcept; + +/// Maps a canonical wire string back to its compact BuiltinErrorCode if it is +/// one of the built-in validator codes, or BuiltinErrorCode::none otherwise. +RFL_API BuiltinErrorCode parse_builtin_error_code( + std::string_view _code) noexcept; + +/// Composes a BuiltinErrorCode under the `size.*` namespace when possible. +RFL_API BuiltinErrorCode compose_size_code(BuiltinErrorCode _inner) noexcept; + +/// Composes a BuiltinErrorCode under the `code_points.*` namespace when +/// possible. +RFL_API BuiltinErrorCode compose_code_points_code( + BuiltinErrorCode _inner) noexcept; + /// Describes a single failure contained in an Error: where it occurred and /// what went wrong. struct ErrorDetail { @@ -28,6 +131,14 @@ struct ErrorDetail { /// '...': " prefixes that Error::what() contains for every level of nesting. std::string message; + /// The coarse category of this failure. + ErrorKind kind = ErrorKind::other; + + /// Optional machine-readable rule or error code (for example, `"minimum"`, + /// `"size.minimum"`, `"pattern"`, or a custom validator code). Empty when + /// no finer-grained code applies. + std::string code = {}; + bool operator==(const ErrorDetail&) const = default; }; @@ -46,6 +157,49 @@ class Error { /// @param _what The error message describing what went wrong (will be moved) Error(std::string&& _what) : what_(std::move(_what)) {} + /// Constructs a classified leaf error with a message (copy), without + /// allocating an explicit detail vector. + /// @param _what The error message describing what went wrong + /// @param _kind Coarse classification of the failure + Error(const std::string& _what, const ErrorKind _kind) + : what_(_what), kind_(_kind) {} + + /// Constructs a classified leaf error with a message (move), without + /// allocating an explicit detail vector. + /// @param _what The error message describing what went wrong (will be moved) + /// @param _kind Coarse classification of the failure + Error(std::string&& _what, const ErrorKind _kind) + : what_(std::move(_what)), kind_(_kind) {} + + /// Constructs a classified leaf error with a built-in rule code, without + /// allocating an explicit detail vector. + Error(std::string _what, const ErrorKind _kind, + const BuiltinErrorCode _builtin_code) + : what_(std::move(_what)), kind_(_kind), builtin_code_(_builtin_code) {} + + /// Constructs a classified error with a machine-readable code. + /// Built-in codes are stored inline without allocating details; custom codes + /// are stored in details_. + Error(std::string _what, const ErrorKind _kind, const std::string_view _code) + : what_(std::move(_what)), kind_(_kind) { + if (_code.empty()) { + return; + } + const auto builtin = parse_builtin_error_code(_code); + if (builtin != BuiltinErrorCode::none) { + builtin_code_ = builtin; + return; + } + std::vector details; + details.push_back(ErrorDetail{ + .path = {}, + .message = what_, + .kind = _kind, + .code = std::string(_code), + }); + details_ = OptionalDetails(std::move(details)); + } + /// Constructs an error with a message and the individual failures it /// summarizes. /// @param _what The error message describing what went wrong @@ -53,7 +207,9 @@ class Error { Error(std::string _what, std::vector _details) : what_(std::move(_what)), details_(_details.empty() ? OptionalDetails() - : OptionalDetails(std::move(_details))) {} + : OptionalDetails(std::move(_details))), + kind_(details_.has_value() ? (*details_).front().kind + : ErrorKind::other) {} /// Destructor. ~Error() = default; @@ -82,12 +238,36 @@ class Error { /// from state std::string what() && { return std::move(what_); } + /// Returns the ErrorKind of this error. For multi-error results, returns the + /// kind of the first detail. + ErrorKind kind() const noexcept { + return details_.has_value() && !(*details_).empty() + ? (*details_).front().kind + : kind_; + } + + /// Returns the machine-readable error code of this error, or an empty view + /// when none is set. For multi-error results, returns the code of the first + /// detail. + /// Note: For custom (non-built-in) codes, the returned string_view refers to + /// storage owned by this Error and must not outlive it. + std::string_view code() const noexcept { + if (details_.has_value() && !(*details_).empty()) { + return (*details_).front().code; + } + return builtin_error_code_str(builtin_code_); + } + /// Returns the individual failures summarized by what(), each with the /// location at which it occurred. An error that was constructed from a /// message only is reported as a single failure at the root. std::vector details() const& { if (!details_.has_value()) { - return {ErrorDetail{.path = {}, .message = what_}}; + return {ErrorDetail{ + .path = {}, + .message = what_, + .kind = kind_, + .code = std::string(builtin_error_code_str(builtin_code_))}}; } return *details_; } @@ -96,12 +276,73 @@ class Error { /// moved from state. std::vector details() && { if (!details_.has_value()) { - return {ErrorDetail{.path = {}, .message = std::move(what_)}}; + return {ErrorDetail{ + .path = {}, + .message = std::move(what_), + .kind = kind_, + .code = std::string(builtin_error_code_str(builtin_code_))}}; } return std::move(*details_); } private: + friend bool has_allocated_details(const Error& _err) noexcept { + return _err.details_.has_value(); + } + + friend BuiltinErrorCode builtin_error_code_of(const Error& _err) noexcept { + return _err.details_.has_value() ? BuiltinErrorCode::none + : _err.builtin_code_; + } + + friend void set_error_kind_if_other(Error& _err, + const ErrorKind _kind) noexcept { + if (_kind == ErrorKind::other) { + return; + } + if (!_err.details_.has_value()) { + if (_err.kind_ == ErrorKind::other) { + _err.kind_ = _kind; + } + return; + } + for (auto& detail : *_err.details_) { + if (detail.kind == ErrorKind::other) { + detail.kind = _kind; + } + } + } + + friend void set_error_code_if_empty(Error& _err, + const std::string_view _code) { + if (_code.empty()) { + return; + } + if (!_err.details_.has_value()) { + if (_err.builtin_code_ != BuiltinErrorCode::none) { + return; + } + const auto builtin = parse_builtin_error_code(_code); + if (builtin != BuiltinErrorCode::none) { + _err.builtin_code_ = builtin; + return; + } + std::vector details; + details.push_back(ErrorDetail{ + .path = {}, + .message = _err.what_, + .kind = _err.kind_, + .code = std::string(_code), + }); + _err.details_ = OptionalDetails(std::move(details)); + return; + } + for (auto& detail : *_err.details_) { + if (detail.code.empty()) { + detail.code = std::string(_code); + } + } + } /// Either nothing or a heap-allocated vector of details, deep-copied along /// with the Error. Holding nothing is the common case: it means that the /// Error is just its message, and it does not allocate. @@ -162,8 +403,29 @@ class Error { /// The individual failures summarized by what_. Holds nothing, unless what_ /// was assembled from failures at nested locations. OptionalDetails details_; + + /// Coarse category for a leaf error when details_ holds nothing. + ErrorKind kind_ = ErrorKind::other; + + /// Compact built-in rule code for a leaf error when details_ holds nothing. + /// Packed into ErrorKind's tail padding so sizeof(Error) does not grow. + BuiltinErrorCode builtin_code_ = BuiltinErrorCode::none; }; +/// Returns whether _err has a heap-allocated detail vector. +bool has_allocated_details(const Error& _err) noexcept; + +/// Returns the inline BuiltinErrorCode for a leaf error (none if detailed). +BuiltinErrorCode builtin_error_code_of(const Error& _err) noexcept; + +/// Replaces ErrorKind::other with _kind in place without copying what_ or +/// allocating details on leaf errors. +void set_error_kind_if_other(Error& _err, ErrorKind _kind) noexcept; + +/// Attaches _code to _err (or to each uncoded detail) when no code is already +/// present. Preserves zero-allocation for built-in codes on leaf errors. +void set_error_code_if_empty(Error& _err, std::string_view _code); + } // namespace rfl::internal #endif diff --git a/include/rfl/internal/HasFromReflectionMethod.hpp b/include/rfl/internal/HasFromReflectionMethod.hpp index 8c794cf06..5c34e6387 100644 --- a/include/rfl/internal/HasFromReflectionMethod.hpp +++ b/include/rfl/internal/HasFromReflectionMethod.hpp @@ -4,13 +4,19 @@ #include #include +#include "../Result.hpp" + namespace rfl::internal { -/// Satisfied by a type `T` providing `static T from_reflection(ReflectionType&&)`. +/// Satisfied by a type `T` providing `static U from_reflection(ReflectionType&&)` +/// where `U` is convertible to `T` or `Result`. template -concept HasFromReflectionMethod = requires(typename T::ReflectionType&& _r) { - { T::from_reflection(std::move(_r)) } -> std::convertible_to; -}; +concept HasFromReflectionMethod = + requires(typename T::ReflectionType&& _r) { + { T::from_reflection(std::move(_r)) } -> std::convertible_to; + } || requires(typename T::ReflectionType&& _r) { + { T::from_reflection(std::move(_r)) } -> std::convertible_to>; + }; } // namespace rfl::internal diff --git a/include/rfl/internal/IndexedTypeMap.hpp b/include/rfl/internal/IndexedTypeMap.hpp new file mode 100644 index 000000000..6bc1404bd --- /dev/null +++ b/include/rfl/internal/IndexedTypeMap.hpp @@ -0,0 +1,38 @@ +#ifndef RFL_INTERNAL_INDEXEDTYPEMAP_HPP_ +#define RFL_INTERNAL_INDEXEDTYPEMAP_HPP_ + +#include +#include + +namespace rfl { +namespace internal { + +template +struct IndexedTypeMapEntry { + using type = T; +}; + +template +struct IndexedTypeMapImpl; + +template +struct IndexedTypeMapImpl, Ts...> + : IndexedTypeMapEntry... {}; + +template +IndexedTypeMapEntry select_indexed_type_map_entry( + const IndexedTypeMapEntry*); + +template +using IndexedTypeMap = + IndexedTypeMapImpl, Ts...>; + +template +using indexed_type_at_t = + typename decltype(rfl::internal::select_indexed_type_map_entry( + static_cast(nullptr)))::type; + +} // namespace internal +} // namespace rfl + +#endif // RFL_INTERNAL_INDEXEDTYPEMAP_HPP_ diff --git a/include/rfl/internal/Skip.hpp b/include/rfl/internal/Skip.hpp index 442683dec..fe9af1053 100644 --- a/include/rfl/internal/Skip.hpp +++ b/include/rfl/internal/Skip.hpp @@ -21,6 +21,8 @@ class Skip { using Type = T; using ReflectionType = std::optional; + template + requires std::is_default_constructible_v Skip() : value_(Type()) {} Skip(const Type& _value) : value_(_value) {} 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/add_null_fields_v.hpp b/include/rfl/internal/add_null_fields_v.hpp new file mode 100644 index 000000000..7c9cef988 --- /dev/null +++ b/include/rfl/internal/add_null_fields_v.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_ADD_NULL_FIELDS_V_HPP_ +#define RFL_INTERNAL_ADD_NULL_FIELDS_V_HPP_ + +#include + +#include "../AddNullFields.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct add_null_fields : std::false_type {}; + +template <> +struct add_null_fields : std::true_type {}; + +template +struct add_null_fields> + : std::bool_constant< + (add_null_fields>::value || ...)> {}; + +template +constexpr bool add_null_fields_v = + add_null_fields>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_ADD_NULL_FIELDS_V_HPP_ diff --git a/include/rfl/internal/base64.hpp b/include/rfl/internal/base64.hpp index 6a18fc2e9..e166b3500 100644 --- a/include/rfl/internal/base64.hpp +++ b/include/rfl/internal/base64.hpp @@ -45,7 +45,7 @@ inline Result decode_base64(const std::string_view _encoded) { const auto padding = _encoded.size() - size; if (size % 4 == 1 || padding > 2 || (padding != 0 && _encoded.size() % 4 != 0)) { - return error("Invalid Base64 length or padding."); + return error("Invalid Base64 length or padding.", ErrorKind::invalid_value); } Bytestring decoded; @@ -66,7 +66,8 @@ inline Result decode_base64(const std::string_view _encoded) { } else if (c == '/' || c == '_') { value = 63; } else { - return error("Invalid character in Base64 string."); + return error("Invalid character in Base64 string.", + ErrorKind::invalid_value); } buffer = (buffer << 6) | value; bits += 6; 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/bitset.hpp b/include/rfl/internal/bitset.hpp index 2ed688361..c3ff1b9bc 100644 --- a/include/rfl/internal/bitset.hpp +++ b/include/rfl/internal/bitset.hpp @@ -19,12 +19,13 @@ Result> bitset_from_string(const std::string_view _str) { message += ", got "; message += std::to_string(_str.size()); message += "."; - return error(std::move(message)); + return error(std::move(message), ErrorKind::invalid_value); } std::bitset bits; for (std::size_t i = 0; i < N; ++i) { if (_str[i] != '0' && _str[i] != '1') { - return error("Bitset strings may contain only '0' and '1'."); + return error("Bitset strings may contain only '0' and '1'.", + ErrorKind::invalid_value); } bits[N - 1 - i] = _str[i] == '1'; } @@ -56,12 +57,13 @@ Result> bitset_from_bytes(const Bytes& _bytes) { message += " packed bitset bytes, got "; message += std::to_string(_bytes.size()); message += "."; - return error(std::move(message)); + return error(std::move(message), ErrorKind::invalid_value); } if constexpr (N % 8 != 0) { constexpr auto mask = (1u << (8 - N % 8)) - 1; if ((static_cast(_bytes.back()) & mask) != 0) { - return error("Packed bitset padding bits must be zero."); + return error("Packed bitset padding bits must be zero.", + ErrorKind::invalid_value); } } std::bitset bits; diff --git a/include/rfl/internal/calc_flattened_size.hpp b/include/rfl/internal/calc_flattened_size.hpp new file mode 100644 index 000000000..ea0e57dca --- /dev/null +++ b/include/rfl/internal/calc_flattened_size.hpp @@ -0,0 +1,34 @@ +#ifndef RFL_INTERNAL_CALC_FLATTENED_SIZE_HPP_ +#define RFL_INTERNAL_CALC_FLATTENED_SIZE_HPP_ + +#include +#include +#include + +#include "../Tuple.hpp" +#include "is_flatten_field.hpp" +#include "ptr_tuple_t.hpp" + +namespace rfl::internal { + +/// Calculates the flattened field count of a type (recursively for +/// rfl::Flatten). +template +consteval std::size_t calc_flattened_size() { + using U = std::remove_cvref_t>; + if constexpr (is_flatten_field_v) { + using Tuple = ptr_tuple_t< + std::remove_cvref_t>>; + return [](std::index_sequence<_is...>) { + return (std::size_t{0} + ... + + calc_flattened_size< + tuple_element_t(_is), Tuple>>()); + }(std::make_index_sequence>{}); + } else { + return 1; + } +} + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/can_write_generic.hpp b/include/rfl/internal/can_write_generic.hpp new file mode 100644 index 000000000..83423f470 --- /dev/null +++ b/include/rfl/internal/can_write_generic.hpp @@ -0,0 +1,490 @@ +#ifndef RFL_INTERNAL_CAN_WRITE_GENERIC_HPP_ +#define RFL_INTERNAL_CAN_WRITE_GENERIC_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#endif + +#include "../common.hpp" +#include "../num_fields.hpp" +#include "HasValidation.hpp" +#include "StringLiteral.hpp" +#include "bind_to_tuple.hpp" +#include "has_reflection_method_v.hpp" +#include "has_reflection_type_v.hpp" +#include "has_reflector.hpp" +#include "is_basic_type.hpp" + +namespace rfl { + +enum class Copyability; + +template +struct AllOf; + +template +struct Attribute; + +template +class Box; + +template +struct Commented; + +template +struct DefaultVal; + +template +struct Deprecated; + +template +struct Description; + +template +class ExtraFields; + +template +struct Field; + +template +struct Flatten; + +class RFL_API Generic; + +template +class Literal; + +template +class NamedTuple; + +template +class Object; + +template +struct Positional; + +template +class Ref; + +template +struct Rename; + +template +struct Short; + +template +struct TaggedUnion; + +template +class Tuple; + +template + requires internal::HasValidation, T> +struct Validator; + +template +class Variant; + +namespace internal { + +template + requires std::is_array_v +struct Array; + +template +class Skip; + +/// Satisfied by a type that carries a nested `ReflectionType` and can be +/// unwrapped by decomposing it, like `rfl::Validator`. +template +concept IsReflectionTypeWrapper = + // We use `std::is_aggregate_v` and `num_fields` rather than `requires` + // because `requires`, well, requires an expression, but checking this via + // syntax would require a statement `const auto& [_] = _t`, which is not + // allowed in a `requires` clause. + has_reflection_type_v && !has_reflection_method_v && + std::is_aggregate_v && num_fields == 1; + +/// Visited type list used to break cycles in recursive types when evaluating +/// `can_write_generic`. +template +struct CanWriteVisited {}; + +template +struct is_in_visited : std::false_type {}; + +template +struct is_in_visited> + : std::bool_constant<(std::is_same_v || ...)> {}; + +template +struct add_visited; + +template +struct add_visited> { + using type = CanWriteVisited; +}; + +template +concept HasValueTypeRange = std::is_class_v && requires(const T& _t) { + typename T::value_type; + _t.begin(); + _t.end(); +}; + +template +concept HasMappedType = + std::is_class_v && requires { typename T::mapped_type; }; + +template > +struct can_write_generic_impl; + +template > +struct can_write_generic_checked { + using U = std::remove_cvref_t; + static constexpr bool value = + std::conditional_t::value, std::true_type, + can_write_generic_impl>::value; +}; + +template > +inline constexpr bool can_write_generic_v = + can_write_generic_checked::value; + +template +struct CanWriteGenericFieldsVisitor { + template + constexpr auto operator()(FieldTypes&...) const noexcept + -> std::bool_constant< + (can_write_generic_v, Visited> && + ...)> { + return {}; + } +}; + +/// Trait for whether the generic writer can serialize `T`, i.e. whether a +/// schema `default` can be produced for it. Wrappers, containers, tuples, +/// variants, and reflected aggregate structs are inspected recursively with +/// cycle protection. Types that can only be constructed from `ReflectionType` +/// (or only have a read `Reflector`) cannot be written back to `Generic`. +template +struct can_write_generic_impl { + using U = std::remove_cvref_t; + using NextVisited = typename add_visited::type; + + static consteval bool eval() { + if constexpr (std::is_void_v) { + return false; + } else if constexpr (is_basic_type_v || std::is_enum_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) { + return true; + } else if constexpr (has_read_reflector && !has_write_reflector) { + return false; + } else if constexpr (has_write_reflector) { + return can_write_generic_v::ReflType, NextVisited>; + } else if constexpr (has_reflection_type_v) { + if constexpr (has_reflection_method_v || IsReflectionTypeWrapper) { + return can_write_generic_v; + } else { + return false; + } + } else if constexpr (HasValueTypeRange) { + if constexpr (HasMappedType) { + return can_write_generic_v && + can_write_generic_v; + } else { + return can_write_generic_v; + } + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + return decltype(apply_to_fields( + std::declval(), + CanWriteGenericFieldsVisitor{}))::value; + } else { + return true; + } + } + + static constexpr bool value = eval(); +}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v, Visited>::type>> { +}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> : std::true_type {}; + +template +struct can_write_generic_impl< + Skip, Visited> + : std::bool_constant< + _skip_serialization || + can_write_generic_v< + T, typename add_visited< + Skip, + Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + typename FieldTypes::Type, + typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl : std::true_type {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl : std::true_type {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, + typename add_visited, Visited>::type>> {}; + +template +struct can_write_generic_impl + : std::bool_constant< + can_write_generic_v::type>> {}; + +template +struct can_write_generic_impl + : std::bool_constant< + can_write_generic_v::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v< + T1, typename add_visited, Visited>::type> && + can_write_generic_v< + T2, typename add_visited, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, + Visited>::type> && + ...)> {}; + +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v< + T, typename add_visited, Visited>::type> && + can_write_generic_v< + E, typename add_visited, Visited>::type>> {}; +#endif + +template +struct can_write_generic : std::bool_constant> {}; + +/// Satisfied when the generic writer can serialize `T`, i.e. whether a schema +/// `default` can be produced for it. Every type is writable, except those that +/// can be constructed from `ReflectionType`, but not converted back to it. +template +concept CanWriteGeneric = can_write_generic>::value; + +template +struct is_transparent_default_wrapper : std::false_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type { +}; + +template +struct is_transparent_default_wrapper> + : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +/// Unwraps metadata/CLI wrappers before serializing a field's default value to +/// `rfl::Generic` so `to_generic` is only instantiated on the underlying value +/// type (never per-field `Description, T>`). +template +constexpr const auto& unwrap_default_value(const T& _val) noexcept { + using U = std::remove_cvref_t; + if constexpr (is_transparent_default_wrapper::value) { + return unwrap_default_value(_val.value()); + } else { + return _val; + } +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_INTERNAL_CAN_WRITE_GENERIC_HPP_ diff --git a/include/rfl/internal/concat_literals.hpp b/include/rfl/internal/concat_literals.hpp index 8f1cbbe2a..ed90dedd5 100644 --- a/include/rfl/internal/concat_literals.hpp +++ b/include/rfl/internal/concat_literals.hpp @@ -1,44 +1,102 @@ #ifndef RFL_INTERNAL_CONCATLITERALS_HPP_ #define RFL_INTERNAL_CONCATLITERALS_HPP_ +#include +#include +#include + #include "../Literal.hpp" #include "StringLiteral.hpp" namespace rfl::internal { -// We don't want the operator+ to apply to normal literals, -// so we introduce this wrapper. -template -struct LiteralWrapper { - Literal<_names...> literal_; +struct ConcatLiteralIndex { + std::size_t outer; + std::size_t inner; }; -template -consteval auto wrap_literal(const Literal<_names...>& _literal) { - return LiteralWrapper<_names...>{_literal}; +template +consteval auto calc_concat_literal_indices() { + constexpr std::size_t total = (std::size_t{0} + ... + _sizes); + std::array indices{}; + constexpr std::array sizes{_sizes...}; + std::size_t pos = 0; + for (std::size_t outer = 0; outer < sizeof...(_sizes); ++outer) { + for (std::size_t inner = 0; inner < sizes[outer]; ++inner) { + indices[pos++] = ConcatLiteralIndex{outer, inner}; + } + } + return indices; } -template -consteval auto operator+(const LiteralWrapper<_names1...>&, - const LiteralWrapper<_names2...>&) { - return LiteralWrapper<_names1..., _names2...>{ - rfl::Literal<_names1..., _names2...>()}; +template +struct IndexedLiteralType {}; + +template +T get_indexed_literal_type(IndexedLiteralType<_i, T>); + +template +struct LiteralTypeTable; + +template +struct LiteralTypeTable, Ts...> + : IndexedLiteralType<_is, Ts>... {}; + +template +struct LiteralToTable; + +template +struct LiteralToTable> { + using Table = + LiteralTypeTable, + rfl::LiteralHelper<_names>...>; +}; + +template +consteval auto concat_literals_impl(std::index_sequence<_sizes...>, + std::index_sequence<_ks...>) { + constexpr auto indices = calc_concat_literal_indices<_sizes...>(); + return rfl::Literal( + rfl::internal::get_indexed_literal_type( + std::declval())))::name_...>(); } -template -consteval auto concat_literals(const Head& _head, const Tail&... _tail) { - return (wrap_literal(_head) + ... + wrap_literal(_tail)).literal_; +// Special case - no literals. +consteval inline auto concat_literals() { return rfl::Literal<>(); } + +// Special case - single literal. +template +consteval auto concat_literals(const rfl::Literal<_names...>&) { + return rfl::Literal<_names...>(); } // Special case - every literal contains exactly one value. -template +template consteval auto concat_literals(const rfl::Literal<_head>&, + const rfl::Literal<_second>&, const rfl::Literal<_tail>&...) { - return rfl::Literal<_head, _tail...>(); + return rfl::Literal<_head, _second, _tail...>(); } -// Special case - no literals. -consteval inline auto concat_literals() { return rfl::Literal<>(); } +// General case - arbitrary mix of empty, single, and multi-value literals. +template +consteval auto concat_literals(const Head&, const Second&, const Tail&...) { + constexpr std::size_t total = + Head::size() + Second::size() + (std::size_t{0} + ... + Tail::size()); + if constexpr (total == 0) { + return rfl::Literal<>(); + } else { + using OuterTable = LiteralTypeTable< + std::make_index_sequence<2 + sizeof...(Tail)>, + typename LiteralToTable::Table, + typename LiteralToTable::Table, + typename LiteralToTable::Table...>; + return concat_literals_impl( + std::index_sequence{}, + std::make_index_sequence{}); + } +} } // namespace rfl::internal 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/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/get_field_names.hpp b/include/rfl/internal/cpp20/get_field_names.hpp index 707a0590a..e447dc42b 100644 --- a/include/rfl/internal/cpp20/get_field_names.hpp +++ b/include/rfl/internal/cpp20/get_field_names.hpp @@ -3,6 +3,7 @@ #ifndef REFLECTCPP_USE_CPP26_REFLECTION +#include #include #include @@ -12,6 +13,7 @@ #include "../../Literal.hpp" #include "../concat_literals.hpp" +#include "../is_alias.hpp" #include "../is_flatten_field.hpp" #include "../is_rename.hpp" #include "get_ith_field_from_fake_object.hpp" @@ -88,8 +90,9 @@ consteval auto get_field_name() { #else using Type = std::remove_cvref_t>; #endif - if constexpr (is_rename_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v) { + using Name = typename UnwrappedType::Name; return Name(); } else if constexpr (is_flatten_field_v) { return get_field_names>(); @@ -104,6 +107,24 @@ consteval auto get_field_name() { #pragma clang diagnostic ignored "-Wundefined-inline" #endif +template +#if __GNUC__ +#ifndef __clang__ +[[gnu::no_sanitize_undefined]] +#endif +#endif +consteval auto extract_field_names(std::index_sequence<_is...>) { + constexpr auto ptrs = get_field_ptrs_from_fake_object(); +#if defined(__clang__) + return concat_literals( + get_field_name(ptrs))>()...); +#else + return concat_literals( + get_field_name(ptrs)>()...); +#endif +} + template #if __GNUC__ #ifndef __clang__ @@ -113,21 +134,12 @@ template consteval auto get_field_names() { using Type = std::remove_cvref_t; if constexpr (std::is_pointer_v) { - return get_field_names>(); + return get_field_names>(); + } else if constexpr (num_fields == 0) { + return rfl::Literal<>(); } else { -#if defined(__clang__) - const auto get = [](std::index_sequence<_is...>) { - return concat_literals( - get_field_name())>()...); - }; -#else - const auto get = [](std::index_sequence<_is...>) { - return concat_literals( - get_field_name()>()...); - }; -#endif - return get(std::make_index_sequence>()); + return extract_field_names( + std::make_index_sequence>()); } } diff --git a/include/rfl/internal/cpp20/get_ith_field_from_fake_object.hpp b/include/rfl/internal/cpp20/get_ith_field_from_fake_object.hpp index d29949677..4062dfad4 100644 --- a/include/rfl/internal/cpp20/get_ith_field_from_fake_object.hpp +++ b/include/rfl/internal/cpp20/get_ith_field_from_fake_object.hpp @@ -5,18 +5,40 @@ #include #include +#include #include "../../always_false.hpp" -#include "../nth_element.hpp" #include "get_fake_object.hpp" #include "num_fields.hpp" namespace rfl::internal::cpp20 { +template +struct IndexedFieldPtr { + Ptr ptr_; +}; + +template +struct FieldPtrPack; + +template +struct FieldPtrPack, Ptrs...> + : IndexedFieldPtr<_is, Ptrs>... {}; + +template +constexpr auto make_field_ptr_pack_from_refs(Refs&... _refs) noexcept { + return FieldPtrPack, Refs*...>{{&_refs}...}; +} + +template +constexpr Ptr select_field_ptr(const IndexedFieldPtr<_i, Ptr>& _p) noexcept { + return _p.ptr_; +} + template struct field_extractor { - template - static consteval auto get_ptr(U&) { + template + static consteval auto get_ptrs(U&) { static_assert( rfl::always_false_v, "\n\nThis error occurs for one of two reasons:\n\n" @@ -30,19 +52,30 @@ struct field_extractor { "classes or custom parsers in the documentation " "for solutions to this problem.\n\n"); } + + template + static consteval auto get_ptr(U& _obj) { + return get_ptrs(_obj); + } }; #define RFL_INTERNAL_FAKE_OBJECT_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS( \ n, ...) \ template \ struct field_extractor { \ + template \ + static consteval auto get_ptrs(U& _obj) { \ + auto& [__VA_ARGS__] = _obj; \ + return rfl::internal::cpp20::make_field_ptr_pack_from_refs(__VA_ARGS__); \ + } \ template \ static consteval auto get_ptr(U& _obj) { \ - auto& [__VA_ARGS__] = _obj; \ - const auto get_ptrs = [](auto&... _refs) { \ - return nth_element<_i>(&_refs...); \ - }; \ - return get_ptrs(__VA_ARGS__); \ + static_assert(_i >= 0, "N out of bounds."); \ + static_assert(static_cast(_i) < n, "N out of bounds."); \ + if constexpr (_i >= 0 && static_cast(_i) < n) { \ + return rfl::internal::cpp20::select_field_ptr< \ + static_cast(_i)>(get_ptrs(_obj)); \ + } \ } \ } @@ -2817,6 +2850,17 @@ RFL_INTERNAL_FAKE_OBJECT_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS( #undef RFL_INTERNAL_FAKE_OBJECT_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS +template +consteval auto get_field_ptrs(U& _obj) { + return field_extractor>::get_ptrs(_obj); +} + +template +consteval auto get_field_ptrs_from_fake_object() { + using Type = std::remove_cvref_t; + return get_field_ptrs(get_fake_object()); +} + template consteval auto get_ith_field_ptr(U& _obj) { return field_extractor>::template get_ptr<_i>(_obj); diff --git a/include/rfl/internal/cpp20/get_member_ptr_name.hpp b/include/rfl/internal/cpp20/get_member_ptr_name.hpp index 37e3a81da..d8c1b5ac9 100644 --- a/include/rfl/internal/cpp20/get_member_ptr_name.hpp +++ b/include/rfl/internal/cpp20/get_member_ptr_name.hpp @@ -5,6 +5,7 @@ #include #include "../StringLiteral.hpp" +#include "../is_alias.hpp" #include "../is_field.hpp" #include "../is_rename.hpp" #include "../lit_name.hpp" @@ -66,8 +67,9 @@ using ptr_type_t = member_type_helper::ptr_type; template consteval auto get_member_ptr_name() { using Type = ptr_type_t; - if constexpr (is_rename_v || is_field_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v || is_field_v) { + using Name = typename UnwrappedType::Name; return lit_name_v; } else { using StructType = struct_type_t; 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/cpp26/get_field_names.hpp b/include/rfl/internal/cpp26/get_field_names.hpp index 07d872f84..e82993589 100644 --- a/include/rfl/internal/cpp26/get_field_names.hpp +++ b/include/rfl/internal/cpp26/get_field_names.hpp @@ -13,6 +13,7 @@ #include "../../Tuple.hpp" #include "../StringLiteral.hpp" #include "../concat_literals.hpp" +#include "../is_alias.hpp" #include "../is_flatten_field.hpp" #include "../is_rename.hpp" #include "bind_to_tuple.hpp" @@ -26,8 +27,9 @@ consteval auto get_field_names(); template consteval auto get_field_names_impl() { using Type = std::remove_cvref_t>; - if constexpr (is_rename_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v) { + using Name = typename UnwrappedType::Name; return Name(); } else if constexpr (is_flatten_field_v) { return get_field_names>(); diff --git a/include/rfl/internal/default_if_null_v.hpp b/include/rfl/internal/default_if_null_v.hpp new file mode 100644 index 000000000..444f61233 --- /dev/null +++ b/include/rfl/internal/default_if_null_v.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_INTERNAL_DEFAULTIFNULL_HPP_ +#define RFL_INTERNAL_DEFAULTIFNULL_HPP_ + +#include + +#include "../DefaultIfNull.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +class default_if_null; + +template +class default_if_null : public std::false_type {}; + +template <> +class default_if_null : public std::true_type {}; + +template +struct default_if_null> { + static constexpr bool value = + (default_if_null::value || ... || default_if_null::value); +}; + +template +constexpr bool default_if_null_v = + default_if_null>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/default_tag.hpp b/include/rfl/internal/default_tag.hpp new file mode 100644 index 000000000..741488e53 --- /dev/null +++ b/include/rfl/internal/default_tag.hpp @@ -0,0 +1,65 @@ +#ifndef RFL_INTERNAL_DEFAULT_TAG_HPP_ +#define RFL_INTERNAL_DEFAULT_TAG_HPP_ + +#include +#include + +#include "../DefaultTag.hpp" +#include "../Processors.hpp" +#include "StringLiteral.hpp" + +namespace rfl::internal { + +template +struct default_tag_info { + static constexpr std::size_t count = 0; +}; + +template +struct default_tag_info, + _discriminator> { + static constexpr std::size_t count = 1; + + static consteval auto get_value() noexcept { return _default_tag; } +}; + +template +struct default_tag_info, _discriminator> { + static constexpr std::size_t count = 0; +}; + +template +struct default_tag_info, _discriminator> { + private: + using HeadInfo = default_tag_info, _discriminator>; + using TailInfo = default_tag_info, _discriminator>; + + public: + static constexpr std::size_t count = HeadInfo::count + TailInfo::count; + + static consteval auto get_value() noexcept { + if constexpr (HeadInfo::count > 0) { + return HeadInfo::get_value(); + } else { + return TailInfo::get_value(); + } + } +}; + +template +inline constexpr std::size_t default_tag_count_v = + default_tag_info, + _discriminator>::count; + +template +inline constexpr bool has_default_tag_v = + default_tag_count_v > 0; + +template +inline constexpr auto default_tag_literal_v = + default_tag_info, + _discriminator>::get_value(); + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/define_literal.hpp b/include/rfl/internal/define_literal.hpp index e97eb3c38..ff109744f 100644 --- a/include/rfl/internal/define_literal.hpp +++ b/include/rfl/internal/define_literal.hpp @@ -1,26 +1,91 @@ #ifndef RFL_INTERNAL_DEFINELITERAL_HPP_ #define RFL_INTERNAL_DEFINELITERAL_HPP_ +#include + #include "../Literal.hpp" +#include "IndexedTypeMap.hpp" +#include "StringLiteral.hpp" namespace rfl { namespace internal { +template +struct to_literal_unit; + +template +struct to_literal_unit> { + using type = Literal<_names...>; +}; + +template +struct concat_literal_types; + +template +struct concat_literal_types, Literal<_c2...>> { + using type = Literal<_c1..., _c2...>; +}; + +template +struct concat_literal_types, Literal<_c2...>, Literal<_c3...>> { + using type = Literal<_c1..., _c2..., _c3...>; +}; + +template +struct concat_literal_types, Literal<_c2...>, Literal<_c3...>, + Literal<_c4...>> { + using type = Literal<_c1..., _c2..., _c3..., _c4...>; +}; + +template +struct merge_literal_units { + static constexpr std::size_t q1 = Count / 4; + static constexpr std::size_t q2 = Count / 2; + static constexpr std::size_t q3 = (3 * Count) / 4; + using type = typename concat_literal_types< + typename merge_literal_units::type, + typename merge_literal_units::type, + typename merge_literal_units::type, + typename merge_literal_units::type>::type; +}; + +template +struct merge_literal_units { + using type = Literal<>; +}; + +template +struct merge_literal_units { + using type = typename to_literal_unit>::type; +}; + +template +struct merge_literal_units { + using type = typename concat_literal_types< + typename to_literal_unit>::type, + typename to_literal_unit>::type>::type; +}; + +template +struct merge_literal_units { + using type = typename concat_literal_types< + typename to_literal_unit>::type, + typename to_literal_unit>::type, + typename to_literal_unit>::type>::type; +}; + /// Allows you to combine several literals. template -struct define_literal; - -/// General case -template -struct define_literal, Literal<_content2...>, Tail...> { - using type = typename define_literal, - Tail...>::type; +struct define_literal { + using type = typename merge_literal_units, 0, + sizeof...(LiteralTypes)>::type; }; -/// Special case - only a single literal is left -template -struct define_literal> { - using type = Literal<_content...>; +/// Fast path when every input is a single-name Literal (including 0 inputs). +template +struct define_literal...> { + using type = Literal<_names...>; }; } // namespace internal diff --git a/include/rfl/internal/define_named_tuple.hpp b/include/rfl/internal/define_named_tuple.hpp index ba71091fb..b04e359dd 100644 --- a/include/rfl/internal/define_named_tuple.hpp +++ b/include/rfl/internal/define_named_tuple.hpp @@ -1,43 +1,115 @@ #ifndef RFL_INTERNAL_DEFINENAMEDTUPLE_HPP_ #define RFL_INTERNAL_DEFINENAMEDTUPLE_HPP_ +#include + #include "../NamedTuple.hpp" +#include "IndexedTypeMap.hpp" +#include "is_named_tuple.hpp" namespace rfl { namespace internal { -template -struct define_named_tuple; +template +struct concat_defined_named_tuples; -/// Allows you to combine several named tuples and/or additional fields. -/// Recursive case - all types are fields. -template -struct define_named_tuple { - using type = typename define_named_tuple, Tail...>::type; +template +struct concat_defined_named_tuples, NamedTuple> { + using type = NamedTuple; }; -/// Allows you to combine several named tuples and/or additional fields. -/// Recursive case - first type is NamedTuple, second type is field. -template -struct define_named_tuple, Head, Tail...> { - using type = typename define_named_tuple, - Tail...>::type; +template +struct concat_defined_named_tuples, NamedTuple, + NamedTuple> { + using type = NamedTuple; }; -/// Allows you to combine several named tuples and/or additional fields. -/// Recursive case - first type is NamedTuple, second type is also NamedTuple. -template -struct define_named_tuple, NamedTuple, - Tail...> { - using type = - typename define_named_tuple, - Tail...>::type; +template +struct concat_defined_named_tuples, NamedTuple, + NamedTuple, NamedTuple> { + using type = NamedTuple; +}; + +template +struct to_defined_named_tuple_unit { + using type = NamedTuple; +}; + +template +struct to_defined_named_tuple_unit> { + using type = NamedTuple; +}; + +template +struct merge_defined_named_tuple_units { + static constexpr std::size_t q1 = Count / 4; + static constexpr std::size_t q2 = Count / 2; + static constexpr std::size_t q3 = (3 * Count) / 4; + using type = typename concat_defined_named_tuples< + typename merge_defined_named_tuple_units::type, + typename merge_defined_named_tuple_units::type, + typename merge_defined_named_tuple_units::type, + typename merge_defined_named_tuple_units::type>::type; +}; + +template +struct merge_defined_named_tuple_units { + using type = NamedTuple<>; +}; + +template +struct merge_defined_named_tuple_units { + using type = + typename to_defined_named_tuple_unit>::type; +}; + +template +struct merge_defined_named_tuple_units { + using type = typename concat_defined_named_tuples< + typename to_defined_named_tuple_unit>::type, + typename to_defined_named_tuple_unit< + indexed_type_at_t>::type>::type; +}; + +template +struct merge_defined_named_tuple_units { + using type = typename concat_defined_named_tuples< + typename to_defined_named_tuple_unit>::type, + typename to_defined_named_tuple_unit< + indexed_type_at_t>::type, + typename to_defined_named_tuple_unit< + indexed_type_at_t>::type>::type; +}; + +template +struct define_named_tuple_dispatch { + using type = typename merge_defined_named_tuple_units, + 0, sizeof...(Ts)>::type; +}; + +template +struct define_named_tuple_dispatch { + using type = NamedTuple; +}; + +template +struct define_named_tuple_dispatch { + using type = typename to_defined_named_tuple_unit::type; +}; + +template +struct define_named_tuple_dispatch { + using type = typename concat_defined_named_tuples< + typename to_defined_named_tuple_unit::type, + typename to_defined_named_tuple_unit::type>::type; }; /// Allows you to combine several named tuples and/or additional fields. -template -struct define_named_tuple> { - using type = NamedTuple; +template +struct define_named_tuple { + using type = typename define_named_tuple_dispatch< + (!is_named_tuple::value && ...), FieldTypes...>::type; }; } // namespace internal diff --git a/include/rfl/internal/define_tagged_union.hpp b/include/rfl/internal/define_tagged_union.hpp index a780148c1..933a53561 100644 --- a/include/rfl/internal/define_tagged_union.hpp +++ b/include/rfl/internal/define_tagged_union.hpp @@ -1,54 +1,142 @@ #ifndef RFL_INTERNAL_DEFINETAGGEDUNION_HPP_ #define RFL_INTERNAL_DEFINETAGGEDUNION_HPP_ +#include +#include + +#include "../NamedTuple.hpp" #include "../TaggedUnion.hpp" +#include "IndexedTypeMap.hpp" #include "StringLiteral.hpp" +#include "is_named_tuple.hpp" namespace rfl { namespace internal { +template +struct to_tagged_union_unit; + +template +struct to_tagged_union_unit<_discriminator, + TaggedUnion<_discriminator, Ts...>> { + using type = TaggedUnion<_discriminator, Ts...>; +}; + +template +struct to_tagged_union_unit<_discriminator, NamedTuple> { + using type = TaggedUnion<_discriminator, NamedTuple>; +}; + +template +struct concat_tagged_union_types; + +template +struct concat_tagged_union_types<_discriminator, + TaggedUnion<_discriminator, Ts1...>, + TaggedUnion<_discriminator, Ts2...>> { + using type = TaggedUnion<_discriminator, Ts1..., Ts2...>; +}; + +template +struct concat_tagged_union_types<_discriminator, + TaggedUnion<_discriminator, Ts1...>, + TaggedUnion<_discriminator, Ts2...>, + TaggedUnion<_discriminator, Ts3...>> { + using type = TaggedUnion<_discriminator, Ts1..., Ts2..., Ts3...>; +}; + +template +struct concat_tagged_union_types<_discriminator, + TaggedUnion<_discriminator, Ts1...>, + TaggedUnion<_discriminator, Ts2...>, + TaggedUnion<_discriminator, Ts3...>, + TaggedUnion<_discriminator, Ts4...>> { + using type = TaggedUnion<_discriminator, Ts1..., Ts2..., Ts3..., Ts4...>; +}; + +template +struct merge_tagged_union_units { + static constexpr std::size_t q1 = Count / 4; + static constexpr std::size_t q2 = Count / 2; + static constexpr std::size_t q3 = (3 * Count) / 4; + using type = typename concat_tagged_union_types< + _discriminator, + typename merge_tagged_union_units<_discriminator, Map, Begin, q1>::type, + typename merge_tagged_union_units<_discriminator, Map, Begin + q1, + q2 - q1>::type, + typename merge_tagged_union_units<_discriminator, Map, Begin + q2, + q3 - q2>::type, + typename merge_tagged_union_units<_discriminator, Map, Begin + q3, + Count - q3>::type>::type; +}; + +template +struct merge_tagged_union_units<_discriminator, Map, Begin, 1> { + using type = typename to_tagged_union_unit< + _discriminator, indexed_type_at_t>::type; +}; + +template +struct merge_tagged_union_units<_discriminator, Map, Begin, 2> { + using type = typename concat_tagged_union_types< + _discriminator, + typename to_tagged_union_unit<_discriminator, + indexed_type_at_t>::type, + typename to_tagged_union_unit<_discriminator, + indexed_type_at_t>::type>:: + type; +}; + +template +struct merge_tagged_union_units<_discriminator, Map, Begin, 3> { + using type = typename concat_tagged_union_types< + _discriminator, + typename to_tagged_union_unit<_discriminator, + indexed_type_at_t>::type, + typename to_tagged_union_unit<_discriminator, + indexed_type_at_t>::type, + typename to_tagged_union_unit<_discriminator, + indexed_type_at_t>::type>:: + type; +}; + +template +struct define_tagged_union_dispatch { + using type = typename merge_tagged_union_units<_discriminator, + IndexedTypeMap, 0, + sizeof...(Ts)>::type; +}; + +template +struct define_tagged_union_dispatch<_discriminator, true, Ts...> { + using type = TaggedUnion<_discriminator, Ts...>; +}; + +template +struct define_tagged_union_dispatch<_discriminator, false, T0> { + using type = typename to_tagged_union_unit<_discriminator, T0>::type; +}; + +template +struct define_tagged_union_dispatch<_discriminator, false, T0, T1> { + using type = typename concat_tagged_union_types< + _discriminator, typename to_tagged_union_unit<_discriminator, T0>::type, + typename to_tagged_union_unit<_discriminator, T1>::type>::type; +}; + /// Allows you to combine several tagged unions. template struct define_tagged_union; -/// Recursive case - both tagged union. -template -struct define_tagged_union< - _discriminator, TaggedUnion<_discriminator, NamedTupleTypes1...>, - TaggedUnion<_discriminator, NamedTupleTypes2...>, Tail...> { - using type = typename define_tagged_union< - _discriminator, - TaggedUnion<_discriminator, NamedTupleTypes1..., NamedTupleTypes2...>, - Tail...>::type; -}; - -/// Recursive case - tagged union plus named tuple. -template -struct define_tagged_union<_discriminator, - TaggedUnion<_discriminator, NamedTupleTypes...>, - NamedTuple, Tail...> { - using type = typename define_tagged_union< - _discriminator, - TaggedUnion<_discriminator, NamedTupleTypes..., - NamedTuple>, - Tail...>::type; -}; - -/// Recursive case - named tuple. -template -struct define_tagged_union<_discriminator, NamedTuple, Tail...> { - using type = typename define_tagged_union< - _discriminator, TaggedUnion<_discriminator, NamedTuple>, - Tail...>::type; -}; - -/// Special case - only a single TaggedUnion is left. -template -struct define_tagged_union<_discriminator, - TaggedUnion<_discriminator, NamedTupleTypes...>> { - using type = TaggedUnion<_discriminator, NamedTupleTypes...>; +template +struct define_tagged_union<_discriminator, Head, Tail...> { + using type = typename define_tagged_union_dispatch< + _discriminator, + (is_named_tuple::value && ... && is_named_tuple::value), Head, + Tail...>::type; }; } // namespace internal diff --git a/include/rfl/internal/define_variant.hpp b/include/rfl/internal/define_variant.hpp index 3c09ebf81..7b0bd9c98 100644 --- a/include/rfl/internal/define_variant.hpp +++ b/include/rfl/internal/define_variant.hpp @@ -1,39 +1,118 @@ #ifndef RFL_INTERNAL_DEFINEVARIANT_HPP_ #define RFL_INTERNAL_DEFINEVARIANT_HPP_ +#include +#include #include +#include "IndexedTypeMap.hpp" + namespace rfl { namespace internal { -/// Allows you to combine several variants. -template -struct define_variant; +template +struct is_std_variant_exact : std::false_type {}; + +template +struct is_std_variant_exact> : std::true_type {}; -/// Recursive case - both variants. -template -struct define_variant, std::variant, Tail...> { - using type = typename define_variant, - Tail...>::type; +template +inline constexpr bool is_std_variant_exact_v = is_std_variant_exact::value; + +template +struct to_variant_unit { + using type = std::variant; }; -/// Recursive case - variant plus other type. -template -struct define_variant, Head, Tail...> { - using type = - typename define_variant, Tail...>::type; +template +struct to_variant_unit> { + using type = std::variant; }; -/// Recursive case - other type. -template -struct define_variant { - using type = typename define_variant, Tail...>::type; +template +struct concat_variant_types; + +template +struct concat_variant_types, std::variant> { + using type = std::variant; +}; + +template +struct concat_variant_types, std::variant, + std::variant> { + using type = std::variant; +}; + +template +struct concat_variant_types, std::variant, + std::variant, std::variant> { + using type = std::variant; +}; + +template +struct merge_variant_units { + static constexpr std::size_t q1 = Count / 4; + static constexpr std::size_t q2 = Count / 2; + static constexpr std::size_t q3 = (3 * Count) / 4; + using type = typename concat_variant_types< + typename merge_variant_units::type, + typename merge_variant_units::type, + typename merge_variant_units::type, + typename merge_variant_units::type>::type; +}; + +template +struct merge_variant_units { + using type = typename to_variant_unit>::type; +}; + +template +struct merge_variant_units { + using type = typename concat_variant_types< + typename to_variant_unit>::type, + typename to_variant_unit>::type>::type; +}; + +template +struct merge_variant_units { + using type = typename concat_variant_types< + typename to_variant_unit>::type, + typename to_variant_unit>::type, + typename to_variant_unit>::type>::type; +}; + +template +struct define_variant_dispatch { + using type = typename merge_variant_units, 0, + sizeof...(Vars)>::type; }; -/// Special case - only a single variant is left. template -struct define_variant> { - using type = std::variant; +struct define_variant_dispatch { + using type = std::variant; +}; + +template +struct define_variant_dispatch { + using type = typename to_variant_unit::type; +}; + +template +struct define_variant_dispatch { + using type = typename concat_variant_types< + typename to_variant_unit::type, + typename to_variant_unit::type>::type; +}; + +/// Allows you to combine several variants. +template +struct define_variant; + +template +struct define_variant { + using type = typename define_variant_dispatch< + (!is_std_variant_exact_v && ... && !is_std_variant_exact_v), + Head, Tail...>::type; }; } // namespace internal diff --git a/include/rfl/internal/element_index.hpp b/include/rfl/internal/element_index.hpp index 09085a7bc..45db26ebf 100644 --- a/include/rfl/internal/element_index.hpp +++ b/include/rfl/internal/element_index.hpp @@ -1,38 +1,31 @@ #ifndef RFL_INTERNAL_ELEMENT_INDEX_HPP_ #define RFL_INTERNAL_ELEMENT_INDEX_HPP_ +#include +#include #include -#include namespace rfl::internal { -template -struct ElementIndexWrapper { - static constexpr int index = _i; - - consteval auto operator||(auto other) const { - if constexpr (std::is_same_v) { - return *this; - } else { - return other; - } - } -}; - /** * Finds the index of the first type T in the list of AlternativeTypes. * If T is not found, returns -1. */ template consteval int element_index() { - return [](std::integer_sequence) { - return ((ElementIndexWrapper, - std::remove_cvref_t, - _is>{} || - ...) || - ElementIndexWrapper{}) - .index; - }(std::make_integer_sequence()); + if constexpr (sizeof...(AlternativeTypes) == 0) { + return -1; + } else { + using Target = std::remove_cvref_t; + constexpr std::array matches{ + std::is_same_v>...}; + for (std::size_t i = 0; i < matches.size(); ++i) { + if (matches[i]) { + return static_cast(i); + } + } + return -1; + } } } // namespace rfl::internal 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/field_aliases.hpp b/include/rfl/internal/field_aliases.hpp new file mode 100644 index 000000000..a95601ec7 --- /dev/null +++ b/include/rfl/internal/field_aliases.hpp @@ -0,0 +1,220 @@ +#ifndef RFL_INTERNAL_FIELD_ALIASES_HPP_ +#define RFL_INTERNAL_FIELD_ALIASES_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +#include "../Tuple.hpp" +#include "StringLiteral.hpp" + +namespace rfl { + +enum class Copyability; + +template +struct Alias; + +template +struct Rename; + +template +struct Description; + +template +struct Deprecated; + +template +struct DefaultVal; + +template +struct Short; + +template +struct Positional; + +template +struct Attribute; + +template +struct Commented; + +template +class Box; + +template +class Ref; + +template +class Nullable; + +template +class TriState; + +namespace internal { + +template +class Skip; + +/// Compile-time list of read-only alias names declared on a field. +template +struct AliasList { + static constexpr size_t size = sizeof...(_names); + + static constexpr std::array + to_array() noexcept { + return {_names.string_view()...}; + } + + static constexpr bool contains(std::string_view _name) noexcept { + return ((_name == _names.string_view()) || ...); + } +}; + +template +struct prepend_alias; + +template +struct prepend_alias<_head, AliasList<_tail...>> { + using type = AliasList<_head, _tail...>; +}; + +/// Collects all rfl::Alias names declared on a field type, unwrapping through +/// transparent field wrappers (Alias, Rename, Description, Deprecated, +/// DefaultVal, Short, Positional, std::optional, Nullable, TriState, Skip, +/// Attribute, Commented, Validator, Box, Ref, std::unique_ptr, std::shared_ptr, +/// and raw pointers). +template +struct field_aliases_impl { + using type = AliasList<>; +}; + +template +using field_aliases_t = typename field_aliases_impl< + std::remove_cvref_t>>::type; + +template +struct field_aliases_impl { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = typename prepend_alias<_name, field_aliases_t>::type; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template + requires requires { + typename T::ReflectionType; + typename T::ValidationType; + } +struct field_aliases_impl { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +/// Returns the total number of rfl::Alias names declared across all fields. +template +consteval size_t total_field_aliases() { + constexpr size_t N = rfl::tuple_size_v; + return [](std::index_sequence) { + return (size_t{0} + ... + + field_aliases_t>::Type>::size); + }(std::make_index_sequence()); +} + +/// Returns true if any field in Fields declares at least one rfl::Alias. +template +consteval bool has_any_aliases() { + return total_field_aliases() > 0; +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_INTERNAL_FIELD_ALIASES_HPP_ diff --git a/include/rfl/internal/find_index.hpp b/include/rfl/internal/find_index.hpp index c962ae5e6..9cc9f88e1 100644 --- a/include/rfl/internal/find_index.hpp +++ b/include/rfl/internal/find_index.hpp @@ -1,65 +1,59 @@ #ifndef RFL_FIND_INDEX_HPP_ #define RFL_FIND_INDEX_HPP_ +#include +#include +#include +#include +#include + #include "../Tuple.hpp" #include "StringLiteral.hpp" namespace rfl { namespace internal { -template -struct FieldWrapper { - constexpr static int i_ = _i; -}; +template +struct FindIndexImpl; -template -constexpr auto operator|(const FieldWrapper& _f1, - const FieldWrapper& _f2) { - if constexpr (F1::name_ == _field_name) { - return _f1; - } else { - return _f2; +template +struct FindIndexImpl> { + static consteval int find(const std::string_view _target) noexcept { + if constexpr (sizeof...(FieldTypes) == 0) { + return -1; + } else { + constexpr std::array names{ + std::remove_cvref_t::name_.string_view()...}; + for (std::size_t i = 0; i < names.size(); ++i) { + if (names[i] == _target) { + return static_cast(i); + } + } + return -1; + } } -} +}; -template -constexpr auto find_matching_field(const Head& _head, const Tail&... _tail) { - return (_head | ... | _tail); -} +template +struct FindIndexImpl> + : FindIndexImpl> {}; -template -constexpr auto wrap_fields(std::integer_sequence) { - return find_matching_field(FieldWrapper, - _field_name, _is>{}...) - .i_; +/// Finds the index of the field signified by _field_name or -1. +template +constexpr int find_index_or_minus_one() { + constexpr int ix = FindIndexImpl>::find( + _field_name.string_view()); + return ix; } /// Finds the index of the field signified by _field_name template constexpr int find_index() { - constexpr int ix = wrap_fields<_field_name, Fields>( - std::make_integer_sequence>()); - static_assert(rfl::tuple_element_t::name_ == _field_name, - "No matching field found."); + constexpr int ix = find_index_or_minus_one<_field_name, Fields>(); + static_assert(ix != -1, "No matching field found."); return ix; } -/// Finds the index of the field signified by _field_name or -1. -template -constexpr int find_index_or_minus_one() { - if constexpr (rfl::tuple_size_v == 0) { - return -1; - } else { - constexpr int ix = wrap_fields<_field_name, Fields>( - std::make_integer_sequence>()); - if constexpr (rfl::tuple_element_t::name_ == _field_name) { - return ix; - } else { - return -1; - } - } -} - } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/has_arrays.hpp b/include/rfl/internal/has_arrays.hpp index 896692059..58e61862d 100644 --- a/include/rfl/internal/has_arrays.hpp +++ b/include/rfl/internal/has_arrays.hpp @@ -1,26 +1,30 @@ #ifndef RFL_INTERNAL_HASARRAYS_HPP_ #define RFL_INTERNAL_HASARRAYS_HPP_ +#include #include -#include #include "../Tuple.hpp" #include "is_array.hpp" namespace rfl::internal { +template +struct HasArrays; + +template +struct HasArrays> + : std::bool_constant<(false || ... || + is_array_v>)> {}; + +template +struct HasArrays> + : std::bool_constant<(false || ... || + is_array_v>)> {}; + template constexpr bool has_arrays() { - const auto is_true_for_one = - [](std::integral_constant) -> bool { - using T = std::remove_cvref_t>; - return is_array_v; - }; - - return [&](std::integer_sequence) { - return (false || ... || - is_true_for_one(std::integral_constant{})); - }(std::make_integer_sequence>()); + return HasArrays>::value; } } // namespace rfl::internal 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/has_fields.hpp b/include/rfl/internal/has_fields.hpp index 412b87b09..5d5f43684 100644 --- a/include/rfl/internal/has_fields.hpp +++ b/include/rfl/internal/has_fields.hpp @@ -1,68 +1,116 @@ #ifndef RFL_INTERNAL_HASFIELDS_HPP_ #define RFL_INTERNAL_HASFIELDS_HPP_ +#include #include #include -#include "../Tuple.hpp" -//#include "all_fields.hpp" +#include "bind_to_tuple.hpp" #include "is_field.hpp" #include "is_flatten_field.hpp" -#include "ptr_tuple_t.hpp" #include "is_named_tuple.hpp" - namespace rfl { namespace internal { -template -constexpr bool all_fields_or_flatten() { - const auto is_true_for_one = - [](std::integral_constant) -> bool { - using T = std::remove_cvref_t>; - if constexpr (is_flatten_field_v) { - return all_fields_or_flatten< - ptr_tuple_t::Type>>(); - } else { - return is_field_v; - } - }; +struct FieldAnnotationFlags { + bool some; + bool all; +}; + +template +struct FieldAnnotationResult { + static constexpr bool some = _some; + static constexpr bool all = _all; +}; + +template +struct HasFieldsDeref { + using Type = std::remove_cvref_t; +}; + +template +struct HasFieldsDeref : HasFieldsDeref> {}; - return [&](std::integer_sequence) { - return (true && ... && is_true_for_one(std::integral_constant{})); +template +struct HasFieldsForStruct; + +template +consteval FieldAnnotationFlags has_fields_member_flags() noexcept { + using U = std::remove_cvref_t; + if constexpr (is_flatten_field::value) { + using Inner = + typename HasFieldsDeref>::Type; + return HasFieldsForStruct::flags; + } else { + constexpr bool is_f = is_field::value; + return FieldAnnotationFlags{is_f, is_f}; } - (std::make_integer_sequence>()); } -template -constexpr bool some_fields_or_flatten() { - const auto is_true_for_one = - [](std::integral_constant) -> bool { - using T = std::remove_cvref_t>; - if constexpr (is_flatten_field_v) { - return some_fields_or_flatten< - ptr_tuple_t::Type>>(); - } else { - return is_field_v; +template +consteval FieldAnnotationFlags has_fields_combine_flags() noexcept { + if constexpr (sizeof...(Fields) == 0) { + return FieldAnnotationFlags{false, true}; + } else if constexpr (!(false || ... || + is_flatten_field< + std::remove_cvref_t>::value)) { + return FieldAnnotationFlags{ + (false || ... || is_field>::value), + (true && ... && is_field>::value)}; + } else { + constexpr std::array flags{ + has_fields_member_flags()...}; + bool some = false; + bool all = true; + for (const auto& f : flags) { + some = some || f.some; + all = all && f.all; } - }; - - return [&](std::integer_sequence) { - return (false || ... || - is_true_for_one(std::integral_constant{})); + return FieldAnnotationFlags{some, all}; } - (std::make_integer_sequence>()); } +struct HasFieldsVisitor { + template + constexpr auto operator()(Fields&...) const noexcept { + constexpr auto flags = has_fields_combine_flags(); + return FieldAnnotationResult{}; + } +}; + +template +struct HasFieldsForStruct { + static constexpr FieldAnnotationFlags flags{false, false}; +}; + +template +struct HasFieldsForStruct> { + static constexpr FieldAnnotationFlags flags{sizeof...(Fields) > 0, true}; +}; + +template + requires(!is_named_tuple::value && std::is_class_v +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + && std::is_aggregate_v +#endif + ) +struct HasFieldsForStruct { + using Result = decltype(rfl::internal::apply_to_fields(std::declval(), + HasFieldsVisitor{})); + static constexpr FieldAnnotationFlags flags{Result::some, Result::all}; +}; + template constexpr bool has_fields() { if constexpr (is_named_tuple_v) { return true; } else { - using TupleType = ptr_tuple_t; - if constexpr (some_fields_or_flatten()) { + using U = typename HasFieldsDeref>::Type; + constexpr auto flags = HasFieldsForStruct::flags; + if constexpr (flags.some) { static_assert( - all_fields_or_flatten(), + flags.all, "If some of your fields are annotated using rfl::Field<...>, " "then you must annotate all of your fields. " "Also, you cannot combine annotated and " diff --git a/include/rfl/internal/has_flatten_fields.hpp b/include/rfl/internal/has_flatten_fields.hpp index 869b41535..c62881410 100644 --- a/include/rfl/internal/has_flatten_fields.hpp +++ b/include/rfl/internal/has_flatten_fields.hpp @@ -1,26 +1,30 @@ #ifndef RFL_INTERNAL_HASFLATTENFIELDS_HPP_ #define RFL_INTERNAL_HASFLATTENFIELDS_HPP_ +#include #include -#include #include "../Tuple.hpp" #include "is_flatten_field.hpp" -namespace rfl ::internal { +namespace rfl::internal { + +template +struct HasFlattenFields; + +template +struct HasFlattenFields> + : std::bool_constant<(false || ... || + is_flatten_field_v>)> {}; + +template +struct HasFlattenFields> + : std::bool_constant<(false || ... || + is_flatten_field_v>)> {}; template constexpr bool has_flatten_fields() { - const auto is_true_for_one = - [](std::integral_constant) -> bool { - using T = std::remove_cvref_t>; - return is_flatten_field_v; - }; - - return [&](std::integer_sequence) { - return (false || ... || - is_true_for_one(std::integral_constant{})); - }(std::make_integer_sequence>()); + return HasFlattenFields>::value; } } // namespace rfl::internal diff --git a/include/rfl/internal/int64_as_string_v.hpp b/include/rfl/internal/int64_as_string_v.hpp new file mode 100644 index 000000000..9fdc8a664 --- /dev/null +++ b/include/rfl/internal/int64_as_string_v.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_INT64ASSTRING_HPP_ +#define RFL_INTERNAL_INT64ASSTRING_HPP_ + +#include + +#include "../Int64AsString.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct int64_as_string : std::false_type {}; + +template <> +struct int64_as_string : std::true_type {}; + +template +struct int64_as_string> + : std::bool_constant<(int64_as_string::value || ...)> {}; + +template +inline constexpr bool int64_as_string_v = + int64_as_string>::value; + +} // namespace rfl::internal + +#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/is_alias.hpp b/include/rfl/internal/is_alias.hpp new file mode 100644 index 000000000..61283b886 --- /dev/null +++ b/include/rfl/internal/is_alias.hpp @@ -0,0 +1,42 @@ +#ifndef RFL_INTERNAL_ISALIAS_HPP_ +#define RFL_INTERNAL_ISALIAS_HPP_ + +#include + +#include "StringLiteral.hpp" + +namespace rfl { + +template +struct Alias; + +namespace internal { + +template +class is_alias : public std::false_type {}; + +template +class is_alias> : public std::true_type {}; + +template +constexpr bool is_alias_v = + is_alias>>::value; + +template +struct remove_alias { + using Type = T; +}; + +template +struct remove_alias> { + using Type = typename remove_alias>::Type; +}; + +template +using remove_alias_t = + typename remove_alias>>::Type; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_attribute.hpp b/include/rfl/internal/is_attribute.hpp index 408dbfafa..9d3e7e5be 100644 --- a/include/rfl/internal/is_attribute.hpp +++ b/include/rfl/internal/is_attribute.hpp @@ -4,6 +4,7 @@ #include #include "../Attribute.hpp" +#include "is_alias.hpp" #include "remove_rename.hpp" namespace rfl::internal { @@ -18,7 +19,8 @@ template class is_attribute> : public std::true_type {}; template -constexpr bool is_attribute_v = is_attribute>::value; +constexpr bool is_attribute_v = + is_attribute>>>::value; } // namespace rfl::internal diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 01189f634..dd265703b 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -8,7 +8,12 @@ #include "../Rename.hpp" #include "StringLiteral.hpp" -namespace rfl::internal { +namespace rfl { + +template +struct Alias; + +namespace internal { template class is_default_val; @@ -20,8 +25,12 @@ template class is_default_val> : public std::true_type {}; template -class is_default_val>> : public std::true_type { -}; +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; template constexpr bool is_default_val_v = @@ -44,6 +53,7 @@ template using default_val_t = std::remove_cvref_t&>()))>; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/internal/is_empty.hpp b/include/rfl/internal/is_empty.hpp index 7434710b0..e3c086896 100644 --- a/include/rfl/internal/is_empty.hpp +++ b/include/rfl/internal/is_empty.hpp @@ -1,22 +1,45 @@ #ifndef RFL_INTERNAL_ISEMPTY_HPP_ #define RFL_INTERNAL_ISEMPTY_HPP_ +#include #include #include "../Tuple.hpp" +#include "../num_fields.hpp" #include "is_named_tuple.hpp" -#include "ptr_tuple_t.hpp" namespace rfl::internal { +template +struct IsEmptyDeref { + using Type = std::remove_cvref_t; +}; + +template +struct IsEmptyDeref : IsEmptyDeref> {}; + +template +struct IsEmptyTuple : std::false_type {}; + +template +struct IsEmptyTuple> : std::true_type { + static constexpr bool empty = (sizeof...(Ts) == 0); +}; + +template +struct IsEmptyTuple> : std::true_type { + static constexpr bool empty = (sizeof...(Ts) == 0); +}; + template constexpr bool is_empty() { - using U = std::remove_cvref_t>; + using U = typename IsEmptyDeref>::Type; if constexpr (is_named_tuple_v) { return U::size() == 0; + } else if constexpr (IsEmptyTuple::value) { + return IsEmptyTuple::empty; } else { - using TupleType = ptr_tuple_t; - return rfl::tuple_size_v == 0; + return rfl::num_fields == 0; } } diff --git a/include/rfl/internal/is_safe_default_constructible.hpp b/include/rfl/internal/is_safe_default_constructible.hpp new file mode 100644 index 000000000..ceb602786 --- /dev/null +++ b/include/rfl/internal/is_safe_default_constructible.hpp @@ -0,0 +1,481 @@ +#ifndef RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ +#define RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#endif + +#include "../common.hpp" +#include "HasValidation.hpp" +#include "StringLiteral.hpp" +#include "bind_to_tuple.hpp" +#include "has_reflection_type_v.hpp" +#include "has_reflector.hpp" +#include "nth_element_t.hpp" + +namespace rfl { + +enum class Copyability; + +template +struct AllOf; + +template +struct Attribute; + +template +class Box; + +template +struct Commented; + +template +struct DefaultVal; + +template +struct Deprecated; + +template +struct Description; + +template +class ExtraFields; + +template +struct Field; + +template +struct Flatten; + +class RFL_API Generic; + +template +class Object; + +template +struct Positional; + +template +class Ref; + +template +struct Rename; + +template +struct Short; + +template +struct TaggedUnion; + +template +class Tuple; + +template + requires internal::HasValidation, T> +struct Validator; + +template +class Variant; + +namespace internal { + +template + requires std::is_array_v +struct Array; + +template +class Skip; + +template +consteval bool is_safe_default_constructible_impl(); + +template +struct safe_default_is_optional : std::false_type {}; + +template +struct safe_default_is_optional> : std::true_type {}; + +template +struct safe_default_is_unique_ptr : std::false_type {}; + +template +struct safe_default_is_unique_ptr> : std::true_type {}; + +template +struct safe_default_is_shared_ptr : std::false_type {}; + +template +struct safe_default_is_shared_ptr> : std::true_type {}; + +template +struct safe_default_is_extra_fields : std::false_type {}; + +template +struct safe_default_is_extra_fields> : std::true_type {}; + +template +struct safe_default_is_object : std::false_type {}; + +template +struct safe_default_is_object> : std::true_type {}; + +template +struct safe_default_is_box : std::false_type {}; + +template +struct safe_default_is_box> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_is_ref : std::false_type {}; + +template +struct safe_default_is_ref> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_is_rfl_array : std::false_type {}; + +template +struct safe_default_is_rfl_array> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_is_std_array : std::false_type {}; + +template +struct safe_default_is_std_array> : std::true_type { + using element_type = V; + static constexpr size_t size = N; +}; + +template +struct safe_default_is_std_variant : std::false_type {}; + +template +struct safe_default_is_std_variant> : std::true_type {}; + +template +struct safe_default_is_rfl_variant : std::false_type {}; + +template +struct safe_default_is_rfl_variant> : std::true_type {}; + +template +struct safe_default_is_tagged_union : std::false_type {}; + +template +struct safe_default_is_tagged_union> + : std::true_type {}; + +template +struct safe_default_is_std_tuple : std::false_type {}; + +template +struct safe_default_is_std_tuple> : std::true_type {}; + +template +struct safe_default_is_rfl_tuple : std::false_type {}; + +template +struct safe_default_is_rfl_tuple> : std::true_type {}; + +template +struct safe_default_is_std_pair : std::false_type {}; + +template +struct safe_default_is_std_pair> : std::true_type { + using first_type = A; + using second_type = B; +}; + +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L +template +struct safe_default_is_expected : std::false_type {}; + +template +struct safe_default_is_expected> : std::true_type { + using value_type = V; +}; +#endif + +template +struct safe_default_value_wrapper : std::false_type {}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> + : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_check_first_alt : std::false_type {}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_all_elements : std::false_type {}; + +template +struct safe_default_check_all_elements, Visited...> + : std::bool_constant< + (is_safe_default_constructible_impl() && ...)> {}; + +template +struct safe_default_check_all_elements, Visited...> + : std::bool_constant< + (is_safe_default_constructible_impl() && ...)> {}; + +// Checks every field of a reflected aggregate struct U (where +// std::is_default_constructible_v is already known to be true). +// If a field type F is itself not std::is_default_constructible_v, U can +// only be default-constructible because F has a default member initializer in +// U, so U{} will not call F{}. Otherwise F may be default-constructed by U{} +// and must be recursively verified. +template +struct SafeDefaultFieldsVisitor { + template + static consteval bool check_one() { + using F = std::remove_cvref_t; + if constexpr (!std::is_default_constructible_v) { + return true; + } else { + return is_safe_default_constructible_impl(); + } + } + + template + constexpr auto operator()(FieldTypes&...) const noexcept + -> std::bool_constant<(check_one() && ...)> { + return {}; + } +}; + +template +consteval bool container_aux_types_default_constructible() { + if constexpr (requires { typename U::allocator_type; }) { + if constexpr (!std::is_default_constructible_v< + typename U::allocator_type>) { + return false; + } + } + if constexpr (requires { typename U::key_compare; }) { + if constexpr (!std::is_default_constructible_v) { + return false; + } + } + if constexpr (requires { typename U::hasher; }) { + if constexpr (!std::is_default_constructible_v) { + return false; + } + } + if constexpr (requires { typename U::key_equal; }) { + if constexpr (!std::is_default_constructible_v) { + return false; + } + } + return true; +} + +/// Checks whether T can be safely default-constructed without triggering hard +/// errors inside unconstrained Box/Ref default constructors or infinite +/// runtime recursion on cyclic Box/Ref graphs. +template +consteval bool is_safe_default_constructible_impl() { + if constexpr (std::is_reference_v) { + return false; + } else { + using U = std::remove_cvref_t; + if constexpr ((std::is_same_v || ...)) { + return false; + } else if constexpr (safe_default_is_optional::value || + safe_default_is_shared_ptr::value || + safe_default_is_extra_fields::value || + safe_default_is_object::value || + std::is_pointer_v || std::is_same_v || + std::is_same_v) { + return true; + } else if constexpr (safe_default_is_unique_ptr::value) { + return std::is_default_constructible_v; + } else if constexpr (safe_default_is_box::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_box::element_type, U, Visited...>(); + } else if constexpr (safe_default_is_ref::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_ref::element_type, U, Visited...>(); +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L + } else if constexpr (safe_default_is_expected::value) { + using V = typename safe_default_is_expected::value_type; + if constexpr (std::is_void_v) { + return true; + } else { + return std::is_default_constructible_v && + is_safe_default_constructible_impl(); + } +#endif + } else if constexpr (safe_default_is_std_variant::value || + safe_default_is_rfl_variant::value || + safe_default_is_tagged_union::value) { + return safe_default_check_first_alt::value; + } else if constexpr (safe_default_is_std_tuple::value || + safe_default_is_rfl_tuple::value) { + return safe_default_check_all_elements::value; + } else if constexpr (safe_default_is_std_pair::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_std_pair::first_type, U, + Visited...>() && + is_safe_default_constructible_impl< + typename safe_default_is_std_pair::second_type, U, + Visited...>(); + } else if constexpr (safe_default_is_std_array::value) { + if constexpr (safe_default_is_std_array::size == 0) { + return true; + } else { + return is_safe_default_constructible_impl< + typename safe_default_is_std_array::element_type, U, + Visited...>(); + } + } else if constexpr (safe_default_is_rfl_array::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_rfl_array::element_type, U, Visited...>(); + } else if constexpr (std::is_bounded_array_v) { + return is_safe_default_constructible_impl, U, + Visited...>(); + } else if constexpr (std::is_unbounded_array_v) { + return false; + } else if constexpr (safe_default_value_wrapper::value) { + return std::is_default_constructible_v && + is_safe_default_constructible_impl< + typename safe_default_value_wrapper::element_type, U, + Visited...>(); + } else if constexpr (std::is_default_constructible_v && + std::is_class_v && std::is_aggregate_v && + !has_reflection_type_v && !has_read_reflector && + !has_write_reflector) { + return decltype(apply_to_fields( + std::declval(), SafeDefaultFieldsVisitor{}))::value; + } else { + return std::is_default_constructible_v && + container_aux_types_default_constructible(); + } + } +} + +template +constexpr bool is_safe_default_constructible_v = + is_safe_default_constructible_impl(); + +template +struct is_safe_default_constructible + : std::bool_constant> {}; + +} // namespace internal +} // namespace rfl + +#endif // RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ diff --git a/include/rfl/internal/is_skip.hpp b/include/rfl/internal/is_skip.hpp index d3357d0e5..0b45d6e7c 100644 --- a/include/rfl/internal/is_skip.hpp +++ b/include/rfl/internal/is_skip.hpp @@ -4,8 +4,14 @@ #include #include "Skip.hpp" +#include "StringLiteral.hpp" -namespace rfl::internal { +namespace rfl { + +template +struct Alias; + +namespace internal { template class is_skip; @@ -17,10 +23,14 @@ template class is_skip> : public std::true_type {}; +template +class is_skip> : public is_skip> {}; + template constexpr bool is_skip_v = is_skip>>::value; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/internal/max_depth.hpp b/include/rfl/internal/max_depth.hpp new file mode 100644 index 000000000..078888d92 --- /dev/null +++ b/include/rfl/internal/max_depth.hpp @@ -0,0 +1,79 @@ +#ifndef RFL_INTERNAL_MAX_DEPTH_HPP_ +#define RFL_INTERNAL_MAX_DEPTH_HPP_ + +#include +#include +#include + +#include "../MaxDepth.hpp" +#include "../Processors.hpp" +#include "../Result.hpp" + +namespace rfl::internal { + +template +struct max_depth_info { + static constexpr std::size_t count = 0; + static constexpr std::size_t limit = 0; +}; + +template +struct max_depth_info> { + static constexpr std::size_t count = 1; + static constexpr std::size_t limit = _limit; +}; + +template <> +struct max_depth_info> { + static constexpr std::size_t count = 0; + static constexpr std::size_t limit = 0; +}; + +template +struct max_depth_info> { + private: + using HeadInfo = max_depth_info>; + using TailInfo = max_depth_info>; + + public: + static constexpr std::size_t count = HeadInfo::count + TailInfo::count; + static_assert(count <= 1, + "Multiple rfl::MaxDepth processors are not allowed."); + static constexpr std::size_t limit = + HeadInfo::count > 0 ? HeadInfo::limit : TailInfo::limit; +}; + +template +inline constexpr std::size_t max_depth_v = + max_depth_info>::limit; + +inline std::size_t& current_parse_depth() noexcept { + thread_local std::size_t depth = 0; + return depth; +} + +template +class ParseDepthGuard { + public: + ParseDepthGuard() noexcept : exceeded_(++current_parse_depth() > _limit) {} + + ~ParseDepthGuard() noexcept { --current_parse_depth(); } + + ParseDepthGuard(const ParseDepthGuard&) = delete; + ParseDepthGuard& operator=(const ParseDepthGuard&) = delete; + + bool exceeded() const noexcept { return exceeded_; } + + static Error make_error() { + return Error("Maximum nesting depth of " + std::to_string(_limit) + + " exceeded.", + ErrorKind::syntax_error); + } + + private: + bool exceeded_; +}; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/move_from_tuple.hpp b/include/rfl/internal/move_from_tuple.hpp index 3855f7741..1c73c60f1 100644 --- a/include/rfl/internal/move_from_tuple.hpp +++ b/include/rfl/internal/move_from_tuple.hpp @@ -2,54 +2,35 @@ #define RFL_MOVE_FROM_TUPLE_HPP_ #include +#include +#include #include +#include #include "../Tuple.hpp" +#include "../apply.hpp" #include "../tuple_cat.hpp" #include "Array.hpp" +#include "calc_flattened_size.hpp" #include "has_arrays.hpp" #include "has_flatten_fields.hpp" #include "is_flatten_field.hpp" #include "ptr_tuple_t.hpp" #include "tup_to_ptr_tuple.hpp" -#include "tuple_t.hpp" namespace rfl::internal { -/** - * Calculates the flattened size of a tuple. - * @tparam T The type to calculate the size for. - * @return The flattened size. - */ -template -consteval size_t calc_flattened_size() { - if constexpr (is_flatten_field_v) { - using Tuple = ptr_tuple_t; - return [&](std::integer_sequence) { - return (calc_flattened_size>() + ...); - }(std::make_integer_sequence>()); - } else { - return 1; +template +consteval auto calc_indptr_from_sizes() { + std::array indptr{}; + indptr[0] = _begin; + constexpr std::array sizes{_sizes...}; + for (std::size_t i = 0; i < sizeof...(_sizes); ++i) { + indptr[i + 1] = indptr[i] + sizes[i]; } + return indptr; } -/** - * Helper struct for calculating the indptr array. - * @tparam _head The head of the indptr array. - * @tparam _tail The tail of the indptr array. - */ -template -struct IndptrHelper { - using ArrayType = std::array; - static constexpr auto indptr_ = ArrayType{_head, _tail...}; - - template - consteval auto operator+(const IndptrHelper<_is...>&) const { - constexpr auto last = std::get(indptr_); - return IndptrHelper<_head, _tail..., (last + _is)...>{}; - } -}; - /** * Calculates the indptr array for a tuple. * The indptr array is used to map the flattened tuple back to the original @@ -58,49 +39,94 @@ struct IndptrHelper { * @tparam _begin The starting index for the indptr. * @return The indptr array. */ -template +template consteval auto calc_indptr() { - return [&](std::integer_sequence) { - return (IndptrHelper<_begin>{} + ... + - IndptrHelper>()>{}) - .indptr_; - }(std::make_integer_sequence>()); + constexpr std::size_t size = rfl::tuple_size_v>; + if constexpr (size == 0) { + return std::array{_begin}; + } else { + return [](std::index_sequence<_is...>) { + return calc_indptr_from_sizes< + _begin, calc_flattened_size< + tuple_element_t(_is), Tuple>>()...>(); + }(std::make_index_sequence{}); + } +} + +template +auto unflatten_ptr_tuple(PtrTupleType& _t); + +template +auto unflatten_one(PtrTupleType& _t) { + using T = std::remove_cvref_t(_i), TargetTupleType>>>; + + if constexpr (is_flatten_field_v) { + using SubTargetTupleType = ptr_tuple_t< + std::remove_cvref_t>>; + + return unflatten_ptr_tuple(_t); + + } else { + return rfl::get(_j)>(_t); + } +} + +template +auto unflatten_ptr_tuple_impl(PtrTupleType&, std::index_sequence<>) { + return rfl::Tuple<>(); +} + +template +auto unflatten_ptr_tuple_impl(PtrTupleType& _t, std::index_sequence<_is...>) { + constexpr auto indptr = calc_indptr(); + return rfl::make_tuple( + unflatten_one(_t)...); } /** - * Unflattens a tuple of pointers into a target tuple. T - * This is meant for when the uses uses rfl::Flatten<...>. + * Unflattens a tuple of pointers into a target tuple. + * This is meant for when the user uses rfl::Flatten<...>. * @param _t Tuple of pointers to elements. * @return A tuple with unflattened elements. */ -template +template auto unflatten_ptr_tuple(PtrTupleType& _t) { constexpr auto size = rfl::tuple_size_v>; + return unflatten_ptr_tuple_impl( + _t, std::make_index_sequence{}); +} - constexpr auto indptr = calc_indptr(); +template +auto move_from_pointers(Pointers&& _ptrs); - const auto unflatten_one = - [&](std::integral_constant) { - using T = std::remove_cvref_t< - std::remove_pointer_t>>; +template +auto move_one_from_pointers(Pointers& _ptrs) { + using FieldType = tuple_element_t(_i), Pointers>; - constexpr size_t j = std::get<_i>(indptr); + if constexpr (std::is_pointer_v) { + return std::move(*rfl::get(_i)>(_ptrs)); - if constexpr (is_flatten_field_v) { - using SubTargetTupleType = - ptr_tuple_t>; + } else { + using PtrTupleType = ptr_tuple_t>; - return unflatten_ptr_tuple(_t); + using U = std::remove_cvref_t(_i), PtrTupleType>>::Type>; - } else { - return std::get(_t); - } - }; + return move_from_pointers(rfl::get(_i)>(_ptrs)); + } +} + +template +auto move_from_pointers_impl(Pointers&, std::index_sequence<>) { + return std::remove_cvref_t{}; +} - return [&](std::integer_sequence) { - return rfl::make_tuple( - unflatten_one(std::integral_constant{})...); - }(std::make_integer_sequence()); +template +auto move_from_pointers_impl(Pointers& _ptrs, std::index_sequence<_is...>) { + return std::remove_cvref_t{move_one_from_pointers(_ptrs)...}; } /** @@ -110,32 +136,19 @@ auto unflatten_ptr_tuple(PtrTupleType& _t) { */ template auto move_from_pointers(Pointers&& _ptrs) { - const auto move_one = [&](std::integral_constant) { - using FieldType = tuple_element_t<_i, std::remove_cvref_t>; - - if constexpr (std::is_pointer_v) { - return std::move(*std::get<_i>(_ptrs)); - - } else { - using PtrTupleType = ptr_tuple_t>; - - using U = std::remove_cvref_t>::Type>; - - return move_from_pointers(std::get<_i>(_ptrs)); - } - }; - return [&](std::integer_sequence) { - return std::remove_cvref_t{ - move_one(std::integral_constant{})...}; - }(std::make_integer_sequence>()); + return move_from_pointers_impl( + _ptrs, + std::make_index_sequence< + rfl::tuple_size_v>>{}); } +template +auto flatten_c_arrays(TupleType&& _tup); + /** * Flattens a single element into a tuple. * @param _v Source element. * @return A tuple containing the element. - * */ template auto flatten_array(T* _v) { @@ -173,17 +186,38 @@ auto make_tuple_from_element(Array* _arr) { return flatten_array(&(_arr->arr_)); } +/** + * Recursively flattens C-style arrays inside a nested unflattened tuple. + * @param _tup Nested pointer tuple from an rfl::Flatten field. + * @return A single-element tuple wrapping the flattened nested tuple. + */ +template +auto make_tuple_from_element(rfl::Tuple _tup) { + return rfl::make_tuple(flatten_c_arrays(std::move(_tup))); +} + /** * Flattens C-style arrays in a tuple. * @param _tup Source tuple. * @return A flattened tuple. */ -auto flatten_c_arrays(auto&& _tup) { +template +auto flatten_c_arrays(TupleType&& _tup) { return rfl::apply( [](auto... _v) { return rfl::tuple_cat(make_tuple_from_element(_v)...); }, _tup); } +template +auto move_from_tuple_direct(TupleType&, std::index_sequence<>) { + return T{}; +} + +template +auto move_from_tuple_direct(TupleType& _t, std::index_sequence<_is...>) { + return T{std::move(rfl::get(_is)>(_t))...}; +} + /** * Moves elements from a tuple to a target object. * @param _t Source tuple. @@ -191,10 +225,26 @@ auto flatten_c_arrays(auto&& _tup) { */ template auto move_from_tuple(TupleType&& _t) { - using TargetTupleType = tuple_t>; - auto ptr_tuple = tup_to_ptr_tuple(_t); - return move_from_pointers( - flatten_c_arrays(unflatten_ptr_tuple(ptr_tuple))); + using TargetType = std::remove_cvref_t; + using TargetPtrTupleType = ptr_tuple_t; + constexpr bool has_flatten = has_flatten_fields(); + constexpr bool has_c_arrays = has_arrays>(); + if constexpr (!has_flatten && !has_c_arrays) { + return move_from_tuple_direct( + _t, std::make_index_sequence< + rfl::tuple_size_v>>{}); + } else { + auto ptr_tuple = tup_to_ptr_tuple(_t); + if constexpr (has_flatten && has_c_arrays) { + return move_from_pointers( + flatten_c_arrays(unflatten_ptr_tuple(ptr_tuple))); + } else if constexpr (has_flatten) { + return move_from_pointers( + unflatten_ptr_tuple(ptr_tuple)); + } else { + return move_from_pointers(flatten_c_arrays(ptr_tuple)); + } + } } } // namespace rfl::internal diff --git a/include/rfl/internal/no_duplicate_field_names.hpp b/include/rfl/internal/no_duplicate_field_names.hpp index 86bf5f671..986dcb6b2 100644 --- a/include/rfl/internal/no_duplicate_field_names.hpp +++ b/include/rfl/internal/no_duplicate_field_names.hpp @@ -5,48 +5,82 @@ #include #include #include -#include -#include "../Tuple.hpp" +namespace rfl::internal { -namespace rfl { -namespace internal { +template +constexpr bool has_no_duplicate_names( + std::array _arr) noexcept { + if constexpr (_n <= 1) { + return true; + } else { + const auto sift_down = [&](std::size_t _root, std::size_t _end) noexcept { + while (true) { + const std::size_t left = 2 * _root + 1; + if (left >= _end) { + break; + } + std::size_t largest = left; + const std::size_t right = left + 1; + if (right < _end && _arr[largest] < _arr[right]) { + largest = right; + } + if (!(_arr[_root] < _arr[largest])) { + break; + } + const auto tmp = _arr[_root]; + _arr[_root] = _arr[largest]; + _arr[largest] = tmp; + _root = largest; + } + }; -template -constexpr inline bool no_duplicate_field_names() { - constexpr std::size_t num_fields = rfl::tuple_size_v; + for (std::size_t i = _n / 2; i > 0; --i) { + sift_down(i - 1, _n); + } - if constexpr (num_fields <= 1) { + for (std::size_t end = _n - 1; end > 0; --end) { + const auto tmp = _arr[0]; + _arr[0] = _arr[end]; + _arr[end] = tmp; + sift_down(0, end); + } + + for (std::size_t i = 1; i < _n; ++i) { + if (_arr[i] == _arr[i - 1]) { + return false; + } + } return true; - } else { - constexpr bool result = - [](std::index_sequence<_is...>) { - std::array arr{ - std::remove_cvref_t>::name_ - .string_view()...}; - for (std::size_t gap = arr.size() / 2; gap > 0; gap /= 2) { - for (std::size_t i = gap; i < arr.size(); ++i) { - const auto key = arr[i]; - std::size_t j = i; - while (j >= gap && key < arr[j - gap]) { - arr[j] = arr[j - gap]; - j -= gap; - } - arr[j] = key; - } - } - for (std::size_t i = 1; i < arr.size(); ++i) { - if (arr[i] == arr[i - 1]) { - return false; - } - } - return true; - }(std::make_index_sequence()); - return result; } } -} // namespace internal -} // namespace rfl +template +struct NoDuplicateFieldNames; + +template