check_internal.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 "common/ostream.h"
  7. namespace Carbon::Internal {
  8. // Wraps a stream and exiting for fatal errors. Should only be used by check.h
  9. // macros.
  10. class ExitingStream {
  11. public:
  12. // A tag type that renders as ": " in an ExitingStream, but only if it is
  13. // followed by additional output. Otherwise, it renders as "". Primarily used
  14. // when building macros around these streams.
  15. struct AddSeparator {};
  16. // Internal type used in macros to dispatch to the `operator|` overload.
  17. struct Helper {};
  18. ExitingStream()
  19. // Prefix the buffer with the current bug report message.
  20. : buffer_(buffer_str_) {}
  21. // Never called.
  22. [[noreturn]] ~ExitingStream();
  23. // If the bool cast occurs, it's because the condition is false. This supports
  24. // && short-circuiting the creation of ExitingStream.
  25. explicit operator bool() const { return true; }
  26. // Forward output to llvm::errs.
  27. template <typename T>
  28. auto operator<<(const T& message) -> ExitingStream& {
  29. if (separator_) {
  30. buffer_ << ": ";
  31. separator_ = false;
  32. }
  33. buffer_ << message;
  34. return *this;
  35. }
  36. auto operator<<(AddSeparator /*add_separator*/) -> ExitingStream& {
  37. separator_ = true;
  38. return *this;
  39. }
  40. // Low-precedence binary operator overload used in check.h macros to flush the
  41. // output and exit the program. We do this in a binary operator rather than
  42. // the destructor to ensure good debug info and backtraces for errors.
  43. [[noreturn]] friend auto operator|(Helper /*helper*/, ExitingStream& stream)
  44. -> void {
  45. stream.Done();
  46. }
  47. private:
  48. [[noreturn]] auto Done() -> void;
  49. // Whether a separator should be printed if << is used again.
  50. bool separator_ = false;
  51. std::string buffer_str_;
  52. llvm::raw_string_ostream buffer_;
  53. };
  54. } // namespace Carbon::Internal
  55. // Raw exiting stream. This should be used when building forms of exiting
  56. // macros. It evaluates to a temporary `ExitingStream` object that can be
  57. // manipulated, streamed into, and then will exit the program.
  58. #define CARBON_CHECK_INTERNAL_STREAM() \
  59. Carbon::Internal::ExitingStream::Helper() | Carbon::Internal::ExitingStream()
  60. #endif // CARBON_COMMON_CHECK_INTERNAL_H_