error.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 {
  18. public:
  19. // Represents an error state.
  20. explicit Error(llvm::Twine prefix, llvm::Twine location, llvm::Twine message)
  21. : prefix_(prefix.str()),
  22. location_(location.str()),
  23. message_(message.str()) {
  24. CARBON_CHECK(!message_.empty()) << "Errors must have a message.";
  25. }
  26. // Represents an error with no associated prefix or location.
  27. // TODO: Consider using two different types.
  28. explicit Error(llvm::Twine message) : Error("", "", message) {}
  29. Error(Error&& other) noexcept
  30. : prefix_(std::move(other.prefix_)),
  31. location_(std::move(other.location_)),
  32. message_(std::move(other.message_)) {}
  33. // Prints the error string.
  34. void Print(llvm::raw_ostream& out) const {
  35. if (!prefix().empty()) {
  36. out << prefix() << ": ";
  37. }
  38. if (!location().empty()) {
  39. out << location() << ": ";
  40. }
  41. out << message();
  42. }
  43. // Returns the prefix to prepend to the error, such as "ERROR".
  44. auto prefix() const -> const std::string& { return prefix_; }
  45. // Returns a string describing the location of the error, such as
  46. // "file.cc:123".
  47. auto location() const -> const std::string& { return location_; }
  48. // Returns the error message.
  49. auto message() const -> const std::string& { return message_; }
  50. private:
  51. // A prefix, indicating the kind of error.
  52. std::string prefix_;
  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. template <typename T>
  61. class [[nodiscard]] ErrorOr {
  62. public:
  63. // Constructs with an error; the error must not be Error::Success().
  64. // Implicit for easy construction on returns.
  65. // NOLINTNEXTLINE(google-explicit-constructor)
  66. ErrorOr(Error err) : val_(std::move(err)) {}
  67. // Constructs with a value.
  68. // Implicit for easy construction on returns.
  69. // NOLINTNEXTLINE(google-explicit-constructor)
  70. ErrorOr(T val) : val_(std::move(val)) {}
  71. // Moves held state.
  72. ErrorOr(ErrorOr&& other) noexcept : val_(std::move(other.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
  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 prefix, std::string location)
  118. : prefix_(std::move(prefix)),
  119. location_(std::move(location)),
  120. out_(std::make_unique<llvm::raw_string_ostream>(message_)) {}
  121. explicit ErrorBuilder() : ErrorBuilder("", "") {}
  122. // Accumulates string message.
  123. template <typename T>
  124. [[nodiscard]] auto operator<<(const T& message) -> ErrorBuilder& {
  125. *out_ << message;
  126. return *this;
  127. }
  128. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  129. operator Error() { return Error(prefix_, location_, message_); }
  130. template <typename T>
  131. // NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
  132. operator ErrorOr<T>() {
  133. return Error(prefix_, location_, message_);
  134. }
  135. private:
  136. std::string prefix_;
  137. std::string location_;
  138. std::string message_;
  139. // Use a pointer to allow move construction.
  140. std::unique_ptr<llvm::raw_string_ostream> out_;
  141. };
  142. } // namespace Carbon
  143. // Macro hackery to get a unique variable name.
  144. #define CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c) a##b##c
  145. #define CARBON_MAKE_UNIQUE_NAME(a, b, c) CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c)
  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__), expr)
  154. #define CARBON_ASSIGN_OR_RETURN_IMPL(unique_name, var, expr) \
  155. auto unique_name = (expr); /* NOLINT(bugprone-macro-parentheses) */ \
  156. if (!(unique_name).ok()) { \
  157. return std::move(unique_name).error(); \
  158. } \
  159. var = std::move(*(unique_name)); /* NOLINT(bugprone-macro-parentheses) */
  160. #define CARBON_ASSIGN_OR_RETURN(var, expr) \
  161. CARBON_ASSIGN_OR_RETURN_IMPL( \
  162. CARBON_MAKE_UNIQUE_NAME(_llvm_expected_line, __LINE__, __COUNTER__), \
  163. var, expr)
  164. #endif // CARBON_COMMON_ERROR_H_