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/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ reflect-cpp currently supports the following processors:
- `rfl::DurationsAsCount`
- `rfl::EnumNamesOnly`
- `rfl::FailFast`
- `rfl::NoDuplicateKeys`
- `rfl::NoExtraFields`
- `rfl::NoFieldNames`
- `rfl::NoOptionals`
Expand Down Expand Up @@ -366,6 +367,18 @@ Failed to parse field 'color': Invalid enum value: '2'. Must be one of [red, gre
This processor only affects reading. Enum values that cannot be matched to
a declared name are still written as their integer representation.

### `rfl::NoDuplicateKeys`

By default, readers such as `rfl::yaml::read` keep their existing behavior when
an input mapping contains repeated keys. Pass `rfl::NoDuplicateKeys` to reject
duplicate mapping keys and report each repeated key as an error (with its key
source location in YAML):

```cpp
const auto result =
rfl::yaml::read<Config, rfl::NoExtraFields, rfl::NoDuplicateKeys>(yaml_str);
```

### `rfl::NoExtraFields`

When reading an object and the object contains a field that cannot be
Expand Down
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
30 changes: 30 additions & 0 deletions docs/content/supported_formats/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,33 @@ 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` and duplicate mapping keys under `rfl::NoDuplicateKeys` point at the offending key (`exact = true`).
- Missing required fields point at the enclosing mapping or sequence (`exact = false`).

Sequence reading collects errors from all failing elements (unless `rfl::FailFast` is passed), matching object field error aggregation. Pass `rfl::NoDuplicateKeys` to reject duplicate mapping keys; recursive YAML aliases are always rejected and reported through `rfl::Result`.

## Post-parse source locations (`rfl::SourceMap`)

If you run semantic validation after deserialization succeeds, you can pass a `rfl::SourceMap*` to `rfl::yaml::read` or `rfl::yaml::load` to retain a map from parsed paths (using the same `rfl::ErrorDetail::PathSegment` representation as `Error::details()`) to `rfl::SourceLocation`:

```cpp
rfl::SourceMap source_map;
const auto result = rfl::yaml::read<Config>(yaml_str, &source_map);
if (result) {
// Exact value location of config.servers[1].port:
const auto loc = source_map.find({"servers", size_t{1}, "port"});
// Key location of config.servers[1].port:
const auto key_loc = source_map.find_key({"servers", size_t{1}, "port"});
// Nearest existing ancestor (exact = false) for omitted optional fields:
const auto fallback = source_map.find_nearest({"servers", size_t{1}, "tls"});
}
```

If reading fails, `source_map` is cleared. Passing `nullptr` (or calling the overloads without `SourceMap*`) avoids building the map.


1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "rfl/Hex.hpp"
#include "rfl/Literal.hpp"
#include "rfl/NamedTuple.hpp"
#include "rfl/NoDuplicateKeys.hpp"
#include "rfl/NoExtraFields.hpp"
#include "rfl/NoFieldNames.hpp"
#include "rfl/NoOptionals.hpp"
Expand Down
24 changes: 24 additions & 0 deletions include/rfl/NoDuplicateKeys.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#ifndef RFL_NODUPLICATEKEYS_HPP_
#define RFL_NODUPLICATEKEYS_HPP_

#include <utility>

namespace rfl {

/// Reject duplicate keys in input mappings/objects for readers that support
/// duplicate-key detection (such as YAML).
///
/// By default, duplicate mapping keys keep existing reader behavior for
/// backwards compatibility. Pass rfl::NoDuplicateKeys to report each repeated
/// key as an error:
/// rfl::yaml::read<MyStruct, rfl::NoExtraFields, rfl::NoDuplicateKeys>(yaml)
struct NoDuplicateKeys {
template <class StructType>
static auto process(auto&& _named_tuple) {
return std::forward<decltype(_named_tuple)>(_named_tuple);
}
};

} // namespace rfl

#endif
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
140 changes: 140 additions & 0 deletions include/rfl/SourceMap.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#ifndef RFL_SOURCEMAP_HPP_
#define RFL_SOURCEMAP_HPP_

#include <cstddef>
#include <initializer_list>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <utility>

#include "Result.hpp"
#include "common.hpp"

namespace rfl {

/// Maps parsed field/element paths (matching rfl::ErrorDetail::path) to their
/// source locations in the input document, enabling post-parse semantic
/// diagnostics to report line and column numbers.
class RFL_API SourceMap {
struct Impl;

public:
using PathSegment = ErrorDetail::PathSegment;

/// Source locations recorded for a single node in the input document.
struct Entry {
/// Location of the node's value (1-based line and column).
std::optional<SourceLocation> value = std::nullopt;

/// Location of the mapping key introducing this node, if it is a mapping
/// field; std::nullopt for root nodes and sequence elements.
std::optional<SourceLocation> key = std::nullopt;

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

class Builder;

/// Opaque handle referencing a node owned by a SourceMap::Builder.
class NodeId {
public:
bool operator==(const NodeId&) const = default;

private:
friend class Builder;
explicit constexpr NodeId(const size_t _index) noexcept : index_(_index) {}
size_t index_;
};

/// Bounds-safe builder for constructing a SourceMap tree.
class RFL_API Builder {
public:
Builder();
explicit Builder(const Entry& _root);
~Builder();
Builder(Builder&& _other) noexcept;
Builder& operator=(Builder&& _other) noexcept;
Builder(const Builder&) = delete;
Builder& operator=(const Builder&) = delete;

/// Returns the NodeId of the root node.
NodeId root() const noexcept;

/// Adds a named field child under _parent and returns its NodeId.
/// If a field with the same name already exists under _parent, the first
/// occurrence is preserved.
NodeId add_field(NodeId _parent, std::string _name, const Entry& _entry);

/// Appends a sequence element child under _parent and returns its NodeId.
NodeId add_element(NodeId _parent, const Entry& _entry);

/// Finalizes construction and returns the resulting SourceMap.
SourceMap build() && noexcept;

private:
std::unique_ptr<Impl> impl_;
};

SourceMap() noexcept;
~SourceMap();
SourceMap(const SourceMap& _other);
SourceMap(SourceMap&& _other) noexcept;
SourceMap& operator=(const SourceMap& _other);
SourceMap& operator=(SourceMap&& _other) noexcept;

/// Returns true if no source nodes have been recorded.
bool empty() const noexcept;

/// Clears all recorded source locations.
void clear() noexcept;

/// Looks up the full Entry (value and key locations) for an exact path.
std::optional<Entry> find_entry(std::span<const PathSegment> _path) const;

std::optional<Entry> find_entry(
std::initializer_list<PathSegment> _path) const {
return find_entry(std::span<const PathSegment>(_path.begin(), _path.size()));
}

/// Looks up the value SourceLocation for an exact path.
std::optional<SourceLocation> find(std::span<const PathSegment> _path) const;

std::optional<SourceLocation> find(
std::initializer_list<PathSegment> _path) const {
return find(std::span<const PathSegment>(_path.begin(), _path.size()));
}

/// Looks up the mapping key SourceLocation for an exact path.
std::optional<SourceLocation> find_key(
std::span<const PathSegment> _path) const;

std::optional<SourceLocation> find_key(
std::initializer_list<PathSegment> _path) const {
return find_key(std::span<const PathSegment>(_path.begin(), _path.size()));
}

/// Looks up the SourceLocation for _path, falling back to the deepest
/// existing ancestor with exact = false if _path is not present in the
/// input (for example, an omitted optional or defaulted field).
std::optional<SourceLocation> find_nearest(
std::span<const PathSegment> _path) const;

std::optional<SourceLocation> find_nearest(
std::initializer_list<PathSegment> _path) const {
return find_nearest(
std::span<const PathSegment>(_path.begin(), _path.size()));
}

bool operator==(const SourceMap& _other) const;

private:
explicit SourceMap(std::unique_ptr<Impl> _impl) noexcept;

std::unique_ptr<Impl> impl_;
};

} // namespace rfl

#endif
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
27 changes: 27 additions & 0 deletions include/rfl/internal/no_duplicate_keys_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#ifndef RFL_INTERNAL_NODUPLICATEKEYS_HPP_
#define RFL_INTERNAL_NODUPLICATEKEYS_HPP_

#include <type_traits>

#include "../NoDuplicateKeys.hpp"
#include "../Processors.hpp"

namespace rfl::internal {

template <class T>
struct no_duplicate_keys : std::false_type {};

template <>
struct no_duplicate_keys<NoDuplicateKeys> : std::true_type {};

template <class... Ps>
struct no_duplicate_keys<Processors<Ps...>>
: std::bool_constant<(no_duplicate_keys<Ps>::value || ...)> {};

template <class T>
inline constexpr bool no_duplicate_keys_v =
no_duplicate_keys<std::remove_cvref_t<T>>::value;

} // namespace rfl::internal

#endif
Loading