check_internal.h 2.5 KB

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