diff --git a/docs/content/default_val.md b/docs/content/default_val.md index 817860bb4..dc0b7dd68 100644 --- a/docs/content/default_val.md +++ b/docs/content/default_val.md @@ -52,6 +52,8 @@ const auto homer = rfl::json::read(R"(["Homer"])").va // homer.town == "" ``` +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description`, `rfl::Deprecated` or `rfl::Rename`, in any order, works like a bare one: a field `rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4;` may be omitted and is then 4. + ## All fields need a valid default value A struct that contains an `rfl::DefaultVal` is default-constructed before it is read. The fields found in the input are then written into it. This means that every field of the struct needs a valid default value, even a required field that is in the input. @@ -88,7 +90,9 @@ The field is still required. If `favorite_foods` is missing in the input, you ge The same restriction applies to every struct that is read with the `rfl::DefaultIfMissing` processor, whether it contains an `rfl::DefaultVal` or not. -An `rfl::NamedTuple` has no in-class initializers. A missing `rfl::DefaultVal` field in it is set to `T{}`. If `T` has no default constructor, or `T{}` throws (for instance a validator that rejects its zero value), the field must be present in the input. +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` gets its default only if the struct can be default-constructed. If all its `rfl::DefaultVal` fields are wrapped and the struct cannot be default-constructed, because a field's type has no default constructor or the default constructor throws, the struct is read without its default values, so those fields must be present in the input. With a bare `rfl::DefaultVal`, such a struct does not compile, or you get the error above. + +An `rfl::NamedTuple` has no in-class initializers. A missing bare `rfl::DefaultVal` field in it is set to `T{}`. If `T` has no default constructor, or `T{}` throws (for instance a validator that rejects its zero value), the field must be present in the input. An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` must always be present in an `rfl::NamedTuple`. ## When to use diff --git a/docs/content/json_schema.md b/docs/content/json_schema.md index ad97d630b..b1a5edc69 100644 --- a/docs/content/json_schema.md +++ b/docs/content/json_schema.md @@ -244,3 +244,76 @@ const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); ``` `rfl::Deprecated` behaves like a thin wrapper around the underlying type, just like `rfl::Description`. You can access the underlying value using `.get()`, `.value()`, `operator()()`, `operator*()`, `operator->()`, or the assignment operator. + +## Default values with `rfl::DefaultIfMissing` + +When you generate a schema with the `rfl::DefaultIfMissing` processor, all fields are omitted from `"required"` and—whenever the struct is default-constructible—each field's default value from `T{}` is emitted as a JSON Schema `"default"` annotation: + +```cpp +struct Config { + int port = 8080; + std::string host = "localhost"; + bool verbose = true; + std::optional tls_cert; + std::optional timeout = 30; +}; + +const std::string json_schema = + rfl::json::to_schema(rfl::json::pretty); +``` + +This produces: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/Config", + "$defs": { + "Config": { + "type": "object", + "properties": { + "port": { + "type": "integer", + "default": 8080 + }, + "host": { + "type": "string", + "default": "localhost" + }, + "verbose": { + "default": true, + "type": "boolean" + }, + "tls_cert": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "timeout": { + "default": 30, + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ] + } + }, + "required": [] + } + } +} +``` + +A few details to keep in mind: + +- Empty nullable fields (`std::optional`, `std::shared_ptr`, `std::unique_ptr` initialized to `std::nullopt` / `nullptr`) do not emit `"default": null`; initialized ones (like `timeout = 30`) emit their default value. +- If a struct is not default-constructible, or if default-constructing it throws an exception (for example, an uninitialized `rfl::Validator` field whose zero value is invalid), schema generation still succeeds and simply omits `"default"` annotations for that struct. +- Without `rfl::DefaultIfMissing`, plain fields do not emit `"default"` annotations (use `rfl::DefaultVal` for per-field defaults). diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 00b4002cc..4634eb834 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -195,6 +195,11 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +The type inside `rfl::Short`, `rfl::Positional` or `rfl::Description` can be +a `std::optional` or an `rfl::DefaultVal`, so the argument may be omitted: +with `rfl::Short<"o", rfl::DefaultVal> output_dir = "out";`, +leaving out `-o` gives `"out"`. + ## Supported types | Type | CLI format | Notes | 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/DefaultVal.hpp b/include/rfl/DefaultVal.hpp index d3c2edc4d..0cb34c423 100644 --- a/include/rfl/DefaultVal.hpp +++ b/include/rfl/DefaultVal.hpp @@ -19,6 +19,8 @@ struct DefaultVal { using Type = std::remove_cvref_t; /// Default constructor - initializes with default-constructed value. + template + requires std::is_default_constructible_v DefaultVal() : value_(Type()) {} /// Constructs from a const reference to the value. 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..a7cfd3b33 100644 --- a/include/rfl/Rename.hpp +++ b/include/rfl/Rename.hpp @@ -29,6 +29,8 @@ struct Rename { using Name = rfl::Literal<_name>; /// Default constructor - creates a Rename with a default-constructed value. + template + requires std::is_default_constructible_v Rename() : value_(Type()) {} /// Constructs from a const reference to the value. diff --git a/include/rfl/Tuple.hpp b/include/rfl/Tuple.hpp index ee12e54c2..d49a1c031 100644 --- a/include/rfl/Tuple.hpp +++ b/include/rfl/Tuple.hpp @@ -49,7 +49,9 @@ class Tuple { /// Default constructor. Initializes each element with its default /// constructor. - Tuple() : Tuple(Types()...) {} + Tuple() + requires(std::is_default_constructible_v && ...) + : Tuple(Types()...) {} /// Copy constructor. Copies all elements from another Tuple. /// @param _other The Tuple to copy from. 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..b746bb796 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -47,8 +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()); } 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/has_default_val_v.hpp b/include/rfl/internal/has_default_val_v.hpp index 1d19ef96b..5473d0d7a 100644 --- a/include/rfl/internal/has_default_val_v.hpp +++ b/include/rfl/internal/has_default_val_v.hpp @@ -10,36 +10,49 @@ namespace rfl::internal { -template +/// With _unwrapped_only, only counts fields for which +/// is_unwrapped_default_val_v is true. +template struct HasDefaultVal; -template +template struct HasDefaultVal { static constexpr bool value = false; }; -template -struct HasDefaultVal> { - static constexpr bool value = - (false || ... || - is_default_val_v< - std::remove_cvref_t>>); +template +struct HasDefaultVal, _unwrapped_only> { + template >> + static constexpr bool is_default_val_field = + _unwrapped_only ? is_unwrapped_default_val_v : is_default_val_v; + + static constexpr bool value = (false || ... || is_default_val_field); }; -template +template requires(std::is_class_v && std::is_aggregate_v) -struct HasDefaultVal : HasDefaultVal> {}; +struct HasDefaultVal + : HasDefaultVal, _unwrapped_only> {}; -template -struct HasDefaultVal> : HasDefaultVal> { -}; +template +struct HasDefaultVal, _unwrapped_only> + : HasDefaultVal, _unwrapped_only> {}; -template -struct HasDefaultVal : HasDefaultVal> {}; +template +struct HasDefaultVal + : HasDefaultVal, _unwrapped_only> {}; template constexpr bool has_default_val_v = HasDefaultVal>::value; +/// Whether T has an rfl::DefaultVal field that is not inside rfl::Short, +/// rfl::Positional, rfl::Description or rfl::Deprecated. +template +constexpr bool has_unwrapped_default_val_v = + HasDefaultVal, true>::value; + } // namespace rfl::internal #endif diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 01189f634..1566e1575 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -5,7 +5,11 @@ #include #include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.hpp" +#include "../Positional.hpp" #include "../Rename.hpp" +#include "../Short.hpp" #include "StringLiteral.hpp" namespace rfl::internal { @@ -19,14 +23,50 @@ class is_default_val : public std::false_type {}; template class is_default_val> : public std::true_type {}; -template -class is_default_val>> : public std::true_type { -}; +// The wrappers below do not change how a field is read, so a DefaultVal +// inside them, in any order, still provides the field's default value. + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; template constexpr bool is_default_val_v = is_default_val>>::value; +/// Whether T is an rfl::DefaultVal itself or inside rfl::Rename, but not +/// inside rfl::Short, rfl::Positional, rfl::Description or rfl::Deprecated. +template +class is_unwrapped_default_val : public std::false_type {}; + +template +class is_unwrapped_default_val> : public std::true_type {}; + +template +class is_unwrapped_default_val> + : public is_unwrapped_default_val> {}; + +template +constexpr bool is_unwrapped_default_val_v = is_unwrapped_default_val< + std::remove_cvref_t>>::value; + /// Returns the DefaultVal inside a field for which is_default_val_v is true. template const DefaultVal& get_default_val(const DefaultVal& _field) noexcept { 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/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..19d8948f7 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -2,26 +2,68 @@ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #include +#include +#include #include +#include +#include #include +#include +#include +#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 "../Literal.hpp" #include "../NamedTuple.hpp" +#include "../Object.hpp" +#include "../Positional.hpp" +#include "../Processors.hpp" +#include "../Ref.hpp" +#include "../Rename.hpp" #include "../Result.hpp" +#include "../Short.hpp" +#include "../TaggedUnion.hpp" +#include "../Tuple.hpp" +#include "../Validator.hpp" +#include "../Variant.hpp" +#include "../internal/Array.hpp" +#include "../internal/Skip.hpp" #include "../internal/always_inline.hpp" #include "../internal/default_if_missing_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/has_reflector.hpp" #include "../internal/is_attribute.hpp" +#include "../internal/is_basic_type.hpp" #include "../internal/is_default_val_v.hpp" #include "../internal/is_extra_fields.hpp" #include "../internal/is_skip.hpp" #include "../internal/no_extra_fields_v.hpp" #include "../internal/nth_element_t.hpp" #include "../internal/ptr_cast.hpp" +#include "../named_tuple_t.hpp" #include "../num_fields.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" @@ -58,26 +100,519 @@ concept IsReflectionTypeWrapper = has_reflection_type_v && !has_reflection_method_v && std::is_aggregate_v && num_fields == 1; +/// Visited type list used to break cycles in recursive types when evaluating +/// `can_write_generic`. +template +struct CanWriteVisited {}; + +template +struct is_in_visited : std::false_type {}; + +template +struct is_in_visited> + : std::bool_constant<(std::is_same_v || ...)> {}; + +template +struct add_visited; + +template +struct add_visited> { + using type = CanWriteVisited; +}; + +template +concept HasValueTypeRange = std::is_class_v && requires(const T& _t) { + typename T::value_type; + _t.begin(); + _t.end(); +}; + +template +concept HasMappedType = + std::is_class_v && requires { typename T::mapped_type; }; + +template > +struct can_write_generic_impl; + +template > +struct can_write_generic_checked { + using U = std::remove_cvref_t; + static constexpr bool value = + std::conditional_t::value, std::true_type, + can_write_generic_impl>::value; +}; + +template > +inline constexpr bool can_write_generic_v = + can_write_generic_checked::value; + +/// Trait for whether the generic writer can serialize `T`, i.e. whether a +/// schema `default` can be produced for it. Wrappers, containers, tuples, +/// variants, and reflected aggregate structs are inspected recursively with +/// cycle protection. Types that can only be constructed from `ReflectionType` +/// (or only have a read `Reflector`) cannot be written back to `Generic`. +template +struct can_write_generic_impl { + using U = std::remove_cvref_t; + using NextVisited = typename add_visited::type; + + static consteval bool eval() { + if constexpr (std::is_void_v) { + return false; + } else if constexpr (is_basic_type_v || std::is_enum_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) { + return true; + } else if constexpr (has_read_reflector && !has_write_reflector) { + return false; + } else if constexpr (has_write_reflector) { + return can_write_generic_v::ReflType, NextVisited>; + } else if constexpr (has_reflection_type_v) { + if constexpr (has_reflection_method_v || IsReflectionTypeWrapper) { + return can_write_generic_v; + } else { + return false; + } + } else if constexpr (HasValueTypeRange) { + if constexpr (HasMappedType) { + return can_write_generic_v && + can_write_generic_v; + } else { + return can_write_generic_v; + } + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + return can_write_generic_v, NextVisited>; + } else { + return true; + } + } + + static constexpr bool value = eval(); +}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v, Visited>::type>> { +}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> : std::true_type {}; + +template +struct can_write_generic_impl< + Skip, Visited> + : std::bool_constant< + _skip_serialization || + can_write_generic_v< + T, typename add_visited< + Skip, + Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + typename FieldTypes::Type, + typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl : std::true_type {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> { +}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl : std::true_type {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant, + typename add_visited, Visited>::type>> {}; + +template +struct can_write_generic_impl + : std::bool_constant< + can_write_generic_v::type>> {}; + +template +struct can_write_generic_impl + : std::bool_constant< + can_write_generic_v::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v< + T1, typename add_visited, Visited>::type> && + can_write_generic_v< + T2, typename add_visited, Visited>::type>> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, Visited>::type> && + ...)> {}; + +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + (can_write_generic_v< + Ts, typename add_visited, + Visited>::type> && + ...)> {}; + +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L +template +struct can_write_generic_impl, Visited> + : std::bool_constant< + can_write_generic_v< + T, typename add_visited, Visited>::type> && + can_write_generic_v< + E, typename add_visited, Visited>::type>> {}; +#endif + +template +struct can_write_generic : std::bool_constant> {}; + /// Satisfied when the generic writer can serialize `T`, i.e. when a schema /// `default` can be produced for it. Every type is writable, except those that /// can be constructed from `ReflectionType`, but not converted back to it. template -concept CanWriteGeneric = - !has_reflection_type_v> || - has_reflection_method_v> || - IsReflectionTypeWrapper>; +concept CanWriteGeneric = can_write_generic>::value; /// Satisfied when a schema `default` can be emitted for the field type `T`: -/// it must be a `DefaultVal` that satisfies `CanWriteGeneric`. +/// it must contain a `DefaultVal` (see `is_default_val_v`) whose value +/// satisfies `CanWriteGeneric`. template concept CanEmitDefault = - is_default_val_v && CanWriteGeneric; + is_default_val_v && CanWriteGeneric::Type>; } // namespace internal } // namespace rfl namespace rfl::parsing { +template +struct call_to_generic { + template + static Generic apply(const T& _val) { + return rfl::to_generic(_val); + } +}; + +template +struct call_to_generic> { + template + static Generic apply(const T& _val) { + return rfl::to_generic(_val); + } +}; + +template +struct is_std_optional_for_default : std::false_type {}; + +template +struct is_std_optional_for_default> : std::true_type {}; + +template +struct is_transparent_default_wrapper : std::false_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> + : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +template +struct is_transparent_default_wrapper> : std::true_type {}; + +/// Unwraps metadata/CLI wrappers before serializing a field's default value to +/// `rfl::Generic` so `to_generic` is only instantiated on the underlying value +/// type (never per-field `Description, T>`). +template +constexpr const auto& unwrap_default_value(const T& _val) noexcept { + using U = std::remove_cvref_t; + if constexpr (is_transparent_default_wrapper::value) { + return unwrap_default_value(_val.value()); + } else { + return _val; + } +} + +template +constexpr bool is_plain_integer_for_default_v = + std::is_integral_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v; + +/// Fast-path conversion of a default field value to `rfl::Generic` for schema +/// emission. Peels metadata wrappers, constructs `rfl::Generic` directly for +/// common scalars/containers, and unpacks `Processors` so +/// `rfl::to_generic` never double-wraps `ProcessorsType`. +template +inline Generic to_default_generic(const U& _val) { + const auto& raw = unwrap_default_value(_val); + using T = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return Generic(raw); + } else if constexpr (is_plain_integer_for_default_v) { + if constexpr (std::is_unsigned_v && sizeof(T) >= sizeof(int64_t)) { + if (raw <= static_cast(std::numeric_limits::max())) { + return Generic(static_cast(raw)); + } + return call_to_generic::apply(raw); + } else { + return Generic(static_cast(raw)); + } + } else if constexpr (std::is_floating_point_v) { + return Generic(static_cast(raw)); + } else if constexpr (std::is_same_v) { + return Generic(raw); + } else if constexpr (std::is_same_v>) { + Generic::Array arr; + arr.reserve(raw.size()); + for (const auto& s : raw) { + arr.emplace_back(s); + } + return Generic(std::move(arr)); + } else if constexpr (is_std_optional_for_default::value) { + if (raw.has_value()) { + return to_default_generic(*raw); + } + return Generic(); + } else { + return call_to_generic::apply(raw); + } +} + +/// Sets the default value of the DefaultVal node in `_schema`. Rename, Short +/// and Positional leave no node in the schema, but Description and +/// Deprecated wrap the DefaultVal node in one of their own. +inline void set_schema_default_value(Generic _default, schema::Type* _schema) { + _schema->variant_.visit([&](auto& _s) { + using S = std::remove_cvref_t; + if constexpr (std::is_same_v) { + _s.default_value_ = std::move(_default); + } else if constexpr (std::is_same_v || + std::is_same_v) { + set_schema_default_value(std::move(_default), &*_s.type_); + } + }); +} + +/// Free per-field schema helper parameterized only by the individual field's +/// type (never by `View` or the enclosing struct's `FieldTypes...`). +template +void build_named_tuple_field_schema( + const std::string_view _name, + std::map* _definitions, SchemaType* _schema, + const FieldValPtrT _field_val) noexcept { + if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { + auto s = Parser::to_schema(_definitions); + if constexpr (!std::is_same_v) { + if (_field_val != nullptr) { + if constexpr (internal::is_default_val_v) { + if constexpr (internal::CanEmitDefault) { + try { + set_schema_default_value( + to_default_generic( + internal::get_default_val(*_field_val).value()), + &s); + } catch (...) { + } + } + } else if constexpr (internal::default_if_missing_v && + internal::CanWriteGeneric) { + try { + bool skip_default = false; + if constexpr (std::is_pointer_v) { + skip_default = (*_field_val == nullptr); + } else if constexpr (!is_required()) { + skip_default = is_empty(*_field_val); + } + if (!skip_default) { + auto default_val = + to_default_generic(*_field_val); + s = schema::Type{schema::Type::DefaultVal{ + .type_ = Ref::make(std::move(s)), + .default_value_ = std::move(default_val)}}; + } + } catch (...) { + } + } + } + } + if constexpr (_no_field_names) { + _schema->types_.emplace_back(std::move(s)); + } else { + _schema->types_[std::string(_name)] = std::move(s); + } + } +} + +template +RFL_ALWAYS_INLINE auto extract_schema_field_ptr(const SlotT& _slot) noexcept { + if constexpr (std::is_pointer_v) { + return static_cast*>(_slot); + } else { + return &_slot; + } +} + template requires AreReaderAndWriter> @@ -151,9 +686,10 @@ struct NamedTupleParser { * @param _var The input variable to read from. * @param _view The view to read into. * @param _value_initialize_default_vals Whether a missing rfl::DefaultVal - * field is value-initialized. Otherwise it is required, because - * the default value in the struct's in-class initializer is not - * available. + * field that is not inside rfl::Short, rfl::Positional, + * rfl::Description or rfl::Deprecated is value-initialized. + * Otherwise it is required, because the default value in the + * struct's in-class initializer is not available. * @return A pair containing a boolean array indicating which fields were * found and an optional error. */ @@ -290,23 +826,18 @@ struct NamedTupleParser { View* _view) noexcept { using F = internal::nth_element_t<_i, FieldTypes...>; using U = std::remove_cvref_t; - if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { - // Add default value here - auto s = Parser::to_schema(_definitions); - if constexpr (!std::is_same_v && internal::CanEmitDefault) { - s.variant_.visit([&](auto& value) { - if constexpr (std::is_same_v, - schema::Type::DefaultVal>) { - value.default_value_ = - rfl::to_generic((*rfl::get<_i>(*_view)).get()); - } - }); - } - if constexpr (_no_field_names) { - _schema->types_.emplace_back(std::move(s)); - } else { - _schema->types_[std::string(F::name())] = std::move(s); - } + if constexpr (std::is_same_v) { + build_named_tuple_field_schema( + F::name(), _definitions, _schema, static_cast(nullptr)); + } else { + const auto field_ptr = + _view != nullptr + ? extract_schema_field_ptr(rfl::get<_i>(*_view)) + : static_cast< + decltype(extract_schema_field_ptr(rfl::get<_i>(*_view)))>( + nullptr); + build_named_tuple_field_schema( + F::name(), _definitions, _schema, field_ptr); } }; @@ -363,7 +894,7 @@ struct NamedTupleParser { // available, so the field is required. const bool defaults_constructed = _set == nullptr; - if constexpr (is_default_val_field) { + if constexpr (internal::is_unwrapped_default_val_v) { if constexpr (can_value_initialize_default_val()) { if (_value_initialize_default_vals && !defaults_constructed) { // The value's constructor can throw, for instance a Validator diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index 2daf57608..d4215e225 100644 --- a/include/rfl/parsing/ParserBox.hpp +++ b/include/rfl/parsing/ParserBox.hpp @@ -44,7 +44,7 @@ struct ParserBox { if constexpr (atomic::is_atomic_v) { using RemoveAtomicT = atomic::remove_atomic_t; - static_assert(!internal::has_default_val_v, + static_assert(!internal::has_unwrapped_default_val_v, "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); diff --git a/include/rfl/parsing/ParserRef.hpp b/include/rfl/parsing/ParserRef.hpp index 4b5e8152d..e12b67ed4 100644 --- a/include/rfl/parsing/ParserRef.hpp +++ b/include/rfl/parsing/ParserRef.hpp @@ -43,7 +43,7 @@ struct ParserRef { if constexpr (atomic::is_atomic_v) { using RemoveAtomicT = atomic::remove_atomic_t; - static_assert(!internal::has_default_val_v, + static_assert(!internal::has_unwrapped_default_val_v, "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); diff --git a/include/rfl/parsing/ParserSharedPtr.hpp b/include/rfl/parsing/ParserSharedPtr.hpp index 50acf14d0..82a345fc4 100644 --- a/include/rfl/parsing/ParserSharedPtr.hpp +++ b/include/rfl/parsing/ParserSharedPtr.hpp @@ -49,7 +49,7 @@ struct ParserSharedPtr { if constexpr (atomic::is_atomic_v) { using RemoveAtomicT = std::shared_ptr>; - static_assert(!internal::has_default_val_v, + static_assert(!internal::has_unwrapped_default_val_v, "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); diff --git a/include/rfl/parsing/ParserUniquePtr.hpp b/include/rfl/parsing/ParserUniquePtr.hpp index 8eed47a91..99ce7bfc8 100644 --- a/include/rfl/parsing/ParserUniquePtr.hpp +++ b/include/rfl/parsing/ParserUniquePtr.hpp @@ -49,7 +49,7 @@ struct ParserUniquePtr { if constexpr (atomic::is_atomic_v) { using RemoveAtomicT = std::unique_ptr>; - static_assert(!internal::has_default_val_v, + static_assert(!internal::has_unwrapped_default_val_v, "Atomic types cannot be mixed with rfl::DefaultVal"); static_assert(!internal::default_if_missing_v, "Atomic types cannot be mixed with rfl::DefaultIfMissing"); diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..622d15692 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -19,6 +19,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" @@ -268,7 +269,13 @@ struct Parser { .and_then(wrap_in_t); } else if constexpr (internal::default_if_missing_v || - internal::has_default_val_v) { + internal::has_unwrapped_default_val_v || + (internal::has_default_val_v && + internal::is_safe_default_constructible_v)) { + // A DefaultVal inside rfl::Short, rfl::Positional, rfl::Description + // or rfl::Deprecated is filled in only if T can be safely + // default-constructed. Otherwise T is read like a struct without + // DefaultVal fields, and those fields are required. return read_struct_with_default(_r, _var); } else { @@ -665,22 +672,35 @@ struct Parser { } else { using NamedTupleType = internal::processed_t; - // The schema takes the default values of rfl::DefaultVal fields from - // a default-constructed instance. A tagged union wrapper holds its - // alternative through a pointer that U{} leaves null, so we construct - // the wrapper that holds the alternative by value instead. + // The schema takes the default values of rfl::DefaultVal fields (and + // all fields under rfl::DefaultIfMissing) from a default-constructed + // instance. A tagged union wrapper holds its alternative through a + // pointer that U{} leaves null, so we construct the wrapper that holds + // the alternative by value instead. using DefaultsType = tagged_union_wrapper_no_ptr_t; - if constexpr (internal::has_default_val_v) { + if constexpr (internal::has_unwrapped_default_val_v) { static_assert(requires { DefaultsType{}; }, "A struct with rfl::DefaultVal fields must be " "default-constructible, because the default values " "come from a default-constructed instance."); - auto defaults = DefaultsType{}; - auto view = ProcessorsType::template process( - to_view(defaults)); - (*_definitions)[name] = - Parser::to_schema( - _definitions, &view); + } + if constexpr (internal::has_unwrapped_default_val_v || + ((internal::has_default_val_v || + internal::default_if_missing_v) && + internal::is_safe_default_constructible_v< + DefaultsType>)) { + try { + auto defaults = DefaultsType{}; + auto view = ProcessorsType::template process( + to_view(defaults)); + (*_definitions)[name] = + Parser::to_schema( + _definitions, &view); + } catch (...) { + (*_definitions)[name] = + Parser::to_schema( + _definitions); + } } else { (*_definitions)[name] = Parser::to_schema( @@ -732,7 +752,8 @@ struct Parser { /// so we only use it when the DefaultIfMissing preprocessor is added. static Result read_struct_with_default(const R& _r, const InputVarType& _var) { - static_assert(!internal::has_default_val_v || requires { T{}; }, + static_assert(!internal::has_unwrapped_default_val_v || + requires { T{}; }, "A struct with rfl::DefaultVal fields must be " "default-constructible, because the default values come " "from a default-constructed instance."); @@ -754,7 +775,15 @@ struct Parser { return error(e.what()); } } catch (std::exception& e) { - return error(default_construction_error(e.what())); + if constexpr (!internal::default_if_missing_v && + !internal::has_unwrapped_default_val_v) { + // Its only rfl::DefaultVal fields are inside rfl::Short, + // rfl::Positional, rfl::Description or rfl::Deprecated. Read it like + // a struct without DefaultVal fields, with those fields required. + return read_struct(_r, _var); + } else { + return error(default_construction_error(e.what())); + } } } @@ -762,7 +791,7 @@ 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 + const std::string reason = internal::has_unwrapped_default_val_v ? "it contains rfl::DefaultVal" : "it is read with rfl::DefaultIfMissing"; return Error( diff --git a/tests/cli/test_optional_short_and_positional.cpp b/tests/cli/test_optional_short_and_positional.cpp index 43396c2f7..94caa2dba 100644 --- a/tests/cli/test_optional_short_and_positional.cpp +++ b/tests/cli/test_optional_short_and_positional.cpp @@ -42,4 +42,50 @@ TEST(cli, test_optional_positional_and_short_omitted) { EXPECT_EQ(rfl::json::write(result.value()), R"({"verbose":true})"); } +struct ConfigWithDefaults { + rfl::Positional> input = std::string("in.txt"); + rfl::Short<"o", rfl::DefaultVal> output = std::string("out.csv"); + rfl::Short<"j", rfl::Description<"Worker threads", rfl::DefaultVal>> + jobs = 4; +}; + +TEST(cli, test_short_default_val_given) { + const char* args[] = { + "program", + "data.csv", + "-o", "x.csv", + "-j", "8" + }; + const auto result = + rfl::cli::read(6, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input().value(), "data.csv"); + EXPECT_EQ(result.value().output().value(), "x.csv"); + EXPECT_EQ(result.value().jobs().value().value(), 8); +} + +TEST(cli, test_short_default_val_given_by_long_name) { + const char* args[] = { + "program", + "--output=x.csv", + "--jobs=8" + }; + const auto result = + rfl::cli::read(3, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input().value(), "in.txt"); + EXPECT_EQ(result.value().output().value(), "x.csv"); + EXPECT_EQ(result.value().jobs().value().value(), 8); +} + +TEST(cli, test_short_and_positional_default_val_omitted) { + const char* args[] = {"program"}; + const auto result = + rfl::cli::read(1, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input().value(), "in.txt"); + EXPECT_EQ(result.value().output().value(), "out.csv"); + EXPECT_EQ(result.value().jobs().value().value(), 4); +} + } // namespace test_optional_short_and_positional diff --git a/tests/generic/test_wrapped_optionals_and_defaults.cpp b/tests/generic/test_wrapped_optionals_and_defaults.cpp index fdd9162ca..231a52b5c 100644 --- a/tests/generic/test_wrapped_optionals_and_defaults.cpp +++ b/tests/generic/test_wrapped_optionals_and_defaults.cpp @@ -21,4 +21,20 @@ TEST(generic, test_wrapped_optionals) { EXPECT_EQ(rfl::to_generic(Optionals{}).to_object().value().size(), 0u); } +struct Defaults { + rfl::Short<"o", rfl::DefaultVal> output = std::string("out.csv"); + rfl::Positional> input = std::string("in.txt"); + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; +}; + +TEST(generic, test_wrapped_defaults) { + write_and_read(Defaults{}); + + const auto res = rfl::from_generic(rfl::Generic::Object()); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().output().value(), "out.csv"); + EXPECT_EQ(res.value().input().value(), "in.txt"); + EXPECT_EQ(res.value().jobs().value(), 4); +} + } // namespace test_wrapped_optionals_and_defaults diff --git a/tests/json/test_json_schema4.cpp b/tests/json/test_json_schema4.cpp index 6ff498eca..9c241e423 100644 --- a/tests/json/test_json_schema4.cpp +++ b/tests/json/test_json_schema4.cpp @@ -65,7 +65,7 @@ TEST(json, test_json_schema4) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","default":"Circle","enum":["Circle"]},"radius":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number","default":0.0},"height":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","default":"Rectangle","enum":["Rectangle"]},"width":{"type":"number","default":0.0},"height":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","default":"Square","enum":["Square"]},"width":{"type":"number","default":0.0}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string","default":""},"f2":{"type":"string","default":""}},"required":[],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema_default_if_missing.cpp b/tests/json/test_json_schema_default_if_missing.cpp new file mode 100644 index 000000000..e77c72213 --- /dev/null +++ b/tests/json/test_json_schema_default_if_missing.cpp @@ -0,0 +1,733 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_json_schema_default_if_missing { + +enum class LogLevel { debug, info, warn, error }; + +struct ServerConfig { + int port = 8080; + std::string host = "localhost"; + bool verbose = true; + double ratio = 0.75; + LogLevel level = LogLevel::info; + std::vector tags = {"web", "api"}; + std::vector empty_vec; +}; + +struct Inner { + int retries = 3; + std::string retry_mode = "fast"; +}; + +struct Outer { + std::string app_name = "demo"; + Inner inner = Inner{.retries = 5, .retry_mode = "safe"}; +}; + +struct OptionalAndPtrFields { + std::optional empty_opt; + std::optional init_opt = 5; + std::optional zero_opt = 0; + std::optional false_opt = false; + std::optional empty_str_opt = std::string(""); + std::shared_ptr null_shared; + std::shared_ptr init_shared = std::make_shared(42); + std::unique_ptr null_unique; + std::unique_ptr init_unique = std::make_unique(7); +}; + +using Port = rfl::Validator, rfl::Maximum<65535>>; + +struct WrappedFields { + rfl::Description<"Server port", int> port = 8080; + rfl::Description<"Optional label", std::optional> label; + rfl::Description<"Optional count", std::optional> count = 10; + rfl::Deprecated<"Use port", "Legacy port", int> old_port = 80; + rfl::Rename<"hostName", std::string> host_name = "localhost"; + rfl::Rename<"optTag", std::optional> opt_tag; + Port valid_port = 443; + rfl::DefaultVal explicit_default = 99; + rfl::Rename<"renamedDefault", rfl::DefaultVal> renamed_default = 77; + rfl::Description<"Described default", rfl::DefaultVal> described_default = + 55; + rfl::Skip skipped = 123; +}; + +struct NoDefaultCtor { + using ReflectionType = int; + explicit NoDefaultCtor(int _v) : value(_v) {} + int reflection() const { return value; } + int value; +}; + +struct WithNonDefaultConstructibleMember { + NoDefaultCtor member; + int port = 8080; +}; + +struct NonWritable { + int copied; + int missing; + struct InnerVal { + int value; + }; + using ReflectionType = InnerVal; + NonWritable() : copied(0), missing(0) {} + explicit NonWritable(ReflectionType&& _r) : copied(_r.value), missing(0) {} + bool operator<(const NonWritable& _other) const { + return copied < _other.copied; + } +}; + +struct WithNonWritableFields { + int port = 8080; + NonWritable raw; + rfl::Description<"desc", NonWritable> described; + std::optional optional_nw; +}; + +inline int throwing_init() { + throw std::runtime_error("cannot default construct"); +} + +struct ThrowingDefaultCtor { + int port = 8080; + int bad = throwing_init(); +}; + +struct ThrowingValidatorField { + int port = 8080; + Port bad_port; // default 0 fails Minimum<1> and throws +}; + +struct ThrowingWithDefaultVal { + rfl::DefaultVal count = 10; + Port bad_port; // default 0 fails Minimum<1> and throws +}; + +struct ThrowingToGeneric { + int value = 1; +}; + +struct ReadOnlyReflected { + int value = 0; +}; + +} // namespace test_json_schema_default_if_missing + +namespace rfl { +template <> +struct Reflector { + using ReflType = int; + static test_json_schema_default_if_missing::ThrowingToGeneric to( + const ReflType& _v) { + return {_v}; + } + static ReflType from( + const test_json_schema_default_if_missing::ThrowingToGeneric&) { + throw std::runtime_error("cannot serialize default"); + } +}; + +template <> +struct Reflector { + using ReflType = int; + static test_json_schema_default_if_missing::ReadOnlyReflected to( + const ReflType& _v) { + return {_v}; + } +}; +} // namespace rfl + +namespace test_json_schema_default_if_missing { + +struct WithThrowingToGenericField { + int port = 8080; + ThrowingToGeneric bad_serialize; +}; + +TEST(json, test_schema_default_if_missing_basic) { + const auto schema = + rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema_default_if_missing__ServerConfig","$defs":{"test_json_schema_default_if_missing__ServerConfig":{"type":"object","properties":{"port":{"type":"integer","default":8080},"host":{"type":"string","default":"localhost"},"verbose":{"default":true,"type":"boolean"},"ratio":{"type":"number","default":0.75},"level":{"type":"string","default":"info","enum":["debug","info","warn","error"]},"tags":{"type":"array","default":["web","api"],"items":{"type":"string"}},"empty_vec":{"type":"array","default":[],"items":{"type":"integer"}}},"required":[]}}})"; + + EXPECT_EQ(schema, expected) << schema; +} + +TEST(json, test_schema_without_default_if_missing_has_no_defaults) { + const auto schema = rfl::json::to_schema(); + + EXPECT_EQ(schema.find("\"default\""), std::string::npos) << schema; + EXPECT_NE( + schema.find( + R"("required":["port","host","verbose","ratio","level","tags","empty_vec"])"), + std::string::npos) + << schema; +} + +TEST(json, test_schema_default_if_missing_nested_structs) { + const auto schema = rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema_default_if_missing__Outer","$defs":{"test_json_schema_default_if_missing__Inner":{"type":"object","properties":{"retries":{"type":"integer","default":3},"retry_mode":{"type":"string","default":"fast"}},"required":[]},"test_json_schema_default_if_missing__Outer":{"type":"object","properties":{"app_name":{"type":"string","default":"demo"},"inner":{"$ref":"#/$defs/test_json_schema_default_if_missing__Inner","default":{"retries":5,"retry_mode":"safe"}}},"required":[]}}})"; + + EXPECT_EQ(schema, expected) << schema; + + // With field-name processors, nested default keys match the renamed schema. + const auto camel_schema = + rfl::json::to_schema(); + + EXPECT_NE( + camel_schema.find(R"("default":{"retries":5,"retryMode":"safe"})"), + std::string::npos) + << camel_schema; + EXPECT_EQ(camel_schema.find("retry_mode"), std::string::npos) << camel_schema; +} + +TEST(json, test_schema_default_if_missing_optionals_and_ptrs) { + const auto schema = + rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema_default_if_missing__OptionalAndPtrFields","$defs":{"test_json_schema_default_if_missing__OptionalAndPtrFields":{"type":"object","properties":{"empty_opt":{"anyOf":[{"type":"integer"},{"type":"null"}]},"init_opt":{"default":5,"anyOf":[{"type":"integer"},{"type":"null"}]},"zero_opt":{"default":0,"anyOf":[{"type":"integer"},{"type":"null"}]},"false_opt":{"default":false,"anyOf":[{"type":"boolean"},{"type":"null"}]},"empty_str_opt":{"default":"","anyOf":[{"type":"string"},{"type":"null"}]},"null_shared":{"anyOf":[{"type":"integer"},{"type":"null"}]},"init_shared":{"default":42,"anyOf":[{"type":"integer"},{"type":"null"}]},"null_unique":{"anyOf":[{"type":"integer"},{"type":"null"}]},"init_unique":{"default":7,"anyOf":[{"type":"integer"},{"type":"null"}]}},"required":[]}}})"; + + EXPECT_EQ(schema, expected) << schema; +} + +TEST(json, test_schema_default_if_missing_wrappers) { + const auto schema = + rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema_default_if_missing__WrappedFields","$defs":{"test_json_schema_default_if_missing__WrappedFields":{"type":"object","properties":{"port":{"type":"integer","description":"Server port","default":8080},"label":{"description":"Optional label","anyOf":[{"type":"string"},{"type":"null"}]},"count":{"description":"Optional count","default":10,"anyOf":[{"type":"integer"},{"type":"null"}]},"old_port":{"type":"integer","description":"Legacy port","deprecated":true,"deprecationMessage":"Use port","default":80},"hostName":{"type":"string","default":"localhost"},"optTag":{"anyOf":[{"type":"string"},{"type":"null"}]},"valid_port":{"default":443,"allOf":[{"minimum":1,"type":"integer"},{"maximum":65535,"type":"integer"}]},"explicit_default":{"type":"integer","default":99},"renamedDefault":{"type":"integer","default":77},"described_default":{"type":"integer","description":"Described default","default":55}},"required":[]}}})"; + + EXPECT_EQ(schema, expected) << schema; +} + +TEST(json, test_schema_default_if_missing_non_default_constructible) { + const auto schema = + rfl::json::to_schema(); + + EXPECT_EQ(schema.find("\"default\""), std::string::npos) << schema; + EXPECT_NE(schema.find("\"required\":[]"), std::string::npos) << schema; + EXPECT_NE(schema.find("\"port\":{\"type\":\"integer\"}"), std::string::npos) + << schema; +} + +TEST(json, test_schema_default_if_missing_non_writable_fields) { + const auto schema = + rfl::json::to_schema(); + + EXPECT_NE(schema.find(R"("port":{"type":"integer","default":8080})"), + std::string::npos) + << schema; + EXPECT_NE( + schema.find( + R"("raw":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable"})"), + std::string::npos) + << schema; + EXPECT_NE( + schema.find( + R"("described":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable","description":"desc"})"), + std::string::npos) + << schema; +} + +TEST(json, test_schema_default_if_missing_throwing_constructors) { + const auto schema1 = + rfl::json::to_schema(); + EXPECT_EQ(schema1.find("\"default\""), std::string::npos) << schema1; + EXPECT_NE(schema1.find(R"("port":{"type":"integer"})"), std::string::npos) + << schema1; + + const auto schema2 = + rfl::json::to_schema(); + EXPECT_EQ(schema2.find("\"default\""), std::string::npos) << schema2; + EXPECT_NE(schema2.find(R"("port":{"type":"integer"})"), std::string::npos) + << schema2; + + const auto schema3 = + rfl::json::to_schema(); + EXPECT_EQ(schema3.find("\"default\""), std::string::npos) << schema3; + EXPECT_NE(schema3.find(R"("count":{"type":"integer"})"), std::string::npos) + << schema3; + + const auto schema4 = + rfl::json::to_schema(); + EXPECT_NE(schema4.find(R"("port":{"type":"integer","default":8080})"), + std::string::npos) + << schema4; + EXPECT_NE( + schema4.find( + R"("bad_serialize":{"$ref":"#/$defs/test_json_schema_default_if_missing__ThrowingToGeneric"})"), + std::string::npos) + << schema4; +} + +struct WithReadOnlyReflector { + int port = 8080; + ReadOnlyReflected ro; +}; + +TEST(json, test_schema_default_if_missing_read_only_reflector) { + const auto schema = + rfl::json::to_schema(); + + EXPECT_NE(schema.find(R"("port":{"type":"integer","default":8080})"), + std::string::npos) + << schema; + EXPECT_NE( + schema.find( + R"("ro":{"$ref":"#/$defs/test_json_schema_default_if_missing__ReadOnlyReflected"})"), + std::string::npos) + << schema; +} + +TEST(json, test_schema_default_if_missing_no_field_names) { + const auto schema = rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema_default_if_missing__Inner","$defs":{"test_json_schema_default_if_missing__Inner":{"type":"array","prefixItems":[{"type":"integer","default":3},{"type":"string","default":"fast"}],"items":false}}})"; + + EXPECT_EQ(schema, expected) << schema; +} + +static_assert( + !rfl::internal::is_safe_default_constructible_v>); +static_assert(!rfl::internal::is_safe_default_constructible_v< + rfl::CopyableBox>); +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>); + +struct WithBoxNoDefault { + rfl::Box boxed; + int port = 8080; +}; + +struct WithRefNoDefault { + rfl::Ref ref; + int port = 8080; +}; + +struct WithAttributeNoDefault { + rfl::Attribute attr; + int port = 8080; +}; + +TEST(json, test_schema_default_if_missing_wrapped_no_default) { + const auto box_schema = + rfl::json::to_schema(); + EXPECT_EQ(box_schema.find("\"default\""), std::string::npos) << box_schema; + EXPECT_NE(box_schema.find("\"required\":[]"), std::string::npos) + << box_schema; + EXPECT_NE(box_schema.find(R"("port":{"type":"integer"})"), std::string::npos) + << box_schema; + + const auto ref_schema = + rfl::json::to_schema(); + EXPECT_EQ(ref_schema.find("\"default\""), std::string::npos) << ref_schema; + EXPECT_NE(ref_schema.find("\"required\":[]"), std::string::npos) + << ref_schema; + EXPECT_NE(ref_schema.find(R"("port":{"type":"integer"})"), std::string::npos) + << ref_schema; + + const auto attr_schema = + rfl::json::to_schema(); + EXPECT_EQ(attr_schema.find("\"default\""), std::string::npos) << attr_schema; + EXPECT_NE(attr_schema.find("\"required\":[]"), std::string::npos) + << attr_schema; + EXPECT_NE(attr_schema.find(R"("port":{"type":"integer"})"), std::string::npos) + << attr_schema; +} + +struct AlwaysValidNonWritable { + static rfl::Result validate(const NonWritable& _v) { + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct NestedWithNonWritable { + int inner_val = 7; + NonWritable nw; +}; + +struct TaggedGoodAlt { + int val = 1; +}; + +struct TaggedBadAlt { + NonWritable nw; +}; + +struct WithWrappedNonWritable { + int port = 8080; + rfl::Box boxed; + rfl::Ref ref; + rfl::Commented commented; + rfl::Attribute attr; + rfl::Validator validated; +}; + +struct WithCompositeNonWritable { + int port = 8080; + std::vector vec; + std::deque deq; + std::set set_nw; + std::map str_map; + std::array arr; + std::pair pair_nw; + std::tuple std_tup; + rfl::Tuple rfl_tup; + std::variant std_var; + rfl::Variant rfl_var; + rfl::TaggedUnion<"tag", TaggedGoodAlt, TaggedBadAlt> tagged_union; + NestedWithNonWritable nested; +}; + +TEST(json, test_schema_default_if_missing_wrapped_and_composite_non_writable) { + static_assert(!rfl::internal::CanWriteGeneric); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric< + rfl::Validator>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert(!rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric< + rfl::TaggedUnion<"tag", TaggedGoodAlt, TaggedBadAlt>>); + static_assert(!rfl::internal::CanWriteGeneric); + static_assert(!rfl::internal::CanWriteGeneric); + static_assert(!rfl::internal::CanWriteGeneric); + static_assert(rfl::internal::CanWriteGeneric>); + static_assert(rfl::internal::CanWriteGeneric); + static_assert(rfl::internal::CanWriteGeneric>); + static_assert( + !rfl::internal::CanWriteGeneric>); + + const auto wrapped_schema = + rfl::json::to_schema(); + EXPECT_NE( + wrapped_schema.find( + R"("test_json_schema_default_if_missing__WithWrappedNonWritable":{"type":"object","properties":{"port":{"type":"integer","default":8080},"boxed":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable"},"ref":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable"},"commented":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable"},"attr":{"$ref":"#/$defs/rfl__Attribute_test_json_schema_default_if_missing__NonWritable_"},"validated":{"allOf":[]}},"required":[]})"), + std::string::npos) + << wrapped_schema; + + const auto composite_schema = + rfl::json::to_schema(); + EXPECT_NE( + composite_schema.find(R"("port":{"type":"integer","default":8080})"), + std::string::npos) + << composite_schema; + // Writable fields inside nested/tagged definitions still get their own + // defaults, while none of the non-writable composite fields on + // WithCompositeNonWritable get a default. + EXPECT_NE( + composite_schema.find(R"("inner_val":{"type":"integer","default":7})"), + std::string::npos) + << composite_schema; + const auto composite_def_pos = composite_schema.find( + R"("test_json_schema_default_if_missing__WithCompositeNonWritable":)"); + ASSERT_NE(composite_def_pos, std::string::npos) << composite_schema; + const auto first_composite_default = + composite_schema.find("\"default\"", composite_def_pos); + ASSERT_NE(first_composite_default, std::string::npos) << composite_schema; + // Only `port` inside WithCompositeNonWritable gets a default. + EXPECT_EQ(composite_schema.find("\"default\"", first_composite_default + 1), + std::string::npos) + << composite_schema; +} + +struct Node { + int v = 1; + std::unique_ptr next; +}; + +struct BoxNode { + int v = 2; + std::optional> next; +}; + +struct NonWritableNode { + int v = 3; + NonWritable nw; + std::unique_ptr next; +}; + +TEST(json, test_schema_default_if_missing_recursive_structs) { + static_assert(rfl::internal::CanWriteGeneric); + static_assert(rfl::internal::CanWriteGeneric); + static_assert(!rfl::internal::CanWriteGeneric); + + const auto node_schema = + rfl::json::to_schema(); + EXPECT_NE(node_schema.find(R"("v":{"type":"integer","default":1})"), + std::string::npos) + << node_schema; + EXPECT_NE( + node_schema.find( + R"("next":{"anyOf":[{"$ref":"#/$defs/test_json_schema_default_if_missing__Node"},{"type":"null"}]})"), + std::string::npos) + << node_schema; + + const auto box_node_schema = + rfl::json::to_schema(); + EXPECT_NE(box_node_schema.find(R"("v":{"type":"integer","default":2})"), + std::string::npos) + << box_node_schema; + + const auto nw_node_schema = + rfl::json::to_schema(); + EXPECT_NE(nw_node_schema.find(R"("v":{"type":"integer","default":3})"), + std::string::npos) + << nw_node_schema; + EXPECT_NE( + nw_node_schema.find( + R"("nw":{"$ref":"#/$defs/test_json_schema_default_if_missing__NonWritable"})"), + std::string::npos) + << nw_node_schema; +} + +namespace recursive_incomplete { + +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; +}; + +} // namespace recursive_incomplete + +TEST(json, test_schema_default_if_missing_recursive_incomplete_box_ref) { + using recursive_incomplete::DirectNode; + using recursive_incomplete::DT; + using recursive_incomplete::Leaf; + using recursive_incomplete::Node; + using recursive_incomplete::Tree; + + 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); + static_assert( + !rfl::internal::is_safe_default_constructible_v); + + // Normal read/write roundtrip for forward-declared recursive variant + Box. + const DT dt_val{Node{rfl::make_box
(DT{Leaf{42}})}}; + const auto dt_json = rfl::json::write(dt_val); + const auto dt_parsed = rfl::json::read
(dt_json); + ASSERT_TRUE(dt_parsed.has_value()) << dt_parsed.error().what(); + ASSERT_TRUE(std::holds_alternative(dt_parsed->v)); + ASSERT_TRUE(std::holds_alternative(std::get(dt_parsed->v).lesser->v)); + EXPECT_EQ(std::get(std::get(dt_parsed->v).lesser->v).x, 42); + + // Schema generation with DefaultIfMissing for forward-declared DT. + const auto dt_schema = rfl::json::to_schema(); + EXPECT_NE(dt_schema.find(R"("x":{"type":"integer","default":0})"), + std::string::npos) + << dt_schema; + EXPECT_NE(dt_schema.find(R"("default":{"x":0})"), std::string::npos) + << dt_schema; + + // Normal read/write roundtrip for nested struct + Box + optional. + const Tree tree_val{Tree::Branch{rfl::make_box()}}; + const auto tree_json = rfl::json::write(tree_val); + const auto tree_parsed = rfl::json::read(tree_json); + ASSERT_TRUE(tree_parsed.has_value()) << tree_parsed.error().what(); + ASSERT_TRUE(tree_parsed->b.has_value()); + EXPECT_FALSE(tree_parsed->b->child->b.has_value()); + + // Schema generation with DefaultIfMissing for Tree. + const auto tree_schema = rfl::json::to_schema(); + EXPECT_NE(tree_schema.find(R"("required":[])"), std::string::npos) + << tree_schema; + + // Cyclic DirectNode must compile and NOT stack-overflow; default is omitted. + const auto direct_schema = + rfl::json::to_schema(); + EXPECT_EQ(direct_schema.find("\"default\""), std::string::npos) + << direct_schema; + EXPECT_NE(direct_schema.find(R"("v":{"type":"integer"})"), std::string::npos) + << direct_schema; + EXPECT_NE(direct_schema.find(R"("required":[])"), std::string::npos) + << direct_schema; +} + +struct AggregateWithNoDefaultDmi { + NoDefaultCtor x = NoDefaultCtor(42); + int y = 7; +}; + +TEST(json, test_schema_default_if_missing_aggregate_dmi_and_references) { + 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 schema = + rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("y":{"type":"integer","default":7})"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("default":42)"), std::string::npos) << schema; +} + +struct WrappedDefaultWithBoxNoDefault { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + rfl::Box boxed; +}; + +struct WrappedDefaultWithRefNoDefault { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + rfl::Ref ref; +}; + +struct WrappedDefaultWithCycle { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + rfl::Box next; +}; + +struct ThrowingOptionalReflection { + using ReflectionType = std::optional; + ThrowingOptionalReflection() = default; + explicit ThrowingOptionalReflection(std::optional) {} + std::optional reflection() const { + throw std::runtime_error("reflection threw"); + } +}; + +struct WithThrowingOptionalReflection { + int port = 8080; + ThrowingOptionalReflection opt; +}; + +TEST(json, test_wrapped_default_unsafe_construct_and_throwing_is_empty) { + static_assert(rfl::internal::is_unwrapped_default_val_v< + rfl::Rename<"a", rfl::Rename<"b", rfl::DefaultVal>>>); + static_assert( + rfl::internal::is_default_val_v< + rfl::Description<"d", const rfl::DefaultVal>>); + + // Wrapped DefaultVal paired with Box or Ref + // must compile cleanly (falling back to non-default read and omitting + // defaults in schema) rather than instantiating Box()/Ref(). + const auto box_ok = rfl::json::read( + R"({"jobs":8,"boxed":5})"); + ASSERT_TRUE(box_ok.has_value()) << box_ok.error().what(); + EXPECT_EQ(box_ok->jobs().value(), 8); + EXPECT_EQ(box_ok->boxed->value, 5); + EXPECT_FALSE( + rfl::json::read(R"({"boxed":5})") + .has_value()); + + const auto box_schema = rfl::json::to_schema(); + EXPECT_EQ(box_schema.find("\"default\""), std::string::npos) << box_schema; + const auto box_schema_dim = + rfl::json::to_schema(); + EXPECT_EQ(box_schema_dim.find("\"default\""), std::string::npos) + << box_schema_dim; + + const auto ref_ok = rfl::json::read( + R"({"jobs":8,"ref":5})"); + ASSERT_TRUE(ref_ok.has_value()) << ref_ok.error().what(); + EXPECT_EQ(ref_ok->jobs().value(), 8); + EXPECT_EQ(ref_ok->ref->value, 5); + const auto ref_schema = rfl::json::to_schema(); + EXPECT_EQ(ref_schema.find("\"default\""), std::string::npos) << ref_schema; + const auto ref_schema_dim = + rfl::json::to_schema(); + EXPECT_EQ(ref_schema_dim.find("\"default\""), std::string::npos) + << ref_schema_dim; + + // Cyclic Box with wrapped DefaultVal must not stack-overflow. + const auto cyc_schema = rfl::json::to_schema(); + EXPECT_EQ(cyc_schema.find("\"default\""), std::string::npos) << cyc_schema; + const auto cyc_schema_dim = + rfl::json::to_schema(); + EXPECT_EQ(cyc_schema_dim.find("\"default\""), std::string::npos) + << cyc_schema_dim; + + // Throwing .reflection() on a nullable ReflectionType field must be caught + // inside noexcept add_field_to_schema instead of calling std::terminate(). + const auto opt_schema = + rfl::json::to_schema(); + EXPECT_NE(opt_schema.find(R"("port":{"type":"integer","default":8080})"), + std::string::npos) + << opt_schema; + EXPECT_NE( + opt_schema.find( + R"("opt":{"$ref":"#/$defs/test_json_schema_default_if_missing__ThrowingOptionalReflection"})"), + std::string::npos) + << opt_schema; +} + +} // namespace test_json_schema_default_if_missing diff --git a/tests/json/test_wrapped_optionals_and_defaults.cpp b/tests/json/test_wrapped_optionals_and_defaults.cpp index 0d5d12583..ec79398a7 100644 --- a/tests/json/test_wrapped_optionals_and_defaults.cpp +++ b/tests/json/test_wrapped_optionals_and_defaults.cpp @@ -1,6 +1,9 @@ #include +#include +#include #include +#include #include #include #include @@ -8,8 +11,9 @@ #include "write_and_read.hpp" // rfl::Short, rfl::Positional and rfl::Description are transparent for JSON, -// so a std::optional inside them is written as on its own: omitted when -// empty. +// so std::optional and rfl::DefaultVal must behave the same inside them as +// they do on their own: omitted when empty, filled in when missing, and not +// required in the schema. namespace test_wrapped_optionals_and_defaults { struct Optionals { @@ -40,4 +44,201 @@ TEST(json, test_wrapped_optionals_write_and_read) { R"({"log":"log.txt","title":"Report","config":"config.json","outDir":"out"})"); } +struct Defaults { + rfl::Short<"o", rfl::DefaultVal> output = std::string("out.csv"); + rfl::Positional> input = std::string("in.txt"); + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; +}; + +struct NestedDefaults { + rfl::Description<"Log file", rfl::Short<"l", rfl::DefaultVal>> + log = std::string("log.txt"); + rfl::Short<"t", rfl::Description<"Title", rfl::DefaultVal>> + title = std::string("Report"); + rfl::Positional>> + config = std::string("config.json"); + rfl::Deprecated<"Use jobs instead.", "Worker threads", rfl::DefaultVal> + threads = 4; + rfl::Rename<"outDir", rfl::Short<"d", rfl::DefaultVal>> out_dir = + std::string("out"); +}; + +TEST(json, test_wrapped_defaults_read_missing_fields) { + const auto partial = rfl::json::read(R"({"jobs":8})"); + ASSERT_TRUE(partial) << partial.error().what(); + EXPECT_EQ(partial.value().output().value(), "out.csv"); + EXPECT_EQ(partial.value().input().value(), "in.txt"); + EXPECT_EQ(partial.value().jobs().value(), 8); + + const auto nested = rfl::json::read(R"({})"); + ASSERT_TRUE(nested) << nested.error().what(); + EXPECT_EQ(nested.value().log().value().value(), "log.txt"); + EXPECT_EQ(nested.value().title().value().value(), "Report"); + EXPECT_EQ(nested.value().config().value().value(), "config.json"); + EXPECT_EQ(nested.value().threads().value(), 4); + EXPECT_EQ(nested.value().out_dir().value().value(), "out"); +} + +TEST(json, test_wrapped_defaults_schema) { + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__NestedDefaults","$defs":{"test_wrapped_optionals_and_defaults__NestedDefaults":{"type":"object","properties":{"log":{"type":"string","description":"Log file","default":"log.txt"},"title":{"type":"string","description":"Title","default":"Report"},"config":{"type":"string","description":"Config file","default":"config.json"},"threads":{"type":"integer","description":"Worker threads","deprecated":true,"deprecationMessage":"Use jobs instead.","default":4},"outDir":{"type":"string","default":"out"}},"required":[]}}})"); +} + +// The schema reads the defaults of a TaggedUnion alternative from a +// default-constructed instance of that alternative. +struct WrappedDefaultAlternative { + rfl::Description<"Output file", rfl::DefaultVal> output = + std::string("out.csv"); + int k = 0; +}; + +struct OtherAlternative { + std::string q; +}; + +TEST(json, test_wrapped_defaults_tagged_union_schema) { + const auto schema = rfl::json::to_schema< + rfl::TaggedUnion<"type", WrappedDefaultAlternative, OtherAlternative>>(); + EXPECT_NE( + schema.find( + R"("output":{"type":"string","description":"Output file","default":"out.csv"})"), + std::string::npos) + << schema; +} + +// A wrapped rfl::DefaultVal in a NamedTuple is required: a NamedTuple has no +// in-class initializers. +TEST(json, test_wrapped_defaults_named_tuple_missing_field) { + using Wrapped = rfl::NamedTuple< + rfl::Field<"o", rfl::Short<"o", rfl::DefaultVal>>, + rfl::Field<"z", int>>; + const auto wrapped = rfl::json::read(R"({"z":1})"); + ASSERT_FALSE(wrapped); + EXPECT_EQ(wrapped.error().what(), std::string("Field named 'o' not found.")); + + const auto present = rfl::json::read(R"({"o":"x","z":1})"); + ASSERT_TRUE(present) << present.error().what(); + EXPECT_EQ(rfl::get<"o">(present.value()).value().value(), "x"); +} + +struct NotDefaultConstructible { + using ReflectionType = int; + NotDefaultConstructible(int _v) : v_(_v) {} + int reflection() const { return v_; } + int v_; +}; + +// A struct that cannot be default-constructed is read into raw memory, so the +// in-class default of a wrapped rfl::DefaultVal field is not available and the +// field is required. +struct WrappedDefaultAndNoDefaultConstructor { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + NotDefaultConstructible n; +}; + +TEST(json, test_wrapped_defaults_not_default_constructible) { + const auto wrapped = rfl::json::read( + R"({"jobs":8,"n":3})"); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().jobs().value(), 8); + + const auto missing = + rfl::json::read(R"({"n":3})"); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().what(), + std::string("Field named 'jobs' not found.")); +} + +// If default construction throws, a struct whose only rfl::DefaultVal fields +// are wrapped is read without its defaults, like a struct that cannot be +// default-constructed, so those fields are required and the schema leaves out +// their defaults. With a bare rfl::DefaultVal, the read fails. +struct ThrowsOnDefault { + using ReflectionType = int; + ThrowsOnDefault() { throw std::runtime_error("No default."); } + ThrowsOnDefault(int _v) : v_(_v) {} + int reflection() const { return v_; } + int v_; +}; + +struct WrappedDefaultAndThrowingDefault { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + ThrowsOnDefault t; +}; + +struct BareDefaultAndThrowingDefault { + rfl::DefaultVal jobs = 4; + ThrowsOnDefault t; +}; + +TEST(json, test_wrapped_defaults_read_with_throwing_default) { + const auto wrapped = + rfl::json::read(R"({"jobs":8,"t":3})"); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().jobs().value(), 8); + EXPECT_EQ(wrapped.value().t.v_, 3); + + const auto wrapped_missing = + rfl::json::read(R"({"t":3})"); + ASSERT_FALSE(wrapped_missing); + EXPECT_EQ(wrapped_missing.error().what(), + std::string("Field named 'jobs' not found.")); + + const auto bare = + rfl::json::read(R"({"jobs":8,"t":3})"); + ASSERT_FALSE(bare); + EXPECT_TRUE(std::string(bare.error().what()) + .starts_with("Could not default-construct")) + << bare.error().what(); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE( + schema.find(R"("jobs":{"type":"integer","description":"Worker threads"})"), + std::string::npos) + << schema; +} + +// Like a struct with a bare rfl::DefaultVal, a struct with a wrapped one is +// default-constructed before it is read, so the in-class defaults of its other +// fields survive a read too. +struct WrappedDefaultAndOptional { + rfl::Short<"j", rfl::DefaultVal> jobs = 4; + std::optional retries = 5; +}; + +TEST(json, test_wrapped_defaults_keep_sibling_defaults) { + const auto res = rfl::json::read(R"({})"); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().jobs().value(), 4); + EXPECT_EQ(res.value().retries, 5); +} + +// A struct with an atomic field is read through a NamedTuple, which has no +// in-class initializers, so a wrapped rfl::DefaultVal there is required. A +// bare one does not compile; a wrapped one does. +struct AtomicAndWrappedDefault { + std::atomic counter; + rfl::Description<"d", rfl::DefaultVal> x = 1; +}; + +template +void check_atomic_and_wrapped_default() { + const auto res = rfl::json::read

(R"({"counter":3,"x":2})"); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ((*res.value()).counter.load(), 3); + EXPECT_EQ((*res.value()).x().value(), 2); + + const auto missing = rfl::json::read

(R"({"counter":3})"); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().what(), std::string("Field named 'x' not found.")); +} + +TEST(json, test_wrapped_defaults_atomic) { + check_atomic_and_wrapped_default>(); + check_atomic_and_wrapped_default>(); + check_atomic_and_wrapped_default>(); + check_atomic_and_wrapped_default>(); +} + } // namespace test_wrapped_optionals_and_defaults