diff --git a/docs/content/default_val.md b/docs/content/default_val.md index 6b29b52b..817860bb 100644 --- a/docs/content/default_val.md +++ b/docs/content/default_val.md @@ -88,6 +88,8 @@ 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. + ## 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/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index d0811eb5..01189f63 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -2,6 +2,7 @@ #define RFL_INTERNAL_ISDEFAULTVAL_HPP_ #include +#include #include "../DefaultVal.hpp" #include "../Rename.hpp" @@ -26,6 +27,23 @@ template constexpr bool is_default_val_v = is_default_val>>::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..90b062ed 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -130,8 +130,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 +150,34 @@ 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 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); } } @@ -331,20 +341,54 @@ 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 (is_default_val_field) { + if constexpr (can_value_initialize_default_val()) { + if (_value_initialize_default_vals && !defaults_constructed) { + // The value's constructor can throw, for instance a Validator + // whose zero value is invalid. + try { + ::new (rfl::get<_i>(_view)) ValueType(); + } catch (std::exception& e) { + constexpr auto current_name = + internal::nth_element_t<_i, FieldTypes...>::name(); + _errors->emplace_back(make_nested_error( + std::string(current_name), + "Field named '" + std::string(current_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } + std::get<_i>(*_set) = true; + 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 +396,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 +429,26 @@ struct NamedTupleParser { } } + /// Whether a missing rfl::DefaultVal field can be value-initialized. Only + /// an rfl::NamedTuple does this at runtime, and it cannot have const fields, + /// so const fields of structs need no instantiation. + template + static constexpr bool can_value_initialize_default_val() { + using T = typename internal::default_val_t::Type; + return !std::is_const_v && std::is_default_constructible_v && + std::is_default_constructible_v; + } + /// 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 +464,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 +485,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 +518,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/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 91cd540d..80d98b31 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -71,6 +71,7 @@ #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" +#include "tagged_union_wrapper_no_ptr.hpp" namespace rfl::parsing { @@ -664,9 +665,19 @@ 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. + using DefaultsType = tagged_union_wrapper_no_ptr_t; if constexpr (internal::has_default_val_v) { - auto t = U{}; - auto view = ProcessorsType::template process(to_view(t)); + 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); @@ -721,6 +732,10 @@ 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{}; }, + "A struct with rfl::DefaultVal fields must be " + "default-constructible, because the default values come " + "from a default-constructed instance."); try { // This might fail, for instance if the default value of a field does not // satisfy its validator. The outer handler is for this line only. diff --git a/tests/json/test_default_val_without_default_construction.cpp b/tests/json/test_default_val_without_default_construction.cpp new file mode 100644 index 00000000..d56b6903 --- /dev/null +++ b/tests/json/test_default_val_without_default_construction.cpp @@ -0,0 +1,76 @@ +#include + +#include +#include +#include +#include + +// rfl::DefaultVal in places where the struct around it is not +// default-constructed before it is read: rfl::NamedTuple and the schema of an +// rfl::TaggedUnion alternative. +namespace test_default_val_without_default_construction { + +struct NoDefaultConstructor { + using ReflectionType = int; + NoDefaultConstructor(int _v) : v_(_v) {} + int reflection() const { return v_; } + int v_; +}; + +// A NamedTuple has no in-class initializers, so a missing rfl::DefaultVal +// field is value-initialized. It is constructed before it is used. +TEST(json, test_default_val_named_tuple_missing_field) { + using WithString = + rfl::NamedTuple, + rfl::Field<"s", rfl::DefaultVal>, + rfl::Field<"opt", std::optional>>; + const auto str = rfl::json::read(R"({"n":3})"); + ASSERT_TRUE(str) << str.error().what(); + EXPECT_EQ(rfl::get<"s">(str.value()).value(), ""); + EXPECT_FALSE(rfl::get<"opt">(str.value())); +} + +// If the value cannot be value-initialized, or its constructor throws, the +// missing field is an error. +TEST(json, test_default_val_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, and its default value " + "could not be constructed: Value expected to be " + "greater than or equal to 1, but got 0.")); + + 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); +} + +// The schema reads the defaults of an rfl::TaggedUnion alternative from a +// default-constructed instance of that alternative. +struct DefaultAlternative { + rfl::DefaultVal output = std::string("out.csv"); + int k = 0; +}; + +struct OtherAlternative { + std::string q; +}; + +TEST(json, test_default_val_tagged_union_schema) { + EXPECT_EQ( + (rfl::json::to_schema< + rfl::TaggedUnion<"type", DefaultAlternative, OtherAlternative>>()), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_default_val_without_default_construction__DefaultAlternative__tagged"},{"$ref":"#/$defs/test_default_val_without_default_construction__OtherAlternative__tagged"}],"$defs":{"test_default_val_without_default_construction__DefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["DefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_default_val_without_default_construction__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})"); +} + +} // namespace test_default_val_without_default_construction