error.h 8.8 KB

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