Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 15 additions & 23 deletions docs/content/default_val.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,41 +52,33 @@ const auto homer = rfl::json::read<Person, rfl::NoFieldNames>(R"(["Homer"])").va
// homer.town == ""
```

## All fields need a valid default value
## Validators without 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.

This matters when the default value of a field's type is not valid, for instance when the field has a validator:
A struct with default values can also contain an `rfl::Validator` whose default-constructed value is invalid, such as `rfl::Validator<int, rfl::Minimum<1>>`. Such a Validator is only checked if its field is missing from the input. Then `read` returns an error:

```cpp
using Foods = rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>>;
using Positive = rfl::Validator<int, rfl::Minimum<1>>;

struct Person {
rfl::DefaultVal<std::string> name = "Homer Simpson";
rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>> favorite_foods;
Foods favorite_foods;
rfl::DefaultVal<Positive> age;
};

// Fails, even though favorite_foods is in the input.
rfl::json::read<Person>(R"({"favorite_foods":["donuts","pizza"]})");
```

An empty vector does not satisfy `rfl::Size<rfl::Minimum<1>>`, so `Person{}` throws an exception and you get the following error:

```
Could not default-construct Person, which is required because it contains rfl::DefaultVal. Give every field a valid default value. Original error: Size validation failed: Value expected to be greater than or equal to 1, but got 0.
rfl::json::read<Person>(R"({"favorite_foods":["donuts"],"age":39})"); // OK
rfl::json::read<Person>(R"({"favorite_foods":["donuts"]})");
// Error: Field named 'age' not found, and its default value is invalid:
// Value expected to be greater than or equal to 1, but got 0.
```

To avoid this, give the field a valid default value:
The same applies to all fields when you pass `rfl::DefaultIfMissing`.

```cpp
struct Person {
rfl::DefaultVal<std::string> name = "Homer Simpson";
rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>> favorite_foods =
std::vector<std::string>({"none"});
};
```
This only concerns a Validator that is default-constructed in place, as in `Foods favorite_foods;`, `rfl::DefaultVal<Positive> age{};` or `= rfl::Default{}`. An explicit default, such as `= 0`, or a temporary passed to a DefaultVal, such as `rfl::DefaultVal<Positive> age = Positive();`, is checked when it is constructed, so it must be valid, or every read fails. Outside of `read`, nothing changes: `Person{}` still throws.

The field is still required. If `favorite_foods` is missing in the input, you get the error `Field named 'favorite_foods' not found.` The default value is only used for a missing field if you pass the `rfl::DefaultIfMissing` processor.
The check also covers copies of such a default value that another default member initializer makes, as long as `read` can look into the type they are copied into: structs, standard containers, `std::optional`, `std::unique_ptr`, `rfl::Box`, variants, `rfl::Object` and wrappers like `rfl::DefaultVal` or `rfl::Rename`. It does not look into a class with a custom reflection type, a Reflector or its own `Parser`, so an invalid default copied into one of its members is not detected. Neither does it follow `std::shared_ptr` or `rfl::Ref`, because the object they point to may be shared with other code, so an invalid default copied into such an object is not detected either.

The same restriction applies to every struct that is read with the `rfl::DefaultIfMissing` processor, whether it contains an `rfl::DefaultVal` or not.
While `read` constructs such a struct, an invalid default value stays in its Validator until the struct is complete. So a default member initializer must not depend on the value of a Validator whose default is invalid, as in `std::string first = favorite_foods.value().front();`: it would see the invalid value. For the same reason, a function that catches the exception of a Validator's default constructor to fall back to another value, as in `Host host = default_host();`, does not get that exception during `read` if the struct also needs the check described here.

An `rfl::NamedTuple` has no in-class initializers. A missing `rfl::DefaultVal<T>` 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.

Expand Down
6 changes: 3 additions & 3 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,9 @@ have gotten had you read the following JSON string:
Because you have not passed a default value to town, the default value
of the type is used instead.

Note that the struct is default-constructed before it is read. Every field
therefore needs a valid default value, even if the field is in the input.
This is explained in the documentation on `rfl::DefaultVal`.
A Validator whose default value is invalid, such as
`rfl::Validator<int, rfl::Minimum<1>>`, is only checked if its field is
missing. Then `read` returns an error (see [rfl::DefaultVal](../default_val)).

### `rfl::DurationsAsCount`

Expand Down
32 changes: 30 additions & 2 deletions include/rfl/Validator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

#include "AllOf.hpp"
#include "Result.hpp"
#include "internal/DeferredValidation.hpp"
#include "internal/HasValidation.hpp"
#include "internal/cold.hpp"

namespace rfl {

Expand Down Expand Up @@ -52,8 +54,13 @@ struct Validator {
}

/// Default constructor - validates a default-constructed T.
/// @throws std::exception if validation of the default value fails
Validator() : value_(ValidationType::validate(T()).value()) {}
/// @throws std::exception if validation of the default value fails, unless
/// the Validator is part of a struct that the parser default-constructs to
/// obtain the default values of missing fields, and constructing that
/// struct normally has already failed. Then the parser checks the default
/// value after reading, if the field is missing (see
/// internal::DeferredValidation).
Validator() : value_(make_default(this)) {}

/// Move constructor.
/// @param _other The validator to move from
Expand Down Expand Up @@ -197,6 +204,27 @@ struct Validator {

Validator(AlreadyValidated, T&& _value) : value_(std::move(_value)) {}

/// Returns the validated default value. If it is invalid, see
/// invalid_default.
static T make_default(Validator* _self) {
auto res = ValidationType::validate(T());
if (res) [[likely]] {
return std::move(*res);
}
return invalid_default(_self, std::move(res).error());
}

/// Called when the default value is invalid. Throws, unless the parser is
/// default-constructing a struct containing this Validator with the check
/// deferred: then records this Validator and returns T() unchecked.
RFL_COLD static T invalid_default(Validator* _self, Error&& _err) {
if (auto* deferred = internal::DeferredValidation::find(_self)) {
deferred->defer(_self, std::move(_err));
return T();
}
throw internal::InvalidDefaultValue(std::move(_err));
}

/// Wraps the result of a validation without throwing if it failed.
static Result<Validator> wrap_validated(Result<T>&& _res) {
return std::move(_res).transform(
Expand Down
2 changes: 1 addition & 1 deletion include/rfl/Variant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class Variant {
/// the variant.
Variant() : index_(IndexType()), data_(DataType()) {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
move_from_type(FirstAlternative());
new (data_.data()) FirstAlternative();
}

/// @brief Copy-constructs the Variant from another Variant.
Expand Down
127 changes: 127 additions & 0 deletions include/rfl/internal/DeferredValidation.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
#ifndef RFL_INTERNAL_DEFERREDVALIDATION_HPP_
#define RFL_INTERNAL_DEFERREDVALIDATION_HPP_

#include <cstddef>
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>

#include "../Result.hpp"

namespace rfl::internal {

/// Thrown by the default constructor of rfl::Validator when the default value
/// is invalid. It derives from the type that Result::value() throws, so code
/// outside of the parser sees no difference. The parser catches exactly this
/// type to tell an invalid default value apart from other exceptions.
#ifdef REFLECTCPP_USE_STD_EXPECTED
class InvalidDefaultValue : public std::bad_expected_access<Error> {
public:
explicit InvalidDefaultValue(Error _err)
: std::bad_expected_access<Error>(std::move(_err)) {}
};
#else
class InvalidDefaultValue : public std::runtime_error {
public:
explicit InvalidDefaultValue(const Error& _err)
: std::runtime_error(_err.what()) {}
};
#endif

/// Lets the parser default-construct a struct even though a default-constructed
/// rfl::Validator inside it rejects its own default value.
///
/// Parser::read_struct_with_default default-constructs the struct it reads
/// into, only to obtain the default values of the fields that the input does
/// not contain. If that throws an InvalidDefaultValue, it constructs the
/// struct again while a DeferredValidation covering the struct's storage is
/// active on this thread. A Validator that is default-constructed inside that
/// storage and whose default value is invalid then keeps it instead of
/// throwing, and is recorded here with its error. After reading, the parser
/// checks the fields that the input did not contain.
///
/// Outside of that one construction nothing is active, and Validators behave
/// exactly as they always have.
class DeferredValidation {
public:
struct Record {
/// The address of the Validator.
const void* address;

/// Why its default value is invalid.
Error error;
};

DeferredValidation(const void* _begin, std::size_t _size) noexcept
: begin_(static_cast<const unsigned char*>(_begin)),
end_(begin_ + _size) {}

DeferredValidation(const DeferredValidation&) = delete;
DeferredValidation& operator=(const DeferredValidation&) = delete;

/// Makes a DeferredValidation the innermost active one on this thread for
/// as long as the Activation lives.
class Activation {
public:
explicit Activation(DeferredValidation* _d) noexcept : d_(_d) {
auto& h = head();
d_->prev_ = h;
h = d_;
}

~Activation() {
head() = d_->prev_;
d_->prev_ = nullptr;
}

Activation(const Activation&) = delete;
Activation& operator=(const Activation&) = delete;

private:
DeferredValidation* d_;
};

/// The innermost active DeferredValidation on this thread, or nullptr.
static DeferredValidation*& head() noexcept {
static thread_local DeferredValidation* h = nullptr;
return h;
}

/// Returns the innermost active DeferredValidation on this thread whose
/// storage contains _address, or nullptr.
static DeferredValidation* find(const void* _address) noexcept {
for (auto* d = head(); d; d = d->prev_) {
if (d->contains(_address)) {
return d;
}
}
return nullptr;
}

/// Records a Validator whose default value is invalid.
void defer(const void* _address, Error&& _error) {
records_.push_back(Record{_address, std::move(_error)});
}

const std::vector<Record>& records() const noexcept { return records_; }

bool contains(const void* _address) const noexcept {
const auto p = static_cast<const unsigned char*>(_address);
return !std::less<>{}(p, begin_) && std::less<>{}(p, end_);
}

private:
/// The storage of the struct being default-constructed.
const unsigned char* begin_;
const unsigned char* end_;

/// The next outer active DeferredValidation, if any.
DeferredValidation* prev_ = nullptr;

std::vector<Record> records_;
};

} // namespace rfl::internal

#endif
15 changes: 10 additions & 5 deletions include/rfl/parsing/NamedTupleParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -187,23 +187,25 @@ struct NamedTupleParser {
* @param _r The reader to use.
* @param _var The input variable to read from.
* @param _view The view to read into.
* @param _found If not null, receives which fields the input contained.
* Only meaningful if no error is returned.
* @return An optional error.
*/
static std::optional<Error> read_view_with_default(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...>* _view) noexcept {
const R& _r, const InputVarType& _var, NamedTuple<FieldTypes...>* _view,
std::array<bool, size_>* _found = nullptr) noexcept {
if constexpr (_no_field_names) {
auto arr = _r.to_array(_var);
if (!arr) [[unlikely]] {
return arr.error();
}
return read_object_or_array_with_default(_r, *arr, _view);
return read_object_or_array_with_default(_r, *arr, _view, _found);
} else {
auto obj = _r.to_object(_var);
if (!obj) [[unlikely]] {
return obj.error();
}
return read_object_or_array_with_default(_r, *obj, _view);
return read_object_or_array_with_default(_r, *obj, _view, _found);
}
}

Expand Down Expand Up @@ -500,7 +502,7 @@ struct NamedTupleParser {

static std::optional<Error> read_object_or_array_with_default(
const R& _r, const InputObjectOrArrayType& _obj_or_arr,
NamedTupleType* _view) noexcept {
NamedTupleType* _view, std::array<bool, size_>* _found) noexcept {
FieldErrors<ProcessorsType> errors;
const auto reader = ViewReaderWithDefaultType(&_r, _view, &errors);
if constexpr (_no_field_names) {
Expand All @@ -514,6 +516,9 @@ struct NamedTupleParser {
return err;
}
}
if (_found) {
*_found = reader.found();
}
if constexpr (internal::has_default_val_v<NamedTupleType> &&
!internal::default_if_missing_v<ProcessorsType>) {
if (!should_stop_on_field_error<ProcessorsType>(errors)) {
Expand Down
Loading