error.h 6.4 KB

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