Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 207 additions & 0 deletions include/rfl/error_format.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
#ifndef RFL_ERROR_FORMAT_HPP_
#define RFL_ERROR_FORMAT_HPP_

#include <concepts>
#include <cstddef>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>

#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) {
static constexpr char kHex[] = "0123456789abcdef";
std::string out = "[\"";
for (const unsigned char ch : _key) {
if (ch == '\\' || ch == '"') {
out.push_back('\\');
out.push_back(static_cast<char>(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<char>(ch));
}
}
return out + "\"]";
}

inline std::string format_segment_label(const ErrorDetail::PathSegment& _seg) {
if (const auto* key = std::get_if<std::string>(&_seg)) {
return needs_bracket_quoting(*key) ? quote_bracket_key(*key) : *key;
}
return "[" + std::to_string(std::get<size_t>(_seg)) + "]";
}

struct TreeNode {
std::vector<std::string> messages;
std::vector<std::pair<ErrorDetail::PathSegment, size_t>> 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<TreeNode>& _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 ? 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 ? kBranchLast : kBranchMid;
_out += format_segment_label(segment);
render_children(_nodes, child_idx,
_prefix + std::string(is_last ? kIndentLast : kIndentMid),
_out);
}
}

} // namespace internal::error_format

/// Formats an ErrorDetail path using dot/bracket notation.
inline std::string format_path(
const std::vector<ErrorDetail::PathSegment>& _path) {
std::string out;
for (const auto& segment : _path) {
if (const auto* idx = std::get_if<size_t>(&segment)) {
out += "[" + std::to_string(*idx) + "]";
} else {
const auto& key = std::get<std::string>(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<ErrorDetail::PathSegment>& _path) {
std::string out;
for (const auto& segment : _path) {
out.push_back('/');
if (const auto* idx = std::get_if<size_t>(&segment)) {
out += std::to_string(*idx);
} else {
for (const char ch : std::get<std::string>(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 <class LeafHook>
requires std::invocable<LeafHook&, const ErrorDetail&> &&
std::constructible_from<
std::string, std::invoke_result_t<LeafHook&, const ErrorDetail&>>
inline std::string format_error_tree(const Error& _err, LeafHook&& _hook) {
const auto details = _err.details();
if (details.empty()) return {};

std::vector<internal::error_format::TreeNode> 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;
}
nodes[cur].messages.emplace_back(_hook(detail));
}

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
89 changes: 89 additions & 0 deletions include/rfl/internal/Error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
Expand Down Expand Up @@ -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<Error> _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<ErrorDetail> 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<std::string>(&_segment)) {
return in_field(*name);
}
return at(std::get<size_t>(_segment));
}

RFL_COLD Error at(ErrorDetail::PathSegment _segment) && {
if (const auto* name = std::get_if<std::string>(&_segment)) {
return std::move(*this).in_field(*name);
}
return std::move(*this).at(std::get<size_t>(_segment));
}

private:
friend bool has_allocated_details(const Error& _err) noexcept {
return _err.details_.has_value();
Expand All @@ -206,6 +287,14 @@ class Error {
}
}

RFL_COLD static Error wrap_with_segment(
std::string _what, const ErrorDetail::PathSegment& _segment,
std::vector<ErrorDetail> _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.
Expand Down
16 changes: 1 addition & 15 deletions include/rfl/parsing/to_single_error_message.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<Error> _errors) {
if (_errors.size() == 1) {
return std::move(_errors[0]);
}
std::vector<std::string> messages;
messages.reserve(_errors.size());
std::vector<ErrorDetail> 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
Expand Down
Loading