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 CARBON_COMMON_CHECK_INTERNAL_H_
  5. #define CARBON_COMMON_CHECK_INTERNAL_H_
  6. #include <cstdlib>
  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. // Prefix the buffer with the current bug report message.
  23. : buffer_(buffer_str_) {}
  24. // Never called.
  25. [[noreturn]] ~ExitingStream();
  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. buffer_ << ": ";
  34. separator_ = false;
  35. }
  36. buffer_ << message;
  37. return *this;
  38. }
  39. auto operator<<(AddSeparator /*add_separator*/) -> 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 /*helper*/, ExitingStream& stream)
  47. -> void {
  48. stream.Done();
  49. }
  50. private:
  51. [[noreturn]] auto Done() -> void;
  52. // Whether a separator should be printed if << is used again.
  53. bool separator_ = false;
  54. std::string buffer_str_;
  55. llvm::raw_string_ostream buffer_;
  56. };
  57. } // namespace Carbon::Internal
  58. // Raw exiting stream. This should be used when building forms of exiting
  59. // macros. It evaluates to a temporary `ExitingStream` object that can be
  60. // manipulated, streamed into, and then will exit the program.
  61. #define CARBON_CHECK_INTERNAL_STREAM() \
  62. Carbon::Internal::ExitingStream::Helper() | Carbon::Internal::ExitingStream()
  63. #endif // CARBON_COMMON_CHECK_INTERNAL_H_