Skip to content
Open
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,13 @@ int main(int argc, char* argv[]) {

Field names are automatically converted from `snake_case` to `kebab-case` (`host_name` matches `--host-name`).

`rfl::cli::read` also takes a range of arguments, such as a `std::vector<std::string>`, and parses every element ([details](https://munich-data-engineering.github.io/reflect-cpp/cli#passing-a-sequence-of-arguments)):

```cpp
const std::vector<std::string> args = {"--host-name=localhost", "--port=8080"};
const auto config = rfl::cli::read<Config>(args);
```

You can mark fields as positional arguments with `rfl::Positional<T>` and add single-character aliases with `rfl::Short<"x", T>`:

```cpp
Expand Down
36 changes: 24 additions & 12 deletions docs/content/default_val.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,41 +52,53 @@ const auto homer = rfl::json::read<Person, rfl::NoFieldNames>(R"(["Homer"])").va
// homer.town == ""
```

## All fields need a valid default value
## Fields 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.
A struct that contains an `rfl::DefaultVal` is default-constructed before it is read, so that the fields missing from the input keep their default values. The fields found in the input are then replaced by the values read from it.

This matters when the default value of a field's type is not valid, for instance when the field has a validator:
Some fields have no valid default value, for instance a validator that an empty vector does not satisfy:

```cpp
using Foods = rfl::Validator<std::vector<std::string>, rfl::Size<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;
};

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

`Person{}` throws, but `read` then constructs the struct again with the check of such a validator deferred until the input has been read. If `favorite_foods` is in the input, its invalid default value has been replaced. If it is missing, you get the error `Field named 'favorite_foods' not found.` Outside of `read`, `Person{}` still throws.

A field whose default value is invalid must not be missing, even where a missing field would otherwise get its default value, that is, for an `rfl::DefaultVal` or with the `rfl::DefaultIfMissing` processor:

```
Field named 'favorite_foods' not found, and its default value is invalid: Size validation failed: Value expected to be greater than or equal to 1, but got 0.
```

An empty vector does not satisfy `rfl::Size<rfl::Minimum<1>>`, so `Person{}` throws an exception and you get the following error:
While the struct is constructed again, every validator that is default-constructed on the same thread keeps its invalid value instead of throwing, wherever it is: in a field, in a nested struct or container, in a temporary, or in a copy such as `rfl::DefaultVal<Foods> other_foods = favorite_foods;`. After reading, `read` checks the validators inside every field that is missing from the input, and fails with the error above if one of them is invalid. `read` looks into structs, containers, `std::optional`, smart pointers, variants, tuples, the wrappers of reflect-cpp and classes with a `reflection()` method. If a missing field holds a class it cannot look into, you get the error `Field named '...' not found, and its default value could not be checked: ...`.

If the struct holds fewer invalid validators than were default-constructed, an invalid value has been used up on the way, for instance a temporary in `int port = Port().value();`, or it is inside a class that `read` cannot look into. A copy can make up for a used-up value, though, and a default member initializer that reads a validator, as in `int count = favorite_foods->size();`, gets its invalid value without an error. A default member initializer that catches the exception of such a validator in order to fall back to another value gets no exception while validation is deferred, so the field must then be in the input. The struct cannot be read, and you get the error below, if an invalid value has been used up, or if `Person{}` throws for another reason, including a validator that is given an invalid value explicitly (as in `Foods favorite_foods = std::vector<std::string>();`):

```
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.
```

To avoid this, give the field a valid default value:
In all of these cases, you can give the field a valid default value:

```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"});
Foods favorite_foods = std::vector<std::string>({"none"});
};
```

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 field is still required. The default value is only used for a missing field if you pass the `rfl::DefaultIfMissing` processor.

All of this applies to every struct that is read with the `rfl::DefaultIfMissing` processor, whether it contains an `rfl::DefaultVal` or not. In JSON schemas, structs with `rfl::DefaultVal` keep their valid default values; any field whose default value holds an invalid validator or a class that cannot be checked gets no default value and is listed as required (unless `rfl::DefaultIfMissing` omits `required` for the whole schema). If an invalid value has been used up, the schema keeps no default values and marks those fields required. If `Person{}` throws for another reason, `rfl::json::to_schema<Person>()` throws that exception. If such a struct is nested inside another struct, the program ends with `std::terminate`, as it does without this feature.

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<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.

## When to use

Expand Down
9 changes: 6 additions & 3 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,12 @@ 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`.
Note that the struct is default-constructed before it is read. A field
whose default value is invalid, such as a validator that the default value
of its type does not satisfy, can be read, but it must not be missing: you
get the error `Field named '...' not found, and its default value is
invalid: ...`. The documentation on `rfl::DefaultVal` explains this and the
cases in which such a struct cannot be read at all.

### `rfl::DurationsAsCount`

Expand Down
43 changes: 42 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ breadcrumbs: true

# rfl::cli — Command-Line Argument Parser

Parse `argc`/`argv` into any reflectable struct via `rfl::cli::read<T>(argc, argv)`.
Parse `argc`/`argv` into any reflectable struct via `rfl::cli::read<T>(argc, argv)`,
or a sequence of arguments via `rfl::cli::read<T>(args)`.

## Usage

Expand All @@ -28,6 +29,46 @@ int main(int argc, char* argv[]) {
Field names undergo automatic `snake_case` -> `kebab-case` conversion:
`host_name` matches `--host-name`.

`argv` may be `char*[]` or `const char*[]`. `argv[0]` is the program name
and is skipped.

## Passing a sequence of arguments

When the arguments do not come straight from `main`, pass them as a range,
such as `std::vector<std::string>`, `std::vector<std::string_view>`,
`std::span<char*>` or `const char* const[]`, or as a braced list of strings.
Ranges of wide strings (`std::vector<std::wstring>`, `const wchar_t*[]`) are
converted to UTF-8. A null pointer in a range or array of pointers is an
error. A braced list holds `std::string_view`s, so a null pointer in it is
undefined behaviour; pass a `std::vector` or an array of pointers instead.

The parser keeps a `std::string_view` to each narrow argument, so a range of
narrow strings must be a `std::forward_range` of lvalue strings, pointers or
`std::string_view`s. `std::views::istream<std::string>`, or a view that
yields temporary `std::string`s, does not compile; copy the arguments into a
`std::vector<std::string>` first.

**Every element is parsed: unlike `read(argc, argv)`, the first one is not
skipped as the program name.** So `std::span(argv, argc)` would read the
program name as an argument (for a struct with a `rfl::Positional` field, as
its first value).

```cpp
// ./app serve --host-name=localhost --port=8080 --verbose --tags=a,b
int main(int argc, char* argv[]) {
// argv[0] is the program name, argv[1] a subcommand the program handles.
const auto rest = std::span(argv, argc).subspan(std::min(argc, 2));
const auto result = rfl::cli::read<Config>(rest);
}

// Arguments from somewhere other than main:
const std::vector<std::string> args = {"--host-name=localhost", "--port=8080",
"--verbose", "--tags=a,b"};
const auto result = rfl::cli::read<Config>(args);
```

`rfl::cli::parse_argv` has the same overloads.

## Positional arguments

Wrap a field with `rfl::Positional<T>` to accept it as a bare (non-flag) argument:
Expand Down
44 changes: 42 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/DeferredDefaults.hpp"
#include "internal/HasValidation.hpp"
#include "internal/cold.hpp"

namespace rfl {

Expand Down Expand Up @@ -52,8 +54,10 @@ 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 parser is default-constructing a struct to read into, see
/// internal::DeferredDefaults.
Validator() : value_(valid_or_deferred()) {}

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

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

/// Returns the validated default value. If it is invalid, this throws,
/// unless the parser defers its validation, see internal::DeferredDefaults.
static T valid_or_deferred() {
if constexpr (std::is_copy_constructible_v<T>) {
auto val = T();
auto res = ValidationType::validate(val);
if (!res) [[unlikely]] {
return deferred_or_throw(res.error(), std::move(val));
}
return *std::move(res);
} else {
const auto saved_num = internal::DeferredDefaults::current_num();
auto res = ValidationType::validate(T());
if (!res) [[unlikely]] {
return deferred_or_throw_reconstruct(res.error(), saved_num);
}
return *std::move(res);
}
}

RFL_COLD static T deferred_or_throw(const Error& _err, T&& _val) {
if (!internal::DeferredDefaults::defer(_err)) {
Result<T>(error(_err)).value();
}
return std::move(_val);
}

RFL_COLD static T deferred_or_throw_reconstruct(const Error& _err,
size_t _saved_num) {
internal::DeferredDefaults::reset_num(_saved_num);
if (!internal::DeferredDefaults::defer(_err)) {
Result<T>(error(_err)).value();
}
return T();
}

/// 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
Loading