From 7f3395cb74fc9140e8acbe08659737714cc5f492 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 02:45:17 +0300 Subject: [PATCH] feat(Functional): add compact Status, ErrorKind/ErrorCode, bounded chains, and Adapters (M-FUNCTIONAL-02) --- include/Void/Functional/Adapters.hpp | 131 +++++++++++ include/Void/Functional/Error.hpp | 245 ++++++++++++++++++-- include/Void/Functional/Result.hpp | 16 ++ tests/standalone/Functional/ErrorStatus.cpp | 178 ++++++++++++++ 4 files changed, 556 insertions(+), 14 deletions(-) create mode 100644 include/Void/Functional/Adapters.hpp create mode 100644 tests/standalone/Functional/ErrorStatus.cpp diff --git a/include/Void/Functional/Adapters.hpp b/include/Void/Functional/Adapters.hpp new file mode 100644 index 0000000..5eed498 --- /dev/null +++ b/include/Void/Functional/Adapters.hpp @@ -0,0 +1,131 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Result +{ + namespace Detail + { + template struct is_expected_type : std::false_type {}; + template + struct is_expected_type> : std::true_type {}; + template + inline constexpr bool is_expected_v = + is_expected_type>::value; + } // namespace Detail + + /// Convert `std::expected` into `Result` by invoking `map_error` + /// only on the error path. Supports `void` and move-only value types. + template + requires std::invocable && + std::convertible_to, Error> + [[nodiscard]] constexpr Result adapt(std::expected exp, + Map&& map_error) + { + if (exp.has_value()) { + if constexpr (std::is_void_v) { + return {}; + } else { + return Result{std::move(*exp)}; + } + } + return Failure{static_cast( + std::invoke(std::forward(map_error), std::move(exp).error()))}; + } + + /// Invoke `fn()`, catching only exceptions accepted by + /// `map_exception(std::exception_ptr) -> std::optional`. + /// `std::bad_alloc` and unrecognized exceptions ALWAYS propagate. + template + requires std::invocable && + std::invocable && + std::convertible_to< + std::invoke_result_t, + std::optional> + [[nodiscard]] auto try_invoke(F&& fn, Map&& map_exception) + { + using Raw = std::invoke_result_t; + using Out = std::conditional_t, Raw, + Result>; + try { + if constexpr (std::is_void_v) { + std::invoke(std::forward(fn)); + return Out{}; + } else if constexpr (Detail::is_expected_v) { + return std::invoke(std::forward(fn)); + } else { + return Out{std::invoke(std::forward(fn))}; + } + } catch (const std::bad_alloc&) { + throw; + } catch (...) { + std::optional mapped = std::invoke( + std::forward(map_exception), std::current_exception()); + if (mapped.has_value()) { + return Out{std::unexpected{std::move(*mapped)}}; + } + throw; + } + } + + /// Map a POSIX errno value into a classified Error carrying `std::error_code`. + [[nodiscard]] inline Error from_errno(int errnum, std::string message = {}) + { + ErrorKind kind = ErrorKind::io; + switch (errnum) { + case EINVAL: + case EDOM: + case ERANGE: kind = ErrorKind::invalid_argument; break; + case ENOENT: + case ESRCH: kind = ErrorKind::not_found; break; + case EEXIST: + case EALREADY: + case EBUSY: kind = ErrorKind::conflict; break; + case ECANCELED: kind = ErrorKind::cancelled; break; + case ETIMEDOUT: kind = ErrorKind::timeout; break; + case EAGAIN: +#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + kind = ErrorKind::overloaded; + break; + case ENOSPC: + case ENOMEM: + case EMFILE: + case ENFILE: kind = ErrorKind::exhausted; break; + case ENOSYS: + case ENOTSUP: +#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP + case EOPNOTSUPP: +#endif + kind = ErrorKind::unsupported; + break; + case EILSEQ: + case EPROTO: + case EBADMSG: kind = ErrorKind::corrupt; break; + default: kind = ErrorKind::io; break; + } + if (message.empty()) { + message = std::strerror(errnum); + } + return Error{ + Status{kind, ErrorCode{kSystemErrorDomain, errnum}}, + std::move(message), + std::error_code{errnum, std::generic_category()}}; + } + +} // namespace Void::Result diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 1dd84ba..016ef37 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -1,36 +1,222 @@ #pragma once +#include +#include +#include #include #include #include +#include #include +#include namespace Void::Result { + /// Machine-readable classification shared across Void modules (C-02). + enum class ErrorKind : std::uint8_t { + invalid_argument = 0, + not_found, + conflict, + cancelled, + timeout, + overloaded, + unsupported, + io, + corrupt, + exhausted, + internal + }; + + [[nodiscard]] constexpr std::string_view + to_string(ErrorKind kind) noexcept + { + switch (kind) { + case ErrorKind::invalid_argument: return "invalid_argument"; + case ErrorKind::not_found: return "not_found"; + case ErrorKind::conflict: return "conflict"; + case ErrorKind::cancelled: return "cancelled"; + case ErrorKind::timeout: return "timeout"; + case ErrorKind::overloaded: return "overloaded"; + case ErrorKind::unsupported: return "unsupported"; + case ErrorKind::io: return "io"; + case ErrorKind::corrupt: return "corrupt"; + case ErrorKind::exhausted: return "exhausted"; + case ErrorKind::internal: return "internal"; + } + return "internal"; + } + + /// Explicit module error-domain identifiers. Domain 0 is reserved for + /// generic cross-module status values; domains are never assigned by + /// hashing type names. + inline constexpr std::uint32_t kGenericErrorDomain = 0; + inline constexpr std::uint32_t kCoreErrorDomain = 1; + inline constexpr std::uint32_t kMemoryErrorDomain = 2; + inline constexpr std::uint32_t kMathErrorDomain = 3; + inline constexpr std::uint32_t kTimeErrorDomain = 4; + inline constexpr std::uint32_t kBinaryErrorDomain = 5; + inline constexpr std::uint32_t kDataErrorDomain = 6; + inline constexpr std::uint32_t kAsyncErrorDomain = 7; + inline constexpr std::uint32_t kIoErrorDomain = 8; + inline constexpr std::uint32_t kStorageErrorDomain = 9; + inline constexpr std::uint32_t kSystemErrorDomain = 10; + + struct ErrorCode { + std::uint32_t domain{kGenericErrorDomain}; + std::int32_t value{0}; + + [[nodiscard]] constexpr bool + operator==(const ErrorCode&) const noexcept = default; + }; + + /// Compact, allocation-free failure descriptor suitable for low-memory and + /// Memory-layer error paths. + struct Status { + ErrorKind kind{ErrorKind::internal}; + ErrorCode code{}; + + [[nodiscard]] constexpr bool + operator==(const Status&) const noexcept = default; + }; + + inline constexpr std::size_t kDefaultMaxErrorFrames = 16; + inline constexpr std::size_t kDefaultMaxErrorMessageBytes = 1024; + inline constexpr std::size_t kDefaultMaxFormattedErrorBytes = 16 * 1024; + + namespace Detail + { + inline void bound_message(std::string& msg, bool& truncated) noexcept + { + constexpr std::string_view suffix = "...[truncated]"; + if (msg.size() <= kDefaultMaxErrorMessageBytes) { + return; + } + truncated = true; + const std::size_t keep = + kDefaultMaxErrorMessageBytes > suffix.size() + ? kDefaultMaxErrorMessageBytes - suffix.size() + : 0; + msg.resize(keep); + try { + msg.append(suffix); + } catch (...) { + // Preserve noexcept guarantee on bounded shrink. + } + } + } // namespace Detail + /// Default error type for Void::Result::Result. /// - /// An Error carries a free-form `message` and an optional chained - /// `cause`. New context layers can be added with `with_context()`, - /// which returns a new Error whose `cause` is the previous error — - /// useful for "loading config: parsing line 42: invalid number". - /// - /// Errors are cheap to copy (the cause chain is shared via - /// shared_ptr). + /// An Error carries a machine-readable `Status`, an optional + /// `std::error_code`, a bounded human-readable `message`, and an optional + /// shared immutable `cause` chain capped at `kDefaultMaxErrorFrames` (16). + /// Constructing from `Status` performs zero heap allocations. class Error { public: - Error() = default; + Error() noexcept = default; + + explicit Error(Status status) noexcept : m_status(status) {} + + Error(Status status, std::string message, + std::error_code sys = {}) noexcept + : m_status(status), m_system_code(sys), + m_message(std::move(message)) + { + Detail::bound_message(m_message, m_truncated); + } + + Error(ErrorKind kind, std::string message, ErrorCode code = {}, + std::error_code sys = {}) noexcept + : Error(Status{kind, code}, std::move(message), sys) + { + } explicit Error(std::string message) noexcept : m_message(std::move(message)) { + Detail::bound_message(m_message, m_truncated); } Error(std::string message, Error cause) - : m_message(std::move(message)), - m_cause(std::make_shared(std::move(cause))) + : m_status(cause.m_status), m_system_code(cause.m_system_code), + m_message(std::move(message)), m_truncated(cause.m_truncated) { + Detail::bound_message(m_message, m_truncated); + if (cause.m_depth < kDefaultMaxErrorFrames) { + m_depth = cause.m_depth + 1; + m_cause = std::make_shared(std::move(cause)); + return; + } + + // Exceeded frame budget: keep newest intermediate frames and + // pin the root frame at the tail so root classification/context + // is never lost. + std::vector chain; + chain.reserve(cause.m_depth); + for (const Error* cur = &cause; cur != nullptr; + cur = cur->m_cause.get()) { + chain.push_back(cur); + } + + m_truncated = true; + std::shared_ptr tail = + std::make_shared(Error{*chain.back(), true}); + const std::size_t keep_middle = + kDefaultMaxErrorFrames >= 2 ? kDefaultMaxErrorFrames - 2 : 0; + const std::size_t available_middle = + chain.size() > 1 ? chain.size() - 1 : 0; + const std::size_t take = std::min(keep_middle, available_middle); + for (std::size_t idx = take; idx > 0; --idx) { + auto node = std::make_shared( + Error{*chain[idx - 1], true}); + node->m_cause = tail; + node->m_depth = tail->m_depth + 1; + node->m_truncated = true; + tail = std::move(node); + } + m_cause = std::move(tail); + m_depth = m_cause->m_depth + 1; + } + + Error(const Error&) = default; + Error(Error&&) noexcept = default; + Error& operator=(const Error&) = default; + Error& operator=(Error&&) noexcept = default; + + ~Error() noexcept + { + std::shared_ptr cur = std::move(m_cause); + while (cur && cur.use_count() == 1) { + auto mutable_cur = std::const_pointer_cast(cur); + auto next = std::move(mutable_cur->m_cause); + cur = std::move(next); + } + } + + [[nodiscard]] Status status() const noexcept { return m_status; } + + [[nodiscard]] ErrorKind kind() const noexcept + { + return m_status.kind; + } + + [[nodiscard]] ErrorCode code() const noexcept + { + return m_status.code; + } + + [[nodiscard]] std::error_code system_code() const noexcept + { + return m_system_code; + } + + [[nodiscard]] std::size_t depth() const noexcept { return m_depth; } + + [[nodiscard]] bool truncated() const noexcept + { + return m_truncated; } [[nodiscard]] const std::string& message() const noexcept @@ -45,7 +231,7 @@ namespace Void::Result } /// Returns a new Error whose message is `ctx` and whose cause - /// is *this. + /// is *this, preserving root Status and system_code. [[nodiscard]] Error with_context(std::string ctx) const& { return Error{std::move(ctx), *this}; @@ -56,24 +242,55 @@ namespace Void::Result return Error{std::move(ctx), std::move(*this)}; } - /// Render the full cause chain as + /// Render the cause chain as /// "outer\n caused by: middle\n caused by: inner" + /// bounded by `kDefaultMaxFormattedErrorBytes`. [[nodiscard]] std::string format() const { - std::string out = m_message; + std::string out = + m_message.empty() ? std::string{to_string(m_status.kind)} + : m_message; const Error* cur = m_cause.get(); while (cur != nullptr) { out += "\n caused by: "; - out += cur->m_message; + out += cur->m_message.empty() + ? to_string(cur->m_status.kind) + : std::string_view{cur->m_message}; + if (out.size() >= kDefaultMaxFormattedErrorBytes) { + break; + } cur = cur->m_cause.get(); } + if (m_truncated) { + out += "\n [truncated: diagnostic limits applied]"; + } + if (out.size() > kDefaultMaxFormattedErrorBytes) { + constexpr std::string_view suffix = "\n...[truncated]"; + const std::size_t keep = + kDefaultMaxFormattedErrorBytes > suffix.size() + ? kDefaultMaxFormattedErrorBytes - suffix.size() + : 0; + out.resize(keep); + out.append(suffix); + } return out; } private: + Error(const Error& other, bool /*detach_cause*/) + : m_status(other.m_status), m_system_code(other.m_system_code), + m_message(other.m_message), m_depth(1), + m_truncated(other.m_truncated) + { + } + + Status m_status{}; + std::error_code m_system_code{}; std::string m_message; std::shared_ptr m_cause; + std::size_t m_depth{1}; + bool m_truncated{false}; }; } // namespace Void::Result diff --git a/include/Void/Functional/Result.hpp b/include/Void/Functional/Result.hpp index a1ab9bf..61f19ad 100644 --- a/include/Void/Functional/Result.hpp +++ b/include/Void/Functional/Result.hpp @@ -37,6 +37,22 @@ namespace Void::Result return Failure{Error{std::move(message)}}; } + /// Zero-allocation Failure factory from a compact Status. + [[nodiscard]] inline Failure fail(Status status) noexcept + { + return Failure{Error{status}}; + } + + /// Failure factory carrying explicit ErrorKind, message, and optional codes. + [[nodiscard]] inline Failure fail(ErrorKind kind, + std::string message, + ErrorCode code = {}, + std::error_code sys = {}) + { + return Failure{ + Error{kind, std::move(message), code, sys}}; + } + /// Convenience factory for a failed Result with an arbitrary E. /// Constrained so string-like types resolve to the `std::string` /// overload above (otherwise a literal `"..."` deduces E to a char diff --git a/tests/standalone/Functional/ErrorStatus.cpp b/tests/standalone/Functional/ErrorStatus.cpp new file mode 100644 index 0000000..2a00d38 --- /dev/null +++ b/tests/standalone/Functional/ErrorStatus.cpp @@ -0,0 +1,178 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Void::Testing::Test compact_status_is_noexcept_and_empty_message() +{ + constexpr Void::Result::Status st{ + Void::Result::ErrorKind::overloaded, + Void::Result::ErrorCode{Void::Result::kAsyncErrorDomain, 42}}; + static_assert(std::is_nothrow_constructible_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(noexcept(Void::Result::fail(st))); + + Void::Result::Error err{st}; + auto r = Void::Result::fail(st); + + Void::Testing::expect(err.kind() == Void::Result::ErrorKind::overloaded); + Void::Testing::expect(err.code() == st.code); + Void::Testing::expect(err.message().empty()); + Void::Testing::expect(err.cause() == nullptr); + Void::Testing::expect(!err.truncated()); + Void::Testing::expect(r.error().kind() == + Void::Result::ErrorKind::overloaded); +} + +Void::Testing::Test context_chain_caps_at_16_and_preserves_root() +{ + Void::Result::Error err{ + Void::Result::ErrorKind::not_found, "root missing file", + Void::Result::ErrorCode{Void::Result::kSystemErrorDomain, ENOENT}, + std::error_code{ENOENT, std::generic_category()}}; + + for (int i = 1; i <= 19; ++i) { + err = std::move(err).with_context("layer_" + std::to_string(i)); + } + + Void::Testing::expect_eq(err.depth(), + Void::Result::kDefaultMaxErrorFrames); + Void::Testing::expect(err.truncated()); + Void::Testing::expect(err.kind() == Void::Result::ErrorKind::not_found); + Void::Testing::expect_eq(err.code().domain, + Void::Result::kSystemErrorDomain); + Void::Testing::expect_eq(err.code().value, ENOENT); + Void::Testing::expect_eq(err.system_code().value(), ENOENT); + Void::Testing::expect_eq(err.message(), std::string{"layer_19"}); + + const Void::Result::Error* tail = &err; + std::size_t count = 1; + while (tail->cause() != nullptr) { + tail = tail->cause().get(); + ++count; + } + Void::Testing::expect_eq(count, Void::Result::kDefaultMaxErrorFrames); + Void::Testing::expect_eq(tail->message(), std::string{"root missing file"}); + + const std::string rendered = err.format(); + Void::Testing::expect(rendered.find("root missing file") != + std::string::npos); + Void::Testing::expect(rendered.find("[truncated:") != std::string::npos); +} + +Void::Testing::Test message_and_format_bounds_enforced() +{ + std::string huge(3000, 'x'); + Void::Result::Error single{Void::Result::ErrorKind::invalid_argument, + std::move(huge)}; + Void::Testing::expect(single.truncated()); + Void::Testing::expect(single.message().size() <= + Void::Result::kDefaultMaxErrorMessageBytes); + Void::Testing::expect(single.message().ends_with("...[truncated]")); + + // Build a 16-frame chain of 1 KiB messages to check total formatted cap + // (~16+ KiB > kDefaultMaxFormattedErrorBytes). + std::string chunk(1000, 'y'); + Void::Result::Error chain{Void::Result::ErrorKind::corrupt, chunk}; + for (int i = 0; i < 16; ++i) { + chain = std::move(chain).with_context(chunk); + } + const std::string formatted = chain.format(); + Void::Testing::expect(formatted.size() <= + Void::Result::kDefaultMaxFormattedErrorBytes); +} + +Void::Testing::Test adapt_handles_move_only_void_and_skips_mapper_on_ok() +{ + bool mapper_called = false; + auto ok_ptr = Void::Result::adapt( + std::expected, int>{std::make_unique(99)}, + [&](int) { + mapper_called = true; + return Void::Result::Error{"bad"}; + }); + Void::Testing::expect(!mapper_called); + Void::Testing::expect(ok_ptr.has_value() && **ok_ptr == 99); + + auto err_void = Void::Result::adapt( + std::expected{std::unexpected{7}}, [&](int v) { + mapper_called = true; + return Void::Result::Error{ + Void::Result::ErrorKind::invalid_argument, + "code " + std::to_string(v)}; + }); + Void::Testing::expect(mapper_called); + Void::Testing::expect(!err_void.has_value()); + Void::Testing::expect(err_void.error().kind() == + Void::Result::ErrorKind::invalid_argument); +} + +Void::Testing::Test try_invoke_maps_known_and_rethrows_unknown_and_bad_alloc() +{ + auto map_known = [](std::exception_ptr ep) + -> std::optional { + try { + std::rethrow_exception(ep); + } catch (const std::invalid_argument& ex) { + return Void::Result::Error{ + Void::Result::ErrorKind::invalid_argument, ex.what()}; + } catch (...) { + return std::nullopt; + } + }; + + auto mapped = Void::Result::try_invoke( + []() -> int { throw std::invalid_argument{"bad arg"}; }, map_known); + Void::Testing::expect(!mapped.has_value()); + Void::Testing::expect(mapped.error().kind() == + Void::Result::ErrorKind::invalid_argument); + + bool rethrew_unknown = false; + try { + (void)Void::Result::try_invoke( + []() -> void { throw std::runtime_error{"unhandled"}; }, map_known); + } catch (const std::runtime_error&) { + rethrew_unknown = true; + } + Void::Testing::expect(rethrew_unknown); + + bool rethrew_bad_alloc = false; + auto catch_all_mapper = [](std::exception_ptr) + -> std::optional { + return Void::Result::Error{"should not catch bad_alloc"}; + }; + try { + (void)Void::Result::try_invoke( + []() -> int { throw std::bad_alloc{}; }, catch_all_mapper); + } catch (const std::bad_alloc&) { + rethrew_bad_alloc = true; + } + Void::Testing::expect(rethrew_bad_alloc); +} + +Void::Testing::Test from_errno_maps_categories() +{ + const auto nf = Void::Result::from_errno(ENOENT); + Void::Testing::expect(nf.kind() == Void::Result::ErrorKind::not_found); + Void::Testing::expect_eq(nf.system_code().value(), ENOENT); + + const auto to = Void::Result::from_errno(ETIMEDOUT, "socket wait"); + Void::Testing::expect(to.kind() == Void::Result::ErrorKind::timeout); + Void::Testing::expect_eq(to.message(), std::string{"socket wait"}); + + const auto ex = Void::Result::from_errno(ENOSPC); + Void::Testing::expect(ex.kind() == Void::Result::ErrorKind::exhausted); +}