error.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 <functional>
  7. #include <string>
  8. #include <type_traits>
  9. #include <variant>
  10. #include "common/check.h"
  11. #include "common/ostream.h"
  12. #include "common/raw_string_ostream.h"
  13. #include "llvm/ADT/Twine.h"
  14. namespace Carbon {
  15. // Success values should be represented as the presence of a value in ErrorOr,
  16. // using `ErrorOr<Success>` and `return Success();` if no value needs to be
  17. // returned.
  18. struct Success : public Printable<Success> {
  19. auto Print(llvm::raw_ostream& out) const -> void { out << "Success"; }
  20. };
  21. // Tracks an error message.
  22. //
  23. // This is nodiscard to enforce error handling prior to destruction.
  24. class [[nodiscard]] Error : public Printable<Error> {
  25. public:
  26. // Represents an error state.
  27. explicit Error(llvm::Twine location, llvm::Twine message)
  28. : location_(location.str()), message_(message.str()) {
  29. CARBON_CHECK(!message_.empty(), "Errors must have a message.");
  30. }
  31. // Represents an error with no associated location.
  32. // TODO: Consider using two different types.
  33. explicit Error(llvm::Twine message) : Error("", message) {}
  34. Error(Error&& other) noexcept
  35. : location_(std::move(other.location_)),
  36. message_(std::move(other.message_)) {}
  37. auto operator=(Error&& other) noexcept -> Error& {
  38. location_ = std::move(other.location_);
  39. message_ = std::move(other.message_);
  40. return *this;
  41. }
  42. // Prints the error string.
  43. auto Print(llvm::raw_ostream& out) const -> void {
  44. if (!location().empty()) {
  45. out << location() << ": ";
  46. }
  47. out << message();
  48. }
  49. // Returns a string describing the location of the error, such as
  50. // "file.cc:123".
  51. auto location() const -> const std::string& { return location_; }
  52. // Returns the error message.
  53. auto message() const -> const std::string& { return message_; }
  54. private:
  55. // The location associated with the error.
  56. std::string location_;
  57. // The error message.
  58. std::string message_;
  59. };
  60. // Holds a value of type `T`, or an Error explaining why the value is
  61. // unavailable.
  62. //
  63. // This is nodiscard to enforce error handling prior to destruction.
  64. template <typename T>
  65. class [[nodiscard]] ErrorOr {
  66. public:
  67. using ValueT = std::remove_reference_t<T>;
  68. // Constructs with an error; the error must not be Error::Success().
  69. // Implicit for easy construction on returns.
  70. // NOLINTNEXTLINE(google-explicit-constructor)
  71. ErrorOr(Error err) : val_(std::move(err)) {}
  72. // Constructs with a reference.
  73. // Implicit for easy construction on returns.
  74. // NOLINTNEXTLINE(google-explicit-constructor)
  75. ErrorOr(T ref)
  76. requires std::is_reference_v<T>
  77. : val_(std::ref(ref)) {}
  78. // Constructs with a value.
  79. // Implicit for easy construction on returns.
  80. // NOLINTNEXTLINE(google-explicit-constructor)
  81. ErrorOr(T val)
  82. requires(!std::is_reference_v<T>)
  83. : val_(std::move(val)) {}
  84. // Returns true for success.
  85. auto ok() const -> bool { return std::holds_alternative<StoredT>(val_); }
  86. // Returns the contained error.
  87. // REQUIRES: `ok()` is false.
  88. auto error() const& -> const Error& {
  89. CARBON_CHECK(!ok());
  90. return std::get<Error>(val_);
  91. }
  92. auto error() && -> Error {
  93. CARBON_CHECK(!ok());
  94. return std::get<Error>(std::move(val_));
  95. }
  96. // Returns the contained value.
  97. // REQUIRES: `ok()` is true.
  98. auto operator*() -> ValueT& {
  99. CARBON_CHECK(ok());
  100. return std::get<StoredT>(val_);
  101. }
  102. // Returns the contained value.
  103. // REQUIRES: `ok()` is true.
  104. auto operator*() const -> const ValueT& {
  105. CARBON_CHECK(ok());
  106. return std::get<StoredT>(val_);
  107. }
  108. // Returns the contained value.
  109. // REQUIRES: `ok()` is true.
  110. auto operator->() -> ValueT* { return &**this; }
  111. // Returns the contained value.
  112. // REQUIRES: `ok()` is true.
  113. auto operator->() const -> const ValueT* { return &**this; }
  114. private:
  115. using StoredT = std::conditional_t<std::is_reference_v<T>,
  116. std::reference_wrapper<ValueT>, T>;
  117. // Either an error message or a value.
  118. std::variant<Error, StoredT> val_;
  119. };
  120. // A helper class for accumulating error message and converting to
  121. // `Error` and `ErrorOr<T>`.
  122. class ErrorBuilder {
  123. public:
  124. explicit ErrorBuilder(std::string location = "")
  125. : location_(std::move(location)),
  126. out_(std::make_unique<RawStringOstream>()) {}
  127. ErrorBuilder(ErrorBuilder&&) = default;
  128. auto operator=(ErrorBuilder&&) -> ErrorBuilder& = default;
  129. // Accumulates string message to a temporary `ErrorBuilder`. After streaming,
  130. // the builder must be converted to an `Error` or `ErrorOr`.
  131. template <typename T>
  132. auto operator<<(T&& message) && -> ErrorBuilder&& {
  133. *out_ << message;
  134. return std::move(*this);
  135. }
  136. // Accumulates string message for an lvalue error builder.
  137. template <typename T>
  138. auto operator<<(T&& message) & -> ErrorBuilder& {
  139. *out_ << message;
  140. return *this;
  141. }
  142. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  143. operator Error() { return Error(location_, out_->TakeStr()); }
  144. template <typename T>
  145. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  146. operator ErrorOr<T>() {
  147. return Error(location_, out_->TakeStr());
  148. }
  149. private:
  150. std::string location_;
  151. std::unique_ptr<RawStringOstream> out_;
  152. };
  153. } // namespace Carbon
  154. // Macro hackery to get a unique variable name.
  155. #define CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c) a##b##c
  156. #define CARBON_MAKE_UNIQUE_NAME(a, b, c) CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c)
  157. // Macro to prevent a top-level comma from being interpreted as a macro
  158. // argument separator.
  159. #define CARBON_PROTECT_COMMAS(...) __VA_ARGS__
  160. #define CARBON_RETURN_IF_ERROR_IMPL(unique_name, expr) \
  161. if (auto unique_name = (expr); !(unique_name).ok()) { \
  162. return std::move(unique_name).error(); \
  163. }
  164. #define CARBON_RETURN_IF_ERROR(expr) \
  165. CARBON_RETURN_IF_ERROR_IMPL( \
  166. CARBON_MAKE_UNIQUE_NAME(_llvm_error_line, __LINE__, __COUNTER__), \
  167. CARBON_PROTECT_COMMAS(expr))
  168. #define CARBON_ASSIGN_OR_RETURN_IMPL(unique_name, var, expr) \
  169. auto unique_name = (expr); \
  170. if (!(unique_name).ok()) { \
  171. return std::move(unique_name).error(); \
  172. } \
  173. var = std::move(*(unique_name));
  174. #define CARBON_ASSIGN_OR_RETURN(var, expr) \
  175. CARBON_ASSIGN_OR_RETURN_IMPL( \
  176. CARBON_MAKE_UNIQUE_NAME(_llvm_expected_line, __LINE__, __COUNTER__), \
  177. CARBON_PROTECT_COMMAS(var), CARBON_PROTECT_COMMAS(expr))
  178. #endif // CARBON_COMMON_ERROR_H_