error.h 5.9 KB

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