diagnostic_emitter.h 2.1 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_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/diagnostic_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. explicit DiagnosticEmitter(
  16. Diagnostics::Consumer* consumer,
  17. llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> tree_and_subtrees_getters,
  18. const SemIR::File* sem_ir)
  19. : DiagnosticEmitterBase(consumer),
  20. sem_ir_(sem_ir),
  21. loc_converter_(tree_and_subtrees_getters, sem_ir) {}
  22. // If a byte offset is past the current last byte offset, advances forward.
  23. // Earlier offsets are ignored.
  24. auto AdvanceToken(Lex::TokenIndex token) -> void {
  25. last_token_ = std::max(last_token_, token);
  26. }
  27. protected:
  28. // Implements argument conversions for supported check-phase arguments.
  29. auto ConvertArg(llvm::Any arg) const -> llvm::Any override;
  30. // Implements `DiagnosticConverter::ConvertLoc`. Adds context for any imports
  31. // used in the current SemIR to get to the underlying code.
  32. //
  33. // For the last byte offset, this uses `last_token_` exclusively for imported
  34. // locations, or `loc` if it's in the same file and (for whatever reason)
  35. // later.
  36. auto ConvertLoc(LocIdForDiagnostics loc_id, ContextFnT context_fn) const
  37. -> Diagnostics::ConvertedLoc override;
  38. private:
  39. // The current SemIR being processed.
  40. const SemIR::File* sem_ir_;
  41. // Converter for locations.
  42. SemIR::DiagnosticLocConverter loc_converter_;
  43. // The last token encountered during processing.
  44. Lex::TokenIndex last_token_ = Lex::TokenIndex::None;
  45. };
  46. } // namespace Carbon::Check
  47. #endif // CARBON_TOOLCHAIN_CHECK_DIAGNOSTIC_EMITTER_H_