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
13 changes: 13 additions & 0 deletions docs/content/result.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,16 @@ Found 2 errors:
If your program needs to know where each failure occurred, for instance to show each message next to the right input in a form, use `.details()` instead. It returns a `std::vector<rfl::ErrorDetail>` with one entry per failure:

```cpp
struct SourceLocation {
// 1-based line and column in the source text.
size_t line = 0;
size_t column = 0;

// True if the location points at the offending value or key; false if it
// points at an enclosing node, such as the parent mapping of a missing field.
bool exact = true;
};

struct ErrorDetail {
using PathSegment = std::variant<std::string, size_t>;

Expand All @@ -154,6 +164,9 @@ struct ErrorDetail {

// The message, without the "Failed to parse field '...': " prefixes.
std::string message;

// Source position when the reader tracks source locations (such as YAML).
std::optional<SourceLocation> location = std::nullopt;
};
```

Expand Down
11 changes: 11 additions & 0 deletions docs/content/supported_formats/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,14 @@ rfl::Result<Person> Person::from_yaml_obj(const YAMLVar& _obj) {
This will force the compiler to only compile the YAML parsing when the
source file is compiled.

## Error reporting

`rfl::yaml::read` populates `ErrorDetail::location` (`rfl::SourceLocation{line, column, exact}`) with 1-based line and column numbers from `yaml-cpp`:

- Type conversion, validator, enum, and syntax errors point at the offending value (`exact = true`).
- Unknown fields under `rfl::NoExtraFields` point at the offending key (`exact = true`).
- Missing required fields point at the enclosing mapping or sequence (`exact = false`).

Recursive YAML aliases are rejected and reported through `rfl::Result`.


1 change: 1 addition & 0 deletions include/rfl/Result.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace rfl {

using Error = rfl::internal::Error;
using ErrorDetail = rfl::internal::ErrorDetail;
using SourceLocation = rfl::internal::SourceLocation;

/// To be returned when there is nothing to return, but there might be an error.
struct Nothing {};
Expand Down
36 changes: 36 additions & 0 deletions include/rfl/internal/Error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
Expand All @@ -12,6 +13,23 @@

namespace rfl::internal {

/// Describes the position of a failure in the source text, for formats that
/// track source locations (such as YAML).
struct SourceLocation {
/// 1-based line number in the source text.
size_t line = 0;

/// 1-based column number in the source text.
size_t column = 0;

/// True if the location points directly at the offending node (for example,
/// a bad value, an unknown key, or a duplicate key). False if it points at
/// an enclosing node, such as the parent mapping of a missing field.
bool exact = true;

bool operator==(const SourceLocation&) const = default;
};

/// Describes a single failure contained in an Error: where it occurred and
/// what went wrong.
struct ErrorDetail {
Expand All @@ -28,6 +46,10 @@ struct ErrorDetail {
/// '...': " prefixes that Error::what() contains for every level of nesting.
std::string message;

/// The position of the failure in the source text, if the reader tracks
/// source locations.
std::optional<SourceLocation> location = std::nullopt;

bool operator==(const ErrorDetail&) const = default;
};

Expand Down Expand Up @@ -101,6 +123,20 @@ class Error {
return std::move(*details_);
}

/// Returns true if explicit details are present and every detail already
/// carries a source location.
bool has_all_source_locations() const noexcept {
if (!details_.has_value()) {
return false;
}
for (const auto& detail : *details_) {
if (!detail.location.has_value()) {
return false;
}
}
return true;
}

private:
/// Either nothing or a heap-allocated vector of details, deep-copied along
/// with the Error. Holding nothing is the common case: it means that the
Expand Down
7 changes: 4 additions & 3 deletions include/rfl/parsing/ArrayReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ class ArrayReader {
*/
std::optional<Error> read(const InputVarType& _var) const {
if (num_set_ == size_) {
return Error("Expected " + std::to_string(size_) +
" elements, got at least " + std::to_string(size_ + 1) +
".");
return attach_source_location(
*r_, _var,
Error("Expected " + std::to_string(size_) +
" elements, got at least " + std::to_string(size_ + 1) + "."));
}
auto res =
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(*r_, _var);
Expand Down
6 changes: 4 additions & 2 deletions include/rfl/parsing/FieldVariantParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "FieldVariantReader.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "wrap_error.hpp"

namespace rfl::parsing {

Expand Down Expand Up @@ -53,9 +54,10 @@ struct FieldVariantParser {
return error(std::move(*err));
}
if (!field_variant) {
return error(
return error(make_error_with_location(
"Could not parse: Expected the object to have "
"exactly one field, but found none.");
"exactly one field, but found none.",
get_source_location(_r, _obj)));
}
return std::move(*field_variant);
};
Expand Down
29 changes: 23 additions & 6 deletions include/rfl/parsing/FieldVariantReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "../internal/is_array.hpp"
#include "../internal/nth_element_t.hpp"
#include "Parser_base.hpp"
#include "wrap_error.hpp"

namespace rfl::parsing {

Expand Down Expand Up @@ -43,10 +44,24 @@ class FieldVariantReader {
*/
void read(const std::string_view& _disc_value,
const InputVarType& _var) const noexcept {
read(_disc_value, _var, std::nullopt);
}

/**
* @brief Reads a field from the input, with an optional source location for
* the key.
*
* @param _disc_value The name of the field.
* @param _var The input variable to read from.
* @param _key_loc The source location of the key, if available.
*/
void read(const std::string_view& _disc_value, const InputVarType& _var,
const std::optional<SourceLocation>& _key_loc) const noexcept {
if (*field_variant_) {
*field_variant_ = error(
*field_variant_ = error(make_error_with_location(
"Could not parse rfl::Variant: Expected the object to have "
"exactly one field, but found more than one.");
"exactly one field, but found more than one.",
_key_loc ? _key_loc : get_source_location(*r_, _var)));
return;
}
try_matching_fields(
Expand All @@ -57,7 +72,8 @@ class FieldVariantReader {
stream << "Could not parse rfl::Variant, could not match field named "
"'"
<< _disc_value << "'.";
*field_variant_ = error(stream.str());
*field_variant_ = error(make_error_with_location(
stream.str(), _key_loc ? _key_loc : get_source_location(*r_, _var)));
}
}

Expand All @@ -80,11 +96,12 @@ class FieldVariantReader {
const auto to_variant = [](ValueType&& _val) {
return rfl::Variant<FieldTypes...>(FieldType(std::move(_val)));
};
const auto embellish_error = [&](const Error& _e) {
const auto embellish_error = [&](Error _e) {
std::stringstream stream;
stream << "Could not parse rfl::Variant with field '"
<< std::string(_disc_value) << "': " << _e.what();
return Error(stream.str());
<< std::string(_disc_value) << "': ";
return wrap_error(stream.str(), std::string(_disc_value),
std::move(_e));
};
*field_variant_ = Parser<R, W, ValueType, ProcessorsType>::read(*r_, _var)
.transform(to_variant)
Expand Down
26 changes: 23 additions & 3 deletions include/rfl/parsing/MapReader.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef RFL_PARSING_MAPREADER_HPP_
#define RFL_PARSING_MAPREADER_HPP_

#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
Expand Down Expand Up @@ -44,7 +45,20 @@ class MapReader {
*/
void read(const std::string_view& _name,
const InputVarType& _var) const noexcept {
auto res = get_pair(_name, _var);
read(_name, _var, std::nullopt);
}

/**
* @brief Reads a single field into the map, with an optional source location
* for the key.
*
* @param _name The name of the field.
* @param _var The input variable to read from.
* @param _key_loc The source location of the key, if available.
*/
void read(const std::string_view& _name, const InputVarType& _var,
const std::optional<SourceLocation>& _key_loc) const noexcept {
auto res = get_pair(_name, _var, _key_loc);
if (res) {
map_->emplace(std::move(*res));
} else {
Expand Down Expand Up @@ -104,10 +118,16 @@ class MapReader {
}

Result<std::pair<KeyType, ValueType>> get_pair(
const std::string_view& _name, const InputVarType& _var) const noexcept {
const std::string_view& _name, const InputVarType& _var,
const std::optional<SourceLocation>& _key_loc) const noexcept {
const auto to_pair = [&](ValueType&& _val) {
auto pair = std::make_pair(std::string(_name), std::move(_val));
return make_key(std::move(pair));
auto key_res = make_key(std::move(pair));
if (!key_res && _key_loc) {
return Result<std::pair<KeyType, ValueType>>(error(
attach_source_location(_key_loc, std::move(key_res).error())));
}
return key_res;
};
return Parser<R, W, std::remove_cvref_t<ValueType>, ProcessorsType>::read(
*r_, _var)
Expand Down
22 changes: 14 additions & 8 deletions include/rfl/parsing/NamedTupleParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ struct NamedTupleParser {
/// Generates error messages for when fields are missing.
template <int _i>
static RFL_ALWAYS_INLINE void handle_one_missing_field(
const R& _r, const InputObjectOrArrayType& _obj_or_arr,
const std::array<bool, size_>& _found, const NamedTupleType& _view,
std::array<bool, size_>* _set, FieldErrors<ProcessorsType>* _errors,
const bool _value_initialize_default_vals) noexcept {
Expand Down Expand Up @@ -392,7 +393,8 @@ struct NamedTupleParser {
"Field named '" + std::string(current_name) +
"' not found, and its default value could not be "
"constructed: " +
e.what()));
e.what(),
get_source_location(_r, _obj_or_arr, /*_exact=*/false)));
return;
}
std::get<_i>(*_set) = true;
Expand All @@ -408,8 +410,9 @@ struct NamedTupleParser {
std::stringstream stream;
stream << "Field named '" << std::string(current_name)
<< "' not found.";
_errors->emplace_back(
make_nested_error(std::string(current_name), stream.str()));
_errors->emplace_back(make_nested_error(
std::string(current_name), stream.str(),
get_source_location(_r, _obj_or_arr, /*_exact=*/false)));
return;
}

Expand All @@ -434,7 +437,8 @@ struct NamedTupleParser {
"Field named '" + std::string(current_name) +
"' not found, and its default value could not be "
"constructed: " +
e.what()));
e.what(),
get_source_location(_r, _obj_or_arr, /*_exact=*/false)));
return;
}
}
Expand All @@ -456,12 +460,13 @@ struct NamedTupleParser {
/// Generates error messages for when fields are missing.
template <int... _is>
static RFL_ALWAYS_INLINE void handle_missing_fields(
const R& _r, const InputObjectOrArrayType& _obj_or_arr,
const std::array<bool, size_>& _found, const NamedTupleType& _view,
std::array<bool, size_>* _set, FieldErrors<ProcessorsType>* _errors,
const bool _value_initialize_default_vals,
std::integer_sequence<int, _is...>) noexcept {
(handle_one_missing_field<_is>(_found, _view, _set, _errors,
_value_initialize_default_vals),
(handle_one_missing_field<_is>(_r, _obj_or_arr, _found, _view, _set,
_errors, _value_initialize_default_vals),
...);
}

Expand Down Expand Up @@ -498,7 +503,7 @@ struct NamedTupleParser {
}
}
if (!should_stop_on_field_error<ProcessorsType>(errors)) {
handle_missing_fields(found, *_view, &set, &errors,
handle_missing_fields(_r, _obj_or_arr, found, *_view, &set, &errors,
_value_initialize_default_vals,
std::make_integer_sequence<int, size_>());
}
Expand Down Expand Up @@ -531,7 +536,8 @@ struct NamedTupleParser {
if constexpr (internal::has_default_val_v<NamedTupleType> &&
!internal::default_if_missing_v<ProcessorsType>) {
if (!should_stop_on_field_error<ProcessorsType>(errors)) {
handle_missing_fields(reader.found(), *_view, nullptr, &errors,
handle_missing_fields(_r, _obj_or_arr, reader.found(), *_view, nullptr,
&errors,
/*_value_initialize_default_vals=*/false,
std::make_integer_sequence<int, size_>());
}
Expand Down
4 changes: 3 additions & 1 deletion include/rfl/parsing/ParserArray.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "Parser_base.hpp"
#include "call_destructors_on_array_where_necessary.hpp"
#include "schema/Type.hpp"
#include "wrap_error.hpp"

namespace rfl::parsing {

Expand Down Expand Up @@ -71,7 +72,8 @@ struct ParserArray {
err = array_reader.check_size();
if (err) {
call_destructors_on_array_where_necessary(array_reader.num_set(), ptr);
return error(std::move(*err));
return error(attach_source_location(_r, _var, std::move(*err),
/*_exact=*/false));
}
auto result = Result<std::array<T, _size>>(std::move(*ptr));
call_destructors_on_array_where_necessary(array_reader.num_set(), ptr);
Expand Down
9 changes: 8 additions & 1 deletion include/rfl/parsing/ParserBitset.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../internal/bitset.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "wrap_error.hpp"

namespace rfl::parsing {

Expand All @@ -24,13 +25,19 @@ struct ParserBitset {

static Result<Type> read(const R& _r,
const typename R::InputVarType& _var) noexcept {
return ReprParser::read(_r, _var).and_then([](const auto& _value) {
auto res = ReprParser::read(_r, _var).and_then([](const auto& _value) {
if constexpr (std::is_same_v<Representation, std::string>) {
return internal::bitset_from_string<N>(_value);
} else {
return internal::bitset_from_bytes<N>(_value);
}
});
if constexpr (requires { _r.source_location(_var); }) {
if (!res) [[unlikely]] {
return error(attach_source_location(_r, _var, std::move(res).error()));
}
}
return res;
}

template <class P>
Expand Down
Loading