test_helpers.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 TOOLCHAIN_LEXER_TEST_HELPERS_H_
  5. #define TOOLCHAIN_LEXER_TEST_HELPERS_H_
  6. #include <gmock/gmock.h>
  7. #include <array>
  8. #include <string>
  9. #include "common/check.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "toolchain/diagnostics/diagnostic_emitter.h"
  13. namespace Carbon::Testing {
  14. // A diagnostic translator for tests that lex a single token. Produces
  15. // locations such as "`12.5`:1:3" to refer to the third character in the token.
  16. class SingleTokenDiagnosticTranslator
  17. : public DiagnosticLocationTranslator<const char*> {
  18. public:
  19. // Form a translator for a given token. The string provided here must refer
  20. // to the same character array that we are going to lex.
  21. explicit SingleTokenDiagnosticTranslator(llvm::StringRef token)
  22. : token_(token) {}
  23. auto GetLocation(const char* pos) -> Diagnostic::Location override {
  24. CHECK(llvm::is_sorted(std::array{token_.begin(), pos, token_.end()}))
  25. << "invalid diagnostic location";
  26. llvm::StringRef prefix = token_.take_front(pos - token_.begin());
  27. auto [before_last_newline, this_line] = prefix.rsplit('\n');
  28. if (before_last_newline.size() == prefix.size()) {
  29. // On first line.
  30. return {.file_name = SynthesizeFilename(),
  31. .line_number = 1,
  32. .column_number = static_cast<int32_t>(pos - token_.begin() + 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 {.file_name = SynthesizeFilename(),
  38. .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. }
  42. }
  43. private:
  44. [[nodiscard]] auto SynthesizeFilename() const -> std::string {
  45. return llvm::formatv("`{0}`", token_);
  46. }
  47. llvm::StringRef token_;
  48. };
  49. } // namespace Carbon::Testing
  50. #endif // TOOLCHAIN_LEXER_TOKENIZED_BUFFER_TEST_HELPERS_H_