diff --git a/docs/content/default_val.md b/docs/content/default_val.md index 6b29b52b..4b7758c0 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,6 +90,10 @@ 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. +If the struct cannot be default-constructed at all, for instance because a field's type has no default constructor, it is read without its default values, so its `rfl::DefaultVal` fields must be present in the input. The same goes for a struct whose default constructor throws if all its `rfl::DefaultVal` fields are inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated`; with a bare `rfl::DefaultVal`, 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, and so must an `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated`. + ## When to use Use `rfl::DefaultVal` when you want a field to be optional at the input side but still available as a value on the resulting object (no std::optional or pointer indirection). It is particularly useful for fields with sensible defaults (for example, a common last name, a default configuration value, or empty containers/strings). diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index d6a22294..93a1084b 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -149,6 +149,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/internal/has_default_val_v.hpp b/include/rfl/internal/has_default_val_v.hpp index 1d19ef96..5473d0d7 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 d0811eb5..78920690 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -2,9 +2,14 @@ #define RFL_INTERNAL_ISDEFAULTVAL_HPP_ #include +#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 { @@ -18,14 +23,64 @@ 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 std::true_type {}; + +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 { + return _field; +} + +template + requires is_default_val_v +const auto& get_default_val(const T& _field) noexcept { + return get_default_val(_field.value()); +} + +/// The DefaultVal type inside a field for which is_default_val_v is true. +template +using default_val_t = std::remove_cvref_t&>()))>; + } // namespace rfl::internal #endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 835e7abc..7763fb46 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -68,10 +68,11 @@ concept CanWriteGeneric = IsReflectionTypeWrapper>; /// 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 @@ -130,8 +131,11 @@ struct NamedTupleParser { auto ptr = internal::ptr_cast*>(&buf); auto view = rfl::to_view(*ptr); using ViewType = std::remove_cvref_t; - auto [set, err] = - Parser::read_view(_r, _var, &view); + // A NamedTuple has no in-class initializers, so a missing bare + // rfl::DefaultVal field is value-initialized, which is what DefaultVal + // means without an initializer. + auto [set, err] = Parser::read_view( + _r, _var, &view, /*_value_initialize_default_vals=*/true); if (err) [[unlikely]] { call_destructors_where_necessary(set, &view); return error(std::move(*err)); @@ -147,27 +151,35 @@ struct NamedTupleParser { * @param _r The reader to use. * @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 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. */ static RFL_ALWAYS_INLINE std::pair, std::optional> read_view(const R& _r, const InputVarType& _var, - NamedTuple* _view) noexcept { + NamedTuple* _view, + const bool _value_initialize_default_vals = false) noexcept { if constexpr (_no_field_names) { auto arr = _r.to_array(_var); if (!arr) [[unlikely]] { auto set = std::array{}; return std::make_pair(set, arr.error()); } - return read_object_or_array(_r, *arr, _view); + return read_object_or_array(_r, *arr, _view, + _value_initialize_default_vals); } else { auto obj = _r.to_object(_var); if (!obj) [[unlikely]] { auto set = std::array{}; return std::make_pair(set, obj.error()); } - return read_object_or_array(_r, *obj, _view); + return read_object_or_array(_r, *obj, _view, + _value_initialize_default_vals); } } @@ -284,13 +296,10 @@ struct NamedTupleParser { // 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()); - } - }); + set_default_value( + rfl::to_generic( + internal::get_default_val(*rfl::get<_i>(*_view)).value()), + &s); } if constexpr (_no_field_names) { _schema->types_.emplace_back(std::move(s)); @@ -300,6 +309,21 @@ struct NamedTupleParser { } }; + /// 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. + static void set_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_default_value(std::move(_default), &*_s.type_); + } + }); + } + template static void build_object(const W& _w, const NamedTuple& _tup, OutputObjectOrArrayType* _ptr, @@ -331,20 +355,38 @@ struct NamedTupleParser { template static RFL_ALWAYS_INLINE void handle_one_missing_field( const std::array& _found, const NamedTupleType& _view, - std::array* _set, - FieldErrors* _errors) noexcept { + std::array* _set, FieldErrors* _errors, + const bool _value_initialize_default_vals) noexcept { if (should_stop_on_field_error(*_errors)) return; using FieldType = internal::nth_element_t<_i, FieldTypes...>; using ValueType = std::remove_reference_t< std::remove_pointer_t>; if (!std::get<_i>(_found)) { + constexpr bool is_default_val_field = + internal::is_default_val_v; constexpr bool is_required_field = - !internal::is_default_val_v && - !internal::is_extra_fields_v && + !is_default_val_field && !internal::is_extra_fields_v && (_all_required || is_required()); - if constexpr (is_required_field) { + // Without _set, the struct was default-constructed before it was read, + // so the field already holds its default value. With _set, the fields + // are constructed in raw memory. An rfl::NamedTuple has no in-class + // initializers, so a missing bare rfl::DefaultVal field is + // value-initialized there. Otherwise the field's default value is not + // available, so the field is required. + const bool defaults_constructed = _set == nullptr; + + if constexpr (internal::is_unwrapped_default_val_v) { + if (_value_initialize_default_vals && !defaults_constructed && + value_initialize_default_val(rfl::get<_i>(_view))) { + std::get<_i>(*_set) = true; + return; + } + } + + if (is_required_field || + (is_default_val_field && !defaults_constructed)) { constexpr auto current_name = internal::nth_element_t<_i, FieldTypes...>::name(); std::stringstream stream; @@ -352,8 +394,13 @@ struct NamedTupleParser { << "' not found."; _errors->emplace_back( make_nested_error(std::string(current_name), stream.str())); + return; + } - } else if constexpr (!internal::has_default_val_v) { + if constexpr (!is_required_field && !is_default_val_field) { + if (defaults_constructed) { + return; + } using NonConstT = std::remove_const_t; const auto ptr = const_cast(rfl::get<_i>(_view)); if constexpr (std::is_nothrow_default_constructible_v) { @@ -380,13 +427,37 @@ struct NamedTupleParser { } } + /// Constructs the rfl::DefaultVal field at `_ptr` with a value-initialized + /// value. Returns false, leaving `_ptr` unconstructed, if the value cannot + /// be value-initialized or its constructor throws, for instance a Validator + /// whose zero value is invalid. + template + static bool value_initialize_default_val(const ValueType* _ptr) noexcept { + using NonConstT = std::remove_const_t; + using T = typename internal::default_val_t::Type; + if constexpr (std::is_default_constructible_v && + std::is_default_constructible_v) { + try { + ::new (const_cast(_ptr)) NonConstT(); + return true; + } catch (const std::exception&) { + return false; + } + } else { + return false; + } + } + /// Generates error messages for when fields are missing. template static RFL_ALWAYS_INLINE void handle_missing_fields( const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors, + const bool _value_initialize_default_vals, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors), ...); + (handle_one_missing_field<_is>(_found, _view, _set, _errors, + _value_initialize_default_vals), + ...); } static auto make_parent(const std::string_view& _name, @@ -402,7 +473,8 @@ struct NamedTupleParser { std::pair, std::optional> read_object_or_array(const R& _r, const InputObjectOrArrayType& _obj_or_arr, - NamedTupleType* _view) noexcept { + NamedTupleType* _view, + const bool _value_initialize_default_vals) noexcept { auto found = std::array(); found.fill(false); auto set = std::array(); @@ -422,6 +494,7 @@ struct NamedTupleParser { } if (!should_stop_on_field_error(errors)) { handle_missing_fields(found, *_view, &set, &errors, + _value_initialize_default_vals, std::make_integer_sequence()); } if constexpr (internal::fail_fast_v) { @@ -454,6 +527,7 @@ struct NamedTupleParser { !internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { handle_missing_fields(reader.found(), *_view, nullptr, &errors, + /*_value_initialize_default_vals=*/false, std::make_integer_sequence()); } } diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index 2daf5760..d4215e22 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 4b5e8152..e12b67ed 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 50acf14d..82a345fc 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 8eed47a9..99ce7bfc 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 91cd540d..60677032 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -1,7 +1,9 @@ #ifndef RFL_PARSING_PARSER_DEFAULT_HPP_ #define RFL_PARSING_PARSER_DEFAULT_HPP_ +#include #include +#include #include #include @@ -71,6 +73,7 @@ #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" +#include "tagged_union_wrapper_no_ptr.hpp" namespace rfl::parsing { @@ -267,7 +270,8 @@ 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 && + std::is_default_constructible_v)) { return read_struct_with_default(_r, _var); } else { @@ -664,13 +668,29 @@ struct Parser { } else { using NamedTupleType = internal::processed_t; - if constexpr (internal::has_default_val_v) { - auto t = U{}; - auto view = ProcessorsType::template process(to_view(t)); - (*_definitions)[name] = - Parser::to_schema( - _definitions, &view); - } else { + // 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. + using DefaultsType = tagged_union_wrapper_no_ptr_t; + std::optional defaults; + if constexpr (internal::has_default_val_v && + std::is_default_constructible_v) { + try { + defaults.emplace(); + } catch (std::exception&) { + // For instance a validator whose default value is invalid. The + // schema is still valid without the default values. + } + if (defaults) { + auto view = ProcessorsType::template process( + to_view(*defaults)); + (*_definitions)[name] = + Parser::to_schema( + _definitions, &view); + } + } + if (!defaults) { (*_definitions)[name] = Parser::to_schema( _definitions); @@ -739,7 +759,16 @@ 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 + // without its defaults, as a struct that cannot be + // default-constructed is read, with those fields required. + return read_struct(_r, _var); + } else { + return error(default_construction_error(e.what())); + } } } @@ -747,7 +776,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/include/rfl/parsing/is_empty.hpp b/include/rfl/parsing/is_empty.hpp index 41d5b851..7f77a7c7 100644 --- a/include/rfl/parsing/is_empty.hpp +++ b/include/rfl/parsing/is_empty.hpp @@ -5,7 +5,9 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_positional.hpp" #include "../internal/is_rename.hpp" +#include "../internal/is_short.hpp" #include "../internal/is_skip.hpp" #include "is_map_like.hpp" #include "is_vector_like.hpp" @@ -34,7 +36,9 @@ static bool is_empty(const T& _var) { const auto& [r] = _var; return is_empty(r); } - } else if constexpr (internal::is_rename_v) { + } else if constexpr (internal::is_rename_v || + internal::is_short_v || + internal::is_positional_v) { return is_empty(_var.value()); } else if constexpr (is_map_like_v || is_vector_like_v) { return _var.begin() == _var.end(); diff --git a/tests/cli/test_optional_short_and_positional.cpp b/tests/cli/test_optional_short_and_positional.cpp new file mode 100644 index 00000000..ac80d759 --- /dev/null +++ b/tests/cli/test_optional_short_and_positional.cpp @@ -0,0 +1,111 @@ +#include +#include +#include +#include +#include +#include + +namespace test_optional_short_and_positional { + +struct Config { + rfl::Positional> input; + rfl::Short<"f", std::optional> format; + bool verbose = false; +}; + +TEST(cli, test_optional_positional_and_short_given) { + const char* args[] = { + "program", + "data.csv", + "-f", "json", + "--verbose" + }; + const auto result = rfl::cli::read(5, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + ASSERT_TRUE(result.value().input().has_value()); + EXPECT_EQ(*result.value().input(), "data.csv"); + ASSERT_TRUE(result.value().format().has_value()); + EXPECT_EQ(*result.value().format(), "json"); + EXPECT_EQ(rfl::json::write(result.value()), + R"({"input":"data.csv","format":"json","verbose":true})"); +} + +TEST(cli, test_optional_positional_and_short_omitted) { + const char* args[] = { + "program", + "--verbose" + }; + const auto result = rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_FALSE(result.value().input().has_value()); + EXPECT_FALSE(result.value().format().has_value()); + 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); +} + +// ConfigWithInvalidDefault{} throws, because n's zero value is invalid. The +// struct is then read without its defaults, so `output` is required. +struct ConfigWithInvalidDefault { + rfl::Short<"o", rfl::DefaultVal> output = std::string("out"); + rfl::Validator> n; +}; + +TEST(cli, test_short_default_val_with_invalid_default) { + const char* args[] = {"program", "-o", "x", "--n=2"}; + const auto result = rfl::cli::read(4, args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().output().value(), "x"); + EXPECT_EQ(result.value().n.value(), 2); + + const char* missing[] = {"program", "--n=2"}; + const auto r = rfl::cli::read(2, missing); + ASSERT_FALSE(r); + EXPECT_EQ(std::string(r.error().what()), "Field named 'output' not found."); +} + +} // 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 new file mode 100644 index 00000000..231a52b5 --- /dev/null +++ b/tests/generic/test_wrapped_optionals_and_defaults.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_wrapped_optionals_and_defaults { + +struct Optionals { + rfl::Short<"f", std::optional> format; + rfl::Positional> input; + rfl::Description<"Log file", rfl::Short<"l", std::optional>> log; +}; + +TEST(generic, test_wrapped_optionals) { + write_and_read(Optionals{}); + write_and_read(Optionals{.format = std::string("csv"), + .input = std::string("in.txt"), + .log = std::string("log.txt")}); + + 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_wrapped_optionals_and_defaults.cpp b/tests/json/test_wrapped_optionals_and_defaults.cpp new file mode 100644 index 00000000..f4d0dca5 --- /dev/null +++ b/tests/json/test_wrapped_optionals_and_defaults.cpp @@ -0,0 +1,377 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +// rfl::Short, rfl::Positional and rfl::Description are transparent for JSON, +// 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 { + rfl::Short<"f", std::optional> format; + rfl::Positional> input; +}; + +struct NestedOptionals { + rfl::Description<"Log file", rfl::Short<"l", std::optional>> log; + rfl::Short<"t", rfl::Description<"Title", std::optional>> title; + rfl::Positional>> + config; + rfl::Rename<"outDir", rfl::Positional>> out_dir; +}; + +TEST(json, test_wrapped_optionals_write_and_read) { + write_and_read(Optionals{}, R"({})"); + write_and_read( + Optionals{.format = std::string("csv"), .input = std::string("in.txt")}, + R"({"format":"csv","input":"in.txt"})"); + + write_and_read(NestedOptionals{}, R"({})"); + write_and_read( + NestedOptionals{.log = std::string("log.txt"), + .title = std::string("Report"), + .config = std::string("config.json"), + .out_dir = std::string("out")}, + R"({"log":"log.txt","title":"Report","config":"config.json","outDir":"out"})"); +} + +TEST(json, test_wrapped_optionals_schema) { + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__Optionals","$defs":{"test_wrapped_optionals_and_defaults__Optionals":{"type":"object","properties":{"format":{"anyOf":[{"type":"string"},{"type":"null"}]},"input":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":[]}}})"); + + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__NestedOptionals","$defs":{"test_wrapped_optionals_and_defaults__NestedOptionals":{"type":"object","properties":{"log":{"description":"Log file","anyOf":[{"type":"string"},{"type":"null"}]},"title":{"description":"Title","anyOf":[{"type":"string"},{"type":"null"}]},"config":{"description":"Config file","anyOf":[{"type":"string"},{"type":"null"}]},"outDir":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":[]}}})"); +} + +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_write_and_read) { + write_and_read(Defaults{}, + R"({"output":"out.csv","input":"in.txt","jobs":4})"); + write_and_read(Defaults{.output = std::string("x.csv"), + .input = std::string("x.txt"), + .jobs = 8}, + R"({"output":"x.csv","input":"x.txt","jobs":8})"); + + write_and_read( + NestedDefaults{}, + R"({"log":"log.txt","title":"Report","config":"config.json","threads":4,"outDir":"out"})"); +} + +TEST(json, test_wrapped_defaults_read_missing_fields) { + const auto defaults = rfl::json::read(R"({})"); + ASSERT_TRUE(defaults) << defaults.error().what(); + EXPECT_EQ(defaults.value().output().value(), "out.csv"); + EXPECT_EQ(defaults.value().input().value(), "in.txt"); + EXPECT_EQ(defaults.value().jobs().value(), 4); + + 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().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__Defaults","$defs":{"test_wrapped_optionals_and_defaults__Defaults":{"type":"object","properties":{"output":{"type":"string","default":"out.csv"},"input":{"type":"string","default":"in.txt"},"jobs":{"type":"integer","description":"Worker threads","default":4}},"required":[]}}})"); + + 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 BareDefaultAlternative { + rfl::DefaultVal output = std::string("out.csv"); + int k = 0; +}; + +struct OtherAlternative { + std::string q; +}; + +TEST(json, test_wrapped_defaults_tagged_union_schema) { + EXPECT_EQ( + (rfl::json::to_schema>()), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_wrapped_optionals_and_defaults__WrappedDefaultAlternative__tagged"},{"$ref":"#/$defs/test_wrapped_optionals_and_defaults__OtherAlternative__tagged"}],"$defs":{"test_wrapped_optionals_and_defaults__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]},"test_wrapped_optionals_and_defaults__WrappedDefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["WrappedDefaultAlternative"]},"output":{"type":"string","description":"Output file","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]}}})"); + + EXPECT_EQ( + (rfl::json::to_schema>()), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_wrapped_optionals_and_defaults__BareDefaultAlternative__tagged"},{"$ref":"#/$defs/test_wrapped_optionals_and_defaults__OtherAlternative__tagged"}],"$defs":{"test_wrapped_optionals_and_defaults__BareDefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["BareDefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_wrapped_optionals_and_defaults__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})"); +} + +// Counts every use of a Tracker whose constructor never ran. +struct Tracker { + static constexpr int alive_ = 0x7ac4e1; + static inline int unconstructed_uses_ = 0; + + using ReflectionType = int; + + Tracker() = default; + Tracker(int _v) : v_(_v) {} + Tracker(const Tracker& _other) : v_(_other.checked()) {} + Tracker(Tracker&& _other) noexcept : v_(_other.checked()) {} + ~Tracker() { state_ = 0; } + Tracker& operator=(const Tracker& _other) { + v_ = _other.checked(); + return *this; + } + Tracker& operator=(Tracker&& _other) noexcept { + v_ = _other.checked(); + return *this; + } + + int reflection() const { return checked(); } + + int checked() const { + if (state_ != alive_) { + ++unconstructed_uses_; + } + return v_; + } + + int v_ = 0; + int state_ = alive_; +}; + +// A NamedTuple has no in-class initializers, so a missing bare rfl::DefaultVal +// field is value-initialized. It is constructed before it is used. A wrapped +// rfl::DefaultVal in a NamedTuple is required. +TEST(json, test_wrapped_defaults_named_tuple_missing_field) { + Tracker::unconstructed_uses_ = 0; + + 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.")); + + using Bare = rfl::NamedTuple>, + rfl::Field<"z", int>>; + const auto bare = rfl::json::read(R"({"z":1})"); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(rfl::get<"o">(bare.value()).value().v_, 0); + EXPECT_EQ(rfl::get<"z">(bare.value()), 1); + + using Scalar = rfl::NamedTuple< + rfl::Field<"n", rfl::Description<"Count", rfl::DefaultVal>>, + rfl::Field<"s", rfl::DefaultVal>>; + const auto scalar = rfl::json::read(R"({"n":3})"); + ASSERT_TRUE(scalar) << scalar.error().what(); + EXPECT_EQ(rfl::get<"n">(scalar.value()).value().value(), 3); + EXPECT_EQ(rfl::get<"s">(scalar.value()).value(), ""); + + const auto present = rfl::json::read(R"({"o":7,"z":1})"); + ASSERT_TRUE(present) << present.error().what(); + EXPECT_EQ(rfl::get<"o">(present.value()).value().value().v_, 7); + + EXPECT_EQ(Tracker::unconstructed_uses_, 0); +} + +struct NoDefaultConstructor { + using ReflectionType = int; + NoDefaultConstructor(int _v) : v_(_v) {} + int reflection() const { return v_; } + int v_; +}; + +// If the value cannot be value-initialized, or its constructor throws, the +// missing field is an error. +TEST(json, test_wrapped_defaults_named_tuple_missing_field_without_zero_value) { + using NoZero = + rfl::NamedTuple>, + rfl::Field<"z", int>>; + const auto no_zero = rfl::json::read(R"({"z":1})"); + ASSERT_FALSE(no_zero); + EXPECT_EQ(no_zero.error().what(), std::string("Field named 'o' not found.")); + + using Invalid = rfl::NamedTuple< + rfl::Field<"v", rfl::DefaultVal>>>, + rfl::Field<"z", int>>; + const auto invalid = rfl::json::read(R"({"z":1})"); + ASSERT_FALSE(invalid); + EXPECT_EQ(invalid.error().what(), std::string("Field named 'v' not found.")); + + const auto present = rfl::json::read(R"({"v":3,"z":1})"); + ASSERT_TRUE(present) << present.error().what(); + EXPECT_EQ(rfl::get<"v">(present.value()).value().value(), 3); +} + +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 rfl::DefaultVal field is not available and the field +// is required. +struct WrappedDefaultAndNoDefaultConstructor { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + NotDefaultConstructible n; +}; + +struct BareDefaultAndNoDefaultConstructor { + 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); + EXPECT_EQ(wrapped.value().n.v_, 3); + + const auto wrapped_missing = + rfl::json::read(R"({"n":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,"n":3})"); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().jobs.value(), 8); + + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__WrappedDefaultAndNoDefaultConstructor","$defs":{"test_wrapped_optionals_and_defaults__NotDefaultConstructible":{"type":"integer"},"test_wrapped_optionals_and_defaults__WrappedDefaultAndNoDefaultConstructor":{"type":"object","properties":{"jobs":{"type":"integer","description":"Worker threads"},"n":{"$ref":"#/$defs/test_wrapped_optionals_and_defaults__NotDefaultConstructible"}},"required":["n"]}}})"); +} + +// The schema leaves out the default values if the struct cannot be +// default-constructed because a validator rejects a field's default value. +struct WrappedDefaultAndInvalidDefault { + rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4; + rfl::Validator> n; +}; + +struct BareDefaultAndInvalidDefault { + rfl::DefaultVal jobs = 4; + rfl::Validator> n; +}; + +TEST(json, test_wrapped_defaults_schema_with_invalid_default) { + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__WrappedDefaultAndInvalidDefault","$defs":{"test_wrapped_optionals_and_defaults__WrappedDefaultAndInvalidDefault":{"type":"object","properties":{"jobs":{"type":"integer","description":"Worker threads"},"n":{"minimum":1,"type":"integer"}},"required":["n"]}}})"); + + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_wrapped_optionals_and_defaults__BareDefaultAndInvalidDefault","$defs":{"test_wrapped_optionals_and_defaults__BareDefaultAndInvalidDefault":{"type":"object","properties":{"jobs":{"type":"integer"},"n":{"minimum":1,"type":"integer"}},"required":["n"]}}})"); +} + +// If default construction throws, a struct whose only rfl::DefaultVal fields +// are wrapped is read into raw memory, so those fields are required. With a +// bare rfl::DefaultVal, the read fails. +TEST(json, test_wrapped_defaults_read_with_invalid_default) { + const auto wrapped = + rfl::json::read(R"({"jobs":8,"n":3})"); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().jobs().value(), 8); + EXPECT_EQ(wrapped.value().n.value(), 3); + + const auto wrapped_missing = + rfl::json::read(R"({"n":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,"n":3})"); + ASSERT_FALSE(bare); + EXPECT_TRUE(std::string(bare.error().what()) + .starts_with("Could not default-construct")) + << bare.error().what(); +} + +// 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. +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