trace_stream.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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_EXPLORER_INTERPRETER_TRACE_STREAM_H_
  5. #define CARBON_EXPLORER_INTERPRETER_TRACE_STREAM_H_
  6. #include <optional>
  7. #include <string>
  8. #include "common/check.h"
  9. #include "common/ostream.h"
  10. #include "explorer/common/nonnull.h"
  11. namespace Carbon {
  12. // Encapsulates the trace stream so that we can cleanly disable tracing while
  13. // the prelude is being processed. The prelude is expected to take a
  14. // disproprotionate amount of time to log, so we try to avoid it.
  15. //
  16. // TODO: While the prelude is combined with the provided program as a single
  17. // AST, the AST knows which declarations came from the prelude. When the prelude
  18. // is fully treated as a separate file, we should be able to take a different
  19. // approach where the caller explicitly toggles tracing when switching file
  20. // contexts.
  21. class TraceStream {
  22. public:
  23. // Returns true if tracing is currently enabled.
  24. auto is_enabled() const -> bool {
  25. return stream_.has_value() && !in_prelude_;
  26. }
  27. // Sets whether the prelude is being skipped.
  28. auto set_in_prelude(bool in_prelude) -> void { in_prelude_ = in_prelude; }
  29. // Sets the trace stream. This should only be called from the main.
  30. auto set_stream(Nonnull<llvm::raw_ostream*> stream) -> void {
  31. stream_ = stream;
  32. }
  33. // Returns the internal stream. Requires is_enabled.
  34. auto stream() const -> llvm::raw_ostream& {
  35. CARBON_CHECK(is_enabled());
  36. return **stream_;
  37. }
  38. // Outputs a trace message. Requires is_enabled.
  39. template <typename T>
  40. auto operator<<(T&& message) const -> llvm::raw_ostream& {
  41. CARBON_CHECK(is_enabled());
  42. **stream_ << message;
  43. return **stream_;
  44. }
  45. private:
  46. std::optional<Nonnull<llvm::raw_ostream*>> stream_;
  47. bool in_prelude_ = false;
  48. };
  49. } // namespace Carbon
  50. #endif // CARBON_EXPLORER_INTERPRETER_TRACE_STREAM_H_