test_helpers.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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_LEX_TEST_HELPERS_H_
  5. #define CARBON_TOOLCHAIN_LEX_TEST_HELPERS_H_
  6. #include <gmock/gmock.h>
  7. #include <array>
  8. #include "common/check.h"
  9. #include "common/string_helpers.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. namespace Carbon::Testing {
  12. // A diagnostic converter for tests that lex a single token. Produces
  13. // locations such as "`12.5`:1:3" to refer to the third character in the token.
  14. class SingleTokenDiagnosticConverter : public DiagnosticConverter<const char*> {
  15. public:
  16. // Form a converter for a given token. The string provided here must refer
  17. // to the same character array that we are going to lex.
  18. explicit SingleTokenDiagnosticConverter(llvm::StringRef token)
  19. : token_(token) {}
  20. // Implements `DiagnosticConverter::ConvertLoc`.
  21. auto ConvertLoc(const char* pos, ContextFnT /*context_fn*/) const
  22. -> ConvertedDiagnosticLoc override {
  23. CARBON_CHECK(StringRefContainsPointer(token_, pos),
  24. "invalid diagnostic location");
  25. llvm::StringRef prefix = token_.take_front(pos - token_.begin());
  26. auto [before_last_newline, this_line] = prefix.rsplit('\n');
  27. if (before_last_newline.size() == prefix.size()) {
  28. // On first line.
  29. return {.loc = {.line_number = 1,
  30. .column_number =
  31. static_cast<int32_t>(pos - token_.begin() + 1)},
  32. .last_byte_offset = -1};
  33. } else {
  34. // On second or subsequent lines. Note that the line number here is 2
  35. // more than the number of newlines because `rsplit` removed one newline
  36. // and `line_number` is 1-based.
  37. return {
  38. .loc = {.line_number =
  39. static_cast<int32_t>(before_last_newline.count('\n') + 2),
  40. .column_number = static_cast<int32_t>(this_line.size() + 1)},
  41. .last_byte_offset = -1};
  42. }
  43. }
  44. private:
  45. llvm::StringRef token_;
  46. };
  47. } // namespace Carbon::Testing
  48. #endif // CARBON_TOOLCHAIN_LEX_TEST_HELPERS_H_