diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..5beaa2bfb 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -7,6 +7,7 @@ #pragma warning(disable : 4101) #endif +#include "rfl/AddNullFields.hpp" #include "rfl/AddStructName.hpp" #include "rfl/AddTagsToVariants.hpp" #include "rfl/AllOf.hpp" @@ -35,6 +36,7 @@ #include "rfl/NoExtraFields.hpp" #include "rfl/NoFieldNames.hpp" #include "rfl/NoOptionals.hpp" +#include "rfl/Nullable.hpp" #include "rfl/Object.hpp" #include "rfl/Oct.hpp" #include "rfl/OneOf.hpp" @@ -54,6 +56,7 @@ #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" +#include "rfl/TriState.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" #include "rfl/Variant.hpp" diff --git a/include/rfl/AddNullFields.hpp b/include/rfl/AddNullFields.hpp new file mode 100644 index 000000000..0a4bde5d8 --- /dev/null +++ b/include/rfl/AddNullFields.hpp @@ -0,0 +1,24 @@ +#ifndef RFL_ADDNULLFIELDS_HPP_ +#define RFL_ADDNULLFIELDS_HPP_ + +namespace rfl { + +/// A write-side processor that instructs serializers to emit `"field": null` +/// for empty optional/nullable fields (`std::optional`, `std::shared_ptr`, +/// `std::unique_ptr`, raw pointers) instead of omitting them, while keeping +/// them optional on read (unlike `rfl::NoOptionals`, which also makes them +/// mandatory on read). +/// +/// `rfl::TriState` fields in `State::omitted` remain omitted so tri-state +/// round-tripping is preserved. +struct AddNullFields { + public: + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Nullable.hpp b/include/rfl/Nullable.hpp new file mode 100644 index 000000000..7a622e749 --- /dev/null +++ b/include/rfl/Nullable.hpp @@ -0,0 +1,204 @@ +#ifndef RFL_NULLABLE_HPP_ +#define RFL_NULLABLE_HPP_ + +#include +#include +#include +#include + +namespace rfl { + +template +class Nullable; + +template +class TriState; + +namespace internal { + +template +struct is_nullable_wrapper : std::false_type {}; + +template +struct is_nullable_wrapper> : std::true_type {}; + +template +constexpr bool is_nullable_wrapper_v = + is_nullable_wrapper>::value; + +template +struct is_std_optional_type : std::false_type {}; + +template +struct is_std_optional_type> : std::true_type {}; + +template +struct is_tri_state_fwd : std::false_type {}; + +template +struct is_tri_state_fwd> : std::true_type {}; + +template +constexpr bool is_bool_optional_like_conversion_v = + std::is_same_v, bool> && + (is_std_optional_type>::value || + is_nullable_wrapper>::value || + is_tri_state_fwd>::value); + +} // namespace internal + +/// A nullable field wrapper that ALWAYS serializes explicitly (`"field": null` +/// when empty, `"field": ` when present), unlike `std::optional` +/// which omits empty keys by default. +/// +/// On `read`, `rfl::Nullable` accepts an omitted key (becoming null), an +/// explicit `null` (becoming null), or a value of type `T`; with +/// `rfl::NoOptionals`, an omitted key fails to parse. In JSON Schema +/// (Draft 2020-12), it emits a nullable schema (`anyOf: [, {"type": +/// "null"}]`) and is not placed in `required`. +/// +/// Note: Formats without a native null representation (TOML, XML) serialize +/// null via their writer's fallback; `rfl::Nullable` is intended for formats +/// with native null values (JSON, YAML, Generic, CBOR, MsgPack, etc.). +template +class Nullable { + public: + using value_type = T; + using Type = T; + + constexpr Nullable() noexcept = default; + constexpr Nullable(std::nullopt_t) noexcept : value_(std::nullopt) {} + + constexpr Nullable(const T& _val) + requires std::is_copy_constructible_v + : value_(_val) {} + + constexpr Nullable(T&& _val) noexcept(std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_val)) {} + + constexpr Nullable(const std::optional& _opt) + requires std::is_copy_constructible_v + : value_(_opt) {} + + constexpr Nullable(std::optional&& _opt) noexcept( + std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_opt)) {} + + template + requires(!std::is_same_v, Nullable> && + !std::is_same_v, std::optional> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v) + explicit(!std::is_convertible_v) constexpr Nullable(U&& _val) + : value_(std::in_place, std::forward(_val)) {} + + constexpr Nullable(const Nullable&) = default; + constexpr Nullable(Nullable&&) noexcept( + std::is_nothrow_move_constructible_v) = default; + constexpr Nullable& operator=(const Nullable&) = default; + constexpr Nullable& operator=(Nullable&&) noexcept( + std::is_nothrow_move_assignable_v && + std::is_nothrow_move_constructible_v) = default; + + constexpr Nullable& operator=(std::nullopt_t) noexcept { + value_.reset(); + return *this; + } + + template + requires(std::is_same_v, std::optional> && + ((std::is_lvalue_reference_v && + std::is_copy_constructible_v && std::is_copy_assignable_v) || + (!std::is_lvalue_reference_v && + std::is_move_constructible_v && std::is_move_assignable_v))) + constexpr Nullable& operator=(Opt&& _opt) { + value_ = std::forward(_opt); + return *this; + } + + template + requires(!std::is_same_v, Nullable> && + !std::is_same_v, std::optional> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v && std::is_assignable_v) + constexpr Nullable& operator=(U&& _val) { + value_ = std::forward(_val); + return *this; + } + + constexpr bool has_value() const noexcept { return value_.has_value(); } + constexpr bool is_null() const noexcept { return !value_.has_value(); } + constexpr explicit operator bool() const noexcept { + return value_.has_value(); + } + + constexpr T& value() & { return value_.value(); } + constexpr const T& value() const& { return value_.value(); } + constexpr T&& value() && { return std::move(value_).value(); } + constexpr const T&& value() const&& { return std::move(value_).value(); } + + template + constexpr T value_or(U&& _default) const& { + return value_.value_or(std::forward(_default)); + } + + template + constexpr T value_or(U&& _default) && { + return std::move(value_).value_or(std::forward(_default)); + } + + constexpr T& operator*() & noexcept { return *value_; } + constexpr const T& operator*() const& noexcept { return *value_; } + constexpr T&& operator*() && noexcept { return std::move(*value_); } + constexpr const T&& operator*() const&& noexcept { return std::move(*value_); } + + constexpr T* operator->() noexcept { return value_.operator->(); } + constexpr const T* operator->() const noexcept { return value_.operator->(); } + + constexpr std::optional& optional() & noexcept { return value_; } + constexpr const std::optional& optional() const& noexcept { + return value_; + } + constexpr std::optional&& optional() && noexcept { + return std::move(value_); + } + + constexpr void reset() noexcept { value_.reset(); } + + template + constexpr T& emplace(Args&&... _args) { + return value_.emplace(std::forward(_args)...); + } + + constexpr bool operator==(const Nullable& _other) const = default; + + constexpr bool operator==(std::nullopt_t) const noexcept { + return !value_.has_value(); + } + + constexpr bool operator==(const std::optional& _other) const { + return value_ == _other; + } + + template + requires(!internal::is_nullable_wrapper_v && + !internal::is_std_optional_type>::value && + !std::is_same_v, std::nullopt_t> && + requires(const T& _a, const U& _b) { + { _a == _b } -> std::convertible_to; + }) + constexpr bool operator==(const U& _other) const { + return value_.has_value() && (*value_ == _other); + } + + private: + std::optional value_{}; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/TriState.hpp b/include/rfl/TriState.hpp new file mode 100644 index 000000000..dc8cd9338 --- /dev/null +++ b/include/rfl/TriState.hpp @@ -0,0 +1,209 @@ +#ifndef RFL_TRISTATE_HPP_ +#define RFL_TRISTATE_HPP_ + +#include +#include +#include +#include + +#include "Nullable.hpp" + +namespace rfl { + +/// Tag value representing an omitted (absent) field in `rfl::TriState`. +struct OmittedTag { + explicit OmittedTag() = default; +}; + +inline constexpr OmittedTag omitted{}; + +namespace internal { + +template +struct is_tri_state : std::false_type {}; + +template +struct is_tri_state> : std::true_type {}; + +template +constexpr bool is_tri_state_v = is_tri_state>::value; + +} // namespace internal + +/// Tri-state field presence wrapper distinguishing: +/// 1. `State::omitted` — key was absent from input (default-constructed; +/// omitted on serialization unless `rfl::NoOptionals` is used). +/// 2. `State::null` — key was explicitly present as `null` (serializes as +/// `"field": null`). +/// 3. `State::value` — key was explicitly present with a value of type `T` +/// (serializes as `"field": `). +/// +/// Works across `read`, `write`, and Draft 2020-12 JSON Schema generation. +/// +/// Note: `rfl::TriState` is intended for formats with native null values +/// (JSON, YAML, Generic, CBOR, MsgPack, etc.). +template +class TriState { + public: + using value_type = T; + using Type = T; + + enum class State : uint8_t { + omitted = 0, + null = 1, + value = 2, + }; + + constexpr TriState() noexcept = default; + constexpr TriState(OmittedTag) noexcept + : value_(std::nullopt), state_(State::omitted) {} + constexpr TriState(std::nullopt_t) noexcept + : value_(std::nullopt), state_(State::null) {} + + constexpr TriState(const T& _val) + requires std::is_copy_constructible_v + : value_(_val), state_(State::value) {} + + constexpr TriState(T&& _val) noexcept(std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + : value_(std::move(_val)), state_(State::value) {} + + template + requires(!std::is_same_v, TriState> && + !std::is_same_v, OmittedTag> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v) + explicit(!std::is_convertible_v) constexpr TriState(U&& _val) + : value_(std::in_place, std::forward(_val)), state_(State::value) {} + + constexpr TriState(const TriState&) = default; + constexpr TriState(TriState&&) noexcept( + std::is_nothrow_move_constructible_v) = default; + constexpr TriState& operator=(const TriState&) = default; + constexpr TriState& operator=(TriState&&) noexcept( + std::is_nothrow_move_assignable_v && + std::is_nothrow_move_constructible_v) = default; + + constexpr TriState& operator=(OmittedTag) noexcept { + value_.reset(); + state_ = State::omitted; + return *this; + } + + constexpr TriState& operator=(std::nullopt_t) noexcept { + value_.reset(); + state_ = State::null; + return *this; + } + + template + requires(!std::is_same_v, TriState> && + !std::is_same_v, OmittedTag> && + !std::is_same_v, std::nullopt_t> && + !internal::is_bool_optional_like_conversion_v && + std::is_constructible_v && std::is_assignable_v) + constexpr TriState& operator=(U&& _val) { + value_ = std::forward(_val); + state_ = State::value; + return *this; + } + + static constexpr TriState omitted() noexcept { return TriState(rfl::omitted); } + static constexpr TriState null() noexcept { return TriState(std::nullopt); } + + template + static constexpr TriState of(Args&&... _args) { + TriState ts; + ts.emplace(std::forward(_args)...); + return ts; + } + + constexpr State state() const noexcept { return state_; } + constexpr bool is_omitted() const noexcept { + return state_ == State::omitted; + } + constexpr bool is_present() const noexcept { + return state_ != State::omitted; + } + constexpr bool is_null() const noexcept { return state_ == State::null; } + constexpr bool has_value() const noexcept { return state_ == State::value; } + constexpr explicit operator bool() const noexcept { return has_value(); } + + constexpr T& value() & { return value_.value(); } + constexpr const T& value() const& { return value_.value(); } + constexpr T&& value() && { return std::move(value_).value(); } + constexpr const T&& value() const&& { return std::move(value_).value(); } + + template + constexpr T value_or(U&& _default) const& { + return has_value() ? *value_ : static_cast(std::forward(_default)); + } + + template + constexpr T value_or(U&& _default) && { + return has_value() ? std::move(*value_) + : static_cast(std::forward(_default)); + } + + constexpr T& operator*() & noexcept { return *value_; } + constexpr const T& operator*() const& noexcept { return *value_; } + constexpr T&& operator*() && noexcept { return std::move(*value_); } + constexpr const T&& operator*() const&& noexcept { return std::move(*value_); } + + constexpr T* operator->() noexcept { return value_.operator->(); } + constexpr const T* operator->() const noexcept { return value_.operator->(); } + + constexpr std::optional to_optional() const& + requires std::is_copy_constructible_v + { + return value_; + } + constexpr std::optional to_optional() && noexcept( + std::is_nothrow_move_constructible_v) + requires std::is_move_constructible_v + { + return std::move(value_); + } + + constexpr void reset() noexcept { + value_.reset(); + state_ = State::omitted; + } + + constexpr void set_omitted() noexcept { reset(); } + + constexpr void set_null() noexcept { + value_.reset(); + state_ = State::null; + } + + template + constexpr T& emplace(Args&&... _args) { + // Preserve invariant (state_ == State::value) == value_.has_value() if + // T's constructor throws after std::optional::emplace destroys the old T. + state_ = State::omitted; + T& ref = value_.emplace(std::forward(_args)...); + state_ = State::value; + return ref; + } + + constexpr bool operator==(const TriState& _other) const + requires requires(const T& _a, const T& _b) { + { _a == _b } -> std::convertible_to; + } + { + if (state_ != _other.state_) { + return false; + } + return state_ != State::value || *value_ == *_other.value_; + } + + private: + std::optional value_{}; + State state_ = State::omitted; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index bfa62c928..f2de5dabc 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -13,9 +13,11 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../Nullable.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" +#include "../TriState.hpp" #include "../Tuple.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" @@ -129,6 +131,12 @@ struct cli_annotations> : cli_annotations_t {}; template struct cli_annotations> : cli_annotations_t {}; +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t {}; + template struct cli_annotations> : cli_annotations_t {}; @@ -197,7 +205,9 @@ auto unwrap_option_type() { if constexpr (std::is_pointer_v) { return unwrap_option_type, ProcessorsType>(); } - else if constexpr (parsing::is_optional_v) { + else if constexpr (parsing::is_optional_v + || rfl::internal::is_nullable_wrapper_v + || rfl::internal::is_tri_state_v) { return unwrap_option_type(); } else if constexpr (parsing::is_unique_ptr_v diff --git a/include/rfl/internal/add_null_fields_v.hpp b/include/rfl/internal/add_null_fields_v.hpp new file mode 100644 index 000000000..1bd221c02 --- /dev/null +++ b/include/rfl/internal/add_null_fields_v.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_ADD_NULL_FIELDS_V_HPP_ +#define RFL_INTERNAL_ADD_NULL_FIELDS_V_HPP_ + +#include + +#include "../AddNullFields.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct add_null_fields : std::false_type {}; + +template <> +struct add_null_fields : std::true_type {}; + +template +struct add_null_fields> + : std::bool_constant<(add_null_fields::value || ...)> {}; + +template +inline constexpr bool add_null_fields_v = + add_null_fields>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..7e257eb19 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -10,6 +10,8 @@ #include "../NamedTuple.hpp" #include "../Result.hpp" +#include "../TriState.hpp" +#include "../internal/add_null_fields_v.hpp" #include "../internal/always_inline.hpp" #include "../internal/default_if_missing_v.hpp" #include "../internal/has_default_val_v.hpp" @@ -18,6 +20,9 @@ #include "../internal/is_attribute.hpp" #include "../internal/is_default_val_v.hpp" #include "../internal/is_extra_fields.hpp" +#include "../internal/is_positional.hpp" +#include "../internal/is_rename.hpp" +#include "../internal/is_short.hpp" #include "../internal/is_skip.hpp" #include "../internal/no_extra_fields_v.hpp" #include "../internal/nth_element_t.hpp" @@ -78,6 +83,42 @@ concept CanEmitDefault = namespace rfl::parsing { +template +consteval bool contains_tri_state_wrapper() { + using U = std::remove_cvref_t; + if constexpr (internal::is_tri_state_v) { + return true; + } else if constexpr (internal::is_skip_v) { + return false; + } else if constexpr (internal::is_rename_v || internal::is_short_v || + internal::is_positional_v || + internal::is_default_val_v) { + return contains_tri_state_wrapper(); + } else if constexpr (internal::has_reflection_type_v && + !std::is_same_v) { + return contains_tri_state_wrapper(); + } else { + return false; + } +} + +template +consteval bool contains_skip_serialization_wrapper() { + using U = std::remove_cvref_t; + if constexpr (internal::is_skip_v) { + return U::skip_serialization_; + } else if constexpr (internal::is_rename_v || internal::is_short_v || + internal::is_positional_v || + internal::is_default_val_v) { + return contains_skip_serialization_wrapper(); + } else if constexpr (internal::has_reflection_type_v && + !std::is_same_v) { + return contains_skip_serialization_wrapper(); + } else { + return false; + } +} + template requires AreReaderAndWriter> @@ -260,10 +301,20 @@ struct NamedTupleParser { _w, v, new_parent); } } else if constexpr (!_all_required && !_no_field_names && - !is_required()) { + (!is_required() || + contains_tri_state_wrapper>>())) { constexpr auto name = FieldType::name_.string_view(); const auto new_parent = make_parent(name, _ptr); - if (!is_empty(value)) { + using UnwrappedValueT = + std::remove_cvref_t>; + constexpr bool is_nullable_field = + !is_required() || std::is_pointer_v; + constexpr bool force_emit_null = + internal::add_null_fields_v && is_nullable_field && + !contains_tri_state_wrapper() && + !contains_skip_serialization_wrapper(); + if (force_emit_null || !is_empty(value)) { if constexpr (internal::is_attribute_v) { Parser::write( _w, value, new_parent.as_attribute()); @@ -297,8 +348,17 @@ struct NamedTupleParser { 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()); + const auto& dv_inner = + internal::get_default_val(*rfl::get<_i>(*_view)).get(); + bool skip_omitted_tristate = false; + if constexpr (contains_tri_state_wrapper< + std::remove_cvref_t>()) { + skip_omitted_tristate = is_empty(dv_inner); + } + if (!skip_omitted_tristate) { + value.default_value_ = + rfl::to_generic(dv_inner); + } } }); } diff --git a/include/rfl/parsing/ParserNullable.hpp b/include/rfl/parsing/ParserNullable.hpp new file mode 100644 index 000000000..306de7b41 --- /dev/null +++ b/include/rfl/parsing/ParserNullable.hpp @@ -0,0 +1,87 @@ +#ifndef RFL_PARSING_PARSER_NULLABLE_HPP_ +#define RFL_PARSING_PARSER_NULLABLE_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "../Nullable.hpp" +#include "../Ref.hpp" +#include "../Result.hpp" +#include "Parent.hpp" +#include "Parser_base.hpp" +#include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/OptionalReader.hpp" + +namespace rfl::parsing { + +template +constexpr bool is_nullable_wrapper_v = internal::is_nullable_wrapper_v; + +template +struct ParserNullable { + using InputVarType = typename R::InputVarType; + using ParentType = Parent; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if constexpr (schemaful::IsSchemafulReader) { + using O = schemaful::OptionalReader, + ProcessorsType>; + const auto to_nullable = [&](const auto& _u) -> Result> { + return _r.template read_union, O>(_u).transform( + [](std::optional&& _opt) { return Nullable(std::move(_opt)); }); + }; + return _r.to_union(_var).and_then(to_nullable); + } else { + if (_r.is_empty(_var)) { + return Nullable(std::nullopt); + } + const auto to_nullable = [](auto&& _t) { + return Nullable(std::forward(_t)); + }; + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_nullable); + } + } + + template + static void write(const W& _w, const Nullable& _n, const P& _parent) { + if constexpr (schemaful::IsSchemafulWriter) { + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = + UnionType{.index_ = static_cast(_n.has_value() ? 0 : 1), + .union_ = &u}; + if (_n.has_value()) { + Parser, ProcessorsType>::write(_w, *_n, p); + } else { + ParentType::add_null(_w, p); + } + } else { + if (_n.has_value()) { + Parser, ProcessorsType>::write(_w, *_n, + _parent); + } else { + ParentType::add_null(_w, _parent); + } + } + } + + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::Optional{Ref::make( + Parser::to_schema(_definitions))}}; + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/ParserTriState.hpp b/include/rfl/parsing/ParserTriState.hpp new file mode 100644 index 000000000..e7e20458b --- /dev/null +++ b/include/rfl/parsing/ParserTriState.hpp @@ -0,0 +1,93 @@ +#ifndef RFL_PARSING_PARSER_TRISTATE_HPP_ +#define RFL_PARSING_PARSER_TRISTATE_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "../Ref.hpp" +#include "../Result.hpp" +#include "../TriState.hpp" +#include "Parent.hpp" +#include "Parser_base.hpp" +#include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/OptionalReader.hpp" + +namespace rfl::parsing { + +template +constexpr bool is_tri_state_v = internal::is_tri_state_v; + +template +struct ParserTriState { + using InputVarType = typename R::InputVarType; + using ParentType = Parent; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if constexpr (schemaful::IsSchemafulReader) { + using O = schemaful::OptionalReader, + ProcessorsType>; + const auto to_ts = [&](const auto& _u) -> Result> { + return _r.template read_union, O>(_u).transform( + [](std::optional&& _opt) { + if (_opt.has_value()) { + return TriState(std::move(*_opt)); + } + return TriState::null(); + }); + }; + return _r.to_union(_var).and_then(to_ts); + } else { + if (_r.is_empty(_var)) { + return TriState::null(); + } + const auto to_ts = [](auto&& _t) { + return TriState(std::forward(_t)); + }; + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_ts); + } + } + + template + static void write(const W& _w, const TriState& _ts, const P& _parent) { + if constexpr (schemaful::IsSchemafulWriter) { + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = + UnionType{.index_ = static_cast(_ts.has_value() ? 0 : 1), + .union_ = &u}; + if (_ts.has_value()) { + Parser, ProcessorsType>::write(_w, *_ts, + p); + } else { + ParentType::add_null(_w, p); + } + } else { + if (_ts.has_value()) { + Parser, ProcessorsType>::write(_w, *_ts, + _parent); + } else { + ParentType::add_null(_w, _parent); + } + } + } + + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::Optional{Ref::make( + Parser::to_schema(_definitions))}}; + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..421719fbb 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -40,6 +40,7 @@ #include "ParserEnum.hpp" #include "ParserExpected.hpp" #include "ParserFilepath.hpp" +#include "ParserNullable.hpp" #include "ParserOptional.hpp" #include "ParserPair.hpp" #include "ParserPositional.hpp" @@ -58,6 +59,7 @@ #include "ParserStringView.hpp" #include "ParserTaggedUnion.hpp" #include "ParserTimePoint.hpp" +#include "ParserTriState.hpp" #include "ParserTuple.hpp" #include "ParserUniquePtr.hpp" #include "ParserVariant.hpp" @@ -119,6 +121,14 @@ struct Parser { return ParserOptional::value_type, ProcessorsType>::read(_r, _var); + } else if constexpr (is_nullable_wrapper_v) { + return ParserNullable::value_type, + ProcessorsType>::read(_r, _var); + + } else if constexpr (is_tri_state_v) { + return ParserTriState::value_type, + ProcessorsType>::read(_r, _var); + } else if constexpr (is_box_v) { using IsBox = is_box>; return ParserBox::value_type, ProcessorsType>::write(_w, _var, _parent); + } else if constexpr (is_nullable_wrapper_v) { + ParserNullable::value_type, + ProcessorsType>::write(_w, _var, _parent); + + } else if constexpr (is_tri_state_v) { + ParserTriState::value_type, + ProcessorsType>::write(_w, _var, _parent); + } else if constexpr (is_box_v) { using IsBox = is_box>; ParserBox::to_schema(_definitions); + } else if constexpr (is_nullable_wrapper_v) { + return ParserNullable::to_schema(_definitions); + + } else if constexpr (is_tri_state_v) { + return ParserTriState::to_schema(_definitions); + } else if constexpr (is_box_v) { using IsBox = is_box; return ParserBox +#include "../Nullable.hpp" +#include "../TriState.hpp" #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_default_val_v.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_rename.hpp" #include "../internal/is_short.hpp" @@ -29,6 +32,12 @@ static bool is_empty(const T& _var) { return !_var || is_empty(*_var); } else if constexpr (internal::is_skip_v) { return Type::skip_serialization_; + } else if constexpr (internal::is_nullable_wrapper_v) { + // rfl::Nullable always serializes explicitly ("field": null when null). + return false; + } else if constexpr (internal::is_tri_state_v) { + // rfl::TriState omits only when State::omitted; State::null emits null. + return _var.is_omitted(); } else if constexpr (internal::has_reflection_type_v) { if constexpr (internal::has_reflection_method_v) { return is_empty(_var.reflection()); @@ -38,7 +47,8 @@ static bool is_empty(const T& _var) { } } else if constexpr (internal::is_rename_v || internal::is_short_v || - internal::is_positional_v) { + internal::is_positional_v || + internal::is_default_val_v) { return is_empty(_var.value()); } else if constexpr (is_map_like_v || is_vector_like_v) { return _var.begin() == _var.end(); diff --git a/include/rfl/parsing/is_required.hpp b/include/rfl/parsing/is_required.hpp index 30fe10f6a..0d7c52063 100644 --- a/include/rfl/parsing/is_required.hpp +++ b/include/rfl/parsing/is_required.hpp @@ -6,9 +6,11 @@ #include #include "../Generic.hpp" +#include "../Nullable.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" +#include "../TriState.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/is_positional.hpp" @@ -34,6 +36,12 @@ class is_never_required : public std::false_type {}; template class is_never_required> : public std::true_type {}; +template +class is_never_required> : public std::true_type {}; + +template +class is_never_required> : public std::true_type {}; + template class is_never_required> : public std::true_type {}; diff --git a/tests/json/test_nullable_and_tristate.cpp b/tests/json/test_nullable_and_tristate.cpp new file mode 100644 index 000000000..78cb2555c --- /dev/null +++ b/tests/json/test_nullable_and_tristate.cpp @@ -0,0 +1,341 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_nullable_and_tristate { + +struct Expr { + std::string nodeType = "Literal"; + std::string value = "0"; +}; + +struct VariableDeclaration { + std::string nodeType = "VariableDeclaration"; + std::vector variables = {}; + rfl::Nullable value = std::nullopt; + std::optional debug_comment = std::nullopt; +}; + +struct JsonRpcEnvelope { + std::string jsonrpc = "2.0"; + std::string method = ""; + rfl::TriState> id = rfl::omitted; +}; + +struct WrappedPresence { + rfl::Description<"Always serialized nullable", rfl::Nullable> + explicit_null = std::nullopt; + rfl::Rename<"reqId", rfl::TriState> request_id = rfl::omitted; + rfl::DefaultVal> with_default = 7; + rfl::DefaultVal> with_default_null = std::nullopt; + rfl::DefaultVal> with_default_omitted = rfl::omitted; + rfl::Rename<"renamedOmitted", rfl::DefaultVal>> + renamed_default_omitted = rfl::omitted; +}; + +struct AddNullFieldsStruct { + std::optional a = std::nullopt; + std::optional b = "ok"; + rfl::TriState c = rfl::omitted; + rfl::TriState d = std::nullopt; + std::unique_ptr ptr = nullptr; + std::shared_ptr sptr = nullptr; + rfl::Skip skipped = 42; + rfl::SkipSerialization skip_ser = 99; +}; + +struct XmlContainerAddNull { + std::vector items = {}; + std::map mapping = {}; + std::string name = "x"; +}; + +struct NonComparable { + int v = 0; +}; + +struct MoveOnlyHolder { + rfl::Nullable> ptr = std::nullopt; + rfl::TriState> ts_ptr = rfl::omitted; +}; + +struct NonDefaultConstructible { + int v; + explicit NonDefaultConstructible(int _v) : v(_v) {} + bool operator==(const NonDefaultConstructible&) const = default; +}; + +struct ThrowingCtor { + int v; + explicit ThrowingCtor(int _v) : v(_v) { + if (_v < 0) { + throw std::runtime_error("negative"); + } + } +}; + +struct CliNested { + int port = 80; +}; + +struct CliPresenceOpts { + rfl::TriState verbose = rfl::omitted; + rfl::Nullable server = std::nullopt; +}; + +TEST(json, test_nullable_always_emits_null_while_optional_omits) { + VariableDeclaration decl; + decl.variables = {"x"}; + const auto out = rfl::json::write(decl); + EXPECT_EQ( + out, + R"({"nodeType":"VariableDeclaration","variables":["x"],"value":null})"); + + const auto from_omitted = + rfl::json::read( + R"({"nodeType":"VariableDeclaration","variables":["x"]})") + .value(); + EXPECT_TRUE(from_omitted.value.is_null()); + EXPECT_FALSE(from_omitted.value.has_value()); + + const auto from_null = + rfl::json::read( + R"({"nodeType":"VariableDeclaration","variables":["x"],"value":null})") + .value(); + EXPECT_TRUE(from_null.value.is_null()); + + const auto from_val = + rfl::json::read( + R"({"nodeType":"VariableDeclaration","variables":["x"],"value":{"nodeType":"Literal","value":"42"}})") + .value(); + ASSERT_TRUE(from_val.value.has_value()); + EXPECT_EQ(from_val.value->value, "42"); + EXPECT_EQ( + rfl::json::write(from_val), + R"({"nodeType":"VariableDeclaration","variables":["x"],"value":{"nodeType":"Literal","value":"42"}})"); +} + +TEST(json, test_tristate_jsonrpc_omitted_vs_null_vs_value) { + const auto notif = + rfl::json::read( + R"({"jsonrpc":"2.0","method":"notify"})") + .value(); + EXPECT_TRUE(notif.id.is_omitted()); + EXPECT_FALSE(notif.id.is_present()); + EXPECT_FALSE(notif.id.is_null()); + EXPECT_FALSE(notif.id.has_value()); + EXPECT_EQ(rfl::json::write(notif), + R"({"jsonrpc":"2.0","method":"notify"})"); + + const auto null_req = + rfl::json::read( + R"({"jsonrpc":"2.0","method":"ping","id":null})") + .value(); + EXPECT_FALSE(null_req.id.is_omitted()); + EXPECT_TRUE(null_req.id.is_present()); + EXPECT_TRUE(null_req.id.is_null()); + EXPECT_FALSE(null_req.id.has_value()); + EXPECT_EQ(rfl::json::write(null_req), + R"({"jsonrpc":"2.0","method":"ping","id":null})"); + + const auto val_req = + rfl::json::read( + R"({"jsonrpc":"2.0","method":"get","id":42})") + .value(); + EXPECT_TRUE(val_req.id.is_present()); + EXPECT_TRUE(val_req.id.has_value()); + EXPECT_EQ(std::get(*val_req.id), 42); + EXPECT_EQ(rfl::json::write(val_req), + R"({"jsonrpc":"2.0","method":"get","id":42})"); + + const auto with_dim = + rfl::json::read( + R"({"method":"ping","id":null})") + .value(); + EXPECT_TRUE(with_dim.id.is_null()); + const auto with_dim_omitted = + rfl::json::read( + R"({"method":"ping"})") + .value(); + EXPECT_TRUE(with_dim_omitted.id.is_omitted()); +} + +TEST(json, test_add_null_fields_processor_and_xml_empty_container) { + static_assert(rfl::internal::add_null_fields_v); + static_assert(rfl::internal::add_null_fields_v< + rfl::Processors>>); + + AddNullFieldsStruct s; + EXPECT_EQ(rfl::json::write(s), R"({"b":"ok","d":null})"); + EXPECT_EQ(rfl::json::write(s), + R"({"a":null,"b":"ok","d":null,"ptr":null,"sptr":null})"); + // Nested Processors<...> pack must still honor AddNullFields. + EXPECT_EQ(rfl::json::write>(s), + R"({"a":null,"b":"ok","d":null,"ptr":null,"sptr":null})"); + + const auto read_back = + rfl::json::read(R"({"b":"hi"})") + .value(); + EXPECT_FALSE(read_back.a.has_value()); + EXPECT_EQ(read_back.b, "hi"); + EXPECT_TRUE(read_back.c.is_omitted()); + EXPECT_TRUE(read_back.d.is_omitted()); + EXPECT_EQ(read_back.ptr, nullptr); + EXPECT_EQ(read_back.sptr, nullptr); + + // Under NoOptionals, omitted Nullable and TriState keys must fail on read. + EXPECT_FALSE( + (rfl::json::read( + R"({"jsonrpc":"2.0","method":"notify"})")) + .has_value()); + EXPECT_FALSE( + (rfl::json::read( + R"({"nodeType":"VariableDeclaration","variables":[]})")) + .has_value()); + // Invalid value type propagates parse error. + EXPECT_FALSE( + rfl::json::read(R"({"explicit_null":"not_an_int"})") + .has_value()); + EXPECT_FALSE( + rfl::json::read(R"({"reqId":"not_an_int"})") + .has_value()); + + // Under XML (_ignore_empty_containers=true), AddNullFields must NOT treat + // non-nullable empty vectors or maps as nullable fields. + XmlContainerAddNull xc; + const auto xml_plain = rfl::xml::write<"root">(xc); + const auto xml_anf = rfl::xml::write<"root", rfl::AddNullFields>(xc); + EXPECT_EQ(xml_anf, xml_plain); +} + +TEST(json, test_nullable_and_tristate_schema_and_wrappers) { + // DefaultVal in State::omitted must omit on write (not emit null). + WrappedPresence wp; + EXPECT_EQ( + rfl::json::write(wp), + R"({"explicit_null":null,"with_default":7,"with_default_null":null})"); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE( + schema.find( + R"("value":{"anyOf":[{"$ref":"#/$defs/test_nullable_and_tristate__Expr"},{"type":"null"}]})"), + std::string::npos); + EXPECT_NE(schema.find(R"("required":["nodeType","variables"])"), + std::string::npos); + + const auto rpc_schema = rfl::json::to_schema(); + EXPECT_NE(rpc_schema.find(R"("type":"null")"), std::string::npos); + EXPECT_NE(rpc_schema.find(R"("required":["jsonrpc","method"])"), + std::string::npos); + + const auto wrapped_schema = rfl::json::to_schema(); + EXPECT_NE(wrapped_schema.find("\"description\":\"Always serialized nullable\""), + std::string::npos); + EXPECT_NE(wrapped_schema.find("\"default\":7"), std::string::npos); + EXPECT_NE(wrapped_schema.find("\"default\":null"), std::string::npos); + EXPECT_NE(wrapped_schema.find("\"reqId\""), std::string::npos); + // DefaultVal> with State::omitted must NOT emit "default":null, + // including when wrapped inside rfl::Rename. + const auto pos_omitted = wrapped_schema.find("\"with_default_omitted\""); + ASSERT_NE(pos_omitted, std::string::npos); + const auto omitted_slice = wrapped_schema.substr(pos_omitted, 120); + EXPECT_EQ(omitted_slice.find("\"default\""), std::string::npos); + + const auto pos_renamed_omitted = wrapped_schema.find("\"renamedOmitted\""); + ASSERT_NE(pos_renamed_omitted, std::string::npos); + const auto renamed_slice = wrapped_schema.substr(pos_renamed_omitted, 120); + EXPECT_EQ(renamed_slice.find("\"default\""), std::string::npos); +} + +TEST(json, test_nullable_and_tristate_type_safety_and_exception_safety) { + // Implicit bool conversions from optional-like types are forbidden. + static_assert(!std::is_convertible_v, rfl::TriState>); + static_assert(!std::is_convertible_v, rfl::TriState>); + static_assert(!std::is_convertible_v, rfl::Nullable>); + static_assert(!std::is_convertible_v, rfl::Nullable>); + static_assert(!std::is_convertible_v>>); + static_assert(std::is_constructible_v>, int>); + + // Move-only types properly disable copy construction traits. + static_assert( + !std::is_copy_constructible_v>>); + static_assert( + !std::is_copy_constructible_v>>); + static_assert(!std::is_constructible_v>, + const std::unique_ptr&>); + static_assert(!std::is_constructible_v>, + const std::unique_ptr&>); + + // Move-only JSON round-trip. + const auto moved = + rfl::json::read(R"({"ptr":5,"ts_ptr":null})").value(); + ASSERT_TRUE(moved.ptr.has_value()); + EXPECT_EQ(**moved.ptr, 5); + EXPECT_TRUE(moved.ts_ptr.is_null()); + EXPECT_EQ(rfl::json::write(moved), R"({"ptr":5,"ts_ptr":null})"); + + // Non-default-constructible T works in Nullable and TriState. + rfl::Nullable ndc_n; + EXPECT_TRUE(ndc_n.is_null()); + ndc_n.emplace(42); + EXPECT_EQ(ndc_n->v, 42); + + rfl::TriState ndc_t; + EXPECT_TRUE(ndc_t.is_omitted()); + ndc_t.emplace(99); + EXPECT_EQ(ndc_t->v, 99); + + // Exception safety in TriState::emplace preserves invariant. + rfl::TriState ts_throw; + ts_throw.emplace(10); + ASSERT_TRUE(ts_throw.has_value()); + EXPECT_THROW(ts_throw.emplace(-1), std::runtime_error); + EXPECT_FALSE(ts_throw.has_value()); + EXPECT_TRUE(ts_throw.is_omitted()); + + static_assert(!std::equality_comparable>); + static_assert(!std::equality_comparable>); + + // Unambiguous comparisons and braced empty assignment. + rfl::Nullable ns; + EXPECT_FALSE(ns == "abc"); + ns = "abc"; + EXPECT_TRUE(ns == "abc"); + ns = {}; + EXPECT_TRUE(ns.is_null()); + + rfl::TriState ts = "hi"; + ts = {}; + EXPECT_TRUE(ts.is_omitted()); +} + +TEST(json, test_nullable_and_tristate_generic_and_cli) { + const auto env = + rfl::json::read( + R"({"jsonrpc":"2.0","method":"ping","id":null})") + .value(); + const auto g = rfl::to_generic(env); + const auto from_g = rfl::from_generic(g).value(); + EXPECT_TRUE(from_g.id.is_null()); + + // CLI flag + nested struct option. + const std::vector argv = {"--verbose", "--server.port=9090"}; + const auto cli_res = rfl::cli::read(argv).value(); + ASSERT_TRUE(cli_res.verbose.has_value()); + EXPECT_TRUE(*cli_res.verbose); + ASSERT_TRUE(cli_res.server.has_value()); + EXPECT_EQ(cli_res.server->port, 9090); +} + +} // namespace test_nullable_and_tristate