sorting_diagnostic_consumer.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 {
  16. // We choose not to automatically flush diagnostics here, because they are
  17. // likely to refer to data that gets destroyed before the diagnostics
  18. // consumer is destroyed, because the diagnostics consumer is typically
  19. // created before the objects that diagnostics refer into are created.
  20. CARBON_CHECK(diagnostics_.empty())
  21. << "Must flush diagnostics consumer before destroying it";
  22. }
  23. // Buffers the diagnostic.
  24. auto HandleDiagnostic(Diagnostic diagnostic) -> void override {
  25. diagnostics_.push_back(std::move(diagnostic));
  26. }
  27. // Sorts and flushes buffered diagnostics.
  28. void Flush() override {
  29. llvm::stable_sort(diagnostics_,
  30. [](const Diagnostic& lhs, const Diagnostic& rhs) {
  31. return std::tie(lhs.message.location.line_number,
  32. lhs.message.location.column_number) <
  33. std::tie(rhs.message.location.line_number,
  34. rhs.message.location.column_number);
  35. });
  36. for (auto& diag : diagnostics_) {
  37. next_consumer_->HandleDiagnostic(std::move(diag));
  38. }
  39. diagnostics_.clear();
  40. }
  41. private:
  42. // A Diagnostic is undesirably large for inline storage by SmallVector, so we
  43. // specify 0.
  44. llvm::SmallVector<Diagnostic, 0> diagnostics_;
  45. DiagnosticConsumer* next_consumer_;
  46. };
  47. } // namespace Carbon
  48. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_