check_internal.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 COMMON_CHECK_INTERNAL_H_
  5. #define COMMON_CHECK_INTERNAL_H_
  6. #include "llvm/Support/ErrorHandling.h"
  7. #include "llvm/Support/Signals.h"
  8. #include "llvm/Support/raw_ostream.h"
  9. namespace Carbon::Internal {
  10. // Wraps a stream and exiting for fatal errors. Should only be used by check.h
  11. // macros.
  12. class ExitingStream {
  13. public:
  14. // A tag type that renders as ": " in an ExitingStream, but only if it is
  15. // followed by additional output. Otherwise, it renders as "". Primarily used
  16. // when building macros around these streams.
  17. struct AddSeparator {};
  18. // Internal type used in macros to dispatch to the `operator|` overload.
  19. struct Helper {};
  20. [[noreturn]] ~ExitingStream() {
  21. llvm_unreachable(
  22. "Exiting streams should only be constructed by check.h macros that "
  23. "ensure the special operator| exits the program prior to their "
  24. "destruction!");
  25. }
  26. // If the bool cast occurs, it's because the condition is false. This supports
  27. // && short-circuiting the creation of ExitingStream.
  28. explicit operator bool() const { return true; }
  29. // Forward output to llvm::errs.
  30. template <typename T>
  31. auto operator<<(const T& message) -> ExitingStream& {
  32. if (separator_) {
  33. llvm::errs() << ": ";
  34. separator_ = false;
  35. }
  36. llvm::errs() << message;
  37. return *this;
  38. }
  39. auto operator<<(AddSeparator /*discarded*/) -> ExitingStream& {
  40. separator_ = true;
  41. return *this;
  42. }
  43. // Low-precedence binary operator overload used in check.h macros to flush the
  44. // output and exit the program. We do this in a binary operator rather than
  45. // the destructor to ensure good debug info and backtraces for errors.
  46. [[noreturn]] friend auto operator|(Helper /*discarded*/, ExitingStream& rhs) {
  47. // Finish with a newline.
  48. llvm::errs() << "\n";
  49. std::abort();
  50. }
  51. private:
  52. // Whether a separator should be printed if << is used again.
  53. bool separator_ = false;
  54. };
  55. } // namespace Carbon::Internal
  56. #endif // COMMON_CHECK_INTERNAL_H_