error.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_ERROR_H_
  5. #define CARBON_COMMON_ERROR_H_
  6. #include <concepts>
  7. #include <functional>
  8. #include <string>
  9. #include <type_traits>
  10. #include <utility>
  11. #include <variant>
  12. #include "common/check.h"
  13. #include "common/ostream.h"
  14. #include "common/raw_string_ostream.h"
  15. #include "llvm/ADT/Twine.h"
  16. namespace Carbon {
  17. // Success values should be represented as the presence of a value in ErrorOr,
  18. // using `ErrorOr<Success>` and `return Success();` if no value needs to be
  19. // returned.
  20. struct Success : public Printable<Success> {
  21. auto Print(llvm::raw_ostream& out) const -> void { out << "Success"; }
  22. };
  23. // Tracks an error message.
  24. //
  25. // This is nodiscard to enforce error handling prior to destruction.
  26. class [[nodiscard]] Error : public Printable<Error> {
  27. public:
  28. // Represents an error state.
  29. explicit Error(llvm::Twine message) : message_(message.str()) {
  30. CARBON_CHECK(!message_.empty(), "Errors must have a message.");
  31. }
  32. // Move-only.
  33. Error(Error&& other) noexcept = default;
  34. auto operator=(Error&& other) noexcept -> Error& = default;
  35. // Prints the error string.
  36. auto Print(llvm::raw_ostream& out) const -> void { out << message(); }
  37. // Returns the error message.
  38. auto message() const -> const std::string& { return message_; }
  39. private:
  40. // The error message.
  41. std::string message_;
  42. };
  43. // A common base class that custom error types should derive from.
  44. //
  45. // This combines the ability to be printed with the ability to convert the error
  46. // to a string and in turn to a non-customized `Error` type by rendering into a
  47. // string.
  48. //
  49. // The goal is that custom error types can be used for errors that are common
  50. // and/or would have cost to fully render the error message to a string. A
  51. // custom type can then be used to allow custom, light-weight handling of errors
  52. // when appropriate. But to avoid these custom types being excessively viral, we
  53. // ensure they can be converted to normal `Error` types when needed by rendering
  54. // fully to a string.
  55. template <typename ErrorT>
  56. class [[nodiscard]] ErrorBase : public Printable<ErrorT> {
  57. public:
  58. ErrorBase(const ErrorBase&) = delete;
  59. auto operator=(const ErrorBase&) -> ErrorBase& = delete;
  60. auto ToString() const -> std::string {
  61. RawStringOstream os;
  62. static_cast<const ErrorT*>(this)->Print(os);
  63. return os.TakeStr();
  64. }
  65. auto ToError() const -> Error { return Error(this->ToString()); }
  66. protected:
  67. ErrorBase() = default;
  68. ErrorBase(ErrorBase&&) noexcept = default;
  69. auto operator=(ErrorBase&&) noexcept -> ErrorBase& = default;
  70. };
  71. // Holds a value of type `T`, or an `ErrorT` type explaining why the value is
  72. // unavailable.
  73. //
  74. // The `ErrorT` type defaults to `Error` but can be customized where desired
  75. // with a type that derives from `ErrorBase` above. See the documentation for
  76. // `ErrorBase` to understand the expected contract of custom error types.
  77. //
  78. // This is nodiscard to enforce error handling prior to destruction.
  79. template <typename T, typename ErrorT = Error>
  80. class [[nodiscard]] ErrorOr {
  81. public:
  82. using ValueT = std::remove_reference_t<T>;
  83. // Check that the custom error type is structured the way we expect. These
  84. // need to be `static_assert`s to enable forward declared error types to be
  85. // used with `ErrorOr` in function signatures.
  86. static_assert(!std::is_reference_v<ErrorT>);
  87. static_assert(std::same_as<ErrorT, Error> ||
  88. std::derived_from<ErrorT, ErrorBase<ErrorT>>);
  89. // Constructs with an error; the error must not be Error::Success().
  90. // Implicit for easy construction on returns.
  91. explicit(false) ErrorOr(ErrorT err) : val_(std::move(err)) {}
  92. // Constructs from a custom error type derived from `ErrorBase` into an
  93. // `ErrorOr` for `Error` to facilitate returning errors transparently.
  94. template <typename OtherErrorT>
  95. requires(std::same_as<ErrorT, Error> &&
  96. std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
  97. // Implicit for easy construction on returns.
  98. explicit(false) ErrorOr(OtherErrorT other_err) : val_(other_err.ToError()) {}
  99. // Constructs with any convertible error type, necessary for return statements
  100. // that are already converting to the `ErrorOr` wrapper.
  101. //
  102. // This supports *explicitly* conversions, not just implicit, which is
  103. // important to make common patterns of returning and adjusting the error
  104. // type without each error type conversion needing to be implicit.
  105. template <typename OtherErrorT>
  106. requires(std::constructible_from<ErrorT, OtherErrorT> &&
  107. std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
  108. // Implicit for easy construction on returns.
  109. explicit(false) ErrorOr(OtherErrorT other_err)
  110. : val_(std::in_place_type<ErrorT>, std::move(other_err)) {}
  111. // Constructs with a reference.
  112. // Implicit for easy construction on returns.
  113. explicit(false) ErrorOr(T ref)
  114. requires std::is_reference_v<T>
  115. : val_(std::ref(ref)) {}
  116. // Constructs with a value.
  117. // Implicit for easy construction on returns.
  118. explicit(false) ErrorOr(T val)
  119. requires(!std::is_reference_v<T>)
  120. : val_(std::move(val)) {}
  121. // Returns true for success.
  122. auto ok() const -> bool { return std::holds_alternative<StoredT>(val_); }
  123. // Returns the contained error.
  124. // REQUIRES: `ok()` is false.
  125. auto error() const& -> const ErrorT& {
  126. CARBON_CHECK(!ok());
  127. return std::get<ErrorT>(val_);
  128. }
  129. auto error() && -> ErrorT {
  130. CARBON_CHECK(!ok());
  131. return std::get<ErrorT>(std::move(val_));
  132. }
  133. // Checks that `ok()` is true.
  134. // REQUIRES: `ok()` is true.
  135. auto Check() const -> void { CARBON_CHECK(ok(), "{0}", error()); }
  136. // Returns the contained value.
  137. // REQUIRES: `ok()` is true.
  138. [[nodiscard]] auto operator*() & -> ValueT& {
  139. Check();
  140. return std::get<StoredT>(val_);
  141. }
  142. // Returns the contained value.
  143. // REQUIRES: `ok()` is true.
  144. [[nodiscard]] auto operator*() const& -> const ValueT& {
  145. Check();
  146. return std::get<StoredT>(val_);
  147. }
  148. // Returns the contained value.
  149. // REQUIRES: `ok()` is true.
  150. [[nodiscard]] auto operator*() && -> ValueT&& {
  151. Check();
  152. return std::get<StoredT>(std::move(val_));
  153. }
  154. // Returns the contained value.
  155. // REQUIRES: `ok()` is true.
  156. auto operator->() -> ValueT* { return &**this; }
  157. // Returns the contained value.
  158. // REQUIRES: `ok()` is true.
  159. auto operator->() const -> const ValueT* { return &**this; }
  160. private:
  161. using StoredT = std::conditional_t<std::is_reference_v<T>,
  162. std::reference_wrapper<ValueT>, T>;
  163. // Either an error message or a value.
  164. std::variant<ErrorT, StoredT> val_;
  165. };
  166. // A helper class for accumulating error message and converting to
  167. // `Error` and `ErrorOr<T>`.
  168. class ErrorBuilder {
  169. public:
  170. explicit ErrorBuilder() : out_(std::make_unique<RawStringOstream>()) {}
  171. ErrorBuilder(ErrorBuilder&&) = default;
  172. auto operator=(ErrorBuilder&&) -> ErrorBuilder& = default;
  173. // Accumulates string message to a temporary `ErrorBuilder`. After streaming,
  174. // the builder must be converted to an `Error` or `ErrorOr`.
  175. template <typename T>
  176. auto operator<<(T&& message) && -> ErrorBuilder&& {
  177. *out_ << message;
  178. return std::move(*this);
  179. }
  180. // Accumulates string message for an lvalue error builder.
  181. template <typename T>
  182. auto operator<<(T&& message) & -> ErrorBuilder& {
  183. *out_ << message;
  184. return *this;
  185. }
  186. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  187. explicit(false) operator Error() { return Error(out_->TakeStr()); }
  188. template <typename T>
  189. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  190. explicit(false) operator ErrorOr<T>() {
  191. return Error(out_->TakeStr());
  192. }
  193. private:
  194. std::unique_ptr<RawStringOstream> out_;
  195. };
  196. } // namespace Carbon
  197. // Macro hackery to get a unique variable name.
  198. #define CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c) a##b##c
  199. #define CARBON_MAKE_UNIQUE_NAME(a, b, c) CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c)
  200. // Macro to prevent a top-level comma from being interpreted as a macro
  201. // argument separator.
  202. #define CARBON_PROTECT_COMMAS(...) __VA_ARGS__
  203. #define CARBON_RETURN_IF_ERROR_IMPL(unique_name, expr) \
  204. if (auto unique_name = (expr); !(unique_name).ok()) { \
  205. return std::move(unique_name).error(); \
  206. }
  207. #define CARBON_RETURN_IF_ERROR(expr) \
  208. CARBON_RETURN_IF_ERROR_IMPL( \
  209. CARBON_MAKE_UNIQUE_NAME(_llvm_error_line, __LINE__, __COUNTER__), \
  210. CARBON_PROTECT_COMMAS(expr))
  211. #define CARBON_ASSIGN_OR_RETURN_IMPL(unique_name, var, expr) \
  212. auto unique_name = (expr); \
  213. if (!(unique_name).ok()) { \
  214. return std::move(unique_name).error(); \
  215. } \
  216. var = std::move(*(unique_name));
  217. #define CARBON_ASSIGN_OR_RETURN(var, expr) \
  218. CARBON_ASSIGN_OR_RETURN_IMPL( \
  219. CARBON_MAKE_UNIQUE_NAME(_llvm_expected_line, __LINE__, __COUNTER__), \
  220. CARBON_PROTECT_COMMAS(var), CARBON_PROTECT_COMMAS(expr))
  221. #endif // CARBON_COMMON_ERROR_H_