From e8c7337bf04d82e30cad221c1453ba6d31ce6feb Mon Sep 17 00:00:00 2001 From: clockblocker Date: Wed, 25 Nov 2026 12:09:39 +0100 Subject: [PATCH] Add opt-in rfl::NoDuplicateKeys processor for YAML duplicate mapping keys Keep existing default duplicate-key behavior intact for backwards compatibility, and add an opt-in rfl::NoDuplicateKeys processor (matching rfl::NoExtraFields and rfl::EnumNamesOnly). When rfl::NoDuplicateKeys is passed, rfl::yaml::Reader::read_object tracks seen keys per mapping and reports each repeated key as "Duplicate key ''." at the repeated key's source location, aggregated alongside other field errors via add_error() (and honoring rfl::FailFast). --- docs/content/processors.md | 14 ++ docs/content/supported_formats/yaml.md | 4 +- include/rfl.hpp | 1 + include/rfl/NoDuplicateKeys.hpp | 24 +++ include/rfl/internal/no_duplicate_keys_v.hpp | 36 +++++ include/rfl/parsing/FieldVariantReader.hpp | 7 + include/rfl/parsing/MapReader.hpp | 15 ++ include/rfl/parsing/Parser_default.hpp | 4 + include/rfl/parsing/ViewReader.hpp | 16 ++ include/rfl/parsing/ViewReaderWithDefault.hpp | 15 ++ include/rfl/yaml/Reader.hpp | 77 +++++++-- tests/yaml/test_no_duplicate_keys.cpp | 150 ++++++++++++++++++ 12 files changed, 347 insertions(+), 16 deletions(-) create mode 100644 include/rfl/NoDuplicateKeys.hpp create mode 100644 include/rfl/internal/no_duplicate_keys_v.hpp create mode 100644 tests/yaml/test_no_duplicate_keys.cpp diff --git a/docs/content/processors.md b/docs/content/processors.md index d0ff17123..e9e686463 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -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` @@ -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(yaml_str); +``` + ### `rfl::NoExtraFields` When reading an object and the object contains a field that cannot be diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index e49ae8384..586959ffd 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -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`. diff --git a/include/rfl.hpp b/include/rfl.hpp index dc5ace36a..2e1fd17be 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" diff --git a/include/rfl/NoDuplicateKeys.hpp b/include/rfl/NoDuplicateKeys.hpp new file mode 100644 index 000000000..4be908b2c --- /dev/null +++ b/include/rfl/NoDuplicateKeys.hpp @@ -0,0 +1,24 @@ +#ifndef RFL_NODUPLICATEKEYS_HPP_ +#define RFL_NODUPLICATEKEYS_HPP_ + +#include + +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(yaml) +struct NoDuplicateKeys { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/internal/no_duplicate_keys_v.hpp b/include/rfl/internal/no_duplicate_keys_v.hpp new file mode 100644 index 000000000..2979be19d --- /dev/null +++ b/include/rfl/internal/no_duplicate_keys_v.hpp @@ -0,0 +1,36 @@ +#ifndef RFL_INTERNAL_NODUPLICATEKEYS_HPP_ +#define RFL_INTERNAL_NODUPLICATEKEYS_HPP_ + +#include + +#include "../NoDuplicateKeys.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct no_duplicate_keys : std::false_type {}; + +template <> +struct no_duplicate_keys : std::true_type {}; + +template +struct no_duplicate_keys> + : std::bool_constant<(no_duplicate_keys::value || ...)> {}; + +template +inline constexpr bool no_duplicate_keys_v = + no_duplicate_keys>::value; + +template +inline constexpr bool reader_supports_no_duplicate_keys_v = []() constexpr { + if constexpr (requires { R::supports_no_duplicate_keys; }) { + return static_cast(R::supports_no_duplicate_keys); + } else { + return false; + } +}(); + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index c019c6dbe..9c31d73dd 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -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" @@ -24,6 +25,12 @@ class FieldVariantReader { using ResultType = Result; public: + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; + static_assert(!no_duplicate_keys || + internal::reader_supports_no_duplicate_keys_v, + "rfl::NoDuplicateKeys is not supported by this reader."); + /** * @brief Constructor. * diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index 761529378..bbb17ccdf 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -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" @@ -25,6 +26,12 @@ class MapReader { std::remove_cvref_t; public: + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; + static_assert(!no_duplicate_keys || + internal::reader_supports_no_duplicate_keys_v, + "rfl::NoDuplicateKeys is not supported by this reader."); + /** * @brief Constructor. * @@ -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 Result key_to_numeric(auto& _pair) const noexcept { diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 1ee574fc4..2276442c1 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -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" @@ -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 || + internal::reader_supports_no_duplicate_keys_v, + "rfl::NoDuplicateKeys is not supported by this reader."); if constexpr (requires { _r.source_location(_var); }) { auto res = read_impl(_r, _var); if (!res) [[unlikely]] { diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index df2096814..cf1bf6bd4 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -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" @@ -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; + static_assert(!no_duplicate_keys || + internal::reader_supports_no_duplicate_keys_v, + "rfl::NoDuplicateKeys is not supported by this reader."); static constexpr size_t size_ = ViewType::size(); /** @@ -69,6 +75,16 @@ class ViewReader { set_, std::make_integer_sequence()); } + /** + * @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(*errors_)) return; + errors_->reserve(size_); + errors_->emplace_back(std::move(_err)); + } + /** * @brief Reads a single field into the view. * diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index 7330be611..1b6ce80ac 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -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" @@ -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; + static_assert(!no_duplicate_keys || + internal::reader_supports_no_duplicate_keys_v, + "rfl::NoDuplicateKeys is not supported by this reader."); static constexpr size_t size_ = ViewType::size(); /** @@ -75,6 +81,15 @@ class ViewReaderWithDefault { std::make_integer_sequence()); } + /** + * @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(*errors_)) return; + errors_->emplace_back(std::move(_err)); + } + /** * @brief Returns the size of the view. * diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index 4e7c3750b..c1df687c6 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -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. @@ -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(); - } 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& + _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()) { + std::unordered_set seen_keys; + seen_keys.reserve(_obj.node_.size()); + std::vector duplicate_errors; + for (const auto& p : _obj.node_) { + std::string k; + try { + k = p.first.as(); + } 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(); + } 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. @@ -343,6 +383,15 @@ struct Reader { } } + template + 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_; diff --git a/tests/yaml/test_no_duplicate_keys.cpp b/tests/yaml/test_no_duplicate_keys.cpp new file mode 100644 index 000000000..d571f206d --- /dev/null +++ b/tests/yaml/test_no_duplicate_keys.cpp @@ -0,0 +1,150 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_yaml_no_duplicate_keys { + +static_assert(rfl::internal::reader_supports_no_duplicate_keys_v< + rfl::yaml::Reader>); +static_assert(!rfl::internal::reader_supports_no_duplicate_keys_v< + rfl::generic::Reader>); + +using Path = std::vector; + +struct Item { + std::string name; + int code; +}; + +struct Entry { + std::string name; + int code; + int port; +}; + +struct WithDefault { + int code = 0; + std::string name = "default"; +}; + +TEST(yaml, test_duplicate_keys_accepted_by_default_for_backwards_compat) { + const std::string yaml_str = + "- name: a\n" + " code: 1\n" + " code: 2\n"; + + const auto res = rfl::yaml::read>(yaml_str); + ASSERT_TRUE(res) << res.error().what(); + ASSERT_EQ(res->size(), 1u); + EXPECT_EQ((*res)[0].name, "a"); + EXPECT_EQ((*res)[0].code, 1); +} + +TEST(yaml, test_no_duplicate_keys_processor_rejects_repeated_keys) { + const std::string yaml_str = + "- name: a\n" + " code: 1\n" + " code: 2\n"; + + // Without NoExtraFields: duplicate key is rejected at the repeated key. + const auto res1 = + rfl::yaml::read, rfl::NoDuplicateKeys>(yaml_str); + ASSERT_FALSE(res1); + const auto details1 = res1.error().details(); + ASSERT_EQ(details1.size(), 1) << res1.error().what(); + EXPECT_EQ(details1[0].path, (Path{size_t{0}, "code"})); + EXPECT_EQ(details1[0].message, "Duplicate key 'code'."); + EXPECT_EQ(details1[0].location, + (rfl::SourceLocation{.line = 3, .column = 3, .exact = true})); + + // With NoExtraFields + NoDuplicateKeys: reported as duplicate key, NOT + // "Value named 'code' not used." + const auto res2 = + rfl::yaml::read, rfl::NoExtraFields, + rfl::NoDuplicateKeys>(yaml_str); + ASSERT_FALSE(res2); + const auto details2 = res2.error().details(); + ASSERT_EQ(details2.size(), 1) << res2.error().what(); + EXPECT_EQ(details2[0].path, (Path{size_t{0}, "code"})); + EXPECT_EQ(details2[0].message, "Duplicate key 'code'."); + EXPECT_EQ(details2[0].location, + (rfl::SourceLocation{.line = 3, .column = 3, .exact = true})); +} + +TEST(yaml, test_no_duplicate_keys_aggregated_with_other_errors) { + const std::string yaml_str = + "code: 1\n" + "code: 2\n" + "port: bad\n"; + + const auto result = + rfl::yaml::read( + yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 3) << result.error().what(); + + EXPECT_EQ(details[0].path, (Path{"code"})); + EXPECT_EQ(details[0].message, "Duplicate key 'code'."); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 2, .column = 1, .exact = true})); + + EXPECT_EQ(details[1].path, (Path{"port"})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 3, .column = 7, .exact = true})); + + EXPECT_EQ(details[2].path, (Path{"name"})); + EXPECT_EQ(details[2].message, "Field named 'name' not found."); + EXPECT_EQ(details[2].location, + (rfl::SourceLocation{.line = 1, .column = 1, .exact = false})); +} + +TEST(yaml, test_no_duplicate_keys_in_map_default_if_missing_and_fail_fast) { + const std::string map_yaml = + "a: 1\n" + "b: 2\n" + "a: 3\n"; + const auto map_res = + rfl::yaml::read, rfl::NoDuplicateKeys>( + map_yaml); + ASSERT_FALSE(map_res); + const auto map_details = map_res.error().details(); + ASSERT_EQ(map_details.size(), 1) << map_res.error().what(); + EXPECT_EQ(map_details[0].path, (Path{"a"})); + EXPECT_EQ(map_details[0].message, "Duplicate key 'a'."); + EXPECT_EQ(map_details[0].location, + (rfl::SourceLocation{.line = 3, .column = 1, .exact = true})); + + const std::string def_yaml = + "code: 1\n" + "code: 2\n" + "extra: 3\n"; + const auto def_res = + rfl::yaml::read(def_yaml); + ASSERT_FALSE(def_res); + const auto def_details = def_res.error().details(); + ASSERT_EQ(def_details.size(), 2) << def_res.error().what(); + EXPECT_EQ(def_details[0].path, (Path{"code"})); + EXPECT_EQ(def_details[0].message, "Duplicate key 'code'."); + EXPECT_EQ(def_details[0].location, + (rfl::SourceLocation{.line = 2, .column = 1, .exact = true})); + EXPECT_EQ(def_details[1].path, (Path{"extra"})); + EXPECT_EQ(def_details[1].location, + (rfl::SourceLocation{.line = 3, .column = 1, .exact = true})); + + const auto ff_res = + rfl::yaml::read( + std::string("code: 1\ncode: 2\nport: bad\n")); + ASSERT_FALSE(ff_res); + ASSERT_EQ(ff_res.error().details().size(), 1); + EXPECT_EQ(ff_res.error().details()[0].message, "Duplicate key 'code'."); +} + +} // namespace test_yaml_no_duplicate_keys