From 6b369d76db3f44c7e3c08676162d2929fc07f57f Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 22:48:53 +0100 Subject: [PATCH 1/3] perf(parsing): add type-erased descriptor-table core (TableStructParser) bypassing NamedTuple for aggregates - Add value-level DirectFieldNames with packed null-terminated char storage, sorted binary-search lookup, recursive rfl::Flatten support, and all 5 built-in case-transform processors (preserving xml_content and Rename). - Add non-T-parameterized TableViewReader / TableViewReaderWithDefault and shared driver loops in TableStructParser, eliminating NamedTuple, Tuple, and per-struct ViewReader/read_object instantiations across wide structs and multi-struct TUs. - Generalize bind_to_tuple into apply_to_fields (C++20 and C++26) and replace HasDefaultVal> with direct apply_to_fields inspection. - Support rfl::ExtraFields, rfl::Flatten, custom/external named Readers (via SizedTableViewReader), env::Reader field_names(), xml is_view_reader_v, and RAII UninitFieldsGuard exception safety. - Add UBSan stress and regression test suites covering lifetime tracking, partial destruction, throwing readers, non-standard-layout aggregates, C-arrays, inheritance, Flatten, ExtraFields, and case-transform pipelines. --- include/rfl/bson/Reader.hpp | 1 + include/rfl/cbor/Reader.hpp | 1 + include/rfl/cli/Reader.hpp | 1 + include/rfl/env/Reader.hpp | 11 + include/rfl/flexbuf/Reader.hpp | 1 + include/rfl/generic/Reader.hpp | 1 + include/rfl/internal/DirectFieldNames.hpp | 436 ++++++ include/rfl/internal/bind_to_tuple.hpp | 14 +- include/rfl/internal/cpp20/bind_to_tuple.hpp | 17 +- .../rfl/internal/cpp20/get_field_names.hpp | 31 + include/rfl/internal/cpp26/bind_to_tuple.hpp | 10 +- .../rfl/internal/cpp26/get_field_names.hpp | 28 + include/rfl/internal/has_default_val_v.hpp | 39 +- include/rfl/json/Reader.hpp | 1 + include/rfl/msgpack/Reader.hpp | 1 + include/rfl/parsing/NamedTupleParser.hpp | 3 + include/rfl/parsing/Parser_default.hpp | 80 +- include/rfl/parsing/TableStructParser.hpp | 1265 +++++++++++++++++ include/rfl/parsing/is_view_reader.hpp | 20 + include/rfl/toml/Reader.hpp | 1 + include/rfl/ubjson/Reader.hpp | 1 + include/rfl/xml/Reader.hpp | 1 + include/rfl/yaml/Reader.hpp | 1 + tests/json/test_descriptor_table_stress.cpp | 684 +++++++++ .../test_descriptor_table_c_arrays.cpp | 54 + 25 files changed, 2667 insertions(+), 36 deletions(-) create mode 100644 include/rfl/internal/DirectFieldNames.hpp create mode 100644 include/rfl/parsing/TableStructParser.hpp create mode 100644 tests/json/test_descriptor_table_stress.cpp create mode 100644 tests/json_c_arrays_and_inheritance/test_descriptor_table_c_arrays.cpp diff --git a/include/rfl/bson/Reader.hpp b/include/rfl/bson/Reader.hpp index 0d7bf53f2..30e09c5c2 100644 --- a/include/rfl/bson/Reader.hpp +++ b/include/rfl/bson/Reader.hpp @@ -19,6 +19,7 @@ namespace bson { /// Please refer to https://mongoc.org/libbson/current/api.html struct Reader { + using UnsizedObjectReader = void; struct BSONInputArray { const bson_value_t* val_; }; diff --git a/include/rfl/cbor/Reader.hpp b/include/rfl/cbor/Reader.hpp index 62fcfa4fa..0d6ad959a 100644 --- a/include/rfl/cbor/Reader.hpp +++ b/include/rfl/cbor/Reader.hpp @@ -36,6 +36,7 @@ namespace rfl::cbor { /// than JSON while maintaining similar data model capabilities. class Reader { public: + using UnsizedObjectReader = void; /// Represents a CBOR array during deserialization. /// Wraps a pointer to the underlying jsoncons JSON value representing the /// array. diff --git a/include/rfl/cli/Reader.hpp b/include/rfl/cli/Reader.hpp index 58c16d37b..7a198b60e 100644 --- a/include/rfl/cli/Reader.hpp +++ b/include/rfl/cli/Reader.hpp @@ -137,6 +137,7 @@ rfl::Result parse_value( /// Parses hierarchical key-value pairs from CLI arguments (e.g., --database.host=localhost). /// Supports arrays through comma-delimited values (e.g., --ports=8080,8081). struct Reader { + using UnsizedObjectReader = void; using InputArrayType = CliArrayType; using InputObjectType = CliObjectType; using InputVarType = CliVarType; diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..4a52a7327 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -135,6 +135,7 @@ rfl::Result parse_value(const std::string& _str, /// arrays and objects, check for empty variables, and convert string values to /// basic C++ types. struct Reader { + using UnsizedObjectReader = void; using InputArrayType = InputEnvArrayType; using InputObjectType = InputEnvObjectType; using InputVarType = InputEnvVarType; @@ -240,6 +241,16 @@ struct Reader { } } + } else if constexpr (requires { _object_reader.field_names(); }) { + for (const auto name_sv : _object_reader.field_names()) { + const std::string name(name_sv); + const auto child_path = _obj.prefix.empty() ? name : _obj.prefix + name; + const auto var = InputVarType{.path = child_path}; + if (!is_empty(var)) { + _object_reader.read(std::string_view(name), var); + } + } + } else { for (char** env = get_environ(); *env != nullptr; ++env) { const std::string env_entry(*env); diff --git a/include/rfl/flexbuf/Reader.hpp b/include/rfl/flexbuf/Reader.hpp index 8ef601d5e..8cc3cd215 100644 --- a/include/rfl/flexbuf/Reader.hpp +++ b/include/rfl/flexbuf/Reader.hpp @@ -20,6 +20,7 @@ namespace rfl { namespace flexbuf { struct Reader { + using UnsizedObjectReader = void; using InputArrayType = flexbuffers::Vector; using InputObjectType = flexbuffers::Map; using InputVarType = flexbuffers::Reference; diff --git a/include/rfl/generic/Reader.hpp b/include/rfl/generic/Reader.hpp index db9631800..f4502ae66 100644 --- a/include/rfl/generic/Reader.hpp +++ b/include/rfl/generic/Reader.hpp @@ -16,6 +16,7 @@ namespace rfl::generic { /// The Generic type can represent any JSON-like structure (objects, arrays, primitives) /// without being tied to a specific serialization format. struct Reader { + using UnsizedObjectReader = void; using InputArrayType = Generic::Array; using InputObjectType = Generic::Object; using InputVarType = Generic; diff --git a/include/rfl/internal/DirectFieldNames.hpp b/include/rfl/internal/DirectFieldNames.hpp new file mode 100644 index 000000000..b02a5d67b --- /dev/null +++ b/include/rfl/internal/DirectFieldNames.hpp @@ -0,0 +1,436 @@ +#ifndef RFL_INTERNAL_DIRECTFIELDNAMES_HPP_ +#define RFL_INTERNAL_DIRECTFIELDNAMES_HPP_ + +#include +#include +#include +#include +#include + +#include "../CamelCaseToSnakeCase.hpp" +#include "../Processors.hpp" +#include "../SnakeCaseToCamelCase.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../SnakeCaseToPascalCase.hpp" +#include "../ToAllCaps.hpp" +#include "../num_fields.hpp" +#include "../parsing/find_field_index.hpp" +#include "bind_to_tuple.hpp" +#include "get_field_names.hpp" +#include "is_field.hpp" +#include "is_flatten_field.hpp" +#include "nth_element_t.hpp" +#include "transform_case.hpp" +#ifndef REFLECTCPP_USE_CPP26_REFLECTION +#include "cpp20/get_ith_field_from_fake_object.hpp" +#endif + +namespace rfl::internal { + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundefined-var-template" +#pragma clang diagnostic ignored "-Wundefined-inline" +#pragma clang diagnostic ignored "-Wundefined-internal" +#endif + +enum class DirectCaseOp : unsigned char { + snake_to_camel, + snake_to_pascal, + camel_to_snake, + snake_to_kebab, + to_all_caps, +}; + +template +struct DirectCasePipeline {}; + +template +struct concat_case_pipelines; + +template +struct concat_case_pipelines, + DirectCasePipeline> { + using type = DirectCasePipeline; +}; + +template +struct extract_case_pipeline { + using type = DirectCasePipeline<>; +}; + +template <> +struct extract_case_pipeline { + using type = DirectCasePipeline; +}; + +template <> +struct extract_case_pipeline { + using type = DirectCasePipeline; +}; + +template <> +struct extract_case_pipeline { + using type = DirectCasePipeline; +}; + +template <> +struct extract_case_pipeline { + using type = DirectCasePipeline; +}; + +template <> +struct extract_case_pipeline { + using type = DirectCasePipeline; +}; + +template <> +struct extract_case_pipeline> { + using type = DirectCasePipeline<>; +}; + +template +struct extract_case_pipeline> { + using type = typename concat_case_pipelines< + typename extract_case_pipeline::type, + typename extract_case_pipeline>::type>::type; +}; + +template +using direct_case_pipeline_t = + typename extract_case_pipeline::type; + +/// Total flattened leaf count for an aggregate struct `T` (recursing into +/// plain aggregate `rfl::Flatten` members). +template +consteval std::size_t direct_flattened_field_count(); + +template +consteval std::size_t direct_single_field_count() { + using U = std::remove_cvref_t; + if constexpr (is_flatten_field_v) { + using Sub = std::remove_cvref_t; + return direct_flattened_field_count(); + } else { + return 1; + } +} + +template +consteval std::size_t direct_flattened_field_count() { + using Type = std::remove_cvref_t; + using Count = decltype(apply_to_fields( + std::declval(), [](Fields&...) { + return std::integral_constant< + std::size_t, (std::size_t{0} + ... + + direct_single_field_count())>{}; + })); + return Count::value; +} + +template +inline constexpr std::size_t direct_flattened_field_count_v = + direct_flattened_field_count(); + +namespace detail { + +#ifndef REFLECTCPP_USE_CPP26_REFLECTION +using DirectNameInfo = cpp20::DirectFieldNameInfo; +#else +using DirectNameInfo = cpp26::DirectFieldNameInfo; +#endif + +template +struct direct_member_type { + using Type = std::remove_cvref_t; + using ptr_type = decltype(apply_to_fields( + std::declval(), [](Fields&...) { + return static_cast*>(nullptr); + })); + using raw_type = std::remove_pointer_t; +}; + +template +consteval std::array> +extract_flattened_raw_names(); + +template +#if defined(__GNUC__) && !defined(__clang__) +[[gnu::no_sanitize_undefined]] +#endif +consteval void append_member_names(DirectNameInfo* _out, std::size_t& _pos) { + using Type = std::remove_cvref_t; + using FieldT = + std::remove_cvref_t::raw_type>; + if constexpr (is_flatten_field_v) { + using Sub = std::remove_cvref_t; + const auto sub_names = extract_flattened_raw_names(); + for (const auto& info : sub_names) { + _out[_pos++] = info; + } + } else { +#ifndef REFLECTCPP_USE_CPP26_REFLECTION +#ifdef __clang__ + _out[_pos++] = cpp20::get_direct_field_name_info< + Type, cpp20::wrap(cpp20::get_ith_field_from_fake_object())>(); +#else + _out[_pos++] = cpp20::get_direct_field_name_info< + Type, cpp20::get_ith_field_from_fake_object()>(); +#endif +#else + _out[_pos++] = cpp26::get_direct_field_name_info(); +#endif + } +} + +template +consteval std::array> +extract_flattened_raw_names() { + using Type = std::remove_cvref_t; + std::array> out{}; + std::size_t pos = 0; + [&](std::index_sequence) { + (append_member_names(out.data(), pos), ...); + }(std::make_index_sequence>{}); + return out; +} + +/// Applies a single case-transform op from `src[0..src_len)` into `dst`, +/// returning the resulting length. Mirrors `include/rfl/internal/transform_case.hpp`. +consteval std::size_t apply_one_case_op(const DirectCaseOp _op, + const char* _src, + const std::size_t _src_len, + char* _dst) { + switch (_op) { + case DirectCaseOp::to_all_caps: { + for (std::size_t i = 0; i < _src_len; ++i) { + _dst[i] = to_upper(_src[i]); + } + return _src_len; + } + case DirectCaseOp::snake_to_kebab: { + for (std::size_t i = 0; i < _src_len; ++i) { + _dst[i] = _src[i] == '_' ? '-' : _src[i]; + } + return _src_len; + } + case DirectCaseOp::snake_to_camel: + case DirectCaseOp::snake_to_pascal: { + const bool capitalize = (_op == DirectCaseOp::snake_to_pascal); + std::size_t non_underscores = 0; + for (std::size_t i = 0; i < _src_len; ++i) { + if (_src[i] != '_') { + ++non_underscores; + } + } + if (non_underscores == 0) { + return 0; + } + _dst[0] = capitalize ? to_upper(_src[0]) : to_lower(_src[0]); + std::size_t shift = 1; + for (std::size_t i = 1; i < _src_len; ++i) { + if (_src[i] == '_') { + continue; + } + _dst[shift++] = _src[i - 1] == '_' ? to_upper(_src[i]) : _src[i]; + } + return shift; + } + case DirectCaseOp::camel_to_snake: { + std::size_t out_len = 0; + for (std::size_t i = 0; i < _src_len; ++i) { + if (is_upper(_src[i])) { + if (i > 0) { + _dst[out_len++] = '_'; + } + _dst[out_len++] = to_lower(_src[i]); + } else { + _dst[out_len++] = _src[i]; + } + } + return out_len; + } + } + return _src_len; +} + +template +consteval std::size_t worst_case_scratch_for_len(const std::size_t _raw_len, + DirectCasePipeline) { + std::size_t cap = _raw_len > 0 ? _raw_len : 1; + if constexpr (sizeof...(Ops) > 0) { + constexpr std::array ops = {Ops...}; + for (const auto op : ops) { + if (op == DirectCaseOp::camel_to_snake) { + // Every char after index 0 could be uppercase -> at most 2x growth. + cap *= 2; + } + } + } + return cap; +} + +template +consteval std::size_t transform_name_into(const DirectNameInfo _info, + char* _out_buf, + DirectCasePipeline) { + constexpr std::size_t kNumOps = sizeof...(Ops); + if constexpr (kNumOps == 0) { + for (std::size_t i = 0; i < _info.name.size(); ++i) { + _out_buf[i] = _info.name[i]; + } + return _info.name.size(); + } else { + if (_info.is_renamed) { + for (std::size_t i = 0; i < _info.name.size(); ++i) { + _out_buf[i] = _info.name[i]; + } + return _info.name.size(); + } + constexpr std::array ops = {Ops...}; + std::array a{}; + std::array b{}; + std::size_t len = _info.name.size(); + for (std::size_t i = 0; i < len; ++i) { + a[i] = _info.name[i]; + } + bool in_a = true; + for (const auto op : ops) { + const char* cur = in_a ? a.data() : b.data(); + // Every case-transform processor checks `name != "xml_content"` before + // transforming, so an intermediate "xml_content" stops further ops. + if (std::string_view(cur, len) == "xml_content") { + break; + } + if (in_a) { + len = apply_one_case_op(op, a.data(), len, b.data()); + } else { + len = apply_one_case_op(op, b.data(), len, a.data()); + } + in_a = !in_a; + } + const char* final_src = in_a ? a.data() : b.data(); + for (std::size_t i = 0; i < len; ++i) { + _out_buf[i] = final_src[i]; + } + return len; + } +} + +} // namespace detail + +/// Value-level flattened field name storage and lookup table keyed solely by +/// `(std::remove_cvref_t, CasePipeline)` — never by `StringLiteral` non-type +/// template parameters and shared across `DefaultIfMissing`, `NoExtraFields`, +/// `FailFast`, `read`, `write`, and `to_schema`. All names are copied into a +/// compact null-terminated char buffer so `__PRETTY_FUNCTION__` strings never +/// leak into `.rodata`. +template > +struct DirectFieldNames { + using CleanT = std::remove_cvref_t; + static constexpr std::size_t size_ = direct_flattened_field_count_v; + + private: + static consteval std::size_t compute_scratch_cap() { + const auto raw = detail::extract_flattened_raw_names(); + std::size_t max_len = 1; + for (const auto& info : raw) { + if (info.name.size() > max_len) { + max_len = info.name.size(); + } + } + return detail::worst_case_scratch_for_len(max_len, CasePipeline{}); + } + + static constexpr std::size_t scratch_cap_ = compute_scratch_cap(); + + static consteval auto compute_lengths() { + const auto raw = detail::extract_flattened_raw_names(); + std::array lens{}; + std::array scratch{}; + for (std::size_t i = 0; i < size_; ++i) { + lens[i] = detail::transform_name_into( + raw[i], scratch.data(), CasePipeline{}); + } + return lens; + } + + static constexpr auto lengths_ = compute_lengths(); + + static consteval std::size_t buffer_size() { + std::size_t total = size_; + for (const auto len : lengths_) { + total += len; + } + return total; + } + + static consteval auto make_buffer() { + const auto raw = detail::extract_flattened_raw_names(); + std::array buffer{}; + std::size_t offset = 0; + for (std::size_t i = 0; i < size_; ++i) { + const auto written = detail::transform_name_into( + raw[i], buffer.data() + offset, CasePipeline{}); + offset += written; + buffer[offset++] = '\0'; + } + return buffer; + } + + static constexpr auto buffer_ = make_buffer(); + + static consteval auto make_names() { + std::array names{}; + std::size_t offset = 0; + for (std::size_t i = 0; i < size_; ++i) { + names[i] = std::string_view(buffer_.data() + offset, lengths_[i]); + offset += lengths_[i] + 1; + } + return names; + } + + static consteval auto make_lookup() { + std::array table{}; + for (std::size_t i = 0; i < size_; ++i) { + table[i] = {names_[i], static_cast(i)}; + } + if constexpr (size_ > 8) { + parsing::detail::sort_field_name_table(table); + } + return table; + } + + static consteval bool has_unique_names() { + if constexpr (size_ <= 8) { + for (std::size_t i = 0; i < size_; ++i) { + for (std::size_t j = i + 1; j < size_; ++j) { + if (names_[i] == names_[j]) { + return false; + } + } + } + return true; + } else { + for (std::size_t i = 1; i < size_; ++i) { + if (lookup_[i - 1].name == lookup_[i].name) { + return false; + } + } + return true; + } + } + + public: + static constexpr auto names_ = make_names(); + static constexpr auto lookup_ = make_lookup(); + static_assert(has_unique_names(), "Duplicate field names are not allowed."); +}; + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/bind_to_tuple.hpp b/include/rfl/internal/bind_to_tuple.hpp index b6a578c34..70d719690 100644 --- a/include/rfl/internal/bind_to_tuple.hpp +++ b/include/rfl/internal/bind_to_tuple.hpp @@ -9,15 +9,21 @@ namespace rfl::internal { -template -auto bind_to_tuple(T& _t) { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION - return cpp20::bind_to_tuple(_t); + return cpp20::apply_to_fields(_t, static_cast(_f)); #else - return cpp26::bind_to_tuple(_t); + return cpp26::apply_to_fields(_t, static_cast(_f)); #endif } +template +auto bind_to_tuple(T& _t) { + return apply_to_fields(_t, + [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); +} + template auto bind_to_tuple(T& _t, const F& _f) { auto view = bind_to_tuple(_t); diff --git a/include/rfl/internal/cpp20/bind_to_tuple.hpp b/include/rfl/internal/cpp20/bind_to_tuple.hpp index 9733f1dbe..98b840bff 100644 --- a/include/rfl/internal/cpp20/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp20/bind_to_tuple.hpp @@ -16,14 +16,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) { +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 +4384,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, auto&& _f) { + return apply_to_fields_impl>(_t, + std::forward(_f)); +} + template auto bind_to_tuple(T& _t) { - return bind_to_tuple_impl>(_t); + return 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..bdb0eccc1 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 @@ -68,6 +69,36 @@ consteval auto get_field_name_str_view() { #endif } +template +struct single_literal_name_view; + +template +struct single_literal_name_view> { + static constexpr std::string_view value = _name.string_view(); +}; + +/// Returns a single non-flattened field's raw wire name and whether it was +/// explicitly renamed with rfl::Rename, without wrapping in rfl::Literal. +struct DirectFieldNameInfo { + std::string_view name; + bool is_renamed; +}; + +template +consteval DirectFieldNameInfo get_direct_field_name_info() { +#if defined(__clang__) + using FieldType = std::remove_cvref_t::Type>>; +#else + using FieldType = std::remove_cvref_t>; +#endif + if constexpr (is_rename_v) { + return {single_literal_name_view::value, true}; + } else { + return {get_field_name_str_view(), false}; + } +} + template consteval auto get_field_name_str_lit() { constexpr auto name = get_field_name_str_view(); diff --git a/include/rfl/internal/cpp26/bind_to_tuple.hpp b/include/rfl/internal/cpp26/bind_to_tuple.hpp index e98f3f2c8..69379d1b4 100644 --- a/include/rfl/internal/cpp26/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp26/bind_to_tuple.hpp @@ -15,11 +15,17 @@ namespace rfl::internal::cpp26 { template -auto bind_to_tuple(T& _t) { +decltype(auto) apply_to_fields(T& _t, auto&& _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 apply_to_fields(_t, + [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp26 diff --git a/include/rfl/internal/cpp26/get_field_names.hpp b/include/rfl/internal/cpp26/get_field_names.hpp index 07d872f84..5e3a37146 100644 --- a/include/rfl/internal/cpp26/get_field_names.hpp +++ b/include/rfl/internal/cpp26/get_field_names.hpp @@ -3,9 +3,11 @@ #ifdef REFLECTCPP_USE_CPP26_REFLECTION +#include #include #include #include +#include #include #include @@ -20,6 +22,32 @@ namespace rfl::internal::cpp26 { +template +struct single_literal_name_view; + +template +struct single_literal_name_view> { + static constexpr std::string_view value = _name.string_view(); +}; + +struct DirectFieldNameInfo { + std::string_view name; + bool is_renamed; +}; + +template +consteval DirectFieldNameInfo get_direct_field_name_info() { + using Type = std::remove_cvref_t; + constexpr auto members = std::define_static_array(get_members()); + using FieldType = + std::remove_cvref_t().[:members[_i]:])>; + if constexpr (is_rename_v) { + return {single_literal_name_view::value, true}; + } else { + return {std::meta::identifier_of(members[_i]), false}; + } +} + template consteval auto get_field_names(); diff --git a/include/rfl/internal/has_default_val_v.hpp b/include/rfl/internal/has_default_val_v.hpp index 1d19ef96b..63ad26358 100644 --- a/include/rfl/internal/has_default_val_v.hpp +++ b/include/rfl/internal/has_default_val_v.hpp @@ -2,11 +2,14 @@ #define RFL_HASDEFAULTVALV_HPP_ #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 { @@ -27,14 +30,40 @@ struct HasDefaultVal> { }; template - requires(std::is_class_v && std::is_aggregate_v) -struct HasDefaultVal : HasDefaultVal> {}; +constexpr bool has_default_val_type_v() { + using U = std::remove_cvref_t>; + if constexpr (is_field_v) { + return has_default_val_type_v(); + } else if constexpr (is_flatten_field_v) { + return HasDefaultVal< + std::remove_cvref_t>>::value; + } else { + return is_default_val_v; + } +} -template +template + requires(std::is_class_v && std::is_aggregate_v && !std::is_union_v) +struct HasDefaultVal { + private: + static consteval bool compute() { + using Result = decltype(apply_to_fields( + std::declval(), [](Fields&...) { + return std::bool_constant< + (false || ... || has_default_val_type_v())>{}; + })); + return Result::value; + } + + public: + static constexpr bool value = compute(); +}; + +template struct HasDefaultVal> : HasDefaultVal> { }; -template +template struct HasDefaultVal : HasDefaultVal> {}; template diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index fe4c576b3..3c895cf0f 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -27,6 +27,7 @@ namespace json { /// This class provides the interface for parsing JSON format into C++ objects. /// Uses the yyjson library for high-performance JSON parsing. struct Reader { + using UnsizedObjectReader = void; /// Represents a JSON array during deserialization. /// Wraps a pointer to the underlying yyjson value representing the array. struct YYJSONInputArray { diff --git a/include/rfl/msgpack/Reader.hpp b/include/rfl/msgpack/Reader.hpp index 5b84b2332..716e53003 100644 --- a/include/rfl/msgpack/Reader.hpp +++ b/include/rfl/msgpack/Reader.hpp @@ -18,6 +18,7 @@ namespace rfl { namespace msgpack { struct Reader { + using UnsizedObjectReader = void; using InputArrayType = msgpack_object_array; using InputObjectType = msgpack_object_map; using InputVarType = msgpack_object; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index edeaa3f4e..d00602767 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -365,6 +365,9 @@ struct NamedTupleParser { using SchemaType = std::conditional_t<_no_field_names, schema::Type::Tuple, schema::Type::Object>; + static constexpr bool ignore_empty_containers_ = _ignore_empty_containers; + static constexpr bool all_required_ = _all_required; + static constexpr bool no_field_names_ = _no_field_names; static constexpr size_t size_ = NamedTupleType::size(); static_assert(NamedTupleType::pos_extra_fields() == -1 || !_no_field_names, diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..630440b16 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -27,6 +27,7 @@ #include "AreReaderAndWriter.hpp" #include "MapParser.hpp" #include "Parent.hpp" +#include "TableStructParser.hpp" #include "ParserArray.hpp" #include "ParserAtomic.hpp" #include "ParserAtomicFlag.hpp" @@ -440,6 +441,11 @@ struct Parser { Parser::write(_w, r, _parent); } + } else if constexpr (can_use_table_struct_parser_v) { + TableStructParser, ProcessorsType>::write( + _w, _var, _parent); + } else { const auto ptr_named_tuple = ProcessorsType::template process( internal::to_ptr_named_tuple(_var)); @@ -663,6 +669,24 @@ struct Parser { (*_definitions)[name] = Parser::ReflType, ProcessorsType>::to_schema(_definitions); + } else if constexpr (can_use_table_struct_parser_v && + std::is_same_v>) { + if constexpr (internal::has_default_val_v) { + static_assert(requires { U{}; }, + "A struct with rfl::DefaultVal fields must be " + "default-constructible, because the default values " + "come from a default-constructed instance."); + const auto defaults = U{}; + (*_definitions)[name] = + TableStructParser::to_schema( + _definitions, &defaults); + } else { + (*_definitions)[name] = + TableStructParser::to_schema( + _definitions); + } + } else { using NamedTupleType = internal::processed_t; // The schema takes the default values of rfl::DefaultVal fields from @@ -710,20 +734,25 @@ struct Parser { /// might not be default-constructible. static RFL_ALWAYS_INLINE Result read_struct(const R& _r, const InputVarType& _var) { - alignas(T) unsigned char buf[sizeof(T)]{}; - auto ptr = internal::ptr_cast(&buf); - auto raw_view = to_view(*ptr); - auto view = ProcessorsType::template process(std::move(raw_view)); - using ViewType = std::remove_cvref_t; - auto [set, err] = - Parser::read_view(_r, _var, &view); - if (err) [[unlikely]] { + if constexpr (can_use_table_struct_parser_v) { + return TableStructParser, + ProcessorsType>::read(_r, _var); + } else { + alignas(T) unsigned char buf[sizeof(T)]{}; + auto ptr = internal::ptr_cast(&buf); + auto raw_view = to_view(*ptr); + auto view = ProcessorsType::template process(std::move(raw_view)); + using ViewType = std::remove_cvref_t; + auto [set, err] = + Parser::read_view(_r, _var, &view); + if (err) [[unlikely]] { + call_destructors_where_necessary(set, &view); + return error(std::move(*err)); + } + auto res = Result(std::move(*ptr)); call_destructors_where_necessary(set, &view); - return error(std::move(*err)); + return res; } - auto res = Result(std::move(*ptr)); - call_destructors_where_necessary(set, &view); - return res; } /// This is actually more straight-forward than the standard case - we @@ -741,15 +770,26 @@ struct Parser { // satisfy its validator. The outer handler is for this line only. auto t = T{}; try { - auto view = ProcessorsType::template process(to_view(t)); - using ViewType = decltype(view); - auto err = - Parser::read_view_with_default( - _r, _var, &view); - if (err) [[unlikely]] { - return error(std::move(*err)); + if constexpr (can_use_table_struct_parser_v) { + auto err = TableStructParser, + ProcessorsType>::read_with_default(_r, + _var, + &t); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return t; + } else { + auto view = ProcessorsType::template process(to_view(t)); + using ViewType = decltype(view); + auto err = + Parser::read_view_with_default( + _r, _var, &view); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return t; } - return t; } catch (std::exception& e) { return error(e.what()); } diff --git a/include/rfl/parsing/TableStructParser.hpp b/include/rfl/parsing/TableStructParser.hpp new file mode 100644 index 000000000..da5efd4f6 --- /dev/null +++ b/include/rfl/parsing/TableStructParser.hpp @@ -0,0 +1,1265 @@ +#ifndef RFL_PARSING_TABLESTRUCTPARSER_HPP_ +#define RFL_PARSING_TABLESTRUCTPARSER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../AddTagsToVariants.hpp" +#include "../AllowRawPtrs.hpp" +#include "../CamelCaseToSnakeCase.hpp" +#include "../DefaultIfMissing.hpp" +#include "../DurationsAsCount.hpp" +#include "../EnumNamesOnly.hpp" +#include "../FailFast.hpp" +#include "../Flatten.hpp" +#include "../NamedTuple.hpp" +#include "../NoExtraFields.hpp" +#include "../NoFieldNames.hpp" +#include "../NoOptionals.hpp" +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToCamelCase.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../SnakeCaseToPascalCase.hpp" +#include "../ToAllCaps.hpp" +#include "../UnderlyingEnums.hpp" +#include "../internal/DirectFieldNames.hpp" +#include "../internal/always_inline.hpp" +#include "../internal/bind_to_tuple.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/has_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_field.hpp" +#include "../internal/is_flatten_field.hpp" +#include "../internal/no_extra_fields_v.hpp" +#include "../internal/ptr_cast.hpp" +#include "../num_fields.hpp" +#include "FieldErrors.hpp" +#include "NamedTupleParser.hpp" +#include "Parent.hpp" +#include "Parser_base.hpp" +#include "ViewReader.hpp" +#include "ViewReaderWithDefault.hpp" +#include "call_destructors_where_necessary.hpp" +#include "find_field_index.hpp" +#include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "to_single_error_message.hpp" +#include "wrap_error.hpp" + +namespace rfl::parsing { + +namespace detail { + +template +struct is_table_supported_processor : std::false_type {}; + +#define RFL_TABLE_SUPPORTED_PROCESSOR(Type) \ + template <> \ + struct is_table_supported_processor : std::true_type {} + +RFL_TABLE_SUPPORTED_PROCESSOR(DefaultIfMissing); +RFL_TABLE_SUPPORTED_PROCESSOR(NoExtraFields); +RFL_TABLE_SUPPORTED_PROCESSOR(NoFieldNames); +RFL_TABLE_SUPPORTED_PROCESSOR(NoOptionals); +RFL_TABLE_SUPPORTED_PROCESSOR(FailFast); +RFL_TABLE_SUPPORTED_PROCESSOR(UnderlyingEnums); +RFL_TABLE_SUPPORTED_PROCESSOR(EnumNamesOnly); +RFL_TABLE_SUPPORTED_PROCESSOR(AddTagsToVariants); +RFL_TABLE_SUPPORTED_PROCESSOR(AddNamespacedTagsToVariants); +RFL_TABLE_SUPPORTED_PROCESSOR(DurationsAsCount); +RFL_TABLE_SUPPORTED_PROCESSOR(AllowRawPtrs); +RFL_TABLE_SUPPORTED_PROCESSOR(SnakeCaseToCamelCase); +RFL_TABLE_SUPPORTED_PROCESSOR(SnakeCaseToPascalCase); +RFL_TABLE_SUPPORTED_PROCESSOR(CamelCaseToSnakeCase); +RFL_TABLE_SUPPORTED_PROCESSOR(SnakeCaseToKebabCase); +RFL_TABLE_SUPPORTED_PROCESSOR(ToAllCaps); + +#undef RFL_TABLE_SUPPORTED_PROCESSOR + +template +struct is_table_supported_processor_pack : is_table_supported_processor {}; + +template +struct is_table_supported_processor_pack> + : std::bool_constant< + (is_table_supported_processor_pack::value && ...)> {}; + +template +concept ReaderSupportsUnsizedObjectReader = + requires { typename R::UnsizedObjectReader; }; + +template +concept HasNamedTupleFormatPolicy = requires { + { + Parser, ProcessorsType>::ignore_empty_containers_ + } -> std::convertible_to; + { + Parser, ProcessorsType>::all_required_ + } -> std::convertible_to; + { + Parser, ProcessorsType>::no_field_names_ + } -> std::convertible_to; +}; + +template +consteval bool table_fields_are_supported(); + +template +consteval bool table_single_field_supported() { + using U = std::remove_cvref_t; + if constexpr (internal::is_field_v) { + return false; + } else if constexpr (internal::is_flatten_field_v) { + using Sub = std::remove_cvref_t; + if constexpr (std::is_pointer_v || !std::is_class_v || + !std::is_aggregate_v || std::is_union_v) { + return false; + } else { + return table_fields_are_supported(); + } + } else { + return true; + } +} + +template +consteval bool table_fields_are_supported() { + using Result = decltype(internal::apply_to_fields( + std::declval(), [](Fields&...) { + return std::bool_constant< + (true && ... && table_single_field_supported())>{}; + })); + return Result::value; +} + +template +struct TableFieldTypeList {}; + +template +struct concat_type_lists; + +template +struct concat_type_lists, TableFieldTypeList> { + using type = TableFieldTypeList; +}; + +template +struct concat_all_type_lists; + +template <> +struct concat_all_type_lists<> { + using type = TableFieldTypeList<>; +}; + +template +struct concat_all_type_lists { + using type = L; +}; + +template +struct concat_all_type_lists { + using type = typename concat_all_type_lists< + typename concat_type_lists::type, Rest...>::type; +}; + +template +struct flattened_field_type_list; + +template +struct single_field_type_list { + using type = TableFieldTypeList; +}; + +template +struct single_field_type_list> { + using type = + typename flattened_field_type_list::Type>::type; +}; + +template +struct single_field_type_list> { + using type = typename flattened_field_type_list< + const typename Flatten::Type>::type; +}; + +template +struct flattened_field_type_list { + using type = decltype(internal::apply_to_fields( + std::declval(), [](Fields&...) { + return typename concat_all_type_lists< + typename single_field_type_list::type...>::type{}; + })); +}; + +template +using flattened_field_type_list_t = typename flattened_field_type_list::type; + +template +struct extra_fields_info; + +template +struct extra_fields_info> { + static consteval int count() { + return (0 + ... + + (internal::is_extra_fields_v> ? 1 : 0)); + } + + static consteval int pos() { + int result = -1; + int idx = 0; + ((internal::is_extra_fields_v> + ? (result = idx) + : 0, + ++idx), + ...); + return result; + } + + static constexpr int count_ = count(); + static constexpr int pos_ = pos(); +}; + +template +inline void collect_flattened_mutable_ptrs_impl(T& _t, void** _out, + std::size_t& _pos) noexcept { + internal::apply_to_fields(_t, [_out, &_pos](auto&... _refs) noexcept { + const auto push = [_out, &_pos](auto& _ref) noexcept { + using U = std::remove_cvref_t; + if constexpr (internal::is_flatten_field_v) { + collect_flattened_mutable_ptrs_impl(_ref.value_, _out, _pos); + } else { + _out[_pos++] = + const_cast(static_cast(std::addressof(_ref))); + } + }; + (push(_refs), ...); + }); +} + +template +inline void collect_flattened_const_ptrs_impl(const T& _t, const void** _out, + std::size_t& _pos) noexcept { + internal::apply_to_fields(_t, [_out, &_pos](const auto&... _refs) noexcept { + const auto push = [_out, &_pos](const auto& _ref) noexcept { + using U = std::remove_cvref_t; + if constexpr (internal::is_flatten_field_v) { + collect_flattened_const_ptrs_impl(_ref.value_, _out, _pos); + } else { + _out[_pos++] = static_cast(std::addressof(_ref)); + } + }; + (push(_refs), ...); + }); +} + +template +inline auto collect_flattened_mutable_ptrs(T& _t) noexcept { + std::array> ptrs{}; + std::size_t pos = 0; + collect_flattened_mutable_ptrs_impl(_t, ptrs.data(), pos); + return ptrs; +} + +template +inline auto collect_flattened_const_ptrs(const T& _t) noexcept { + std::array> ptrs{}; + std::size_t pos = 0; + collect_flattened_const_ptrs_impl(_t, ptrs.data(), pos); + return ptrs; +} + +/// Shared lookup helper operating on descriptor table slices (never templated +/// on `T` or `N`). +inline int find_in_table(const FieldNameEntry* _lookup, const std::size_t _size, + const std::string_view _name) noexcept { + if (_size <= 8) { + for (std::size_t i = 0; i < _size; ++i) { + if (_lookup[i].name == _name) { + return _lookup[i].field_idx; + } + } + return -1; + } + std::size_t lo = 0; + std::size_t hi = _size; + while (lo < hi) { + const std::size_t mid = lo + (hi - lo) / 2; + if (_lookup[mid].name < _name) { + lo = mid + 1; + } else { + hi = mid; + } + } + return (lo < _size && _lookup[lo].name == _name) ? _lookup[lo].field_idx : -1; +} + +/// Type-erased per-field thunks parameterized ONLY by individual field type +/// (never by enclosing struct `T`, `NamedTuple`, or `Tuple`). + +template +void read_uninit_field_erased(const R& _r, + const typename R::InputVarType& _var, + const std::string_view _name, void* _field_ptr, + bool& _is_set, + FieldErrors* _errors, + const std::size_t _reserve_errors) { + auto* ptr = static_cast(_field_ptr); + detail::assign_uninitialized_view_field( + _r, _var, _name, ptr, _is_set, _errors, _reserve_errors); +} + +template +void read_extra_uninit_erased(const R& _r, const std::string_view _current_name, + const typename R::InputVarType& _var, + void* _extra_ptr, bool& _is_found, bool& _is_set, + FieldErrors* _errors) { + static_assert(!std::is_const_v, + "rfl::ExtraFields field cannot be const."); + using CleanExtra = std::remove_cvref_t; + auto* extra = static_cast(_extra_ptr); + detail::assign_extra_uninitialized_field( + _r, _current_name, _var, extra, _is_found, _is_set, _errors); +} + +template +void read_default_field_erased(const R& _r, + const typename R::InputVarType& _var, + const std::string_view _name, void* _field_ptr, + FieldErrors* _errors) { + auto* ptr = static_cast(_field_ptr); + detail::assign_default_view_field( + _r, _var, _name, ptr, _errors); +} + +template +void read_extra_default_erased(const R& _r, + const std::string_view _current_name, + const typename R::InputVarType& _var, + void* _extra_ptr, + FieldErrors* _errors) { + static_assert(!std::is_const_v, + "rfl::ExtraFields field cannot be const."); + using CleanExtra = std::remove_cvref_t; + auto* extra = static_cast(_extra_ptr); + detail::assign_extra_default_field( + _r, _current_name, _var, extra, _errors); +} + +template +void handle_missing_field_erased( + const std::string_view _name, const bool _is_found, void* _field_ptr, + bool* _is_set_ptr, FieldErrors* _errors, + const bool _value_initialize_default_vals) noexcept { + auto* ptr = static_cast(_field_ptr); + detail::handle_missing_named_tuple_field< + _ignore_empty_containers, _all_required, _defaults_constructed, + ProcessorsType>(_name, _is_found, ptr, _is_set_ptr, _errors, + _value_initialize_default_vals); +} + +template +void destroy_field_erased(void* _field_ptr) noexcept { + auto* ptr = static_cast(_field_ptr); + detail::destroy_field_if_set(true, ptr); +} + +template +void write_field_erased(const W& _w, const std::string_view _name, + const void* _field_ptr, + OutputObjectOrArrayType* _ptr) { + using CleanFieldT = std::remove_cvref_t; + const auto* ptr = static_cast(_field_ptr); + detail::write_named_tuple_field(_w, _name, + ptr, _ptr); +} + +template +std::size_t extra_fields_size_erased(const void* _field_ptr) noexcept { + using CleanExtra = std::remove_cvref_t; + return static_cast(_field_ptr)->size(); +} + +template +void build_schema_field_erased( + std::map* _definitions, SchemaType* _schema, + const std::string_view _name, const void* _default_field_ptr) { + using U = std::remove_cvref_t; + const U* ptr = static_cast(_default_field_ptr); + detail::build_named_tuple_field_schema(_definitions, _schema, _name, ptr); +} + +template +schema::Type build_extra_schema_erased( + std::map* _definitions) { + using CleanExtra = std::remove_cvref_t; + using U = std::remove_cvref_t; + return Parser::to_schema(_definitions); +} + +template +struct nth_type_in_list; + +template +struct nth_type_in_list<_pos, TableFieldTypeList> + : nth_type_in_list<_pos - 1, TableFieldTypeList> {}; + +template +struct nth_type_in_list<0, TableFieldTypeList> { + using type = Head; +}; + +} // namespace detail + +template +inline constexpr bool can_use_table_struct_parser_v = [] { + using Type = std::remove_cvref_t; + if constexpr (!detail::HasNamedTupleFormatPolicy || + !std::is_class_v || !std::is_aggregate_v || + std::is_union_v || + !detail::is_table_supported_processor_pack< + ProcessorsType>::value) { + return false; + } else if constexpr (!detail::table_fields_are_supported()) { + return false; + } else { + return internal::direct_flattened_field_count_v > 0; + } +}(); + +// ---------------------------------------------------------------------------- +// Non-`T`-parameterized descriptor-table view readers. +// Instantiated ONCE per `(R, W, ProcessorsType)` across the entire TU! +// ---------------------------------------------------------------------------- + +template +class TableViewReader { + public: + using InputVarType = typename R::InputVarType; + using ReadUninitFn = void (*)(const R&, const InputVarType&, std::string_view, + void*, bool&, FieldErrors*, + std::size_t); + using ReadExtraUninitFn = void (*)(const R&, std::string_view, + const InputVarType&, void*, bool&, bool&, + FieldErrors*); + + struct Desc { + const std::string_view* names; + const detail::FieldNameEntry* lookup; + const ReadUninitFn* read_fns; + std::size_t size; + int pos_extra_fields; + ReadExtraUninitFn read_extra_fn; + }; + + TableViewReader(const R* _r, const Desc* _desc, void* const* _field_ptrs, + bool* _found, bool* _set, + FieldErrors* _errors) noexcept + : r_(_r), + desc_(_desc), + field_ptrs_(_field_ptrs), + found_(_found), + set_(_set), + errors_(_errors) {} + + ~TableViewReader() = default; + + std::span field_names() const noexcept { + return {desc_->names, desc_->size}; + } + + void read(const std::string_view& _name, const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) return; + bool already_assigned = false; + if (const int idx = + detail::find_in_table(desc_->lookup, desc_->size, _name); + idx >= 0 && idx != desc_->pos_extra_fields) { + const auto u = static_cast(idx); + if (!found_[u]) { + found_[u] = true; + already_assigned = true; + desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], set_[u], + errors_, desc_->size); + } + } + if (desc_->pos_extra_fields >= 0) { + if (!already_assigned) { + const auto pos = static_cast(desc_->pos_extra_fields); + desc_->read_extra_fn(*r_, _name, _var, field_ptrs_[pos], found_[pos], + set_[pos], errors_); + } + } else if constexpr (internal::no_extra_fields_v) { + if (!already_assigned) { + std::stringstream stream; + stream << "Value named '" << _name << "' not used."; + errors_->emplace_back( + make_nested_error(std::string(_name), stream.str())); + } + } + } + + void read(const int _index, const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) return; + bool already_assigned = false; + if (_index >= 0 && static_cast(_index) < desc_->size && + _index != desc_->pos_extra_fields) { + const auto u = static_cast(_index); + if (!found_[u]) { + found_[u] = true; + already_assigned = true; + desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], set_[u], + errors_, desc_->size); + } + } + if constexpr (internal::no_extra_fields_v) { + if (desc_->pos_extra_fields < 0 && !already_assigned) { + std::stringstream stream; + stream << "Value named '" << _index << "' not used."; + errors_->emplace_back( + make_nested_error(static_cast(_index), stream.str())); + } + } + } + + template + void read(std::integral_constant, const InputVarType& _var) const { + read(i, _var); + } + + protected: + const R* r_; + const Desc* desc_; + void* const* field_ptrs_; + bool* found_; + bool* set_; + FieldErrors* errors_; +}; + +/// Thin static-size adapter for positional/schemaful/external readers that +/// require `ObjectReader::size()` as a compile-time constant. +template +class SizedTableViewReader : public TableViewReader { + public: + using Base = TableViewReader; + using InputVarType = typename Base::InputVarType; + using Base::Base; + using Base::read; + + void read(const int _index, const InputVarType& _var) const { + static_assert(!_has_extra_fields, + "rfl::ExtraFields are not supported for positional reads."); + Base::read(_index, _var); + } + + template + void read(std::integral_constant, const InputVarType& _var) const { + static_assert(!_has_extra_fields, + "rfl::ExtraFields are not supported for positional reads."); + Base::read(i, _var); + } + + static constexpr std::size_t size() noexcept { return _size; } +}; + +template +class TableViewReaderWithDefault { + public: + using InputVarType = typename R::InputVarType; + using ReadDefaultFn = void (*)(const R&, const InputVarType&, + std::string_view, void*, + FieldErrors*); + using ReadExtraDefaultFn = void (*)(const R&, std::string_view, + const InputVarType&, void*, + FieldErrors*); + + struct Desc { + const std::string_view* names; + const detail::FieldNameEntry* lookup; + const ReadDefaultFn* read_fns; + std::size_t size; + int pos_extra_fields; + ReadExtraDefaultFn read_extra_fn; + }; + + TableViewReaderWithDefault(const R* _r, const Desc* _desc, + void* const* _field_ptrs, bool* _found, + FieldErrors* _errors) noexcept + : r_(_r), + desc_(_desc), + field_ptrs_(_field_ptrs), + found_(_found), + errors_(_errors) {} + + ~TableViewReaderWithDefault() = default; + + std::span field_names() const noexcept { + return {desc_->names, desc_->size}; + } + + void read(const std::string_view& _name, const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) return; + bool already_assigned = false; + if (const int idx = + detail::find_in_table(desc_->lookup, desc_->size, _name); + idx >= 0 && idx != desc_->pos_extra_fields) { + const auto u = static_cast(idx); + if (!found_[u]) { + found_[u] = true; + already_assigned = true; + desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], errors_); + } + } + if (desc_->pos_extra_fields >= 0) { + if (!already_assigned) { + const auto pos = static_cast(desc_->pos_extra_fields); + desc_->read_extra_fn(*r_, _name, _var, field_ptrs_[pos], errors_); + } + } else if constexpr (internal::no_extra_fields_v) { + if (!already_assigned) { + std::stringstream stream; + stream << "Value named '" << std::string(_name) + << "' not used. Remove the rfl::NoExtraFields processor or add " + "rfl::ExtraFields to avoid this error message."; + errors_->emplace_back( + make_nested_error(std::string(_name), stream.str())); + } + } + } + + void read(const int _index, const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) return; + bool already_assigned = false; + if (_index >= 0 && static_cast(_index) < desc_->size && + _index != desc_->pos_extra_fields) { + const auto u = static_cast(_index); + if (!found_[u]) { + found_[u] = true; + already_assigned = true; + desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], errors_); + } + } + if constexpr (internal::no_extra_fields_v) { + if (desc_->pos_extra_fields < 0 && !already_assigned) { + std::stringstream stream; + stream << "Value named '" << _index << "' not used."; + errors_->emplace_back( + make_nested_error(static_cast(_index), stream.str())); + } + } + } + + template + void read(std::integral_constant, const InputVarType& _var) const { + read(i, _var); + } + + protected: + const R* r_; + const Desc* desc_; + void* const* field_ptrs_; + bool* found_; + FieldErrors* errors_; +}; + +template +class SizedTableViewReaderWithDefault + : public TableViewReaderWithDefault { + public: + using Base = TableViewReaderWithDefault; + using InputVarType = typename Base::InputVarType; + using Base::Base; + using Base::read; + + void read(const int _index, const InputVarType& _var) const { + static_assert(!_has_extra_fields, + "rfl::ExtraFields are not supported for positional reads."); + Base::read(_index, _var); + } + + template + void read(std::integral_constant, const InputVarType& _var) const { + static_assert(!_has_extra_fields, + "rfl::ExtraFields are not supported for positional reads."); + Base::read(i, _var); + } + + static constexpr std::size_t size() noexcept { return _size; } +}; + +template +class TableViewReaderStripped { + public: + using InputVarType = typename R::InputVarType; + using Desc = typename TableViewReader::Desc; + + TableViewReaderStripped(const R* _r, const Desc* _desc, + void* const* _field_ptrs, bool* _found, bool* _set, + FieldErrors* _errors) noexcept + : i_(0), + r_(_r), + desc_(_desc), + field_ptrs_(_field_ptrs), + found_(_found), + set_(_set), + errors_(_errors) {} + + ~TableViewReaderStripped() = default; + + std::optional read(const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) { + return std::nullopt; + } + if (i_ == desc_->size) { + std::stringstream stream; + stream << "Expected a maximum of " << std::to_string(desc_->size) + << " fields, but got at least one more."; + return Error(stream.str()); + } + found_[i_] = true; + desc_->read_fns[i_](*r_, _var, desc_->names[i_], field_ptrs_[i_], set_[i_], + errors_, desc_->size); + ++i_; + return std::nullopt; + } + + private: + mutable std::size_t i_; + const R* r_; + const Desc* desc_; + void* const* field_ptrs_; + bool* found_; + bool* set_; + FieldErrors* errors_; +}; + +template +class TableViewReaderWithDefaultStripped { + public: + using InputVarType = typename R::InputVarType; + using Desc = typename TableViewReaderWithDefault::Desc; + + TableViewReaderWithDefaultStripped( + const R* _r, const Desc* _desc, void* const* _field_ptrs, bool* _found, + FieldErrors* _errors) noexcept + : i_(0), + r_(_r), + desc_(_desc), + field_ptrs_(_field_ptrs), + found_(_found), + errors_(_errors) {} + + ~TableViewReaderWithDefaultStripped() = default; + + std::optional read(const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) { + return std::nullopt; + } + if (i_ == desc_->size) { + std::stringstream stream; + stream << "Expected a maximum of " << std::to_string(desc_->size) + << " fields, but got at least one more."; + return Error(stream.str()); + } + found_[i_] = true; + desc_->read_fns[i_](*r_, _var, desc_->names[i_], field_ptrs_[i_], errors_); + ++i_; + return std::nullopt; + } + + private: + mutable std::size_t i_; + const R* r_; + const Desc* desc_; + void* const* field_ptrs_; + bool* found_; + FieldErrors* errors_; +}; + +// ---------------------------------------------------------------------------- +// Non-`T`-parameterized shared driver functions. +// Instantiated ONCE per `(R, W, ProcessorsType)` per TU! +// ---------------------------------------------------------------------------- + +namespace detail { + +using DestroyFn = void (*)(void*) noexcept; + +inline void destroy_set_fields_table(const DestroyFn* _destroy_fns, + const bool* _set, + void* const* _field_ptrs, + const std::size_t _size) noexcept { + for (std::size_t i = 0; i < _size; ++i) { + if (_set[i] && _destroy_fns[i] != nullptr) { + _destroy_fns[i](_field_ptrs[i]); + } + } +} + +/// RAII scope guard guaranteeing every placement-constructed field in `buf` is +/// destroyed on error return, normal move return, or exception unwind (e.g. if +/// `T`'s move constructor or a field constructor throws). +struct UninitFieldsGuard { + const DestroyFn* destroy_fns; + const bool* set; + void* const* field_ptrs; + std::size_t size; + + ~UninitFieldsGuard() noexcept { + destroy_set_fields_table(destroy_fns, set, field_ptrs, size); + } +}; + +template +std::optional read_table_uninit_common( + const R& _r, const typename R::InputVarType& _var, + const typename TableViewReader::Desc& _desc, + void (*const* _missing_fns)(std::string_view, bool, void*, bool*, + FieldErrors*, bool) noexcept, + void* const* _field_ptrs, bool* _found, bool* _set) { + FieldErrors errors; + if constexpr (_no_field_names) { + auto arr = _r.to_array(_var); + if (!arr) [[unlikely]] { + return arr.error(); + } + const auto reader = TableViewReaderStripped( + &_r, &_desc, _field_ptrs, _found, _set, &errors); + if (auto err = _r.read_array(reader, *arr)) [[unlikely]] { + return err; + } + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return obj.error(); + } + const auto reader = + ReaderObj(&_r, &_desc, _field_ptrs, _found, _set, &errors); + if (auto err = _r.read_object(reader, *obj)) [[unlikely]] { + return err; + } + } + + if (!should_stop_on_field_error(errors)) { + for (std::size_t i = 0; i < _desc.size; ++i) { + _missing_fns[i](_desc.names[i], _found[i], _field_ptrs[i], &_set[i], + &errors, /*_value_initialize_default_vals=*/false); + } + } + + if constexpr (internal::fail_fast_v) { + return std::move(errors).error(); + } else { + if (errors.size() != 0) [[unlikely]] { + return to_single_error(std::move(errors)); + } + return std::nullopt; + } +} + +template +std::optional read_table_with_default_common( + const R& _r, const typename R::InputVarType& _var, + const typename TableViewReaderWithDefault::Desc& + _desc, + void (*const* _missing_fns)(std::string_view, bool, void*, bool*, + FieldErrors*, bool) noexcept, + void* const* _field_ptrs, bool* _found) { + FieldErrors errors; + if constexpr (_no_field_names) { + auto arr = _r.to_array(_var); + if (!arr) [[unlikely]] { + return arr.error(); + } + const auto reader = + TableViewReaderWithDefaultStripped( + &_r, &_desc, _field_ptrs, _found, &errors); + if (auto err = _r.read_array(reader, *arr)) [[unlikely]] { + return err; + } + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return obj.error(); + } + const auto reader = ReaderObj(&_r, &_desc, _field_ptrs, _found, &errors); + if (auto err = _r.read_object(reader, *obj)) [[unlikely]] { + return err; + } + } + + if (_missing_fns != nullptr && + !should_stop_on_field_error(errors)) { + for (std::size_t i = 0; i < _desc.size; ++i) { + _missing_fns[i](_desc.names[i], _found[i], _field_ptrs[i], nullptr, + &errors, /*_value_initialize_default_vals=*/false); + } + } + + if constexpr (internal::fail_fast_v) { + return std::move(errors).error(); + } else { + if (errors.size() != 0) [[unlikely]] { + return to_single_error(std::move(errors)); + } + return std::nullopt; + } +} + +template +void write_table_common( + const W& _w, const std::string_view* _names, + void (*const* _write_fns)(const W&, std::string_view, const void*, + OutputObjectOrArrayType*), + const void* const* _field_ptrs, const std::size_t _size, + const int _pos_extra_fields, + std::size_t (*_extra_size_fn)(const void*) noexcept, const P& _parent) { + using ParentType = Parent; + const std::size_t total_fields = + (_pos_extra_fields >= 0 && _extra_size_fn != nullptr) + ? (_size - 1 + + _extra_size_fn( + _field_ptrs[static_cast(_pos_extra_fields)])) + : _size; + if constexpr (_no_field_names) { + auto arr = ParentType::add_array(_w, total_fields, _parent); + for (std::size_t i = 0; i < _size; ++i) { + _write_fns[i](_w, _names[i], _field_ptrs[i], &arr); + } + _w.end_array(&arr); + } else { + auto obj = ParentType::add_object(_w, total_fields, _parent); + for (std::size_t i = 0; i < _size; ++i) { + _write_fns[i](_w, _names[i], _field_ptrs[i], &obj); + } + _w.end_object(&obj); + } +} + +template +schema::Type to_schema_table_common( + std::map* _definitions, + const std::string_view* _names, + void (*const* _schema_fns)(std::map*, + SchemaType*, std::string_view, const void*), + const void* const* _default_ptrs, const std::size_t _size, + schema::Type (*_extra_schema_fn)(std::map*)) { + SchemaType schema; + for (std::size_t i = 0; i < _size; ++i) { + _schema_fns[i](_definitions, &schema, _names[i], + _default_ptrs ? _default_ptrs[i] : nullptr); + } + if constexpr (!_no_field_names) { + if (_extra_schema_fn != nullptr) { + schema.additional_properties_ = + std::make_shared(_extra_schema_fn(_definitions)); + } else if constexpr (internal::no_extra_fields_v) { + schema.additional_properties_ = false; + } + } + return schema::Type{schema}; +} + +} // namespace detail + +/// Type-erased descriptor-table aggregate parser. Bypasses `rfl::NamedTuple`, +/// `rfl::Tuple`, and per-struct `ViewReader` / `NamedTupleParser` templates +/// completely: each struct `T` emits only `static constexpr` data tables and +/// delegates all loops to non-`T`-parameterized shared drivers. +template +struct TableStructParser { + using InputVarType = typename R::InputVarType; + using CasePipeline = internal::direct_case_pipeline_t; + using Names = internal::DirectFieldNames; + using FieldList = detail::flattened_field_type_list_t; + using ExtraInfo = detail::extra_fields_info; + + static constexpr std::size_t size_ = Names::size_; + static constexpr int pos_extra_fields_ = ExtraInfo::pos_; + + static_assert(ExtraInfo::count_ <= 1, + "There can be at most one rfl::ExtraFields field per struct."); + + using FormatNTParser = Parser, ProcessorsType>; + static constexpr bool ignore_empty_containers_ = + FormatNTParser::ignore_empty_containers_; + static constexpr bool all_required_ = FormatNTParser::all_required_; + static constexpr bool no_field_names_ = FormatNTParser::no_field_names_; + + static_assert(pos_extra_fields_ == -1 || !no_field_names_, + "You cannot use the rfl::NoFieldNames processor if you are " + "including rfl::ExtraFields."); + + using OutputObjectOrArrayType = + std::conditional_t; + using SchemaType = std::conditional_t; + + using UninitReader = std::conditional_t< + detail::ReaderSupportsUnsizedObjectReader, + TableViewReader, + SizedTableViewReader>; + using DefaultReader = std::conditional_t< + detail::ReaderSupportsUnsizedObjectReader, + TableViewReaderWithDefault, + SizedTableViewReaderWithDefault>; + + using ReadUninitFn = + typename TableViewReader::ReadUninitFn; + using ReadExtraUninitFn = + typename TableViewReader::ReadExtraUninitFn; + using ReadDefaultFn = + typename TableViewReaderWithDefault::ReadDefaultFn; + using ReadExtraDefaultFn = typename TableViewReaderWithDefault< + R, W, ProcessorsType>::ReadExtraDefaultFn; + using MissingFn = void (*)(std::string_view, bool, void*, bool*, + FieldErrors*, bool) noexcept; + using DestroyFn = detail::DestroyFn; + using WriteFn = void (*)(const W&, std::string_view, const void*, + OutputObjectOrArrayType*); + using SchemaFn = void (*)(std::map*, SchemaType*, + std::string_view, const void*); + + private: + template + static consteval ReadUninitFn make_read_uninit_fn() noexcept { + if constexpr (internal::is_extra_fields_v>) { + return nullptr; + } else { + return &detail::read_uninit_field_erased; + } + } + + template + static consteval auto make_read_uninit_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + make_read_uninit_fn()...}; + } + + template + static consteval ReadDefaultFn make_read_default_fn() noexcept { + if constexpr (internal::is_extra_fields_v>) { + return nullptr; + } else { + return &detail::read_default_field_erased; + } + } + + template + static consteval auto make_read_default_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + make_read_default_fn()...}; + } + + template + static consteval auto make_missing_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + &detail::handle_missing_field_erased< + ignore_empty_containers_, all_required_, _defaults_constructed, + ProcessorsType, Fields>...}; + } + + template + static consteval DestroyFn make_destroy_fn() noexcept { + if constexpr (std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + return nullptr; + } else { + return &detail::destroy_field_erased; + } + } + + template + static consteval auto make_destroy_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + make_destroy_fn()...}; + } + + template + static consteval auto make_write_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + &detail::write_field_erased...}; + } + + template + static consteval auto make_schema_table( + detail::TableFieldTypeList) noexcept { + return std::array{ + &detail::build_schema_field_erased...}; + } + + static consteval ReadExtraUninitFn make_read_extra_uninit_fn() noexcept { + if constexpr (pos_extra_fields_ >= 0) { + using ExtraT = + typename detail::nth_type_in_list::type; + return &detail::read_extra_uninit_erased; + } else { + return nullptr; + } + } + + static consteval ReadExtraDefaultFn make_read_extra_default_fn() noexcept { + if constexpr (pos_extra_fields_ >= 0) { + using ExtraT = + typename detail::nth_type_in_list::type; + return &detail::read_extra_default_erased; + } else { + return nullptr; + } + } + + static consteval std::size_t (*make_extra_size_fn() noexcept)( + const void*) noexcept { + if constexpr (pos_extra_fields_ >= 0) { + using ExtraT = + typename detail::nth_type_in_list::type; + return &detail::extra_fields_size_erased; + } else { + return nullptr; + } + } + + static consteval schema::Type (*make_extra_schema_fn() noexcept)( + std::map*) { + if constexpr (pos_extra_fields_ >= 0) { + using ExtraT = + typename detail::nth_type_in_list::type; + return &detail::build_extra_schema_erased; + } else { + return nullptr; + } + } + + public: + static Result read(const R& _r, const InputVarType& _var) { + static_assert(pos_extra_fields_ == -1 || !schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + static_assert(!internal::no_extra_fields_v || + pos_extra_fields_ != -1 || + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not " + "make sense, because schemaful formats cannot have extra " + "fields."); + + static constexpr auto read_fns = make_read_uninit_table(FieldList{}); + static constexpr auto missing_fns = make_missing_table(FieldList{}); + static constexpr auto destroy_fns = make_destroy_table(FieldList{}); + static constexpr typename TableViewReader::Desc desc{ + Names::names_.data(), Names::lookup_.data(), read_fns.data(), + size_, pos_extra_fields_, make_read_extra_uninit_fn()}; + + alignas(T) unsigned char buf[sizeof(T)]{}; + auto* ptr = internal::ptr_cast(&buf); + const auto field_ptrs = detail::collect_flattened_mutable_ptrs(*ptr); + std::array found{}; + std::array set{}; + const detail::UninitFieldsGuard guard{destroy_fns.data(), set.data(), + field_ptrs.data(), size_}; + + auto err = detail::read_table_uninit_common( + _r, _var, desc, missing_fns.data(), field_ptrs.data(), found.data(), + set.data()); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return Result(std::move(*ptr)); + } + + static std::optional read_with_default(const R& _r, + const InputVarType& _var, + T* _target) { + static_assert(pos_extra_fields_ == -1 || !schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + static_assert(!internal::no_extra_fields_v || + pos_extra_fields_ != -1 || + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not " + "make sense, because schemaful formats cannot have extra " + "fields."); + + static constexpr auto read_fns = make_read_default_table(FieldList{}); + static constexpr typename TableViewReaderWithDefault< + R, W, ProcessorsType>::Desc desc{ + Names::names_.data(), Names::lookup_.data(), read_fns.data(), + size_, pos_extra_fields_, make_read_extra_default_fn()}; + + const auto field_ptrs = detail::collect_flattened_mutable_ptrs(*_target); + std::array found{}; + + if constexpr (internal::has_default_val_v && + !internal::default_if_missing_v) { + static constexpr auto missing_fns = make_missing_table(FieldList{}); + return detail::read_table_with_default_common< + R, W, no_field_names_, ProcessorsType, DefaultReader>( + _r, _var, desc, missing_fns.data(), field_ptrs.data(), found.data()); + } else { + return detail::read_table_with_default_common< + R, W, no_field_names_, ProcessorsType, DefaultReader>( + _r, _var, desc, nullptr, field_ptrs.data(), found.data()); + } + } + + template + static void write(const W& _w, const T& _var, const P& _parent) { + static constexpr auto write_fns = make_write_table(FieldList{}); + const auto field_ptrs = detail::collect_flattened_const_ptrs(_var); + detail::write_table_common( + _w, Names::names_.data(), write_fns.data(), field_ptrs.data(), size_, + pos_extra_fields_, make_extra_size_fn(), _parent); + } + + static schema::Type to_schema( + std::map* _definitions, + const T* _defaults = nullptr) { + static constexpr auto schema_fns = make_schema_table(FieldList{}); + if (_defaults != nullptr) { + const auto default_ptrs = detail::collect_flattened_const_ptrs(*_defaults); + return detail::to_schema_table_common( + _definitions, Names::names_.data(), schema_fns.data(), + default_ptrs.data(), size_, make_extra_schema_fn()); + } + return detail::to_schema_table_common( + _definitions, Names::names_.data(), schema_fns.data(), nullptr, size_, + make_extra_schema_fn()); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/is_view_reader.hpp b/include/rfl/parsing/is_view_reader.hpp index 0afab185a..3f32f5472 100644 --- a/include/rfl/parsing/is_view_reader.hpp +++ b/include/rfl/parsing/is_view_reader.hpp @@ -1,10 +1,20 @@ #ifndef RFL_PARSING_ISVIEWREADER_HPP_ #define RFL_PARSING_ISVIEWREADER_HPP_ +#include +#include + #include "ViewReader.hpp" namespace rfl ::parsing { +template +class TableViewReader; + +template +class SizedTableViewReader; + /** * @brief Trait to check if a type is a view reader. * @@ -20,6 +30,16 @@ template class is_view_reader> : public std::true_type {}; +template +class is_view_reader> + : public std::true_type {}; + +template +class is_view_reader< + SizedTableViewReader> + : public std::true_type {}; + template constexpr bool is_view_reader_v = is_view_reader>>::value; diff --git a/include/rfl/toml/Reader.hpp b/include/rfl/toml/Reader.hpp index d54d139f8..36eabf770 100644 --- a/include/rfl/toml/Reader.hpp +++ b/include/rfl/toml/Reader.hpp @@ -19,6 +19,7 @@ namespace rfl::toml { struct Reader { + using UnsizedObjectReader = void; using InputArrayType = ::toml::array*; using InputObjectType = ::toml::table*; using InputVarType = ::toml::node*; diff --git a/include/rfl/ubjson/Reader.hpp b/include/rfl/ubjson/Reader.hpp index 49472f178..f5d71b04a 100644 --- a/include/rfl/ubjson/Reader.hpp +++ b/include/rfl/ubjson/Reader.hpp @@ -32,6 +32,7 @@ namespace rfl::ubjson { class Reader { public: + using UnsizedObjectReader = void; struct UBJSONInputArray { jsoncons::json* val_; }; diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index 6ef06975b..d57d5607e 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -21,6 +21,7 @@ namespace rfl::xml { /// Uses the pugixml library for XML parsing. XML has a hierarchical structure /// with elements (nodes) and attributes, both of which can be mapped to object fields. struct Reader { + using UnsizedObjectReader = void; /// Represents an XML array during deserialization. /// In XML, arrays are represented as multiple sibling elements with the same name. /// Wraps a pugixml node representing the first element in the array. diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index c8625c04a..0632f0515 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -23,6 +23,7 @@ namespace rfl { namespace yaml { struct Reader { + using UnsizedObjectReader = void; struct YAMLInputArray { /// @brief Constructs a YAMLInputArray from a YAML::Node. /// @param _node The YAML node representing a sequence. diff --git a/tests/json/test_descriptor_table_stress.cpp b/tests/json/test_descriptor_table_stress.cpp new file mode 100644 index 000000000..13c51ed5a --- /dev/null +++ b/tests/json/test_descriptor_table_stress.cpp @@ -0,0 +1,684 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_descriptor_table_stress { + +// ---------------------------------------------------------------------------- +// 1. Tracked non-default-constructible move-only type for strict lifetime / +// partial-destruction verification under ASan + UBSan. +// ---------------------------------------------------------------------------- + +struct LiveCounter { + static inline std::atomic live{0}; + static inline std::atomic constructed{0}; + static inline std::atomic destroyed{0}; + + static void reset() { + live.store(0); + constructed.store(0); + destroyed.store(0); + } +}; + +struct Tracked { + using ReflectionType = std::string; + + std::string value; + bool destroyed_ = false; + + Tracked() = delete; + Tracked(const Tracked&) = delete; + Tracked& operator=(const Tracked&) = delete; + + explicit Tracked(std::string v) : value(std::move(v)), destroyed_(false) { + if (value == "__THROW__") { + throw std::runtime_error("Tracked intentional throw"); + } + LiveCounter::live.fetch_add(1); + LiveCounter::constructed.fetch_add(1); + } + + Tracked(Tracked&& other) noexcept + : value(std::move(other.value)), destroyed_(false) { + LiveCounter::live.fetch_add(1); + LiveCounter::constructed.fetch_add(1); + } + + Tracked& operator=(Tracked&& other) noexcept { + if (this != &other) { + value = std::move(other.value); + } + return *this; + } + + ~Tracked() { + EXPECT_FALSE(destroyed_) << "Double destruction detected!"; + destroyed_ = true; + LiveCounter::live.fetch_sub(1); + LiveCounter::destroyed.fetch_add(1); + } + + const std::string& reflection() const { return value; } +}; + +struct TwelveTracked { + Tracked f0; + int n0; + Tracked f1; + std::string s1; + Tracked f2; + int n2; + Tracked f3; + std::optional opt; + Tracked f4; + int n4; + Tracked f5; + Tracked f6; +}; + +TEST(descriptor_table_stress, tracked_full_roundtrip) { + LiveCounter::reset(); + { + const std::string json = + R"({"f0":"a","n0":1,"f1":"b","s1":"x","f2":"c","n2":2,"f3":"d","opt":"y","f4":"e","n4":4,"f5":"f","f6":"g"})"; + const auto res = rfl::json::read(json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->f0.value, "a"); + EXPECT_EQ(res->f6.value, "g"); + EXPECT_EQ(res->n4, 4); + const auto out = rfl::json::write(*res); + const auto rt = rfl::json::read(out); + ASSERT_TRUE(rt.has_value()) << rt.error().what(); + EXPECT_EQ(rt->f3.value, "d"); + EXPECT_EQ(rt->opt, std::optional("y")); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_GT(LiveCounter::constructed.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); +} + +TEST(descriptor_table_stress, tracked_mid_parse_failures_and_out_of_order) { + // Fails at various positions, out-of-order keys, missing fields, and throwing + // constructors — both default error collection and rfl::FailFast. + const std::vector bad_inputs = { + // Fail on first field (type mismatch) + R"({"f0":123,"n0":1,"f1":"b","s1":"x","f2":"c","n2":2,"f3":"d","f4":"e","n4":4,"f5":"f","f6":"g"})", + // Fail in middle (n2 wrong type) after f0, f1, f2 constructed + R"({"f0":"a","n0":1,"f1":"b","s1":"x","f2":"c","n2":"bad","f3":"d","f4":"e","n4":4,"f5":"f","f6":"g"})", + // Out-of-order keys failing near the end + R"({"f6":"g","f5":"f","f4":"e","f3":"d","f2":"c","f1":"b","f0":"a","n4":4,"n2":2,"s1":"x","n0":"bad"})", + // Missing required field at start + R"({"n0":1,"f1":"b","s1":"x","f2":"c","n2":2,"f3":"d","f4":"e","n4":4,"f5":"f","f6":"g"})", + // Missing required field at end + R"({"f0":"a","n0":1,"f1":"b","s1":"x","f2":"c","n2":2,"f3":"d","f4":"e","n4":4,"f5":"f"})", + // Constructor throws mid-parse + R"({"f0":"a","n0":1,"f1":"b","s1":"x","f2":"__THROW__","n2":2,"f3":"d","f4":"e","n4":4,"f5":"f","f6":"g"})", + // Wrong root type + R"([1, 2, 3])", + }; + + for (const auto& input : bad_inputs) { + LiveCounter::reset(); + { + const auto r1 = rfl::json::read(input); + EXPECT_FALSE(r1.has_value()); + } + EXPECT_EQ(LiveCounter::live.load(), 0) << "Leaked on input: " << input; + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); + + LiveCounter::reset(); + { + const auto r2 = rfl::json::read(input); + EXPECT_FALSE(r2.has_value()); + } + EXPECT_EQ(LiveCounter::live.load(), 0) + << "Leaked (FailFast) on input: " << input; + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); + } +} + +// ---------------------------------------------------------------------------- +// 2. Non-standard-layout aggregates: inheritance, empty base, const fields, +// move-only fields, C-arrays, empty struct. +// ---------------------------------------------------------------------------- + +struct NonStandardLayoutMember { + int a = 1; + private: + int b_ = 2; + public: + using ReflectionType = int; + NonStandardLayoutMember() = default; + explicit NonStandardLayoutMember(int v) : a(v), b_(v * 2) {} + int reflection() const { return a; } + int doubled() const { return b_; } +}; + +struct NonStandardLayoutAggregate { + int base_x = 10; + std::string base_name = "base"; + NonStandardLayoutMember nsl; + double derived_val = 2.5; + std::optional derived_note; +}; + +TEST(descriptor_table_stress, non_standard_layout_aggregate) { + static_assert(!std::is_standard_layout_v); + const std::string json = + R"({"base_x":42,"base_name":"hello","nsl":7,"derived_val":3.5,"derived_note":"ok"})"; + const auto res = rfl::json::read(json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->base_x, 42); + EXPECT_EQ(res->base_name, "hello"); + EXPECT_EQ(res->nsl.a, 7); + EXPECT_DOUBLE_EQ(res->derived_val, 3.5); + EXPECT_EQ(res->derived_note, std::optional("ok")); + + const auto written = rfl::json::write(*res); + EXPECT_EQ(written, json); + + // Also DefaultIfMissing path + const auto res_def = + rfl::json::read( + R"({"derived_val":9.0})"); + ASSERT_TRUE(res_def.has_value()) << res_def.error().what(); + EXPECT_EQ(res_def->base_x, 10); + EXPECT_EQ(res_def->base_name, "base"); + EXPECT_EQ(res_def->nsl.a, 1); + EXPECT_DOUBLE_EQ(res_def->derived_val, 9.0); +} + +struct MoveOnlyAndConst { + const int id = 7; + const std::string tag = "default_tag"; + std::unique_ptr ptr; + rfl::Box boxed = rfl::make_box("box_default"); +}; + +TEST(descriptor_table_stress, move_only_and_const_members) { + const std::string json = + R"({"id":99,"tag":"custom","ptr":123,"boxed":"hello"})"; + const auto res = rfl::json::read(json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->id, 99); + EXPECT_EQ(res->tag, "custom"); + ASSERT_NE(res->ptr, nullptr); + EXPECT_EQ(*res->ptr, 123); + EXPECT_EQ(*res->boxed, "hello"); + + const auto out = rfl::json::write(*res); + EXPECT_EQ(out, json); + + const auto res_def = + rfl::json::read( + R"({"id":55,"ptr":null})"); + ASSERT_TRUE(res_def.has_value()) << res_def.error().what(); + EXPECT_EQ(res_def->id, 55); + EXPECT_EQ(res_def->tag, "default_tag"); + EXPECT_EQ(res_def->ptr, nullptr); + EXPECT_EQ(*res_def->boxed, "box_default"); +} + +struct EmptyStruct {}; + +TEST(descriptor_table_stress, empty_struct) { + const auto res = rfl::json::read("{}"); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(rfl::json::write(*res), "{}"); + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("EmptyStruct"), std::string::npos); +} + +// ---------------------------------------------------------------------------- +// 3. Flatten + ExtraFields + Tracked partial-destruction on failure. +// ---------------------------------------------------------------------------- + +struct InnerFlat { + Tracked inner_a; + int inner_b; +}; + +struct OuterFlat { + Tracked outer_first; + rfl::Flatten flat; + Tracked outer_last; +}; + +TEST(descriptor_table_stress, flatten_tracked_partial_destruction) { + LiveCounter::reset(); + { + const std::string ok_json = + R"({"outer_first":"x","inner_a":"y","inner_b":7,"outer_last":"z"})"; + const auto ok = rfl::json::read(ok_json); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok->outer_first.value, "x"); + EXPECT_EQ(ok->flat.value_.inner_a.value, "y"); + EXPECT_EQ(ok->flat.value_.inner_b, 7); + EXPECT_EQ(ok->outer_last.value, "z"); + EXPECT_EQ(rfl::json::write(*ok), ok_json); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + + LiveCounter::reset(); + { + const std::string bad_json = + R"({"outer_first":"x","inner_a":"y","inner_b":"not_an_int","outer_last":"z"})"; + const auto bad = rfl::json::read(bad_json); + EXPECT_FALSE(bad.has_value()); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); +} + +struct WithExtraAndTracked { + Tracked required_a; + int count; + rfl::ExtraFields extras; +}; + +TEST(descriptor_table_stress, extra_fields_and_tracked_cleanup) { + LiveCounter::reset(); + { + const std::string ok_json = + R"({"required_a":"hi","count":3,"dyn1":"v1","dyn2":42})"; + const auto ok = rfl::json::read(ok_json); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok->required_a.value, "hi"); + EXPECT_EQ(ok->extras.size(), 2u); + const auto out = rfl::json::write(*ok); + EXPECT_NE(out.find("\"dyn1\":\"v1\""), std::string::npos); + EXPECT_NE(out.find("\"dyn2\":42"), std::string::npos); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + + // Failure after extras and required_a have been constructed + LiveCounter::reset(); + { + const std::string bad_json = + R"({"required_a":"hi","dyn1":"v1","count":"oops"})"; + const auto bad = rfl::json::read(bad_json); + EXPECT_FALSE(bad.has_value()); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); +} + +// ---------------------------------------------------------------------------- +// 4. Case-transform processors + Rename + Skip + DefaultVal + NoExtraFields +// + NoFieldNames + Duplicate JSON keys + Wide struct (> 8 fields). +// ---------------------------------------------------------------------------- + +struct WideCaseStruct { + int first_field = 1; + std::string second_field = "two"; + rfl::Rename<"EXACT_WIRE_NAME", int> renamed_field = 3; + rfl::DefaultVal default_fourth = 4; + rfl::Skip skipped_fifth = 5; + bool sixth_flag = true; + double seventh_ratio = 1.5; + std::optional eighth_opt; + int ninth_value = 9; + std::string tenth_name = "ten"; +}; + +TEST(descriptor_table_stress, case_transforms_respect_rename_and_skip) { + const std::string camel_json = + R"({"firstField":11,"secondField":"two2","EXACT_WIRE_NAME":33,"defaultFourth":44,"sixthFlag":false,"seventhRatio":2.5,"eighthOpt":"e","ninthValue":99,"tenthName":"ten10"})"; + const auto res = + rfl::json::read(camel_json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->first_field, 11); + EXPECT_EQ(res->renamed_field.value(), 33); + EXPECT_EQ(res->default_fourth.value(), 44); + EXPECT_EQ(res->skipped_fifth.value(), 5); + EXPECT_EQ(res->tenth_name, "ten10"); + + const auto written = + rfl::json::write(*res); + EXPECT_EQ(written, camel_json); + + // Unknown key rejected under NoExtraFields + SnakeCaseToCamelCase + const auto bad = + rfl::json::read( + R"({"firstField":1,"secondField":"s","EXACT_WIRE_NAME":3,"sixthFlag":true,"seventhRatio":1.0,"ninthValue":9,"tenthName":"t","bogus":1})"); + EXPECT_FALSE(bad.has_value()); + + // Schema respects transformed names + EXACT_WIRE_NAME + DefaultVal default + const auto schema = + rfl::json::to_schema(); + EXPECT_NE(schema.find("\"firstField\""), std::string::npos); + EXPECT_NE(schema.find("\"EXACT_WIRE_NAME\""), std::string::npos); + EXPECT_EQ(schema.find("\"skippedFifth\""), std::string::npos); + EXPECT_NE(schema.find("\"additionalProperties\":false"), std::string::npos); + + // Kebab-case + DefaultIfMissing + const auto kebab = + rfl::json::read( + R"({"first-field":77,"EXACT_WIRE_NAME":88,"tenth-name":"k"})"); + ASSERT_TRUE(kebab.has_value()) << kebab.error().what(); + EXPECT_EQ(kebab->first_field, 77); + EXPECT_EQ(kebab->renamed_field.value(), 88); + EXPECT_EQ(kebab->default_fourth.value(), 4); + EXPECT_EQ(kebab->tenth_name, "k"); + + // PascalCase + const auto pascal_out = + rfl::json::write(*kebab); + EXPECT_NE(pascal_out.find("\"FirstField\":77"), std::string::npos); + EXPECT_NE(pascal_out.find("\"EXACT_WIRE_NAME\":88"), std::string::npos); + + // ToAllCaps + const auto caps_out = rfl::json::write(*kebab); + EXPECT_NE(caps_out.find("\"FIRST_FIELD\":77"), std::string::npos); + EXPECT_NE(caps_out.find("\"EXACT_WIRE_NAME\":88"), std::string::npos); +} + +struct CamelStruct { + int myFieldOne = 1; + std::string anotherFieldTwo = "x"; +}; + +TEST(descriptor_table_stress, camel_to_snake_and_no_field_names) { + const auto res = rfl::json::read( + R"({"my_field_one":5,"another_field_two":"ok"})"); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->myFieldOne, 5); + EXPECT_EQ(rfl::json::write(*res), + R"({"my_field_one":5,"another_field_two":"ok"})"); + + // NoFieldNames (array representation) + const auto arr_res = + rfl::json::read(R"([42,"pos"])"); + ASSERT_TRUE(arr_res.has_value()) << arr_res.error().what(); + EXPECT_EQ(arr_res->myFieldOne, 42); + EXPECT_EQ(arr_res->anotherFieldTwo, "pos"); + EXPECT_EQ(rfl::json::write(*arr_res), R"([42,"pos"])"); + + // Too many array elements rejected + const auto arr_bad = + rfl::json::read(R"([1,"a","extra"])"); + EXPECT_FALSE(arr_bad.has_value()); + + // NoFieldNames + DefaultIfMissing + const auto arr_def = + rfl::json::read( + R"([99])"); + ASSERT_TRUE(arr_def.has_value()) << arr_def.error().what(); + EXPECT_EQ(arr_def->myFieldOne, 99); + EXPECT_EQ(arr_def->anotherFieldTwo, "x"); +} + +struct DuplicateKeyStruct { + int a; + int b; + int c; + int d; + int e; + int f; + int g; + int h; + int i; +}; + +TEST(descriptor_table_stress, duplicate_json_key_first_wins_and_no_extra) { + const std::string dup_json = + R"({"a":1,"a":999,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9})"; + const auto res = rfl::json::read(dup_json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->a, 1); + + // Under NoExtraFields, duplicate key is treated as unused (matches ViewReader) + const auto res_strict = + rfl::json::read(dup_json); + EXPECT_FALSE(res_strict.has_value()); +} + +struct TaggedItem { + int x = 1; + std::string label = "lbl"; +}; + +TEST(descriptor_table_stress, add_struct_name_and_validators) { + const auto out = rfl::json::write>(TaggedItem{}); + EXPECT_EQ(out, R"({"kind":"TaggedItem","x":1,"label":"lbl"})"); + const auto rt = rfl::json::read>(out); + ASSERT_TRUE(rt.has_value()) << rt.error().what(); + EXPECT_EQ(rt->x, 1); + EXPECT_EQ(rt->label, "lbl"); + + struct ValidatedStruct { + rfl::Validator> positive = 1; + rfl::DefaultVal> desc = + "hi"; + }; + const auto v_ok = rfl::json::read(R"({"positive":5})"); + ASSERT_TRUE(v_ok.has_value()) << v_ok.error().what(); + EXPECT_EQ(v_ok->positive.value(), 5); + EXPECT_EQ(v_ok->desc.value().value(), "hi"); + + const auto v_bad = rfl::json::read(R"({"positive":0})"); + EXPECT_FALSE(v_bad.has_value()); +} + +// ---------------------------------------------------------------------------- +// 5. Review Round 1 regression tests: +// - ExtraFields key matching C++ member name (first key, uninit + default) +// - Throwing move constructor during Result(std::move(*ptr)) +// - Throwing move-assign inside read_with_default (must return Error, not terminate) +// - Flatten mutability + multi-op xml_content preservation +// ---------------------------------------------------------------------------- + +struct ExtraStringStruct { + std::string name = "default"; + rfl::ExtraFields extras; +}; + +TEST(descriptor_table_stress, extra_fields_key_matching_member_name) { + // Key literally named "extras" arrives FIRST, before any other extra key. + const std::string input = R"({"extras":"first_val","name":"Alice","k2":"v2"})"; + const auto r1 = rfl::json::read(input); + ASSERT_TRUE(r1.has_value()) << r1.error().what(); + EXPECT_EQ(r1->name, "Alice"); + ASSERT_EQ(r1->extras.size(), 2u); + EXPECT_EQ(r1->extras.get("extras").value(), "first_val"); + EXPECT_EQ(r1->extras.get("k2").value(), "v2"); + + const auto r2 = + rfl::json::read(input); + ASSERT_TRUE(r2.has_value()) << r2.error().what(); + EXPECT_EQ(r2->extras.get("extras").value(), "first_val"); + EXPECT_EQ(r2->extras.get("k2").value(), "v2"); +} + +// Minimal non-noexcept custom named Reader (intentionally WITHOUT +// `using UnsizedObjectReader = void;`) that both: +// 1. Verifies custom/external named readers work with rfl::ExtraFields, and +// 2. Throws mid-parse on a sentinel key to exercise UninitFieldsGuard and +// read_struct_with_default exception catching. +struct CustomThrowingReader { + struct InputVarType { + std::string str; + bool is_obj = false; + std::vector> entries; + }; + using InputObjectType = InputVarType; + using InputArrayType = InputVarType; + + template + static constexpr bool has_custom_constructor = false; + + rfl::Result get_field_from_array(const std::size_t, + const InputArrayType&) const { + return rfl::error("unused"); + } + + rfl::Result get_field_from_object(const std::string&, + const InputObjectType&) const { + return rfl::error("unused"); + } + + bool is_empty(const InputVarType& _var) const { + return !_var.is_obj && _var.str.empty(); + } + + template + rfl::Result to_basic_type(const InputVarType& _var) const { + if constexpr (std::is_same_v, std::string>) { + return _var.str; + } else if constexpr (std::is_same_v, int>) { + return std::stoi(_var.str); + } else { + return rfl::error("unsupported"); + } + } + + rfl::Result to_array(const InputVarType&) const { + return rfl::error("not array"); + } + + rfl::Result to_object(const InputVarType& _var) const { + if (!_var.is_obj) return rfl::error("not object"); + return _var; + } + + template + std::optional read_array(const ArrayReader&, + const InputArrayType&) const { + return rfl::Error("unused"); + } + + template + std::optional read_object(const ObjectReader& _reader, + const InputObjectType& _obj) const { + for (const auto& [k, v] : _obj.entries) { + if (k == "__THROW_READER__") { + throw std::runtime_error("intentional reader throw"); + } + _reader.read(std::string_view(k), InputVarType{.str = v}); + } + return std::nullopt; + } + + template + rfl::Result use_custom_constructor(const InputVarType&) const { + return rfl::error("unused"); + } +}; + +struct ThrowingReaderTarget { + Tracked before; + Tracked after; +}; + +struct ThrowingDefaultTarget { + std::string label = "init"; + int count = 0; +}; + +TEST(descriptor_table_stress, + throwing_reader_guard_and_custom_named_reader_extra_fields) { + using PUninit = rfl::parsing::Parser>; + using PDefault = + rfl::parsing::Parser>; + using PExtra = rfl::parsing::Parser>; + + const CustomThrowingReader reader{}; + + // 1. UninitFieldsGuard must destroy `before` when read_object throws mid-parse + LiveCounter::reset(); + bool caught = false; + try { + const CustomThrowingReader::InputVarType input{ + .is_obj = true, + .entries = {{"before", "alive_val"}, {"__THROW_READER__", "boom"}}}; + (void)PUninit::read(reader, input); + } catch (const std::runtime_error& e) { + caught = (std::string_view(e.what()) == "intentional reader throw"); + } + EXPECT_TRUE(caught); + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_GT(LiveCounter::constructed.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); + + // 2. read_with_default must NOT be noexcept so Parser_default's try/catch + // catches the exception and returns an rfl::Error cleanly. + { + const CustomThrowingReader::InputVarType input{ + .is_obj = true, + .entries = {{"label", "ok"}, {"__THROW_READER__", "boom"}}}; + const auto res = PDefault::read(reader, input); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("intentional reader throw"), + std::string::npos); + } + + // 3. External/custom named Reader without UnsizedObjectReader tag must still + // compile and handle rfl::ExtraFields cleanly via SizedTableViewReader. + { + const CustomThrowingReader::InputVarType input{ + .is_obj = true, + .entries = {{"extras", "first_val"}, {"name", "Bob"}, {"dyn", "v"}}}; + const auto res = PExtra::read(reader, input); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->name, "Bob"); + EXPECT_EQ(res->extras.get("extras").value(), "first_val"); + EXPECT_EQ(res->extras.get("dyn").value(), "v"); + } +} + +struct InnerPlain { + int a = 1; + std::string b = "init"; +}; + +struct FlattenConstWrapper { + rfl::Flatten flat; + int tail = 2; +}; + +struct XmlMultiOpStruct { + int firstField = 1; + std::string xmlContent = "body"; +}; + +TEST(descriptor_table_stress, flatten_const_sub_and_multi_op_xml_content) { + const auto r = rfl::json::read( + R"({"a":10,"b":"updated","tail":20})"); + ASSERT_TRUE(r.has_value()) << r.error().what(); + EXPECT_EQ(r->flat.value_.a, 10); + EXPECT_EQ(r->flat.value_.b, "updated"); + EXPECT_EQ(r->tail, 20); + + // CamelCaseToSnakeCase turns xmlContent -> xml_content, then ToAllCaps must + // leave xml_content untouched (matching NamedTuple processor semantics). + const auto out = + rfl::json::write( + XmlMultiOpStruct{}); + EXPECT_EQ(out, R"({"FIRST_FIELD":1,"xml_content":"body"})"); + const auto rt = + rfl::json::read(out); + ASSERT_TRUE(rt.has_value()) << rt.error().what(); + EXPECT_EQ(rt->firstField, 1); + EXPECT_EQ(rt->xmlContent, "body"); +} + +} // namespace test_descriptor_table_stress diff --git a/tests/json_c_arrays_and_inheritance/test_descriptor_table_c_arrays.cpp b/tests/json_c_arrays_and_inheritance/test_descriptor_table_c_arrays.cpp new file mode 100644 index 000000000..666d662d5 --- /dev/null +++ b/tests/json_c_arrays_and_inheritance/test_descriptor_table_c_arrays.cpp @@ -0,0 +1,54 @@ +#include + +#include +#include +#include + +namespace test_descriptor_table_c_arrays { + +struct WithCArrays { + int nums[3] = {1, 2, 3}; + std::string words[2] = {"a", "b"}; + int tail = 9; +}; + +TEST(descriptor_table_c_arrays, c_arrays_read_write_default_schema) { + const std::string json = + R"({"nums":[10,20,30],"words":["hi","yo"],"tail":42})"; + const auto res = rfl::json::read(json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->nums[0], 10); + EXPECT_EQ(res->nums[2], 30); + EXPECT_EQ(res->words[1], "yo"); + EXPECT_EQ(res->tail, 42); + EXPECT_EQ(rfl::json::write(*res), json); + + const auto def_res = + rfl::json::read(R"({"tail":77})"); + ASSERT_TRUE(def_res.has_value()) << def_res.error().what(); + EXPECT_EQ(def_res->nums[1], 2); + EXPECT_EQ(def_res->words[0], "a"); + EXPECT_EQ(def_res->tail, 77); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("nums"), std::string::npos); + EXPECT_NE(schema.find("words"), std::string::npos); +} + +struct EmptyBase {}; +struct BaseWithMembers { + int base_x = 10; + std::string base_name = "base"; +}; +struct DerivedWithBaseMembers : EmptyBase, BaseWithMembers {}; + +TEST(descriptor_table_c_arrays, inherited_base_members_roundtrip) { + const std::string json = R"({"base_x":42,"base_name":"hello"})"; + const auto res = rfl::json::read(json); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->base_x, 42); + EXPECT_EQ(res->base_name, "hello"); + EXPECT_EQ(rfl::json::write(*res), json); +} + +} // namespace test_descriptor_table_c_arrays From 65b06dda685519f2589980e83eff661d4d537492 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 28 Nov 2026 07:15:36 +0100 Subject: [PATCH 2/3] perf(parsing): add sequential-key cursor hint, found_count missing-field short-circuit, and trivial-dtor skip --- include/rfl/parsing/TableStructParser.hpp | 146 +++++++++++++++++----- 1 file changed, 113 insertions(+), 33 deletions(-) diff --git a/include/rfl/parsing/TableStructParser.hpp b/include/rfl/parsing/TableStructParser.hpp index da5efd4f6..fd965509b 100644 --- a/include/rfl/parsing/TableStructParser.hpp +++ b/include/rfl/parsing/TableStructParser.hpp @@ -468,14 +468,16 @@ class TableViewReader { }; TableViewReader(const R* _r, const Desc* _desc, void* const* _field_ptrs, - bool* _found, bool* _set, + bool* _found, bool* _set, std::size_t* _found_count, FieldErrors* _errors) noexcept : r_(_r), desc_(_desc), field_ptrs_(_field_ptrs), found_(_found), set_(_set), - errors_(_errors) {} + found_count_(_found_count), + errors_(_errors), + next_idx_(0) {} ~TableViewReader() = default; @@ -483,15 +485,29 @@ class TableViewReader { return {desc_->names, desc_->size}; } - void read(const std::string_view& _name, const InputVarType& _var) const { + RFL_ALWAYS_INLINE void read(const std::string_view& _name, + const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; bool already_assigned = false; - if (const int idx = - detail::find_in_table(desc_->lookup, desc_->size, _name); - idx >= 0 && idx != desc_->pos_extra_fields) { + int idx = -1; + if (next_idx_ < desc_->size && + static_cast(next_idx_) != desc_->pos_extra_fields && + desc_->names[next_idx_] == _name) [[likely]] { + idx = static_cast(next_idx_); + ++next_idx_; + } else { + const int found_idx = + detail::find_in_table(desc_->lookup, desc_->size, _name); + if (found_idx >= 0 && found_idx != desc_->pos_extra_fields) { + idx = found_idx; + next_idx_ = static_cast(found_idx) + 1; + } + } + if (idx >= 0) { const auto u = static_cast(idx); if (!found_[u]) { found_[u] = true; + ++(*found_count_); already_assigned = true; desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], set_[u], errors_, desc_->size); @@ -500,8 +516,12 @@ class TableViewReader { if (desc_->pos_extra_fields >= 0) { if (!already_assigned) { const auto pos = static_cast(desc_->pos_extra_fields); + const bool was_found = found_[pos]; desc_->read_extra_fn(*r_, _name, _var, field_ptrs_[pos], found_[pos], set_[pos], errors_); + if (!was_found && found_[pos]) { + ++(*found_count_); + } } } else if constexpr (internal::no_extra_fields_v) { if (!already_assigned) { @@ -521,6 +541,7 @@ class TableViewReader { const auto u = static_cast(_index); if (!found_[u]) { found_[u] = true; + ++(*found_count_); already_assigned = true; desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], set_[u], errors_, desc_->size); @@ -547,7 +568,9 @@ class TableViewReader { void* const* field_ptrs_; bool* found_; bool* set_; + std::size_t* found_count_; FieldErrors* errors_; + mutable std::size_t next_idx_; }; /// Thin static-size adapter for positional/schemaful/external readers that @@ -599,12 +622,15 @@ class TableViewReaderWithDefault { TableViewReaderWithDefault(const R* _r, const Desc* _desc, void* const* _field_ptrs, bool* _found, + std::size_t* _found_count, FieldErrors* _errors) noexcept : r_(_r), desc_(_desc), field_ptrs_(_field_ptrs), found_(_found), - errors_(_errors) {} + found_count_(_found_count), + errors_(_errors), + next_idx_(0) {} ~TableViewReaderWithDefault() = default; @@ -612,15 +638,29 @@ class TableViewReaderWithDefault { return {desc_->names, desc_->size}; } - void read(const std::string_view& _name, const InputVarType& _var) const { + RFL_ALWAYS_INLINE void read(const std::string_view& _name, + const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; bool already_assigned = false; - if (const int idx = - detail::find_in_table(desc_->lookup, desc_->size, _name); - idx >= 0 && idx != desc_->pos_extra_fields) { + int idx = -1; + if (next_idx_ < desc_->size && + static_cast(next_idx_) != desc_->pos_extra_fields && + desc_->names[next_idx_] == _name) [[likely]] { + idx = static_cast(next_idx_); + ++next_idx_; + } else { + const int found_idx = + detail::find_in_table(desc_->lookup, desc_->size, _name); + if (found_idx >= 0 && found_idx != desc_->pos_extra_fields) { + idx = found_idx; + next_idx_ = static_cast(found_idx) + 1; + } + } + if (idx >= 0) { const auto u = static_cast(idx); if (!found_[u]) { found_[u] = true; + ++(*found_count_); already_assigned = true; desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], errors_); } @@ -650,6 +690,7 @@ class TableViewReaderWithDefault { const auto u = static_cast(_index); if (!found_[u]) { found_[u] = true; + ++(*found_count_); already_assigned = true; desc_->read_fns[u](*r_, _var, desc_->names[u], field_ptrs_[u], errors_); } @@ -674,7 +715,9 @@ class TableViewReaderWithDefault { const Desc* desc_; void* const* field_ptrs_; bool* found_; + std::size_t* found_count_; FieldErrors* errors_; + mutable std::size_t next_idx_; }; template * _errors) noexcept : i_(0), r_(_r), @@ -718,6 +762,7 @@ class TableViewReaderStripped { field_ptrs_(_field_ptrs), found_(_found), set_(_set), + found_count_(_found_count), errors_(_errors) {} ~TableViewReaderStripped() = default; @@ -733,6 +778,7 @@ class TableViewReaderStripped { return Error(stream.str()); } found_[i_] = true; + ++(*found_count_); desc_->read_fns[i_](*r_, _var, desc_->names[i_], field_ptrs_[i_], set_[i_], errors_, desc_->size); ++i_; @@ -746,6 +792,7 @@ class TableViewReaderStripped { void* const* field_ptrs_; bool* found_; bool* set_; + std::size_t* found_count_; FieldErrors* errors_; }; @@ -757,12 +804,14 @@ class TableViewReaderWithDefaultStripped { TableViewReaderWithDefaultStripped( const R* _r, const Desc* _desc, void* const* _field_ptrs, bool* _found, + std::size_t* _found_count, FieldErrors* _errors) noexcept : i_(0), r_(_r), desc_(_desc), field_ptrs_(_field_ptrs), found_(_found), + found_count_(_found_count), errors_(_errors) {} ~TableViewReaderWithDefaultStripped() = default; @@ -778,6 +827,7 @@ class TableViewReaderWithDefaultStripped { return Error(stream.str()); } found_[i_] = true; + ++(*found_count_); desc_->read_fns[i_](*r_, _var, desc_->names[i_], field_ptrs_[i_], errors_); ++i_; return std::nullopt; @@ -789,6 +839,7 @@ class TableViewReaderWithDefaultStripped { const Desc* desc_; void* const* field_ptrs_; bool* found_; + std::size_t* found_count_; FieldErrors* errors_; }; @@ -835,13 +886,14 @@ std::optional read_table_uninit_common( FieldErrors*, bool) noexcept, void* const* _field_ptrs, bool* _found, bool* _set) { FieldErrors errors; + std::size_t found_count = 0; if constexpr (_no_field_names) { auto arr = _r.to_array(_var); if (!arr) [[unlikely]] { return arr.error(); } const auto reader = TableViewReaderStripped( - &_r, &_desc, _field_ptrs, _found, _set, &errors); + &_r, &_desc, _field_ptrs, _found, _set, &found_count, &errors); if (auto err = _r.read_array(reader, *arr)) [[unlikely]] { return err; } @@ -850,17 +902,20 @@ std::optional read_table_uninit_common( if (!obj) [[unlikely]] { return obj.error(); } - const auto reader = - ReaderObj(&_r, &_desc, _field_ptrs, _found, _set, &errors); + const auto reader = ReaderObj(&_r, &_desc, _field_ptrs, _found, _set, + &found_count, &errors); if (auto err = _r.read_object(reader, *obj)) [[unlikely]] { return err; } } - if (!should_stop_on_field_error(errors)) { + if (found_count < _desc.size && + !should_stop_on_field_error(errors)) { for (std::size_t i = 0; i < _desc.size; ++i) { - _missing_fns[i](_desc.names[i], _found[i], _field_ptrs[i], &_set[i], - &errors, /*_value_initialize_default_vals=*/false); + if (!_found[i]) { + _missing_fns[i](_desc.names[i], false, _field_ptrs[i], &_set[i], + &errors, /*_value_initialize_default_vals=*/false); + } } } @@ -884,6 +939,7 @@ std::optional read_table_with_default_common( FieldErrors*, bool) noexcept, void* const* _field_ptrs, bool* _found) { FieldErrors errors; + std::size_t found_count = 0; if constexpr (_no_field_names) { auto arr = _r.to_array(_var); if (!arr) [[unlikely]] { @@ -891,7 +947,7 @@ std::optional read_table_with_default_common( } const auto reader = TableViewReaderWithDefaultStripped( - &_r, &_desc, _field_ptrs, _found, &errors); + &_r, &_desc, _field_ptrs, _found, &found_count, &errors); if (auto err = _r.read_array(reader, *arr)) [[unlikely]] { return err; } @@ -900,17 +956,20 @@ std::optional read_table_with_default_common( if (!obj) [[unlikely]] { return obj.error(); } - const auto reader = ReaderObj(&_r, &_desc, _field_ptrs, _found, &errors); + const auto reader = + ReaderObj(&_r, &_desc, _field_ptrs, _found, &found_count, &errors); if (auto err = _r.read_object(reader, *obj)) [[unlikely]] { return err; } } - if (_missing_fns != nullptr && + if (_missing_fns != nullptr && found_count < _desc.size && !should_stop_on_field_error(errors)) { for (std::size_t i = 0; i < _desc.size; ++i) { - _missing_fns[i](_desc.names[i], _found[i], _field_ptrs[i], nullptr, - &errors, /*_value_initialize_default_vals=*/false); + if (!_found[i]) { + _missing_fns[i](_desc.names[i], false, _field_ptrs[i], nullptr, + &errors, /*_value_initialize_default_vals=*/false); + } } } @@ -1093,6 +1152,14 @@ struct TableStructParser { } } + template + static consteval bool has_any_non_trivial_dtor( + detail::TableFieldTypeList) noexcept { + return (false || ... || + !std::is_trivially_destructible_v< + std::remove_all_extents_t>); + } + template static consteval auto make_destroy_table( detail::TableFieldTypeList) noexcept { @@ -1175,7 +1242,8 @@ struct TableStructParser { static constexpr auto read_fns = make_read_uninit_table(FieldList{}); static constexpr auto missing_fns = make_missing_table(FieldList{}); - static constexpr auto destroy_fns = make_destroy_table(FieldList{}); + static constexpr bool kHasNonTrivialDtor = + has_any_non_trivial_dtor(FieldList{}); static constexpr typename TableViewReader::Desc desc{ Names::names_.data(), Names::lookup_.data(), read_fns.data(), size_, pos_extra_fields_, make_read_extra_uninit_fn()}; @@ -1185,17 +1253,29 @@ struct TableStructParser { const auto field_ptrs = detail::collect_flattened_mutable_ptrs(*ptr); std::array found{}; std::array set{}; - const detail::UninitFieldsGuard guard{destroy_fns.data(), set.data(), - field_ptrs.data(), size_}; - - auto err = detail::read_table_uninit_common( - _r, _var, desc, missing_fns.data(), field_ptrs.data(), found.data(), - set.data()); - if (err) [[unlikely]] { - return error(std::move(*err)); + + if constexpr (kHasNonTrivialDtor) { + static constexpr auto destroy_fns = make_destroy_table(FieldList{}); + const detail::UninitFieldsGuard guard{destroy_fns.data(), set.data(), + field_ptrs.data(), size_}; + auto err = detail::read_table_uninit_common( + _r, _var, desc, missing_fns.data(), field_ptrs.data(), found.data(), + set.data()); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return Result(std::move(*ptr)); + } else { + auto err = detail::read_table_uninit_common( + _r, _var, desc, missing_fns.data(), field_ptrs.data(), found.data(), + set.data()); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return Result(std::move(*ptr)); } - return Result(std::move(*ptr)); } static std::optional read_with_default(const R& _r, From 54d62e9e276a2fb999a9096e0e68e345854d122c Mon Sep 17 00:00:00 2001 From: Denis Popov Date: Sat, 28 Nov 2026 12:06:34 -0800 Subject: [PATCH 3/3] fix(parsing): replace consteval-in-lambda in DirectFieldNames for GCC 13 --- include/rfl/internal/DirectFieldNames.hpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/include/rfl/internal/DirectFieldNames.hpp b/include/rfl/internal/DirectFieldNames.hpp index b02a5d67b..02195a167 100644 --- a/include/rfl/internal/DirectFieldNames.hpp +++ b/include/rfl/internal/DirectFieldNames.hpp @@ -183,15 +183,22 @@ consteval void append_member_names(DirectNameInfo* _out, std::size_t& _pos) { } } +template +consteval void append_all_member_names(DirectNameInfo* _out, std::size_t& _pos, + std::index_sequence) { + (void)_out; + (void)_pos; + (append_member_names(_out, _pos), ...); +} + template consteval std::array> extract_flattened_raw_names() { using Type = std::remove_cvref_t; std::array> out{}; std::size_t pos = 0; - [&](std::index_sequence) { - (append_member_names(out.data(), pos), ...); - }(std::make_index_sequence>{}); + append_all_member_names(out.data(), pos, + std::make_index_sequence>{}); return out; }