diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..99ffd8b82 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` @@ -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(yaml_str); +``` + ### `rfl::NoExtraFields` When reading an object and the object contains a field that cannot be diff --git a/docs/content/result.md b/docs/content/result.md index fb59c2280..c7a388776 100644 --- a/docs/content/result.md +++ b/docs/content/result.md @@ -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` 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; @@ -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 location = std::nullopt; }; ``` diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index b07f6263e..480b40944 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -103,3 +103,33 @@ rfl::Result 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(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.hpp b/include/rfl.hpp index 432fff2f6..9c5f43b52 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" 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/Result.hpp b/include/rfl/Result.hpp index 08d01fc1f..c7cc3b1b6 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -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 {}; diff --git a/include/rfl/SourceMap.hpp b/include/rfl/SourceMap.hpp new file mode 100644 index 000000000..a83b18a94 --- /dev/null +++ b/include/rfl/SourceMap.hpp @@ -0,0 +1,140 @@ +#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: + 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_; + }; + + 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; + + std::optional find_entry( + std::initializer_list _path) const { + 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; + + std::optional find( + std::initializer_list _path) const { + 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; + + std::optional find_key( + std::initializer_list _path) const { + 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). + std::optional find_nearest( + std::span _path) const; + + std::optional find_nearest( + std::initializer_list _path) const { + return find_nearest( + std::span(_path.begin(), _path.size())); + } + + bool operator==(const SourceMap& _other) const; + + private: + explicit SourceMap(std::unique_ptr _impl) noexcept; + + std::unique_ptr impl_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/internal/Error.hpp b/include/rfl/internal/Error.hpp index f8797c1f0..f8da89322 100644 --- a/include/rfl/internal/Error.hpp +++ b/include/rfl/internal/Error.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -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 { @@ -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 location = std::nullopt; + bool operator==(const ErrorDetail&) const = default; }; @@ -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 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..be2c49a31 --- /dev/null +++ b/include/rfl/internal/no_duplicate_keys_v.hpp @@ -0,0 +1,27 @@ +#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; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/ArrayReader.hpp b/include/rfl/parsing/ArrayReader.hpp index eb600ee5a..0da169dff 100644 --- a/include/rfl/parsing/ArrayReader.hpp +++ b/include/rfl/parsing/ArrayReader.hpp @@ -7,6 +7,7 @@ #include #include "../Result.hpp" +#include "../internal/fail_fast_v.hpp" #include "../internal/is_array.hpp" #include "Parser_base.hpp" #include "wrap_error.hpp" @@ -20,13 +21,15 @@ class ArrayReader { static constexpr size_t size_ = _size; public: + static constexpr bool fail_fast = internal::fail_fast_v; + /** * @brief Constructor. * @param _r The reader to use. * @param _array The array to read into. */ ArrayReader(const R* _r, std::array* _array) - : array_(_array), num_set_(0), r_(_r) {} + : array_(_array), num_set_(0), num_failed_(0), r_(_r) {} ~ArrayReader() = default; @@ -54,21 +57,33 @@ class ArrayReader { * @return An error if reading fails or if the array is already full, std::nullopt otherwise. */ std::optional read(const InputVarType& _var) const { - if (num_set_ == size_) { - return Error("Expected " + std::to_string(size_) + - " elements, got at least " + std::to_string(size_ + 1) + - "."); + const auto idx = num_set_ + num_failed_; + if (idx >= size_) [[unlikely]] { + ++num_failed_; + if (idx == size_) { + return attach_source_location( + *r_, _var, + Error("Expected " + std::to_string(size_) + + " elements, got at least " + std::to_string(size_ + 1) + + ".")); + } + return std::nullopt; } auto res = Parser, ProcessorsType>::read(*r_, _var); if (res) { - move_to(&((*array_)[num_set_]), &(*res)); + if (num_failed_ == 0) [[likely]] { + move_to(&((*array_)[num_set_]), &(*res)); + ++num_set_; + } else { + ++num_failed_; + } } else { + ++num_failed_; return wrap_error( - "Failed to parse element " + std::to_string(num_set_) + ": ", - num_set_, std::move(res).error()); + "Failed to parse element " + std::to_string(idx) + ": ", idx, + std::move(res).error()); } - ++num_set_; return std::optional(); } @@ -102,9 +117,12 @@ class ArrayReader { /// The underlying array. std::array* array_; - /// Indicates the current field + /// Number of contiguous prefix elements constructed in *array_. mutable size_t num_set_; + /// Number of elements seen after the first failure (not constructed in *array_). + mutable size_t num_failed_; + /// The underlying reader. const R* r_; }; diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 7e586b749..52ad40efa 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -15,6 +15,7 @@ #include "FieldVariantReader.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -53,9 +54,10 @@ struct FieldVariantParser { return error(std::move(*err)); } if (!field_variant) { - return error( + return error(make_error_with_location( "Could not parse: Expected the object to have " - "exactly one field, but found none."); + "exactly one field, but found none.", + get_source_location(_r, _obj))); } return std::move(*field_variant); }; diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index b7454b1a7..ca035d71f 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -10,8 +10,10 @@ #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" namespace rfl::parsing { @@ -23,6 +25,9 @@ class FieldVariantReader { using ResultType = Result; public: + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; + /** * @brief Constructor. * @@ -43,10 +48,24 @@ class FieldVariantReader { */ void read(const std::string_view& _disc_value, const InputVarType& _var) const noexcept { + read(_disc_value, _var, std::nullopt); + } + + /** + * @brief Reads a field from the input, with an optional source location for + * the key. + * + * @param _disc_value The name of the field. + * @param _var The input variable to read from. + * @param _key_loc The source location of the key, if available. + */ + void read(const std::string_view& _disc_value, const InputVarType& _var, + const std::optional& _key_loc) const noexcept { if (*field_variant_) { - *field_variant_ = error( + *field_variant_ = error(make_error_with_location( "Could not parse rfl::Variant: Expected the object to have " - "exactly one field, but found more than one."); + "exactly one field, but found more than one.", + _key_loc ? _key_loc : get_source_location(*r_, _var))); return; } try_matching_fields( @@ -57,7 +76,8 @@ class FieldVariantReader { stream << "Could not parse rfl::Variant, could not match field named " "'" << _disc_value << "'."; - *field_variant_ = error(stream.str()); + *field_variant_ = error(make_error_with_location( + stream.str(), _key_loc ? _key_loc : get_source_location(*r_, _var))); } } @@ -80,11 +100,12 @@ class FieldVariantReader { const auto to_variant = [](ValueType&& _val) { return rfl::Variant(FieldType(std::move(_val))); }; - const auto embellish_error = [&](const Error& _e) { + const auto embellish_error = [&](Error _e) { std::stringstream stream; stream << "Could not parse rfl::Variant with field '" - << std::string(_disc_value) << "': " << _e.what(); - return Error(stream.str()); + << std::string(_disc_value) << "': "; + return wrap_error(stream.str(), std::string(_disc_value), + std::move(_e)); }; *field_variant_ = Parser::read(*r_, _var) .transform(to_variant) diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index fe1e8ffdc..2286dc96c 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_MAPREADER_HPP_ #define RFL_PARSING_MAPREADER_HPP_ +#include #include #include #include @@ -10,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" @@ -24,6 +26,9 @@ class MapReader { std::remove_cvref_t; public: + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; + /** * @brief Constructor. * @@ -44,7 +49,20 @@ class MapReader { */ void read(const std::string_view& _name, const InputVarType& _var) const noexcept { - auto res = get_pair(_name, _var); + read(_name, _var, std::nullopt); + } + + /** + * @brief Reads a single field into the map, with an optional source location + * for the key. + * + * @param _name The name of the field. + * @param _var The input variable to read from. + * @param _key_loc The source location of the key, if available. + */ + void read(const std::string_view& _name, const InputVarType& _var, + const std::optional& _key_loc) const noexcept { + auto res = get_pair(_name, _var, _key_loc); if (res) { map_->emplace(std::move(*res)); } else { @@ -52,6 +70,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 { @@ -104,10 +130,16 @@ class MapReader { } Result> get_pair( - const std::string_view& _name, const InputVarType& _var) const noexcept { + const std::string_view& _name, const InputVarType& _var, + const std::optional& _key_loc) const noexcept { const auto to_pair = [&](ValueType&& _val) { auto pair = std::make_pair(std::string(_name), std::move(_val)); - return make_key(std::move(pair)); + auto key_res = make_key(std::move(pair)); + if (!key_res && _key_loc) { + return Result>(error( + attach_source_location(_key_loc, std::move(key_res).error()))); + } + return key_res; }; return Parser, ProcessorsType>::read( *r_, _var) diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 835e7abc7..9a693422a 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -330,6 +330,7 @@ struct NamedTupleParser { /// Generates error messages for when fields are missing. template static RFL_ALWAYS_INLINE void handle_one_missing_field( + const R& _r, const InputObjectOrArrayType& _obj_or_arr, const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors) noexcept { @@ -350,8 +351,9 @@ struct NamedTupleParser { std::stringstream stream; stream << "Field named '" << std::string(current_name) << "' not found."; - _errors->emplace_back( - make_nested_error(std::string(current_name), stream.str())); + _errors->emplace_back(make_nested_error( + std::string(current_name), stream.str(), + get_source_location(_r, _obj_or_arr, /*_exact=*/false))); } else if constexpr (!internal::has_default_val_v) { using NonConstT = std::remove_const_t; @@ -371,7 +373,8 @@ struct NamedTupleParser { "Field named '" + std::string(current_name) + "' not found, and its default value could not be " "constructed: " + - e.what())); + e.what(), + get_source_location(_r, _obj_or_arr, /*_exact=*/false))); return; } } @@ -383,10 +386,13 @@ struct NamedTupleParser { /// Generates error messages for when fields are missing. template static RFL_ALWAYS_INLINE void handle_missing_fields( + const R& _r, const InputObjectOrArrayType& _obj_or_arr, const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors), ...); + (handle_one_missing_field<_is>(_r, _obj_or_arr, _found, _view, _set, + _errors), + ...); } static auto make_parent(const std::string_view& _name, @@ -421,7 +427,7 @@ struct NamedTupleParser { } } if (!should_stop_on_field_error(errors)) { - handle_missing_fields(found, *_view, &set, &errors, + handle_missing_fields(_r, _obj_or_arr, found, *_view, &set, &errors, std::make_integer_sequence()); } if constexpr (internal::fail_fast_v) { @@ -453,7 +459,8 @@ struct NamedTupleParser { if constexpr (internal::has_default_val_v && !internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { - handle_missing_fields(reader.found(), *_view, nullptr, &errors, + handle_missing_fields(_r, _obj_or_arr, reader.found(), *_view, nullptr, + &errors, std::make_integer_sequence()); } } diff --git a/include/rfl/parsing/ParserArray.hpp b/include/rfl/parsing/ParserArray.hpp index c34e38cf3..7bca251f5 100644 --- a/include/rfl/parsing/ParserArray.hpp +++ b/include/rfl/parsing/ParserArray.hpp @@ -15,6 +15,7 @@ #include "Parser_base.hpp" #include "call_destructors_on_array_where_necessary.hpp" #include "schema/Type.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -71,7 +72,8 @@ struct ParserArray { err = array_reader.check_size(); if (err) { call_destructors_on_array_where_necessary(array_reader.num_set(), ptr); - return error(std::move(*err)); + return error(attach_source_location(_r, _var, std::move(*err), + /*_exact=*/false)); } auto result = Result>(std::move(*ptr)); call_destructors_on_array_where_necessary(array_reader.num_set(), ptr); diff --git a/include/rfl/parsing/ParserBitset.hpp b/include/rfl/parsing/ParserBitset.hpp index bc3dfbe19..0a6afbc6f 100644 --- a/include/rfl/parsing/ParserBitset.hpp +++ b/include/rfl/parsing/ParserBitset.hpp @@ -11,6 +11,7 @@ #include "../internal/bitset.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -24,13 +25,19 @@ struct ParserBitset { static Result read(const R& _r, const typename R::InputVarType& _var) noexcept { - return ReprParser::read(_r, _var).and_then([](const auto& _value) { + auto res = ReprParser::read(_r, _var).and_then([](const auto& _value) { if constexpr (std::is_same_v) { return internal::bitset_from_string(_value); } else { return internal::bitset_from_bytes(_value); } }); + if constexpr (requires { _r.source_location(_var); }) { + if (!res) [[unlikely]] { + return error(attach_source_location(_r, _var, std::move(res).error())); + } + } + return res; } template diff --git a/include/rfl/parsing/ParserTaggedUnion.hpp b/include/rfl/parsing/ParserTaggedUnion.hpp index 0e9c6dc81..9fe70e01e 100644 --- a/include/rfl/parsing/ParserTaggedUnion.hpp +++ b/include/rfl/parsing/ParserTaggedUnion.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_PARSER_TAGGED_UNION_HPP_ #include +#include #include #include @@ -74,14 +75,14 @@ struct ParserTaggedUnion, } else { const auto get_disc = - [&_r](InputObjectOrArrayType _obj_or_arr) -> Result { + [&_r](InputObjectOrArrayType _obj_or_arr) -> Result { return get_discriminator(_r, _obj_or_arr); }; const auto to_result = - [&_r, _var](const std::string& _disc_value) -> ResultType { + [&_r, _var](const Discriminator& _disc) -> ResultType { return find_matching_alternative( - _r, _disc_value, _var, + _r, _disc, _var, std::make_integer_sequence()); }; @@ -135,9 +136,14 @@ struct ParserTaggedUnion, } private: + struct Discriminator { + std::string value; + std::optional location; + }; + template static ResultType find_matching_alternative( - const R& _r, const std::string& _disc_value, const InputVarType& _var, + const R& _r, const Discriminator& _disc, const InputVarType& _var, std::integer_sequence) noexcept { using PossibleTags = possible_tags_t>; @@ -145,7 +151,7 @@ struct ParserTaggedUnion, "Duplicate tags are not allowed inside tagged unions."); ResultType res = error(""); bool match_found = false; - (set_if_disc_value_matches<_is>(_r, _disc_value, _var, &res, &match_found), + (set_if_disc_value_matches<_is>(_r, _disc.value, _var, &res, &match_found), ...); if (match_found) [[likely]] { return res; @@ -153,10 +159,10 @@ struct ParserTaggedUnion, const auto names = PossibleTags::names(); std::stringstream stream; stream << "Could not parse tagged union, could not match " - << _discriminator.str() << " '" << _disc_value + << _discriminator.str() << " '" << _disc.value << "'. The following tags are allowed: " << internal::strings::join(", ", names); - return error(stream.str()); + return error(make_error_with_location(stream.str(), _disc.location)); } } @@ -204,27 +210,39 @@ struct ParserTaggedUnion, } /// Retrieves the discriminator from an object - static Result get_discriminator( + static Result get_discriminator( const R& _r, const InputObjectOrArrayType& _obj_or_arr) noexcept { - const auto to_type = [&_r](auto _var) { - return _r.template to_basic_type(_var); + const auto make_disc_error = + [](const std::optional& _loc) { + std::stringstream stream; + stream << "Could not parse tagged union: Could not find field '" + << _discriminator.str() + << "' or type of field was not a string."; + return make_error_with_location(stream.str(), _loc); + }; + + const auto to_type = [&](auto _var) -> Result { + const auto loc = get_source_location(_r, _var, /*_exact=*/true); + auto res = _r.template to_basic_type(_var); + if (!res) { + return error(make_disc_error(loc)); + } + return Discriminator{.value = std::move(*res), .location = loc}; }; - const auto embellish_error = [](const auto&) { - std::stringstream stream; - stream << "Could not parse tagged union: Could not find field '" - << _discriminator.str() << "' or type of field was not a string."; - return Error(stream.str()); + const auto missing_error = [&](const auto&) { + return make_disc_error( + get_source_location(_r, _obj_or_arr, /*_exact=*/false)); }; if constexpr (no_field_names_) { return _r.get_field_from_array(0, _obj_or_arr) - .and_then(to_type) - .transform_error(embellish_error); + .transform_error(missing_error) + .and_then(to_type); } else { return _r.get_field_from_object(_discriminator.str(), _obj_or_arr) - .and_then(to_type) - .transform_error(embellish_error); + .transform_error(missing_error) + .and_then(to_type); } } diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 91cd540d6..3d08df2bb 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -71,6 +71,7 @@ #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -91,6 +92,21 @@ struct Parser { * @return A Result containing the parsed value or an error. */ static RFL_ALWAYS_INLINE auto read(const R& _r, const InputVarType& _var) { + if constexpr (requires { _r.source_location(_var); }) { + auto res = read_impl(_r, _var); + if (!res) [[unlikely]] { + return decltype(res)(error( + attach_source_location(_r, _var, std::move(res).error()))); + } + return res; + } else { + return read_impl(_r, _var); + } + } + + private: + static RFL_ALWAYS_INLINE auto read_impl(const R& _r, + const InputVarType& _var) { if constexpr (internal::is_basic_type_v) { return ParserBasicType::read(_r, _var); @@ -276,6 +292,7 @@ struct Parser { } } + public: /** * @brief Writes a value to the output. * diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 0e3655dff..7547c57c8 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -19,6 +19,7 @@ #include "schemaful/IsSchemafulWriter.hpp" #include "schemaful/tuple_to_named_tuple.hpp" #include "schemaful/tuple_to_named_tuple_t.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -68,7 +69,8 @@ struct TupleParser { if (err) { call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return error(std::move(*err)); + return error(attach_source_location(_r, _arr, std::move(*err), + /*_exact=*/false)); } auto res = Result(std::move(*ptr)); call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); diff --git a/include/rfl/parsing/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index dab0c7fdf..f93652201 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -8,6 +8,7 @@ #include "../Result.hpp" #include "../Tuple.hpp" +#include "../internal/fail_fast_v.hpp" #include "../internal/is_array.hpp" #include "AreReaderAndWriter.hpp" #include "Parser_base.hpp" @@ -24,6 +25,8 @@ class TupleReader { static constexpr size_t size_ = rfl::tuple_size_v; public: + static constexpr bool fail_fast = internal::fail_fast_v; + /** * @brief Constructor. * @@ -31,7 +34,7 @@ class TupleReader { * @param _tuple The tuple to read into. */ TupleReader(const R* _r, TupleType* _tuple) - : num_set_(0), r_(_r), tuple_(_tuple) {} + : num_set_(0), num_failed_(0), r_(_r), tuple_(_tuple) {} ~TupleReader() = default; @@ -62,8 +65,13 @@ class TupleReader { * @return An optional error. */ std::optional read(const InputVarType& _var) const { + const auto idx = num_set_ + num_failed_; + if (idx > size_) [[unlikely]] { + ++num_failed_; + return std::nullopt; + } std::optional err; - read_impl(_var, &err); + read_impl(idx, _var, &err); return err; } @@ -107,29 +115,36 @@ class TupleReader { } template - void read_impl(const InputVarType& _var, std::optional* _err) const { + void read_impl(const size_t _idx, const InputVarType& _var, + std::optional* _err) const { if constexpr (_i < size_) { - if (num_set_ == _i) { + if (_idx == _i) { using CurrentType = std::remove_cvref_t>; auto res = Parser::read(*r_, _var); if (res) { - move_to(&(rfl::get<_i>(*tuple_)), &(*res)); - ++num_set_; + if (num_failed_ == 0) [[likely]] { + move_to(&(rfl::get<_i>(*tuple_)), &(*res)); + ++num_set_; + } else { + ++num_failed_; + } } else { + ++num_failed_; *_err = wrap_error("Failed to parse field " + std::to_string(_i) + ": ", _i, std::move(res).error()); } return; } - read_impl<_i + 1>(_var, _err); + read_impl<_i + 1>(_idx, _var, _err); } else { + ++num_failed_; std::stringstream stream; stream << "Expected " << size_ << " fields, but got at least one more."; - *_err = Error(stream.str()); + *_err = attach_source_location(*r_, _var, Error(stream.str())); return; } } @@ -153,9 +168,12 @@ class TupleReader { } private: - /// Indicates the last field that was set. + /// Number of contiguous prefix fields constructed in *tuple_. mutable size_t num_set_; + /// Number of fields seen after the first failure (not constructed in *tuple_). + mutable size_t num_failed_; + /// The underlying reader. const R* r_; diff --git a/include/rfl/parsing/VectorReader.hpp b/include/rfl/parsing/VectorReader.hpp index 2e22fef88..cb4e82463 100644 --- a/include/rfl/parsing/VectorReader.hpp +++ b/include/rfl/parsing/VectorReader.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "../internal/always_inline.hpp" +#include "../internal/fail_fast_v.hpp" #include "Parser_base.hpp" #include "is_inplace_vector.hpp" #include "is_map_like.hpp" @@ -36,6 +37,8 @@ class VectorReader { using ParsedType = typename decltype(parsed_type())::type; public: + static constexpr bool fail_fast = internal::fail_fast_v; + /** * @brief Constructor. * @@ -43,7 +46,7 @@ class VectorReader { * @param _vec The vector to read into. */ VectorReader(const R* _r, VecType* _vec) - : num_inserted_(0), r_(_r), vec_(_vec) {} + : num_inserted_(0), num_failed_(0), r_(_r), vec_(_vec) {} ~VectorReader() = default; @@ -67,19 +70,37 @@ class VectorReader { * @return An optional error. */ RFL_ALWAYS_INLINE std::optional read(const InputVarType& _var) const { + if constexpr (is_inplace_vector_v) { + const auto idx = index(); + if (idx >= vec_->capacity()) [[unlikely]] { + ++num_failed_; + if (idx == vec_->capacity()) { + return attach_source_location( + *r_, _var, + Error("Too many elements, capacity is " + + std::to_string(vec_->capacity()) + ".")); + } + return std::nullopt; + } + } auto res = Parser::read(*r_, _var); - if (!res) { + if (!res) [[unlikely]] { // The message stays as it is, but the index of the element becomes // part of the path. - return wrap_error("", index(), std::move(res).error()); + const auto idx = index(); + ++num_failed_; + return wrap_error("", idx, std::move(res).error()); } if constexpr (is_map_like_v || is_set_like_v) { vec_->insert(std::move(*res)); ++num_inserted_; } else if constexpr (is_inplace_vector_v) { if (!vec_->try_emplace_back(std::move(*res))) { - return Error("Too many elements, capacity is " + - std::to_string(vec_->capacity()) + "."); + ++num_failed_; + return attach_source_location( + *r_, _var, + Error("Too many elements, capacity is " + + std::to_string(vec_->capacity()) + ".")); } } else { vec_->emplace_back(std::move(*res)); @@ -89,12 +110,12 @@ class VectorReader { private: /// Returns the index of the element that is currently being read. - size_t index() const { + size_t index() const noexcept { if constexpr (is_map_like_v || is_set_like_v) { // Inserting a duplicate does not change the size of a map or set. - return num_inserted_; + return num_inserted_ + num_failed_; } else { - return vec_->size(); + return vec_->size() + num_failed_; } } @@ -102,6 +123,10 @@ class VectorReader { /// The number of elements inserted into a map or set so far. mutable size_t num_inserted_; + /// The number of elements that failed to parse so far (only touched on the + /// error path to avoid adding overhead to successful std::vector reads). + mutable size_t num_failed_; + /// The underlying reader. const R* r_; diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..cffd99c18 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_VIEWREADER_HPP_ #include +#include #include #include #include @@ -11,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" @@ -25,6 +27,8 @@ class ViewReader { using InputVarType = typename R::InputVarType; using ViewType = _ViewType; + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; static constexpr size_t size_ = ViewType::size(); /** @@ -50,9 +54,32 @@ class ViewReader { * @param _var The input variable to read from. */ void read(const std::string_view& _name, const InputVarType& _var) const { + read(_name, _var, std::nullopt); + } + + /** + * @brief Reads a single field into the view, with an optional source + * location for the key. + * + * @param _name The name of the field. + * @param _var The input variable to read from. + * @param _key_loc The source location of the key, if available. + */ + void read(const std::string_view& _name, const InputVarType& _var, + const std::optional& _key_loc) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _name, _var, view_, errors_, found_, set_, - std::make_integer_sequence()); + assign_to_matching_field(*r_, _name, _var, _key_loc, view_, errors_, found_, + 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)); } /** @@ -63,7 +90,8 @@ class ViewReader { */ void read(const int _index, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _index, _var, view_, errors_, found_, set_, + assign_to_matching_field(*r_, _index, _var, std::nullopt, view_, errors_, + found_, set_, std::make_integer_sequence()); } @@ -71,8 +99,8 @@ class ViewReader { template void read(std::integral_constant, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, i, _var, view_, errors_, found_, set_, - std::integer_sequence()); + assign_to_matching_field(*r_, i, _var, std::nullopt, view_, errors_, found_, + set_, std::integer_sequence()); } /** @@ -158,11 +186,10 @@ class ViewReader { } template - static void assign_to_matching_field(const R& _r, - const auto _current_name_or_index, - const auto& _var, auto* _view, - auto* _errors, auto* _found, auto* _set, - std::integer_sequence) { + static void assign_to_matching_field( + const R& _r, const auto _current_name_or_index, const auto& _var, + const std::optional& _key_loc, auto* _view, auto* _errors, + auto* _found, auto* _set, std::integer_sequence) { bool already_assigned = false; (assign_if_field_matches(_r, _current_name_or_index, _var, _view, @@ -187,7 +214,8 @@ class ViewReader { std::stringstream stream; stream << "Value named '" << _current_name_or_index << "' not used."; _errors->emplace_back(make_nested_error( - to_path_segment(_current_name_or_index), stream.str())); + to_path_segment(_current_name_or_index), stream.str(), + _key_loc ? _key_loc : get_source_location(_r, _var))); } } } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..f53e8b62d 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -11,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" @@ -24,6 +26,8 @@ class ViewReaderWithDefault { using InputVarType = typename R::InputVarType; using ViewType = _ViewType; + static constexpr bool no_duplicate_keys = + internal::no_duplicate_keys_v; static constexpr size_t size_ = ViewType::size(); /** @@ -55,11 +59,34 @@ class ViewReaderWithDefault { * @param _var The input variable to read from. */ void read(const std::string_view& _name, const InputVarType& _var) const { + read(_name, _var, std::nullopt); + } + + /** + * @brief Reads a single field into the view, with an optional source + * location for the key. + * + * @param _name The name of the field. + * @param _var The input variable to read from. + * @param _key_loc The source location of the key, if available. + */ + void read(const std::string_view& _name, const InputVarType& _var, + const std::optional& _key_loc) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _name, _var, view_, errors_, found_.get(), + assign_to_matching_field(*r_, _name, _var, _key_loc, view_, errors_, + found_.get(), 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. * @@ -116,11 +143,10 @@ class ViewReaderWithDefault { } template - static void assign_to_matching_field(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, - std::integer_sequence) { + static void assign_to_matching_field( + const R& _r, const std::string_view& _current_name, const auto& _var, + const std::optional& _key_loc, auto* _view, auto* _errors, + auto* _found, std::integer_sequence) { bool already_assigned = false; (assign_if_field_matches(_r, _current_name, _var, _view, _errors, @@ -138,8 +164,9 @@ class ViewReaderWithDefault { stream << "Value named '" << std::string(_current_name) << "' not used. Remove the rfl::NoExtraFields processor or add " "rfl::ExtraFields to avoid this error message."; - _errors->emplace_back( - make_nested_error(std::string(_current_name), stream.str())); + _errors->emplace_back(make_nested_error( + std::string(_current_name), stream.str(), + _key_loc ? _key_loc : get_source_location(_r, _var))); } } } diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 72512ff66..ef96f0f7d 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -23,6 +23,7 @@ class ViewReaderWithDefaultAndStrippedFieldNames { using InputVarType = typename R::InputVarType; using ViewType = _ViewType; + static constexpr bool fail_fast = internal::fail_fast_v; static constexpr size_t size_ = ViewType::size(); /** diff --git a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp index 2b356f807..8617b47aa 100644 --- a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp @@ -22,6 +22,7 @@ class ViewReaderWithStrippedFieldNames { using InputVarType = typename R::InputVarType; using ViewType = _ViewType; + static constexpr bool fail_fast = internal::fail_fast_v; static constexpr size_t size_ = ViewType::size(); /** diff --git a/include/rfl/parsing/wrap_error.hpp b/include/rfl/parsing/wrap_error.hpp index 0a5fb625e..1a59b17e0 100644 --- a/include/rfl/parsing/wrap_error.hpp +++ b/include/rfl/parsing/wrap_error.hpp @@ -1,12 +1,14 @@ #ifndef RFL_PARSING_WRAPERROR_HPP_ #define RFL_PARSING_WRAPERROR_HPP_ +#include #include #include #include #include #include "../Result.hpp" +#include "../internal/always_inline.hpp" #include "../internal/cold.hpp" namespace rfl::parsing { @@ -73,15 +75,91 @@ RFL_COLD inline Error wrap_error(const std::string_view _prefix, Error&& _err) { * * @param _segment The location of the nested value relative to its parent. * @param _msg The error message. + * @param _location Optional source location for the error detail. * @return The error as seen from the parent. */ RFL_COLD inline Error make_nested_error( - const ErrorDetail::PathSegment& _segment, std::string _msg) { + const ErrorDetail::PathSegment& _segment, std::string _msg, + std::optional _location = std::nullopt) { + auto details = std::vector({ErrorDetail{ + .path = {_segment}, .message = _msg, .location = _location}}); + return Error(std::move(_msg), std::move(details)); +} + +/** + * @brief Creates a root error carrying an optional source location. + * + * @param _msg The error message. + * @param _location Optional source location for the error detail. + * @return The error. + */ +RFL_COLD inline Error make_error_with_location( + std::string _msg, std::optional _location) { + if (!_location) { + return Error(std::move(_msg)); + } auto details = std::vector( - {ErrorDetail{.path = {_segment}, .message = _msg}}); + {ErrorDetail{.path = {}, .message = _msg, .location = _location}}); return Error(std::move(_msg), std::move(details)); } +/** + * @brief Queries a reader for the source location of an input node, if the + * reader supports source locations. + */ +template +std::optional get_source_location( + const R& _r, const InputType& _input, const bool _exact = true) noexcept { + if constexpr (requires { _r.source_location(_input); }) { + auto loc = _r.source_location(_input); + if (loc) { + loc->exact = _exact; + } + return loc; + } else { + return std::nullopt; + } +} + +/** + * @brief Fills in a source location on any error details that do not already + * have one, preserving existing leaf locations. + */ +RFL_COLD inline Error attach_source_location( + const std::optional& _location, Error&& _err) { + if (!_location || _err.has_all_source_locations()) { + return std::move(_err); + } + auto what = _err.what(); + auto details = std::move(_err).details(); + for (auto& detail : details) { + if (!detail.location.has_value()) { + detail.location = _location; + } + } + return Error(std::move(what), std::move(details)); +} + +/** + * @brief Fills in a source location from a reader on any error details that do + * not already have one, preserving existing leaf locations. + */ +template +RFL_ALWAYS_INLINE Error attach_source_location(const R& _r, + const InputType& _input, + Error&& _err, + const bool _exact = true) { + if constexpr (requires { _r.source_location(_input); }) { + if (_err.has_all_source_locations()) { + return std::move(_err); + } + return attach_source_location(get_source_location(_r, _input, _exact), + std::move(_err)); + } else { + return std::move(_err); + } +} + } // namespace rfl::parsing #endif diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index c8625c04a..c132c9f3d 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -14,10 +14,16 @@ #include #include #include +#include +#include #include #include "../Result.hpp" +#include "../SourceMap.hpp" #include "../always_false.hpp" +#include "../common.hpp" +#include "../parsing/to_single_error_message.hpp" +#include "../parsing/wrap_error.hpp" namespace rfl { namespace yaml { @@ -59,10 +65,79 @@ struct Reader { static constexpr bool has_custom_constructor = (requires(InputVarType var) { T::from_yaml_obj(var); }); + /// @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. + class RFL_API ActiveNodeGuard { + public: + explicit ActiveNodeGuard(const YAML::Node& _node); + ~ActiveNodeGuard(); + ActiveNodeGuard(const ActiveNodeGuard&) = delete; + ActiveNodeGuard& operator=(const ActiveNodeGuard&) = delete; + + bool is_cycle() const noexcept { return is_cycle_; } + + private: + bool is_cycle_; + bool pushed_; + }; + /// @brief Constructs a Reader from a YAML string view. /// @param _yaml_str The YAML document as a string view. Reader(const std::string_view& _yaml_str) noexcept : yaml_str_(_yaml_str) {} + /// @brief Converts a yaml-cpp Mark (0-based) into a 1-based SourceLocation. + static std::optional mark_to_location( + const YAML::Mark& _mark, const bool _exact = true) noexcept { + if (_mark.is_null() || _mark.line < 0 || _mark.column < 0) { + return std::nullopt; + } + return SourceLocation{.line = static_cast(_mark.line) + 1, + .column = static_cast(_mark.column) + 1, + .exact = _exact}; + } + + /// @brief Extracts a 1-based SourceLocation from a YAML::Node, if valid. + static std::optional node_location( + const YAML::Node& _node, const bool _exact = true) noexcept { + if (!_node.IsDefined()) { + return std::nullopt; + } + return mark_to_location(_node.Mark(), _exact); + } + + /// @brief Creates an Error carrying a source location from a yaml-cpp Mark. + static Error make_error(std::string _msg, const YAML::Mark& _mark, + const bool _exact = true) { + return parsing::make_error_with_location(std::move(_msg), + mark_to_location(_mark, _exact)); + } + + /// @brief Creates an Error carrying a source location from a YAML::Node. + static Error make_error(std::string _msg, const YAML::Node& _node, + const bool _exact = true) { + return parsing::make_error_with_location(std::move(_msg), + node_location(_node, _exact)); + } + + /// @brief Returns the 1-based source location of a YAML value node. + std::optional source_location( + const InputVarType& _var) const noexcept { + return node_location(_var.node_); + } + + /// @brief Returns the 1-based source location of a YAML mapping node. + std::optional source_location( + const InputObjectType& _obj) const noexcept { + return node_location(_obj.node_); + } + + /// @brief Returns the 1-based source location of a YAML sequence node. + std::optional source_location( + const InputArrayType& _arr) const noexcept { + return node_location(_arr.node_); + } + /// @brief Retrieves an element from a YAML sequence by index. /// @param _idx The index of the element in the array. /// @param _arr The YAMLInputArray representing the sequence. @@ -70,7 +145,8 @@ struct Reader { rfl::Result get_field_from_array( const size_t _idx, const InputArrayType& _arr) const noexcept { if (_idx >= _arr.node_.size()) { - return error("Index " + std::to_string(_idx) + " of of bounds."); + return error(make_error("Index " + std::to_string(_idx) + " of of bounds.", + _arr.node_, /*_exact=*/false)); } return InputVarType(_arr.node_[_idx]); } @@ -84,7 +160,8 @@ struct Reader { const std::string& _name, const InputObjectType& _obj) const noexcept { auto var = InputVarType(_obj.node_[_name]); if (!var.node_) { - return error("Object contains no field named '" + _name + "'."); + return error(make_error("Object contains no field named '" + _name + "'.", + _obj.node_, /*_exact=*/false)); } return var; } @@ -117,8 +194,10 @@ struct Reader { // // This is only done for literal blocks which doesn't have tags or // anchors - if (_var.node_.Tag() == "!" && - yaml_str_[_var.node_.Mark().pos] == '|') { + const auto pos = _var.node_.Mark().pos; + if (_var.node_.Tag() == "!" && pos >= 0 && + static_cast(pos) < yaml_str_.size() && + yaml_str_[static_cast(pos)] == '|') { auto last_non_new_line = result.find_last_not_of("\r\n"); if (last_non_new_line != std::string::npos) { result = result.substr(0, last_non_new_line + 1); @@ -134,8 +213,13 @@ struct Reader { static_assert(rfl::always_false_v, "Unsupported type."); } - } catch (std::exception& e) { - return error(e.what()); + } catch (const YAML::Exception& e) { + if (!e.mark.is_null()) { + return error(make_error(e.what(), e.mark)); + } + return error(make_error(e.what(), _var.node_)); + } catch (const std::exception& e) { + return error(make_error(e.what(), _var.node_)); } } @@ -146,7 +230,7 @@ struct Reader { rfl::Result to_array( const InputVarType& _var) const noexcept { if (!_var.node_.IsSequence()) { - return error("Could not cast to sequence!"); + return error(make_error("Could not cast to sequence!", _var.node_)); } return InputArrayType(_var.node_); } @@ -159,17 +243,29 @@ struct Reader { template std::optional read_array(const ArrayReader& _array_reader, const InputArrayType& _arr) const noexcept { + const ActiveNodeGuard guard(_arr.node_); + if (guard.is_cycle()) { + return make_error("Recursive YAML alias detected.", _arr.node_); + } if constexpr (requires { _array_reader.reserve(_arr.node_.size()); }) { if (auto err = _array_reader.reserve(_arr.node_.size())) { return err; } } + std::vector errors; for (size_t i = 0; i < _arr.node_.size(); ++i) { - auto err = _array_reader.read(_arr.node_[i]); + auto err = _array_reader.read(InputVarType(_arr.node_[i])); if (err) { - return err; + if constexpr (is_fail_fast()) { + return err; + } else { + errors.emplace_back(std::move(*err)); + } } } + if (!errors.empty()) { + return parsing::to_single_error(std::move(errors)); + } return std::nullopt; } @@ -182,15 +278,69 @@ struct Reader { template std::optional read_object(const ObjectReader& _object_reader, const InputObjectType& _obj) const noexcept { - for (const auto& p : _obj.node_) { - try { - const auto k = p.first.as(); - _object_reader.read(std::string_view(k), InputVarType(p.second)); - } catch (std::exception& e) { - continue; + const ActiveNodeGuard guard(_obj.node_); + if (guard.is_cycle()) { + return make_error("Recursive YAML alias detected.", _obj.node_); + } + 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; + } + if constexpr (requires { + _object_reader.read(std::string_view(k), + InputVarType(p.second), key_loc); + }) { + _object_reader.read(std::string_view(k), InputVarType(p.second), + key_loc); + } else { + _object_reader.read(std::string_view(k), InputVarType(p.second)); + } + } + 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; + } + const auto key_loc = node_location(p.first); + if constexpr (requires { + _object_reader.read(std::string_view(k), + InputVarType(p.second), key_loc); + }) { + _object_reader.read(std::string_view(k), InputVarType(p.second), + key_loc); + } else { + _object_reader.read(std::string_view(k), InputVarType(p.second)); + } } + return std::nullopt; } - return std::nullopt; } /// @brief Converts a YAMLInputVar to a YAMLInputObject if it is a mapping. @@ -200,7 +350,7 @@ struct Reader { rfl::Result to_object( const InputVarType& _var) const noexcept { if (!_var.node_.IsMap()) { - return error("Could not cast to map!"); + return error(make_error("Could not cast to map!", _var.node_)); } return InputObjectType(_var.node_); } @@ -215,17 +365,44 @@ struct Reader { const InputVarType _var) const noexcept { try { return T::from_yaml_obj(_var); - } catch (std::exception& e) { - return error(e.what()); + } catch (const YAML::Exception& e) { + if (!e.mark.is_null()) { + return error(make_error(e.what(), e.mark)); + } + return error(make_error(e.what(), _var.node_)); + } catch (const std::exception& e) { + return error(make_error(e.what(), _var.node_)); } } private: + template + static constexpr bool is_fail_fast() noexcept { + if constexpr (requires { ArrayReader::fail_fast; }) { + return ArrayReader::fail_fast; + } else { + return false; + } + } + + 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_; }; +/// @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 f8b1b3385..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" @@ -46,7 +47,9 @@ Result> read(const std::string& _yaml_str) { try { const auto var = InputVarType(YAML::Load(_yaml_str)); return read(var, _yaml_str); - } catch (std::exception& e) { + } catch (const YAML::Exception& e) { + return error(Reader::make_error(e.what(), e.mark)); + } catch (const std::exception& e) { return error(e.what()); } } @@ -75,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/reflectcpp_yaml.cpp b/src/reflectcpp_yaml.cpp index 3f3f1beab..8e6b2aad2 100644 --- a/src/reflectcpp_yaml.cpp +++ b/src/reflectcpp_yaml.cpp @@ -29,4 +29,5 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. +#include "rfl/yaml/Reader.cpp" #include "rfl/yaml/Writer.cpp" diff --git a/src/rfl/SourceMap.cpp b/src/rfl/SourceMap.cpp new file mode 100644 index 000000000..611345eaf --- /dev/null +++ b/src/rfl/SourceMap.cpp @@ -0,0 +1,187 @@ +#include "rfl/SourceMap.hpp" + +#include +#include +#include + +namespace rfl { + +namespace { + +constexpr size_t kInvalidNodeIndex = std::numeric_limits::max(); + +} // namespace + +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(kInvalidNodeIndex); + } + 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(kInvalidNodeIndex); + } + 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(kInvalidNodeIndex); + } + 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 { + 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 { + const auto entry = find_entry(_path); + return entry ? entry->value : std::nullopt; +} + +std::optional SourceMap::find_key( + const std::span _path) const { + const auto entry = find_entry(_path); + return entry ? entry->key : std::nullopt; +} + +std::optional SourceMap::find_nearest( + const std::span _path) const { + if (empty()) { + return std::nullopt; + } + size_t current = 0; + std::optional last_known = impl_->nodes[0].entry.value; + bool exact = true; + for (const auto& segment : _path) { + const auto next = impl_->step(current, segment); + if (!next) { + exact = false; + break; + } + current = *next; + if (impl_->nodes[current].entry.value.has_value()) { + last_known = impl_->nodes[current].entry.value; + } + } + if (!last_known) { + return std::nullopt; + } + if (!exact) { + last_known->exact = false; + } + return last_known; +} + +bool SourceMap::operator==(const SourceMap& _other) const { + 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 new file mode 100644 index 000000000..ca0b0e5d4 --- /dev/null +++ b/src/rfl/yaml/Reader.cpp @@ -0,0 +1,92 @@ +#include "rfl/yaml/Reader.hpp" + +#include +#include +#include +#include + +namespace rfl::yaml { + +namespace { + +std::vector& active_nodes() noexcept { + static thread_local std::vector nodes; + return nodes; +} + +bool is_active_node(const std::vector& _nodes, + const YAML::Node& _node) noexcept { + if (!_node.IsDefined()) { + return false; + } + for (const auto& active : _nodes) { + if (active.is(_node)) { + return true; + } + } + 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)}); + 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}); + walk_node(elem, child_id, _builder); + } + } +} + +} // namespace + +Reader::ActiveNodeGuard::ActiveNodeGuard(const YAML::Node& _node) + : is_cycle_(false), pushed_(false) { + auto& nodes = active_nodes(); + if (is_active_node(nodes, _node)) { + is_cycle_ = true; + return; + } + if (_node.IsDefined()) { + nodes.push_back(_node); + pushed_ = true; + } +} + +Reader::ActiveNodeGuard::~ActiveNodeGuard() { + if (pushed_) { + active_nodes().pop_back(); + } +} + +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_error_details.cpp b/tests/yaml/test_error_details.cpp new file mode 100644 index 000000000..457a8f7e3 --- /dev/null +++ b/tests/yaml/test_error_details.cpp @@ -0,0 +1,359 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_yaml_error_details { + +using Path = std::vector; + +struct Item { + std::string name; + rfl::Validator> code; +}; + +struct Config { + std::string title; + std::vector items; +}; + +enum class Mode { fast, safe }; + +struct Settings { + int port; + Mode mode; + std::bitset<4> mask; +}; + +struct Circle { + rfl::Validator> radius; +}; + +struct Square { + double width; +}; + +using Shape = rfl::TaggedUnion<"shape", Circle, Square>; + +struct Drawing { + Shape missing_tag; + Shape bad_tag_type; + Shape unknown_tag; + Shape bad_field; + Shape missing_field; + std::variant id; +}; + +TEST(yaml, test_error_details_source_locations_value_key_parent) { + const std::string yaml_str = + "title: ok\n" + "items:\n" + " - name: first\n" + " code: 0\n" + " unknown_field: 42\n" + " - name: second\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(); + + // Validator error points directly at the bad value (line 4, col 11: "0"). + EXPECT_EQ(details[0].path, (Path{"items", size_t{0}, "code"})); + EXPECT_EQ(details[0].message, + "Value expected to be greater than or equal to 1, but got 0."); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 4, .column = 11, .exact = true})); + + // Unknown field points directly at the key (line 5, col 5: "unknown_field"), + // not at its value (col 20: "42"). + EXPECT_EQ(details[1].path, (Path{"items", size_t{0}, "unknown_field"})); + EXPECT_EQ(details[1].message, "Value named 'unknown_field' not used."); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 5, .column = 5, .exact = true})); + + // Missing field points at its parent mapping (line 6, col 5) with exact=false. + EXPECT_EQ(details[2].path, (Path{"items", size_t{1}, "code"})); + EXPECT_EQ(details[2].message, "Field named 'code' not found."); + EXPECT_EQ(details[2].location, + (rfl::SourceLocation{.line = 6, .column = 5, .exact = false})); +} + +TEST(yaml, test_error_details_type_conversion_and_enum_locations) { + const std::string yaml_str = + "port: not_a_number\n" + "mode: turbo\n" + "mask: 1020\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{"port"})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 1, .column = 7, .exact = true})); + + EXPECT_EQ(details[1].path, (Path{"mode"})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 2, .column = 7, .exact = true})); + + EXPECT_EQ(details[2].path, (Path{"mask"})); + EXPECT_EQ(details[2].location, + (rfl::SourceLocation{.line = 3, .column = 7, .exact = true})); +} + +TEST(yaml, test_error_details_syntax_error_location) { + const std::string yaml_str = + "title: ok\n" + "items: [1, 2\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1); + EXPECT_TRUE(details[0].path.empty()); + EXPECT_EQ(details[0].message, result.error().what()); + ASSERT_TRUE(details[0].location.has_value()); + EXPECT_TRUE(details[0].location->exact); + EXPECT_GE(details[0].location->line, 2u); +} + +TEST(yaml, test_error_details_collects_all_sequence_errors) { + const std::string yaml_str = + "title: batch\n" + "items:\n" + " - name: zero\n" + " code: -1\n" + " - name: one\n" + " code: 10\n" + " - name: two\n" + " code: abc\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 2) << result.error().what(); + + EXPECT_EQ(details[0].path, (Path{"items", size_t{0}, "code"})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 4, .column = 11, .exact = true})); + + EXPECT_EQ(details[1].path, (Path{"items", size_t{2}, "code"})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 8, .column = 11, .exact = true})); +} + +TEST(yaml, test_error_details_sequence_fail_fast) { + const std::string yaml_str = + "title: batch\n" + "items:\n" + " - name: zero\n" + " code: -1\n" + " - name: one\n" + " code: 10\n" + " - name: two\n" + " code: abc\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1) << result.error().what(); + EXPECT_EQ(details[0].path, (Path{"items", size_t{0}, "code"})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 4, .column = 11, .exact = true})); +} + +TEST(yaml, test_error_details_array_tuple_set_and_map) { + struct Containers { + std::array arr; + std::tuple tup; + std::set set; + std::map map; + }; + + const std::string yaml_str = + "arr:\n" + " - bad0\n" + " - 2\n" + " - bad2\n" + "tup:\n" + " - bad_int\n" + " - ok\n" + " - bad_int2\n" + "set:\n" + " - bad_s0\n" + " - 1\n" + " - 1\n" + " - bad_s3\n" + "map:\n" + " 1: bad_val\n" + " bad_key: 2\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 8) << result.error().what(); + + EXPECT_EQ(details[0].path, (Path{"arr", size_t{0}})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 2, .column = 5, .exact = true})); + + EXPECT_EQ(details[1].path, (Path{"arr", size_t{2}})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 4, .column = 5, .exact = true})); + + EXPECT_EQ(details[2].path, (Path{"tup", size_t{0}})); + EXPECT_EQ(details[2].location, + (rfl::SourceLocation{.line = 6, .column = 5, .exact = true})); + + EXPECT_EQ(details[3].path, (Path{"tup", size_t{2}})); + EXPECT_EQ(details[3].location, + (rfl::SourceLocation{.line = 8, .column = 5, .exact = true})); + + EXPECT_EQ(details[4].path, (Path{"set", size_t{0}})); + EXPECT_EQ(details[4].location, + (rfl::SourceLocation{.line = 10, .column = 5, .exact = true})); + + EXPECT_EQ(details[5].path, (Path{"set", size_t{3}})); + EXPECT_EQ(details[5].location, + (rfl::SourceLocation{.line = 13, .column = 5, .exact = true})); + + // Map value error points at the value. + EXPECT_EQ(details[6].path, (Path{"map", "1"})); + EXPECT_EQ(details[6].location, + (rfl::SourceLocation{.line = 15, .column = 6, .exact = true})); + + // Map key error points at the key. + EXPECT_EQ(details[7].path, (Path{"map", "bad_key"})); + EXPECT_EQ(details[7].location, + (rfl::SourceLocation{.line = 16, .column = 3, .exact = true})); +} + +TEST(yaml, test_error_details_tagged_union_and_variant) { + const std::string yaml_str = + "missing_tag:\n" + " width: 2.0\n" + "bad_tag_type:\n" + " shape: [1, 2]\n" + "unknown_tag:\n" + " shape: Triangle\n" + "bad_field:\n" + " shape: Circle\n" + " radius: -5\n" + "missing_field:\n" + " shape: Square\n" + "id: not_int_or_bool\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 6) << result.error().what(); + + // Missing discriminator points at parent mapping with exact=false. + EXPECT_EQ(details[0].path, (Path{"missing_tag"})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 2, .column = 3, .exact = false})); + + // Non-string discriminator points at the discriminator value with exact=true. + EXPECT_EQ(details[1].path, (Path{"bad_tag_type"})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 4, .column = 10, .exact = true})); + + // Unknown discriminator points at the tag value with exact=true. + EXPECT_EQ(details[2].path, (Path{"unknown_tag"})); + EXPECT_EQ(details[2].location, + (rfl::SourceLocation{.line = 6, .column = 10, .exact = true})); + + // Bad field inside matched alternative keeps the leaf value location. + EXPECT_EQ(details[3].path, (Path{"bad_field", "radius"})); + EXPECT_EQ(details[3].location, + (rfl::SourceLocation{.line = 9, .column = 11, .exact = true})); + + // Missing field inside matched alternative points at parent with exact=false. + EXPECT_EQ(details[4].path, (Path{"missing_field", "width"})); + EXPECT_EQ(details[4].location, + (rfl::SourceLocation{.line = 11, .column = 3, .exact = false})); + + // Untagged variant points at the variant value with exact=true. + EXPECT_EQ(details[5].path, (Path{"id"})); + EXPECT_EQ(details[5].location, + (rfl::SourceLocation{.line = 12, .column = 5, .exact = true})); +} + +TEST(yaml, test_error_details_field_variant_and_array_tuple_bounds) { + using FieldVar = rfl::Variant, + rfl::Field<"square", Square>>; + + // Nested error inside externally tagged variant keeps leaf location. + const auto fv_nested = + rfl::yaml::read(std::string("circle:\n radius: 0\n")); + ASSERT_FALSE(fv_nested); + ASSERT_EQ(fv_nested.error().details().size(), 1); + EXPECT_EQ(fv_nested.error().details()[0].path, (Path{"circle", "radius"})); + EXPECT_EQ(fv_nested.error().details()[0].location, + (rfl::SourceLocation{.line = 2, .column = 11, .exact = true})); + + // Unknown field in externally tagged variant points at key. + const auto fv_unknown = + rfl::yaml::read(std::string("triangle:\n sides: 3\n")); + ASSERT_FALSE(fv_unknown); + ASSERT_EQ(fv_unknown.error().details().size(), 1); + EXPECT_EQ(fv_unknown.error().details()[0].location, + (rfl::SourceLocation{.line = 1, .column = 1, .exact = true})); + + // Too few elements in std::array points at sequence with exact=false. + const auto arr_short = + rfl::yaml::read>(std::string("- 1\n- 2\n")); + ASSERT_FALSE(arr_short); + ASSERT_EQ(arr_short.error().details().size(), 1); + EXPECT_EQ(arr_short.error().details()[0].location, + (rfl::SourceLocation{.line = 1, .column = 1, .exact = false})); + + // Too many elements in std::array points at the extra element with exact=true. + const auto arr_long = + rfl::yaml::read>(std::string("- 1\n- 2\n- 3\n")); + ASSERT_FALSE(arr_long); + ASSERT_EQ(arr_long.error().details().size(), 1); + EXPECT_EQ(arr_long.error().details()[0].location, + (rfl::SourceLocation{.line = 3, .column = 3, .exact = true})); + + // Missing element in std::tuple points at sequence with exact=false. + const auto tup_short = + rfl::yaml::read>(std::string("- 1\n")); + ASSERT_FALSE(tup_short); + ASSERT_EQ(tup_short.error().details().size(), 1); + EXPECT_EQ(tup_short.error().details()[0].path, (Path{size_t{1}})); + EXPECT_EQ(tup_short.error().details()[0].location, + (rfl::SourceLocation{.line = 1, .column = 1, .exact = false})); +} + +TEST(yaml, test_what_unchanged_for_single_and_multi_errors) { + const std::string single_err = + "name: ok\n" + "code: 0\n"; + const auto res = rfl::yaml::read(single_err); + ASSERT_FALSE(res); + EXPECT_EQ( + res.error().what(), + "Failed to parse field 'code': Value expected to be greater than or " + "equal to 1, but got 0."); +} + +} // namespace test_yaml_error_details diff --git a/tests/yaml/test_no_duplicate_keys.cpp b/tests/yaml/test_no_duplicate_keys.cpp new file mode 100644 index 000000000..3f29b6b7b --- /dev/null +++ b/tests/yaml/test_no_duplicate_keys.cpp @@ -0,0 +1,144 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_yaml_no_duplicate_keys { + +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 diff --git a/tests/yaml/test_recursive_alias.cpp b/tests/yaml/test_recursive_alias.cpp new file mode 100644 index 000000000..f288f6ad6 --- /dev/null +++ b/tests/yaml/test_recursive_alias.cpp @@ -0,0 +1,86 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_yaml_recursive_alias { + +using Path = std::vector; + +struct Endpoint { + std::string host; + int port; +}; + +struct Cluster { + Endpoint defaults; + Endpoint primary; + Endpoint secondary; +}; + +struct TreeNode { + std::string name; + std::optional> child; +}; + +TEST(yaml, test_non_recursive_alias_allowed) { + const std::string yaml_str = + "defaults: &def\n" + " host: localhost\n" + " port: 8080\n" + "primary: *def\n" + "secondary: *def\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result->primary.host, "localhost"); + EXPECT_EQ(result->primary.port, 8080); + EXPECT_EQ(result->secondary.host, "localhost"); + EXPECT_EQ(result->secondary.port, 8080); +} + +TEST(yaml, test_recursive_mapping_alias_rejected) { + const std::string yaml_str = + "&self\n" + "name: loop\n" + "child: *self\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1) << result.error().what(); + EXPECT_EQ(details[0].path, (Path{"child"})); + EXPECT_EQ(details[0].message, "Recursive YAML alias detected."); + ASSERT_TRUE(details[0].location.has_value()); + EXPECT_TRUE(details[0].location->exact); +} + +TEST(yaml, test_recursive_sequence_alias_rejected) { + const std::string yaml_str = + "&seq\n" + "- *seq\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); +} + +TEST(yaml, test_mutual_recursive_alias_rejected) { + const std::string yaml_str = + "&a\n" + "name: a\n" + "child: &b\n" + " name: b\n" + " child: *a\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1) << result.error().what(); + EXPECT_EQ(details[0].path, (Path{"child", "child"})); + EXPECT_EQ(details[0].message, "Recursive YAML alias detected."); +} + +} // namespace test_yaml_recursive_alias diff --git a/tests/yaml/test_source_map.cpp b/tests/yaml/test_source_map.cpp new file mode 100644 index 000000000..d4301fc63 --- /dev/null +++ b/tests/yaml/test_source_map.cpp @@ -0,0 +1,176 @@ +#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. + builder.add_field( + root, "items", + {.value = rfl::SourceLocation{.line = 99, .column = 1, .exact = true}}); + + rfl::SourceMap map = std::move(builder).build(); + EXPECT_EQ(map.find({"items", size_t{0}}), + (rfl::SourceLocation{.line = 3, .column = 5, .exact = true})); + + // 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{}); +} + +} // namespace test_source_map