From 144614c03a610f1ecc23990186822ad81c3bca0a Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 09:47:40 +0100 Subject: [PATCH 1/2] Add rfl::Error composition methods and opt-in --- include/rfl/error_format.hpp | 196 ++++++++++++++++++ include/rfl/internal/Error.hpp | 89 ++++++++ .../rfl/parsing/to_single_error_message.hpp | 16 +- tests/json/test_error_format.cpp | 169 +++++++++++++++ 4 files changed, 455 insertions(+), 15 deletions(-) create mode 100644 include/rfl/error_format.hpp create mode 100644 tests/json/test_error_format.cpp diff --git a/include/rfl/error_format.hpp b/include/rfl/error_format.hpp new file mode 100644 index 000000000..e6fddfd1c --- /dev/null +++ b/include/rfl/error_format.hpp @@ -0,0 +1,196 @@ +#ifndef RFL_ERROR_FORMAT_HPP_ +#define RFL_ERROR_FORMAT_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Result.hpp" + +namespace rfl { + +namespace internal::error_format { + +inline bool needs_bracket_quoting(const std::string_view _key) { + if (_key.empty()) return true; + for (const unsigned char ch : _key) { + if (ch == '.' || ch == '[' || ch == ']' || ch == '"' || ch == '\\' || + ch <= 0x20 || ch == 0x7f) { + return true; + } + } + return false; +} + +inline std::string quote_bracket_key(const std::string_view _key) { + std::string out = "[\""; + for (const char ch : _key) { + if (ch == '\\' || ch == '"') out.push_back('\\'); + out.push_back(ch); + } + return out + "\"]"; +} + +inline std::string format_segment_label(const ErrorDetail::PathSegment& _seg) { + if (const auto* key = std::get_if(&_seg)) { + return needs_bracket_quoting(*key) ? quote_bracket_key(*key) : *key; + } + return "[" + std::to_string(std::get(_seg)) + "]"; +} + +struct TreeNode { + std::vector messages; + std::vector> children; +}; + +inline void append_multiline(std::string& _out, const std::string_view _prefix, + const std::string_view _connector, + const std::string_view _cont_prefix, + const std::string_view _text) { + if (!_out.empty()) _out.push_back('\n'); + _out += _prefix; + _out += _connector; + size_t pos = 0; + while (true) { + const size_t nl = _text.find('\n', pos); + if (nl == std::string_view::npos) { + _out.append(_text.substr(pos)); + break; + } + _out.append(_text.substr(pos, nl - pos)); + _out.push_back('\n'); + _out += _cont_prefix; + pos = nl + 1; + } +} + +inline void render_children(const std::vector& _nodes, + const size_t _node_idx, + const std::string& _prefix, std::string& _out) { + const auto& node = _nodes[_node_idx]; + const size_t total = node.messages.size() + node.children.size(); + size_t item = 0; + for (const auto& msg : node.messages) { + const bool is_last = (++item == total); + append_multiline(_out, _prefix, is_last ? "└─ " : "├─ ", + _prefix + (is_last ? " " : "│ "), msg); + } + for (const auto& [segment, child_idx] : node.children) { + const bool is_last = (++item == total); + if (!_out.empty()) _out.push_back('\n'); + _out += _prefix; + _out += is_last ? "└─ " : "├─ "; + _out += format_segment_label(segment); + render_children(_nodes, child_idx, _prefix + (is_last ? " " : "│ "), + _out); + } +} + +} // namespace internal::error_format + +/// Formats an ErrorDetail path using dot/bracket notation. +inline std::string format_path( + const std::vector& _path) { + std::string out; + for (const auto& segment : _path) { + if (const auto* idx = std::get_if(&segment)) { + out += "[" + std::to_string(*idx) + "]"; + } else { + const auto& key = std::get(segment); + if (internal::error_format::needs_bracket_quoting(key)) { + out += internal::error_format::quote_bracket_key(key); + } else { + if (!out.empty()) out.push_back('.'); + out += key; + } + } + } + return out; +} + +/// Formats an ErrorDetail path as an RFC 6901 JSON Pointer. +inline std::string format_json_pointer( + const std::vector& _path) { + std::string out; + for (const auto& segment : _path) { + out.push_back('/'); + if (const auto* idx = std::get_if(&segment)) { + out += std::to_string(*idx); + } else { + for (const char ch : std::get(segment)) { + if (ch == '~') { + out += "~0"; + } else if (ch == '/') { + out += "~1"; + } else { + out.push_back(ch); + } + } + } + } + return out; +} + +/// Formats an Error as a grouped multi-line diagnostic tree, invoking +/// _hook(detail) to render each leaf message. +template + requires std::invocable && + std::constructible_from< + std::string, std::invoke_result_t> +inline std::string format_error_tree(const Error& _err, LeafHook&& _hook) { + const auto details = _err.details(); + if (details.empty()) return {}; + + std::vector nodes(1); + for (const auto& detail : details) { + size_t cur = 0; + for (const auto& segment : detail.path) { + size_t next = nodes.size(); + for (const auto& [existing_seg, child_idx] : nodes[cur].children) { + if (existing_seg == segment) { + next = child_idx; + break; + } + } + if (next == nodes.size()) { + nodes[cur].children.emplace_back(segment, next); + nodes.emplace_back(); + } + cur = next; + } + std::string leaf(_hook(detail)); + const auto append_location = [&](const auto& _d) { + if constexpr (requires { _d.location; }) { + if (_d.location.has_value()) { + leaf += " (line " + std::to_string(_d.location->line) + ", col " + + std::to_string(_d.location->column) + ")"; + } + } + }; + append_location(detail); + nodes[cur].messages.emplace_back(std::move(leaf)); + } + + if (nodes[0].children.empty() && nodes[0].messages.size() == 1) { + return nodes[0].messages[0]; + } + std::string out; + internal::error_format::render_children(nodes, 0, "", out); + return out; +} + +/// Formats an Error as a grouped multi-line diagnostic tree. +inline std::string format_error_tree(const Error& _err) { + return format_error_tree(_err, [](const ErrorDetail& _detail) -> std::string { + return _detail.message; + }); +} + +} // namespace rfl + +#endif diff --git a/include/rfl/internal/Error.hpp b/include/rfl/internal/Error.hpp index 11a5f58af..03b0b9d6c 100644 --- a/include/rfl/internal/Error.hpp +++ b/include/rfl/internal/Error.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -183,6 +184,86 @@ class Error { return std::move(*details_); } + /// Combines multiple errors into a single Error, preserving every error's + /// details (path, message, and kind). + RFL_COLD static Error combine(std::vector _errors) { + if (_errors.empty()) { + return Error(""); + } + if (_errors.size() == 1) { + return std::move(_errors[0]); + } + constexpr size_t kErrLimit = 10; + std::string what = "Found " + std::to_string(_errors.size()) + " errors:"; + std::vector all_details; + all_details.reserve(_errors.size()); + for (size_t i = 0; i < _errors.size(); ++i) { + if (i < kErrLimit) { + what += "\n" + std::to_string(i + 1) + ") "; + for (const char ch : _errors[i].what()) { + if (ch == '\n') { + what += "\n "; + } else { + what.push_back(ch); + } + } + } + for (auto& detail : std::move(_errors[i]).details()) { + all_details.emplace_back(std::move(detail)); + } + } + if (_errors.size() > kErrLimit) { + const auto limit_str = std::to_string(kErrLimit); + what += "\n...\nMore than " + limit_str + + " errors occurred, but I am only showing the first " + limit_str + + "."; + } + return Error(std::move(what), std::move(all_details)); + } + + /// Prepends field segment _name to every detail's path and prefixes what(). + RFL_COLD Error in_field(const std::string_view _name) const& { + auto name = std::string(_name); + auto what = "Failed to parse field '" + name + "': " + what_; + return wrap_with_segment(std::move(what), std::move(name), details()); + } + + RFL_COLD Error in_field(const std::string_view _name) && { + auto name = std::string(_name); + auto what = "Failed to parse field '" + name + "': " + what_; + auto d = std::move(*this).details(); + return wrap_with_segment(std::move(what), std::move(name), std::move(d)); + } + + /// Prepends index segment _index to every detail's path and prefixes what(). + RFL_COLD Error at(const size_t _index) const& { + auto what = + "Failed to parse element " + std::to_string(_index) + ": " + what_; + return wrap_with_segment(std::move(what), _index, details()); + } + + RFL_COLD Error at(const size_t _index) && { + auto what = + "Failed to parse element " + std::to_string(_index) + ": " + what_; + auto d = std::move(*this).details(); + return wrap_with_segment(std::move(what), _index, std::move(d)); + } + + /// Prepends _segment (field name or array index) to every detail's path. + RFL_COLD Error at(ErrorDetail::PathSegment _segment) const& { + if (const auto* name = std::get_if(&_segment)) { + return in_field(*name); + } + return at(std::get(_segment)); + } + + RFL_COLD Error at(ErrorDetail::PathSegment _segment) && { + if (const auto* name = std::get_if(&_segment)) { + return std::move(*this).in_field(*name); + } + return std::move(*this).at(std::get(_segment)); + } + private: friend bool has_allocated_details(const Error& _err) noexcept { return _err.details_.has_value(); @@ -206,6 +287,14 @@ class Error { } } + RFL_COLD static Error wrap_with_segment( + std::string _what, const ErrorDetail::PathSegment& _segment, + std::vector _details) { + for (auto& detail : _details) { + detail.path.insert(detail.path.begin(), _segment); + } + return Error(std::move(_what), std::move(_details)); + } /// 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 /// Error is just its message, and it does not allocate. diff --git a/include/rfl/parsing/to_single_error_message.hpp b/include/rfl/parsing/to_single_error_message.hpp index bb3d0326e..07c3734c8 100644 --- a/include/rfl/parsing/to_single_error_message.hpp +++ b/include/rfl/parsing/to_single_error_message.hpp @@ -55,21 +55,7 @@ inline std::string to_single_error_message( * to_single_error_message, and whose details are the details of all errors. */ RFL_COLD inline Error to_single_error(std::vector _errors) { - if (_errors.size() == 1) { - return std::move(_errors[0]); - } - std::vector messages; - messages.reserve(_errors.size()); - std::vector details; - details.reserve(_errors.size()); - for (auto& err : _errors) { - messages.emplace_back(err.what()); - for (auto& detail : std::move(err).details()) { - details.emplace_back(std::move(detail)); - } - } - return Error(to_single_error_message(std::move(messages)), - std::move(details)); + return Error::combine(std::move(_errors)); } } // namespace rfl::parsing diff --git a/tests/json/test_error_format.cpp b/tests/json/test_error_format.cpp new file mode 100644 index 000000000..34e794a3d --- /dev/null +++ b/tests/json/test_error_format.cpp @@ -0,0 +1,169 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_json_error_format { + +using Path = std::vector; + +TEST(json, test_error_combine_and_chaining) { + EXPECT_EQ(rfl::Error::combine({}).what(), ""); + + const auto single_src = + rfl::error("bad port", rfl::ErrorKind::invalid_value, {"port"}).error(); + const auto single = rfl::Error::combine({single_src}); + EXPECT_EQ(single.what(), "bad port"); + EXPECT_EQ(single.details(), single_src.details()); + + // Lvalue chaining preserves the original Error and propagates path/kind. + const rfl::Error base_lval = + rfl::error("must be positive", rfl::ErrorKind::constraint_violation) + .error(); + const auto wrapped_lval = + base_lval.in_field("zip").in_field("address").at(0).in_field("users"); + EXPECT_EQ(base_lval.what(), "must be positive"); + EXPECT_TRUE(base_lval.details()[0].path.empty()); + EXPECT_EQ(wrapped_lval.what(), + "Failed to parse field 'users': Failed to parse element 0: " + "Failed to parse field 'address': Failed to parse field 'zip': " + "must be positive"); + ASSERT_EQ(wrapped_lval.details().size(), 1u); + EXPECT_EQ(wrapped_lval.details()[0].path, + (Path{"users", size_t{0}, "address", "zip"})); + EXPECT_EQ(wrapped_lval.details()[0].kind, + rfl::ErrorKind::constraint_violation); + + // Rvalue chaining and PathSegment overloads (field name + index). + const auto wrapped_rval = + rfl::error("expected int", rfl::ErrorKind::invalid_type) + .error() + .at(rfl::ErrorDetail::PathSegment{"count"}) + .at(rfl::ErrorDetail::PathSegment{size_t{2}}) + .at("items"); + EXPECT_EQ(wrapped_rval.what(), + "Failed to parse field 'items': Failed to parse element 2: " + "Failed to parse field 'count': expected int"); + ASSERT_EQ(wrapped_rval.details().size(), 1u); + EXPECT_EQ(wrapped_rval.details()[0].path, (Path{"items", size_t{2}, "count"})); + EXPECT_EQ(wrapped_rval.details()[0].kind, rfl::ErrorKind::invalid_type); + + const auto combined = rfl::Error::combine({wrapped_lval, wrapped_rval}); + EXPECT_EQ(combined.what(), + "Found 2 errors:\n" + "1) Failed to parse field 'users': Failed to parse element 0: " + "Failed to parse field 'address': Failed to parse field 'zip': " + "must be positive\n" + "2) Failed to parse field 'items': Failed to parse element 2: " + "Failed to parse field 'count': expected int"); + ASSERT_EQ(combined.details().size(), 2u); + EXPECT_EQ(combined.details()[0].path, + (Path{"users", size_t{0}, "address", "zip"})); + EXPECT_EQ(combined.details()[0].kind, rfl::ErrorKind::constraint_violation); + EXPECT_EQ(combined.details()[1].path, (Path{"items", size_t{2}, "count"})); + EXPECT_EQ(combined.details()[1].kind, rfl::ErrorKind::invalid_type); +} + +TEST(json, test_format_path) { + EXPECT_EQ(rfl::format_path({}), ""); + EXPECT_EQ(rfl::format_path(Path{"users", size_t{0}, "address", "zip"}), + "users[0].address.zip"); + EXPECT_EQ(rfl::format_path(Path{size_t{0}, "name"}), "[0].name"); + EXPECT_EQ(rfl::format_path(Path{"a.b"}), "[\"a.b\"]"); + EXPECT_EQ(rfl::format_path(Path{"cfg", "a.b", "has space", "k[0]", "x]y"}), + "cfg[\"a.b\"][\"has space\"][\"k[0]\"][\"x]y\"]"); + EXPECT_EQ(rfl::format_path(Path{""}), "[\"\"]"); + EXPECT_EQ(rfl::format_path(Path{"a\"b\\c"}), "[\"a\\\"b\\\\c\"]"); +} + +TEST(json, test_format_json_pointer) { + EXPECT_EQ(rfl::format_json_pointer({}), ""); + EXPECT_EQ(rfl::format_json_pointer(Path{"users", size_t{0}, "a/b", "c~d"}), + "/users/0/a~1b/c~0d"); + EXPECT_EQ(rfl::format_json_pointer(Path{"~1", "/~"}), "/~01/~1~0"); + EXPECT_EQ(rfl::format_json_pointer(Path{""}), "/"); +} + +TEST(json, test_format_error_tree) { + EXPECT_EQ(rfl::format_error_tree(rfl::Error("Invalid syntax")), + "Invalid syntax"); + + const auto grouped = rfl::Error::combine({ + rfl::error("Could not cast to int.", rfl::ErrorKind::invalid_type, + {"port"}) + .error(), + rfl::error("Must be >= 1.", rfl::ErrorKind::constraint_violation, + {"items", size_t{0}, "count"}) + .error(), + rfl::error("Could not cast to string.", rfl::ErrorKind::invalid_type, + {"items", size_t{0}, "name"}) + .error(), + rfl::error("Field named 'host' not found.", rfl::ErrorKind::missing_field, + {"host"}) + .error(), + }); + + EXPECT_EQ(rfl::format_error_tree(grouped), + "├─ port\n" + "│ └─ Could not cast to int.\n" + "├─ items\n" + "│ └─ [0]\n" + "│ ├─ count\n" + "│ │ └─ Must be >= 1.\n" + "│ └─ name\n" + "│ └─ Could not cast to string.\n" + "└─ host\n" + " └─ Field named 'host' not found."); + + const auto custom_tree = + rfl::format_error_tree(grouped, [](const rfl::ErrorDetail& _d) { + switch (_d.kind) { + case rfl::ErrorKind::invalid_type: + return std::string("[TYPE] ") + _d.message; + case rfl::ErrorKind::constraint_violation: + return std::string("[RULE] ") + _d.message; + case rfl::ErrorKind::missing_field: + return std::string("[MISSING] ") + _d.message; + default: + return _d.message; + } + }); + EXPECT_EQ(custom_tree, + "├─ port\n" + "│ └─ [TYPE] Could not cast to int.\n" + "├─ items\n" + "│ └─ [0]\n" + "│ ├─ count\n" + "│ │ └─ [RULE] Must be >= 1.\n" + "│ └─ name\n" + "│ └─ [TYPE] Could not cast to string.\n" + "└─ host\n" + " └─ [MISSING] Field named 'host' not found."); +} + +TEST(json, test_error_details_json_serialization) { + const auto err = rfl::Error::combine({ + rfl::error("Must be >= 1.", rfl::ErrorKind::constraint_violation, + {"items", size_t{0}, "count"}) + .error(), + rfl::error("Field named 'host' not found.", rfl::ErrorKind::missing_field, + {"host"}) + .error(), + }); + + const std::string serialized = rfl::json::write(err.details()); + const auto roundtrip = + rfl::json::read>(serialized); + ASSERT_TRUE(roundtrip) << roundtrip.error().what(); + EXPECT_EQ(*roundtrip, err.details()); + EXPECT_NE(serialized.find("\"path\":[\"items\",0,\"count\"]"), + std::string::npos); + EXPECT_NE(serialized.find("\"kind\":\"constraint_violation\""), + std::string::npos); + EXPECT_NE(serialized.find("\"kind\":\"missing_field\""), std::string::npos); +} + +} // namespace test_json_error_format From b9e476817d4bd1d019e3dd2dda8d1959966cb0ee Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 10:12:58 +0100 Subject: [PATCH 2/2] Address dual-model review feedback on error_format.hpp --- include/rfl/error_format.hpp | 47 ++++++++++++++++++++------------ tests/json/test_error_format.cpp | 2 ++ 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/include/rfl/error_format.hpp b/include/rfl/error_format.hpp index e6fddfd1c..66afdb958 100644 --- a/include/rfl/error_format.hpp +++ b/include/rfl/error_format.hpp @@ -28,10 +28,25 @@ inline bool needs_bracket_quoting(const std::string_view _key) { } inline std::string quote_bracket_key(const std::string_view _key) { + static constexpr char kHex[] = "0123456789abcdef"; std::string out = "[\""; - for (const char ch : _key) { - if (ch == '\\' || ch == '"') out.push_back('\\'); - out.push_back(ch); + for (const unsigned char ch : _key) { + if (ch == '\\' || ch == '"') { + out.push_back('\\'); + out.push_back(static_cast(ch)); + } else if (ch == '\n') { + out += "\\n"; + } else if (ch == '\r') { + out += "\\r"; + } else if (ch == '\t') { + out += "\\t"; + } else if (ch < 0x20 || ch == 0x7f) { + out += "\\x"; + out.push_back(kHex[(ch >> 4) & 0x0f]); + out.push_back(kHex[ch & 0x0f]); + } else { + out.push_back(static_cast(ch)); + } } return out + "\"]"; } @@ -72,21 +87,27 @@ inline void append_multiline(std::string& _out, const std::string_view _prefix, inline void render_children(const std::vector& _nodes, const size_t _node_idx, const std::string& _prefix, std::string& _out) { + static constexpr std::string_view kBranchMid = "\xE2\x94\x9C\xE2\x94\x80 "; + static constexpr std::string_view kBranchLast = "\xE2\x94\x94\xE2\x94\x80 "; + static constexpr std::string_view kIndentMid = "\xE2\x94\x82 "; + static constexpr std::string_view kIndentLast = " "; const auto& node = _nodes[_node_idx]; const size_t total = node.messages.size() + node.children.size(); size_t item = 0; for (const auto& msg : node.messages) { const bool is_last = (++item == total); - append_multiline(_out, _prefix, is_last ? "└─ " : "├─ ", - _prefix + (is_last ? " " : "│ "), msg); + append_multiline(_out, _prefix, is_last ? kBranchLast : kBranchMid, + _prefix + std::string(is_last ? kIndentLast : kIndentMid), + msg); } for (const auto& [segment, child_idx] : node.children) { const bool is_last = (++item == total); if (!_out.empty()) _out.push_back('\n'); _out += _prefix; - _out += is_last ? "└─ " : "├─ "; + _out += is_last ? kBranchLast : kBranchMid; _out += format_segment_label(segment); - render_children(_nodes, child_idx, _prefix + (is_last ? " " : "│ "), + render_children(_nodes, child_idx, + _prefix + std::string(is_last ? kIndentLast : kIndentMid), _out); } } @@ -163,17 +184,7 @@ inline std::string format_error_tree(const Error& _err, LeafHook&& _hook) { } cur = next; } - std::string leaf(_hook(detail)); - const auto append_location = [&](const auto& _d) { - if constexpr (requires { _d.location; }) { - if (_d.location.has_value()) { - leaf += " (line " + std::to_string(_d.location->line) + ", col " + - std::to_string(_d.location->column) + ")"; - } - } - }; - append_location(detail); - nodes[cur].messages.emplace_back(std::move(leaf)); + nodes[cur].messages.emplace_back(_hook(detail)); } if (nodes[0].children.empty() && nodes[0].messages.size() == 1) { diff --git a/tests/json/test_error_format.cpp b/tests/json/test_error_format.cpp index 34e794a3d..c8975c0ae 100644 --- a/tests/json/test_error_format.cpp +++ b/tests/json/test_error_format.cpp @@ -77,6 +77,8 @@ TEST(json, test_format_path) { "cfg[\"a.b\"][\"has space\"][\"k[0]\"][\"x]y\"]"); EXPECT_EQ(rfl::format_path(Path{""}), "[\"\"]"); EXPECT_EQ(rfl::format_path(Path{"a\"b\\c"}), "[\"a\\\"b\\\\c\"]"); + EXPECT_EQ(rfl::format_path(Path{"line1\nline2\t\r\x01"}), + "[\"line1\\nline2\\t\\r\\x01\"]"); } TEST(json, test_format_json_pointer) {