diff --git a/include/rfl/internal/DirectFieldNames.hpp b/include/rfl/internal/DirectFieldNames.hpp new file mode 100644 index 000000000..71a8a9a12 --- /dev/null +++ b/include/rfl/internal/DirectFieldNames.hpp @@ -0,0 +1,196 @@ +#ifndef RFL_INTERNAL_DIRECTFIELDNAMES_HPP_ +#define RFL_INTERNAL_DIRECTFIELDNAMES_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "../num_fields.hpp" +#include "../parsing/find_field_index.hpp" +#include "get_field_names.hpp" +#ifndef REFLECTCPP_USE_CPP26_REFLECTION +#include "cpp20/get_ith_field_from_fake_object.hpp" +#endif + +namespace rfl::internal { + +/// Non-templated runtime view over a struct's field names and optional sorted +/// lookup table (`lookup == nullptr` when `size <= 8`, where linear scan over +/// `names` avoids emitting a separate sorted table in `.rodata`). +struct DirectFieldNamesDesc { + const std::string_view* names; + const parsing::detail::FieldNameEntry* lookup; + std::size_t size; + + constexpr int find(const std::string_view _name) const noexcept { + if (size <= 8) { + for (std::size_t i = 0; i < size; ++i) { + if (names[i] == _name) { + return static_cast(i); + } + } + return -1; + } + std::size_t lo = 0; + std::size_t hi = size; + while (lo < hi) { + const auto 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; + } + + constexpr std::span span() const noexcept { + return {names, size}; + } +}; + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundefined-var-template" +#pragma clang diagnostic ignored "-Wundefined-inline" +#endif + +/// Value-level field name storage and lookup table keyed solely by struct type +/// `T` — never by `StringLiteral` non-type template parameters. All names are +/// copied into a compact null-terminated char buffer so `__PRETTY_FUNCTION__` +/// strings never leak into `.rodata` and every `std::string_view` is +/// null-terminated. +template +struct DirectFieldNames { + using Type = std::remove_cvref_t; + static constexpr std::size_t size_ = num_fields; + + private: + // Intentionally invoked inside consteval helpers rather than stored as a + // `static constexpr` data member of raw `std::string_view`s so compiler + // `__PRETTY_FUNCTION__` strings are never retained in `.rodata`. +#if __GNUC__ +#ifndef __clang__ + [[gnu::no_sanitize_undefined]] +#endif +#endif + static consteval auto extract_names() { + return [](std::index_sequence) { +#ifndef REFLECTCPP_USE_CPP26_REFLECTION +#ifdef __clang__ + return std::array{ + cpp20::get_direct_field_name< + Type, cpp20::wrap( + cpp20::get_ith_field_from_fake_object())>()...}; +#else + return std::array{ + cpp20::get_direct_field_name< + Type, cpp20::get_ith_field_from_fake_object()>()...}; +#endif +#else + return std::array{ + cpp26::get_direct_field_name()...}; +#endif + }(std::make_index_sequence{}); + } + + static consteval auto compute_lengths() { + const auto src = extract_names(); + std::array lens{}; + for (std::size_t i = 0; i < size_; ++i) { + lens[i] = src[i].size(); + } + 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 src = extract_names(); + std::array buffer{}; + std::size_t offset = 0; + for (const auto name : src) { + for (const char ch : name) { + buffer[offset++] = ch; + } + 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_sorted_lookup() { + if constexpr (size_ <= 8) { + return std::array{}; + } else { + std::array table{}; + for (std::size_t i = 0; i < size_; ++i) { + table[i] = {names_[i], static_cast(i)}; + } + 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_sorted_lookup(); + static_assert(has_unique_names(), "Duplicate field names are not allowed."); + + static constexpr DirectFieldNamesDesc desc_{ + names_.data(), size_ <= 8 ? nullptr : lookup_.data(), size_}; + + static constexpr int find(const std::string_view _name) noexcept { + return desc_.find(_name); + } +}; + +#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..8cf445a6a 100644 --- a/include/rfl/internal/bind_to_tuple.hpp +++ b/include/rfl/internal/bind_to_tuple.hpp @@ -9,15 +9,20 @@ 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..502125a14 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,15 @@ 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..684f27f63 100644 --- a/include/rfl/internal/cpp20/get_field_names.hpp +++ b/include/rfl/internal/cpp20/get_field_names.hpp @@ -68,6 +68,31 @@ 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 field's runtime name without wrapping it in rfl::Literal. Unlike +/// get_field_name(), this is suitable for value-level lookup tables. +template +consteval std::string_view get_direct_field_name() { +#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; + } else { + return get_field_name_str_view(); + } +} + 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..9fef01711 100644 --- a/include/rfl/internal/cpp26/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp26/bind_to_tuple.hpp @@ -15,11 +15,16 @@ 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..73d557150 100644 --- a/include/rfl/internal/cpp26/get_field_names.hpp +++ b/include/rfl/internal/cpp26/get_field_names.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -20,6 +21,27 @@ 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(); +}; + +template +consteval std::string_view get_direct_field_name() { + 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; + } else { + return std::meta::identifier_of(members[_i]); + } +} + 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..a8911629b 100644 --- a/include/rfl/internal/has_default_val_v.hpp +++ b/include/rfl/internal/has_default_val_v.hpp @@ -5,7 +5,9 @@ #include #include "../NamedTuple.hpp" -#include "../named_tuple_t.hpp" +#include "bind_to_tuple.hpp" +#include "is_field.hpp" +#include "is_flatten_field.hpp" #include "is_default_val_v.hpp" namespace rfl::internal { @@ -26,9 +28,35 @@ struct HasDefaultVal> { std::remove_cvref_t>>); }; +template +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 requires(std::is_class_v && std::is_aggregate_v) -struct HasDefaultVal : HasDefaultVal> {}; +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> { diff --git a/include/rfl/parsing/DirectStructParser.hpp b/include/rfl/parsing/DirectStructParser.hpp new file mode 100644 index 000000000..b69a9ea75 --- /dev/null +++ b/include/rfl/parsing/DirectStructParser.hpp @@ -0,0 +1,837 @@ +#ifndef RFL_PARSING_DIRECTSTRUCTPARSER_HPP_ +#define RFL_PARSING_DIRECTSTRUCTPARSER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Metadata.hpp" +#include "../NamedTuple.hpp" +#include "../Processors.hpp" +#include "../Result.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 "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "to_single_error_message.hpp" +#include "wrap_error.hpp" + +namespace rfl { +// Forward-declare flag-only identity processors so DirectStructParser.hpp +// avoids pulling in 10 processor headers unconditionally. +struct AddNamespacedTagsToVariants; +struct AddTagsToVariants; +struct AllowRawPtrs; +struct DefaultIfMissing; +struct DurationsAsCount; +struct EnumNamesOnly; +struct FailFast; +struct NoExtraFields; +struct NoFieldNames; +struct NoOptionals; +struct UnderlyingEnums; + +// Forward-declare known named-field readers that never query +// `ObjectReader::size()` as a `static constexpr` expression. +namespace json { +struct Reader; +} +namespace generic { +struct Reader; +} +namespace xml { +struct Reader; +} +namespace env { +struct Reader; +} +namespace yaml { +struct Reader; +} +namespace toml { +struct Reader; +} +namespace cli { +struct Reader; +} +namespace cbor { +struct Reader; +} +namespace bson { +struct Reader; +} +namespace msgpack { +struct Reader; +} +namespace ubjson { +struct Reader; +} +namespace flexbuf { +struct Reader; +} +} // namespace rfl + +namespace rfl::parsing { + +namespace detail { + +template +struct is_direct_identity_processor : std::false_type {}; + +#define RFL_DIRECT_IDENTITY_PROCESSOR(Type) \ + template <> \ + struct is_direct_identity_processor : std::true_type {} + +RFL_DIRECT_IDENTITY_PROCESSOR(DefaultIfMissing); +RFL_DIRECT_IDENTITY_PROCESSOR(NoExtraFields); +RFL_DIRECT_IDENTITY_PROCESSOR(NoFieldNames); +RFL_DIRECT_IDENTITY_PROCESSOR(NoOptionals); +RFL_DIRECT_IDENTITY_PROCESSOR(FailFast); +RFL_DIRECT_IDENTITY_PROCESSOR(UnderlyingEnums); +RFL_DIRECT_IDENTITY_PROCESSOR(EnumNamesOnly); +RFL_DIRECT_IDENTITY_PROCESSOR(AddTagsToVariants); +RFL_DIRECT_IDENTITY_PROCESSOR(AddNamespacedTagsToVariants); +RFL_DIRECT_IDENTITY_PROCESSOR(DurationsAsCount); +RFL_DIRECT_IDENTITY_PROCESSOR(AllowRawPtrs); + +#undef RFL_DIRECT_IDENTITY_PROCESSOR + +template +struct is_direct_identity_processor_pack : is_direct_identity_processor {}; + +template +struct is_direct_identity_processor_pack> + : std::bool_constant< + (is_direct_identity_processor_pack::value && ...)> {}; + +/// Known named-field readers that never query `ObjectReader::size()` as a +/// `static constexpr` expression. For these readers we pass the non-`T`, +/// non-`N` `DirectStructViewReader`, so +/// `R::read_object` is instantiated once per `(R, W, ProcessorsType)` per TU. +/// Unknown/positional readers default to `SizedDirectStructViewReader`. +template +struct reader_needs_static_view_size : std::true_type {}; + +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; +template <> +struct reader_needs_static_view_size : std::false_type {}; + +template +inline constexpr bool reader_needs_static_view_size_v = + reader_needs_static_view_size>::value; + +template +struct DirectFieldTypeList {}; + +template +using direct_field_type_list_t = decltype(internal::apply_to_fields( + std::declval(), [](Fields&...) { + return DirectFieldTypeList{}; + })); + +template +consteval bool direct_field_list_is_supported(DirectFieldTypeList) { + return ((!internal::is_field_v && + !internal::is_flatten_field_v && + !internal::is_extra_fields_v) && + ...); +} + +/// Non-template field-address collector wrappers. Unlike a generic variadic +/// lambda `[](auto&... _refs)`, `FieldAddrCollector::operator()` +/// is a non-template function keyed solely by field count `N` (shared across +/// all `N`-field structs with zero `Fields...` pack mangling or DWARF bloat). +struct MutableFieldAddr { + void* ptr; + + template + RFL_ALWAYS_INLINE MutableFieldAddr(U& _u) noexcept + : ptr(const_cast(static_cast(std::addressof(_u)))) {} +}; + +struct ConstFieldAddr { + const void* ptr; + + template + RFL_ALWAYS_INLINE ConstFieldAddr(const U& _u) noexcept + : ptr(static_cast(std::addressof(_u))) {} +}; + +template +using FieldAddrAt = Addr; + +template +struct FieldAddrCollector; + +template +struct FieldAddrCollector> { + RFL_ALWAYS_INLINE std::array operator()( + FieldAddrAt... _addrs) const noexcept { + return {_addrs.ptr...}; + } +}; + +template +RFL_ALWAYS_INLINE auto collect_mutable_field_ptrs(T& _t) noexcept { + constexpr std::size_t n = num_fields>; + return internal::apply_to_fields( + _t, FieldAddrCollector>{}); +} + +template +RFL_ALWAYS_INLINE auto collect_const_field_ptrs(const T& _t) noexcept { + constexpr std::size_t n = num_fields>; + return internal::apply_to_fields( + _t, FieldAddrCollector>{}); +} + +/// Type-erased per-field thunks parameterized ONLY by individual field type +/// (never by the 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 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_default_field_erased(const R& _r, + const typename R::InputVarType& _var, + const std::string_view _name, void* _field_ptr, + bool& /*_unused_set*/, + FieldErrors* _errors, + const size_t /*_unused_reserve*/) { + auto* ptr = static_cast(_field_ptr); + detail::assign_default_view_field( + _r, _var, _name, ptr, _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 +void build_schema_field_erased( + std::map* _definitions, SchemaType* _schema, + const std::string_view _wire_name, const std::string_view _raw_name, + const void* _default_field_ptr, + const std::span _field_meta) noexcept { + using U = std::remove_cvref_t; + const U* ptr = static_cast(_default_field_ptr); + detail::build_named_tuple_field_schema(_definitions, _schema, _wire_name, + _raw_name, ptr, _field_meta); +} + +using DirectDestroyFn = void (*)(void*) noexcept; + +/// Destroys constructed fields in reverse member order. +inline void destroy_direct_fields(const bool* _set, void* const* _field_ptrs, + const DirectDestroyFn* _destroy_fns, + const size_t _size) noexcept { + for (size_t i = _size; i > 0; --i) { + const size_t idx = i - 1; + if (_set[idx] && _destroy_fns[idx] != nullptr) { + _destroy_fns[idx](_field_ptrs[idx]); + } + } +} + +struct DirectDestroyGuard { + const bool* set; + void* const* field_ptrs; + const DirectDestroyFn* destroy_fns; + size_t size; + + ~DirectDestroyGuard() noexcept { + destroy_direct_fields(set, field_ptrs, destroy_fns, size); + } +}; + +} // namespace detail + +template +struct reader_supports_direct_struct : std::true_type {}; + +/// `rfl::env::Reader::read_object` probes `ObjectReader::ViewType::Names` for +/// struct-field environment lookups (public `rfl::env::read` always appends +/// `ToAllCaps` anyway, so excluding `env::Reader` also keeps direct +/// `rfl::env::Parser>` invocations safe). +template <> +struct reader_supports_direct_struct : std::false_type {}; + +template +inline constexpr bool can_use_direct_struct_parser_v = [] { + using Type = std::remove_cvref_t; + if constexpr (!reader_supports_direct_struct< + std::remove_cvref_t>::value || + !std::is_class_v || !std::is_aggregate_v || + num_fields == 0 || + !detail::is_direct_identity_processor_pack< + ProcessorsType>::value) { + return false; + } else { + return detail::direct_field_list_is_supported( + detail::direct_field_type_list_t{}); + } +}(); + +/// Non-`T`, non-`N` direct view reader for both uninitialized (`_with_default = +/// false`) and default-constructed (`_with_default = true`) aggregate storage. +/// Parameterized only by `(R, W, ProcessorsType, _with_default)` so +/// `R::read_object` is instantiated once per combination across all structs. +template +class DirectStructViewReader { + public: + using InputVarType = typename R::InputVarType; + + using ReadFieldFn = void (*)(const R&, const InputVarType&, std::string_view, + void*, bool&, FieldErrors*, + size_t); + + DirectStructViewReader(const R* _r, + const internal::DirectFieldNamesDesc* _names, + void* const* _field_ptrs, const ReadFieldFn* _read_fns, + bool* _found, bool* _set, size_t* _found_count, + FieldErrors* _errors) noexcept + : r_(_r), + names_(_names), + field_ptrs_(_field_ptrs), + read_fns_(_read_fns), + found_(_found), + set_(_set), + found_count_(_found_count), + errors_(_errors) {} + + ~DirectStructViewReader() = default; + + 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 = names_->find(_name); idx >= 0) { + const auto u = static_cast(idx); + if (!found_[u]) { + found_[u] = true; + ++(*found_count_); + already_assigned = true; + bool dummy_set = false; + read_fns_[u](*r_, _var, names_->names[u], field_ptrs_[u], + set_ != nullptr ? set_[u] : dummy_set, errors_, + names_->size); + } + } + if constexpr (internal::no_extra_fields_v) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + if (!already_assigned) { + std::string msg = "Value named '"; + msg.append(_name); + msg.append("' not used."); + errors_->emplace_back( + make_nested_error(std::string(_name), std::move(msg))); + } + } + } + + 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) < names_->size) { + const auto u = static_cast(_index); + if (!found_[u]) { + found_[u] = true; + ++(*found_count_); + already_assigned = true; + bool dummy_set = false; + read_fns_[u](*r_, _var, names_->names[u], field_ptrs_[u], + set_ != nullptr ? set_[u] : dummy_set, errors_, + names_->size); + } + } + if constexpr (internal::no_extra_fields_v) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + if (!already_assigned) { + std::string msg = "Value named '"; + msg.append(std::to_string(_index)); + msg.append("' not used."); + errors_->emplace_back( + make_nested_error(static_cast(_index), std::move(msg))); + } + } + } + + template + void read(std::integral_constant, const InputVarType& _var) const { + read(i, _var); + } + + private: + const R* r_; + const internal::DirectFieldNamesDesc* names_; + void* const* field_ptrs_; + const ReadFieldFn* read_fns_; + bool* found_; + bool* set_; + size_t* found_count_; + FieldErrors* errors_; +}; + +/// Non-`T`, non-`N` stripped-field-names array reader for both uninitialized +/// and default-constructed aggregate storage. +template +class DirectStructViewReaderStripped { + public: + using InputVarType = typename R::InputVarType; + + using ReadFieldFn = void (*)(const R&, const InputVarType&, std::string_view, + void*, bool&, FieldErrors*, + size_t); + + DirectStructViewReaderStripped( + const R* _r, const internal::DirectFieldNamesDesc* _names, + void* const* _field_ptrs, const ReadFieldFn* _read_fns, bool* _found, + bool* _set, size_t* _found_count, + FieldErrors* _errors) noexcept + : i_(0), + r_(_r), + names_(_names), + field_ptrs_(_field_ptrs), + read_fns_(_read_fns), + found_(_found), + set_(_set), + found_count_(_found_count), + errors_(_errors) {} + + ~DirectStructViewReaderStripped() = default; + + std::optional read(const InputVarType& _var) const { + if (should_stop_on_field_error(*errors_)) { + return std::nullopt; + } + if (i_ == names_->size) { + return Error("Expected a maximum of " + std::to_string(names_->size) + + " fields, but got at least one more."); + } + found_[i_] = true; + ++(*found_count_); + bool dummy_set = false; + read_fns_[i_](*r_, _var, names_->names[i_], field_ptrs_[i_], + set_ != nullptr ? set_[i_] : dummy_set, errors_, + names_->size); + ++i_; + return std::nullopt; + } + + private: + mutable size_t i_; + const R* r_; + const internal::DirectFieldNamesDesc* names_; + void* const* field_ptrs_; + const ReadFieldFn* read_fns_; + bool* found_; + bool* set_; + size_t* found_count_; + FieldErrors* errors_; +}; + +/// Single static-size wrapper for positional/external readers requiring +/// `static constexpr size_t ObjectReader::size()`. +template +class SizedDirectStructViewReader : public Base { + public: + using Base::Base; + static constexpr std::size_t size() noexcept { return _size; } +}; + +namespace detail { + +/// Non-`T`, non-`N` free runtime drivers — instantiated once per +/// `(R, W, _no_field_names, ProcessorsType, ReaderType)` across all structs. +template +std::optional run_direct_read( + const R& _r, const typename R::InputVarType& _var, + const internal::DirectFieldNamesDesc* _names, void* const* _field_ptrs, + const ReadFieldFn* _read_fns, const MissingFn* _missing_fns, bool* _found, + bool* _set) { + FieldErrors errors; + size_t found_count = 0; + + if constexpr (_no_field_names) { + auto arr = _r.to_array(_var); + if (!arr) [[unlikely]] { + return arr.error(); + } + const ReaderType reader(&_r, _names, _field_ptrs, _read_fns, _found, _set, + &found_count, &errors); + auto err = _r.read_array(reader, *arr); + if (err) [[unlikely]] { + return err; + } + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return obj.error(); + } + const ReaderType reader(&_r, _names, _field_ptrs, _read_fns, _found, _set, + &found_count, &errors); + auto err = _r.read_object(reader, *obj); + if (err) [[unlikely]] { + return err; + } + } + + // Happy-path fast exit: when every field was present in input, no missing + // field handler needs to run (eliminating N indirect calls per read). + if (_missing_fns != nullptr && found_count < _names->size && + !should_stop_on_field_error(errors)) { + for (size_t i = 0; i < _names->size; ++i) { + if (!_found[i]) [[unlikely]] { + _missing_fns[i](_names->names[i], false, _field_ptrs[i], + _set != nullptr ? &_set[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 run_direct_write(const W& _w, const P& _parent, + const internal::DirectFieldNamesDesc* _names, + const void* const* _field_ptrs, + const WriteFn* _write_fns) { + using ParentType = Parent; + if constexpr (_no_field_names) { + auto arr = ParentType::add_array(_w, _names->size, _parent); + for (size_t i = 0; i < _names->size; ++i) { + _write_fns[i](_w, _names->names[i], _field_ptrs[i], &arr); + } + _w.end_array(&arr); + } else { + auto obj = ParentType::add_object(_w, _names->size, _parent); + for (size_t i = 0; i < _names->size; ++i) { + _write_fns[i](_w, _names->names[i], _field_ptrs[i], &obj); + } + _w.end_object(&obj); + } +} + +template +schema::Type run_direct_to_schema( + std::map* _definitions, + const internal::DirectFieldNamesDesc* _names, + const void* const* _default_ptrs, const SchemaFn* _schema_fns, + const std::span _field_meta) { + SchemaType schema; + for (size_t i = 0; i < _names->size; ++i) { + _schema_fns[i](_definitions, &schema, _names->names[i], _names->names[i], + _default_ptrs != nullptr ? _default_ptrs[i] : nullptr, + _field_meta); + } + if constexpr (internal::no_extra_fields_v && + !_no_field_names) { + schema.additional_properties_ = false; + } + return schema::Type{schema}; +} + +} // namespace detail + +/// Direct aggregate parser that bypasses `rfl::NamedTuple` and `rfl::Tuple` +/// completely, dispatching through pay-as-you-go `static constexpr` tables of +/// type-erased per-field function pointers and shared non-`T` runtime drivers. +template +struct DirectStructParser { + using InputVarType = typename R::InputVarType; + using Names = internal::DirectFieldNames; + static constexpr size_t size_ = Names::size_; + + 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_; + + using OutputObjectOrArrayType = + std::conditional_t; + using SchemaType = std::conditional_t; + + using ReadFieldFn = void (*)(const R&, const InputVarType&, std::string_view, + void*, bool&, FieldErrors*, + size_t); + using MissingFn = void (*)(std::string_view, bool, void*, bool*, + FieldErrors*, bool) noexcept; + using WriteFn = void (*)(const W&, std::string_view, const void*, + OutputObjectOrArrayType*); + using SchemaFn = void (*)(std::map*, SchemaType*, + std::string_view, std::string_view, const void*, + std::span) noexcept; + + private: + static constexpr bool needs_static_size_ = + detail::reader_needs_static_view_size_v; + + template + using BaseReaderType = std::conditional_t< + no_field_names_, + DirectStructViewReaderStripped, + DirectStructViewReader>; + + template + using ReaderType = std::conditional_t< + needs_static_size_, + SizedDirectStructViewReader, size_>, + BaseReaderType<_with_default>>; + + template + static consteval auto make_read_uninit_table( + detail::DirectFieldTypeList) noexcept { + return std::array{ + &detail::read_uninit_field_erased...}; + } + + template + static consteval auto make_read_default_table( + detail::DirectFieldTypeList) noexcept { + return std::array{ + &detail::read_default_field_erased...}; + } + + template + static consteval auto make_missing_table( + detail::DirectFieldTypeList) noexcept { + return std::array{ + &detail::handle_missing_field_erased< + ignore_empty_containers_, all_required_, _defaults_constructed, + ProcessorsType, Fields>...}; + } + + template + static consteval detail::DirectDestroyFn 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::DirectFieldTypeList) noexcept { + return std::array{ + make_destroy_fn()...}; + } + + template + static consteval auto make_write_table( + detail::DirectFieldTypeList) noexcept { + return std::array{ + &detail::write_field_erased...}; + } + + template + static consteval auto make_schema_table( + detail::DirectFieldTypeList) noexcept { + return std::array{ + &detail::build_schema_field_erased...}; + } + + public: + static RFL_ALWAYS_INLINE Result read(const R& _r, + const InputVarType& _var) { + static constexpr auto read_fns = + make_read_uninit_table(detail::direct_field_type_list_t{}); + static constexpr auto missing_fns = + make_missing_table(detail::direct_field_type_list_t{}); + + alignas(T) unsigned char buf[sizeof(T)]{}; + auto* ptr = internal::ptr_cast(&buf); + const auto field_ptrs = detail::collect_mutable_field_ptrs(*ptr); + std::array found{}; + std::array set{}; + + if constexpr (!std::is_trivially_destructible_v) { + static constexpr auto destroy_fns = + make_destroy_table(detail::direct_field_type_list_t{}); + const detail::DirectDestroyGuard guard{set.data(), field_ptrs.data(), + destroy_fns.data(), size_}; + auto err = detail::run_direct_read>( + _r, _var, &Names::desc_, field_ptrs.data(), read_fns.data(), + missing_fns.data(), found.data(), set.data()); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return Result(std::move(*ptr)); + } else { + auto err = detail::run_direct_read>( + _r, _var, &Names::desc_, field_ptrs.data(), read_fns.data(), + missing_fns.data(), found.data(), set.data()); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return Result(std::move(*ptr)); + } + } + + /// Marked `noexcept` to match `NamedTupleParser::read_view_with_default`, + /// preserving the invariant in `detail::move_assign_field` that updating a + /// live `const` field via destroy + placement-new cannot unwind and + /// double-destroy the member. + static std::optional read_with_default(const R& _r, + const InputVarType& _var, + T* _target) noexcept { + static constexpr auto read_fns = + make_read_default_table(detail::direct_field_type_list_t{}); + const auto field_ptrs = detail::collect_mutable_field_ptrs(*_target); + std::array found{}; + + const MissingFn* missing_ptr = nullptr; + if constexpr (internal::has_default_val_v && + !internal::default_if_missing_v) { + static constexpr auto missing_fns = + make_missing_table(detail::direct_field_type_list_t{}); + missing_ptr = missing_fns.data(); + } + + return detail::run_direct_read>( + _r, _var, &Names::desc_, field_ptrs.data(), read_fns.data(), + missing_ptr, found.data(), nullptr); + } + + template + static void write(const W& _w, const T& _var, const P& _parent) { + static constexpr auto write_fns = + make_write_table(detail::direct_field_type_list_t{}); + const auto field_ptrs = detail::collect_const_field_ptrs(_var); + detail::run_direct_write(_w, _parent, &Names::desc_, + field_ptrs.data(), + write_fns.data()); + } + + static schema::Type to_schema( + std::map* _definitions, + const T* _defaults = nullptr, + const std::span _field_meta = {}) { + static constexpr auto schema_fns = + make_schema_table(detail::direct_field_type_list_t{}); + if (_defaults != nullptr) { + const auto default_ptrs = detail::collect_const_field_ptrs(*_defaults); + return detail::run_direct_to_schema( + _definitions, &Names::desc_, default_ptrs.data(), schema_fns.data(), + _field_meta); + } + return detail::run_direct_to_schema( + _definitions, &Names::desc_, nullptr, schema_fns.data(), _field_meta); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 1e5a0e2d1..2ee587dd7 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -394,6 +394,10 @@ struct NamedTupleParser { static constexpr size_t size_ = NamedTupleType::size(); + 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_assert(NamedTupleType::pos_extra_fields() == -1 || !_no_field_names, "You cannot use the rfl::NoFieldNames processor if you are " "including rfl::ExtraFields."); diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 2974d8499..063555a6d 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -33,6 +33,7 @@ #include "../named_tuple_t.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" +#include "DirectStructParser.hpp" #include "MapParser.hpp" #include "Parent.hpp" #include "ParserArray.hpp" @@ -448,6 +449,10 @@ struct Parser { Parser::write(_w, r, _parent); } + } else if constexpr (can_use_direct_struct_parser_v) { + DirectStructParser, ProcessorsType>::write( + _w, _var, _parent); + } else { const auto ptr_named_tuple = ProcessorsType::template process( internal::to_ptr_named_tuple(_var)); @@ -673,6 +678,30 @@ struct Parser { (*_definitions)[name] = Parser::ReflType, ProcessorsType>::to_schema(_definitions); + } else if constexpr (can_use_direct_struct_parser_v) { + const auto field_meta = [&]() -> std::span { + if constexpr (internal::has_field_metadata_v) { + return internal::get_field_metadata(); + } else { + return {}; + } + }(); + 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] = + DirectStructParser::to_schema( + _definitions, &defaults, field_meta); + } else { + (*_definitions)[name] = + DirectStructParser::to_schema( + _definitions, nullptr, field_meta); + } + } else { using NamedTupleType = internal::processed_t; // The schema takes the default values of rfl::DefaultVal fields from @@ -768,20 +797,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_direct_struct_parser_v) { + return DirectStructParser, + 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 @@ -799,15 +833,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_direct_struct_parser_v) { + auto err = DirectStructParser, + 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/is_view_reader.hpp b/include/rfl/parsing/is_view_reader.hpp index 0afab185a..73b0ef656 100644 --- a/include/rfl/parsing/is_view_reader.hpp +++ b/include/rfl/parsing/is_view_reader.hpp @@ -1,9 +1,18 @@ #ifndef RFL_PARSING_ISVIEWREADER_HPP_ #define RFL_PARSING_ISVIEWREADER_HPP_ +#include +#include + #include "ViewReader.hpp" -namespace rfl ::parsing { +namespace rfl::parsing { + +template +class DirectStructViewReader; + +template +class SizedDirectStructViewReader; /** * @brief Trait to check if a type is a view reader. @@ -20,6 +29,14 @@ template class is_view_reader> : public std::true_type {}; +template +class is_view_reader> + : public std::true_type {}; + +template +class is_view_reader> + : public is_view_reader {}; + template constexpr bool is_view_reader_v = is_view_reader>>::value; diff --git a/scripts/bind_to_tuple.py b/scripts/bind_to_tuple.py index 5b29d356d..97fbad499 100644 --- a/scripts/bind_to_tuple.py +++ b/scripts/bind_to_tuple.py @@ -35,10 +35,10 @@ def _generate_bind_to_tuple_impl(maximum: int) -> str: macros = _generate_macros(1, maximum) return ( """ -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 { """ + macros diff --git a/tests/json/test_direct_struct_parser.cpp b/tests/json/test_direct_struct_parser.cpp new file mode 100644 index 000000000..a7f0ebefb --- /dev/null +++ b/tests/json/test_direct_struct_parser.cpp @@ -0,0 +1,479 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_direct_struct_parser { + +struct PlainStruct { + int a = 1; + std::string b = "hello"; + std::optional c = std::nullopt; +}; + +struct EmptyStruct {}; + +struct FlattenedStruct { + rfl::Flatten inner; + int extra = 0; +}; + +struct ExtraFieldsStruct { + int id = 0; + rfl::ExtraFields extras; +}; + +struct ExplicitFieldStruct { + rfl::Field<"x", int> x = 1; +}; + +struct CustomProcessor { + template + static auto process(NT&& _nt) { + return std::forward(_nt); + } +}; + +// Eligibility static_asserts +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, rfl::Processors<>>); +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, + rfl::Processors>); +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, + rfl::Processors>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + EmptyStruct, rfl::Processors<>>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + FlattenedStruct, rfl::Processors<>>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + ExtraFieldsStruct, rfl::Processors<>>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + ExplicitFieldStruct, rfl::Processors<>>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, rfl::Processors>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, rfl::Processors>>); +static_assert(!rfl::parsing::can_use_direct_struct_parser_v< + PlainStruct, rfl::Processors>); + +// Verify DirectFieldNames null-termination and binary-search (>8 fields) +struct WideStruct { + int f01 = 1; + int f02 = 2; + int f03 = 3; + int f04 = 4; + int f05 = 5; + int f06 = 6; + int f07 = 7; + int f08 = 8; + rfl::Rename<"custom_f09", int> f09 = 9; + int f10 = 10; + std::string f11 = "eleven"; + bool f12 = true; +}; + +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + WideStruct, rfl::Processors<>>); +static_assert(rfl::internal::DirectFieldNames::names_[8] == + "custom_f09"); +static_assert( + rfl::internal::DirectFieldNames::names_[8].data() + [rfl::internal::DirectFieldNames::names_[8].size()] == '\0'); +static_assert( + rfl::internal::DirectFieldNames::find("custom_f09") == 8); +static_assert(rfl::internal::DirectFieldNames::find("f09") == -1); +static_assert(rfl::internal::DirectFieldNames::find("f12") == 11); + +// Lifetime-tracked move-only non-default-constructible type +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 alive = true; + + Tracked() = delete; + Tracked(const Tracked&) = delete; + Tracked& operator=(const Tracked&) = delete; + + explicit Tracked(std::string _v) : value(std::move(_v)), alive(true) { + 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)), alive(true) { + 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_TRUE(alive) << "Double destruction detected!"; + alive = false; + LiveCounter::live.fetch_sub(1); + LiveCounter::destroyed.fetch_add(1); + } + + const std::string& reflection() const { return value; } +}; + +struct TenFieldTracked { + Tracked t0; + int n0; + Tracked t1; + std::string s1; + Tracked t2; + int n2; + Tracked t3; + std::optional opt; + Tracked t4; + Tracked t5; +}; + +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + TenFieldTracked, rfl::Processors<>>); + +struct MoveOnlyConstAndArrays { + const int id = 7; + const std::string tag = "default_tag"; + std::unique_ptr ptr; + std::array nums = {1, 2, 3}; + std::array words = {"a", "b"}; +}; + +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + MoveOnlyConstAndArrays, rfl::Processors<>>); + +struct RenamedSkipAndDefaults { + rfl::Rename<"wire_name", std::string> cpp_name; + rfl::DefaultVal count = 42; + rfl::Skip skipped = 99; + std::optional note; +}; + +struct MetaDocStruct { + int port = 8080; + std::string host = "localhost"; + rfl::DefaultVal tls = true; +}; + +} // namespace test_direct_struct_parser + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = "Server endpoint settings"; + static constexpr std::array fields = {{ + {"port", "TCP listen port"}, + {"host", "Bind address", "Use bind_addr instead"}, + }}; +}; + +namespace test_direct_struct_parser { + +TEST(json, test_direct_struct_wide_binary_search_and_rename) { + const std::string input = + R"({"f12":false,"custom_f09":99,"f01":11,"f02":12,"f03":13,"f04":14,"f05":15,"f06":16,"f07":17,"f08":18,"f10":20,"f11":"hi"})"; + const auto res = rfl::json::read(input); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->f01, 11); + EXPECT_EQ(res->f09.value(), 99); + EXPECT_EQ(res->f11, "hi"); + EXPECT_FALSE(res->f12); + + const auto written = rfl::json::write(*res); + EXPECT_NE(written.find(R"("custom_f09":99)"), std::string::npos); + + const auto extra = rfl::json::read( + R"({"f01":1,"f02":2,"f03":3,"f04":4,"f05":5,"f06":6,"f07":7,"f08":8,"custom_f09":9,"f10":10,"f11":"x","f12":true,"bogus":1})"); + ASSERT_FALSE(extra.has_value()); + EXPECT_NE(extra.error().what().find("Value named 'bogus' not used."), + std::string::npos); +} + +TEST(json, test_direct_struct_tracked_lifetime_and_partial_destruction) { + LiveCounter::reset(); + { + const std::string ok = + R"({"t0":"a","n0":1,"t1":"b","s1":"x","t2":"c","n2":2,"t3":"d","opt":"y","t4":"e","t5":"f"})"; + const auto res = rfl::json::read(ok); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->t0.value, "a"); + EXPECT_EQ(res->t5.value, "f"); + const auto rt = rfl::json::read(rfl::json::write(*res)); + ASSERT_TRUE(rt.has_value()) << rt.error().what(); + EXPECT_EQ(rt->t3.value, "d"); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); + + const std::vector bad_inputs = { + R"({"t0":123,"n0":1,"t1":"b","s1":"x","t2":"c","n2":2,"t3":"d","t4":"e","t5":"f"})", + R"({"t0":"a","n0":1,"t1":"b","s1":"x","t2":"c","n2":"bad","t3":"d","t4":"e","t5":"f"})", + R"({"t5":"f","t4":"e","t3":"d","t2":"c","t1":"b","t0":"a","n2":2,"s1":"x","n0":"bad"})", + R"({"t0":"a","n0":1,"t1":"b","s1":"x","t2":"__THROW__","n2":2,"t3":"d","t4":"e","t5":"f"})", + R"({"t0":"a","n0":1,"t1":"b","s1":"x","t2":"c","n2":2,"t3":"d","t4":"e"})", + 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); + 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); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); + } +} + +TEST(json, test_direct_struct_const_move_only_and_arrays) { + const std::string json = + R"({"id":99,"tag":"custom","ptr":123,"nums":[10,20,30],"words":["hi","yo"]})"; + 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->nums[0], 10); + EXPECT_EQ(res->nums[2], 30); + EXPECT_EQ(res->words[0], "hi"); + EXPECT_EQ(res->words[1], "yo"); + EXPECT_EQ(rfl::json::write(*res), json); + + const auto res_def = + rfl::json::read( + R"({"id":55,"words":["x","y"]})"); + 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->nums[1], 2); + EXPECT_EQ(res_def->words[1], "y"); +} + +TEST(json, test_direct_struct_defaults_skip_no_field_names_and_metadata) { + const auto res = + rfl::json::read(R"({"wire_name":"ok"})"); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res->cpp_name.value(), "ok"); + EXPECT_EQ(res->count.value(), 42); + EXPECT_EQ(res->skipped.value(), 99); + + const auto missing_req = rfl::json::read(R"({})"); + ASSERT_FALSE(missing_req.has_value()); + + // NoFieldNames array read/write & excess-field error + const auto arr_json = rfl::json::write(PlainStruct{3, "z", 1.5}); + EXPECT_EQ(arr_json, R"([3,"z",1.5])"); + const auto arr_rt = rfl::json::read(arr_json); + ASSERT_TRUE(arr_rt.has_value()) << arr_rt.error().what(); + EXPECT_EQ(arr_rt->a, 3); + EXPECT_EQ(arr_rt->b, "z"); + EXPECT_EQ(arr_rt->c, std::optional(1.5)); + + const auto arr_excess = + rfl::json::read(R"([1,"a",2.0,"extra"])"); + ASSERT_FALSE(arr_excess.has_value()); + EXPECT_NE(arr_excess.error().what().find( + "Expected a maximum of 3 fields, but got at least one more."), + std::string::npos); + + // Metadata + DefaultVal + NoExtraFields schema + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("Server endpoint settings"), std::string::npos); + EXPECT_NE(schema.find("TCP listen port"), std::string::npos); + EXPECT_NE(schema.find("Use bind_addr instead"), std::string::npos); + EXPECT_NE(schema.find(R"("default":true)"), std::string::npos); + EXPECT_NE(schema.find(R"("additionalProperties":false)"), std::string::npos); +} + +struct ThrowingDefaultCtorField { + using ReflectionType = std::string; + std::string value; + ThrowingDefaultCtorField() { + throw std::runtime_error("intentional default-ctor throw"); + } + explicit ThrowingDefaultCtorField(std::string _v) : value(std::move(_v)) {} + const std::string& reflection() const { return value; } +}; + +struct ThrowingDefaultStruct { + int a = 1; + ThrowingDefaultCtorField boom; +}; + +struct ThrowingMidParseReader : rfl::json::Reader { + template + std::optional read_object(const ObjectReader& _reader, + const InputObjectType& _obj) const { + rfl::json::Reader::read_object(_reader, _obj); + throw std::runtime_error("mid-parse reader throw"); + } +}; + +TEST(json, test_direct_struct_exception_safety_guard_and_default_catch) { + // 1. Throwing default constructor during DefaultIfMissing must be caught and + // returned as rfl::Error (not std::terminate). + { + const auto res = + rfl::json::read( + R"({"a":2,"boom":"ok"})"); + EXPECT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("intentional default-ctor throw"), + std::string::npos); + } + + // 2. If a non-noexcept reader throws mid-parse after constructing fields in + // stack buf, DirectDestroyGuard must destroy every constructed field with + // zero leaks. + using DirectParserT = rfl::parsing::DirectStructParser< + ThrowingMidParseReader, rfl::json::Writer, TenFieldTracked, + rfl::Processors<>>; + LiveCounter::reset(); + { + const std::string payload = R"({"t0":"first","n0":7,"t1":"second"})"; + yyjson_doc* doc = yyjson_read(payload.data(), payload.size(), 0); + ASSERT_NE(doc, nullptr); + const ThrowingMidParseReader reader{}; + EXPECT_THROW((void)DirectParserT::read( + reader, rfl::json::Reader::InputVarType( + yyjson_doc_get_root(doc))), + std::runtime_error); + yyjson_doc_free(doc); + } + EXPECT_EQ(LiveCounter::live.load(), 0); + EXPECT_GT(LiveCounter::constructed.load(), 0); + EXPECT_EQ(LiveCounter::constructed.load(), LiveCounter::destroyed.load()); +} + +struct DefaultValAndRequired { + int req_a; + rfl::DefaultVal opt_b = "def_b"; + int req_c; +}; + +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + DefaultValAndRequired, rfl::Processors<>>); + +TEST(json, test_direct_struct_duplicate_keys_no_optionals_and_default_edges) { + // 1. Duplicate keys: first-wins by default, rejected under NoExtraFields + // on BOTH uninitialized read() and DefaultIfMissing read_with_default(). + const std::string dup_json = R"({"a":10,"b":"first","a":20})"; + { + const auto r_uninit = rfl::json::read(dup_json); + ASSERT_TRUE(r_uninit.has_value()) << r_uninit.error().what(); + EXPECT_EQ(r_uninit->a, 10); + + const auto r_def = + rfl::json::read(dup_json); + ASSERT_TRUE(r_def.has_value()) << r_def.error().what(); + EXPECT_EQ(r_def->a, 10); + + const auto r_uninit_strict = + rfl::json::read(dup_json); + ASSERT_FALSE(r_uninit_strict.has_value()); + EXPECT_NE(r_uninit_strict.error().what().find("Value named 'a' not used."), + std::string::npos); + + const auto r_def_strict = + rfl::json::read( + dup_json); + ASSERT_FALSE(r_def_strict.has_value()); + EXPECT_NE(r_def_strict.error().what().find("Value named 'a' not used."), + std::string::npos); + } + + // 2. NoOptionals rejects missing std::optional field on direct path. + { + const auto missing_opt = + rfl::json::read(R"({"a":1,"b":"hi"})"); + ASSERT_FALSE(missing_opt.has_value()); + EXPECT_NE(missing_opt.error().what().find("Field named 'c' not found."), + std::string::npos); + + const auto present_null = rfl::json::read( + R"({"a":1,"b":"hi","c":null})"); + ASSERT_TRUE(present_null.has_value()) << present_null.error().what(); + EXPECT_FALSE(present_null->c.has_value()); + } + + // 3. DefaultIfMissing + NoExtraFields + FailFast reports first unknown key. + { + const auto res = + rfl::json::read(R"({"u1":1,"u2":2,"a":5})"); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("Value named 'u1' not used."), + std::string::npos); + EXPECT_EQ(res.error().what().find("u2"), std::string::npos); + } + + // 4. DefaultVal + NoFieldNames: omitted trailing required fails, excess fails, + // and full array succeeds; also DefaultVal schema emits default value. + { + const auto ok = rfl::json::read( + R"([1,"custom",3])"); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok->req_a, 1); + EXPECT_EQ(ok->opt_b.value(), "custom"); + EXPECT_EQ(ok->req_c, 3); + + const auto missing_req = + rfl::json::read(R"([1])"); + ASSERT_FALSE(missing_req.has_value()); + EXPECT_NE(missing_req.error().what().find("Field named 'req_c' not found."), + std::string::npos); + + const auto excess = + rfl::json::read( + R"([1,"x",3,99])"); + ASSERT_FALSE(excess.has_value()); + EXPECT_NE(excess.error().what().find( + "Expected a maximum of 3 fields, but got at least one more."), + std::string::npos); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("default":"def_b")"), std::string::npos); + } +} + +} // namespace test_direct_struct_parser diff --git a/tests/json_c_arrays_and_inheritance/test_direct_struct_c_arrays.cpp b/tests/json_c_arrays_and_inheritance/test_direct_struct_c_arrays.cpp new file mode 100644 index 000000000..ff31875c7 --- /dev/null +++ b/tests/json_c_arrays_and_inheritance/test_direct_struct_c_arrays.cpp @@ -0,0 +1,46 @@ +#include + +#include +#include +#include + +namespace test_direct_struct_c_arrays { + +struct DirectCArrays { + int nums[3] = {1, 2, 3}; + std::string words[2] = {"a", "b"}; + int tail = 9; +}; + +static_assert(rfl::parsing::can_use_direct_struct_parser_v< + DirectCArrays, rfl::Processors<>>); + +TEST(json_c_arrays_and_inheritance, test_direct_struct_c_arrays) { + 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[0], "hi"); + 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[0], 1); + EXPECT_EQ(def_res->nums[2], 3); + EXPECT_EQ(def_res->words[0], "a"); + EXPECT_EQ(def_res->words[1], "b"); + EXPECT_EQ(def_res->tail, 77); + + // Partial-construction failure after non-trivial std::string[2] was populated + // exercises destroy_field_erased cleanup. + const auto bad_res = rfl::json::read( + R"({"nums":[1,2,3],"words":["constructed","strings"],"tail":"not_an_int"})"); + EXPECT_FALSE(bad_res.has_value()); +} + +} // namespace test_direct_struct_c_arrays