diff --git a/CMakeLists.txt b/CMakeLists.txt index aae285585..c9b1d862e 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 @@ -29,25 +38,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 +90,28 @@ 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_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 +125,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 +174,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() @@ -182,16 +206,117 @@ if (REFLECTCPP_USE_VCPKG) list(APPEND VCPKG_MANIFEST_FEATURES "yas") endif() - set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") + if (NOT DEFINED CMAKE_TOOLCHAIN_FILE OR "${CMAKE_TOOLCHAIN_FILE}" STREQUAL "") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "") + if (DEFINED VCPKG_ROOT AND NOT "${VCPKG_ROOT}" STREQUAL "") + file(TO_CMAKE_PATH "${VCPKG_ROOT}" _REFLECTCPP_VCPKG_ROOT) + if (EXISTS "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + endif () + endif () + if (NOT _REFLECTCPP_VCPKG_TOOLCHAIN AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") + endif () + if (NOT _REFLECTCPP_VCPKG_TOOLCHAIN AND DEFINED ENV{VCPKG_ROOT} AND NOT "$ENV{VCPKG_ROOT}" STREQUAL "") + file(TO_CMAKE_PATH "$ENV{VCPKG_ROOT}" _REFLECTCPP_VCPKG_ROOT) + if (EXISTS "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(_REFLECTCPP_VCPKG_TOOLCHAIN "${_REFLECTCPP_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + endif () + endif () + if (_REFLECTCPP_VCPKG_TOOLCHAIN) + set(CMAKE_TOOLCHAIN_FILE "${_REFLECTCPP_VCPKG_TOOLCHAIN}" CACHE STRING "Vcpkg toolchain file") + else () + set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" CACHE STRING "Vcpkg toolchain file") + endif () + endif () endif () project(reflectcpp VERSION 0.27.1 LANGUAGES CXX) -find_package(ament_cmake QUIET) +function(_reflectcpp_strip_flags_from_string _input _out_var _token_regex) + set(_val "${_input}") + if (NOT "${_val}" STREQUAL "") + set(_prev "") + while (NOT "${_val}" STREQUAL "${_prev}") + set(_prev "${_val}") + string(REGEX REPLACE "(^|[ \t])(${_token_regex})([ \t]|$)" "\\1\\3" _val "${_val}") + endwhile () + string(STRIP "${_val}" _val) + endif () + set(${_out_var} "${_val}" PARENT_SCOPE) +endfunction() -if (PROJECT_IS_TOP_LEVEL) - set(REFLECTCPP_INSTALL ON) -endif() +function(_reflectcpp_strip_msvc_warning_flags _strip_wx) + set(_rfl_token_regex "[/-]W[0-4]|[/-]Wall|[/-]w") + if (_strip_wx) + string(APPEND _rfl_token_regex "|[/-]WX-?") + endif () + if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND _strip_wx) + string(APPEND _rfl_token_regex "|-W[a-z][a-zA-Z0-9_=+-]*") + endif () + + set(_rfl_configs DEBUG RELEASE RELWITHDEBINFO MINSIZEREL) + if (DEFINED CMAKE_CONFIGURATION_TYPES) + foreach (_rfl_cfg IN LISTS CMAKE_CONFIGURATION_TYPES) + string(TOUPPER "${_rfl_cfg}" _rfl_cfg_upper) + list(APPEND _rfl_configs "${_rfl_cfg_upper}") + endforeach () + endif () + if (DEFINED CMAKE_BUILD_TYPE AND NOT "${CMAKE_BUILD_TYPE}" STREQUAL "") + string(TOUPPER "${CMAKE_BUILD_TYPE}" _rfl_cfg_upper) + list(APPEND _rfl_configs "${_rfl_cfg_upper}") + endif () + list(REMOVE_DUPLICATES _rfl_configs) + + set(_rfl_flag_vars CMAKE_CXX_FLAGS CMAKE_C_FLAGS) + foreach (_rfl_cfg IN LISTS _rfl_configs) + list(APPEND _rfl_flag_vars "CMAKE_CXX_FLAGS_${_rfl_cfg}" "CMAKE_C_FLAGS_${_rfl_cfg}") + endforeach () + foreach (_rfl_var IN LISTS _rfl_flag_vars) + if (DEFINED ${_rfl_var} AND NOT "${${_rfl_var}}" STREQUAL "") + _reflectcpp_strip_flags_from_string("${${_rfl_var}}" _rfl_cleaned "${_rfl_token_regex}") + if (NOT "${_rfl_cleaned}" STREQUAL "${${_rfl_var}}") + set(${_rfl_var} "${_rfl_cleaned}" PARENT_SCOPE) + endif () + endif () + endforeach () + + get_directory_property(_rfl_dir_opts COMPILE_OPTIONS) + if (_rfl_dir_opts) + set(_rfl_filtered_opts "") + foreach (_rfl_opt IN LISTS _rfl_dir_opts) + if ("${_rfl_opt}" MATCHES "^(${_rfl_token_regex})$") + continue() + elseif ("${_rfl_opt}" MATCHES "^\\$<([01]|BUILD_INTERFACE|INSTALL_INTERFACE|.+>):(${_rfl_token_regex})>$") + continue() + elseif ("${_rfl_opt}" MATCHES "^SHELL:(.*)$") + _reflectcpp_strip_flags_from_string("${CMAKE_MATCH_1}" _rfl_shell_cleaned "${_rfl_token_regex}") + if (NOT "${_rfl_shell_cleaned}" STREQUAL "") + list(APPEND _rfl_filtered_opts "SHELL:${_rfl_shell_cleaned}") + endif () + else () + list(APPEND _rfl_filtered_opts "${_rfl_opt}") + endif () + endforeach () + set_directory_properties(PROPERTIES COMPILE_OPTIONS "${_rfl_filtered_opts}") + endif () +endfunction() + +# Strip inherited MSVC warning flags in this directory's local scope before +# add_library(reflectcpp ...) snapshots directory COMPILE_OPTIONS, so +# reflectcpp's own /W0 or /W4 never triggers MSVC D9025 override warnings +# without mutating the parent project's flags or COMPILE_OPTIONS. +if (MSVC) + if (NOT _REFLECTCPP_IS_TOP_LEVEL AND NOT REFLECTCPP_STRICT_WARNINGS) + _reflectcpp_strip_msvc_warning_flags(ON) + elseif (REFLECTCPP_STRICT_WARNINGS) + _reflectcpp_strip_msvc_warning_flags(OFF) + endif () +endif () + +if (_REFLECTCPP_IS_TOP_LEVEL) + find_package(ament_cmake QUIET) +endif () if (REFLECTCPP_BUILD_SHARED) add_library(reflectcpp SHARED) @@ -202,13 +327,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 +410,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 PRIVATE + $) +target_include_directories( + reflectcpp ${_REFLECTCPP_INCLUDE_SYSTEM} INTERFACE + $ + $) target_include_directories( - reflectcpp PUBLIC + 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 +492,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 +564,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 +617,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 +632,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 +660,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,17 +671,21 @@ 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>>) @@ -407,7 +695,7 @@ 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 +711,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 +720,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 +817,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 +892,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 +935,41 @@ if (REFLECTCPP_INSTALL) ) endif () -# Set general package information -set(CPACK_PACKAGE_NAME "reflectcpp") -set(CPACK_PACKAGE_VENDOR "Reflect C++ Team") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Reflect C++ library") -set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) -set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") -set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") - -# Configure generators -set(CPACK_GENERATOR "TGZ;RPM;DEB") - -# DEB specific configuration -set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) -set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) -# Fix maintainer information - ensure both are set consistently -set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") -set(CPACK_DEBIAN_PACKAGE_MAINTAINER "maintainer@reflectcpp.org") -set(CPACK_DEBIAN_PACKAGE_DEPENDS "") - -# RPM specific configuration -set(CPACK_RPM_PACKAGE_REQUIRES "") -set(CPACK_RPM_FILE_NAME RPM-DEFAULT) -set(CPACK_RPM_PACKAGE_LICENSE "MIT") -set(CPACK_RPM_PACKAGE_LICENSE "MIT") -set(CPACK_RPM_PACKAGE_URL "https://munich-data-engineering.github.io/reflect-cpp") - -include(CPack) - -if (ament_cmake_FOUND) - ament_package() -endif() +if (_REFLECTCPP_IS_TOP_LEVEL) + # Set general package information + set(CPACK_PACKAGE_NAME "reflectcpp") + set(CPACK_PACKAGE_VENDOR "Reflect C++ Team") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Reflect C++ library") + set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) + set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) + set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) + set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) + set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") + set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") + set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") + + # Configure generators + set(CPACK_GENERATOR "TGZ;RPM;DEB") + + # DEB specific configuration + set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) + set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) + # Fix maintainer information - ensure both are set consistently + set(CPACK_PACKAGE_CONTACT "maintainer@reflectcpp.org") + set(CPACK_DEBIAN_PACKAGE_MAINTAINER "maintainer@reflectcpp.org") + set(CPACK_DEBIAN_PACKAGE_DEPENDS "") + + # RPM specific configuration + set(CPACK_RPM_PACKAGE_REQUIRES "") + set(CPACK_RPM_FILE_NAME RPM-DEFAULT) + set(CPACK_RPM_PACKAGE_LICENSE "MIT") + set(CPACK_RPM_PACKAGE_LICENSE "MIT") + set(CPACK_RPM_PACKAGE_URL "https://munich-data-engineering.github.io/reflect-cpp") + + include(CPack) + + if (ament_cmake_FOUND) + ament_package() + endif() +endif () diff --git a/README.md b/README.md index 9cfdfa223..374776f8c 100644 --- a/README.md +++ b/README.md @@ -48,11 +48,12 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile - [Extra fields](#extra-fields) - [Reflective programming](#reflective-programming) - [Standard Library Integration](#support-for-containers) + - [Installation](#installation) - [The team behind reflect-cpp](#the-team-behind-reflect-cpp) - [License](#license) ### More in our [documentation](https://munich-data-engineering.github.io/reflect-cpp): - - [Installation ↗](https://munich-data-engineering.github.io/reflect-cpp/install/#option-2-compilation-using-cmake) + - [Installation ↗](https://munich-data-engineering.github.io/reflect-cpp/install/#option-3-compilation-using-cmake) - [C++26 reflection ↗](https://munich-data-engineering.github.io/reflect-cpp/cpp26_reflection) - [Benchmarks ↗](https://munich-data-engineering.github.io/reflect-cpp/benchmarks) - [How to contribute ↗](https://munich-data-engineering.github.io/reflect-cpp/contributing) @@ -373,6 +374,17 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`: + +```cpp +if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + // Usage: ./app -o|--output-dir= -v|--verbose[=] --count= + // + // Arguments: ... +} +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages @@ -671,6 +683,7 @@ In addition, it supports the following custom containers: - `rfl::Tuple`: An alternative to `std::tuple` that compiles considerably faster. - `rfl::Validator`: Allows for automatic input validation. - `rfl::Variant`: An alternative to `std::variant` that compiles considerably faster. +- `rfl::json::Raw`: Holds a raw JSON value for passthrough serialization and deserialization (JSON only; [details](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/json/#raw-json-passthrough-rfljsonraw)). #### Custom classes @@ -687,6 +700,29 @@ The following compilers are supported for C++-20: The following compilers are supported for C++-26: - GCC 16.2 or higher +### Using CMake FetchContent + +JSON-only (zero external dependencies — `yyjson`, `ctre`, and `enchantum` are bundled): + +```cmake +include(FetchContent) +FetchContent_Declare(reflectcpp + GIT_REPOSITORY https://github.com/munich-data-engineering/reflect-cpp.git + GIT_TAG main # replace with a release tag containing CMake 3.20 / subproject support + GIT_SHALLOW TRUE + GIT_SUBMODULES "") +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +To enable additional formats (for example YAML), set the corresponding `REFLECTCPP_*` option **before** `FetchContent_MakeAvailable(reflectcpp)` (non-JSON format libraries are resolved via `find_package` from system packages, vcpkg, or Conan because `REFLECTCPP_USE_VCPKG` defaults to `OFF` when consumed as a subproject): + +```cmake +set(REFLECTCPP_YAML ON) +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + ### Using vcpkg https://vcpkg.io/en/package/reflectcpp @@ -722,7 +758,7 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` -For other installation methods, refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/docs-readme). +For other installation methods, refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/install). ### Compiling with C++-26 reflection @@ -752,3 +788,5 @@ reflect-cpp includes [YYJSON](https://github.com/ibireme/yyjson), the fastest JS reflect-cpp includes [compile-time-regular-expressions](https://github.com/hanickadot/compile-time-regular-expressions). CTRE is written by Hana Dusíková and released under the Apache-2.0 License with LLVM exceptions. reflect-cpp includes [enchantum](https://github.com/ZXShady/enchantum/tree/main). enchantum is written by ZXShady and also released under the MIT License. + +See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for full third-party license texts, SPDX identifiers, and CMake/feature inclusion conditions. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..d8639fbb8 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,322 @@ +# Third-Party Notices + +`reflect-cpp` itself is licensed under the MIT License (see [LICENSE](LICENSE)). + +For out-of-the-box builds (`REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, the default), +this repository vendors the third-party components listed below under +`include/rfl/thirdparty/` and `src/yyjson.c`. When all bundled dependencies are +used, the composite SPDX license expression is: + +`MIT AND Apache-2.0 WITH LLVM-exception` + +Passing `-DREFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF` disables all bundled +components in CMake, resolving `ctre` and `enchantum` unconditionally via +`find_package` and resolving `yyjson` via `find_package` only when JSON, Avro, +CBOR, or UBJSON is enabled (`CMakeLists.txt`). Note that `REFLECTCPP_INSTALL=ON` +installs the entire `include/` tree, including `include/rfl/thirdparty/`. + +## Vendored Components + +| Component | Vendored Path(s) | Version | Upstream URL | SPDX License | CMake / Feature Condition | +|---|---|---|---|---|---| +| **yyjson** | `include/rfl/thirdparty/yyjson.h`, `src/yyjson.c` | `0.12.0` | | `MIT` | Compiled only when `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON` **and** at least one of `REFLECTCPP_JSON=ON` (default), `REFLECTCPP_AVRO=ON`, `REFLECTCPP_CBOR=ON`, or `REFLECTCPP_UBJSON=ON` is enabled (`_REFLECTCPP_NEEDS_JSON_IMPL` in `CMakeLists.txt`). Not compiled when all four options are `OFF`. | +| **CTRE** (compile-time-regular-expressions) | `include/rfl/thirdparty/ctre.hpp` | `3.10.0` | | `Apache-2.0 WITH LLVM-exception` | Header-only; included by `include/rfl/PatternValidator.hpp`, which is unconditionally included by `include/rfl.hpp` (and transitively every format umbrella header `include/rfl/.hpp` and `reflectcpp`'s precompiled header). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled header; installed/non-CMake builds fall back to `thirdparty/ctre.hpp` when no external `` is on the include path. | +| **enchantum** | `include/rfl/thirdparty/enchantum/` | Vendored from upstream `main` in reflect-cpp PR #441 (`750e67d6`, 2025-05-30; minor unused-include cleanup in PR #519 / `732e9fe8`; no embedded version macro; external installs require `>= 0.5.0` in `vcpkg.json`) | | `MIT` | Header-only; included by `include/rfl/internal/enums/cpp20/enchantum.hpp` for C++20 enum reflection when `REFLECTCPP_USE_CPP26_REFLECTION=OFF` (default). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled copy (installed/non-CMake builds fall back to `thirdparty/enchantum/enchantum.hpp` when no external copy is on the include path). Not included by C++ headers when `REFLECTCPP_USE_CPP26_REFLECTION=ON` (CMake still runs `find_package(enchantum)` if `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF`). | + +--- + +## yyjson + +- **Upstream:** +- **Author:** YaoYuan +- **Version:** `0.12.0` (`YYJSON_VERSION_STRING` in `include/rfl/thirdparty/yyjson.h`) +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/yyjson.h` and `src/yyjson.c` + +```text + Copyright (c) 2020 YaoYuan + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +``` + +--- + +## CTRE (compile-time-regular-expressions) + +- **Upstream:** +- **Author:** Hana Dusíková +- **Version:** `3.10.0` +- **SPDX License:** `Apache-2.0 WITH LLVM-exception` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/ctre.hpp` + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +--- + +## enchantum + +- **Upstream:** +- **Author:** ZXShady +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from upstream + (the 22 vendored header files under `include/rfl/thirdparty/enchantum/` do + not carry inline copyright or license headers). + +```text +MIT License + +Copyright (c) 2025 ZXShady + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 838fde939..9c46580fe 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -1,4 +1,9 @@ -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") +if (NOT MSVC) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") +elseif (REFLECTCPP_STRICT_WARNINGS) + # Restore /W3 for benchmark targets after top-level CMakeLists strips /W3 before setting /W4 on reflectcpp. + add_compile_options(/W3) +endif () if (MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std:c++20 -O2") diff --git a/benchmarks/all/CMakeLists.txt b/benchmarks/all/CMakeLists.txt index cbed30674..5efb69f35 100644 --- a/benchmarks/all/CMakeLists.txt +++ b/benchmarks/all/CMakeLists.txt @@ -1,4 +1,4 @@ -project(reflect-cpp-all-format-benchmarks) +project(reflect-cpp-all-format-benchmarks LANGUAGES CXX) file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") diff --git a/benchmarks/json/CMakeLists.txt b/benchmarks/json/CMakeLists.txt index 60dd74ddc..1c34e3d55 100644 --- a/benchmarks/json/CMakeLists.txt +++ b/benchmarks/json/CMakeLists.txt @@ -1,4 +1,4 @@ -project(reflect-cpp-json-benchmarks) +project(reflect-cpp-json-benchmarks LANGUAGES CXX) file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") diff --git a/docs/content/enums.md b/docs/content/enums.md index 5ab5561af..4d972f20a 100644 --- a/docs/content/enums.md +++ b/docs/content/enums.md @@ -215,3 +215,26 @@ constexpr auto enumerator_array = rfl::get_enumerator_array(); In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also `rfl::get_underlying_enumerators()` and `rfl::get_underlying_enumerator_array()`. + +## Custom wire names (`rfl::EnumNames` and `rfl::TransformEnumNames`) + +To customize serialized enum wire names across JSON, CLI, Generic, XML, YAML, and JSON Schema without duplicating enumerators as `rfl::Literal<...>`, specialize `rfl::EnumNames` and/or pass a `rfl::TransformEnumNames<...>` processor (`rfl::EnumSnakeCaseToKebabCase`, `rfl::EnumSnakeCaseToCamelCase`, `rfl::EnumSnakeCaseToPascalCase`, `rfl::EnumCamelCaseToSnakeCase`, `rfl::EnumToLowerCase`, `rfl::EnumToUpperCase`): + +```cpp +enum class OptimizationLevel { no_opt, size_opt, speed_opt, cxx_standard }; + +template <> +struct rfl::EnumNames { + static constexpr rfl::EnumNameTransform transform = + rfl::EnumNameTransform::snake_to_kebab; + static constexpr std::array, 1> + overrides = {{ + {OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; +``` + +- `overrides` (either a static contiguous range or a static `overrides()` returning a borrowed contiguous range such as `std::span>`) takes precedence over `transform`, and also supports enumerators outside the default reflected range. +- `transform` can be either a `rfl::EnumNameTransform` constant or a static callable `transform(std::string_view)` returning `std::string` or `std::string_view`. +- If `rfl::EnumNames` only defines `overrides` (without `transform`), non-overridden enumerators still receive any `rfl::TransformEnumNames<...>` processor passed to `read`, `write`, or `to_schema`. +- Use `rfl::get_enum_wire_names()` to inspect resolved `(wire_name, enumerator)` pairs. diff --git a/docs/content/install.md b/docs/content/install.md index 5aad26843..03537420c 100644 --- a/docs/content/install.md +++ b/docs/content/install.md @@ -36,6 +36,41 @@ Simply use [this recipe](https://conan.io/center/recipes/reflect-cpp). ## Option 3: Compilation using cmake +### Using FetchContent + +To consume reflect-cpp directly from a CMake project with JSON support only (zero external dependencies — `yyjson`, `ctre`, and `enchantum` are bundled): + +```cmake +include(FetchContent) +FetchContent_Declare(reflectcpp + GIT_REPOSITORY https://github.com/munich-data-engineering/reflect-cpp.git + GIT_TAG main # replace with a release tag containing CMake 3.20 / subproject support + GIT_SHALLOW TRUE + GIT_SUBMODULES "") +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +To enable additional serialization formats (for example YAML), set the corresponding `REFLECTCPP_*` option **before** `FetchContent_MakeAvailable(reflectcpp)`: + +```cmake +set(REFLECTCPP_YAML ON) +FetchContent_MakeAvailable(reflectcpp) +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) +``` + +When reflect-cpp is consumed as a subproject, `REFLECTCPP_USE_VCPKG` defaults to `OFF`, so each non-JSON format's underlying library (such as `yaml-cpp`) is resolved via `find_package` from your system packages, vcpkg toolchain, or Conan generator. + +### Subproject packaging options & `reflectcpp::headers` + +When embedding reflect-cpp inside larger projects or shared libraries, additional CMake controls are available: + +- **`REFLECTCPP_USE_BUNDLED_YYJSON`** (defaults to `REFLECTCPP_USE_BUNDLED_DEPENDENCIES`) and **`REFLECTCPP_YYJSON_TARGET`** (defaults to `yyjson::yyjson` when `REFLECTCPP_USE_BUNDLED_YYJSON=OFF`): reuse an existing external `yyjson` target without disabling bundled `ctre`/`enchantum`. *(Note: if you mix `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF` with `REFLECTCPP_USE_BUNDLED_YYJSON=ON`, ensure no external `` on your include path shadows the bundled header.)* +- **`REFLECTCPP_HIDDEN_VISIBILITY`** (default `OFF`): compiles static `reflectcpp` with hidden symbol visibility (`-fvisibility=hidden` / `-fvisibility-inlines-hidden`). Bundled `yyjson_*` symbols are already hidden by default on static non-Windows builds so consumer shared libraries never re-export them. +- **`reflectcpp::headers`**: an exported `INTERFACE` target propagating core reflection (`ctre`/`enchantum`) and JSON (`yyjson`) headers, compile features, and compile definitions without linking compiled `reflectcpp` objects (useful for header-only reflection or intermediate `OBJECT` libraries; final binaries/DSOs using out-of-line symbols still link `reflectcpp::reflectcpp`, and non-JSON backends are not propagated through `reflectcpp::headers`). + +### Building standalone + This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary. ```bash @@ -44,6 +79,8 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` +> **Tip (Windows multi-config installs):** When installing both `Debug` and `Release` configurations into the same prefix with Visual Studio, pass `-DCMAKE_DEBUG_POSTFIX=d` so Debug (`reflectcppd.lib`) and Release (`reflectcpp.lib`) libraries coexist without overwriting each other. + ## Option 4: Include source files into your own build Simply copy the contents of the folders `include` and `src` into your source repository or add it to your include path and also add `src/reflectcpp.cpp` and `src/reflectcpp_json.cpp` and `src/yyjson.c` to your source files for compilation. @@ -72,11 +109,9 @@ cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` -To use reflect-cpp in your project: +To use reflect-cpp in your project as a subdirectory, set any optional format flags **before** `add_subdirectory`: ```cmake -add_subdirectory(reflect-cpp) # Add this project as a subdirectory - set(REFLECTCPP_AVRO ON) # Optional set(REFLECTCPP_BSON ON) # Optional set(REFLECTCPP_CBOR ON) # Optional @@ -87,7 +122,9 @@ set(REFLECTCPP_UBJSON ON) # Optional set(REFLECTCPP_XML ON) # Optional set(REFLECTCPP_YAML ON) # Optional -target_link_libraries(your_project PRIVATE reflectcpp) # Link against the library +add_subdirectory(reflect-cpp) # Add this project as a subdirectory + +target_link_libraries(your_project PRIVATE reflectcpp::reflectcpp) # Link against the library ``` ### Troubleshooting vcpkg diff --git a/docs/content/json_schema.md b/docs/content/json_schema.md index ad97d630b..21f3f034b 100644 --- a/docs/content/json_schema.md +++ b/docs/content/json_schema.md @@ -74,6 +74,31 @@ This will result in the following JSON schema: You can insert this into the tools mentioned above and see the generated code. +## Variants and tagged unions + +`rfl::TaggedUnion` becomes `oneOf`: every alternative has a different tag, so a value +matches exactly one of them. + +`rfl::Variant` and `std::variant` become `anyOf`, because their alternatives can overlap: +`1` is both an `integer` and a `number`, and `{"width": 1, "height": 2}` matches both +`Square` and `Rectangle` from the example in [variants](../variants_and_tagged_unions). +`oneOf` would reject such values, even though reflect-cpp reads them without problems. + +If you know that the alternatives of your variants never overlap, you can pass +`rfl::VariantsAsOneOf` to get `oneOf` for `rfl::Variant` and `std::variant` as well: + +```cpp +const std::string json_schema = + rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +Warning: `oneOf` rejects values that match more than one alternative, so with this +processor the schema rejects `1` for `rfl::Variant`. Structs can overlap +as well, for instance when additional properties are allowed (see `rfl::NoExtraFields`). + +`std::optional` and `rfl::Generic` stay `anyOf` either way. `std::optional` is not +a variant, and the alternatives of `rfl::Generic` overlap (`1` is both an `integer` and a `number`). + ## Adding descriptions JSON schemata also often contain descriptions. reflect-cpp supports this as well. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..366043c02 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -45,6 +45,7 @@ reflect-cpp currently supports the following processors: - `rfl::NoFieldNames` - `rfl::NoOptionals` - `rfl::UnderlyingEnums` +- `rfl::VariantsAsOneOf` - `rfl::SnakeCaseToCamelCase` - `rfl::SnakeCaseToPascalCase` @@ -492,6 +493,19 @@ The resulting JSON string looks like this: {"radius":2.0,"color":1} ``` +### `rfl::VariantsAsOneOf` + +By default, the JSON schema describes `rfl::Variant` and `std::variant` as `anyOf`. +By passing the processor `rfl::VariantsAsOneOf` to `rfl::json::to_schema`, they +become `oneOf`: + +```cpp +rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +It only changes the schema, not reading or writing. Please refer to +the [JSON schema documentation](../json_schema) for details. + ### `rfl::SnakeCaseToCamelCase` Please refer to the example above. @@ -549,6 +563,42 @@ The resulting JSON string looks like this: {"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} ``` +## `rfl::TransformEnumNames` (`EnumSnakeCaseToKebabCase`, etc.) + +Applies a whole-enum wire-name casing transform to enum fields during reading, +writing, and JSON Schema generation. Resolved wire-name tables are cached once +per `(EnumType, EnumNameTransform)` pair. + +Built-in aliases: +- `rfl::EnumSnakeCaseToKebabCase` +- `rfl::EnumSnakeCaseToCamelCase` +- `rfl::EnumSnakeCaseToPascalCase` +- `rfl::EnumCamelCaseToSnakeCase` +- `rfl::EnumToLowerCase` +- `rfl::EnumToUpperCase` + +```cpp +enum class CostModel { t_count, two_qubit_gate_count, gate_count }; +struct Config { CostModel cost_model; }; + +const auto json_str = rfl::json::write( + Config{.cost_model = CostModel::two_qubit_gate_count}); +// {"cost_model":"two-qubit-gate-count"} +``` + +## `rfl::IntegerBounds` + +Opt-in schema processor that emits C++ integer width `minimum` and `maximum` +keywords in JSON Schema for signed and unsigned integer types (`int8_t`–`int64_t`, +`uint8_t`–`uint64_t`, etc.), excluding `bool`, character types (`char`, `wchar_t`, +`char8_t`, `char16_t`, `char32_t`), and `rfl::UnderlyingEnums`. + +```cpp +struct NetConfig { uint16_t port; }; +const auto schema = rfl::json::to_schema(); +// "port": {"type":"integer","minimum":0,"maximum":65535} +``` + ## Writing your own processors In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter. diff --git a/docs/content/supported_formats/capnproto.md b/docs/content/supported_formats/capnproto.md index 63f0a372b..442818af1 100644 --- a/docs/content/supported_formats/capnproto.md +++ b/docs/content/supported_formats/capnproto.md @@ -105,6 +105,34 @@ rfl::capnproto::write(person, std::cout) << std::endl; (Since Cap'n Proto is a binary format, the readability of this will be limited, but it might be useful for debugging). +## Reader options + +Cap'n Proto enforces a default traversal limit of 64 MiB (`8 * 1024 * 1024` words) and a default nesting limit of 64 when reading messages. You can pass a `capnp::ReaderOptions` struct to any `rfl::capnproto::read` overload (byte buffers, containers, explicit schemas, or `std::istream`) or `rfl::capnproto::read_unpacked` overload to raise the limit for large messages or tighten it for untrusted input: + +```cpp +capnp::ReaderOptions options; +options.traversalLimitInWords = 64ULL * 1024 * 1024; // 512 MiB + +const rfl::Result result = rfl::capnproto::read(bytes, options); +const rfl::Result from_stream = rfl::capnproto::read(my_istream, options); +``` + +Limit violations and corrupt or truncated messages are reported as `rfl::Error` via `rfl::Result` rather than throwing uncaught exceptions. + +## Unpacked flat-array reading and writing + +By default, `rfl::capnproto::write` and `rfl::capnproto::read` use Cap'n Proto's packed wire format. When exchanging messages in memory, over shared memory, or from `mmap`-backed buffers, you can skip packing and unpacking with `rfl::capnproto::write_unpacked` and `rfl::capnproto::read_unpacked`: + +```cpp +const kj::Array words = rfl::capnproto::write_unpacked(person); + +// Read directly from kj::Array, kj::ArrayPtr, +// std::span, or (const capnp::word*, size_t). +const rfl::Result result = rfl::capnproto::read_unpacked(words); +``` + +Both `write_unpacked` and `read_unpacked` accept an optional explicit `rfl::capnproto::Schema`, and `read_unpacked` also accepts an optional `capnp::ReaderOptions`. + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 00b4002cc..433cecb03 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -195,6 +195,80 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. +It returns an `rfl::Result`. + +```cpp +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional> + input_file; + rfl::Short<"p", rfl::Description<"Port to listen on", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", std::vector> tags; + Database database; +}; +``` + +`rfl::cli::usage("app", true).value()` is the usage line, where +optional arguments are in brackets, and one line per argument, with its +description and whether it is required. `rfl::cli::usage("app")` +gives only the usage line. + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Required. + --database.host= Required. + --database.port= Required. +``` + +Fields wrapped in `rfl::DefaultVal` are optional, and so are all fields if you +pass `rfl::DefaultIfMissing` (to both `read` and `usage`). The parser takes +the defaults of `rfl::DefaultVal` fields from a default-constructed struct. If +a struct with `rfl::DefaultVal` cannot be default-constructed (for instance +because a validator rejects another field's default value), it cannot be read, +and `usage` returns the error, as it does for two fields with the same short +name. + +Each argument is shown as the option table that `read` parses with (see +[Architecture](#architecture)) reads it: a `bool`, also inside a nested +struct, is a flag whose value can be left out (`--verbose[=]`), and +every other option takes a value (`--port=`). + +`rfl::Positional` and `rfl::Short` are found through the other wrappers, as +the parser does (see [Combining wrappers](#combining-wrappers)), so +`rfl::Description<"...", rfl::Positional>` is listed as a +positional argument. + +`read` does not handle `--help`: check `argv` for it and print `usage` +yourself: + +```cpp +int main(int argc, char* argv[]) { + if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + return 0; + } + const auto config = rfl::cli::read(argc, argv).value(); +} +``` + ## Supported types | Type | CLI format | Notes | @@ -239,6 +313,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..b1bd26bdc 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,60 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Read and write flags + +`rfl::json` provides `inline constexpr` flag constants (combinable with `|`) so you do not need to reference underlying `YYJSON_*` constants directly. + +### Read flags (`rfl::json::read` and `rfl::json::load`) + +| Flag | Description | +| --- | --- | +| `rfl::json::allow_comments` | Allow C-style single-line (`//`) and multi-line (`/* */`) comments | +| `rfl::json::allow_trailing_commas` | Allow a single trailing comma at the end of an object or array | +| `rfl::json::jsonc` | Shorthand for `allow_comments \| allow_trailing_commas` (JSONC) | +| `rfl::json::allow_bom` | Allow and skip a leading UTF-8 BOM *(requires yyjson >= 0.11.0)* | +| `rfl::json::stop_when_done` | Stop after the first JSON value and ignore trailing content | +| `rfl::json::read_allow_inf_and_nan` | Allow `Inf`, `Infinity`, and `NaN` numbers and literals | +| `rfl::json::read_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences in string values | +| `rfl::json::allow_ext_number` | Allow hex numbers, leading/trailing decimal points, and leading `+` *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_escape` | Allow extended string escape sequences *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_whitespace` | Allow extended whitespace characters *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_single_quoted_str` | Allow single-quoted strings *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_unquoted_key` | Allow unquoted object keys *(requires yyjson >= 0.12.0)* | +| `rfl::json::json5` | Allow JSON5 syntax *(requires yyjson >= 0.12.0)* | + +Example reading JSONC: + +```cpp +const auto result = rfl::json::read( + jsonc_string, rfl::json::allow_comments | rfl::json::allow_trailing_commas); + +// Or using the convenience alias: +const auto result2 = rfl::json::read(jsonc_string, rfl::json::jsonc); +``` + +### Write flags (`rfl::json::write`, `rfl::json::save`, and `rfl::json::to_schema`) + +| Flag | Description | +| --- | --- | +| `rfl::json::pretty` | Pretty-print with 4-space indentation | +| `rfl::json::pretty_two_spaces` | Pretty-print with 2-space indentation (overrides `pretty`) *(requires yyjson >= 0.7.0)* | +| `rfl::json::newline_at_end` | Append a trailing `\n` to the output *(requires yyjson >= 0.9.0)* | +| `rfl::json::escape_unicode` | Escape non-ASCII characters as `\uXXXX` for ASCII-only output | +| `rfl::json::escape_slashes` | Escape `/` as `\/` | +| `rfl::json::write_allow_inf_and_nan` | Write `Inf`/`NaN` as `Infinity`/`NaN` literals (non-standard) | +| `rfl::json::inf_and_nan_as_null` | Write `Inf`/`NaN` as `null` (overrides `write_allow_inf_and_nan`) | +| `rfl::json::write_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences when encoding strings | + +Example combining write flags: + +```cpp +const std::string json_string = rfl::json::write( + person, rfl::json::pretty_two_spaces | rfl::json::newline_at_end); +``` + +> Note: `read_allow_inf_and_nan` / `write_allow_inf_and_nan` and `read_allow_invalid_unicode` / `write_allow_invalid_unicode` are prefixed with `read_` / `write_` because the underlying read and write flag bit values differ. Low-level/unsafe read flags (`YYJSON_READ_INSITU`, `YYJSON_READ_NUMBER_AS_RAW`, `YYJSON_READ_BIGNUM_AS_RAW`) are intentionally not exposed as `rfl::json` aliases (`YYJSON_READ_INSITU` is rejected at runtime). + ## Custom constructors One of the great things about C++ is that it gives you control over @@ -118,3 +172,34 @@ rfl::Result Person::from_json_obj(const JSONVar& _obj) { This will force the compiler to only compile the JSON parsing when the source file is compiled. +## Raw JSON Passthrough (`rfl::json::Raw`) + +Use `rfl::json::Raw` when a struct contains a JSON subtree that you want to +pass through without converting into intermediate C++ types: + +```cpp +struct Envelope { + int id; + rfl::json::Raw payload; +}; + +const auto env = rfl::json::read( + R"({"id":1,"payload":{"nested":[1,2,3]}})").value(); +const auto out = rfl::json::write(env); +``` + +Construct `rfl::json::Raw` from text using the validating factory +`rfl::json::Raw::from_string(...)` (which returns `rfl::Result` +after checking strict RFC 8259 JSON). When you already hold validated JSON +(such as output from `rfl::json::write`), `rfl::json::Raw::from_trusted_string(...)` +constructs a `Raw` without re-parsing; writing emits the stored JSON text +verbatim via `yyjson_mut_rawncpy`. + +On read, `rfl::json::Raw` captures the parsed `yyjson` subtree via +`yyjson_val_write_opts` with strict RFC 8259 formatting (flag `0`), which +canonicalizes whitespace and rejects non-standard values such as `NaN` or +`Infinity` even when parsed with `YYJSON_READ_ALLOW_INF_AND_NAN`. Pass +`YYJSON_READ_BIGNUM_AS_RAW` to `rfl::json::read` if integers wider than 64 bits +must be preserved verbatim. `rfl::json::Raw` is supported with `rfl::json` +(and `rfl::Generic` conversions / JSON Schema) only. + diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..0ed1b41d2 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -23,6 +23,7 @@ #include "rfl/DefaultVal.hpp" #include "rfl/Description.hpp" #include "rfl/DurationsAsCount.hpp" +#include "rfl/EnumNames.hpp" #include "rfl/EnumNamesOnly.hpp" #include "rfl/ExtraFields.hpp" #include "rfl/FailFast.hpp" @@ -30,6 +31,7 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/IntegerBounds.hpp" #include "rfl/Literal.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" @@ -51,12 +53,15 @@ #include "rfl/SnakeCaseToCamelCase.hpp" #include "rfl/SnakeCaseToKebabCase.hpp" #include "rfl/SnakeCaseToPascalCase.hpp" +#include "rfl/StringLiteral.hpp" #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" +#include "rfl/TransformEnumNames.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" #include "rfl/Variant.hpp" +#include "rfl/VariantsAsOneOf.hpp" #include "rfl/Vectorstring.hpp" #include "rfl/always_false.hpp" #include "rfl/apply.hpp" @@ -92,6 +97,7 @@ #include "rfl/to_named_tuple.hpp" #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" +#include "rfl/type_name.hpp" #include "rfl/type_name_t.hpp" #include "rfl/view_t.hpp" #include "rfl/visit.hpp" diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index 5b61bb2bf..0e76a6e8e 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -1,6 +1,7 @@ #ifndef RFL_ALLOF_HPP_ #define RFL_ALLOF_HPP_ +#include #include #include @@ -33,14 +34,20 @@ struct AllOf { private: template static rfl::Result validate_impl(T _value) noexcept { - if constexpr (sizeof...(Tail) == 0) { - return Head::validate(std::move(_value)); - } else { + try { auto res = Head::validate(std::move(_value)); if (!res) { return res; } - return validate_impl(std::move(*res)); + if constexpr (sizeof...(Tail) == 0) { + return res; + } else { + return validate_impl(std::move(*res)); + } + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } }; diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index eb6425401..91169998f 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ANYOF_HPP_ #define RFL_ANYOF_HPP_ -#include +#include #include #include #include @@ -37,13 +37,13 @@ struct AnyOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected at least one of the following validations to pass, but " - "none of them did:"; + std::string msg = + "Expected at least one of the following validations to pass, but " + "none of them did:"; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template diff --git a/include/rfl/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/EnumNames.hpp b/include/rfl/EnumNames.hpp new file mode 100644 index 000000000..3a7a2d515 --- /dev/null +++ b/include/rfl/EnumNames.hpp @@ -0,0 +1,150 @@ +#ifndef RFL_ENUMNAMES_HPP_ +#define RFL_ENUMNAMES_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Processors.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" + +namespace rfl { + +/// Pair of `(enumerator, wire_name)` for per-enumerator overrides in +/// `rfl::EnumNames`. +template +using EnumOverride = std::pair; + +/// Specialize `rfl::EnumNames` to customize wire names for enum `E` across +/// JSON, CLI, Generic, YAML, XML, and JSON Schema without duplicating +/// enumerators as `rfl::Literal<...>`. +/// +/// Supported members (individually or combined; `overrides` takes precedence): +/// - `static constexpr EnumNameTransform transform = EnumNameTransform::snake_to_kebab;` +/// OR `static std::string transform(std::string_view _raw_name);` +/// (any return type convertible or explicitly constructible into `std::string`, +/// such as `std::string_view`, is accepted) +/// - `static constexpr std::array, N> overrides = {{ ... }};` +/// OR `static std::span> overrides();` +template +struct EnumNames {}; + +namespace internal { + +template +struct is_std_span : std::false_type {}; + +template +struct is_std_span> : std::true_type {}; + +template +concept EnumOverrideContiguousRange = + (std::is_array_v> && + std::same_as< + std::remove_cv_t>>, + EnumOverride>) || + requires(const std::remove_reference_t& _r) { + { _r.data() } -> std::convertible_to*>; + { _r.size() } -> std::convertible_to; + }; + +template +concept BorrowedEnumOverridesResult = + std::is_lvalue_reference_v || + is_std_span>::value; + +template +concept HasEnumOverridesVar = requires { + requires EnumOverrideContiguousRange::overrides), E>; +}; + +template +concept HasAnyEnumOverridesFn = requires { + requires EnumOverrideContiguousRange::overrides()), E>; +}; + +template +concept HasEnumOverridesFn = + HasAnyEnumOverridesFn && + BorrowedEnumOverridesResult::overrides())>; + +template +concept HasEnumTransformConst = requires { + { EnumNames::transform } -> std::convertible_to; +}; + +template +concept HasEnumTransformFn = requires(std::string_view _s) { + requires std::constructible_from::transform(_s))>; +}; + +template +inline constexpr bool has_custom_enum_names_for_transform_v = + HasEnumOverridesVar> || + HasAnyEnumOverridesFn> || + HasEnumTransformConst> || + HasEnumTransformFn> || + (_transform != EnumNameTransform::none); + +template > +inline constexpr bool has_custom_enum_names_v = + has_custom_enum_names_for_transform_v< + E, enum_name_transform_v>; + +template +inline std::span>> +get_enum_overrides() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyEnumOverridesFn || HasEnumOverridesFn, + "rfl::EnumNames::overrides() must return a borrowed contiguous range " + "(for example, std::span> or const auto&)."); + if constexpr (HasEnumOverridesFn) { + auto&& r = EnumNames::overrides(); + return std::span>(std::data(r), std::size(r)); + } else if constexpr (HasEnumOverridesVar) { + return std::span>(std::data(EnumNames::overrides), + std::size(EnumNames::overrides)); + } else { + return {}; + } +} + +template +inline std::string resolve_enum_wire_name_for_transform( + const E _val, const std::string_view _raw_name) { + using U = std::remove_cvref_t; + for (const auto& [e, wire] : get_enum_overrides()) { + if (e == _val) { + return std::string(wire); + } + } + if constexpr (HasEnumTransformFn) { + return std::string(EnumNames::transform(_raw_name)); + } else if constexpr (HasEnumTransformConst) { + return apply_enum_name_transform(_raw_name, EnumNames::transform); + } else if constexpr (_transform != EnumNameTransform::none) { + return apply_enum_name_transform(_raw_name, _transform); + } else { + return std::string(_raw_name); + } +} + +template > +inline std::string resolve_enum_wire_name(const E _val, + const std::string_view _raw_name) { + return resolve_enum_wire_name_for_transform< + E, enum_name_transform_v>(_val, _raw_name); +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_ENUMNAMES_HPP_ diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index 46f79f65f..7bec8d867 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 @@ -196,10 +237,10 @@ class RFL_API Generic { Result to_string() const noexcept; /// Returns the underlying variant. - VariantType& variant() noexcept { return value_; }; + VariantType& variant() noexcept { return value_; } /// Returns the underlying variant. - const VariantType& variant() const noexcept { return value_; }; + const VariantType& variant() const noexcept { return value_; } /// Equality comparison. Two Generics are equal if they hold the same /// alternative and the underlying values compare equal. @@ -216,6 +257,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/IntegerBounds.hpp b/include/rfl/IntegerBounds.hpp new file mode 100644 index 000000000..d63b77845 --- /dev/null +++ b/include/rfl/IntegerBounds.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_INTEGERBOUNDS_HPP_ +#define RFL_INTEGERBOUNDS_HPP_ + +#include + +namespace rfl { + +/// Opt-in JSON Schema processor: emit `minimum` and `maximum` bounds matching +/// C++ integer widths (`int8_t`..`int64_t`, `uint8_t`..`uint64_t`, `short`, +/// `int`, `long`, `long long`, and their unsigned counterparts; excludes +/// `bool` and character types whose signedness is platform-dependent). +struct IntegerBounds { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif // RFL_INTEGERBOUNDS_HPP_ diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 4208d7713..7aa3e845c 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)); +} + +} // 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."); } /// 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/MetaField.hpp b/include/rfl/MetaField.hpp index 192c7e6c5..62ac12294 100644 --- a/include/rfl/MetaField.hpp +++ b/include/rfl/MetaField.hpp @@ -21,11 +21,11 @@ class MetaField { /// Returns the name of the field. /// @return The field name as it appears in the struct - const std::string& name() const { return name_; }; + const std::string& name() const { return name_; } /// Returns the type information of the field. /// @return A string describing the field's type - const std::string& type() const { return type_; }; + const std::string& type() const { return type_; } private: /// The name of the field. diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 381fe8811..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."); }; // ---------------------------------------------------------------------------- @@ -716,7 +735,14 @@ class NamedTuple<> { using Values = rfl::Tuple<>; /// @brief Default constructor for empty NamedTuple. - 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/Object.hpp b/include/rfl/Object.hpp index 7c36cb5b0..1360eda11 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 diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 8b302cf13..5ef86d7b4 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ONEOF_HPP_ #define RFL_ONEOF_HPP_ -#include +#include #include #include #include @@ -39,40 +39,32 @@ struct OneOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message indicating the validation failure static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected exactly 1 out of " << sizeof...(Cs) + 1 - << " validations to pass, but " << sizeof...(Cs) + 1 - _errors.size() - << " of them did. The following errors were generated: "; + std::string msg = "Expected exactly 1 out of " + + std::to_string(sizeof...(Cs) + 1) + + " validations to pass, but " + + std::to_string(sizeof...(Cs) + 1 - _errors.size()) + + " of them did. The following errors were generated: "; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - return Head::validate(_value) - .and_then([&](auto&&) -> rfl::Result { - if constexpr (sizeof...(Tail) == 0) { - if (_errors.size() == sizeof...(Cs)) { - return _value; - // The AI suggests return std::forward(_result); - // is it correct in this context? - } - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }) - .or_else([&](auto&& _err) -> rfl::Result { - _errors.emplace_back(std::move(_err)); - if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }); + auto res = Head::validate(_value); + if (!res) { + _errors.emplace_back(std::move(res).error()); + } + if constexpr (sizeof...(Tail) == 0) { + if (_errors.size() == sizeof...(Cs)) { + return _value; + } + return error(make_error_message(_errors)); + } else { + return validate_impl(_value, std::move(_errors)); + } } }; diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index b1dcbc040..a22e569a7 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -1,7 +1,6 @@ #ifndef RFL_PATTERNVALIDATOR_HPP_ #define RFL_PATTERNVALIDATOR_HPP_ -#include #include #include @@ -35,10 +34,8 @@ struct PatternValidator { ctll::construct_from_pointer, _regex.arr_.data()}>(_str)) { return std::move(_str); } else { - std::stringstream stream; - stream << "String '" << _str << "' did not match format '" << _name.str() - << "': '" << _regex.str() << "'."; - return error(stream.str()); + return error("String '" + _str + "' did not match format '" + + _name.str() + "': '" + _regex.str() + "'."); } } diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index 5148b0b00..d3c0e0ec7 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -1,7 +1,7 @@ #ifndef RFL_SIZE_HPP_ #define RFL_SIZE_HPP_ -#include +#include #include #include "Ref.hpp" diff --git a/include/rfl/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 a940e0fcb..8129848ae 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -73,8 +73,10 @@ class Timestamp { static Result from_string(const char* _str) noexcept { try { return Timestamp(_str); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while parsing timestamp."); } } @@ -82,7 +84,7 @@ class Timestamp { /// This is an alternative to the throwing constructor for error handling without exceptions. /// @param _str The string to parse in the format specified by the template parameter /// @return Result containing the Timestamp if parsing succeeded, or an error otherwise - static Result from_string(const std::string& _str) { + static Result from_string(const std::string& _str) noexcept { return from_string(_str.c_str()); } diff --git a/include/rfl/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/Tuple.hpp b/include/rfl/Tuple.hpp index ee12e54c2..c32d06bd0 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_]; @@ -59,16 +81,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 +110,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 +150,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 +165,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 9be58bf61..4a0cd1243 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -34,8 +34,10 @@ struct Validator { static Result from_value(const T& _value) noexcept { try { return wrap_validated(ValidationType::validate(_value)); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } @@ -46,8 +48,10 @@ struct Validator { static Result from_value(T&& _value) noexcept { try { return wrap_validated(ValidationType::validate(std::move(_value))); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index 018edca72..ee7a03dca 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,30 @@ 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()); + Variant() : index_(0) { + ::new (static_cast(data_.data())) FirstAlternative(); } /// @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 +69,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 +78,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 +112,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 +144,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 +186,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 +195,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 +210,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 +269,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 +278,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 +308,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 +360,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 +391,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 +422,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 +437,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 @@ -774,7 +596,7 @@ namespace std { template void swap(rfl::Variant& _lhs, rfl::Variant& _rhs) noexcept { _lhs.swap(_rhs); -}; +} } // namespace std #endif diff --git a/include/rfl/VariantsAsOneOf.hpp b/include/rfl/VariantsAsOneOf.hpp new file mode 100644 index 000000000..0b71c9752 --- /dev/null +++ b/include/rfl/VariantsAsOneOf.hpp @@ -0,0 +1,33 @@ +#ifndef RFL_VARIANTSASONEOF_HPP_ +#define RFL_VARIANTSASONEOF_HPP_ + +#include + +namespace rfl { + +/// A processor that makes the JSON schema describe rfl::Variant and +/// std::variant as oneOf instead of anyOf. +/// This is a marker type (doesn't modify data) that changes the generated +/// schema. It has no effect on reading or writing. +/// By default, untagged variants are described as anyOf, because their +/// alternatives can overlap: 1 matches both alternatives of +/// rfl::Variant, and oneOf would reject it. rfl::TaggedUnion is +/// always described as oneOf, and std::optional and rfl::Generic always as +/// anyOf. +/// Usage: rfl::json::to_schema() +struct VariantsAsOneOf { + public: + /// Identity process function - returns the named tuple unchanged. + /// The actual change happens in the schema generation, not here. + /// @tparam StructType The struct type being processed + /// @param _named_tuple The named tuple representation of the struct + /// @return The same named tuple (unchanged) + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/atomic/is_atomic.hpp b/include/rfl/atomic/is_atomic.hpp index 93312de28..303468e3f 100644 --- a/include/rfl/atomic/is_atomic.hpp +++ b/include/rfl/atomic/is_atomic.hpp @@ -19,7 +19,7 @@ template struct is_atomic { static constexpr bool value = false; using RemoveAtomicT = T; - static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); }; + static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); } }; template @@ -28,7 +28,7 @@ struct is_atomic> { using RemoveAtomicT = T; static void set(RemoveAtomicT&& val, std::atomic* _t) { _t->store(std::forward(val), std::memory_order_relaxed); - }; + } }; template <> diff --git a/include/rfl/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/NumericListParser.hpp b/include/rfl/capnproto/NumericListParser.hpp new file mode 100644 index 000000000..d79fa460c --- /dev/null +++ b/include/rfl/capnproto/NumericListParser.hpp @@ -0,0 +1,186 @@ +#ifndef RFL_CAPNPROTO_NUMERICLISTPARSER_HPP_ +#define RFL_CAPNPROTO_NUMERICLISTPARSER_HPP_ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../parsing/Parent.hpp" +#include "../parsing/Parser.hpp" +#include "../parsing/ParserArray.hpp" +#include "../parsing/VectorParser.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl::internal::capnproto { + +template +inline constexpr bool is_exact_capnp_scalar_v = + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v; + +template +inline bool matches_capnp_scalar_type(const capnp::Type& _type) { + if constexpr (std::is_same_v) { + return _type.isBool(); + } else if constexpr (std::is_same_v) { + return _type.isInt32(); + } else if constexpr (std::is_same_v) { + return _type.isUInt32(); + } else if constexpr (std::is_same_v) { + return _type.isInt64(); + } else if constexpr (std::is_same_v) { + return _type.isUInt64(); + } else if constexpr (std::is_same_v) { + return _type.isFloat32(); + } else if constexpr (std::is_same_v) { + return _type.isFloat64(); + } else { + return false; + } +} + +} // namespace rfl::internal::capnproto + +namespace rfl::parsing { + +template + requires rfl::internal::capnproto::is_exact_capnp_scalar_v +struct Parser, + ProcessorsType> + : VectorParser, + ProcessorsType> { + using R = capnproto::Reader; + using W = capnproto::Writer; + using Type = std::vector; + using Base = VectorParser; + + static Result read(const R& _r, + const typename R::InputVarType& _var) noexcept { + if (_var.val_.getType() != capnp::DynamicValue::LIST) { + return error("Could not cast to a list."); + } + try { + const auto dyn_list = _var.val_.as(); + if (!rfl::internal::capnproto::matches_capnp_scalar_type( + dyn_list.getSchema().getElementType())) [[unlikely]] { + return Base::read(_r, _var); + } + const auto typed = dyn_list.as>(); + const auto n = typed.size(); + Type res; + res.resize(n); + for (unsigned int i = 0; i < n; ++i) { + res[i] = typed[i]; + } + return res; + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); + } + } + + template + static void write(const W& _w, const Type& _vec, const ParentType& _parent) { + auto arr = Parent::add_array(_w, _vec.size(), _parent); + if (rfl::internal::capnproto::matches_capnp_scalar_type( + arr.val_.getSchema().getElementType())) [[likely]] { + auto typed = arr.val_.template as>(); + const auto n = typed.size(); + for (unsigned int i = 0; i < n; ++i) { + typed.set(i, _vec[i]); + } + } else { + const auto new_parent = typename Parent::Array{&arr}; + for (const T v : _vec) { + Parser::write(_w, v, new_parent); + } + } + _w.end_array(&arr); + } +}; + +template + requires rfl::internal::capnproto::is_exact_capnp_scalar_v +struct Parser, + ProcessorsType> + : ParserArray { + using R = capnproto::Reader; + using W = capnproto::Writer; + using Type = std::array; + using Base = ParserArray; + + static Result read(const R& _r, + const typename R::InputVarType& _var) noexcept { + if (_var.val_.getType() != capnp::DynamicValue::LIST) { + return error("Could not cast to a list."); + } + try { + const auto dyn_list = _var.val_.as(); + if (!rfl::internal::capnproto::matches_capnp_scalar_type( + dyn_list.getSchema().getElementType())) [[unlikely]] { + return Base::read(_r, _var); + } + const auto n = dyn_list.size(); + if (static_cast(n) != N) { + return error("Expected " + std::to_string(N) + " elements, got " + + std::to_string(n) + "."); + } + Type res{}; + if constexpr (N != 0) { + const auto typed = dyn_list.as>(); + for (std::size_t i = 0; i < N; ++i) { + res[i] = typed[static_cast(i)]; + } + } + return res; + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); + } + } + + template + static void write(const W& _w, const Type& _arr, const ParentType& _parent) { + auto arr = Parent::add_fixed_array(_w, N, _parent); + if constexpr (N != 0) { + if (rfl::internal::capnproto::matches_capnp_scalar_type( + arr.val_.getSchema().getElementType())) [[likely]] { + auto typed = arr.val_.template as>(); + for (std::size_t i = 0; i < N; ++i) { + typed.set(static_cast(i), _arr[i]); + } + } else { + const auto new_parent = typename Parent::Array{&arr}; + for (const T v : _arr) { + Parser::write(_w, v, new_parent); + } + } + } else { + static_cast(_arr); + } + _w.end_array(&arr); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/capnproto/Parser.hpp b/include/rfl/capnproto/Parser.hpp index 157f4d848..ea6a27c8f 100644 --- a/include/rfl/capnproto/Parser.hpp +++ b/include/rfl/capnproto/Parser.hpp @@ -7,6 +7,7 @@ #include "../always_false.hpp" #include "../internal/no_field_names_v.hpp" #include "../parsing/Parser.hpp" +#include "NumericListParser.hpp" #include "Reader.hpp" #include "Writer.hpp" diff --git a/include/rfl/capnproto/Reader.hpp b/include/rfl/capnproto/Reader.hpp index 31bbfdb50..ec383b6f7 100644 --- a/include/rfl/capnproto/Reader.hpp +++ b/include/rfl/capnproto/Reader.hpp @@ -2,10 +2,14 @@ #define RFL_CAPNPROTO_READER_HPP_ #include +#include +#include +#include #include #include #include +#include #include #include @@ -62,7 +66,8 @@ class RFL_API Reader { if (type != capnp::DynamicValue::TEXT) { return error("Could not cast to string."); } - return std::string(_var.val_.as().cStr()); + const auto text = _var.val_.as(); + return std::string(text.cStr(), text.size()); } else if constexpr (std::is_same, rfl::Bytestring>() || @@ -150,70 +155,125 @@ class RFL_API Reader { template std::optional read_array(const ArrayReader& _array_reader, const InputArrayType& _arr) const noexcept { - if constexpr (requires { _array_reader.reserve(_arr.val_.size()); }) { - if (auto err = _array_reader.reserve(_arr.val_.size())) { - return err; + try { + if constexpr (requires { _array_reader.reserve(_arr.val_.size()); }) { + if (auto err = _array_reader.reserve(_arr.val_.size())) { + return err; + } } - } - for (auto element : _arr.val_) { - auto err = _array_reader.read(InputVarType{std::move(element)}); - if (err) { - return err; + for (auto element : _arr.val_) { + auto err = _array_reader.read(InputVarType{std::move(element)}); + if (err) { + return err; + } } + return std::nullopt; + } catch (const kj::Exception& e) { + return Error{e.getDescription().cStr()}; + } catch (const std::exception& e) { + return Error{e.what()}; + } catch (...) { + return Error{"Unknown Cap'n Proto error."}; } - return std::nullopt; } template std::optional read_map(const MapReader& _map_reader, const InputMapType& _map) const noexcept { try { - const auto entries = _map.val_.get("entries").as(); + const auto map_schema = _map.val_.getSchema(); + const auto map_fields = map_schema.getFields(); + const auto entries_field = + (map_fields.size() > 0 && + std::string_view(map_fields[0].getProto().getName().cStr(), + map_fields[0].getProto().getName().size()) == + "entries") + ? map_fields[0] + : map_schema.getFieldByName("entries"); + const auto entries = + _map.val_.get(entries_field).as(); + const auto entry_schema = + entries.getSchema().getElementType().asStruct(); + const auto entry_fields = entry_schema.getFields(); + const auto key_field = + (entry_fields.size() > 0 && + std::string_view(entry_fields[0].getProto().getName().cStr(), + entry_fields[0].getProto().getName().size()) == + "key") + ? entry_fields[0] + : entry_schema.getFieldByName("key"); + const auto value_field = + (entry_fields.size() > 1 && + std::string_view(entry_fields[1].getProto().getName().cStr(), + entry_fields[1].getProto().getName().size()) == + "value") + ? entry_fields[1] + : entry_schema.getFieldByName("value"); for (auto entry : entries) { auto s = entry.template as(); - const auto key = s.get("key").as(); + const auto key = s.get(key_field).as(); _map_reader.read(std::string_view(key.cStr(), key.size()), - InputVarType{s.get("value")}); + InputVarType{s.get(value_field)}); } return std::nullopt; - } catch (std::exception& e) { + } catch (const kj::Exception& e) { + return Error{e.getDescription().cStr()}; + } catch (const std::exception& e) { return Error{e.what()}; + } catch (...) { + return Error{"Unknown Cap'n Proto error."}; } } template std::optional read_object(const ObjectReader& _object_reader, const InputObjectType& _obj) const noexcept { - const auto fields = _obj.val_.getSchema().getFields(); - if constexpr (requires { - std::make_integer_sequence{}; - }) { - if (fields.size() == ObjectReader::size()) { - [&](std::integer_sequence) { - (_object_reader.read(std::integral_constant{}, - InputVarType{_obj.val_.get(fields[Is])}), - ...); - }(std::make_integer_sequence{}); - return std::nullopt; + try { + const auto fields = _obj.val_.getSchema().getFields(); + if constexpr (requires { + std::make_integer_sequence{}; + }) { + if (fields.size() == ObjectReader::size()) { + [&](std::integer_sequence) { + (_object_reader.read(std::integral_constant{}, + InputVarType{_obj.val_.get(fields[Is])}), + ...); + }(std::make_integer_sequence{}); + return std::nullopt; + } } + int i = 0; + for (auto field : fields) { + _object_reader.read(i++, InputVarType{_obj.val_.get(field)}); + } + return std::nullopt; + } catch (const kj::Exception& e) { + return Error{e.getDescription().cStr()}; + } catch (const std::exception& e) { + return Error{e.what()}; + } catch (...) { + return Error{"Unknown Cap'n Proto error."}; } - int i = 0; - for (auto field : fields) { - _object_reader.read(i++, InputVarType{_obj.val_.get(field)}); - } - return std::nullopt; } template rfl::Result read_union( const InputUnionType& _union) const noexcept { - const auto opt_pair = identify_discriminant(_union); - if (!opt_pair) { - return error("Could not get the discriminant."); + try { + const auto opt_pair = identify_discriminant(_union); + if (!opt_pair) { + return error("Could not get the discriminant."); + } + const auto& [field, disc] = *opt_pair; + return UnionReaderType::read(*this, disc, + InputVarType{_union.val_.get(field)}); + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); } - const auto& [field, disc] = *opt_pair; - return UnionReaderType::read(*this, disc, - InputVarType{_union.val_.get(field)}); } template @@ -221,8 +281,12 @@ class RFL_API Reader { const InputVarType& _var) const noexcept { try { return T::from_capnproto_obj(_var); - } catch (std::exception& e) { + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); } } diff --git a/include/rfl/capnproto/Writer.hpp b/include/rfl/capnproto/Writer.hpp index f61967714..27632baac 100644 --- a/include/rfl/capnproto/Writer.hpp +++ b/include/rfl/capnproto/Writer.hpp @@ -2,9 +2,12 @@ #define RFL_CAPNPROTO_WRITER_HPP_ #include +#include #include +#include #include +#include #include #include #include @@ -15,6 +18,7 @@ #include "../always_false.hpp" #include "../common.hpp" #include "../internal/is_literal.hpp" +#include "../internal/ptr_cast.hpp" namespace rfl::capnproto { @@ -26,12 +30,16 @@ class RFL_API Writer { }; struct CapnProtoOutputMap { - capnp::DynamicStruct::Builder val_; + capnp::DynamicList::Builder entries_; + capnp::StructSchema::Field key_field_; + capnp::StructSchema::Field value_field_; size_t ix_ = 0; }; struct CapnProtoOutputObject { capnp::DynamicStruct::Builder val_; + capnp::StructSchema::FieldList fields_; + unsigned int ix_ = 0; }; struct CapnProtoOutputUnion { @@ -53,14 +61,14 @@ class RFL_API Writer { ~Writer(); template - OutputArrayType array_as_root(const T /*_size*/) const { + OutputArrayType array_as_root(const T) const { static_assert(always_false_v, "In Cap'n Proto, root values must always be structs."); throw std::runtime_error("Unsupported."); } template - OutputMapType map_as_root(const T /*_size*/) const { + OutputMapType map_as_root(const T) const { static_assert(always_false_v, "In Cap'n Proto, root values must always be structs."); throw std::runtime_error("Unsupported."); @@ -83,7 +91,7 @@ class RFL_API Writer { } template - OutputVarType value_as_root(const T& /*_var*/) const { + OutputVarType value_as_root(const T&) const { static_assert(always_false_v, "In Cap'n Proto, root values must always be structs."); throw std::runtime_error("Unsupported."); @@ -156,37 +164,41 @@ class RFL_API Writer { template OutputVarType add_value_to_array(const T& _var, OutputArrayType* _parent) const { - if constexpr (std::is_same, std::string>()) { - _parent->val_.set(_parent->ix_++, _var.c_str()); + using U = std::remove_cvref_t; + if constexpr (internal::is_literal_v) { + return add_value_to_array(_var.value(), _parent); + + } else if constexpr (std::is_same_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), + capnp::Text::Reader(_var.c_str(), _var.size())); - } else if constexpr (std::is_same, - rfl::Bytestring>() || - std::is_same, - rfl::Vectorstring>()) { + } else if constexpr (std::is_same_v || + std::is_same_v) { const auto array_ptr = kj::ArrayPtr( internal::ptr_cast(_var.data()), _var.size()); - _parent->val_.set(_parent->ix_++, capnp::Data::Reader(array_ptr)); - - } else if constexpr (std::is_same, bool>()) { - _parent->val_.set(_parent->ix_++, _var); + _parent->val_.set(safe_size_to_uint(_parent->ix_++), + capnp::Data::Reader(array_ptr)); - } else if constexpr (std::is_same, float>()) { - _parent->val_.set(_parent->ix_++, _var); + } else if constexpr (std::is_same_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), _var); - } else if constexpr (std::is_same, double>()) { - _parent->val_.set(_parent->ix_++, _var); + } else if constexpr (std::is_same_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), _var); - } else if constexpr (std::is_floating_point>()) { - _parent->val_.set(_parent->ix_++, static_cast(_var)); + } else if constexpr (std::is_same_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), _var); - } else if constexpr (std::is_unsigned>()) { - _parent->val_.set(_parent->ix_++, static_cast(_var)); + } else if constexpr (std::is_floating_point_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), + static_cast(_var)); - } else if constexpr (std::is_integral>()) { - _parent->val_.set(_parent->ix_++, static_cast(_var)); + } else if constexpr (std::is_unsigned_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), + static_cast(_var)); - } else if constexpr (internal::is_literal_v) { - return add_value_to_array(_var.value(), _parent); + } else if constexpr (std::is_integral_v) { + _parent->val_.set(safe_size_to_uint(_parent->ix_++), + static_cast(_var)); } else { static_assert(rfl::always_false_v, "Unsupported type."); @@ -197,107 +209,109 @@ class RFL_API Writer { template OutputVarType add_value_to_map(const std::string_view& _name, const T& _var, OutputMapType* _parent) const { - auto entries = OutputArrayType{ - .val_ = _parent->val_.get("entries").as(), - .ix_ = _parent->ix_++}; - auto new_entry = add_object_to_array(2, &entries); - add_value_to_object("key", std::string(_name), &new_entry); - return add_value_to_object("value", _var, &new_entry); + auto entry = init_map_entry(_name, _parent); + set_field_value(&entry, _parent->value_field_, _var); + return OutputVarType{}; } template OutputVarType add_value_to_object(const std::string_view& _name, const T& _var, OutputObjectType* _parent) const { - if constexpr (std::is_same, std::string>()) { - _parent->val_.set(to_kj_string_ptr(_name), _var.c_str()); - - } else if constexpr (std::is_same, - rfl::Bytestring>()) { - const auto array_ptr = kj::ArrayPtr( - internal::ptr_cast(_var.data()), _var.size()); - _parent->val_.set(to_kj_string_ptr(_name), - capnp::Data::Reader(array_ptr)); - - } else if constexpr (std::is_same, bool>()) { - _parent->val_.set(to_kj_string_ptr(_name), _var); + const auto field = next_field(_parent, _name); + set_field_value(&_parent->val_, field, _var); + return OutputVarType{}; + } - } else if constexpr (std::is_same, float>()) { - _parent->val_.set(to_kj_string_ptr(_name), _var); + template + OutputVarType add_value_to_union(const size_t _index, const T& _var, + OutputUnionType* _parent) const { + const auto field = + _parent->val_.getSchema().getFields()[safe_size_to_uint(_index)]; + set_field_value(&_parent->val_, field, _var); + return OutputVarType{}; + } - } else if constexpr (std::is_same, double>()) { - _parent->val_.set(to_kj_string_ptr(_name), _var); + void end_array(OutputArrayType*) const {} - } else if constexpr (std::is_floating_point>()) { - _parent->val_.set(to_kj_string_ptr(_name), static_cast(_var)); + void end_map(OutputMapType*) const {} - } else if constexpr (std::is_unsigned>()) { - _parent->val_.set(to_kj_string_ptr(_name), - static_cast(_var)); + void end_object(OutputObjectType*) const {} - } else if constexpr (std::is_integral>()) { - _parent->val_.set(to_kj_string_ptr(_name), - static_cast(_var)); + private: + static unsigned int safe_size_to_uint(const size_t _size) { + if (_size > static_cast(std::numeric_limits::max())) + [[unlikely]] { + throw std::overflow_error( + "size_t value is too big to fit into an unsigned int."); + } + return static_cast(_size); + } - } else if constexpr (internal::is_literal_v) { - return add_value_to_object(_name, _var.value(), _parent); + static kj::StringPtr to_kj_string_ptr(const std::string_view& _str) { + return kj::StringPtr(_str.data(), _str.size()); + } - } else { - static_assert(rfl::always_false_v, "Unsupported type."); + static capnp::StructSchema::Field next_field(OutputObjectType* _parent, + const std::string_view& _name) { + if (_parent->ix_ < _parent->fields_.size()) [[likely]] { + const auto field = _parent->fields_[_parent->ix_]; + const auto name = field.getProto().getName(); + if (std::string_view(name.cStr(), name.size()) == _name) [[likely]] { + ++_parent->ix_; + return field; + } } - return OutputVarType{}; + return _parent->val_.getSchema().getFieldByName(to_kj_string_ptr(_name)); } - template - OutputVarType add_value_to_union(const size_t _index, const T& _var, - OutputUnionType* _parent) const { - const auto field = _parent->val_.getSchema().getFields()[_index]; + static OutputObjectType make_output_object( + capnp::DynamicStruct::Builder _val); - if constexpr (std::is_same, std::string>()) { - _parent->val_.set(field, _var.c_str()); + static OutputMapType make_output_map(capnp::DynamicStruct::Builder _val, + const size_t _size); - } else if constexpr (std::is_same, - rfl::Bytestring>()) { + static capnp::DynamicStruct::Builder init_map_entry( + const std::string_view& _name, OutputMapType* _parent); + + template + static void set_field_value(capnp::DynamicStruct::Builder* _struct, + const capnp::StructSchema::Field _field, + const T& _var) { + using U = std::remove_cvref_t; + if constexpr (internal::is_literal_v) { + set_field_value(_struct, _field, _var.value()); + + } else if constexpr (std::is_same_v) { + _struct->set(_field, capnp::Text::Reader(_var.c_str(), _var.size())); + + } else if constexpr (std::is_same_v || + std::is_same_v) { const auto array_ptr = kj::ArrayPtr( internal::ptr_cast(_var.data()), _var.size()); - _parent->val_.set(field, capnp::Data::Reader(array_ptr)); - - } else if constexpr (std::is_same, bool>()) { - _parent->val_.set(field, _var); + _struct->set(_field, capnp::Data::Reader(array_ptr)); - } else if constexpr (std::is_same, float>()) { - _parent->val_.set(field, _var); + } else if constexpr (std::is_same_v) { + _struct->set(_field, _var); - } else if constexpr (std::is_same, double>()) { - _parent->val_.set(field, _var); + } else if constexpr (std::is_same_v) { + _struct->set(_field, _var); - } else if constexpr (std::is_floating_point>()) { - _parent->val_.set(field, static_cast(_var)); + } else if constexpr (std::is_same_v) { + _struct->set(_field, _var); - } else if constexpr (std::is_unsigned>()) { - _parent->val_.set(field, static_cast(_var)); + } else if constexpr (std::is_floating_point_v) { + _struct->set(_field, static_cast(_var)); - } else if constexpr (std::is_integral>()) { - _parent->val_.set(field, static_cast(_var)); + } else if constexpr (std::is_unsigned_v) { + _struct->set(_field, static_cast(_var)); - } else if constexpr (internal::is_literal_v) { - return add_value_to_union(_index, _var.value(), _parent); + } else if constexpr (std::is_integral_v) { + _struct->set(_field, static_cast(_var)); } else { static_assert(rfl::always_false_v, "Unsupported type."); } - return OutputVarType{}; - } - - void end_array(OutputArrayType* /*_arr*/) const {} - - void end_map(OutputMapType* /*_obj*/) const {} - - void end_object(OutputObjectType* /*_obj*/) const {} - - private: - kj::StringPtr to_kj_string_ptr(const std::string_view& _str) const { - return kj::StringPtr(_str.data(), _str.size()); } private: diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp index cad64d631..a45a4986d 100644 --- a/include/rfl/capnproto/is_named_type.hpp +++ b/include/rfl/capnproto/is_named_type.hpp @@ -1,6 +1,8 @@ #ifndef RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ #define RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ +#include + #include "../parsing/schema/Type.hpp" namespace rfl::capnproto { @@ -8,10 +10,15 @@ namespace rfl::capnproto { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same() || - std::is_same() || - std::is_same(); + if constexpr (std::is_same_v || + std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same() || + std::is_same() || + std::is_same(); + } }); } diff --git a/include/rfl/capnproto/read.hpp b/include/rfl/capnproto/read.hpp index 609797d4f..b7443c6c7 100644 --- a/include/rfl/capnproto/read.hpp +++ b/include/rfl/capnproto/read.hpp @@ -2,17 +2,25 @@ #define RFL_CAPNPROTO_READ_HPP_ #include +#include #include +#include +#include +#include #include +#include +#include +#include #include +#include #include +#include #include "../Processors.hpp" #include "../SnakeCaseToCamelCase.hpp" #include "../concepts.hpp" -//#include "../internal/ptr_cast.hpp" -//#include "../internal/strings/strings.hpp" +#include "../internal/ptr_cast.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" #include "Parser.hpp" #include "Reader.hpp" @@ -20,6 +28,30 @@ #include "get_root_name.hpp" #include "to_schema.hpp" +namespace rfl::internal::capnproto { + +template +struct is_schema : std::false_type {}; + +template +struct is_schema> : std::true_type {}; + +template +concept CompatibleSchema = + is_schema>::value && + std::is_same_v::Type, + std::remove_cvref_t>; + +template +concept ContiguousWordContainer = + !std::convertible_to> && + requires(const Container& c) { + { c.data() } -> std::convertible_to; + { c.size() } -> std::convertible_to; + }; + +} // namespace rfl::internal::capnproto + namespace rfl::capnproto { using InputObjectType = typename Reader::InputObjectType; @@ -29,58 +61,163 @@ using InputVarType = typename Reader::InputVarType; template auto read(const InputVarType& _obj) { const auto r = Reader(); - return Parser>::read(r, _obj); + return Parser, + Processors>::read(r, _obj); } -/// Parses an object from CAPNPROTO using reflection. +/// Parses an object from packed CAPNPROTO bytes using reflection. template -Result> read( +Result>> read( const concepts::ByteLike auto* _bytes, const size_t _size, - const Schema& _schema) { - const auto array_ptr = kj::ArrayPtr( - internal::ptr_cast(_bytes), _size); - auto input_stream = kj::ArrayInputStream(array_ptr); - auto message_reader = capnp::PackedMessageReader(input_stream); - const auto root_name = get_root_name, Ps...>(); - const auto root_schema = _schema.value().getNested(root_name.c_str()); - const auto input_var = InputVarType{ - message_reader.getRoot(root_schema.asStruct())}; - return read(input_var); + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + if (_bytes == nullptr && _size > 0) { + return error("Null byte pointer with non-zero size."); + } + try { + const auto array_ptr = kj::ArrayPtr( + internal::ptr_cast(_bytes), _size); + auto input_stream = kj::ArrayInputStream(array_ptr); + auto message_reader = capnp::PackedMessageReader(input_stream, _options); + const auto root_name = get_root_name, Ps...>(); + const auto root_schema = _schema.value().getNested(root_name.c_str()); + const auto input_var = InputVarType{ + message_reader.getRoot(root_schema.asStruct())}; + return read(input_var); + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); + } } -/// Parses an object from CAPNPROTO using reflection. +/// Parses an object from packed CAPNPROTO bytes using reflection. template -auto read(const char* _bytes, const size_t _size) { - const auto schema = to_schema, Ps...>(); - return read(_bytes, _size, schema); +Result>> read( + const concepts::ByteLike auto* _bytes, const size_t _size, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + const auto& schema_res = + schema_holder, Ps...>.schema_; + if (!schema_res) [[unlikely]] { + return error(schema_res.error()); + } + return read(_bytes, _size, *schema_res, _options); } -/// Parses an object from CAPNPROTO using reflection. +/// Parses an object from packed CAPNPROTO bytes using reflection. template auto read(const concepts::ContiguousByteContainer auto& _bytes, - const Schema& _schema) noexcept { - return read(_bytes.data(), _bytes.size(), _schema); + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + return read(_bytes.data(), _bytes.size(), _schema, _options); } -/// Parses an object from CAPNPROTO using reflection. +/// Parses an object from packed CAPNPROTO bytes using reflection. template -auto read(const concepts::ContiguousByteContainer auto& _bytes) { - return read(_bytes.data(), _bytes.size()); +auto read(const concepts::ContiguousByteContainer auto& _bytes, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + return read(_bytes.data(), _bytes.size(), _options); } -/// Parses an object from a stream. +/// Parses an object from a packed CAPNPROTO stream. template -auto read(std::istream& _stream) { +auto read(std::istream& _stream, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { std::istreambuf_iterator begin(_stream), end; auto bytes = std::vector(begin, end); - return read(bytes.data(), bytes.size()); + return read(bytes.data(), bytes.size(), _options); } +/// Parses an object from a packed CAPNPROTO stream with an explicit schema. template -auto read(std::istream& _stream, const Schema& _schema) { +auto read(std::istream& _stream, + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { std::istreambuf_iterator begin(_stream), end; auto bytes = std::vector(begin, end); - return read(bytes.data(), bytes.size(), _schema); + return read(bytes.data(), bytes.size(), _schema, _options); +} + +/// Parses an object from unpacked CAPNPROTO words via FlatArrayMessageReader. +template +Result>> read_unpacked( + const kj::ArrayPtr _words, + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + try { + auto message_reader = capnp::FlatArrayMessageReader(_words, _options); + const auto root_name = get_root_name, Ps...>(); + const auto root_schema = _schema.value().getNested(root_name.c_str()); + const auto input_var = InputVarType{ + message_reader.getRoot(root_schema.asStruct())}; + return read(input_var); + } catch (const kj::Exception& e) { + return error(e.getDescription().cStr()); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown Cap'n Proto error."); + } +} + +/// Parses an object from unpacked CAPNPROTO words via FlatArrayMessageReader. +template +Result>> read_unpacked( + const kj::ArrayPtr _words, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + const auto& schema_res = + schema_holder, Ps...>.schema_; + if (!schema_res) [[unlikely]] { + return error(schema_res.error()); + } + return read_unpacked(_words, *schema_res, _options); +} + +/// Parses an object from a raw word buffer via FlatArrayMessageReader. +template +Result>> read_unpacked( + const capnp::word* _words, const size_t _size, + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + if (_words == nullptr && _size > 0) { + return error("Null word pointer with non-zero size."); + } + return read_unpacked(kj::ArrayPtr(_words, _size), + _schema, _options); +} + +/// Parses an object from a raw word buffer via FlatArrayMessageReader. +template +Result>> read_unpacked( + const capnp::word* _words, const size_t _size, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + if (_words == nullptr && _size > 0) { + return error("Null word pointer with non-zero size."); + } + return read_unpacked(kj::ArrayPtr(_words, _size), + _options); +} + +/// Parses an object from a contiguous word container (e.g. std::span or +/// std::array of capnp::word) via FlatArrayMessageReader. +template +auto read_unpacked( + const internal::capnproto::ContiguousWordContainer auto& _words, + const internal::capnproto::CompatibleSchema auto& _schema, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + return read_unpacked(_words.data(), _words.size(), _schema, + _options); +} + +/// Parses an object from a contiguous word container (e.g. std::span or +/// std::array of capnp::word) via FlatArrayMessageReader. +template +auto read_unpacked( + const internal::capnproto::ContiguousWordContainer auto& _words, + const capnp::ReaderOptions& _options = capnp::ReaderOptions{}) { + return read_unpacked(_words.data(), _words.size(), _options); } } // namespace rfl::capnproto diff --git a/include/rfl/capnproto/write.hpp b/include/rfl/capnproto/write.hpp index 78949ece3..a10c07f10 100644 --- a/include/rfl/capnproto/write.hpp +++ b/include/rfl/capnproto/write.hpp @@ -6,39 +6,53 @@ #include #include #include +#include +#include #include +#include #include #include +#include #include "../SnakeCaseToCamelCase.hpp" #include "../internal/ptr_cast.hpp" -//#include "../internal/strings/strings.hpp" #include "../parsing/Parent.hpp" #include "Parser.hpp" -//#include "Schema.hpp" +#include "Schema.hpp" #include "Writer.hpp" #include "get_root_name.hpp" #include "to_schema.hpp" -namespace rfl::capnproto { +namespace rfl::internal::capnproto { -/// Returns CAPNPROTO bytes. -template -std::vector write(const auto& _obj, const auto& _schema) { - using T = std::remove_cvref_t; - using U = typename std::remove_cvref_t::Type; - using ParentType = parsing::Parent; - static_assert(std::is_same(), +template +void populate_message(const T& _obj, const rfl::capnproto::Schema& _schema, + capnp::MallocMessageBuilder* _message_builder) { + using ObjType = std::remove_cvref_t; + using SchemaType = typename rfl::capnproto::Schema::Type; + using ParentType = rfl::parsing::Parent; + static_assert(std::is_same(), "The schema must be compatible with the type to write."); - const auto root_name = get_root_name(); + const auto root_name = rfl::capnproto::get_root_name(); const auto root_schema = _schema.value().getNested(root_name.c_str()); + auto root = _message_builder->initRoot( + root_schema.asStruct()); + const auto writer = rfl::capnproto::Writer(&root); + rfl::capnproto::Parser>:: + write(writer, _obj, typename ParentType::Root{}); +} + +} // namespace rfl::internal::capnproto + +namespace rfl::capnproto { + +/// Returns packed CAPNPROTO bytes. +template +std::vector write(const T& _obj, const Schema& _schema) { capnp::MallocMessageBuilder message_builder; - auto root = - message_builder.initRoot(root_schema.asStruct()); - const auto writer = Writer(&root); - Parser>::write( - writer, _obj, typename ParentType::Root{}); + internal::capnproto::populate_message(_obj, _schema, &message_builder); kj::VectorOutputStream output_stream; capnp::writePackedMessage(output_stream, message_builder); auto arr_ptr = output_stream.getArray(); @@ -46,24 +60,41 @@ std::vector write(const auto& _obj, const auto& _schema) { internal::ptr_cast(arr_ptr.end())); } -/// Returns CAPNPROTO bytes. -template -std::vector write(const auto& _obj) { - using T = std::remove_cvref_t; - const auto schema = to_schema(); +/// Returns packed CAPNPROTO bytes. +template +std::vector write(const T& _obj) { + const auto& schema = + schema_holder, Ps...>.schema_.value(); return write(_obj, schema); } +/// Returns unpacked CAPNPROTO words via capnp::messageToFlatArray. +template +kj::Array write_unpacked(const T& _obj, const Schema& _schema) { + capnp::MallocMessageBuilder message_builder; + internal::capnproto::populate_message(_obj, _schema, &message_builder); + return capnp::messageToFlatArray(message_builder); +} + +/// Returns unpacked CAPNPROTO words via capnp::messageToFlatArray. +template +kj::Array write_unpacked(const T& _obj) { + const auto& schema = + schema_holder, Ps...>.schema_.value(); + return write_unpacked(_obj, schema); +} + /// Writes a CAPNPROTO into an ostream. -template -std::ostream& write(const auto& _obj, std::ostream& _stream) { +template +std::ostream& write(const T& _obj, std::ostream& _stream) { auto buffer = write(_obj); _stream.write(buffer.data(), buffer.size()); return _stream; } -template -std::ostream& write(const auto& _obj, const auto& _schema, std::ostream& _stream) { +template +std::ostream& write(const T& _obj, const Schema& _schema, + std::ostream& _stream) { auto buffer = write(_obj, _schema); _stream.write(buffer.data(), buffer.size()); return _stream; 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.hpp b/include/rfl/cli.hpp index 85881e7b9..a35b9e025 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -8,5 +8,6 @@ #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" +#include "cli/usage.hpp" #endif diff --git a/include/rfl/cli/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..b3003d4ed 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -1,22 +1,22 @@ #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 "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" -#include "../Tuple.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" @@ -155,11 +155,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 +173,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 @@ -267,67 +254,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 +359,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 new file mode 100644 index 000000000..e1f05df5c --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,496 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../NamedTuple.hpp" +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../generic/Writer.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/is_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_named_tuple.hpp" +#include "../internal/no_optionals_v.hpp" +#include "../parsing/is_required.hpp" +#include "../parsing/schema/Definition.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Whether a top-level field is required, which the schema cannot tell the +/// way the parser sees it. +struct UsageFieldMeta { + bool required = true; +}; + +/// Everything usage() renders about one argument. +struct UsageArg { + /// The long name, including the path of nested objects ("database.host"). + std::string name; + std::string short_name; + bool positional = false; + /// What the option does with a value, from the parser's option table: + /// flags (`--verbose`) can be given without one. + OptionKind kind = OptionKind::value; + /// Whether the field is a list. + bool is_list = false; + bool required = true; + /// Whether `required` was taken from the parser's compile-time traits, so + /// that the schema must not override it. + bool required_is_known = false; + /// The placeholder for one value: "", "" or "". Lists + /// are rendered from it with the list delimiter. + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; +}; + +/// 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 (_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 _is_default_constructible; + } +} + +/// 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; + // 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. + 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::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 +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + 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. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + std::vector collect(const bool _all_optional) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), false); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, const bool _outermost) { + _type.variant_.visit([&](const auto& _t) { + using T = std::remove_cvref_t; + // Description and Deprecated wrap the inner schema node without changing + // how the field is read. Short, Positional and Rename leave no node. + if constexpr (std::is_same_v + || std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _outermost); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + // The schema populates `default_value_` only when the parser recognizes + // the DefaultVal field and default-constructed its enclosing struct. + if (!_arg.required_is_known && _outermost && _t.default_value_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + const auto it = definition_->definitions_.find(_t.name_); + if (it == definition_->definitions_.end() + || !visiting_.insert(_t.name_).second) { + // Unknown or recursive: there is no finite set of paths to list. + add_leaf(std::move(_arg)); + return; + } + add(it->second, std::move(_arg), _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg); + + } else if constexpr (std::is_same_v) { + if (!_arg.name.empty()) { + _arg.name += path_separator; + } + _arg.name += ""; + _arg.short_name.clear(); + _arg.positional = false; + add(*_t.value_type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + _arg.kind = OptionKind::flag; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg)); + + } else if constexpr (std::is_same_v) { + auto values = std::vector(); + for (const auto& v : _t.values_) { + values.push_back(v.value_); + } + add_choices(values, std::move(_arg)); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.is_list = true; + add_leaf(std::move(_arg)); + + } else { + add_leaf(std::move(_arg)); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent) { + const bool is_root = _parent.name.empty(); + for (const auto& [name, type] : _object.types_) { + auto arg = UsageArg{}; + arg.name = is_root ? name : _parent.name + path_separator + name; + // Children of an optional object are only needed if it is given. + arg.required = _parent.required; + if (is_root) { + arg.positional = positionals_.contains(name); + const auto short_name = short_names_.find(name); + if (short_name != short_names_.end()) { + arg.short_name = std::string(short_name->second); + } + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + add(type, std::move(arg), true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg) { + _arg.choices = _values; + _arg.value = "<"; + for (size_t i = 0; i < _values.size(); ++i) { + _arg.value += (i == 0 ? "" : "|") + _values[i]; + } + _arg.value += ">"; + add_leaf(std::move(_arg)); + } + + void add_leaf(UsageArg _arg) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. Keep + // the schema-derived kind (such as OptionKind::flag for nested booleans) + // when the option table only tracks top-level paths. + const auto option = options_->find_long(_arg.name); + if (option.kind != OptionKind::unknown) { + _arg.kind = option.kind; + } + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::unordered_map* meta_; + const Options* options_; + const bool optionals_are_required_; + /// The rfl::Short aliases, by the path of their field. + 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_; +}; + +/// The placeholder for the value of _arg: "", "", or for a list +/// "" with the list delimiter. +inline std::string usage_value_to_string(const UsageArg& _arg) { + if (!_arg.is_list) { + return _arg.value; + } + const auto d = std::string(1, array_delimiter); + return ""; +} + +/// "", "-p|--port=", "--verbose[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep) { + if (_arg.positional) { + return "<" + _arg.name + ">"; + } + auto str = _arg.short_name.empty() ? std::string() + : "-" + _arg.short_name + _short_sep; + str += "--" + _arg.name; + const auto value = usage_value_to_string(_arg); + switch (_arg.kind) { + case OptionKind::flag: + // `--verbose`: the value can be left out. + str += "[=" + value + "]"; + break; + default: + str += "=" + value; + break; + } + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + if (_arg.required) { + sentences.push_back("Required"); + } + auto text = _arg.description; + while (!text.empty() + && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' + || text.back() == '\n')) { + text.pop_back(); + } + for (const auto& s : sentences) { + if (!text.empty()) { + text += usage_ends_sentence(text) ? " " : ". "; + } + text += s; + } + if (!sentences.empty() && !usage_ends_sentence(text)) { + text += "."; + } + return text; +} + +inline std::string format_usage(const std::string& _program_name, + const std::vector& _args, + const bool _detailed) { + auto out = "Usage: " + _program_name; + for (const auto& arg : _args) { + const auto str = usage_arg_to_string(arg, "|"); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + if (!_detailed || _args.empty()) { + return out; + } + + auto rows = std::vector>(); + size_t width = 0; + for (const auto& arg : _args) { + rows.emplace_back(usage_arg_to_string(arg, ", "), usage_help_text(arg)); + width = std::max(width, rows.back().first.size()); + } + + constexpr size_t indent = 2; + constexpr size_t gap = 2; + const auto continuation = '\n' + std::string(indent + width + gap, ' '); + out += "\nArguments:\n"; + for (const auto& [left, right] : rows) { + out += std::string(indent, ' ') + left; + if (!right.empty()) { + out += std::string(width - left.size() + gap, ' '); + for (size_t i = 0; i < right.size(); ++i) { + const char c = right[i]; + if (c == '\n') { + if (i + 1 < right.size() && right[i + 1] != '\n') { + out += continuation; + } else { + out += '\n'; + } + } else { + out += c; + } + } + } + out += '\n'; + } + return out; +} + +} // namespace internal + +/// Generates the usage line, and optionally a help text with one row per +/// argument, for the struct that `rfl::cli::read()` parses into. +/// It applies the same processors as `read`, so the names always match what +/// the parser accepts (kebab-case, rfl::Rename, rfl::Flatten, nested paths). +/// +/// The help text lists the description (rfl::Description), the allowed +/// values of enums and literals and whether the argument is required. +/// @tparam T The struct type that the arguments are parsed into +/// @tparam Ps The processors passed to `rfl::cli::read` +/// @param _program_name The name shown after "Usage:", usually argv[0] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline, or an error if no read of +/// T can succeed: two fields have the same short name, or T has a bare +/// rfl::DefaultVal and default-constructing it throws. +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using U = internal::unwrapped_option_t; + // The table that read() parses with, so the help shows what the parser + // accepts. + const auto options = internal::make_options(); + return internal::check_short_names(options).and_then( + [&](auto) -> rfl::Result { + try { + std::unordered_map meta; + if constexpr (internal::is_option_struct_v) { + meta = internal::collect_usage_field_meta(); + } + // The schema takes the default values from a default-constructed + // T, which can throw. + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v); + return internal::format_usage(_program_name, args, _detailed); + } catch (const std::exception& e) { + return error(e.what()); + } + }); +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 1233f2f09..258adf8d4 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -1,7 +1,9 @@ #ifndef RFL_COMPARISONS_HPP_ #define RFL_COMPARISONS_HPP_ -#include +#include +#include +#include #include #include "Result.hpp" @@ -9,6 +11,46 @@ namespace rfl { +namespace internal { + +template +std::string format_comparison_value(const T& _val) { + if constexpr (std::is_floating_point_v) { + char buf[64]; + const int n = [&]() { + if constexpr (std::is_same_v) { + return std::snprintf(buf, sizeof(buf), "%Lg", _val); + } else { + return std::snprintf(buf, sizeof(buf), "%g", static_cast(_val)); + } + }(); + if (n <= 0) { + return {}; + } + const auto len = static_cast(n) < sizeof(buf) + ? static_cast(n) + : sizeof(buf) - 1; + return std::string(buf, len); + } else if constexpr (std::is_same_v) { + return std::string(1, _val); + } else if constexpr (std::is_enum_v) { + return std::to_string(static_cast>(_val)); + } else { + // signed char / unsigned char (int8_t / uint8_t) intentionally format as + // decimal integers via std::to_string rather than raw characters. + return std::to_string(_val); + } +} + +template +std::string comparison_error_message(const char* _prefix, const T& _threshold, + const T& _value) { + return std::string(_prefix) + format_comparison_value(_threshold) + + ", but got " + format_comparison_value(_value) + "."; +} + +} // namespace internal + template struct EqualTo { /// @brief Validates that the given value is equal to the threshold. @@ -22,10 +64,8 @@ struct EqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value != threshold) { - std::stringstream stream; - stream << "Value expected to be equal to " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be equal to ", threshold, _value)); } return _value; } @@ -61,10 +101,8 @@ struct Minimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value < threshold) { - std::stringstream stream; - stream << "Value expected to be greater than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than or equal to ", threshold, _value)); } return _value; } @@ -100,10 +138,8 @@ struct ExclusiveMinimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value <= threshold) { - std::stringstream stream; - stream << "Value expected to be greater than " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than ", threshold, _value)); } return _value; } @@ -139,10 +175,8 @@ struct Maximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value > threshold) { - std::stringstream stream; - stream << "Value expected to be less than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than or equal to ", threshold, _value)); } return _value; } @@ -177,10 +211,8 @@ struct ExclusiveMaximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value >= threshold) { - std::stringstream stream; - stream << "Value expected to be less than " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than ", threshold, _value)); } return _value; } @@ -215,10 +247,8 @@ struct NotEqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value == threshold) { - std::stringstream stream; - stream << "Value expected not to be equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected not to be equal to ", threshold, _value)); } return _value; } diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..46c16df1e 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -1,10 +1,19 @@ #ifndef RFL_ENUMS_HPP_ #define RFL_ENUMS_HPP_ -#include +#include +#include #include +#include +#include +#include +#include +#include "EnumNames.hpp" +#include "Processors.hpp" #include "Result.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" #include "internal/enums/get_enum_range.hpp" @@ -52,94 +61,262 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// Converts an enum value to tis string representation. -template -std::string enum_to_string(const EnumType _enum) { - if constexpr (internal::enums::is_flag_enum) { +namespace internal { + +template +std::vector>> +build_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back( + resolve_enum_wire_name_for_transform(val, raw_name), + val); + } + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [val, wire] : get_enum_overrides()) { + bool already_present = false; + for (const auto& entry : out) { + if (entry.second == val) { + already_present = true; + break; + } + } + if (!already_present) { + out.emplace_back(std::string(wire), val); + } + } + } + return out; +} + +template +const std::vector>>& +get_cached_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kTable = build_enum_wire_names_with_transform(); + return kTable; +} + +template +const std::vector>>& +get_cached_unique_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kUnique = []() { + std::vector> out; + const auto& all = get_cached_enum_wire_names_with_transform(); + out.reserve(all.size()); + for (const auto& entry : all) { + bool dup = false; + for (const auto& existing : out) { + if (existing.first == entry.first) { + dup = true; + break; + } + } + if (!dup) { + out.push_back(entry); + } + } + return out; + }(); + return kUnique; +} + +template +std::string enum_to_single_wire_name(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (val == _enum) { + return wire; + } + } + return std::to_string(static_cast>(_enum)); + } else { + return internal::enums::to_string(_enum); + } +} + +template +std::string enum_to_string_with_transform(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (internal::enums::is_flag_enum) { // Iterates through the enum bit by bit and matches it against the flags. - using T = std::underlying_type_t; + using T = std::underlying_type_t; auto val = static_cast(_enum); int i = 0; std::vector flags; while (val != 0) { const auto bit = val & static_cast(1); if (bit == 1) { - auto str = internal::enums::to_string( - static_cast(static_cast(1) << i)); + auto str = enum_to_single_wire_name( + static_cast(static_cast(1) << i)); flags.emplace_back(std::move(str)); } ++i; val >>= 1; } if (flags.empty()) { - return internal::enums::to_string(static_cast(0)); + return enum_to_single_wire_name(static_cast(0)); } return internal::strings::join("|", flags); } else { - return internal::enums::to_string(_enum); + return enum_to_single_wire_name(_enum); } } -// Converts a string to a value of the given enum type. -// -// By default, numeric values are accepted in addition to the declared -// enumerator names, even when they do not correspond to a declared -// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 -// will produce the cast value 4). Pass enum_names_only = true (or use the -// EnumNamesOnly processor with a parser) to accept only the declared -// enumerator names instead. -template -Result string_to_enum(const std::string& _str) { - const auto make_error_msg = [&](const auto& name) { +template +Result> string_to_enum_with_transform( + const std::string_view _str) { + using E = std::remove_cvref_t; + const auto make_error_msg = [](const std::string_view name) { std::string msg = "Invalid enum value: '"; msg += name; msg += "'. Must be one of ["; const char* sep = ""; - for (const auto& p : get_enumerator_array()) { - msg += sep; - msg += p.first; - sep = ", "; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& p : + get_cached_unique_enum_wire_names_with_transform()) { + msg += sep; + msg += p.first; + sep = ", "; + } + } else { + for (const auto& p : get_enumerator_array()) { + msg += sep; + msg += p.first; + sep = ", "; + } } msg += "]."; return error(msg); }; const auto cast_numbers_or_names = - [&](const std::string& name) -> Result { - const auto r = internal::enums::from_string(name); - if (r) { - return *r; + [&](const std::string_view name) -> Result { + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (wire == name) { + return val; + } + } + } else { + const auto r = internal::enums::from_string(name); + if (r) { + return *r; + } } if constexpr (enum_names_only) { return make_error_msg(name); } else { - try { - const auto val = std::stoi(name); - return static_cast(val); - } catch (std::exception& exp) { + if (name.empty()) { return make_error_msg(name); } + using Underlying = std::underlying_type_t; + using ParseType = std::conditional_t< + (sizeof(Underlying) < sizeof(int)), int, + std::conditional_t< + std::is_signed_v, + std::conditional_t< + (sizeof(Underlying) <= sizeof(int)), int, + std::conditional_t<(sizeof(Underlying) <= sizeof(long)), long, + long long>>, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned int)), unsigned int, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned long)), + unsigned long, unsigned long long>>>>; + ParseType val{}; + const auto* begin = name.data(); + const auto* end = begin + name.size(); + const auto [ptr, ec] = std::from_chars(begin, end, val); + if (ec == std::errc{} && ptr == end) { + return static_cast(val); + } + return make_error_msg(name); } }; - if constexpr (internal::enums::is_flag_enum) { - using T = std::underlying_type_t; - const auto split = internal::strings::split(_str, "|"); + if constexpr (internal::enums::is_flag_enum) { + using T = std::underlying_type_t; auto res = static_cast(0); - for (const auto& s : split) { - const auto r = cast_numbers_or_names(s); - if (r) { - res |= static_cast(*r); - } else { + std::string_view remaining = _str; + while (true) { + const auto pos = remaining.find('|'); + const auto token = remaining.substr(0, pos); + const auto r = cast_numbers_or_names(token); + if (!r) { return r; } + res |= static_cast(*r); + if (pos == std::string_view::npos) { + break; + } + remaining.remove_prefix(pos + 1); } - return static_cast(res); + return static_cast(res); } else { return cast_numbers_or_names(_str); } } +template +Result> string_to_enum_with_transform_noexcept( + const std::string_view _str) noexcept { + try { + return string_to_enum_with_transform( + _str); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception thrown while parsing enum value."); + } +} + +} // namespace internal + +// Converts an enum value to its wire string representation, honoring +// `rfl::EnumNames` and any `rfl::TransformEnumNames<...>` processor +// passed in `Ps...`. +template +std::string enum_to_string(const EnumType _enum) { + return internal::enum_to_string_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(_enum); +} + +// Returns all declared enumerators (plus any explicit `rfl::EnumNames` +// overrides for values outside the reflected range) paired with their resolved +// wire names. +template +std::vector>> +get_enum_wire_names() { + return internal::get_cached_enum_wire_names_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(); +} + +// Converts a string to a value of the given enum type. +// +// By default, numeric values are accepted in addition to the declared +// enumerator names, even when they do not correspond to a declared +// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 +// will produce the cast value 4). Pass enum_names_only = true (or use the +// EnumNamesOnly processor with a parser) to accept only the declared +// enumerator names instead. +template +Result> string_to_enum( + const std::string_view _str) noexcept { + return internal::string_to_enum_with_transform_noexcept< + std::remove_cvref_t, enum_names_only, + internal::enum_name_transform_v>>(_str); +} + } // namespace rfl #endif // RFL_ENUMS_HPP_ diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..b87690baa 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -170,14 +171,13 @@ struct Reader { /// @param _var The ENV variable to check /// @return true if the variable is empty, false otherwise bool is_empty(const InputVarType& _var) const noexcept { - const auto str = std::getenv(_var.path.c_str()); - if (str != nullptr) { - return false; - } if (_var.path.empty()) { return true; } - const auto prefix = _var.path.empty() ? std::string("") : _var.path + "_"; + if (has_env_var(_var.path.c_str())) { + return false; + } + const auto prefix = _var.path + "_"; for (char** env = get_environ(); *env != nullptr; ++env) { const std::string env_entry(*env); if (env_entry.size() <= prefix.size()) { @@ -304,14 +304,41 @@ struct Reader { } private: + static bool has_env_var(const char* _name) noexcept { + if (_name == nullptr || *_name == '\0') { + return false; + } +#ifdef _MSC_VER + std::size_t required_size = 0; + return ::getenv_s(&required_size, nullptr, 0, _name) == 0 && + required_size > 0; +#else + return std::getenv(_name) != nullptr; +#endif + } + static std::optional get_value( const InputVarType& _var) noexcept { + if (_var.path.empty()) { + return std::nullopt; + } +#ifdef _MSC_VER + char* env_value = nullptr; + if (::_dupenv_s(&env_value, nullptr, _var.path.c_str()) == 0 && + env_value != nullptr) { + std::string result(env_value); + std::free(env_value); + return result; + } + return std::nullopt; +#else const char* env_value = std::getenv(_var.path.c_str()); if (env_value) { return std::string(env_value); } else { return std::nullopt; } +#endif } }; diff --git a/include/rfl/env/Writer.hpp b/include/rfl/env/Writer.hpp index 23512bb72..d0d505fd4 100644 --- a/include/rfl/env/Writer.hpp +++ b/include/rfl/env/Writer.hpp @@ -56,7 +56,7 @@ class RFL_API Writer { } template - OutputVarType value_as_root(const T& _var) const noexcept { + OutputVarType value_as_root(const T&) const noexcept { static_assert( always_false_v, "Writing basic types to ENV as root variables is not supported."); diff --git a/include/rfl/field_names_t.hpp b/include/rfl/field_names_t.hpp index c30ddc585..08bc5f36c 100644 --- a/include/rfl/field_names_t.hpp +++ b/include/rfl/field_names_t.hpp @@ -1,7 +1,6 @@ #ifndef RFL_FIELD_NAMES_T_HPP_ #define RFL_FIELD_NAMES_T_HPP_ -#include #include #include "internal/get_field_names.hpp" @@ -13,8 +12,8 @@ namespace rfl { /// for iteration, validation, or other metaprogramming tasks. /// @tparam T The struct type to extract field names from template -using field_names_t = typename std::invoke_result< - decltype(internal::get_field_names>)>::type; +using field_names_t = + decltype(internal::get_field_names>()); } // namespace rfl 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/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/Field.hpp b/include/rfl/internal/Field.hpp index 186b12f04..2e3087ad3 100644 --- a/include/rfl/internal/Field.hpp +++ b/include/rfl/internal/Field.hpp @@ -2,6 +2,7 @@ #define RFL_INTERNAL_FIELD_TUPLE_T_HPP_ #include +#include #include "copy_to_field_tuple.hpp" @@ -9,8 +10,7 @@ namespace rfl { namespace internal { template -using field_tuple_t = - typename std::invoke_result), T>::type; +using field_tuple_t = decltype(copy_to_field_tuple(std::declval())); } } // namespace rfl 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/StringLiteral.hpp b/include/rfl/internal/StringLiteral.hpp index 56a64e108..c8bf5d1e9 100644 --- a/include/rfl/internal/StringLiteral.hpp +++ b/include/rfl/internal/StringLiteral.hpp @@ -1,68 +1,11 @@ #ifndef RFL_INTERNAL_STRINGLITERAL_HPP_ #define RFL_INTERNAL_STRINGLITERAL_HPP_ -#include -#include -#include -#include -#include +#include "../StringLiteral.hpp" namespace rfl::internal { -/// Normal strings cannot be used as template -/// parameters, but this can. This is needed -/// for the parameters names in the NamedTuples. -template -struct StringLiteral { - /// Constrained via template type parameters rather than a requires-fold - /// over decltype of the function parameter pack: the latter crashes - /// clang 21/22 in C++26 mode (llvm/llvm-project#198052, #205000). - template ... Chars> - constexpr StringLiteral(const Chars... _chars) : arr_{_chars..., '\0'} {} - - constexpr StringLiteral(const std::array _arr) : arr_(_arr) {} - - constexpr StringLiteral(const char (&_str)[N]) { - std::copy_n(_str, N, std::data(arr_)); - } - - constexpr StringLiteral(const std::string_view _str) { - std::copy_n(_str.data(), _str.size(), std::data(arr_)); - } - - template - requires(std::is_same_v || std::is_same_v) - explicit constexpr StringLiteral(T _data) { - std::copy_n(_data, N, std::data(arr_)); - } - - /// Returns the value as a string. - std::string str() const { return std::string(string_view()); } - - /// Returns the value as a string. - constexpr std::string_view string_view() const { - return std::string_view(std::data(arr_), N - 1); - } - - static constexpr size_t length = N - 1; - - std::array arr_{}; -}; - -template -constexpr inline bool operator==(const StringLiteral& _first, - const StringLiteral& _second) { - if constexpr (N1 != N2) { - return false; - } - return _first.string_view() == _second.string_view(); -} - -template -constexpr inline bool operator!=(const StringLiteral& _first, - const StringLiteral& _second) { - return !(_first == _second); -} +using rfl::StringLiteral; } // namespace rfl::internal diff --git a/include/rfl/internal/bind_to_tuple.hpp b/include/rfl/internal/bind_to_tuple.hpp index b6a578c34..49e7333d9 100644 --- a/include/rfl/internal/bind_to_tuple.hpp +++ b/include/rfl/internal/bind_to_tuple.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_BIND_TO_TUPLE_HPP_ #define RFL_INTERNAL_BIND_TO_TUPLE_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/bind_to_tuple.hpp" #else @@ -9,6 +11,15 @@ namespace rfl::internal { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + return cpp20::apply_to_fields(_t, std::forward(_f)); +#else + return cpp26::apply_to_fields(_t, std::forward(_f)); +#endif +} + template auto bind_to_tuple(T& _t) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION diff --git a/include/rfl/internal/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/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/Result.hpp b/include/rfl/internal/cpp20/Result.hpp index fb436bedb..6fa61f146 100644 --- a/include/rfl/internal/cpp20/Result.hpp +++ b/include/rfl/internal/cpp20/Result.hpp @@ -2,7 +2,6 @@ #define RFL_INTERNAL_CPP20_RESULT_HPP_ #include -#include #include #include #include @@ -60,7 +59,9 @@ template class Result { static_assert(!std::is_same(), "The result type cannot be Error."); - using TOrErr = std::array; + using TOrErr = + std::array sizeof(Error) ? sizeof(T) : sizeof(Error))>; public: using value_type = T; @@ -154,7 +155,7 @@ class Result { template auto and_then(const F& _f) && { /// Result_U is expected to be of type Result. - using Result_U = typename std::invoke_result::type; + using Result_U = decltype(_f(std::move(*this).get_t())); if (success_) { return Result_U(_f(std::move(*this).get_t())); } else { @@ -178,7 +179,7 @@ class Result { template auto and_then(const F& _f) const& { /// Result_U is expected to be of type Result. - using Result_U = typename std::invoke_result::type; + using Result_U = decltype(_f(get_t())); if (success_) { return Result_U(_f(get_t())); } else { @@ -335,7 +336,7 @@ class Result { template RFL_ALWAYS_INLINE auto transform(const F& _f) && { /// Result_U is expected to be of type Result. - using U = decltype(std::declval()(std::declval())); + using U = decltype(_f(std::move(*this).get_t())); if (success_) { return Result(_f(std::move(*this).get_t())); } else { @@ -355,7 +356,7 @@ class Result { template auto transform(const F& _f) const& { /// Result_U is expected to be of type Result. - using U = typename std::invoke_result::type; + using U = decltype(_f(get_t())); if (success_) { return Result(_f(get_t())); } else { @@ -555,7 +556,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, std::move(*this).get_err())}; + return Result{std::forward(f)(std::move(*this).get_err())}; } else { return Result{std::move(*this).value()}; } @@ -584,7 +585,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, get_err())}; + return Result{std::forward(f)(get_err())}; } else { return Result{value()}; } @@ -681,7 +682,8 @@ class Result { bool success_; /// The underlying data, can either be T or Error. - alignas(std::max(alignof(T), alignof(Error))) TOrErr t_or_err_; + alignas((alignof(T) > alignof(Error) ? alignof(T) + : alignof(Error))) TOrErr t_or_err_; }; } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/bind_to_tuple.hpp b/include/rfl/internal/cpp20/bind_to_tuple.hpp index 9733f1dbe..218e34c70 100644 --- a/include/rfl/internal/cpp20/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp20/bind_to_tuple.hpp @@ -5,6 +5,7 @@ #include #include +#include #include #include "../../Tuple.hpp" @@ -16,14 +17,14 @@ namespace rfl::internal::cpp20 { #define RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS( \ n, ...) \ auto& [__VA_ARGS__] = _t; \ - return [](auto&... _refs) { return rfl::make_tuple(&_refs...); }(__VA_ARGS__); + return std::forward(_f)(__VA_ARGS__); // The following boilerplate code has been generated with -// scripts/bind_to_tuple_impl.py -template -auto bind_to_tuple_impl(auto& _t) { +// scripts/bind_to_tuple.py +template +decltype(auto) apply_to_fields_impl(T& _t, F&& _f) { if constexpr (_num_fields == 0) { - return rfl::make_tuple(); + return std::forward(_f)(); } else { if constexpr (_num_fields < 129) { if constexpr (_num_fields < 65) { @@ -4384,9 +4385,16 @@ auto bind_to_tuple_impl(auto& _t) { #undef RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { + return cpp20::apply_to_fields_impl>>( + _t, std::forward(_f)); +} + template auto bind_to_tuple(T& _t) { - return bind_to_tuple_impl>(_t); + return cpp20::apply_to_fields( + _t, [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/get_field_names.hpp b/include/rfl/internal/cpp20/get_field_names.hpp index 707a0590a..e60222023 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 @@ -104,6 +105,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 +132,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/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_type_name.hpp b/include/rfl/internal/cpp26/get_type_name.hpp index dbcb50678..97eb82773 100644 --- a/include/rfl/internal/cpp26/get_type_name.hpp +++ b/include/rfl/internal/cpp26/get_type_name.hpp @@ -11,10 +11,10 @@ namespace rfl::internal::cpp26 { template -consteval auto get_type_name() { +consteval auto get_type_name_str_view() { using Type = std::remove_cvref_t; if constexpr (std::is_pointer_v) { - return get_type_name>(); + return get_type_name_str_view>(); } else { // TODO: Is there a way to get the name of the type without using // compiler-specific extensions? @@ -22,9 +22,7 @@ consteval auto get_type_name() { constexpr auto display_string = std::meta::display_string_of(^^Type); constexpr auto drop_last_char = display_string.substr(0, display_string.size() - 1); - constexpr auto name = - drop_last_char.substr(drop_last_char.find("{aka ") + 5); - return StringLiteral(name); + return drop_last_char.substr(drop_last_char.find("{aka ") + 5); #else static_assert(false, "You are using an unsupported compiler. Please use GCC or " @@ -32,6 +30,12 @@ consteval auto get_type_name() { #endif } } + +template +consteval auto get_type_name() { + constexpr auto name = get_type_name_str_view(); + return StringLiteral(name); +} } // namespace rfl::internal::cpp26 #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/enums/cpp20/from_string.hpp b/include/rfl/internal/enums/cpp20/from_string.hpp index b14315964..1d1cec7de 100644 --- a/include/rfl/internal/enums/cpp20/from_string.hpp +++ b/include/rfl/internal/enums/cpp20/from_string.hpp @@ -3,15 +3,14 @@ #ifndef REFLECTCPP_USE_CPP26_REFLECTION -#include -#include +#include #include "enchantum.hpp" // NOLINT(unused-includes) namespace rfl::internal::enums::cpp20 { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { return enchantum::cast(_str); } diff --git a/include/rfl/internal/enums/cpp26/from_string.hpp b/include/rfl/internal/enums/cpp26/from_string.hpp index 919be47c6..1f4698529 100644 --- a/include/rfl/internal/enums/cpp26/from_string.hpp +++ b/include/rfl/internal/enums/cpp26/from_string.hpp @@ -5,13 +5,13 @@ #include #include -#include +#include #include namespace rfl::internal::enums::cpp26 { template -std::optional from_string(const std::string& _str) { +std::optional from_string(const std::string_view _str) { template for (constexpr auto e : std::define_static_array( std::meta::enumerators_of(^^EnumType))) { if (_str == std::meta::identifier_of(e)) { diff --git a/include/rfl/internal/enums/from_string.hpp b/include/rfl/internal/enums/from_string.hpp index 160363283..c966f6d36 100644 --- a/include/rfl/internal/enums/from_string.hpp +++ b/include/rfl/internal/enums/from_string.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ #define RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/from_string.hpp" #else @@ -10,7 +12,7 @@ namespace rfl::internal::enums { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION return cpp20::from_string(_str); #else diff --git a/include/rfl/internal/field_tuple_t.hpp b/include/rfl/internal/field_tuple_t.hpp index bf0e473d4..882937350 100644 --- a/include/rfl/internal/field_tuple_t.hpp +++ b/include/rfl/internal/field_tuple_t.hpp @@ -2,14 +2,14 @@ #define RFL_INTERNAL_FIELD_TUPLE_T_HPP_ #include +#include #include "copy_to_field_tuple.hpp" namespace rfl::internal { template -using field_tuple_t = - typename std::invoke_result), T>::type; +using field_tuple_t = decltype(copy_to_field_tuple(std::declval())); } // namespace rfl::internal diff --git a/include/rfl/internal/find_index.hpp b/include/rfl/internal/find_index.hpp index 04c524e7d..9cc9f88e1 100644 --- a/include/rfl/internal/find_index.hpp +++ b/include/rfl/internal/find_index.hpp @@ -1,63 +1,57 @@ #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 -constexpr auto wrap_fields(std::integer_sequence) { - return find_matching_field(FieldWrapper, - _field_name, _is>{}...) - .i_; -} +template +struct FindIndexImpl> + : FindIndexImpl> {}; -/// Finds the index of the field signified by _field_name +/// Finds the index of the field signified by _field_name or -1. 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 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 or -1. +/// Finds the index of the field signified by _field_name 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; - } - } +constexpr int find_index() { + constexpr int ix = find_index_or_minus_one<_field_name, Fields>(); + static_assert(ix != -1, "No matching field found."); + return ix; } } // namespace internal diff --git a/include/rfl/internal/flattened_ptr_tuple_t.hpp b/include/rfl/internal/flattened_ptr_tuple_t.hpp index 9c8a3f3cd..11d601a11 100644 --- a/include/rfl/internal/flattened_ptr_tuple_t.hpp +++ b/include/rfl/internal/flattened_ptr_tuple_t.hpp @@ -2,6 +2,7 @@ #define RFL_INTERNAL_FLATTENED_PTR_TUPLE_T_HPP_ #include +#include #include "to_flattened_ptr_tuple.hpp" @@ -10,7 +11,7 @@ namespace internal { template using flattened_ptr_tuple_t = - typename std::invoke_result), T>::type; + decltype(to_flattened_ptr_tuple(std::declval())); } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/get_type_name.hpp b/include/rfl/internal/get_type_name.hpp index 9596ad231..c5299fbe7 100644 --- a/include/rfl/internal/get_type_name.hpp +++ b/include/rfl/internal/get_type_name.hpp @@ -20,7 +20,11 @@ consteval auto get_type_name() { template consteval auto get_type_name_str_view() { - return get_type_name().string_view(); +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + return cpp20::get_type_name_str_view(); +#else + return cpp26::get_type_name_str_view(); +#endif } } // namespace rfl::internal 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/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_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/move_from_named_tuple.hpp b/include/rfl/internal/move_from_named_tuple.hpp index 617bcb163..51b7cb652 100644 --- a/include/rfl/internal/move_from_named_tuple.hpp +++ b/include/rfl/internal/move_from_named_tuple.hpp @@ -2,6 +2,7 @@ #define RFL_MOVE_FROM_NAMED_TUPLE_HPP_ #include +#include #include "../Tuple.hpp" #include "../named_tuple_t.hpp" @@ -20,8 +21,7 @@ auto make_ptr_fields(PtrNamedTupleType& _n) { using T = std::remove_cvref_t>; if constexpr (is_named_tuple_v) { using SubPtrNamedTupleType = - typename std::invoke_result), - T>::type; + decltype(nt_to_ptr_named_tuple(std::declval())); return SubPtrNamedTupleType(_n).fields(); } else if constexpr (is_flatten_field::value) { using SubPtrFieldTupleType = std::remove_cvref_t>; diff --git a/include/rfl/internal/move_from_tuple.hpp b/include/rfl/internal/move_from_tuple.hpp index c5edf9043..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...>& _other) 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