sorting_diagnostic_consumer.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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(Diagnostic diagnostic) -> void override {
  18. diagnostics_.push_back(std::move(diagnostic));
  19. }
  20. // Sorts and flushes buffered diagnostics.
  21. void Flush() override {
  22. llvm::stable_sort(diagnostics_,
  23. [](const Diagnostic& lhs, const Diagnostic& rhs) {
  24. return std::tie(lhs.message.location.line_number,
  25. lhs.message.location.column_number) <
  26. std::tie(rhs.message.location.line_number,
  27. rhs.message.location.column_number);
  28. });
  29. for (auto& diag : diagnostics_) {
  30. next_consumer_->HandleDiagnostic(std::move(diag));
  31. }
  32. diagnostics_.clear();
  33. }
  34. private:
  35. llvm::SmallVector<Diagnostic, 0> diagnostics_;
  36. DiagnosticConsumer* next_consumer_;
  37. };
  38. } // namespace Carbon
  39. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_