diff --git a/docs/content/atomic.md b/docs/content/atomic.md index 88e5ae2a7..21995f2f2 100644 --- a/docs/content/atomic.md +++ b/docs/content/atomic.md @@ -66,7 +66,7 @@ if (!res) { ## Limitations and notes - Structs containing atomic fields must be default-constructible. -- Atomic types cannot be mixed with `rfl::DefaultVal` or the `rfl::DefaultIfMissing` processor; attempting to do so triggers a static assertion at compile-time (see parser implementations). +- Atomic types cannot be mixed with `rfl::DefaultVal`, `rfl::DefaultIfMissing`, or `rfl::DefaultIfNull`; attempting to do so triggers a static assertion at compile-time (see parser implementations). - The semantics used for setting atomic values use relaxed memory order (`std::memory_order_relaxed`). - For complex aggregates, `rfl::atomic` will recurse into nested fields and arrays to set atomic members. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..892736b97 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -38,6 +38,7 @@ reflect-cpp currently supports the following processors: - `rfl::AddNamespacedTagsToVariants` - `rfl::AllowRawPtrs` - `rfl::DefaultIfMissing` +- `rfl::DefaultIfNull` - `rfl::DurationsAsCount` - `rfl::EnumNamesOnly` - `rfl::FailFast` @@ -314,6 +315,54 @@ Note that the struct is default-constructed before it is read. Every field therefore needs a valid default value, even if the field is in the input. This is explained in the documentation on `rfl::DefaultVal`. +### `rfl::DefaultIfNull` + +The `rfl::DefaultIfNull` processor is only relevant for reading data. For writing data, it will make no difference. + +Usually, when a non-nullable value is `null` or empty in the input (for example, an empty or comment-only YAML document, a YAML key with no value such as `tags:` or `logging:`, or a JSON `null`), reading fails with a parse error. +If you pass `rfl::DefaultIfNull`, null/empty values are replaced by the target's default value instead (when the target type is default-constructible): + +```cpp +struct Logging { + std::string level = "info"; +}; + +struct Config { + int port = 8080; + std::string host = "localhost"; + std::vector tags; + std::map env; + Logging logging; + std::map modules; +}; +``` + +```yaml +port: null +host: +tags: +env: +logging: +modules: + network: +``` + +```cpp +const auto cfg = rfl::yaml::read(yaml_str).value(); +// cfg.port == 8080, cfg.host == "localhost", cfg.tags.empty(), cfg.env.empty(), +// cfg.logging.level == "info", cfg.modules["network"].level == "info" +``` + +Empty or comment-only YAML documents (and root `null` in JSON) also produce a default-constructed `Config{}`. + +Key details: + +- **In-class member initializers are preserved:** For default-constructible structs, `port: null` preserves `8080` rather than overwriting it with `0`. +- **Nullable types still decode `null` as empty:** `std::optional`, `std::unique_ptr`, `std::shared_ptr`, raw pointers, and `rfl::Generic` always decode an explicit `null` as `std::nullopt` / `nullptr` / `rfl::Generic::Null` — even if the field has a non-null in-class initializer such as `std::optional x = 5`. +- **Missing fields remain required unless combined with `rfl::DefaultIfMissing`:** `rfl::DefaultIfNull` only applies to null/empty values that are present (or a null root document). Combine `rfl::DefaultIfMissing, rfl::DefaultIfNull` when you want both missing fields and null values to fall back to defaults. +- **Non-default-constructible types:** If a type is not default-constructible, encountering `null` falls back to normal error reporting rather than failing to compile. +- **Default-constructible structs are default-constructed before reading:** To preserve in-class member initializers, default-constructible structs are default-constructed before their fields are read. Every field of such a struct therefore needs a valid default value (for example, a `rfl::Validator` whose default constructor throws will cause reading to return an error, even if the field is present in the input). This is explained in the documentation on `rfl::DefaultVal`. + ### `rfl::DurationsAsCount` By default, `std::chrono::duration` types are written as an object containing diff --git a/docs/content/supported_formats/parquet.md b/docs/content/supported_formats/parquet.md index 622d1df32..c46549b06 100644 --- a/docs/content/supported_formats/parquet.md +++ b/docs/content/supported_formats/parquet.md @@ -148,6 +148,7 @@ The following processors are **NOT supported** and will cause compilation errors - `rfl::AddTagsToVariants` - Cannot be used for tabular data - `rfl::NoOptionals` - Cannot be used for tabular data - `rfl::DefaultIfMissing` - Cannot be used for tabular data +- `rfl::DefaultIfNull` - Cannot be used for tabular data - `rfl::NoExtraFields` - Cannot be used for tabular data - `rfl::NoFieldNames` - Cannot be used for tabular data diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..b12732afd 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -20,6 +20,7 @@ #include "rfl/CodePoints.hpp" #include "rfl/Commented.hpp" #include "rfl/DefaultIfMissing.hpp" +#include "rfl/DefaultIfNull.hpp" #include "rfl/DefaultVal.hpp" #include "rfl/Description.hpp" #include "rfl/DurationsAsCount.hpp" diff --git a/include/rfl/Attribute.hpp b/include/rfl/Attribute.hpp index e277323bf..a54928d32 100644 --- a/include/rfl/Attribute.hpp +++ b/include/rfl/Attribute.hpp @@ -24,6 +24,8 @@ struct Attribute { using ReflectionType = T; /// Default constructor. + template + requires std::is_default_constructible_v Attribute() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Commented.hpp b/include/rfl/Commented.hpp index def8e58e4..9dba62aee 100644 --- a/include/rfl/Commented.hpp +++ b/include/rfl/Commented.hpp @@ -24,6 +24,8 @@ struct Commented { /// Default constructor - initializes with default-constructed value and no /// comment. + template + requires std::is_default_constructible_v Commented() : value_(Type()) {} /// Constructs from a value without a comment. diff --git a/include/rfl/DefaultIfNull.hpp b/include/rfl/DefaultIfNull.hpp new file mode 100644 index 000000000..c328692b9 --- /dev/null +++ b/include/rfl/DefaultIfNull.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_DEFAULTIFNULL_HPP_ +#define RFL_DEFAULTIFNULL_HPP_ + +namespace rfl { + +/// A processor that instructs parsers to use default values when encountering +/// null or empty input values. +/// This is a marker type (doesn't modify data) that changes parser behavior. +/// When an input value is null/empty (for example, `null`, `~`, or an empty +/// scalar in YAML, or `null` in JSON) and the target type is +/// default-constructible, the default value is used instead of treating it as +/// an error. On struct fields, in-class member initializers are preserved. +/// Nullable types such as `std::optional`, `std::unique_ptr`, +/// `std::shared_ptr`, and raw pointers continue to decode `null` as empty +/// (`std::nullopt` / `nullptr`). +/// Usage: rfl::yaml::read(yaml_str) +struct DefaultIfNull { + public: + /// Identity process function - returns the named tuple unchanged. + /// The actual default value application happens in the parser, not here. + /// @tparam StructType The struct type being processed + /// @param _named_tuple The named tuple representation of the struct + /// @return The same named tuple (unchanged) + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/DefaultVal.hpp b/include/rfl/DefaultVal.hpp index d3c2edc4d..23ef35412 100644 --- a/include/rfl/DefaultVal.hpp +++ b/include/rfl/DefaultVal.hpp @@ -19,7 +19,9 @@ struct DefaultVal { using Type = std::remove_cvref_t; /// Default constructor - initializes with default-constructed value. - DefaultVal() : value_(Type()) {} + DefaultVal() + requires std::is_default_constructible_v + : value_(Type()) {} /// Constructs from a const reference to the value. /// @param _value The value to store diff --git a/include/rfl/Deprecated.hpp b/include/rfl/Deprecated.hpp index e1cd712fb..dc0c4a5c2 100644 --- a/include/rfl/Deprecated.hpp +++ b/include/rfl/Deprecated.hpp @@ -36,6 +36,8 @@ struct Deprecated { using ReflectionType = Type; /// Default constructor. + template + requires std::is_default_constructible_v Deprecated() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Description.hpp b/include/rfl/Description.hpp index 37fc84092..8fc6b4869 100644 --- a/include/rfl/Description.hpp +++ b/include/rfl/Description.hpp @@ -30,6 +30,8 @@ struct Description { using ReflectionType = Type; /// Default constructor. + template + requires std::is_default_constructible_v Description() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Rename.hpp b/include/rfl/Rename.hpp index c92ecf5fb..ffca72082 100644 --- a/include/rfl/Rename.hpp +++ b/include/rfl/Rename.hpp @@ -29,7 +29,9 @@ struct Rename { using Name = rfl::Literal<_name>; /// Default constructor - creates a Rename with a default-constructed value. - Rename() : value_(Type()) {} + Rename() + requires std::is_default_constructible_v + : value_(Type()) {} /// Constructs from a const reference to the value. /// @param _value The value to store diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 9be58bf61..735f0ce0f 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -53,6 +53,8 @@ struct Validator { /// Default constructor - validates a default-constructed T. /// @throws std::exception if validation of the default value fails + template + requires std::is_default_constructible_v Validator() : value_(ValidationType::validate(T()).value()) {} /// Move constructor. diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index 018edca72..2df6c5e53 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -47,9 +47,10 @@ class Variant { /// alternative type. /// @details The first alternative type is default-constructed and stored in /// the variant. + template > + requires std::is_default_constructible_v Variant() : index_(IndexType()), data_(DataType()) { - using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; - move_from_type(FirstAlternative()); + move_from_type(U()); } /// @brief Copy-constructs the Variant from another Variant. diff --git a/include/rfl/internal/Skip.hpp b/include/rfl/internal/Skip.hpp index 442683dec..fe9af1053 100644 --- a/include/rfl/internal/Skip.hpp +++ b/include/rfl/internal/Skip.hpp @@ -21,6 +21,8 @@ class Skip { using Type = T; using ReflectionType = std::optional; + template + requires std::is_default_constructible_v Skip() : value_(Type()) {} Skip(const Type& _value) : value_(_value) {} diff --git a/include/rfl/internal/default_if_null_v.hpp b/include/rfl/internal/default_if_null_v.hpp new file mode 100644 index 000000000..444f61233 --- /dev/null +++ b/include/rfl/internal/default_if_null_v.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_INTERNAL_DEFAULTIFNULL_HPP_ +#define RFL_INTERNAL_DEFAULTIFNULL_HPP_ + +#include + +#include "../DefaultIfNull.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +class default_if_null; + +template +class default_if_null : public std::false_type {}; + +template <> +class default_if_null : public std::true_type {}; + +template +struct default_if_null> { + static constexpr bool value = + (default_if_null::value || ... || default_if_null::value); +}; + +template +constexpr bool default_if_null_v = + default_if_null>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/is_safe_default_constructible.hpp b/include/rfl/internal/is_safe_default_constructible.hpp new file mode 100644 index 000000000..aaecd57da --- /dev/null +++ b/include/rfl/internal/is_safe_default_constructible.hpp @@ -0,0 +1,405 @@ +#ifndef RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ +#define RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#endif + +#include "../Attribute.hpp" +#include "../Box.hpp" +#include "../Commented.hpp" +#include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.hpp" +#include "../ExtraFields.hpp" +#include "../Field.hpp" +#include "../Flatten.hpp" +#include "../Generic.hpp" +#include "../Object.hpp" +#include "../Positional.hpp" +#include "../Ref.hpp" +#include "../Rename.hpp" +#include "../Short.hpp" +#include "../TaggedUnion.hpp" +#include "../Tuple.hpp" +#include "../Validator.hpp" +#include "../Variant.hpp" +#include "../named_tuple_t.hpp" +#include "Array.hpp" +#include "Skip.hpp" +#include "StringLiteral.hpp" +#include "has_reflection_type_v.hpp" +#include "has_reflector.hpp" +#include "nth_element_t.hpp" + +namespace rfl::internal { + +template +consteval bool is_safe_default_constructible_impl(); + +template +struct safe_default_is_optional : std::false_type {}; + +template +struct safe_default_is_optional> : std::true_type {}; + +template +struct safe_default_is_unique_ptr : std::false_type {}; + +template +struct safe_default_is_unique_ptr> : std::true_type {}; + +template +struct safe_default_is_shared_ptr : std::false_type {}; + +template +struct safe_default_is_shared_ptr> : std::true_type {}; + +template +struct safe_default_is_extra_fields : std::false_type {}; + +template +struct safe_default_is_extra_fields> : std::true_type {}; + +template +struct safe_default_is_object : std::false_type {}; + +template +struct safe_default_is_object> : std::true_type {}; + +template +struct safe_default_is_box : std::false_type {}; + +template +struct safe_default_is_box> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_is_ref : std::false_type {}; + +template +struct safe_default_is_ref> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_is_rfl_array : std::false_type {}; + +template +struct safe_default_is_rfl_array> : std::true_type { + using std_array_type = typename Array::StdArrayType; +}; + +template +struct safe_default_is_std_array : std::false_type {}; + +template +struct safe_default_is_std_array> : std::true_type { + using element_type = V; + static constexpr size_t size = N; +}; + +template +struct safe_default_is_std_variant : std::false_type {}; + +template +struct safe_default_is_std_variant> : std::true_type {}; + +template +struct safe_default_is_rfl_variant : std::false_type {}; + +template +struct safe_default_is_rfl_variant> : std::true_type {}; + +template +struct safe_default_is_tagged_union : std::false_type {}; + +template +struct safe_default_is_tagged_union> + : std::true_type {}; + +template +struct safe_default_is_std_tuple : std::false_type {}; + +template +struct safe_default_is_std_tuple> : std::true_type {}; + +template +struct safe_default_is_rfl_tuple : std::false_type {}; + +template +struct safe_default_is_rfl_tuple> : std::true_type {}; + +template +struct safe_default_is_std_pair : std::false_type {}; + +template +struct safe_default_is_std_pair> : std::true_type { + using first_type = A; + using second_type = B; +}; + +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L +template +struct safe_default_is_expected : std::false_type {}; + +template +struct safe_default_is_expected> : std::true_type { + using value_type = V; +}; +#endif + +template +struct safe_default_value_wrapper : std::false_type {}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> + : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_value_wrapper> : std::true_type { + using element_type = V; +}; + +template +struct safe_default_check_first_alt : std::false_type {}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_first_alt, Visited...> { + static consteval bool eval() { + if constexpr (sizeof...(Alts) == 0) { + return false; + } else { + return is_safe_default_constructible_impl, + Visited...>(); + } + } + static constexpr bool value = eval(); +}; + +template +struct safe_default_check_all_elements : std::false_type {}; + +template +struct safe_default_check_all_elements, Visited...> + : std::bool_constant< + (is_safe_default_constructible_impl() && ...)> {}; + +template +struct safe_default_check_all_elements, Visited...> + : std::bool_constant< + (is_safe_default_constructible_impl() && ...)> {}; + +// Checks every field of a reflected aggregate struct U (where +// std::is_default_constructible_v is already known to be true). +// If a field type F is itself not std::is_default_constructible_v, U can +// only be default-constructible because F has a default member initializer in +// U, so U{} will not call F{}. Otherwise F may be default-constructed by U{} +// and must be recursively verified. +template +struct safe_default_check_aggregate_fields : std::false_type {}; + +template +struct safe_default_check_aggregate_fields, Visited...> { + template + static consteval bool check_one() { + using F = typename std::remove_cvref_t::Type; + if constexpr (!std::is_default_constructible_v) { + return true; + } else { + return is_safe_default_constructible_impl(); + } + } + + static constexpr bool value = (check_one() && ...); +}; + +/// Checks whether T can be safely default-constructed without triggering hard +/// errors inside unconstrained Box/Ref/Tuple default constructors or infinite +/// runtime recursion on cyclic Box/Ref graphs. +template +consteval bool is_safe_default_constructible_impl() { + if constexpr (std::is_reference_v) { + return false; + } else { + using U = std::remove_cvref_t; + if constexpr ((std::is_same_v || ...)) { + return false; + } else if constexpr (safe_default_is_optional::value || + safe_default_is_shared_ptr::value || + safe_default_is_extra_fields::value || + safe_default_is_object::value || + std::is_pointer_v || std::is_same_v || + std::is_same_v) { + return true; + } else if constexpr (safe_default_is_unique_ptr::value) { + return std::is_default_constructible_v; + } else if constexpr (safe_default_is_box::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_box::element_type, U, Visited...>(); + } else if constexpr (safe_default_is_ref::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_ref::element_type, U, Visited...>(); +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L + } else if constexpr (safe_default_is_expected::value) { + using V = typename safe_default_is_expected::value_type; + if constexpr (std::is_void_v) { + return true; + } else { + return std::is_default_constructible_v && + is_safe_default_constructible_impl(); + } +#endif + } else if constexpr (safe_default_is_std_variant::value || + safe_default_is_rfl_variant::value || + safe_default_is_tagged_union::value) { + return safe_default_check_first_alt::value; + } else if constexpr (safe_default_is_std_tuple::value || + safe_default_is_rfl_tuple::value) { + return safe_default_check_all_elements::value; + } else if constexpr (safe_default_is_std_pair::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_std_pair::first_type, U, + Visited...>() && + is_safe_default_constructible_impl< + typename safe_default_is_std_pair::second_type, U, + Visited...>(); + } else if constexpr (safe_default_is_std_array::value) { + if constexpr (safe_default_is_std_array::size == 0) { + return true; + } else { + return is_safe_default_constructible_impl< + typename safe_default_is_std_array::element_type, U, + Visited...>(); + } + } else if constexpr (safe_default_is_rfl_array::value) { + return is_safe_default_constructible_impl< + typename safe_default_is_rfl_array::std_array_type, U, + Visited...>(); + } else if constexpr (std::is_bounded_array_v) { + return is_safe_default_constructible_impl, U, + Visited...>(); + } else if constexpr (std::is_unbounded_array_v) { + return false; + } else if constexpr (safe_default_value_wrapper::value) { + return std::is_default_constructible_v && + is_safe_default_constructible_impl< + typename safe_default_value_wrapper::element_type, U, + Visited...>(); + } else if constexpr (std::is_default_constructible_v && + std::is_class_v && std::is_aggregate_v && + !has_reflection_type_v && !has_read_reflector && + !has_write_reflector) { + if constexpr (requires { typename named_tuple_t; }) { + using Fields = typename named_tuple_t::Fields; + return safe_default_check_aggregate_fields::value; + } else { + return true; + } + } else { + return std::is_default_constructible_v; + } + } +} + +template +constexpr bool is_safe_default_constructible_v = + is_safe_default_constructible_impl(); + +template +struct is_safe_default_constructible + : std::bool_constant> {}; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_IS_SAFE_DEFAULT_CONSTRUCTIBLE_HPP_ diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index ed4cb7454..0059dfe09 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -8,6 +8,7 @@ #include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" #include "MapReader.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -43,6 +44,11 @@ struct MapParser { * @return A Result containing the parsed map or an error. */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return MapType{}; + } + } const auto to_map = [&](auto obj) -> Result { return make_map(_r, obj); }; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..497509739 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -12,12 +15,14 @@ #include "../Result.hpp" #include "../internal/always_inline.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/is_attribute.hpp" #include "../internal/is_default_val_v.hpp" #include "../internal/is_extra_fields.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/is_skip.hpp" #include "../internal/no_extra_fields_v.hpp" #include "../internal/nth_element_t.hpp" @@ -34,6 +39,7 @@ #include "ViewReaderWithStrippedFieldNames.hpp" #include "call_destructors_where_necessary.hpp" #include "is_empty.hpp" +#include "is_nullable.hpp" #include "is_required.hpp" #include "schema/Type.hpp" #include "to_single_error_message.hpp" @@ -125,6 +131,19 @@ struct NamedTupleParser { */ static Result> read( const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + (internal::is_safe_default_constructible_v< + typename std::remove_cvref_t::Type> && + ...)) { + if (_r.is_empty(_var)) { + try { + return NamedTuple( + typename std::remove_cvref_t::Type{}...); + } catch (std::exception& e) { + return error(e.what()); + } + } + } alignas(NamedTuple) unsigned char buf[sizeof(NamedTuple)]; auto ptr = internal::ptr_cast*>(&buf); @@ -401,30 +420,94 @@ struct NamedTupleParser { if constexpr (!is_required_field && !is_default_val_field) { if (defaults_constructed) { + if constexpr (internal::default_if_null_v && + !internal::default_if_missing_v && + !internal::has_default_val_v && + is_nullable_v) { + using NonConstT = std::remove_const_t; + if constexpr (internal::is_safe_default_constructible_v) { + auto* const ptr = const_cast(rfl::get<_i>(_view)); + const auto record_reset_error = [&](const std::string& _msg) { + constexpr auto current_name = + internal::nth_element_t<_i, FieldTypes...>::name(); + _errors->emplace_back(make_nested_error( + std::string(current_name), + "Field named '" + std::string(current_name) + + "' not found, and its default value could not be " + "constructed: " + + _msg)); + }; + if constexpr (std::is_const_v || + !std::is_move_assignable_v) { + if constexpr (std::is_nothrow_default_constructible_v< + NonConstT>) { + std::destroy_at(ptr); + ::new (ptr) NonConstT{}; + } else if constexpr (std::is_nothrow_move_constructible_v< + NonConstT>) { + std::optional tmp; + try { + tmp.emplace(); + } catch (std::exception& e) { + record_reset_error(e.what()); + return; + } + std::destroy_at(ptr); + ::new (ptr) NonConstT(std::move(*tmp)); + } else { + record_reset_error( + "cannot safely reset a const or non-move-assignable " + "field whose default and move constructors may throw."); + } + } else if constexpr (std::is_nothrow_default_constructible_v< + NonConstT> && + std::is_nothrow_move_assignable_v< + NonConstT>) { + *ptr = NonConstT{}; + } else { + try { + *ptr = NonConstT{}; + } catch (std::exception& e) { + record_reset_error(e.what()); + } + } + } + } return; } using NonConstT = std::remove_const_t; - const auto ptr = const_cast(rfl::get<_i>(_view)); - if constexpr (std::is_nothrow_default_constructible_v) { - ::new (ptr) NonConstT(); + if constexpr (!internal::is_safe_default_constructible_v) { + constexpr auto current_name = + internal::nth_element_t<_i, FieldTypes...>::name(); + std::stringstream stream; + stream << "Field named '" << std::string(current_name) + << "' not found."; + _errors->emplace_back( + make_nested_error(std::string(current_name), stream.str())); + return; } else { - // The default value can throw, for instance a Validator whose - // default value is invalid. - try { + const auto ptr = const_cast(rfl::get<_i>(_view)); + if constexpr (std::is_nothrow_default_constructible_v) { ::new (ptr) NonConstT(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; + } else { + // The default value can throw, for instance a Validator whose + // default value is invalid. + try { + ::new (ptr) NonConstT(); + } catch (std::exception& e) { + constexpr auto current_name = + internal::nth_element_t<_i, FieldTypes...>::name(); + _errors->emplace_back(make_nested_error( + std::string(current_name), + "Field named '" + std::string(current_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } } + std::get<_i>(*_set) = true; } - std::get<_i>(*_set) = true; } } } @@ -514,8 +597,7 @@ struct NamedTupleParser { return err; } } - if constexpr (internal::has_default_val_v && - !internal::default_if_missing_v) { + if constexpr (!internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { handle_missing_fields(reader.found(), *_view, nullptr, &errors, /*_value_initialize_default_vals=*/false, diff --git a/include/rfl/parsing/ParserArray.hpp b/include/rfl/parsing/ParserArray.hpp index c34e38cf3..b71eb4336 100644 --- a/include/rfl/parsing/ParserArray.hpp +++ b/include/rfl/parsing/ParserArray.hpp @@ -9,11 +9,14 @@ #include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/ptr_cast.hpp" #include "ArrayReader.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "call_destructors_on_array_where_necessary.hpp" +#include "default_construct.hpp" #include "schema/Type.hpp" namespace rfl::parsing { @@ -46,6 +49,13 @@ struct ParserArray { */ static Result> read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + internal::is_safe_default_constructible_v< + std::array>) { + if (_r.is_empty(_var)) { + return default_construct>(); + } + } alignas( std::array) unsigned char buf[sizeof(std::array)]; auto ptr = internal::ptr_cast*>(&buf); diff --git a/include/rfl/parsing/ParserBasicType.hpp b/include/rfl/parsing/ParserBasicType.hpp index f950ff017..abbc384e5 100644 --- a/include/rfl/parsing/ParserBasicType.hpp +++ b/include/rfl/parsing/ParserBasicType.hpp @@ -9,6 +9,7 @@ #include "../enums.hpp" #include "../from_named_tuple.hpp" #include "../internal/always_inline.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" @@ -50,6 +51,11 @@ struct ParserBasicType { */ static RFL_ALWAYS_INLINE Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return T{}; + } + } return _r.template to_basic_type>(_var); } diff --git a/include/rfl/parsing/ParserBitset.hpp b/include/rfl/parsing/ParserBitset.hpp index bc3dfbe19..e9df1eb38 100644 --- a/include/rfl/parsing/ParserBitset.hpp +++ b/include/rfl/parsing/ParserBitset.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "../internal/bitset.hpp" +#include "../internal/default_if_null_v.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -24,6 +25,11 @@ struct ParserBitset { static Result read(const R& _r, const typename R::InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return Type{}; + } + } return ReprParser::read(_r, _var).and_then([](const auto& _value) { if constexpr (std::is_same_v) { return internal::bitset_from_string(_value); diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index 2daf57608..ccc32d848 100644 --- a/include/rfl/parsing/ParserBox.hpp +++ b/include/rfl/parsing/ParserBox.hpp @@ -10,6 +10,7 @@ #include "../atomic/remove_atomic_t.hpp" #include "../atomic/set_atomic.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -48,6 +49,8 @@ struct ParserBox { "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); + static_assert(!internal::default_if_null_v, + "Atomic types cannot be mixed with rfl::DefaultIfNull"); return Parser::read(_r, _var) .transform([](auto&& _t) { diff --git a/include/rfl/parsing/ParserBytestring.hpp b/include/rfl/parsing/ParserBytestring.hpp index c191ae593..7b7e1c0dc 100644 --- a/include/rfl/parsing/ParserBytestring.hpp +++ b/include/rfl/parsing/ParserBytestring.hpp @@ -6,6 +6,7 @@ #include "../Bytestring.hpp" #include "../Result.hpp" +#include "../internal/default_if_null_v.hpp" #include "AreReaderAndWriter.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -36,6 +37,11 @@ struct ParserBytestring { */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return Bytestring{}; + } + } return _r.template to_basic_type(_var); } diff --git a/include/rfl/parsing/ParserDuration.hpp b/include/rfl/parsing/ParserDuration.hpp index cc02e91c4..2dfefda92 100644 --- a/include/rfl/parsing/ParserDuration.hpp +++ b/include/rfl/parsing/ParserDuration.hpp @@ -8,6 +8,7 @@ #include "../Literal.hpp" #include "../Variant.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/durations_as_count_v.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -56,6 +57,11 @@ struct ParserDuration { */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return DurationType{}; + } + } if constexpr (internal::durations_as_count_v) { return Parser::read(_r, _var).transform( [](const Rep _count) { return DurationType(_count); }); diff --git a/include/rfl/parsing/ParserEnum.hpp b/include/rfl/parsing/ParserEnum.hpp index 4a216f434..a09248c9c 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -7,6 +7,7 @@ #include "../Result.hpp" #include "../config.hpp" #include "../enums.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/enum_names_only_v.hpp" #include "../internal/enums/is_flag_enum.hpp" #include "../internal/enums/is_scoped_enum.hpp" @@ -16,6 +17,7 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "call_destructors_where_necessary.hpp" +#include "is_nullable.hpp" #include "make_type_name.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" @@ -39,6 +41,12 @@ struct ParserEnum { * @return A Result containing the parsed enum or an error. */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + !is_nullable_v) { + if (_r.is_empty(_var)) { + return T{}; + } + } if constexpr (internal::has_read_reflector) { const auto wrap_in_t = [](auto&& _named_tuple) -> Result { try { diff --git a/include/rfl/parsing/ParserRef.hpp b/include/rfl/parsing/ParserRef.hpp index 4b5e8152d..8c598f17f 100644 --- a/include/rfl/parsing/ParserRef.hpp +++ b/include/rfl/parsing/ParserRef.hpp @@ -11,6 +11,7 @@ #include "../atomic/remove_atomic_t.hpp" #include "../atomic/set_atomic.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -47,6 +48,8 @@ struct ParserRef { "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); + static_assert(!internal::default_if_null_v, + "Atomic types cannot be mixed with rfl::DefaultIfNull"); return Parser::read(_r, _var) .transform([](auto&& _t) { diff --git a/include/rfl/parsing/ParserRflVariant.hpp b/include/rfl/parsing/ParserRflVariant.hpp index 857aff132..b64b1961b 100644 --- a/include/rfl/parsing/ParserRflVariant.hpp +++ b/include/rfl/parsing/ParserRflVariant.hpp @@ -8,12 +8,16 @@ #include "../Variant.hpp" #include "../internal/add_tags_to_variants_v.hpp" #include "../internal/all_fields.hpp" +#include "../internal/default_if_null_v.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/nth_element_t.hpp" #include "../visit.hpp" #include "FieldVariantParser.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "VariantAlternativeWrapper.hpp" +#include "default_construct.hpp" +#include "is_nullable.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" @@ -52,6 +56,14 @@ class ParserRflVariant, */ static Result> read( const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + !(is_nullable_v || ...) && + internal::is_safe_default_constructible_v< + rfl::Variant>) { + if (_r.is_empty(_var)) { + return default_construct>(); + } + } if constexpr (internal::all_fields_v) { if constexpr (schemaful::IsSchemafulReader) { using WrappedType = rfl::Variant...>; @@ -222,6 +234,13 @@ class ParserRflVariant, if (!*_result) { using AltType = std::remove_cvref_t>; + if constexpr (internal::default_if_null_v && + (is_nullable_v || ...) && + !is_nullable_v) { + if (_r.is_empty(_var)) { + return; + } + } auto res = Parser::read(_r, _var); if (res) { *_result = std::move(*res); diff --git a/include/rfl/parsing/ParserSharedPtr.hpp b/include/rfl/parsing/ParserSharedPtr.hpp index 50acf14d0..719fbc287 100644 --- a/include/rfl/parsing/ParserSharedPtr.hpp +++ b/include/rfl/parsing/ParserSharedPtr.hpp @@ -12,6 +12,7 @@ #include "../atomic/remove_atomic_t.hpp" #include "../atomic/set_atomic.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -53,6 +54,8 @@ struct ParserSharedPtr { "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); + static_assert(!internal::default_if_null_v, + "Atomic types cannot be mixed with rfl::DefaultIfNull"); return Parser::read(_r, _var) .transform([](auto&& _t) { diff --git a/include/rfl/parsing/ParserTaggedUnion.hpp b/include/rfl/parsing/ParserTaggedUnion.hpp index dee232752..894f3f856 100644 --- a/include/rfl/parsing/ParserTaggedUnion.hpp +++ b/include/rfl/parsing/ParserTaggedUnion.hpp @@ -9,12 +9,15 @@ #include "../Result.hpp" #include "../TaggedUnion.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/no_field_names_v.hpp" #include "../internal/strings/strings.hpp" #include "../named_tuple_t.hpp" #include "../visit.hpp" #include "Parser_base.hpp" #include "TaggedUnionWrapper.hpp" +#include "default_construct.hpp" #include "is_tagged_union_wrapper.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" @@ -65,6 +68,14 @@ struct ParserTaggedUnion, * @return A Result containing the parsed tagged union or an error. */ static ResultType read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + internal::is_safe_default_constructible_v< + TaggedUnion<_discriminator, AlternativeTypes...>>) { + if (_r.is_empty(_var)) { + return default_construct< + TaggedUnion<_discriminator, AlternativeTypes...>>(); + } + } if constexpr (schemaful::IsSchemafulReader) { return Parser, ProcessorsType>::read( _r, _var) diff --git a/include/rfl/parsing/ParserTimePoint.hpp b/include/rfl/parsing/ParserTimePoint.hpp index 558bb42b5..5839e39c8 100644 --- a/include/rfl/parsing/ParserTimePoint.hpp +++ b/include/rfl/parsing/ParserTimePoint.hpp @@ -11,6 +11,7 @@ #include #include "../Result.hpp" +#include "../internal/default_if_null_v.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -47,6 +48,11 @@ struct ParserTimePoint { */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return TimePointType{}; + } + } return Parser::read(_r, _var).and_then( from_string); } diff --git a/include/rfl/parsing/ParserUniquePtr.hpp b/include/rfl/parsing/ParserUniquePtr.hpp index 8eed47a91..8be4d0863 100644 --- a/include/rfl/parsing/ParserUniquePtr.hpp +++ b/include/rfl/parsing/ParserUniquePtr.hpp @@ -12,6 +12,7 @@ #include "../atomic/remove_atomic_t.hpp" #include "../atomic/set_atomic.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -53,6 +54,8 @@ struct ParserUniquePtr { "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); + static_assert(!internal::default_if_null_v, + "Atomic types cannot be mixed with rfl::DefaultIfNull"); return Parser::read(_r, _var) .transform([](auto&& _t) { diff --git a/include/rfl/parsing/ParserVariant.hpp b/include/rfl/parsing/ParserVariant.hpp index 6ea04ce5d..48c912eea 100644 --- a/include/rfl/parsing/ParserVariant.hpp +++ b/include/rfl/parsing/ParserVariant.hpp @@ -11,12 +11,16 @@ #include "../Variant.hpp" #include "../internal/add_tags_to_variants_v.hpp" #include "../internal/all_fields.hpp" +#include "../internal/default_if_null_v.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/to_ptr_field.hpp" #include "../visit.hpp" #include "FieldVariantParser.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "VariantAlternativeWrapper.hpp" +#include "default_construct.hpp" +#include "is_nullable.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" @@ -65,6 +69,14 @@ class ParserVariant, ProcessorsType> { */ static Result> read( const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + !(is_nullable_v || ...) && + internal::is_safe_default_constructible_v< + std::variant>) { + if (_r.is_empty(_var)) { + return default_construct>(); + } + } if constexpr (internal::all_fields_v) { if constexpr (schemaful::IsSchemafulReader) { using WrappedType = rfl::Variant...>; @@ -264,6 +276,13 @@ class ParserVariant, ProcessorsType> { if (!*_result) { using AltType = std::remove_cvref_t>; + if constexpr (internal::default_if_null_v && + (is_nullable_v || ...) && + !is_nullable_v) { + if (_r.is_empty(_var)) { + return; + } + } auto res = Parser::read(_r, _var); if (res) { _result->emplace(std::move(*res)); diff --git a/include/rfl/parsing/ParserVectorstring.hpp b/include/rfl/parsing/ParserVectorstring.hpp index 0618f5620..ab74dcccc 100644 --- a/include/rfl/parsing/ParserVectorstring.hpp +++ b/include/rfl/parsing/ParserVectorstring.hpp @@ -5,6 +5,7 @@ #include "../Result.hpp" #include "../Vectorstring.hpp" +#include "../internal/default_if_null_v.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -35,6 +36,11 @@ struct ParserVectorstring { */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return Vectorstring{}; + } + } return _r.template to_basic_type(_var); } diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..80838d6d4 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -11,6 +11,7 @@ #include "../internal/always_inline.hpp" #include "../internal/cold.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/has_default_val_v.hpp" #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" @@ -19,6 +20,7 @@ #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" #include "../internal/is_literal.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/is_validator.hpp" #include "../internal/processed_t.hpp" #include "../internal/ptr_cast.hpp" @@ -66,6 +68,8 @@ #include "Parser_base.hpp" #include "VectorParser.hpp" #include "call_destructors_where_necessary.hpp" +#include "default_construct.hpp" +#include "is_nullable.hpp" #include "is_string_map.hpp" #include "make_type_name.hpp" #include "schema/Type.hpp" @@ -222,6 +226,18 @@ struct Parser { ProcessorsType>::read(_r, _var); } else if constexpr (internal::has_read_reflector) { + if constexpr (internal::default_if_null_v && + !is_nullable_v) { + if (_r.is_empty(_var)) { + if constexpr (internal::is_safe_default_constructible_v) { + return default_construct(); + } else { + return Result( + error("Cannot construct non-default-constructible type '" + + type_name_t().str() + "' from a null value.")); + } + } + } const auto wrap_in_t = [](auto&& _named_tuple) -> Result { try { using NT = decltype(_named_tuple); @@ -236,13 +252,38 @@ struct Parser { } else if constexpr (schemaful::IsSchemafulReader && internal::is_literal_v) { + if constexpr (internal::default_if_null_v && + internal::is_safe_default_constructible_v) { + if (_r.is_empty(_var)) { + return default_construct(); + } + } return _r.template to_basic_type(_var); } else if constexpr (R::template has_custom_constructor) { + if constexpr (internal::default_if_null_v && + !is_nullable_v && + internal::is_safe_default_constructible_v) { + if (_r.is_empty(_var)) { + return default_construct(); + } + } return _r.template use_custom_constructor(_var); } else { if constexpr (internal::has_reflection_type_v) { + if constexpr (internal::default_if_null_v && + !is_nullable_v) { + if (_r.is_empty(_var)) { + if constexpr (internal::is_safe_default_constructible_v) { + return default_construct(); + } else { + return Result( + error("Cannot construct non-default-constructible type '" + + type_name_t().str() + "' from a null value.")); + } + } + } using ReflectionType = std::remove_cvref_t; const auto wrap_in_t = [](auto&& _named_tuple) -> Result { try { @@ -268,7 +309,9 @@ struct Parser { .and_then(wrap_in_t); } else if constexpr (internal::default_if_missing_v || - internal::has_default_val_v) { + internal::has_default_val_v || + (internal::default_if_null_v && + internal::is_safe_default_constructible_v)) { return read_struct_with_default(_r, _var); } else { @@ -740,6 +783,11 @@ struct Parser { // This might fail, for instance if the default value of a field does not // satisfy its validator. The outer handler is for this line only. auto t = T{}; + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return t; + } + } try { auto view = ProcessorsType::template process(to_view(t)); using ViewType = decltype(view); @@ -762,9 +810,12 @@ struct Parser { /// own, the exception reads as if the input was wrong, so we name the struct /// and explain why it was default-constructed. RFL_COLD static Error default_construction_error(const char* _what) { - const std::string reason = internal::has_default_val_v - ? "it contains rfl::DefaultVal" - : "it is read with rfl::DefaultIfMissing"; + const std::string reason = + internal::has_default_val_v + ? "it contains rfl::DefaultVal" + : (internal::default_if_missing_v + ? "it is read with rfl::DefaultIfMissing" + : "it is read with rfl::DefaultIfNull"); return Error( "Could not default-construct " + type_name_t().str() + ", which is required because " + reason + diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 0e3655dff..3b9505747 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -9,11 +9,14 @@ #include "../Result.hpp" #include "../Tuple.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" +#include "../internal/is_safe_default_constructible.hpp" #include "../internal/nth_element_t.hpp" #include "../internal/ptr_cast.hpp" #include "Parent.hpp" #include "TupleReader.hpp" #include "call_destructors_on_tuple_where_necessary.hpp" +#include "default_construct.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" @@ -41,6 +44,12 @@ struct TupleParser { */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v && + internal::is_safe_default_constructible_v) { + if (_r.is_empty(_var)) { + return default_construct(); + } + } if constexpr (schemaful::IsSchemafulReader) { using NamedTupleType = schemaful::tuple_to_named_tuple_t; const auto to_tuple = [](auto&& _named_tuple) { diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index 2be9ee2e7..987ad5f39 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -10,6 +10,7 @@ #include "../Result.hpp" #include "../Vectorstring.hpp" #include "../always_false.hpp" +#include "../internal/default_if_null_v.hpp" #include "MapParser.hpp" #include "Parent.hpp" #include "Parser_base.hpp" @@ -51,6 +52,11 @@ struct VectorParser { * @return A Result containing the parsed type or an error. */ static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (internal::default_if_null_v) { + if (_r.is_empty(_var)) { + return VecType{}; + } + } if constexpr (treat_as_map()) { return MapParser::read(_r, _var); } else if constexpr (is_forward_list()) { diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..db0d52826 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -10,10 +10,12 @@ #include "../Ref.hpp" #include "../Tuple.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "is_nullable.hpp" #include "wrap_error.hpp" namespace rfl::parsing { @@ -83,6 +85,12 @@ class ViewReaderWithDefault { _current_name == name) { std::get(*_found) = true; *_already_assigned = true; + if constexpr (internal::default_if_null_v && + !is_nullable_v) { + if (_r.is_empty(_var)) { + return; + } + } auto res = Parser::read(_r, _var); if (!res) { _errors->emplace_back(wrap_field_error(name, std::move(res).error())); diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 72512ff66..1add46a8b 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -10,9 +10,11 @@ #include "../Result.hpp" #include "../Tuple.hpp" +#include "../internal/default_if_null_v.hpp" #include "../internal/is_array.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "is_nullable.hpp" #include "wrap_error.hpp" namespace rfl::parsing { @@ -86,6 +88,12 @@ class ViewReaderWithDefaultAndStrippedFieldNames { std::remove_cvref_t>; constexpr auto name = FieldType::name(); if (_i == i) { + if constexpr (internal::default_if_null_v && + !is_nullable_v) { + if (_r.is_empty(_var)) { + return; + } + } auto res = Parser::read(_r, _var); if (!res) { _errors->emplace_back(wrap_field_error(name, std::move(res).error())); diff --git a/include/rfl/parsing/default_construct.hpp b/include/rfl/parsing/default_construct.hpp new file mode 100644 index 000000000..f842aacd0 --- /dev/null +++ b/include/rfl/parsing/default_construct.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_DEFAULT_CONSTRUCT_HPP_ +#define RFL_PARSING_DEFAULT_CONSTRUCT_HPP_ + +#include +#include + +#include "../Result.hpp" +#include "../internal/is_safe_default_constructible.hpp" + +namespace rfl::parsing { + +/// Default-constructs T, catching any exception thrown by T's default +/// constructor and returning it as an rfl::Error so noexcept parsers never +/// terminate. +template + requires internal::is_safe_default_constructible_v +Result default_construct() noexcept { + if constexpr (std::is_nothrow_default_constructible_v && + std::is_nothrow_move_constructible_v) { + return T{}; + } else { + try { + return T{}; + } catch (std::exception& e) { + return error(e.what()); + } + } +} + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/is_nullable.hpp b/include/rfl/parsing/is_nullable.hpp new file mode 100644 index 000000000..42587f6c1 --- /dev/null +++ b/include/rfl/parsing/is_nullable.hpp @@ -0,0 +1,157 @@ +#ifndef RFL_PARSING_IS_NULLABLE_HPP_ +#define RFL_PARSING_IS_NULLABLE_HPP_ + +#include +#include +#include +#include + +#include "../Box.hpp" +#include "../Commented.hpp" +#include "../DefaultVal.hpp" +#include "../Ref.hpp" +#include "../Variant.hpp" +#include "../internal/has_reflection_type_v.hpp" +#include "../internal/has_reflector.hpp" +#include "../internal/is_positional.hpp" +#include "../internal/is_rename.hpp" +#include "../internal/is_short.hpp" +#include "../internal/is_skip.hpp" + +namespace rfl::parsing { + +template +consteval bool is_nullable(); + +namespace internal_nullable { + +template +struct is_optional : std::false_type {}; + +template +struct is_optional> : std::true_type {}; + +template +struct is_unique_ptr : std::false_type {}; + +template +struct is_unique_ptr> : std::true_type {}; + +template +struct is_shared_ptr : std::false_type {}; + +template +struct is_shared_ptr> : std::true_type {}; + +template +struct is_box : std::false_type {}; + +template +struct is_box> : std::true_type { + using element_type = T; +}; + +template +struct is_ref : std::false_type {}; + +template +struct is_ref> : std::true_type { + using element_type = T; +}; + +template +struct is_commented : std::false_type {}; + +template +struct is_commented> : std::true_type { + using element_type = T; +}; + +template +struct is_default_val : std::false_type {}; + +template +struct is_default_val> : std::true_type { + using element_type = T; +}; + +template +struct is_variant : std::false_type {}; + +template +struct is_variant> : std::true_type {}; + +template +struct is_rfl_variant : std::false_type {}; + +template +struct is_rfl_variant> : std::true_type {}; + +template +struct has_nullable_alternative : std::false_type {}; + +template +struct has_nullable_alternative, Seen...> + : std::bool_constant<(is_nullable() || ...)> {}; + +template +struct has_nullable_alternative, Seen...> + : std::bool_constant<(is_nullable() || ...)> {}; + +} // namespace internal_nullable + +/// Checks whether a type natively represents null as a valid value +/// (such as std::optional, std::unique_ptr, std::shared_ptr, raw pointers, +/// rfl::Generic, variants containing a nullable alternative, or transparent +/// wrappers around them). +template +consteval bool is_nullable() { + using U = std::remove_cvref_t; + if constexpr ((std::is_same_v || ...)) { + return false; + } else if constexpr (internal_nullable::is_optional::value || + internal_nullable::is_unique_ptr::value || + internal_nullable::is_shared_ptr::value || + std::is_pointer_v) { + return true; + } else if constexpr (internal_nullable::is_variant::value || + internal_nullable::is_rfl_variant::value) { + return internal_nullable::has_nullable_alternative::value; + } else if constexpr (internal::is_rename_v || internal::is_short_v || + internal::is_positional_v) { + return is_nullable(); + } else if constexpr (internal_nullable::is_default_val::value) { + return is_nullable< + typename internal_nullable::is_default_val::element_type, U, + Seen...>(); + } else if constexpr (internal_nullable::is_commented::value) { + return is_nullable< + typename internal_nullable::is_commented::element_type, U, + Seen...>(); + } else if constexpr (internal_nullable::is_box::value) { + return is_nullable::element_type, U, + Seen...>(); + } else if constexpr (internal_nullable::is_ref::value) { + return is_nullable::element_type, U, + Seen...>(); + } else if constexpr (internal::is_skip_v) { + if constexpr (U::skip_deserialization_) { + return false; + } else { + return is_nullable(); + } + } else if constexpr (internal::has_reflection_type_v) { + return is_nullable(); + } else if constexpr (internal::has_read_reflector) { + return is_nullable::ReflType, U, Seen...>(); + } else { + return false; + } +} + +template +constexpr bool is_nullable_v = is_nullable(); + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/tabular/ArrowReader.hpp b/include/rfl/parsing/tabular/ArrowReader.hpp index aea813965..77cfd16fd 100644 --- a/include/rfl/parsing/tabular/ArrowReader.hpp +++ b/include/rfl/parsing/tabular/ArrowReader.hpp @@ -29,6 +29,7 @@ #include "../../get.hpp" #include "../../internal/add_tags_to_variants_v.hpp" #include "../../internal/default_if_missing_v.hpp" +#include "../../internal/default_if_null_v.hpp" #include "../../internal/no_extra_fields_v.hpp" #include "../../internal/no_field_names_v.hpp" #include "../../internal/no_optionals_v.hpp" @@ -51,6 +52,8 @@ class ArrowReader { "rfl::NoOptionals cannot be used for tabular data."); static_assert(!internal::default_if_missing_v>, "rfl::DefaultIfMissing cannot be used for tabular data."); + static_assert(!internal::default_if_null_v>, + "rfl::DefaultIfNull cannot be used for tabular data."); static_assert(!internal::no_extra_fields_v>, "rfl::NoExtraFields cannot be used for tabular data (neither " "can rfl::ExtraFields)."); diff --git a/include/rfl/parsing/tabular/ArrowWriter.hpp b/include/rfl/parsing/tabular/ArrowWriter.hpp index fb61a1c87..effeb62e9 100644 --- a/include/rfl/parsing/tabular/ArrowWriter.hpp +++ b/include/rfl/parsing/tabular/ArrowWriter.hpp @@ -25,6 +25,7 @@ #include "../../get.hpp" #include "../../internal/add_tags_to_variants_v.hpp" #include "../../internal/default_if_missing_v.hpp" +#include "../../internal/default_if_null_v.hpp" #include "../../internal/no_extra_fields_v.hpp" #include "../../internal/no_field_names_v.hpp" #include "../../internal/no_optionals_v.hpp" @@ -48,6 +49,8 @@ class ArrowWriter { "rfl::NoOptionals cannot be used for tabular data."); static_assert(!internal::default_if_missing_v>, "rfl::DefaultIfMissing cannot be used for tabular data."); + static_assert(!internal::default_if_null_v>, + "rfl::DefaultIfNull cannot be used for tabular data."); static_assert(!internal::no_extra_fields_v>, "rfl::NoExtraFields cannot be used for tabular data (neither " "can rfl::ExtraFields)."); diff --git a/tests/json/test_default_if_null.cpp b/tests/json/test_default_if_null.cpp new file mode 100644 index 000000000..3e6143849 --- /dev/null +++ b/tests/json/test_default_if_null.cpp @@ -0,0 +1,873 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_default_if_null { + +struct Logging { + std::string level = "info"; + bool timestamps = true; +}; + +struct Config { + int port = 8080; + std::string host = "localhost"; + std::vector tags; + std::map env; + std::unordered_map labels; + Logging logging; + std::map modules; +}; + +struct NoDefault { + using ReflectionType = int; + int v; + NoDefault() = delete; + explicit NoDefault(int _v) : v(_v) {} + int reflection() const { return v; } +}; + +struct NonDefaultParent { + NoDefault req; + std::vector tags; +}; + +struct DefaultConstructibleWithNonDefaultField { + NoDefault req = NoDefault(42); + int port = 8080; +}; + +struct WithNullableFields { + int port = 8080; + std::optional opt_empty; + std::optional opt_with_default = 5; + std::unique_ptr uptr = std::make_unique(7); + std::shared_ptr sptr = std::make_shared(9); + rfl::Rename<"opt_renamed", std::optional> opt_renamed = 11; + rfl::DefaultVal> opt_default_val = 13; + rfl::Generic generic_val = 99; +}; + +struct WithOptionalDmi { + int port = 8080; + std::optional opt_with_default = 5; + std::unique_ptr uptr = std::make_unique(7); + std::shared_ptr sptr = std::make_shared(9); + rfl::Rename<"opt_renamed", std::optional> opt_renamed = 11; + const std::optional const_opt = 15; +}; + +struct PositiveNoDefault { + static rfl::Result validate(NoDefault _v) { + if (_v.v <= 0) { + return rfl::error("Must be positive"); + } + return _v; + } +}; + +struct NoDefault2 { + using ReflectionType = std::string; + std::string s; + NoDefault2() = delete; + explicit NoDefault2(std::string _s) : s(std::move(_s)) {} + const std::string& reflection() const { return s; } +}; + +struct WrappedNoDefaultFields { + rfl::Description<"desc", NoDefault> desc; + rfl::Deprecated<"old", "dep", NoDefault> dep; + rfl::Commented commented; + rfl::Box box; + rfl::Ref ref; + rfl::Attribute attr; + rfl::Validator validated; + rfl::Variant variant; + rfl::SkipSerialization skipped_ser; + std::vector tags; +}; + +struct WithNullableVariants { + std::variant> std_var = 42; + rfl::Variant> rfl_var = 42; + std::variant plain_std_var = 7; + rfl::Variant plain_rfl_var = 9; +}; + +struct WithDefaultValAndRename { + rfl::DefaultVal retries = 3; + rfl::DefaultVal mode = "fast"; + rfl::Rename<"server_port", int> port = 9090; + const int fixed_version = 2; + std::vector default_tags = {"alpha", "beta"}; + Logging custom_logging = Logging{.level = "warn", .timestamps = false}; +}; + +struct Outer { + struct Inner { + int timeout = 30; + std::string endpoint = "http://localhost"; + }; + Inner inner; + std::vector sinks; +}; + +enum class Color { red, green, blue }; + +using NonEmptyTags = + rfl::Validator, rfl::Size>>; + +struct WithThrowingValidatorDefault { + std::string name; + NonEmptyTags tags; +}; + +struct WithValidValidatorDefault { + std::string name = "svc"; + NonEmptyTags tags = std::vector{"default"}; +}; + +// Case 1 & 2 equivalent in JSON: root null -> default-constructed root struct. +TEST(json, test_default_if_null_root_null) { + // Default behavior without DefaultIfNull still fails. + EXPECT_FALSE(rfl::json::read("null").has_value()); + + const auto res = rfl::json::read("null"); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& cfg = res.value(); + EXPECT_EQ(cfg.port, 8080); + EXPECT_EQ(cfg.host, "localhost"); + EXPECT_TRUE(cfg.tags.empty()); + EXPECT_TRUE(cfg.env.empty()); + EXPECT_TRUE(cfg.labels.empty()); + EXPECT_EQ(cfg.logging.level, "info"); + EXPECT_TRUE(cfg.logging.timestamps); + EXPECT_TRUE(cfg.modules.empty()); +} + +// Cases 3, 4, 5, 6 + DMI preservation on struct fields. +TEST(json, test_default_if_null_all_cases_and_dmis) { + const std::string json_str = R"({ + "port": null, + "host": null, + "tags": null, + "env": null, + "labels": null, + "logging": null, + "modules": { + "network": null, + "storage": {"level": "debug", "timestamps": false} + } + })"; + + // Without DefaultIfNull, this fails. + EXPECT_FALSE(rfl::json::read(json_str).has_value()); + + const auto res = rfl::json::read(json_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& cfg = res.value(); + EXPECT_EQ(cfg.port, 8080); + EXPECT_EQ(cfg.host, "localhost"); + EXPECT_TRUE(cfg.tags.empty()); + EXPECT_TRUE(cfg.env.empty()); + EXPECT_TRUE(cfg.labels.empty()); + EXPECT_EQ(cfg.logging.level, "info"); + EXPECT_TRUE(cfg.logging.timestamps); + ASSERT_EQ(cfg.modules.size(), 2u); + EXPECT_EQ(cfg.modules.at("network").level, "info"); + EXPECT_TRUE(cfg.modules.at("network").timestamps); + EXPECT_EQ(cfg.modules.at("storage").level, "debug"); + EXPECT_FALSE(cfg.modules.at("storage").timestamps); +} + +// Case 6b: Null element inside std::vector and nested structs. +TEST(json, test_default_if_null_nested_and_vector_elements) { + const std::string json_str = R"({ + "inner": null, + "sinks": [null, {"level": "error", "timestamps": false}] + })"; + + EXPECT_FALSE(rfl::json::read(json_str).has_value()); + + const auto res = rfl::json::read(json_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res.value().inner.timeout, 30); + EXPECT_EQ(res.value().inner.endpoint, "http://localhost"); + ASSERT_EQ(res.value().sinks.size(), 2u); + EXPECT_EQ(res.value().sinks[0].level, "info"); + EXPECT_TRUE(res.value().sinks[0].timestamps); + EXPECT_EQ(res.value().sinks[1].level, "error"); + EXPECT_FALSE(res.value().sinks[1].timestamps); +} + +// Nullable types (optional, unique_ptr, shared_ptr, Generic) MUST still decode +// explicit null as std::nullopt / nullptr / Generic::Null even if they have +// non-null DMIs. +TEST(json, test_default_if_null_preserves_nullable_semantics) { + const std::string json_str = R"({ + "port": null, + "opt_empty": null, + "opt_with_default": null, + "uptr": null, + "sptr": null, + "opt_renamed": null, + "opt_default_val": null, + "generic_val": null + })"; + + const auto res = + rfl::json::read(json_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& v = res.value(); + EXPECT_EQ(v.port, 8080); + EXPECT_FALSE(v.opt_empty.has_value()); + EXPECT_FALSE(v.opt_with_default.has_value()); + EXPECT_EQ(v.uptr, nullptr); + EXPECT_EQ(v.sptr, nullptr); + EXPECT_FALSE(v.opt_renamed.value().has_value()); + EXPECT_FALSE(v.opt_default_val.value().has_value()); + EXPECT_TRUE(v.generic_val.is_null()); +} + +// Omitted optional with DMI: +// - DefaultIfNull alone resets omitted nullable fields to empty (matching +// default read without DefaultIfMissing), and explicit null also decodes to +// empty. +// - DefaultIfMissing + DefaultIfNull preserves the DMI when omitted, while +// explicit null clears it to empty. +TEST(json, test_default_if_null_optional_omitted_vs_null) { + // Baseline without processors: omitted nullable fields become empty. + const auto res_baseline = + rfl::json::read(R"({"port": 80})"); + ASSERT_TRUE(res_baseline.has_value()) << res_baseline.error().what(); + EXPECT_EQ(res_baseline.value().port, 80); + EXPECT_FALSE(res_baseline.value().opt_with_default.has_value()); + EXPECT_EQ(res_baseline.value().uptr, nullptr); + EXPECT_EQ(res_baseline.value().sptr, nullptr); + EXPECT_FALSE(res_baseline.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_baseline.value().const_opt.has_value()); + + // DefaultIfNull alone + omitted nullable fields: must match baseline (empty). + const auto res_null_only_omitted = + rfl::json::read(R"({"port": null})"); + ASSERT_TRUE(res_null_only_omitted.has_value()) + << res_null_only_omitted.error().what(); + EXPECT_EQ(res_null_only_omitted.value().port, 8080); + EXPECT_FALSE(res_null_only_omitted.value().opt_with_default.has_value()); + EXPECT_EQ(res_null_only_omitted.value().uptr, nullptr); + EXPECT_EQ(res_null_only_omitted.value().sptr, nullptr); + EXPECT_FALSE(res_null_only_omitted.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_null_only_omitted.value().const_opt.has_value()); + + // DefaultIfNull alone + explicit null: also empty. + const std::string explicit_null_json = R"({ + "port": null, + "opt_with_default": null, + "uptr": null, + "sptr": null, + "opt_renamed": null, + "const_opt": null + })"; + const auto res_null_only_explicit = + rfl::json::read(explicit_null_json); + ASSERT_TRUE(res_null_only_explicit.has_value()) + << res_null_only_explicit.error().what(); + EXPECT_EQ(res_null_only_explicit.value().port, 8080); + EXPECT_FALSE(res_null_only_explicit.value().opt_with_default.has_value()); + EXPECT_EQ(res_null_only_explicit.value().uptr, nullptr); + EXPECT_EQ(res_null_only_explicit.value().sptr, nullptr); + EXPECT_FALSE(res_null_only_explicit.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_null_only_explicit.value().const_opt.has_value()); + + // DefaultIfMissing + DefaultIfNull + omitted: preserves DMIs. + const auto res_combined_omitted = + rfl::json::read(R"({"port": null})"); + ASSERT_TRUE(res_combined_omitted.has_value()) + << res_combined_omitted.error().what(); + EXPECT_EQ(res_combined_omitted.value().port, 8080); + ASSERT_TRUE(res_combined_omitted.value().opt_with_default.has_value()); + EXPECT_EQ(*res_combined_omitted.value().opt_with_default, 5); + ASSERT_NE(res_combined_omitted.value().uptr, nullptr); + EXPECT_EQ(*res_combined_omitted.value().uptr, 7); + ASSERT_NE(res_combined_omitted.value().sptr, nullptr); + EXPECT_EQ(*res_combined_omitted.value().sptr, 9); + ASSERT_TRUE(res_combined_omitted.value().opt_renamed.value().has_value()); + EXPECT_EQ(*res_combined_omitted.value().opt_renamed.value(), 11); + ASSERT_TRUE(res_combined_omitted.value().const_opt.has_value()); + EXPECT_EQ(*res_combined_omitted.value().const_opt, 15); + + // DefaultIfMissing + DefaultIfNull + explicit null: resets to empty. + const auto res_combined_explicit = + rfl::json::read(explicit_null_json); + ASSERT_TRUE(res_combined_explicit.has_value()) + << res_combined_explicit.error().what(); + EXPECT_EQ(res_combined_explicit.value().port, 8080); + EXPECT_FALSE(res_combined_explicit.value().opt_with_default.has_value()); + EXPECT_EQ(res_combined_explicit.value().uptr, nullptr); + EXPECT_EQ(res_combined_explicit.value().sptr, nullptr); + EXPECT_FALSE(res_combined_explicit.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_combined_explicit.value().const_opt.has_value()); +} + +// DefaultVal, Rename, const fields, container DMIs, and field-level struct DMIs. +TEST(json, test_default_if_null_default_val_and_dmis) { + const std::string json_str = R"({ + "retries": null, + "mode": null, + "server_port": null, + "fixed_version": null, + "default_tags": null, + "custom_logging": null + })"; + + const auto res = + rfl::json::read(json_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& v = res.value(); + EXPECT_EQ(v.retries.value(), 3); + EXPECT_EQ(v.mode.value(), "fast"); + EXPECT_EQ(v.port.value(), 9090); + EXPECT_EQ(v.fixed_version, 2); + EXPECT_EQ(v.default_tags, (std::vector{"alpha", "beta"})); + EXPECT_EQ(v.custom_logging.level, "warn"); + EXPECT_FALSE(v.custom_logging.timestamps); +} + +// Missing required fields still fail when DefaultIfMissing is NOT passed, +// and succeed when combined with DefaultIfMissing (also with NoFieldNames). +TEST(json, test_default_if_null_missing_fields_vs_combined) { + const std::string partial_json = R"({"port": null, "tags": null})"; + + const auto res_only_null = + rfl::json::read(partial_json); + EXPECT_FALSE(res_only_null.has_value()); + + const auto res_combined = + rfl::json::read( + partial_json); + ASSERT_TRUE(res_combined.has_value()) << res_combined.error().what(); + EXPECT_EQ(res_combined.value().port, 8080); + EXPECT_EQ(res_combined.value().host, "localhost"); + EXPECT_TRUE(res_combined.value().tags.empty()); + EXPECT_EQ(res_combined.value().logging.level, "info"); + + // NoFieldNames + DefaultIfNull preserves DMIs for null elements. + struct Pair { + int port = 8080; + std::string host = "localhost"; + }; + const auto res_no_names = + rfl::json::read( + R"([null, "example.com"])"); + ASSERT_TRUE(res_no_names.has_value()) << res_no_names.error().what(); + EXPECT_EQ(res_no_names.value().port, 8080); + EXPECT_EQ(res_no_names.value().host, "example.com"); +} + +// Non-default-constructible structs and fields compile cleanly and fall back to +// normal error reporting when null cannot be default-constructed. +TEST(json, test_default_if_null_non_default_constructible) { + EXPECT_FALSE( + (rfl::json::read("null")).has_value()); + EXPECT_FALSE( + (rfl::json::read("null")) + .has_value()); + + const auto ok = rfl::json::read( + R"({"req": 42, "tags": null})"); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok.value().req.v, 42); + EXPECT_TRUE(ok.value().tags.empty()); + + const auto fail = rfl::json::read( + R"({"req": null, "tags": null})"); + EXPECT_FALSE(fail.has_value()); + + const auto with_dmi = + rfl::json::read(R"({"req": null, "port": null})"); + ASSERT_TRUE(with_dmi.has_value()) << with_dmi.error().what(); + EXPECT_EQ(with_dmi.value().req.v, 42); + EXPECT_EQ(with_dmi.value().port, 8080); +} + +// Validators whose default constructor throws return a clean error rather than +// terminating, while validators with a valid DMI succeed. +TEST(json, test_default_if_null_validators) { + const auto fail_standalone = + rfl::json::read("null"); + EXPECT_FALSE(fail_standalone.has_value()); + + const auto fail_struct = + rfl::json::read( + R"({"name": "svc", "tags": ["a"]})"); + ASSERT_FALSE(fail_struct.has_value()); + EXPECT_NE(fail_struct.error().what().find("rfl::DefaultIfNull"), + std::string::npos) + << fail_struct.error().what(); + + const auto ok_struct = + rfl::json::read( + R"({"name": null, "tags": null})"); + ASSERT_TRUE(ok_struct.has_value()) << ok_struct.error().what(); + EXPECT_EQ(ok_struct.value().name, "svc"); + EXPECT_EQ(ok_struct.value().tags.value(), + (std::vector{"default"})); +} + +// Format-generality: Generic reader, standalone containers, tuples, arrays, +// enums, bitsets, durations, and NamedTuples. +TEST(json, test_default_if_null_generic_and_standalone_types) { + // Format-general check via rfl::from_generic. + const auto from_null_generic = + rfl::from_generic(rfl::Generic{}); + ASSERT_TRUE(from_null_generic.has_value()) + << from_null_generic.error().what(); + EXPECT_EQ(from_null_generic.value().port, 8080); + EXPECT_EQ(from_null_generic.value().host, "localhost"); + EXPECT_EQ(from_null_generic.value().logging.level, "info"); + + EXPECT_EQ((rfl::json::read("null")).value(), 0); + EXPECT_EQ((rfl::json::read("null")).value(), + ""); + EXPECT_TRUE( + (rfl::json::read, rfl::DefaultIfNull>("null")) + .value() + .empty()); + EXPECT_TRUE( + (rfl::json::read, rfl::DefaultIfNull>("null")) + .value() + .empty()); + EXPECT_EQ((rfl::json::read("null")).value(), + Color::red); + EXPECT_EQ( + (rfl::json::read, rfl::DefaultIfNull>("null")).value(), + std::bitset<4>(0)); + EXPECT_EQ( + (rfl::json::read, rfl::DefaultIfNull>("null")).value(), + (std::array{0, 0})); + EXPECT_EQ( + (rfl::json::read, rfl::DefaultIfNull>( + "null")) + .value(), + (std::tuple{0, ""})); + EXPECT_EQ( + (rfl::json::read, rfl::DefaultIfNull>("null")) + .value(), + (std::pair{0, ""})); + EXPECT_EQ( + (rfl::json::read("null")) + .value(), + std::chrono::milliseconds(0)); + + using NT = + rfl::NamedTuple, rfl::Field<"b", std::string>>; + const auto nt = rfl::json::read("null"); + ASSERT_TRUE(nt.has_value()); + EXPECT_EQ(nt.value().get<"a">(), 0); + EXPECT_EQ(nt.value().get<"b">(), ""); +} + +// Regression test: wrappers around non-default-constructible types must report +// std::is_default_constructible_v == false and compile cleanly under +// DefaultIfNull even when reading structs that contain them. +TEST(json, test_default_if_null_wrapped_non_default_constructible) { + static_assert( + !std::is_default_constructible_v>); + static_assert( + !std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v< + rfl::Validator>); + static_assert( + !std::is_default_constructible_v>); + static_assert( + std::is_default_constructible_v>); + static_assert( + !std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert( + !rfl::internal::is_safe_default_constructible_v>); + static_assert( + !rfl::internal::is_safe_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v>); + static_assert(!std::is_default_constructible_v); + static_assert( + !rfl::internal::is_safe_default_constructible_v); + + const std::string valid_json = R"({ + "desc": 1, + "dep": 2, + "commented": 3, + "box": 4, + "ref": 5, + "attr": 6, + "validated": 7, + "variant": "hello", + "skipped_ser": 8, + "tags": null + })"; + const auto ok = + rfl::json::read(valid_json); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok.value().desc.value().v, 1); + EXPECT_EQ(ok.value().dep.value().v, 2); + EXPECT_EQ(ok.value().commented.value().v, 3); + EXPECT_EQ(ok.value().box->v, 4); + EXPECT_EQ(ok.value().ref->v, 5); + EXPECT_EQ(ok.value().attr.value().v, 6); + EXPECT_EQ(ok.value().validated.value().v, 7); + ASSERT_TRUE(rfl::holds_alternative(ok.value().variant)); + EXPECT_EQ(rfl::get(ok.value().variant).s, "hello"); + EXPECT_EQ(ok.value().skipped_ser.value().v, 8); + EXPECT_TRUE(ok.value().tags.empty()); + + // Null for non-default-constructible wrapped fields fails cleanly. + EXPECT_FALSE( + (rfl::json::read("null")) + .has_value()); + EXPECT_FALSE((rfl::json::read, rfl::DefaultIfNull>("null")) + .has_value()); + EXPECT_FALSE((rfl::json::read, rfl::DefaultIfNull>("null")) + .has_value()); + EXPECT_FALSE( + (rfl::json::read, rfl::DefaultIfNull>( + "null")) + .has_value()); +} + +// Variants containing a nullable alternative must decode explicit null as that +// nullable alternative (std::nullopt) rather than default-constructing the +// first alternative. +TEST(json, test_default_if_null_variants_with_nullable_alternative) { + using StdVar = std::variant>; + using RflVar = rfl::Variant>; + + const auto sv_null = rfl::json::read("null"); + ASSERT_TRUE(sv_null.has_value()) << sv_null.error().what(); + ASSERT_TRUE(std::holds_alternative>(sv_null.value())); + EXPECT_FALSE(std::get>(sv_null.value()).has_value()); + + const auto rv_null = rfl::json::read("null"); + ASSERT_TRUE(rv_null.has_value()) << rv_null.error().what(); + ASSERT_TRUE(rfl::holds_alternative>(rv_null.value())); + EXPECT_FALSE(rfl::get>(rv_null.value()).has_value()); + + // Non-null values still decode as the matching alternative. + const auto sv_int = rfl::json::read("42"); + ASSERT_TRUE(sv_int.has_value()) << sv_int.error().what(); + ASSERT_TRUE(std::holds_alternative(sv_int.value())); + EXPECT_EQ(std::get(sv_int.value()), 42); + + // Non-nullable variants still default-construct to the first alternative. + const auto plain_sv = + rfl::json::read, rfl::DefaultIfNull>( + "null"); + ASSERT_TRUE(plain_sv.has_value()) << plain_sv.error().what(); + ASSERT_TRUE(std::holds_alternative(plain_sv.value())); + EXPECT_EQ(std::get(plain_sv.value()), 0); + + const auto plain_rv = + rfl::json::read, rfl::DefaultIfNull>( + "null"); + ASSERT_TRUE(plain_rv.has_value()) << plain_rv.error().what(); + ASSERT_TRUE(rfl::holds_alternative(plain_rv.value())); + EXPECT_EQ(rfl::get(plain_rv.value()), 0); + + // Inside a struct with DMIs: nullable variants decode explicit null as + // std::nullopt, while non-nullable variants preserve their DMI. + const auto in_struct = + rfl::json::read(R"({ + "std_var": null, + "rfl_var": null, + "plain_std_var": null, + "plain_rfl_var": null + })"); + ASSERT_TRUE(in_struct.has_value()) << in_struct.error().what(); + ASSERT_TRUE(std::holds_alternative>( + in_struct.value().std_var)); + EXPECT_FALSE( + std::get>(in_struct.value().std_var) + .has_value()); + ASSERT_TRUE(rfl::holds_alternative>( + in_struct.value().rfl_var)); + EXPECT_FALSE( + rfl::get>(in_struct.value().rfl_var) + .has_value()); + ASSERT_TRUE(std::holds_alternative(in_struct.value().plain_std_var)); + EXPECT_EQ(std::get(in_struct.value().plain_std_var), 7); + ASSERT_TRUE(rfl::holds_alternative(in_struct.value().plain_rfl_var)); + EXPECT_EQ(rfl::get(in_struct.value().plain_rfl_var), 9); +} + +struct DT; +struct Leaf { + int x = 0; +}; +struct Node { + rfl::Box
lesser; +}; +struct DT { + std::variant v; +}; + +struct Tree { + struct Branch { + rfl::Box child; + }; + std::optional b; +}; + +struct DirectNode { + int v = 1; + rfl::Box next; +}; + +struct BoxAndRefOnlyNoDefault { + rfl::Box box; + rfl::Ref ref; +}; + +// Regression test: recursive structs with incomplete types in rfl::Box / +// rfl::Ref must remain valid for normal read/write AND DefaultIfNull, while +// cyclic Box/Ref graphs and Box/Ref must be rejected as +// unsafe to default-construct without stack overflow or compile errors. +TEST(json, test_default_if_null_recursive_and_cyclic_box_ref) { + static_assert(rfl::internal::is_safe_default_constructible_v
); + static_assert(rfl::internal::is_safe_default_constructible_v); + static_assert(!rfl::internal::is_safe_default_constructible_v); + static_assert( + !rfl::internal::is_safe_default_constructible_v>); + static_assert( + !rfl::internal::is_safe_default_constructible_v>); + static_assert( + !rfl::internal::is_safe_default_constructible_v); + + // 1. Recursive variant struct DT: normal write + read and DefaultIfNull read. + const DT dt_orig{Node{.lesser = rfl::make_box
(DT{Leaf{.x = 42}})}}; + const auto dt_json = rfl::json::write(dt_orig); + + const auto dt_normal = rfl::json::read
(dt_json); + ASSERT_TRUE(dt_normal.has_value()) << dt_normal.error().what(); + ASSERT_TRUE(std::holds_alternative(dt_normal.value().v)); + const auto& inner_dt = *std::get(dt_normal.value().v).lesser; + ASSERT_TRUE(std::holds_alternative(inner_dt.v)); + EXPECT_EQ(std::get(inner_dt.v).x, 42); + + const auto dt_with_flag = rfl::json::read(dt_json); + ASSERT_TRUE(dt_with_flag.has_value()) << dt_with_flag.error().what(); + ASSERT_TRUE(std::holds_alternative(dt_with_flag.value().v)); + const auto& inner_dt2 = *std::get(dt_with_flag.value().v).lesser; + ASSERT_TRUE(std::holds_alternative(inner_dt2.v)); + EXPECT_EQ(std::get(inner_dt2.v).x, 42); + + const auto dt_null = rfl::json::read("null"); + ASSERT_TRUE(dt_null.has_value()) << dt_null.error().what(); + ASSERT_TRUE(std::holds_alternative(dt_null.value().v)); + EXPECT_EQ(std::get(dt_null.value().v).x, 0); + + // 2. Recursive optional-wrapped Tree: normal write + read and DefaultIfNull. + const Tree tree_orig{ + .b = Tree::Branch{.child = rfl::make_box(Tree{.b = std::nullopt})}}; + const auto tree_json = rfl::json::write(tree_orig); + + const auto tree_normal = rfl::json::read(tree_json); + ASSERT_TRUE(tree_normal.has_value()) << tree_normal.error().what(); + ASSERT_TRUE(tree_normal.value().b.has_value()); + EXPECT_FALSE(tree_normal.value().b->child->b.has_value()); + + const auto tree_with_flag = + rfl::json::read(tree_json); + ASSERT_TRUE(tree_with_flag.has_value()) << tree_with_flag.error().what(); + ASSERT_TRUE(tree_with_flag.value().b.has_value()); + EXPECT_FALSE(tree_with_flag.value().b->child->b.has_value()); + + const auto tree_null = rfl::json::read("null"); + ASSERT_TRUE(tree_null.has_value()) << tree_null.error().what(); + EXPECT_FALSE(tree_null.value().b.has_value()); + + // 3. Cyclic DirectNode: must NOT stack-overflow on null. + const auto cyclic_null = + rfl::json::read("null"); + EXPECT_FALSE(cyclic_null.has_value()); + + const auto cyclic_field_null = + rfl::json::read( + R"({"v": 7, "next": null})"); + EXPECT_FALSE(cyclic_field_null.has_value()); + + // 4. Struct containing ONLY Box and Ref compiles + // cleanly with DefaultIfNull and handles both valid input and null cleanly. + const auto box_ref_ok = + rfl::json::read( + R"({"box": 10, "ref": 20})"); + ASSERT_TRUE(box_ref_ok.has_value()) << box_ref_ok.error().what(); + EXPECT_EQ(box_ref_ok.value().box->v, 10); + EXPECT_EQ(box_ref_ok.value().ref->v, 20); + + EXPECT_FALSE( + (rfl::json::read("null")) + .has_value()); + EXPECT_FALSE((rfl::json::read( + R"({"box": null, "ref": 20})")) + .has_value()); +} + +struct AggregateWithNoDefaultDmi { + NoDefault x = NoDefault(42); + int y = 7; +}; + +struct ThrowingNullableOpt { + using ReflectionType = std::optional; + static inline int live_count = 0; + static inline bool should_throw = false; + std::optional v = std::nullopt; + + ThrowingNullableOpt() { + if (should_throw) { + throw std::runtime_error("default ctor failed"); + } + ++live_count; + } + explicit ThrowingNullableOpt(std::optional _v) : v(_v) { ++live_count; } + ThrowingNullableOpt(const ThrowingNullableOpt& _o) : v(_o.v) { ++live_count; } + ThrowingNullableOpt(ThrowingNullableOpt&& _o) noexcept : v(_o.v) { + ++live_count; + } + ThrowingNullableOpt& operator=(const ThrowingNullableOpt&) = default; + ThrowingNullableOpt& operator=(ThrowingNullableOpt&&) noexcept = default; + ~ThrowingNullableOpt() { --live_count; } + + const std::optional& reflection() const { return v; } +}; + +struct ThrowingMoveNullableOpt { + using ReflectionType = std::optional; + static inline int live_count = 0; + std::optional v = std::nullopt; + + ThrowingMoveNullableOpt() noexcept(false) { ++live_count; } + explicit ThrowingMoveNullableOpt(std::optional _v) : v(_v) { + ++live_count; + } + ThrowingMoveNullableOpt(const ThrowingMoveNullableOpt& _o) : v(_o.v) { + ++live_count; + } + ThrowingMoveNullableOpt(ThrowingMoveNullableOpt&& _o) noexcept(false) + : v(_o.v) { + ++live_count; + } + ThrowingMoveNullableOpt& operator=(const ThrowingMoveNullableOpt&) = default; + ThrowingMoveNullableOpt& operator=(ThrowingMoveNullableOpt&&) = default; + ~ThrowingMoveNullableOpt() { --live_count; } + + const std::optional& reflection() const { return v; } +}; + +struct WithConstThrowingNullableOpt { + int keep = 1; + const ThrowingNullableOpt opt = ThrowingNullableOpt(5); +}; + +struct WithConstThrowingMoveNullableOpt { + int keep = 1; + const ThrowingMoveNullableOpt opt = ThrowingMoveNullableOpt(5); +}; + +struct WithRawPtrDefault { + static inline int sentinel = 123; + int keep = 7; + int* ptr = &sentinel; +}; + +TEST(json, test_default_if_null_aggregate_dmi_and_const_throw_safety) { + static_assert(!rfl::internal::is_safe_default_constructible_v); + static_assert(!rfl::internal::is_safe_default_constructible_v); + static_assert(!rfl::internal::is_safe_default_constructible_v); + static_assert( + rfl::internal::is_safe_default_constructible_v); + + const auto agg = + rfl::json::read( + R"({"x": null, "y": null})"); + ASSERT_TRUE(agg.has_value()) << agg.error().what(); + EXPECT_EQ(agg.value().x.v, 42); + EXPECT_EQ(agg.value().y, 7); + + // Omitted const nullable field resets cleanly from DMI (5) to default + // (std::nullopt) when default construction succeeds. + ThrowingNullableOpt::live_count = 0; + ThrowingNullableOpt::should_throw = false; + { + const auto ok = + rfl::json::read( + R"({"keep": 9})"); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok.value().keep, 9); + EXPECT_FALSE(ok.value().opt.v.has_value()); + } + EXPECT_EQ(ThrowingNullableOpt::live_count, 0); + + // If resetting an omitted const nullable field throws during default + // construction, the error is reported and the original live subobject + // remains intact (no double destruction when the struct unwinds). + ThrowingNullableOpt::live_count = 0; + ThrowingNullableOpt::should_throw = true; + { + const auto res = + rfl::json::read( + R"({"keep": 9})"); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("default ctor failed"), + std::string::npos) + << res.error().what(); + } + ThrowingNullableOpt::should_throw = false; + EXPECT_EQ(ThrowingNullableOpt::live_count, 0); + + // A const nullable field whose default and move constructors may both throw + // must not be destroyed before replacement; it returns an error cleanly and + // unwinds with balanced live_count. + ThrowingMoveNullableOpt::live_count = 0; + { + const auto res = + rfl::json::read( + R"({"keep": 9})"); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("cannot safely reset"), + std::string::npos) + << res.error().what(); + } + EXPECT_EQ(ThrowingMoveNullableOpt::live_count, 0); + + // Raw pointers under AllowRawPtrs + DefaultIfNull decode explicit null as + // nullptr (overriding a non-null DMI) while non-nullable fields keep their + // in-class default. + const auto raw_res = + rfl::json::read( + R"({"keep": null, "ptr": null})"); + ASSERT_TRUE(raw_res.has_value()) << raw_res.error().what(); + EXPECT_EQ(raw_res.value().keep, 7); + EXPECT_EQ(raw_res.value().ptr, nullptr); +} + +} // namespace test_default_if_null diff --git a/tests/yaml/test_default_if_null.cpp b/tests/yaml/test_default_if_null.cpp new file mode 100644 index 000000000..be1060df0 --- /dev/null +++ b/tests/yaml/test_default_if_null.cpp @@ -0,0 +1,490 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_default_if_null { + +using namespace std::string_view_literals; + +struct Logging { + std::string level = "info"; + bool timestamps = true; +}; + +struct Config { + int port = 8080; + std::string host = "localhost"; + std::vector tags; + std::map env; + std::unordered_map labels; + Logging logging; + std::map modules; +}; + +struct NoDefault { + using ReflectionType = int; + int v; + NoDefault() = delete; + explicit NoDefault(int _v) : v(_v) {} + int reflection() const { return v; } +}; + +struct NonDefaultParent { + NoDefault req; + std::vector tags; +}; + +struct DefaultConstructibleWithNonDefaultField { + NoDefault req = NoDefault(42); + int port = 8080; +}; + +struct WithNullableFields { + int port = 8080; + std::optional opt_empty; + std::optional opt_with_default = 5; + std::unique_ptr uptr = std::make_unique(7); + std::shared_ptr sptr = std::make_shared(9); + rfl::Rename<"opt_renamed", std::optional> opt_renamed = 11; + rfl::DefaultVal> opt_default_val = 13; + rfl::Generic generic_val = 99; +}; + +struct WithOptionalDmi { + int port = 8080; + std::optional opt_with_default = 5; + std::unique_ptr uptr = std::make_unique(7); + std::shared_ptr sptr = std::make_shared(9); + rfl::Rename<"opt_renamed", std::optional> opt_renamed = 11; + const std::optional const_opt = 15; +}; + +struct PositiveNoDefault { + static rfl::Result validate(NoDefault _v) { + if (_v.v <= 0) { + return rfl::error("Must be positive"); + } + return _v; + } +}; + +struct NoDefault2 { + using ReflectionType = std::string; + std::string s; + NoDefault2() = delete; + explicit NoDefault2(std::string _s) : s(std::move(_s)) {} + const std::string& reflection() const { return s; } +}; + +struct WrappedNoDefaultFields { + rfl::Description<"desc", NoDefault> desc; + rfl::Deprecated<"old", "dep", NoDefault> dep; + rfl::Commented commented; + rfl::Box box; + rfl::Ref ref; + rfl::Attribute attr; + rfl::Validator validated; + rfl::Variant variant; + rfl::SkipSerialization skipped_ser; + std::vector tags; +}; + +struct WithDefaultValAndRename { + rfl::DefaultVal retries = 3; + rfl::DefaultVal mode = "fast"; + rfl::Rename<"server_port", int> port = 9090; + const int fixed_version = 2; + std::vector default_tags = {"alpha", "beta"}; + Logging custom_logging = Logging{.level = "warn", .timestamps = false}; +}; + +struct Outer { + struct Inner { + int timeout = 30; + std::string endpoint = "http://localhost"; + }; + Inner inner; + std::vector sinks; +}; + +enum class LogFormat { text, json }; + +struct Extras { + LogFormat format = LogFormat::json; + std::array dims = {1, 2, 3}; + std::bitset<4> flags; + std::chrono::milliseconds timeout = std::chrono::milliseconds(500); +}; + +// Case 1: Empty YAML document -> default-constructed root struct. +TEST(yaml, test_default_if_null_empty_document) { + // Default behavior without DefaultIfNull still fails. + EXPECT_FALSE(rfl::yaml::read(""sv).has_value()); + + const auto res = rfl::yaml::read(""sv); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& cfg = res.value(); + EXPECT_EQ(cfg.port, 8080); + EXPECT_EQ(cfg.host, "localhost"); + EXPECT_TRUE(cfg.tags.empty()); + EXPECT_TRUE(cfg.env.empty()); + EXPECT_TRUE(cfg.labels.empty()); + EXPECT_EQ(cfg.logging.level, "info"); + EXPECT_TRUE(cfg.logging.timestamps); + EXPECT_TRUE(cfg.modules.empty()); +} + +// Case 2: All-commented YAML document -> default-constructed root struct. +TEST(yaml, test_default_if_null_comment_only_document) { + const std::string yaml_str = + "# just a comment\n" + "# another comment line\n"; + EXPECT_FALSE(rfl::yaml::read(yaml_str).has_value()); + + const auto res = rfl::yaml::read(yaml_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& cfg = res.value(); + EXPECT_EQ(cfg.port, 8080); + EXPECT_EQ(cfg.host, "localhost"); + EXPECT_TRUE(cfg.tags.empty()); + EXPECT_TRUE(cfg.env.empty()); + EXPECT_EQ(cfg.logging.level, "info"); +} + +// Cases 3, 4, 5, 6 + DMI preservation on struct fields. +TEST(yaml, test_default_if_null_all_cases_and_dmis) { + const std::string yaml_str = + "port: null\n" + "host:\n" + "tags:\n" + "env:\n" + "labels: ~\n" + "logging:\n" + "modules:\n" + " network:\n" + " storage:\n" + " level: debug\n" + " timestamps: false\n"; + + // Without DefaultIfNull, this fails. + EXPECT_FALSE(rfl::yaml::read(yaml_str).has_value()); + + const auto res = rfl::yaml::read(yaml_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& cfg = res.value(); + EXPECT_EQ(cfg.port, 8080); + EXPECT_EQ(cfg.host, "localhost"); + EXPECT_TRUE(cfg.tags.empty()); + EXPECT_TRUE(cfg.env.empty()); + EXPECT_TRUE(cfg.labels.empty()); + EXPECT_EQ(cfg.logging.level, "info"); + EXPECT_TRUE(cfg.logging.timestamps); + ASSERT_EQ(cfg.modules.size(), 2u); + EXPECT_EQ(cfg.modules.at("network").level, "info"); + EXPECT_TRUE(cfg.modules.at("network").timestamps); + EXPECT_EQ(cfg.modules.at("storage").level, "debug"); + EXPECT_FALSE(cfg.modules.at("storage").timestamps); +} + +// Case 6b: Null element inside std::vector and nested structs. +TEST(yaml, test_default_if_null_nested_and_vector_elements) { + const std::string yaml_str = + "inner:\n" + "sinks:\n" + " - null\n" + " - ~\n" + " - level: error\n" + " timestamps: false\n"; + + EXPECT_FALSE(rfl::yaml::read(yaml_str).has_value()); + + const auto res = rfl::yaml::read(yaml_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(res.value().inner.timeout, 30); + EXPECT_EQ(res.value().inner.endpoint, "http://localhost"); + ASSERT_EQ(res.value().sinks.size(), 3u); + EXPECT_EQ(res.value().sinks[0].level, "info"); + EXPECT_TRUE(res.value().sinks[0].timestamps); + EXPECT_EQ(res.value().sinks[1].level, "info"); + EXPECT_TRUE(res.value().sinks[1].timestamps); + EXPECT_EQ(res.value().sinks[2].level, "error"); + EXPECT_FALSE(res.value().sinks[2].timestamps); +} + +// Nullable types (optional, unique_ptr, shared_ptr, Generic) MUST still decode +// explicit null as std::nullopt / nullptr / Generic::Null even if they have +// non-null DMIs. +TEST(yaml, test_default_if_null_preserves_nullable_semantics) { + const std::string yaml_str = + "port: null\n" + "opt_empty: null\n" + "opt_with_default: null\n" + "uptr: ~\n" + "sptr:\n" + "opt_renamed: null\n" + "opt_default_val: null\n" + "generic_val: null\n"; + + const auto res = + rfl::yaml::read(yaml_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& v = res.value(); + EXPECT_EQ(v.port, 8080); + EXPECT_FALSE(v.opt_empty.has_value()); + EXPECT_FALSE(v.opt_with_default.has_value()); + EXPECT_EQ(v.uptr, nullptr); + EXPECT_EQ(v.sptr, nullptr); + EXPECT_FALSE(v.opt_renamed.value().has_value()); + EXPECT_FALSE(v.opt_default_val.value().has_value()); + EXPECT_TRUE(v.generic_val.is_null()); +} + +// Omitted optional with DMI: +// - DefaultIfNull alone resets omitted nullable fields to empty (matching +// default read without DefaultIfMissing), and explicit null also decodes to +// empty. +// - DefaultIfMissing + DefaultIfNull preserves the DMI when omitted, while +// explicit null clears it to empty. +TEST(yaml, test_default_if_null_optional_omitted_vs_null) { + const std::string yaml_omitted = "port: null\n"; + const std::string yaml_explicit_null = + "port: null\n" + "opt_with_default: null\n" + "uptr: ~\n" + "sptr:\n" + "opt_renamed: null\n" + "const_opt: null\n"; + + // DefaultIfNull alone + omitted: resets nullable fields to empty. + const auto res_null_only_omitted = + rfl::yaml::read(yaml_omitted); + ASSERT_TRUE(res_null_only_omitted.has_value()) + << res_null_only_omitted.error().what(); + EXPECT_EQ(res_null_only_omitted.value().port, 8080); + EXPECT_FALSE(res_null_only_omitted.value().opt_with_default.has_value()); + EXPECT_EQ(res_null_only_omitted.value().uptr, nullptr); + EXPECT_EQ(res_null_only_omitted.value().sptr, nullptr); + EXPECT_FALSE(res_null_only_omitted.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_null_only_omitted.value().const_opt.has_value()); + + // DefaultIfNull alone + explicit null: also empty. + const auto res_null_only_explicit = + rfl::yaml::read(yaml_explicit_null); + ASSERT_TRUE(res_null_only_explicit.has_value()) + << res_null_only_explicit.error().what(); + EXPECT_EQ(res_null_only_explicit.value().port, 8080); + EXPECT_FALSE(res_null_only_explicit.value().opt_with_default.has_value()); + EXPECT_EQ(res_null_only_explicit.value().uptr, nullptr); + EXPECT_EQ(res_null_only_explicit.value().sptr, nullptr); + EXPECT_FALSE(res_null_only_explicit.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_null_only_explicit.value().const_opt.has_value()); + + // DefaultIfMissing + DefaultIfNull + omitted: preserves DMIs. + const auto res_combined_omitted = + rfl::yaml::read(yaml_omitted); + ASSERT_TRUE(res_combined_omitted.has_value()) + << res_combined_omitted.error().what(); + EXPECT_EQ(res_combined_omitted.value().port, 8080); + ASSERT_TRUE(res_combined_omitted.value().opt_with_default.has_value()); + EXPECT_EQ(*res_combined_omitted.value().opt_with_default, 5); + ASSERT_NE(res_combined_omitted.value().uptr, nullptr); + EXPECT_EQ(*res_combined_omitted.value().uptr, 7); + ASSERT_NE(res_combined_omitted.value().sptr, nullptr); + EXPECT_EQ(*res_combined_omitted.value().sptr, 9); + ASSERT_TRUE(res_combined_omitted.value().opt_renamed.value().has_value()); + EXPECT_EQ(*res_combined_omitted.value().opt_renamed.value(), 11); + ASSERT_TRUE(res_combined_omitted.value().const_opt.has_value()); + EXPECT_EQ(*res_combined_omitted.value().const_opt, 15); + + // DefaultIfMissing + DefaultIfNull + explicit null: resets to empty. + const auto res_combined_explicit = + rfl::yaml::read(yaml_explicit_null); + ASSERT_TRUE(res_combined_explicit.has_value()) + << res_combined_explicit.error().what(); + EXPECT_EQ(res_combined_explicit.value().port, 8080); + EXPECT_FALSE(res_combined_explicit.value().opt_with_default.has_value()); + EXPECT_EQ(res_combined_explicit.value().uptr, nullptr); + EXPECT_EQ(res_combined_explicit.value().sptr, nullptr); + EXPECT_FALSE(res_combined_explicit.value().opt_renamed.value().has_value()); + EXPECT_FALSE(res_combined_explicit.value().const_opt.has_value()); +} + +// DefaultVal, Rename, const fields, container DMIs, and field-level struct DMIs. +TEST(yaml, test_default_if_null_default_val_and_dmis) { + const std::string yaml_str = + "retries: null\n" + "mode:\n" + "server_port: ~\n" + "fixed_version: null\n" + "default_tags: null\n" + "custom_logging:\n"; + + const auto res = + rfl::yaml::read(yaml_str); + ASSERT_TRUE(res.has_value()) << res.error().what(); + const auto& v = res.value(); + EXPECT_EQ(v.retries.value(), 3); + EXPECT_EQ(v.mode.value(), "fast"); + EXPECT_EQ(v.port.value(), 9090); + EXPECT_EQ(v.fixed_version, 2); + EXPECT_EQ(v.default_tags, (std::vector{"alpha", "beta"})); + EXPECT_EQ(v.custom_logging.level, "warn"); + EXPECT_FALSE(v.custom_logging.timestamps); +} + +// Missing required fields still fail when DefaultIfMissing is NOT passed, +// and succeed when combined with DefaultIfMissing. +TEST(yaml, test_default_if_null_missing_fields_vs_combined) { + const std::string partial_yaml = + "port: null\n" + "tags:\n"; + + // Without DefaultIfMissing, omitted non-optional fields must still fail. + const auto res_only_null = + rfl::yaml::read(partial_yaml); + EXPECT_FALSE(res_only_null.has_value()); + + // Combined DefaultIfMissing + DefaultIfNull succeeds for both missing and null. + const auto res_combined = + rfl::yaml::read( + partial_yaml); + ASSERT_TRUE(res_combined.has_value()) << res_combined.error().what(); + EXPECT_EQ(res_combined.value().port, 8080); + EXPECT_EQ(res_combined.value().host, "localhost"); + EXPECT_TRUE(res_combined.value().tags.empty()); + EXPECT_EQ(res_combined.value().logging.level, "info"); +} + +// Non-default-constructible structs and fields compile cleanly and fall back to +// normal error reporting when null cannot be default-constructed. +TEST(yaml, test_default_if_null_non_default_constructible) { + // Root null for non-default-constructible types fails cleanly. + EXPECT_FALSE( + (rfl::yaml::read(""sv)).has_value()); + EXPECT_FALSE((rfl::yaml::read(""sv)) + .has_value()); + + // Non-default-constructible parent with valid req and null tags succeeds. + const auto ok = rfl::yaml::read( + "req: 42\ntags:\n"sv); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok.value().req.v, 42); + EXPECT_TRUE(ok.value().tags.empty()); + + // Null for non-default-constructible field fails cleanly. + const auto fail = rfl::yaml::read( + "req: null\ntags:\n"sv); + EXPECT_FALSE(fail.has_value()); + + // Default-constructible struct with DMI on non-default-constructible field + // preserves its DMI on null. + const auto with_dmi = + rfl::yaml::read("req: null\nport: null\n"sv); + ASSERT_TRUE(with_dmi.has_value()) << with_dmi.error().what(); + EXPECT_EQ(with_dmi.value().req.v, 42); + EXPECT_EQ(with_dmi.value().port, 8080); +} + +// Standalone containers, enums, bitsets, durations, and NamedTuples. +TEST(yaml, test_default_if_null_standalone_types) { + const auto vec = + rfl::yaml::read, rfl::DefaultIfNull>(""sv); + ASSERT_TRUE(vec.has_value()); + EXPECT_TRUE(vec.value().empty()); + + const auto m = + rfl::yaml::read, rfl::DefaultIfNull>(""sv); + ASSERT_TRUE(m.has_value()); + EXPECT_TRUE(m.value().empty()); + + const auto extras = rfl::yaml::read( + "format: null\ndims: null\nflags: null\ntimeout: null\n"sv); + ASSERT_TRUE(extras.has_value()) << extras.error().what(); + EXPECT_EQ(extras.value().format, LogFormat::json); + EXPECT_EQ(extras.value().dims, (std::array{1, 2, 3})); + EXPECT_EQ(extras.value().flags, std::bitset<4>(0)); + EXPECT_EQ(extras.value().timeout, std::chrono::milliseconds(500)); + + const auto root_extras = rfl::yaml::read(""sv); + ASSERT_TRUE(root_extras.has_value()); + EXPECT_EQ(root_extras.value().format, LogFormat::json); + EXPECT_EQ(root_extras.value().timeout, std::chrono::milliseconds(500)); + + const auto standalone_enum = + rfl::yaml::read("null"sv); + ASSERT_TRUE(standalone_enum.has_value()); + EXPECT_EQ(standalone_enum.value(), LogFormat::text); + + const auto standalone_bitset = + rfl::yaml::read, rfl::DefaultIfNull>("null"sv); + ASSERT_TRUE(standalone_bitset.has_value()); + EXPECT_EQ(standalone_bitset.value(), std::bitset<4>(0)); + + using NT = + rfl::NamedTuple, rfl::Field<"b", std::string>>; + const auto nt = rfl::yaml::read(""sv); + ASSERT_TRUE(nt.has_value()); + EXPECT_EQ(nt.value().get<"a">(), 0); + EXPECT_EQ(nt.value().get<"b">(), ""); +} + +TEST(yaml, test_default_if_null_wrapped_non_default_and_nullable_variants) { + const std::string valid_yaml = + "desc: 1\n" + "dep: 2\n" + "commented: 3\n" + "box: 4\n" + "ref: 5\n" + "attr: 6\n" + "validated: 7\n" + "variant: hello\n" + "skipped_ser: 8\n" + "tags:\n"; + const auto ok = + rfl::yaml::read(valid_yaml); + ASSERT_TRUE(ok.has_value()) << ok.error().what(); + EXPECT_EQ(ok.value().desc.value().v, 1); + EXPECT_EQ(ok.value().dep.value().v, 2); + EXPECT_EQ(ok.value().commented.value().v, 3); + EXPECT_EQ(ok.value().box->v, 4); + EXPECT_EQ(ok.value().ref->v, 5); + EXPECT_EQ(ok.value().attr.value().v, 6); + EXPECT_EQ(ok.value().validated.value().v, 7); + ASSERT_TRUE(rfl::holds_alternative(ok.value().variant)); + EXPECT_EQ(rfl::get(ok.value().variant).s, "hello"); + EXPECT_EQ(ok.value().skipped_ser.value().v, 8); + EXPECT_TRUE(ok.value().tags.empty()); + + using StdVar = std::variant>; + using RflVar = rfl::Variant>; + + const auto sv_null = rfl::yaml::read("null"sv); + ASSERT_TRUE(sv_null.has_value()) << sv_null.error().what(); + ASSERT_TRUE( + std::holds_alternative>(sv_null.value())); + EXPECT_FALSE( + std::get>(sv_null.value()).has_value()); + + const auto rv_null = rfl::yaml::read(""sv); + ASSERT_TRUE(rv_null.has_value()) << rv_null.error().what(); + ASSERT_TRUE( + rfl::holds_alternative>(rv_null.value())); + EXPECT_FALSE( + rfl::get>(rv_null.value()).has_value()); +} + +} // namespace test_default_if_null