From d45c23eb1870b22c8b2ffa1290a7e3d4c2606dbb Mon Sep 17 00:00:00 2001 From: clockblocker Date: Wed, 25 Nov 2026 12:14:02 +0100 Subject: [PATCH] Add optional rfl::SourceMap support to rfl::yaml::read and rfl::yaml::load Add an opt-in rfl::SourceMap type mapping ErrorDetail::PathSegment paths to rfl::SourceLocation entries (value and mapping key locations, plus find_nearest fallback to the deepest enclosing ancestor with exact = false). - Move the non-template SourceMap implementation out of the header into src/rfl/SourceMap.cpp (via Pimpl) and keep SourceMap.hpp out of the umbrella rfl.hpp header so non-YAML TUs pay no compile-time cost. - Replace raw node-index mutators with a bounds-safe SourceMap::Builder and opaque SourceMap::NodeId. - Expose RFL_API rfl::yaml::build_source_map(const YAML::Node&) in src/rfl/yaml/Reader.cpp, reusing Reader::ActiveNodeGuard for cycle safety. - Add SourceMap* overloads for rfl::yaml::read and rfl::yaml::load that clear the map up front and populate it on success. --- docs/content/supported_formats/yaml.md | 19 ++ include/rfl/SourceMap.hpp | 149 ++++++++++++++++ include/rfl/yaml/Reader.hpp | 5 + include/rfl/yaml/load.hpp | 13 ++ include/rfl/yaml/read.hpp | 49 ++++++ src/reflectcpp.cpp | 1 + src/rfl/SourceMap.cpp | 184 ++++++++++++++++++++ src/rfl/yaml/Reader.cpp | 48 +++++ tests/yaml/test_source_map.cpp | 232 +++++++++++++++++++++++++ 9 files changed, 700 insertions(+) create mode 100644 include/rfl/SourceMap.hpp create mode 100644 src/rfl/SourceMap.cpp create mode 100644 tests/yaml/test_source_map.cpp diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index 586959ffd..480b40944 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -113,4 +113,23 @@ source file is compiled. 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(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. + diff --git a/include/rfl/SourceMap.hpp b/include/rfl/SourceMap.hpp new file mode 100644 index 000000000..c177e928b --- /dev/null +++ b/include/rfl/SourceMap.hpp @@ -0,0 +1,149 @@ +#ifndef RFL_SOURCEMAP_HPP_ +#define RFL_SOURCEMAP_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +#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 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 key = std::nullopt; + + bool operator==(const Entry&) const = default; + }; + + class Builder; + + /// Opaque handle referencing a node owned by a SourceMap::Builder. + class NodeId { + public: + constexpr bool is_valid() const noexcept { + return index_ != kInvalidIndex; + } + explicit constexpr operator bool() const noexcept { return is_valid(); } + bool operator==(const NodeId&) const = default; + + private: + friend class Builder; + static constexpr size_t kInvalidIndex = static_cast(-1); + 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 (or _parent + /// is invalid), the existing tree is left unchanged and an invalid NodeId + /// is returned. + 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_; + }; + + 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 find_entry( + std::span _path) const noexcept; + + std::optional find_entry( + std::initializer_list _path) const noexcept { + return find_entry(std::span(_path.begin(), _path.size())); + } + + /// Looks up the value SourceLocation for an exact path. + std::optional find( + std::span _path) const noexcept; + + std::optional find( + std::initializer_list _path) const noexcept { + return find(std::span(_path.begin(), _path.size())); + } + + /// Looks up the mapping key SourceLocation for an exact path. + std::optional find_key( + std::span _path) const noexcept; + + std::optional find_key( + std::initializer_list _path) const noexcept { + return find_key(std::span(_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) or has no + /// recorded value location. + std::optional find_nearest( + std::span _path) const noexcept; + + std::optional find_nearest( + std::initializer_list _path) const noexcept { + return find_nearest( + std::span(_path.begin(), _path.size())); + } + + bool operator==(const SourceMap& _other) const noexcept; + + private: + explicit SourceMap(std::unique_ptr _impl) noexcept; + + std::unique_ptr impl_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index c1df687c6..94878b42f 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -19,6 +19,7 @@ #include #include "../Result.hpp" +#include "../SourceMap.hpp" #include "../always_false.hpp" #include "../common.hpp" #include "../parsing/to_single_error_message.hpp" @@ -397,6 +398,10 @@ struct Reader { std::string_view yaml_str_; }; +/// @brief Builds a path-to-SourceLocation map for all nodes in a parsed YAML +/// tree, allowing post-parse validation to locate fields and elements. +RFL_API SourceMap build_source_map(const YAML::Node& _root); + } // namespace yaml } // namespace rfl diff --git a/include/rfl/yaml/load.hpp b/include/rfl/yaml/load.hpp index db4b358f4..47e049939 100644 --- a/include/rfl/yaml/load.hpp +++ b/include/rfl/yaml/load.hpp @@ -2,6 +2,7 @@ #define RFL_YAML_LOAD_HPP_ #include "../Result.hpp" +#include "../SourceMap.hpp" #include "../io/load_string.hpp" #include "read.hpp" @@ -22,6 +23,18 @@ Result load(const std::string& _fname) { return rfl::io::load_string(_fname).and_then(read_string); } +/// Loads an object from a YAML file and populates _source_map on success. +template +Result load(const std::string& _fname, SourceMap* _source_map) { + if (_source_map) { + _source_map->clear(); + } + const auto read_string = [_source_map](const auto& _str) { + return read(_str, _source_map); + }; + return rfl::io::load_string(_fname).and_then(read_string); +} + } // namespace yaml } // namespace rfl diff --git a/include/rfl/yaml/read.hpp b/include/rfl/yaml/read.hpp index 7304f7b11..08403b9d2 100644 --- a/include/rfl/yaml/read.hpp +++ b/include/rfl/yaml/read.hpp @@ -8,6 +8,7 @@ #include #include "../Processors.hpp" +#include "../SourceMap.hpp" #include "../internal/no_field_names_v.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" #include "Parser.hpp" @@ -77,6 +78,54 @@ auto read(std::istream& _stream) { return read(yaml_str); } +/// Parses an object from a YAML var and populates _source_map on success. +template +auto read(const InputVarType& _var, const std::string& _yaml_str, + SourceMap* _source_map) { + if (_source_map) { + _source_map->clear(); + } + auto res = read(_var, _yaml_str); + if (res && _source_map) { + *_source_map = build_source_map(_var.node_); + } + return res; +} + +/// Parses an object from a YAML string and populates _source_map on success. +template +Result> read(const std::string& _yaml_str, + SourceMap* _source_map) { + if (_source_map) { + _source_map->clear(); + } + try { + const auto var = InputVarType(YAML::Load(_yaml_str)); + return read(var, _yaml_str, _source_map); + } catch (const YAML::Exception& e) { + return error(Reader::make_error(e.what(), e.mark)); + } catch (const std::exception& e) { + return error(e.what()); + } +} + +/// Parses an object from a YAML string_view and populates _source_map on +/// success. +template +Result> read(const std::string_view _yaml_str, + SourceMap* _source_map) { + return read(std::string(_yaml_str), _source_map); +} + +/// Parses an object from an istream containing YAML and populates _source_map +/// on success. +template +auto read(std::istream& _stream, SourceMap* _source_map) { + const auto yaml_str = std::string(std::istreambuf_iterator(_stream), + std::istreambuf_iterator()); + return read(yaml_str, _source_map); +} + } // namespace yaml } // namespace rfl diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index ea76c27ca..3f2821906 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -30,6 +30,7 @@ SOFTWARE. // compilation. #include "rfl/Generic.cpp" +#include "rfl/SourceMap.cpp" #include "rfl/env/Writer.cpp" #include "rfl/generic/Writer.cpp" #include "rfl/internal/strings/strings.cpp" diff --git a/src/rfl/SourceMap.cpp b/src/rfl/SourceMap.cpp new file mode 100644 index 000000000..2bbeac7a3 --- /dev/null +++ b/src/rfl/SourceMap.cpp @@ -0,0 +1,184 @@ +#include "rfl/SourceMap.hpp" + +#include +#include + +namespace rfl { + +struct SourceMap::Impl { + struct Node { + Entry entry; + std::map fields; + std::vector elements; + + bool operator==(const Node&) const = default; + }; + + std::vector nodes; + + std::optional step(const size_t _node_id, + const PathSegment& _segment) const noexcept { + const auto& node = nodes[_node_id]; + if (const auto* name = std::get_if(&_segment)) { + const auto it = node.fields.find(*name); + if (it == node.fields.end()) { + return std::nullopt; + } + return it->second; + } + const auto idx = std::get(_segment); + if (idx >= node.elements.size()) { + return std::nullopt; + } + return node.elements[idx]; + } + + bool operator==(const Impl&) const = default; +}; + +SourceMap::Builder::Builder() : Builder(Entry{}) {} + +SourceMap::Builder::Builder(const Entry& _root) + : impl_(std::make_unique()) { + impl_->nodes.push_back(Impl::Node{.entry = _root}); +} + +SourceMap::Builder::~Builder() = default; + +SourceMap::Builder::Builder(Builder&& _other) noexcept = default; + +SourceMap::Builder& SourceMap::Builder::operator=(Builder&& _other) noexcept = + default; + +SourceMap::NodeId SourceMap::Builder::root() const noexcept { + if (!impl_ || impl_->nodes.empty()) { + return NodeId(NodeId::kInvalidIndex); + } + return NodeId(0); +} + +SourceMap::NodeId SourceMap::Builder::add_field(const NodeId _parent, + std::string _name, + const Entry& _entry) { + if (!impl_ || _parent.index_ >= impl_->nodes.size()) { + return NodeId(NodeId::kInvalidIndex); + } + if (impl_->nodes[_parent.index_].fields.contains(_name)) { + return NodeId(NodeId::kInvalidIndex); + } + const auto id = impl_->nodes.size(); + impl_->nodes.push_back(Impl::Node{.entry = _entry}); + impl_->nodes[_parent.index_].fields.emplace(std::move(_name), id); + return NodeId(id); +} + +SourceMap::NodeId SourceMap::Builder::add_element(const NodeId _parent, + const Entry& _entry) { + if (!impl_ || _parent.index_ >= impl_->nodes.size()) { + return NodeId(NodeId::kInvalidIndex); + } + const auto id = impl_->nodes.size(); + impl_->nodes.push_back(Impl::Node{.entry = _entry}); + impl_->nodes[_parent.index_].elements.push_back(id); + return NodeId(id); +} + +SourceMap SourceMap::Builder::build() && noexcept { + return SourceMap(std::move(impl_)); +} + +SourceMap::SourceMap() noexcept = default; + +SourceMap::SourceMap(std::unique_ptr _impl) noexcept + : impl_(std::move(_impl)) {} + +SourceMap::~SourceMap() = default; + +SourceMap::SourceMap(const SourceMap& _other) + : impl_(_other.impl_ ? std::make_unique(*_other.impl_) : nullptr) {} + +SourceMap::SourceMap(SourceMap&& _other) noexcept = default; + +SourceMap& SourceMap::operator=(const SourceMap& _other) { + if (this != &_other) { + impl_ = _other.impl_ ? std::make_unique(*_other.impl_) : nullptr; + } + return *this; +} + +SourceMap& SourceMap::operator=(SourceMap&& _other) noexcept = default; + +bool SourceMap::empty() const noexcept { + return !impl_ || impl_->nodes.empty(); +} + +void SourceMap::clear() noexcept { impl_.reset(); } + +std::optional SourceMap::find_entry( + const std::span _path) const noexcept { + if (empty()) { + return std::nullopt; + } + size_t current = 0; + for (const auto& segment : _path) { + const auto next = impl_->step(current, segment); + if (!next) { + return std::nullopt; + } + current = *next; + } + return impl_->nodes[current].entry; +} + +std::optional SourceMap::find( + const std::span _path) const noexcept { + const auto entry = find_entry(_path); + return entry ? entry->value : std::nullopt; +} + +std::optional SourceMap::find_key( + const std::span _path) const noexcept { + const auto entry = find_entry(_path); + return entry ? entry->key : std::nullopt; +} + +std::optional SourceMap::find_nearest( + const std::span _path) const noexcept { + if (empty()) { + return std::nullopt; + } + size_t current = 0; + std::optional last_known = impl_->nodes[0].entry.value; + bool matched_all = true; + for (const auto& segment : _path) { + const auto next = impl_->step(current, segment); + if (!next) { + matched_all = false; + break; + } + current = *next; + if (impl_->nodes[current].entry.value.has_value()) { + last_known = impl_->nodes[current].entry.value; + } + } + if (matched_all && impl_->nodes[current].entry.value.has_value()) { + return impl_->nodes[current].entry.value; + } + if (!last_known) { + return std::nullopt; + } + last_known->exact = false; + return last_known; +} + +bool SourceMap::operator==(const SourceMap& _other) const noexcept { + if (empty() && _other.empty()) { + return true; + } + if (empty() != _other.empty()) { + return false; + } + return *impl_ == *_other.impl_; +} + +} // namespace rfl diff --git a/src/rfl/yaml/Reader.cpp b/src/rfl/yaml/Reader.cpp index 7aae58866..c9a035844 100644 --- a/src/rfl/yaml/Reader.cpp +++ b/src/rfl/yaml/Reader.cpp @@ -1,5 +1,8 @@ #include "rfl/yaml/Reader.hpp" +#include +#include +#include #include namespace rfl::yaml { @@ -24,6 +27,41 @@ bool is_active_node(const std::vector& _nodes, return false; } +void walk_node(const YAML::Node& _node, const SourceMap::NodeId _node_id, + SourceMap::Builder& _builder) { + const Reader::ActiveNodeGuard guard(_node); + if (guard.is_cycle()) { + return; + } + if (_node.IsMap()) { + for (const auto& p : _node) { + std::string k; + try { + k = p.first.as(); + } catch (const std::exception&) { + continue; + } + const auto child_id = _builder.add_field( + _node_id, std::move(k), + SourceMap::Entry{.value = Reader::node_location(p.second), + .key = Reader::node_location(p.first)}); + if (child_id && (p.second.IsMap() || p.second.IsSequence())) { + walk_node(p.second, child_id, _builder); + } + } + } else if (_node.IsSequence()) { + for (size_t i = 0; i < _node.size(); ++i) { + const auto elem = _node[i]; + const auto child_id = _builder.add_element( + _node_id, SourceMap::Entry{.value = Reader::node_location(elem), + .key = std::nullopt}); + if (child_id && (elem.IsMap() || elem.IsSequence())) { + walk_node(elem, child_id, _builder); + } + } + } +} + } // namespace Reader::ActiveNodeGuard::ActiveNodeGuard(const YAML::Node& _node) @@ -45,4 +83,14 @@ Reader::ActiveNodeGuard::~ActiveNodeGuard() { } } +SourceMap build_source_map(const YAML::Node& _root) { + if (!_root.IsDefined()) { + return SourceMap{}; + } + SourceMap::Builder builder(SourceMap::Entry{ + .value = Reader::node_location(_root), .key = std::nullopt}); + walk_node(_root, builder.root(), builder); + return std::move(builder).build(); +} + } // namespace rfl::yaml diff --git a/tests/yaml/test_source_map.cpp b/tests/yaml/test_source_map.cpp new file mode 100644 index 000000000..13701fa79 --- /dev/null +++ b/tests/yaml/test_source_map.cpp @@ -0,0 +1,232 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_source_map { + +struct Endpoint { + std::string host; + int port; + std::optional tls; +}; + +struct Config { + std::string name; + std::vector endpoints; +}; + +struct Pair { + Endpoint primary; + Endpoint backup; +}; + +TEST(yaml, test_source_map_nested_paths_and_keys) { + const std::string yaml_str = + "name: demo\n" + "endpoints:\n" + " - host: alpha\n" + " port: 8080\n" + " - host: beta\n" + " port: 9090\n" + " tls: strict\n"; + + rfl::SourceMap source_map; + const auto res = rfl::yaml::read(yaml_str, &source_map); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_FALSE(source_map.empty()); + + // Root node. + EXPECT_EQ(source_map.find({}), + (rfl::SourceLocation{.line = 1, .column = 1, .exact = true})); + EXPECT_EQ(source_map.find_key({}), std::nullopt); + + // Top-level scalar value and key. + EXPECT_EQ(source_map.find({"name"}), + (rfl::SourceLocation{.line = 1, .column = 7, .exact = true})); + EXPECT_EQ(source_map.find_key({"name"}), + (rfl::SourceLocation{.line = 1, .column = 1, .exact = true})); + + // Nested sequence element fields. + EXPECT_EQ(source_map.find({"endpoints", size_t{0}, "host"}), + (rfl::SourceLocation{.line = 3, .column = 11, .exact = true})); + EXPECT_EQ(source_map.find_key({"endpoints", size_t{0}, "host"}), + (rfl::SourceLocation{.line = 3, .column = 5, .exact = true})); + EXPECT_EQ(source_map.find({"endpoints", size_t{1}, "port"}), + (rfl::SourceLocation{.line = 6, .column = 11, .exact = true})); + EXPECT_EQ(source_map.find_key({"endpoints", size_t{1}, "port"}), + (rfl::SourceLocation{.line = 6, .column = 5, .exact = true})); + EXPECT_EQ(source_map.find({"endpoints", size_t{1}, "tls"}), + (rfl::SourceLocation{.line = 7, .column = 10, .exact = true})); + + // find_entry returns both value and key locations together. + const auto entry = source_map.find_entry({"endpoints", size_t{1}, "port"}); + ASSERT_TRUE(entry.has_value()); + EXPECT_EQ(entry->value, + (rfl::SourceLocation{.line = 6, .column = 11, .exact = true})); + EXPECT_EQ(entry->key, + (rfl::SourceLocation{.line = 6, .column = 5, .exact = true})); + + // Path vector interoperability with ErrorDetail::PathSegment. + const std::vector path = {"endpoints", size_t{1}, + "host"}; + EXPECT_EQ(source_map.find(path), + (rfl::SourceLocation{.line = 5, .column = 11, .exact = true})); + + // Omitted optional field: find() returns nullopt, find_nearest() falls back + // to the enclosing element mapping with exact = false. + EXPECT_EQ(source_map.find({"endpoints", size_t{0}, "tls"}), std::nullopt); + EXPECT_EQ(source_map.find_key({"endpoints", size_t{0}, "tls"}), std::nullopt); + EXPECT_EQ(source_map.find_nearest({"endpoints", size_t{0}, "tls"}), + (rfl::SourceLocation{.line = 3, .column = 5, .exact = false})); + + // Out-of-bounds sequence index falls back to the sequence node. + EXPECT_EQ(source_map.find({"endpoints", size_t{5}, "host"}), std::nullopt); + EXPECT_EQ(source_map.find_nearest({"endpoints", size_t{5}, "host"}), + (rfl::SourceLocation{.line = 3, .column = 3, .exact = false})); +} + +TEST(yaml, test_source_map_dag_aliases_and_stream) { + const std::string yaml_str = + "primary: &ep\n" + " host: shared\n" + " port: 443\n" + "backup: *ep\n"; + + std::istringstream iss(yaml_str); + rfl::SourceMap source_map; + const auto res = rfl::yaml::read(iss, &source_map); + ASSERT_TRUE(res.has_value()) << res.error().what(); + + EXPECT_EQ(source_map.find({"primary", "port"}), + (rfl::SourceLocation{.line = 3, .column = 9, .exact = true})); + EXPECT_EQ(source_map.find({"backup", "port"}), + (rfl::SourceLocation{.line = 3, .column = 9, .exact = true})); + EXPECT_EQ(source_map.find_key({"backup"}), + (rfl::SourceLocation{.line = 4, .column = 1, .exact = true})); +} + +TEST(yaml, test_source_map_cleared_on_failure_and_nullptr) { + const std::string valid_yaml = + "name: ok\n" + "endpoints: []\n"; + const std::string invalid_yaml = + "name: bad\n" + "endpoints:\n" + " - host: alpha\n" + " port: nope\n"; + + // nullptr source_map is accepted without error. + const auto ok_null = + rfl::yaml::read(valid_yaml, static_cast(nullptr)); + ASSERT_TRUE(ok_null.has_value()) << ok_null.error().what(); + + rfl::SourceMap source_map; + ASSERT_TRUE(rfl::yaml::read(valid_yaml, &source_map).has_value()); + EXPECT_FALSE(source_map.empty()); + + // Failed read clears any previous entries. + const auto bad = rfl::yaml::read(invalid_yaml, &source_map); + ASSERT_FALSE(bad.has_value()); + EXPECT_TRUE(source_map.empty()); + EXPECT_EQ(source_map.find({"name"}), std::nullopt); + EXPECT_EQ(source_map.find_nearest({"name"}), std::nullopt); +} + +TEST(yaml, test_source_map_copy_move_equality_and_builder) { + rfl::SourceMap::Builder builder( + {.value = rfl::SourceLocation{.line = 1, .column = 1, .exact = true}}); + const auto root = builder.root(); + const auto items = builder.add_field( + root, "items", + {.value = rfl::SourceLocation{.line = 2, .column = 3, .exact = true}, + .key = rfl::SourceLocation{.line = 2, .column = 1, .exact = true}}); + builder.add_element( + items, + {.value = rfl::SourceLocation{.line = 3, .column = 5, .exact = true}}); + + // Adding a duplicate field preserves the first occurrence without leaking + // orphan nodes or mutating the first occurrence's children. + const auto dup = builder.add_field( + root, "items", + {.value = rfl::SourceLocation{.line = 99, .column = 1, .exact = true}}); + EXPECT_FALSE(dup.is_valid()); + EXPECT_FALSE(static_cast(dup)); + EXPECT_FALSE( + builder + .add_element(dup, {.value = rfl::SourceLocation{ + .line = 100, .column = 1, .exact = true}}) + .is_valid()); + + rfl::SourceMap map = std::move(builder).build(); + EXPECT_EQ(map.find({"items", size_t{0}}), + (rfl::SourceLocation{.line = 3, .column = 5, .exact = true})); + EXPECT_EQ(map.find({"items", size_t{1}}), std::nullopt); + + // An identical SourceMap constructed without the duplicate add_field must + // compare equal (proving no orphan nodes were leaked). + rfl::SourceMap::Builder clean_builder( + {.value = rfl::SourceLocation{.line = 1, .column = 1, .exact = true}}); + const auto clean_items = clean_builder.add_field( + clean_builder.root(), "items", + {.value = rfl::SourceLocation{.line = 2, .column = 3, .exact = true}, + .key = rfl::SourceLocation{.line = 2, .column = 1, .exact = true}}); + clean_builder.add_element( + clean_items, + {.value = rfl::SourceLocation{.line = 3, .column = 5, .exact = true}}); + EXPECT_EQ(map, std::move(clean_builder).build()); + + // Copy & equality. + rfl::SourceMap copy = map; + EXPECT_EQ(copy, map); + + // Move & empty equality. + rfl::SourceMap moved = std::move(copy); + EXPECT_EQ(moved, map); + EXPECT_TRUE(copy.empty()); + EXPECT_EQ(copy, rfl::SourceMap{}); + + // Clearing makes it equal to default-constructed empty SourceMap. + moved.clear(); + EXPECT_TRUE(moved.empty()); + EXPECT_EQ(moved, rfl::SourceMap{}); +} + +TEST(yaml, test_source_map_duplicate_yaml_key_and_null_value_nearest) { + // Without NoDuplicateKeys, YAML keeps the first occurrence; SourceMap must + // keep the first occurrence's subtree intact and ignore the duplicate. + const std::string dup_yaml = + "name: demo\n" + "endpoints:\n" + " - host: first\n" + " port: 8080\n" + "endpoints:\n" + " - host: second\n" + " port: 9090\n"; + + rfl::SourceMap source_map; + const auto res = rfl::yaml::read(dup_yaml, &source_map); + ASSERT_TRUE(res.has_value()) << res.error().what(); + EXPECT_EQ(source_map.find({"endpoints", size_t{0}, "host"}), + (rfl::SourceLocation{.line = 3, .column = 11, .exact = true})); + EXPECT_EQ(source_map.find({"endpoints", size_t{1}, "host"}), std::nullopt); + + // find_nearest on a matched node whose own value location is std::nullopt + // must fall back to the deepest ancestor with exact = false. + rfl::SourceMap::Builder builder( + {.value = rfl::SourceLocation{.line = 1, .column = 1, .exact = true}}); + const auto parent = builder.add_field( + builder.root(), "parent", + {.value = rfl::SourceLocation{.line = 2, .column = 3, .exact = true}}); + builder.add_field(parent, "synthetic", {.value = std::nullopt}); + const auto map = std::move(builder).build(); + + EXPECT_EQ(map.find({"parent", "synthetic"}), std::nullopt); + EXPECT_EQ(map.find_nearest({"parent", "synthetic"}), + (rfl::SourceLocation{.line = 2, .column = 3, .exact = false})); +} + +} // namespace test_source_map