diagnostic_emitter.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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_CHECK_DIAGNOSTIC_EMITTER_H_
  5. #define CARBON_TOOLCHAIN_CHECK_DIAGNOSTIC_EMITTER_H_
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/diagnostics/emitter.h"
  9. #include "toolchain/lex/token_index.h"
  10. #include "toolchain/sem_ir/diagnostic_loc_converter.h"
  11. namespace Carbon::Check {
  12. // Handles the transformation of a SemIR::LocId to a DiagnosticLoc.
  13. class DiagnosticEmitter : public DiagnosticEmitterBase {
  14. public:
  15. // `consumer`, `tree_and_subtrees_getters`, and `sem_ir` must be non-null.
  16. explicit DiagnosticEmitter(
  17. Diagnostics::Consumer* consumer,
  18. const Parse::GetTreeAndSubtreesStore* tree_and_subtrees_getters,
  19. const SemIR::File* sem_ir)
  20. : DiagnosticEmitterBase(consumer),
  21. sem_ir_(sem_ir),
  22. loc_converter_(tree_and_subtrees_getters, sem_ir) {}
  23. // If a byte offset is past the current last byte offset, advances forward.
  24. // Earlier offsets are ignored.
  25. auto AdvanceToken(Lex::TokenIndex token) -> void {
  26. last_token_ = std::max(last_token_, token);
  27. }
  28. protected:
  29. // Implements argument conversions for supported check-phase arguments.
  30. auto ConvertArg(llvm::Any arg) const -> llvm::Any override;
  31. // Implements `DiagnosticConverter::ConvertLoc`. Adds context for any imports
  32. // used in the current SemIR to get to the underlying code.
  33. //
  34. // For the last byte offset, this uses `last_token_` exclusively for imported
  35. // locations, or `loc` if it's in the same file and (for whatever reason)
  36. // later.
  37. auto ConvertLoc(LocIdForDiagnostics loc_id, ContextFnT context_fn) const
  38. -> Diagnostics::ConvertedLoc override;
  39. private:
  40. // The current SemIR being processed.
  41. const SemIR::File* sem_ir_;
  42. // Converter for locations.
  43. SemIR::DiagnosticLocConverter loc_converter_;
  44. // The last token encountered during processing.
  45. Lex::TokenIndex last_token_ = Lex::TokenIndex::None;
  46. };
  47. } // namespace Carbon::Check
  48. #endif // CARBON_TOOLCHAIN_CHECK_DIAGNOSTIC_EMITTER_H_