Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
66ce386
start work on Result class
SizzinSeal Mar 20, 2025
5878600
remove const qualifier from Result member variables
SizzinSeal Mar 28, 2025
e0c4824
move ResultError type member to the end of the struct
SizzinSeal Mar 28, 2025
69bb041
add const qualifier to parse member function of ResultError formatter
SizzinSeal Mar 28, 2025
bdecefa
make << operator use std::format for ResultError
SizzinSeal Mar 28, 2025
641d235
add some "flair" to result stacktrace formatting
SizzinSeal Mar 28, 2025
326b332
more consistent template parameter typing in result.hpp
SizzinSeal Mar 28, 2025
2fba9c7
remove Result move constructor, as it's equivalent to the implicit mo…
SizzinSeal Mar 28, 2025
76b7c67
add option for forcing explicit unwrapping of Result
SizzinSeal Mar 29, 2025
f8cdc43
fix meson language server ramblings
SizzinSeal Mar 29, 2025
ac4609e
use error types in Result class
SizzinSeal Apr 27, 2025
ac561fe
mark Result constructor as explicit
SizzinSeal Apr 28, 2025
1f2ac91
improve sentinel trait naming
SizzinSeal Apr 28, 2025
3d2fdd2
clean up Result constraints
SizzinSeal Apr 29, 2025
edf7646
improve get member function of Result
SizzinSeal Apr 29, 2025
1033540
specialize Result with void type
SizzinSeal Apr 29, 2025
d83b85f
require at least one error type in the Result class
SizzinSeal Apr 29, 2025
15eb38d
fix Result constructor warnings
SizzinSeal Apr 29, 2025
67f6c8a
add comparison operator overload to Result
SizzinSeal Apr 29, 2025
83328b2
Merge branch 'main' into feat/better-errors
SizzinSeal Apr 29, 2025
84f3e7e
Merge branch 'feat/better-errors' of https://github.com/ZestCommunity…
SizzinSeal Apr 29, 2025
99398cf
improve Result comparison operator
SizzinSeal Apr 29, 2025
dc99edf
fix SentinelValue specialization for integral types
SizzinSeal Apr 29, 2025
41c3d29
fix Result ctor order warnings
SizzinSeal Apr 29, 2025
7d4eea4
add time point to ResultError
SizzinSeal Apr 29, 2025
3628c58
improve Result error type constraints
SizzinSeal Apr 30, 2025
d5a4999
use infinity as a sentinel value if possible
SizzinSeal Apr 30, 2025
479f1c4
fix bad variant access in Result::get
SizzinSeal Apr 30, 2025
953874f
fix SentinelValue floating-point values
SizzinSeal May 1, 2025
c0408dc
use doxygen documentation in result.hpp
SizzinSeal May 1, 2025
f397080
use std::remove_cvref instead of std::remove_cvref_t in result.hpp
SizzinSeal May 1, 2025
7d1792e
fix ambiguous Result comparison operator
SizzinSeal May 2, 2025
a930af2
add comparison operator tests for Result
SizzinSeal May 2, 2025
7a86847
add Result void specialization test
SizzinSeal May 2, 2025
ce756f7
remove `constexpr` qualifiers for certain `Result` member functions
SizzinSeal May 2, 2025
11d3b0d
support compile-time ResultError
SizzinSeal May 2, 2025
5f1ff0b
use proper move semantics for Result conversion operators
SizzinSeal May 2, 2025
d41d766
remove Result conversion operators returning r-value references
SizzinSeal May 2, 2025
255afd4
fix Result conversion operator qualifiers again
SizzinSeal May 2, 2025
b329187
add const-rvalue reference overload for Result::get
SizzinSeal May 2, 2025
29c8fa6
rename Result.cpp to result.cpp
SizzinSeal May 2, 2025
36f16db
fix Result::get return types
SizzinSeal May 3, 2025
44b326e
fix meson language server tweaking
SizzinSeal May 3, 2025
3a07636
fix Result::get return type
SizzinSeal May 3, 2025
b6a854a
add more Result compile-time tests
SizzinSeal May 3, 2025
92bdad1
add second Result test function
SizzinSeal May 3, 2025
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
314 changes: 314 additions & 0 deletions include/common/result.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
#pragma once

#include <chrono>
#include <concepts>
#include <limits>
#include <optional>
#include <stacktrace>
#include <variant>

namespace zest {

/**
* @brief Base class for custom error types used in the Result class.
*
*/
class ResultError {
public:
/**
* @brief struct containing data that can only be known at runtime.
*
*/
struct RuntimeData {
std::stacktrace stacktrace;
std::chrono::time_point<std::chrono::system_clock> time;
};

/**
* @brief Construct a new ResultError object.
*
* @details Captures the current stacktrace and system time if called at runtime.
*/
constexpr ResultError() {
if !consteval {
runtime_data = {
.stacktrace = std::stacktrace::current(),
.time = std::chrono::system_clock::now()
};
}
}

std::optional<RuntimeData> runtime_data;
};

/**
* @brief Trait to define a "sentinel" value for types indicating an error state.
* @tparam T Type to provide a sentinel value for.
* @note Specialize this template for custom types if needed.
*/
template<typename T>
class SentinelValue;

/**
* @brief Concept to check if a type has a defined sentinel value.
* @tparam T Type to check.
*/
template<typename T>
concept Sentinel = requires(const T& val) { SentinelValue<T>::value; };

/**
* @brief Helper variable to simplify access to a type's sentinel value.
* @tparam T Type with a defined sentinel (must satisfy Sentinel concept).
*/
template<Sentinel T>
constexpr T sentinel_v = SentinelValue<T>::value;

/**
* @brief Partial specialization of SentinelValue for integral and floating-point types.
* @tparam T Integral or floating-point type.
* @details Uses infinity for floating-point types if available; otherwise uses max value.
*/
template<typename T>
requires(std::integral<T> || std::floating_point<T>)
class SentinelValue<T> {
public:
static constexpr T get() {
if constexpr (std::numeric_limits<T>::has_infinity) {
return std::numeric_limits<T>::infinity();
} else {
return std::numeric_limits<T>::max();
}
}

static constexpr T value = get(); ///< Precomputed sentinel value for type T.
};

/**
* @brief Result class for expected value or error handling (similar to std::expected).
* @tparam T Type of the expected value.
* @tparam Errs List of possible error types (must inherit from ResultError).
* @note Errors are stored in a variant, and the value is always initialized.
*/
template<typename T, typename... Errs>
requires(sizeof...(Errs) > 0) && (std::derived_from<Errs, ResultError> && ...)
class Result {
public:
/**
* @brief Construct a Result with a normal value (no error).
* @tparam U Type convertible to T.
* @param value Value to initialize the result with.
*/
template<typename U>
requires std::constructible_from<T, U>
constexpr Result(U&& value)
: error(std::monostate()),
value(std::forward<U>(value)) {}

/**
* @brief Construct a Result with a value and an error.
* @tparam U Type convertible to T.
* @tparam E Error type (must be in Errs).
* @param value Value to store.
* @param error Error to store.
*/
template<typename U, typename E>
requires std::constructible_from<T, U>
&& (std::same_as<std::remove_cvref_t<E>, Errs> || ...)
constexpr Result(U&& value, E&& error)
: value(std::forward<U>(value)),
error(std::forward<E>(error)) {}

/**
* @brief Construct a Result with an error, initializing the value to its sentinel.
* @tparam E Error type (must be in Errs).
* @param error Error to store.
* @note Requires T to have a defined sentinel value (via SentinelValue<T>).
*/
template<typename E>
requires Sentinel<T> && (std::same_as<std::remove_cvref_t<E>, Errs> || ...)
constexpr Result(E&& error)
: error(std::forward<E>(error)),
value(sentinel_v<T>) {}

/**
* @brief Get an error of type E if present (const-qualified overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr std::optional<E> get() const& {
if (std::holds_alternative<E>(error)) {
return std::get<E>(error);
} else {
return std::nullopt;
}
}

/**
* @brief Get an error of type E if present (rvalue overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr std::optional<E> get() && {
if (std::holds_alternative<E>(error)) {
return std::move(std::get<E>(error));
} else {
return std::nullopt;
}
}

/**
* @brief Get an error of type E if present (const rvalue overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr const std::optional<E> get() const&& {
if (std::holds_alternative<E>(error)) {
return std::move(std::get<E>(error));
} else {
return std::nullopt;
}
}

/**
* @brief Get the stored value (const-qualified overload).
* @return T Copy of the stored value.
*/
template<typename U = T>
requires std::same_as<U, T>
constexpr T get() const& {
return value;
}

/**
* @brief Get the stored value (rvalue overload).
* @return T Moved value.
*/
template<typename U = T>
requires std::same_as<U, T>
constexpr T get() && {
return std::move(value);
}

constexpr operator T&() & {
return value;
}

constexpr operator const T&() const& {
return value;
};

constexpr operator T&&() && {
return std::move(value);
}

constexpr operator const T&&() const&& {
return std::move(value);
}

/**
* @brief error value
* @details instead of wrapping the variant in std::optional, it's more efficient to use
* std::monostate. since we have to use std::variant in any case.
*/
std::variant<std::monostate, Errs...> error;
T value;
};

/**
* @brief compare Result instances with comparable normal values
*
* @tparam LhsT the normal value type of the left-hand side argument
* @tparam RhsT the normal value type of the right-hand side argument
* @tparam LhsErrs the error value types of the left-hand side argument
* @tparam RhsErrs the error value types of the right-hand side argument
* @param lhs the left-hand side of the expression
* @param rhs the right-hand side of the expression
* @return true if the values are equal
* @return false if the values are not equal
*/
template<typename LhsT, typename RhsT, typename... LhsErrs, typename... RhsErrs>
requires std::equality_comparable_with<LhsT, RhsT>
constexpr bool
operator==(const Result<LhsT, LhsErrs...>& lhs, const Result<RhsT, RhsErrs...>& rhs) {
return lhs.value == rhs.value;
}

/**
* @brief Result specialization for void value type (no stored value).
* @tparam Errs List of possible error types (must inherit from ResultError).
*/
template<typename... Errs>
requires(sizeof...(Errs) > 0) && (std::derived_from<Errs, ResultError> && ...)
class Result<void, Errs...> {
public:
/**
* @brief Construct a Result with an error.
* @tparam E Error type (must be in Errs).
* @param error Error to store.
*/
template<typename E>
requires(std::same_as<std::remove_cvref_t<E>, Errs> || ...)
constexpr Result(E&& error)
: error(std::forward<E>(error)) {}

/**
* @brief Construct a Result with no error (success state).
*/
constexpr Result()
: error(std::monostate()) {}

/**
* @brief Get an error of type E if present (const-qualified overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr std::optional<E> get() const& {
if (std::holds_alternative<E>(error)) {
return std::get<E>(error);
} else {
return std::nullopt;
}
}

/**
* @brief Get an error of type E if present (rvalue overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr std::optional<E> get() && {
if (std::holds_alternative<E>(error)) {
return std::move(std::get<E>(error));
} else {
return std::nullopt;
}
}

/**
* @brief Get an error of type E if present (const rvalue overload).
* @tparam E Error type to retrieve.
* @return std::optional<E> Contains the error if present; otherwise nullopt.
*/
template<typename E>
requires(std::same_as<E, Errs> || ...)
constexpr const std::optional<E> get() const&& {
if (std::holds_alternative<E>(error)) {
return std::move(std::get<E>(error));
} else {
return std::nullopt;
}
}

std::variant<std::monostate, Errs...> error; ///< Variant holding an error or monostate.
};

} // namespace zest
16 changes: 11 additions & 5 deletions meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ linker_flags = [
# system libraries we depend on
system_deps = [
'-nostartfiles', # we still need to implement some newlib stubs
'-lstdc++exp',
]
add_global_link_arguments( system_deps, language: 'c')
add_global_link_arguments(system_deps, language: 'cpp')
Expand All @@ -73,11 +74,16 @@ stdlib_conf = [
'-D_POSIX_MONOTONIC_CLOCK', # enable the POSIX monotonic clock
]

# warning flags
warning_flags = [
'-Wno-psabi' # all libraries (except libv5) are compiled from source, making this warning useless
]

# apply all these flags and configs
add_global_arguments(optimization_flags, formatting_flags, stdlib_conf, language: 'c')
add_global_arguments(optimization_flags, formatting_flags, stdlib_conf, language: 'cpp')
add_global_link_arguments(optimization_flags, linker_flags, formatting_flags, system_deps, language: 'c')
add_global_link_arguments(optimization_flags, linker_flags, formatting_flags, system_deps, language: 'cpp')
add_global_arguments(optimization_flags, formatting_flags, warning_flags, stdlib_conf, language: 'c')
add_global_arguments(optimization_flags, formatting_flags, warning_flags, stdlib_conf, language: 'cpp')
add_global_link_arguments(optimization_flags, linker_flags, formatting_flags, warning_flags, system_deps, language: 'c')
add_global_link_arguments(optimization_flags, linker_flags, formatting_flags, warning_flags, system_deps, language: 'cpp')

# include directories.
# we only specify the top level in order to enforce paths in include directives.
Expand Down Expand Up @@ -109,4 +115,4 @@ custom_target(
input: elf,
build_by_default: true, # otherwise it won't be built
command: [objcopy, ['-O', 'binary', '-S', '@INPUT@', '@OUTPUT@']],
)
)
Loading
Loading