diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..d0ff17123 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -53,7 +53,9 @@ reflect-cpp currently supports the following processors: By default, reflect-cpp collects errors from multiple object fields. `rfl::FailFast` reports the first field error and skips decoding the remaining fields of that object. It also applies to nested structs and named tuples, -including structs stored in containers, across serialization formats. +including structs stored in containers, across serialization formats. For YAML, +`rfl::FailFast` also stops sequence reading at the first failing element +instead of collecting all element errors. ```cpp const auto result = rfl::yas::read(bytes); diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index 0f357dc37..e49ae8384 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -111,6 +111,6 @@ source file is compiled. - 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`. +Sequence reading collects errors from all failing elements (unless `rfl::FailFast` is passed), matching object field error aggregation. Recursive YAML aliases are rejected and reported through `rfl::Result`. diff --git a/include/rfl/parsing/ArrayReader.hpp b/include/rfl/parsing/ArrayReader.hpp index f88316b7b..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,22 +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 attach_source_location( - *r_, _var, - 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(); } @@ -103,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/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index e54cbb57f..17592957c 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "../Tuple.hpp" #include "../internal/always_inline.hpp" +#include "../internal/fail_fast_v.hpp" #include "../internal/is_array.hpp" #include "AreReaderAndWriter.hpp" #include "Parser_base.hpp" @@ -25,6 +26,8 @@ class TupleReader { static constexpr size_t size_ = rfl::tuple_size_v; public: + static constexpr bool fail_fast = internal::fail_fast_v; + /** * @brief Constructor. * @@ -32,7 +35,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) {} /** * @brief Handles any fields that were missing from the input. @@ -63,17 +66,20 @@ class TupleReader { * @return An optional error. */ std::optional read(const InputVarType& _var) const { - if (num_set_ == size_) { + const auto idx = num_set_ + num_failed_; + if (idx > size_) [[unlikely]] { + ++num_failed_; + return std::nullopt; + } + if (idx == size_) [[unlikely]] { + ++num_failed_; std::stringstream stream; stream << "Expected " << size_ << " fields, but got at least one more."; return attach_source_location(*r_, _var, Error(stream.str())); } std::optional err; [&](std::integer_sequence) { - (read_impl<_is>(*this, _var, &err), ...); - if (!err) { - ++num_set_; - } + (read_impl<_is>(*this, idx, _var, &err), ...); }(std::make_integer_sequence()); return err; } @@ -122,9 +128,9 @@ class TupleReader { } template - static void read_impl(const TupleReader& _tuple_reader, + static void read_impl(const TupleReader& _tuple_reader, const size_t _idx, const InputVarType& _var, std::optional* _err) { - if (_tuple_reader.num_set_ != _i) { + if (_idx != _i) { return; } using CurrentType = @@ -134,8 +140,14 @@ class TupleReader { *_tuple_reader.r_, _var); if (res) { - move_to(&(rfl::get<_i>(*_tuple_reader.tuple_)), &(*res)); + if (_tuple_reader.num_failed_ == 0) [[likely]] { + move_to(&(rfl::get<_i>(*_tuple_reader.tuple_)), &(*res)); + ++_tuple_reader.num_set_; + } else { + ++_tuple_reader.num_failed_; + } } else { + ++_tuple_reader.num_failed_; *_err = wrap_error("Failed to parse field " + std::to_string(_i) + ": ", _i, std::move(res).error()); } @@ -161,9 +173,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 f20029c9d..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,17 +70,33 @@ 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))) { + ++num_failed_; return attach_source_location( *r_, _var, Error("Too many elements, capacity is " + @@ -91,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_; } } @@ -104,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/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/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index 62995cad1..4e7c3750b 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -20,6 +20,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "../common.hpp" +#include "../parsing/to_single_error_message.hpp" #include "../parsing/wrap_error.hpp" namespace rfl { @@ -249,12 +250,20 @@ struct Reader { return err; } } + std::vector errors; for (size_t i = 0; i < _arr.node_.size(); ++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; } @@ -325,6 +334,15 @@ struct Reader { } private: + template + static constexpr bool is_fail_fast() noexcept { + if constexpr (requires { ArrayReader::fail_fast; }) { + return ArrayReader::fail_fast; + } else { + return false; + } + } + /// @brief The YAML document as a string view, used for context and error /// reporting. std::string_view yaml_str_; diff --git a/tests/yaml/test_error_details.cpp b/tests/yaml/test_error_details.cpp index ee6d2b6ac..457a8f7e3 100644 --- a/tests/yaml/test_error_details.cpp +++ b/tests/yaml/test_error_details.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -58,13 +59,14 @@ TEST(yaml, test_error_details_source_locations_value_key_parent) { "items:\n" " - name: first\n" " code: 0\n" - " unknown_field: 42\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(), 2) << result.error().what(); + 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"})); @@ -80,20 +82,11 @@ TEST(yaml, test_error_details_source_locations_value_key_parent) { 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})); + // 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) { @@ -138,26 +131,118 @@ TEST(yaml, test_error_details_syntax_error_location) { EXPECT_GE(details[0].location->line, 2u); } -TEST(yaml, test_error_details_map_value_and_key_locations) { +TEST(yaml, test_error_details_collects_all_sequence_errors) { const std::string yaml_str = - "1: bad_val\n" - "bad_key: 2\n"; + "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); + 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].path, (Path{"items", size_t{0}, "code"})); EXPECT_EQ(details[0].location, - (rfl::SourceLocation{.line = 1, .column = 4, .exact = true})); + (rfl::SourceLocation{.line = 4, .column = 11, .exact = true})); - // Map key error points at the key. - EXPECT_EQ(details[1].path, (Path{"bad_key"})); + 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 = 2, .column = 1, .exact = true})); + (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) {