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
19 changes: 19 additions & 0 deletions docs/content/supported_formats/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<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.


149 changes: 149 additions & 0 deletions include/rfl/SourceMap.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#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:
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<size_t>(-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> 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 noexcept;

std::optional<Entry> find_entry(
std::initializer_list<PathSegment> _path) const noexcept {
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 noexcept;

std::optional<SourceLocation> find(
std::initializer_list<PathSegment> _path) const noexcept {
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 noexcept;

std::optional<SourceLocation> find_key(
std::initializer_list<PathSegment> _path) const noexcept {
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) or has no
/// recorded value location.
std::optional<SourceLocation> find_nearest(
std::span<const PathSegment> _path) const noexcept;

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

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

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

std::unique_ptr<Impl> impl_;
};

} // namespace rfl

#endif
5 changes: 5 additions & 0 deletions include/rfl/yaml/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <vector>

#include "../Result.hpp"
#include "../SourceMap.hpp"
#include "../always_false.hpp"
#include "../common.hpp"
#include "../parsing/to_single_error_message.hpp"
Expand Down Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions include/rfl/yaml/load.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define RFL_YAML_LOAD_HPP_

#include "../Result.hpp"
#include "../SourceMap.hpp"
#include "../io/load_string.hpp"
#include "read.hpp"

Expand All @@ -22,6 +23,18 @@ Result<T> 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 <class T, class... Ps>
Result<T> 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<T, Ps...>(_str, _source_map);
};
return rfl::io::load_string(_fname).and_then(read_string);
}

} // namespace yaml
} // namespace rfl

Expand Down
49 changes: 49 additions & 0 deletions include/rfl/yaml/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <string_view>

#include "../Processors.hpp"
#include "../SourceMap.hpp"
#include "../internal/no_field_names_v.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "Parser.hpp"
Expand Down Expand Up @@ -77,6 +78,54 @@ auto read(std::istream& _stream) {
return read<T, Ps...>(yaml_str);
}

/// Parses an object from a YAML var and populates _source_map on success.
template <class T, class... Ps>
auto read(const InputVarType& _var, const std::string& _yaml_str,
SourceMap* _source_map) {
if (_source_map) {
_source_map->clear();
}
auto res = read<T, Ps...>(_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 <class T, class... Ps>
Result<internal::wrap_in_rfl_array_t<T>> 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<T, Ps...>(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 <class T, class... Ps>
Result<internal::wrap_in_rfl_array_t<T>> read(const std::string_view _yaml_str,
SourceMap* _source_map) {
return read<T, Ps...>(std::string(_yaml_str), _source_map);
}

/// Parses an object from an istream containing YAML and populates _source_map
/// on success.
template <class T, class... Ps>
auto read(std::istream& _stream, SourceMap* _source_map) {
const auto yaml_str = std::string(std::istreambuf_iterator<char>(_stream),
std::istreambuf_iterator<char>());
return read<T, Ps...>(yaml_str, _source_map);
}

} // namespace yaml
} // namespace rfl

Expand Down
1 change: 1 addition & 0 deletions src/reflectcpp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading