test_helpers.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 translator 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 SingleTokenDiagnosticTranslator
  15. : public DiagnosticLocationTranslator<const char*> {
  16. public:
  17. // Form a translator for a given token. The string provided here must refer
  18. // to the same character array that we are going to lex.
  19. explicit SingleTokenDiagnosticTranslator(llvm::StringRef token)
  20. : token_(token) {}
  21. auto GetLocation(const char* pos) -> DiagnosticLocation override {
  22. CARBON_CHECK(StringRefContainsPointer(token_, pos))
  23. << "invalid diagnostic location";
  24. llvm::StringRef prefix = token_.take_front(pos - token_.begin());
  25. auto [before_last_newline, this_line] = prefix.rsplit('\n');
  26. if (before_last_newline.size() == prefix.size()) {
  27. // On first line.
  28. return {.line_number = 1,
  29. .column_number = static_cast<int32_t>(pos - token_.begin() + 1)};
  30. } else {
  31. // On second or subsequent lines. Note that the line number here is 2
  32. // more than the number of newlines because `rsplit` removed one newline
  33. // and `line_number` is 1-based.
  34. return {.line_number =
  35. static_cast<int32_t>(before_last_newline.count('\n') + 2),
  36. .column_number = static_cast<int32_t>(this_line.size() + 1)};
  37. }
  38. }
  39. private:
  40. llvm::StringRef token_;
  41. };
  42. } // namespace Carbon::Testing
  43. #endif // CARBON_TOOLCHAIN_LEX_TEST_HELPERS_H_