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..0f357dc37 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -103,3 +103,14 @@ 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` point at the offending key (`exact = true`). +- Missing required fields point at the enclosing mapping or sequence (`exact = false`). + +Recursive YAML aliases are rejected and reported through `rfl::Result`. + + 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/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/parsing/ArrayReader.hpp b/include/rfl/parsing/ArrayReader.hpp index eb600ee5a..f88316b7b 100644 --- a/include/rfl/parsing/ArrayReader.hpp +++ b/include/rfl/parsing/ArrayReader.hpp @@ -55,9 +55,10 @@ class ArrayReader { */ 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) + - "."); + return attach_source_location( + *r_, _var, + Error("Expected " + std::to_string(size_) + + " elements, got at least " + std::to_string(size_ + 1) + ".")); } auto res = Parser, ProcessorsType>::read(*r_, _var); 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..c019c6dbe 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -12,6 +12,7 @@ #include "../internal/is_array.hpp" #include "../internal/nth_element_t.hpp" #include "Parser_base.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -43,10 +44,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 +72,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 +96,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..761529378 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 @@ -44,7 +45,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 { @@ -104,10 +118,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 518fc3185..988224f56 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -354,6 +354,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, const bool _value_initialize_default_vals) noexcept { @@ -392,7 +393,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; } std::get<_i>(*_set) = true; @@ -408,8 +410,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))); return; } @@ -434,7 +437,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; } } @@ -456,12 +460,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, const bool _value_initialize_default_vals, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors, - _value_initialize_default_vals), + (handle_one_missing_field<_is>(_r, _obj_or_arr, _found, _view, _set, + _errors, _value_initialize_default_vals), ...); } @@ -498,7 +503,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, _value_initialize_default_vals, std::make_integer_sequence()); } @@ -531,7 +536,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, /*_value_initialize_default_vals=*/false, 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 dee232752..f2523f9bc 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 #include @@ -75,14 +76,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()); }; @@ -137,9 +138,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>; @@ -147,7 +153,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; @@ -155,10 +161,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)); } } @@ -207,27 +213,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 d284b5245..1ee574fc4 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -73,6 +73,7 @@ #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" #include "tagged_union_wrapper_no_ptr.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -93,6 +94,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); @@ -284,6 +300,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 df127aa70..e54cbb57f 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -66,7 +66,7 @@ class TupleReader { if (num_set_ == size_) { std::stringstream stream; stream << "Expected " << size_ << " fields, but got at least one more."; - return Error(stream.str()); + return attach_source_location(*r_, _var, Error(stream.str())); } std::optional err; [&](std::integer_sequence) { diff --git a/include/rfl/parsing/VectorReader.hpp b/include/rfl/parsing/VectorReader.hpp index 2e22fef88..f20029c9d 100644 --- a/include/rfl/parsing/VectorReader.hpp +++ b/include/rfl/parsing/VectorReader.hpp @@ -78,8 +78,10 @@ class VectorReader { ++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()) + "."); + return attach_source_location( + *r_, _var, + Error("Too many elements, capacity is " + + std::to_string(vec_->capacity()) + ".")); } } else { vec_->emplace_back(std::move(*res)); diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..df2096814 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 @@ -50,9 +51,22 @@ 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()); } /** @@ -63,7 +77,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 +86,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 +173,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 +201,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..7330be611 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -55,8 +56,22 @@ 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()); } @@ -116,11 +131,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 +152,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/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..62995cad1 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -14,10 +14,13 @@ #include #include #include +#include #include #include "../Result.hpp" #include "../always_false.hpp" +#include "../common.hpp" +#include "../parsing/wrap_error.hpp" namespace rfl { namespace yaml { @@ -59,10 +62,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 +142,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 +157,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 +191,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 +210,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 +227,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,13 +240,17 @@ 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; } } 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; } @@ -182,13 +267,27 @@ struct Reader { template std::optional read_object(const ObjectReader& _object_reader, const InputObjectType& _obj) const noexcept { + const ActiveNodeGuard guard(_obj.node_); + if (guard.is_cycle()) { + return make_error("Recursive YAML alias detected.", _obj.node_); + } for (const auto& p : _obj.node_) { + std::string k; try { - const auto k = p.first.as(); - _object_reader.read(std::string_view(k), InputVarType(p.second)); - } catch (std::exception& e) { + 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; } @@ -200,7 +299,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,8 +314,13 @@ 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_)); } } diff --git a/include/rfl/yaml/read.hpp b/include/rfl/yaml/read.hpp index f8b1b3385..7304f7b11 100644 --- a/include/rfl/yaml/read.hpp +++ b/include/rfl/yaml/read.hpp @@ -46,7 +46,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()); } } 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/yaml/Reader.cpp b/src/rfl/yaml/Reader.cpp new file mode 100644 index 000000000..7aae58866 --- /dev/null +++ b/src/rfl/yaml/Reader.cpp @@ -0,0 +1,48 @@ +#include "rfl/yaml/Reader.hpp" + +#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; +} + +} // 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(); + } +} + +} // 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..ee6d2b6ac --- /dev/null +++ b/tests/yaml/test_error_details.cpp @@ -0,0 +1,274 @@ +#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"; + + 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(); + + // 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 3, col 5) with exact=false. + const std::string missing_yaml = + "title: ok\n" + "items:\n" + " - name: only_name\n"; + const auto missing_res = rfl::yaml::read(missing_yaml); + ASSERT_FALSE(missing_res); + ASSERT_EQ(missing_res.error().details().size(), 1); + EXPECT_EQ(missing_res.error().details()[0].path, + (Path{"items", size_t{0}, "code"})); + EXPECT_EQ(missing_res.error().details()[0].message, + "Field named 'code' not found."); + EXPECT_EQ(missing_res.error().details()[0].location, + (rfl::SourceLocation{.line = 3, .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_map_value_and_key_locations) { + const std::string yaml_str = + "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(), 2) << result.error().what(); + + // Map value error points at the value. + EXPECT_EQ(details[0].path, (Path{"1"})); + EXPECT_EQ(details[0].location, + (rfl::SourceLocation{.line = 1, .column = 4, .exact = true})); + + // Map key error points at the key. + EXPECT_EQ(details[1].path, (Path{"bad_key"})); + EXPECT_EQ(details[1].location, + (rfl::SourceLocation{.line = 2, .column = 1, .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_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