test_helpers.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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_LEXER_TEST_HELPERS_H_
  5. #define CARBON_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) -> DiagnosticLocation override {
  25. CARBON_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 {.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 {.line_number =
  38. static_cast<int32_t>(before_last_newline.count('\n') + 2),
  39. .column_number = static_cast<int32_t>(this_line.size() + 1)};
  40. }
  41. }
  42. private:
  43. llvm::StringRef token_;
  44. };
  45. } // namespace Carbon::Testing
  46. #endif // CARBON_TOOLCHAIN_LEXER_TEST_HELPERS_H_