From 3a0cded6e7d1227e4df7b211ca98bc4de2ec3b4d Mon Sep 17 00:00:00 2001 From: Denis Popov Date: Wed, 2 Dec 2026 09:52:34 -0800 Subject: [PATCH] perf(parsing): isolate per-field helpers in NamedTupleParser, destructors, and flatten Moves per-field serialization, schema building, missing-field handling, and destructor helpers out of `NamedTupleParser<..., FieldTypes...>` into free templates parameterized only on each field's type (never the enclosing `NamedTuple` pack), and skips instantiating destructors for trivially destructible fields/arrays. Eliminates O(N^2) symbol-table and DWARF growth on wide structs with zero public API changes. Split from parser-symbol-isolation (#118) into an independent, reviewable chunk (no lookup algorithm changes; `to_default_generic` fast-path and `ViewReader` isolation follow in separate commits). Follow-up to: https://github.com/munich-data-engineering/reflect-cpp/pull/795, #799 Downstream receipts (combined Wave 1 N=3 interleaved medians vs main): - hudson-trading/slang-server (`SlangServer.cpp` Debug): -15.0% `.o` Clang, -9.6% GCC, -6.1% wall - openmoq/moqx (`Loader.cpp` Debug): -17.5% `.o` Clang, -13.5% GCC, -4.4% wall - FANUC-CORPORATION/fanuc_driver (`serialization.cpp` Debug): -27.1% `.o` Clang, -9.9% wall - games-on-whales/wolf (`unix_socket_server.cpp` Release): -19.4% `.o` Clang --- .../copy_flattened_tuple_to_named_tuple.hpp | 12 +- include/rfl/parsing/NamedTupleParser.hpp | 447 ++++++++++-------- .../call_destructors_where_necessary.hpp | 71 +-- 3 files changed, 303 insertions(+), 227 deletions(-) diff --git a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp index 5f3a13926..32a30e737 100644 --- a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp +++ b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp @@ -10,21 +10,15 @@ namespace rfl::internal { -template -auto copy_one_element(const auto& _flattened_tuple) { - const auto name_literal = FieldNames::template name_of<_i>(); - return rfl::make_field< - lit_name_v>>( - std::get<_i>(_flattened_tuple)); -} - template auto copy_flattened_tuple_to_named_tuple(const auto& _flattened_tuple) { constexpr auto size = rfl::tuple_size_v>; return [&](std::integer_sequence) { return make_named_tuple( - copy_one_element(_flattened_tuple)...); + rfl::make_field())>>>( + std::get<_i>(_flattened_tuple))...); }(std::make_integer_sequence()); } diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..fee7e13d1 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -2,12 +2,18 @@ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #include +#include #include #include +#include #include +#include +#include #include #include +#include +#include "../Generic.hpp" #include "../NamedTuple.hpp" #include "../Result.hpp" #include "../internal/always_inline.hpp" @@ -78,6 +84,219 @@ concept CanEmitDefault = namespace rfl::parsing { +/// Sets the default value of the DefaultVal node in `_schema`. +inline void set_schema_default_value(Generic _default, schema::Type* _schema) { + _schema->variant_.visit([&](auto& _s) { + if constexpr (std::is_same_v, + schema::Type::DefaultVal>) { + _s.default_value_ = std::move(_default); + } + }); +} + +/// Free per-field serialization helper parameterized only by ValueType (never +/// the enclosing NamedTuple's FieldTypes... pack). +template +void write_named_tuple_field(const W& _w, const std::string_view _name, + const ValueType& _value, + OutputObjectOrArrayType* _ptr) { + using ParentType = Parent; + const auto make_parent = [](const std::string_view _n, + OutputObjectOrArrayType* _p) { + if constexpr (_no_field_names) { + return typename ParentType::Array{_p}; + } else { + return typename ParentType::Object{_n, _p}; + } + }; + if constexpr (internal::is_extra_fields_v) { + for (const auto& [k, v] : *_value) { + const auto new_parent = make_parent(k, _ptr); + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + } else if constexpr (!_all_required && !_no_field_names && + !is_required()) { + const auto new_parent = make_parent(_name, _ptr); + if (!is_empty(_value)) { + if constexpr (internal::is_attribute_v) { + Parser::write( + _w, _value, new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } + } else { + const auto new_parent = make_parent(_name, _ptr); + if constexpr (internal::is_attribute_v) { + Parser::write(_w, _value, + new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } +} + +/// Extracts a pointer to a view slot for schema default inspection. +/// Pointer slots (including `T*` and C-array pointers `T (*)[N]`) are returned +/// directly without dereferencing; non-pointer processor-added slots (such as +/// `rfl::AddStructName`'s `rfl::Literal<...>`) return `nullptr`. +template +RFL_ALWAYS_INLINE auto extract_schema_field_ptr(const SlotT& _slot) noexcept { + if constexpr (std::is_pointer_v) { + return _slot; + } else { + return static_cast(nullptr); + } +} + +/// Free per-field schema helper parameterized only by field type U and its +/// view-slot pointer type (never the enclosing NamedTuple's FieldTypes... +/// pack). Deduces `FieldValPtrT` independently of `U` so both raw C-array +/// pointers (`T (*)[N]` vs `rfl::internal::Array`) and non-pointer +/// processor-added slots (`const void*` / `nullptr`) work cleanly. +template +void build_named_tuple_field_schema( + std::map* _definitions, SchemaType* _schema, + const std::string_view _name, const FieldValPtrT _field_val) noexcept { + using PtrT = std::remove_cvref_t; + if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { + auto s = Parser::to_schema(_definitions); + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + internal::CanEmitDefault) { + if (_field_val != nullptr) { + set_schema_default_value( + rfl::to_generic( + internal::get_default_val(*_field_val).get()), + &s); + } + } + if constexpr (_no_field_names) { + _schema->types_.emplace_back(std::move(s)); + } else { + _schema->types_[std::string(_name)] = std::move(s); + } + } +} + +/// Whether a missing rfl::DefaultVal field can be value-initialized. Only +/// an rfl::NamedTuple does this at runtime, and it cannot have const fields, +/// so const fields of structs need no instantiation. +template +constexpr bool can_value_initialize_default_val() { + using T = typename internal::default_val_t::Type; + return !std::is_const_v && std::is_default_constructible_v && + std::is_default_constructible_v; +} + +/// Free per-field missing-field handler parameterized only by FieldSlotType +/// (never the enclosing NamedTuple's FieldTypes... pack). +/// Precondition: `_is_set_ptr` is non-null whenever `_defaults_constructed` is +/// false (the uninitialized-memory read path). +template +#if defined(_MSC_VER) && !defined(__clang__) +inline +#else +RFL_ALWAYS_INLINE +#endif + void handle_missing_named_tuple_field( + const std::string_view _name, const bool _is_found, + const FieldSlotType& _field_slot, bool* _is_set_ptr, + FieldErrors* _errors, + const bool _value_initialize_default_vals) noexcept { + using SlotT = std::remove_cvref_t; + using ValueType = std::remove_reference_t>; + constexpr bool is_default_val_field = internal::is_default_val_v; + constexpr bool is_required_field = + !is_default_val_field && !internal::is_extra_fields_v && + (_all_required || is_required()); + + // When the struct was default-constructed, missing optional or DefaultVal + // fields already hold their default values, so nothing is needed. + if constexpr (_defaults_constructed && !is_required_field) { + return; + } else { + if (should_stop_on_field_error(*_errors)) return; + if (!_is_found) { + if constexpr (std::is_pointer_v && !_defaults_constructed && + is_default_val_field) { + if constexpr (can_value_initialize_default_val()) { + if (_value_initialize_default_vals) { + // The value's constructor can throw, for instance a Validator + // whose zero value is invalid. + try { + ::new (_field_slot) ValueType(); + } catch (const std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } catch (...) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: unknown exception.")); + return; + } + *_is_set_ptr = true; + return; + } + } + } + + if constexpr (is_required_field || + (is_default_val_field && !_defaults_constructed)) { + std::stringstream stream; + stream << "Field named '" << std::string(_name) << "' not found."; + _errors->emplace_back( + make_nested_error(std::string(_name), stream.str())); + return; + } + + if constexpr (std::is_pointer_v && !_defaults_constructed && + !is_required_field && !is_default_val_field) { + using NonConstT = std::remove_const_t; + const auto ptr = const_cast(_field_slot); + if constexpr (std::is_nothrow_default_constructible_v) { + ::new (ptr) NonConstT(); + } else { + // The default value can throw, for instance a Validator whose + // default value is invalid. + try { + ::new (ptr) NonConstT(); + } catch (const std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } catch (...) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: unknown exception.")); + return; + } + } + *_is_set_ptr = true; + } + } + } +} + template requires AreReaderAndWriter> @@ -246,83 +465,39 @@ struct NamedTupleParser { } private: - template - static void add_field_to_object(const W& _w, - const NamedTuple& _tup, - OutputObjectOrArrayType* _ptr) { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_cvref_t; - const auto value = rfl::get<_i>(_tup); - if constexpr (internal::is_extra_fields_v) { - for (const auto& [k, v] : *value) { - const auto new_parent = make_parent(k, _ptr); - Parser, ProcessorsType>::write( - _w, v, new_parent); - } - } else if constexpr (!_all_required && !_no_field_names && - !is_required()) { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if (!is_empty(value)) { - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } else { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } - - template - static void add_field_to_schema( - std::map* _definitions, - SchemaType* _schema, - View* _view) noexcept { - using F = internal::nth_element_t<_i, FieldTypes...>; - using U = std::remove_cvref_t; - if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { - // Add default value here - auto s = Parser::to_schema(_definitions); - if constexpr (!std::is_same_v && internal::CanEmitDefault) { - s.variant_.visit([&](auto& value) { - if constexpr (std::is_same_v, - schema::Type::DefaultVal>) { - value.default_value_ = - rfl::to_generic((*rfl::get<_i>(*_view)).get()); - } - }); - } - if constexpr (_no_field_names) { - _schema->types_.emplace_back(std::move(s)); - } else { - _schema->types_[std::string(F::name())] = std::move(s); - } - } - }; - template static void build_object(const W& _w, const NamedTuple& _tup, OutputObjectOrArrayType* _ptr, std::integer_sequence) { - (add_field_to_object<_is>(_w, _tup, _ptr), ...); + (write_named_tuple_field( + _w, internal::nth_element_t<_is, FieldTypes...>::name_.string_view(), + rfl::get<_is>(_tup), _ptr), + ...); } - template + template static void build_schema(std::map* _definitions, - SchemaType* _schema, - View* _view, + SchemaType* _schema, View* _view, std::integer_sequence) noexcept { - (add_field_to_schema(_definitions, _schema, _view), ...); + if constexpr (!std::is_same_v) { + (build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), + _view ? extract_schema_field_ptr(rfl::get<_is>(*_view)) : nullptr), + ...); + } else { + (build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), nullptr), + ...); + } if constexpr (NamedTupleType::pos_extra_fields() != -1) { using F = internal::nth_element_t - static RFL_ALWAYS_INLINE void handle_one_missing_field( - const std::array& _found, const NamedTupleType& _view, - std::array* _set, FieldErrors* _errors, - const bool _value_initialize_default_vals) noexcept { - if (should_stop_on_field_error(*_errors)) return; - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_reference_t< - std::remove_pointer_t>; - - if (!std::get<_i>(_found)) { - constexpr bool is_default_val_field = - internal::is_default_val_v; - constexpr bool is_required_field = - !is_default_val_field && !internal::is_extra_fields_v && - (_all_required || is_required()); - - // Without _set, the struct was default-constructed before it was read, - // so the field already holds its default value. With _set, the fields - // are constructed in raw memory. An rfl::NamedTuple has no in-class - // initializers, so a missing bare rfl::DefaultVal field is - // value-initialized there. Otherwise the field's default value is not - // available, so the field is required. - const bool defaults_constructed = _set == nullptr; - - if constexpr (is_default_val_field) { - if constexpr (can_value_initialize_default_val()) { - if (_value_initialize_default_vals && !defaults_constructed) { - // The value's constructor can throw, for instance a Validator - // whose zero value is invalid. - try { - ::new (rfl::get<_i>(_view)) ValueType(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - std::get<_i>(*_set) = true; - return; - } - } - } - - if (is_required_field || - (is_default_val_field && !defaults_constructed)) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - std::stringstream stream; - stream << "Field named '" << std::string(current_name) - << "' not found."; - _errors->emplace_back( - make_nested_error(std::string(current_name), stream.str())); - return; - } - - if constexpr (!is_required_field && !is_default_val_field) { - if (defaults_constructed) { - return; - } - using NonConstT = std::remove_const_t; - const auto ptr = const_cast(rfl::get<_i>(_view)); - if constexpr (std::is_nothrow_default_constructible_v) { - ::new (ptr) NonConstT(); - } else { - // The default value can throw, for instance a Validator whose - // default value is invalid. - try { - ::new (ptr) NonConstT(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - } - std::get<_i>(*_set) = true; - } - } - } - - /// Whether a missing rfl::DefaultVal field can be value-initialized. Only - /// an rfl::NamedTuple does this at runtime, and it cannot have const fields, - /// so const fields of structs need no instantiation. - template - static constexpr bool can_value_initialize_default_val() { - using T = typename internal::default_val_t::Type; - return !std::is_const_v && std::is_default_constructible_v && - std::is_default_constructible_v; - } - - /// Generates error messages for when fields are missing. - template + template static RFL_ALWAYS_INLINE void handle_missing_fields( const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors, const bool _value_initialize_default_vals, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors, - _value_initialize_default_vals), + (handle_missing_named_tuple_field<_ignore_empty_containers, _all_required, + _defaults_constructed, ProcessorsType>( + internal::nth_element_t<_is, FieldTypes...>::name(), + std::get<_is>(_found), rfl::get<_is>(_view), + _set ? &std::get<_is>(*_set) : nullptr, _errors, + _value_initialize_default_vals), ...); } - static auto make_parent(const std::string_view& _name, - OutputObjectOrArrayType* _ptr) { - if constexpr (_no_field_names) { - return typename ParentType::Array{_ptr}; - } else { - return typename ParentType::Object{_name, _ptr}; - } - } - static RFL_ALWAYS_INLINE std::pair, std::optional> read_object_or_array(const R& _r, @@ -484,9 +552,9 @@ struct NamedTupleParser { } } if (!should_stop_on_field_error(errors)) { - handle_missing_fields(found, *_view, &set, &errors, - _value_initialize_default_vals, - std::make_integer_sequence()); + handle_missing_fields( + found, *_view, &set, &errors, _value_initialize_default_vals, + std::make_integer_sequence()); } if constexpr (internal::fail_fast_v) { return std::make_pair(set, std::move(errors).error()); @@ -517,9 +585,10 @@ struct NamedTupleParser { if constexpr (internal::has_default_val_v && !internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { - handle_missing_fields(reader.found(), *_view, nullptr, &errors, - /*_value_initialize_default_vals=*/false, - std::make_integer_sequence()); + handle_missing_fields( + reader.found(), *_view, nullptr, &errors, + /*_value_initialize_default_vals=*/false, + std::make_integer_sequence()); } } if constexpr (internal::fail_fast_v) { diff --git a/include/rfl/parsing/call_destructors_where_necessary.hpp b/include/rfl/parsing/call_destructors_where_necessary.hpp index 403609760..a78450fd6 100644 --- a/include/rfl/parsing/call_destructors_where_necessary.hpp +++ b/include/rfl/parsing/call_destructors_where_necessary.hpp @@ -2,7 +2,9 @@ #define RFL_PARSING_CALL_DESTRUCTORS_WHERE_NECESSARY_HPP_ #include +#include #include +#include #include "../get.hpp" @@ -17,41 +19,42 @@ namespace rfl::parsing { */ template void call_destructor_on_array(const size_t _size, T* _ptr) { - for (size_t i = 0; i < _size; ++i) { - if constexpr (std::is_array_v) { - call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); - } else if constexpr (std::is_destructible_v>) { - (_ptr + i)->~T(); + if constexpr (!std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + for (size_t i = 0; i < _size; ++i) { + if constexpr (std::is_array_v) { + call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); + } else if constexpr (std::is_destructible_v>) { + (_ptr + i)->~T(); + } } } } /** - * @brief Calls the destructor on a single element of a view, if necessary. - * - * @tparam ViewType The type of the view. - * @tparam _size The size of the set array. - * @tparam _i The index of the element. - * @param _set A boolean array indicating which elements have been set. - * @param _view The view to call the destructor on. + * @brief Calls the destructor on a single field pointer if it was set. + * Free function parameterized only by the field's pointer type (never + * ViewType) so instantiations do not carry the enclosing NamedTuple in their + * mangled symbol name or DWARF debug info. */ -template -void call_destructor_on_one_if_necessary(const std::array& _set, - ViewType* _view) { - using FieldType = tuple_element_t<_i, typename ViewType::Fields>; - using OriginalType = std::remove_cv_t; - using ValueType = - std::remove_cvref_t>; - if constexpr (!std::is_array_v && - std::is_pointer_v && - std::is_destructible_v) { - if (std::get<_i>(_set)) { - rfl::get<_i>(*_view)->~ValueType(); +template +inline void destroy_field_if_set(const bool _is_set, + const OriginalType& _slot) noexcept { + using CleanOriginal = std::remove_cvref_t; + using ValueType = std::remove_cvref_t>; + if constexpr (std::is_pointer_v && + std::is_array_v) { + if constexpr (!std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + if (_is_set) { + call_destructor_on_array(sizeof(*_slot) / sizeof(**_slot), *_slot); + } } - } else if constexpr (std::is_array_v) { - if (std::get<_i>(_set)) { - auto ptr = rfl::get<_i>(*_view); - call_destructor_on_array(sizeof(*ptr) / sizeof(**ptr), *ptr); + } else if constexpr (std::is_pointer_v && + std::is_destructible_v && + !std::is_trivially_destructible_v) { + if (_is_set) { + _slot->~ValueType(); } } } @@ -68,7 +71,17 @@ template void call_destructors_where_necessary(const std::array& _set, ViewType* _view) { [&](std::integer_sequence) { - (call_destructor_on_one_if_necessary(_set, _view), + ([&]() { + using CleanOriginal = + std::remove_cvref_t(*_view))>; + using ValueType = + std::remove_cvref_t>; + if constexpr (std::is_pointer_v && + !std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + destroy_field_if_set(std::get<_i>(_set), rfl::get<_i>(*_view)); + } + }.template operator()(), ...); }(std::make_integer_sequence()); }