20#include <unordered_map>
22#ifdef TCALC_USE_TL_EXPECTED
23#include <tl/expected.hpp>
24#define _TCALC_EXPECTED_NS tl
27#define _TCALC_EXPECTED_NS std
32#define ret_err(expr) \
33 if (auto res = (expr); !res.has_value()) { \
34 return _TCALC_EXPECTED_NS::unexpected(res.error()); \
37#define unwrap_err(expr) \
40 if (!_ret.has_value()) { \
41 return _TCALC_EXPECTED_NS::unexpected(_ret.error()); \
46#define log_err(expr) \
49 if (!_ret.has_value()) { \
54#define log_err_exit(expr) \
57 if (!_ret.has_value()) { \
59 std::exit(EXIT_FAILURE); \
63namespace tcalc::error {
80inline const std::unordered_map<Code, std::string>
CODE_NAMES = {
81 { Code::SYNTAX_ERROR,
"SYNAX_ERROR" },
82 { Code::UNDEFINED_VAR,
"UNDEFINED_VAR" },
83 { Code::UNDEFINED_FUNC,
"UNDEFINED_FUNC" },
84 { Code::MISMATCHED_ARGS,
"MISMATCHED_ARGS" },
85 { Code::ZERO_DIVISION,
"ZERO_DIVISION" },
86 { Code::RECURSION_LIMIT,
"RECURSION_LIMIT" },
87 { Code::FILE_NOT_FOUND,
"FILE_NOT_FOUND" },
94class TCALC_PUBLIC
Error :
public std::exception
97 constexpr static std::size_t MAX_MSG_LEN = 256;
112 , _msg{ std::move(msg) }
121 [[nodiscard]] TCALC_INLINE
auto code() const noexcept {
return _code; }
128 [[nodiscard]] TCALC_INLINE
const auto&
msg() const noexcept {
return _msg; }
134 void log() const noexcept;
141 [[nodiscard]] const
char* what() const noexcept
override
153using Result = _TCALC_EXPECTED_NS::expected<T, Error>;
163err(
Code code,
const std::string& message)
noexcept
165 return _TCALC_EXPECTED_NS::unexpected(
Error(code, message));
177 auto errno_copy = errno;
179 errno_copy == 0 ?
"Unknown error" : std::strerror(errno_copy));
191 return _TCALC_EXPECTED_NS::unexpected(
raw_err(code));
204TCALC_PRINTF_FORMAT(2, 3)
205_TCALC_EXPECTED_NS::unexpected<Error>
206err(Code code, const
char* fmt, ...) noexcept;
216template<typename T, typename... Args>
218ok(Args&&... args) noexcept
220 return _TCALC_EXPECTED_NS::expected<T, Error>(T(std::forward<Args>(args)...));
232 return _TCALC_EXPECTED_NS::expected<void, Error>();
Error class.
Definition error.hpp:95
Error(Code code, std::string msg) noexcept
Construct a new Error object (should be noexcept in semantic).
Definition error.hpp:110
TCALC_INLINE const auto & msg() const noexcept
Get error message.
Definition error.hpp:128
TCALC_INLINE auto code() const noexcept
Get error code.
Definition error.hpp:121
TCALC_INLINE auto err(Code code, const std::string &message) noexcept
Create an error.
Definition error.hpp:163
_TCALC_EXPECTED_NS::expected< T, Error > Result
Result type.
Definition error.hpp:153
Code
Error code.
Definition error.hpp:70
TCALC_INLINE auto raw_err(Code code) noexcept
Create a raw error with errno.
Definition error.hpp:175
const std::unordered_map< Code, std::string > CODE_NAMES
Definition error.hpp:80