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
14 changes: 14 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 @@ -368,6 +369,19 @@ 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, `rfl::yaml::read` keeps its 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). Passing `rfl::NoDuplicateKeys` to a reader that does not support
duplicate-key detection fails at compile time (`static_assert`):

```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
4 changes: 2 additions & 2 deletions docs/content/supported_formats/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ source file is compiled.
`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`).
- 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. Recursive YAML aliases are rejected and reported through `rfl::Result`.
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`.


1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include "rfl/ImplicitValue.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
36 changes: 36 additions & 0 deletions include/rfl/internal/no_duplicate_keys_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#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;

template <class R>
inline constexpr bool reader_supports_no_duplicate_keys_v = []() constexpr {
if constexpr (requires { R::supports_no_duplicate_keys; }) {
return static_cast<bool>(R::supports_no_duplicate_keys);
} else {
return false;
}
}();

} // namespace rfl::internal

#endif
7 changes: 7 additions & 0 deletions include/rfl/parsing/FieldVariantReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/nth_element_t.hpp"
#include "Parser_base.hpp"
#include "wrap_error.hpp"
Expand All @@ -24,6 +25,12 @@ class FieldVariantReader {
using ResultType = Result<FieldVariantType>;

public:
static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

/**
* @brief Constructor.
*
Expand Down
15 changes: 15 additions & 0 deletions include/rfl/parsing/MapReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/has_reflection_type_v.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "Parser_base.hpp"
#include "wrap_error.hpp"

Expand All @@ -25,6 +26,12 @@ class MapReader {
std::remove_cvref_t<typename MapType::value_type::second_type>;

public:
static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

/**
* @brief Constructor.
*
Expand Down Expand Up @@ -66,6 +73,14 @@ class MapReader {
}
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const noexcept {
errors_->emplace_back(std::move(_err));
}

private:
template <class T>
Result<T> key_to_numeric(auto& _pair) const noexcept {
Expand Down
4 changes: 4 additions & 0 deletions include/rfl/parsing/Parser_default.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include "../internal/is_implicit_value.hpp"
#include "../internal/is_literal.hpp"
#include "../internal/is_validator.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/processed_t.hpp"
#include "../internal/ptr_cast.hpp"
#include "../internal/to_ptr_named_tuple.hpp"
Expand Down Expand Up @@ -94,6 +95,9 @@ struct Parser {
* @return A Result containing the parsed value or an error.
*/
static RFL_ALWAYS_INLINE auto read(const R& _r, const InputVarType& _var) {
static_assert(!internal::no_duplicate_keys_v<ProcessorsType> ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");
if constexpr (requires { _r.source_location(_var); }) {
auto res = read_impl(_r, _var);
if (!res) [[unlikely]] {
Expand Down
16 changes: 16 additions & 0 deletions include/rfl/parsing/ViewReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "../Tuple.hpp"
#include "../internal/always_inline.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/no_extra_fields_v.hpp"
#include "FieldErrors.hpp"
#include "Parser_base.hpp"
Expand All @@ -26,6 +27,11 @@ class ViewReader {
using InputVarType = typename R::InputVarType;
using ViewType = _ViewType;

static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");
static constexpr size_t size_ = ViewType::size();

/**
Expand Down Expand Up @@ -69,6 +75,16 @@ class ViewReader {
set_, std::make_integer_sequence<int, size_>());
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const {
if (should_stop_on_field_error<ProcessorsType>(*errors_)) return;
errors_->reserve(size_);
errors_->emplace_back(std::move(_err));
}

/**
* @brief Reads a single field into the view.
*
Expand Down
15 changes: 15 additions & 0 deletions include/rfl/parsing/ViewReaderWithDefault.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "../Ref.hpp"
#include "../Tuple.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/no_extra_fields_v.hpp"
#include "FieldErrors.hpp"
#include "Parser_base.hpp"
Expand All @@ -25,6 +26,11 @@ class ViewReaderWithDefault {
using InputVarType = typename R::InputVarType;
using ViewType = _ViewType;

static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");
static constexpr size_t size_ = ViewType::size();

/**
Expand Down Expand Up @@ -75,6 +81,15 @@ class ViewReaderWithDefault {
std::make_integer_sequence<int, size_>());
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const {
if (should_stop_on_field_error<ProcessorsType>(*errors_)) return;
errors_->emplace_back(std::move(_err));
}

/**
* @brief Returns the size of the view.
*
Expand Down
77 changes: 63 additions & 14 deletions include/rfl/yaml/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

Expand Down Expand Up @@ -63,6 +64,9 @@ struct Reader {
static constexpr bool has_custom_constructor =
(requires(InputVarType var) { T::from_yaml_obj(var); });

/// @brief Advertises support for the opt-in rfl::NoDuplicateKeys processor.
static constexpr bool supports_no_duplicate_keys = true;

/// @brief RAII guard tracking ancestor YAML nodes on the current thread to
/// reject cyclic aliases while keeping const Reader instances thread-safe and
/// allowing non-cyclic (DAG) alias reuse.
Expand Down Expand Up @@ -280,25 +284,61 @@ struct Reader {
if (guard.is_cycle()) {
return make_error("Recursive YAML alias detected.", _obj.node_);
}
for (const auto& p : _obj.node_) {
std::string k;
try {
k = p.first.as<std::string>();
} catch (const std::exception&) {
continue;
}
const auto key_loc = node_location(p.first);
const auto dispatch_entry = [&](const std::string& _k,
const YAML::Node& _val,
const std::optional<SourceLocation>&
_key_loc) {
if constexpr (requires {
_object_reader.read(std::string_view(k),
InputVarType(p.second), key_loc);
_object_reader.read(std::string_view(_k),
InputVarType(_val), _key_loc);
}) {
_object_reader.read(std::string_view(k), InputVarType(p.second),
key_loc);
_object_reader.read(std::string_view(_k), InputVarType(_val), _key_loc);
} else {
_object_reader.read(std::string_view(k), InputVarType(p.second));
_object_reader.read(std::string_view(_k), InputVarType(_val));
}
};
if constexpr (is_no_duplicate_keys<ObjectReader>()) {
std::unordered_set<std::string> seen_keys;
seen_keys.reserve(_obj.node_.size());
std::vector<Error> duplicate_errors;
for (const auto& p : _obj.node_) {
std::string k;
try {
k = p.first.as<std::string>();
} catch (const std::exception&) {
continue;
}
const auto key_loc = node_location(p.first);
if (!seen_keys.insert(k).second) {
auto dup_err = parsing::make_nested_error(
k, "Duplicate key '" + k + "'.", key_loc);
if constexpr (requires {
_object_reader.add_error(std::move(dup_err));
}) {
_object_reader.add_error(std::move(dup_err));
} else {
duplicate_errors.emplace_back(std::move(dup_err));
}
continue;
}
dispatch_entry(k, p.second, key_loc);
}
if (!duplicate_errors.empty()) {
return parsing::to_single_error(std::move(duplicate_errors));
}
return std::nullopt;
} else {
for (const auto& p : _obj.node_) {
std::string k;
try {
k = p.first.as<std::string>();
} catch (const std::exception&) {
continue;
}
dispatch_entry(k, p.second, node_location(p.first));
}
return std::nullopt;
}
return std::nullopt;
}

/// @brief Converts a YAMLInputVar to a YAMLInputObject if it is a mapping.
Expand Down Expand Up @@ -343,6 +383,15 @@ struct Reader {
}
}

template <class ObjectReader>
static constexpr bool is_no_duplicate_keys() noexcept {
if constexpr (requires { ObjectReader::no_duplicate_keys; }) {
return ObjectReader::no_duplicate_keys;
} else {
return false;
}
}

/// @brief The YAML document as a string view, used for context and error
/// reporting.
std::string_view yaml_str_;
Expand Down
Loading