sorting_diagnostic_consumer.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. //
  12. // Sorting is based on `last_byte_offset` without taking the filename into
  13. // account. When processing multiple files, it's expected that separate
  14. // consumers will be used in order to keep diagnostics distinct. Typically
  15. // `Diagnostic::messages[0]` will always be a location in the consumer's primary
  16. // file, but if it needs to correspond to a different file, the
  17. // `last_byte_offset` must still indicate an offset within the primary file.
  18. class SortingDiagnosticConsumer : public DiagnosticConsumer {
  19. public:
  20. explicit SortingDiagnosticConsumer(DiagnosticConsumer& next_consumer)
  21. : next_consumer_(&next_consumer) {}
  22. ~SortingDiagnosticConsumer() override {
  23. // We choose not to automatically flush diagnostics here, because they are
  24. // likely to refer to data that gets destroyed before the diagnostics
  25. // consumer is destroyed, because the diagnostics consumer is typically
  26. // created before the objects that diagnostics refer into are created.
  27. CARBON_CHECK(diagnostics_.empty(),
  28. "Must flush diagnostics consumer before destroying it");
  29. }
  30. // Buffers the diagnostic.
  31. auto HandleDiagnostic(Diagnostic diagnostic) -> void override {
  32. diagnostics_.push_back(std::move(diagnostic));
  33. }
  34. // Sorts and flushes buffered diagnostics.
  35. auto Flush() -> void override {
  36. llvm::stable_sort(diagnostics_,
  37. [](const Diagnostic& lhs, const Diagnostic& rhs) {
  38. return lhs.last_byte_offset < rhs.last_byte_offset;
  39. });
  40. for (auto& diag : diagnostics_) {
  41. next_consumer_->HandleDiagnostic(std::move(diag));
  42. }
  43. diagnostics_.clear();
  44. }
  45. private:
  46. // A Diagnostic is undesirably large for inline storage by SmallVector, so we
  47. // specify 0.
  48. llvm::SmallVector<Diagnostic, 0> diagnostics_;
  49. DiagnosticConsumer* next_consumer_;
  50. };
  51. } // namespace Carbon
  52. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_SORTING_DIAGNOSTIC_CONSUMER_H_