test_helpers.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 "common/string_helpers.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/Support/FormatVariadic.h"
  13. #include "toolchain/diagnostics/diagnostic_emitter.h"
  14. namespace Carbon::Testing {
  15. // A diagnostic translator for tests that lex a single token. Produces
  16. // locations such as "`12.5`:1:3" to refer to the third character in the token.
  17. class SingleTokenDiagnosticTranslator
  18. : public DiagnosticLocationTranslator<const char*> {
  19. public:
  20. // Form a translator for a given token. The string provided here must refer
  21. // to the same character array that we are going to lex.
  22. explicit SingleTokenDiagnosticTranslator(llvm::StringRef token)
  23. : token_(token) {}
  24. auto GetLocation(const char* pos) -> Diagnostic::Location override {
  25. CHECK(StringRefContainsPointer(token_, pos))
  26. << "invalid diagnostic location";
  27. llvm::StringRef prefix = token_.take_front(pos - token_.begin());
  28. auto [before_last_newline, this_line] = prefix.rsplit('\n');
  29. if (before_last_newline.size() == prefix.size()) {
  30. // On first line.
  31. return {.file_name = SynthesizeFilename(),
  32. .line_number = 1,
  33. .column_number = static_cast<int32_t>(pos - token_.begin() + 1)};
  34. } else {
  35. // On second or subsequent lines. Note that the line number here is 2
  36. // more than the number of newlines because `rsplit` removed one newline
  37. // and `line_number` is 1-based.
  38. return {.file_name = SynthesizeFilename(),
  39. .line_number =
  40. static_cast<int32_t>(before_last_newline.count('\n') + 2),
  41. .column_number = static_cast<int32_t>(this_line.size() + 1)};
  42. }
  43. }
  44. private:
  45. [[nodiscard]] auto SynthesizeFilename() const -> std::string {
  46. return llvm::formatv("`{0}`", token_);
  47. }
  48. llvm::StringRef token_;
  49. };
  50. } // namespace Carbon::Testing
  51. #endif // TOOLCHAIN_LEXER_TOKENIZED_BUFFER_TEST_HELPERS_H_