error.h 6.2 KB

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