sorting_diagnostic_consumer.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_
  6. #include "common/check.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "toolchain/diagnostics/diagnostic_emitter.h"
  9. namespace Carbon {
  10. // Buffers incoming diagnostics for printing and sorting.
  11. class SortingDiagnosticConsumer : public DiagnosticConsumer {
  12. public:
  13. explicit SortingDiagnosticConsumer(DiagnosticConsumer& next_consumer)
  14. : next_consumer_(&next_consumer) {}
  15. ~SortingDiagnosticConsumer() override { Flush(); }
  16. // Buffers the diagnostic.
  17. auto HandleDiagnostic(const Diagnostic& diagnostic) -> void override {
  18. diagnostics_.push_back(diagnostic);
  19. }
  20. // Sorts and flushes buffered diagnostics.
  21. void Flush() override {
  22. llvm::sort(diagnostics_, [](const Diagnostic& lhs, const Diagnostic& rhs) {
  23. return std::tie(lhs.location.line_number, lhs.location.column_number) <
  24. std::tie(rhs.location.line_number, rhs.location.column_number);
  25. });
  26. for (const auto& diagnostic : diagnostics_) {
  27. next_consumer_->HandleDiagnostic(diagnostic);
  28. }
  29. diagnostics_.clear();
  30. }
  31. private:
  32. llvm::SmallVector<Diagnostic, 0> diagnostics_;
  33. DiagnosticConsumer* next_consumer_;
  34. };
  35. } // namespace Carbon
  36. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_