error.h 6.3 KB

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