error.h 6.3 KB

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