error.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. // NOLINTNEXTLINE(google-explicit-constructor)
  92. ErrorOr(ErrorT err) : val_(std::move(err)) {}
  93. // Constructs from a custom error type derived from `ErrorBase` into an
  94. // `ErrorOr` for `Error` to facilitate returning errors transparently.
  95. template <typename OtherErrorT>
  96. requires(std::same_as<ErrorT, Error> &&
  97. std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
  98. // Implicit for easy construction on returns.
  99. // NOLINTNEXTLINE(google-explicit-constructor)
  100. ErrorOr(OtherErrorT other_err) : val_(other_err.ToError()) {}
  101. // Constructs with any convertible error type, necessary for return statements
  102. // that are already converting to the `ErrorOr` wrapper.
  103. //
  104. // This supports *explicitly* conversions, not just implicit, which is
  105. // important to make common patterns of returning and adjusting the error
  106. // type without each error type conversion needing to be implicit.
  107. template <typename OtherErrorT>
  108. requires(std::constructible_from<ErrorT, OtherErrorT> &&
  109. std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
  110. // Implicit for easy construction on returns.
  111. // NOLINTNEXTLINE(google-explicit-constructor)
  112. ErrorOr(OtherErrorT other_err)
  113. : val_(std::in_place_type<ErrorT>, std::move(other_err)) {}
  114. // Constructs with a reference.
  115. // Implicit for easy construction on returns.
  116. // NOLINTNEXTLINE(google-explicit-constructor)
  117. ErrorOr(T ref)
  118. requires std::is_reference_v<T>
  119. : val_(std::ref(ref)) {}
  120. // Constructs with a value.
  121. // Implicit for easy construction on returns.
  122. // NOLINTNEXTLINE(google-explicit-constructor)
  123. ErrorOr(T val)
  124. requires(!std::is_reference_v<T>)
  125. : val_(std::move(val)) {}
  126. // Returns true for success.
  127. auto ok() const -> bool { return std::holds_alternative<StoredT>(val_); }
  128. // Returns the contained error.
  129. // REQUIRES: `ok()` is false.
  130. auto error() const& -> const ErrorT& {
  131. CARBON_CHECK(!ok());
  132. return std::get<ErrorT>(val_);
  133. }
  134. auto error() && -> ErrorT {
  135. CARBON_CHECK(!ok());
  136. return std::get<ErrorT>(std::move(val_));
  137. }
  138. // Checks that `ok()` is true.
  139. // REQUIRES: `ok()` is true.
  140. auto Check() const -> void { CARBON_CHECK(ok(), "{0}", error()); }
  141. // Returns the contained value.
  142. // REQUIRES: `ok()` is true.
  143. [[nodiscard]] auto operator*() & -> ValueT& {
  144. Check();
  145. return std::get<StoredT>(val_);
  146. }
  147. // Returns the contained value.
  148. // REQUIRES: `ok()` is true.
  149. [[nodiscard]] auto operator*() const& -> const ValueT& {
  150. Check();
  151. return std::get<StoredT>(val_);
  152. }
  153. // Returns the contained value.
  154. // REQUIRES: `ok()` is true.
  155. [[nodiscard]] auto operator*() && -> ValueT&& {
  156. Check();
  157. return std::get<StoredT>(std::move(val_));
  158. }
  159. // Returns the contained value.
  160. // REQUIRES: `ok()` is true.
  161. auto operator->() -> ValueT* { return &**this; }
  162. // Returns the contained value.
  163. // REQUIRES: `ok()` is true.
  164. auto operator->() const -> const ValueT* { return &**this; }
  165. private:
  166. using StoredT = std::conditional_t<std::is_reference_v<T>,
  167. std::reference_wrapper<ValueT>, T>;
  168. // Either an error message or a value.
  169. std::variant<ErrorT, StoredT> val_;
  170. };
  171. // A helper class for accumulating error message and converting to
  172. // `Error` and `ErrorOr<T>`.
  173. class ErrorBuilder {
  174. public:
  175. explicit ErrorBuilder() : out_(std::make_unique<RawStringOstream>()) {}
  176. ErrorBuilder(ErrorBuilder&&) = default;
  177. auto operator=(ErrorBuilder&&) -> ErrorBuilder& = default;
  178. // Accumulates string message to a temporary `ErrorBuilder`. After streaming,
  179. // the builder must be converted to an `Error` or `ErrorOr`.
  180. template <typename T>
  181. auto operator<<(T&& message) && -> ErrorBuilder&& {
  182. *out_ << message;
  183. return std::move(*this);
  184. }
  185. // Accumulates string message for an lvalue error builder.
  186. template <typename T>
  187. auto operator<<(T&& message) & -> ErrorBuilder& {
  188. *out_ << message;
  189. return *this;
  190. }
  191. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  192. operator Error() { return Error(out_->TakeStr()); }
  193. template <typename T>
  194. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  195. operator ErrorOr<T>() {
  196. return Error(out_->TakeStr());
  197. }
  198. private:
  199. std::unique_ptr<RawStringOstream> out_;
  200. };
  201. } // namespace Carbon
  202. // Macro hackery to get a unique variable name.
  203. #define CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c) a##b##c
  204. #define CARBON_MAKE_UNIQUE_NAME(a, b, c) CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c)
  205. // Macro to prevent a top-level comma from being interpreted as a macro
  206. // argument separator.
  207. #define CARBON_PROTECT_COMMAS(...) __VA_ARGS__
  208. #define CARBON_RETURN_IF_ERROR_IMPL(unique_name, expr) \
  209. if (auto unique_name = (expr); !(unique_name).ok()) { \
  210. return std::move(unique_name).error(); \
  211. }
  212. #define CARBON_RETURN_IF_ERROR(expr) \
  213. CARBON_RETURN_IF_ERROR_IMPL( \
  214. CARBON_MAKE_UNIQUE_NAME(_llvm_error_line, __LINE__, __COUNTER__), \
  215. CARBON_PROTECT_COMMAS(expr))
  216. #define CARBON_ASSIGN_OR_RETURN_IMPL(unique_name, var, expr) \
  217. auto unique_name = (expr); \
  218. if (!(unique_name).ok()) { \
  219. return std::move(unique_name).error(); \
  220. } \
  221. var = std::move(*(unique_name));
  222. #define CARBON_ASSIGN_OR_RETURN(var, expr) \
  223. CARBON_ASSIGN_OR_RETURN_IMPL( \
  224. CARBON_MAKE_UNIQUE_NAME(_llvm_expected_line, __LINE__, __COUNTER__), \
  225. CARBON_PROTECT_COMMAS(var), CARBON_PROTECT_COMMAS(expr))
  226. #endif // CARBON_COMMON_ERROR_H_