llvmorg-github-actions[bot] wrote:

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-tidy

Author: Chen Miao (ChenMiaoi)

<details>
<summary>Changes</summary>

Leading escaped newlines can remain in a token's source range after spelling 
cleanup. For example:

```c
\
B
```

The identifier is spelled `B`, but its location points at the backslash and its 
length is 3. Start the token at `B` with length 1 instead.

Skip these prefixes when forming tokens, preserving any cleaning needed within 
the token and leaving whitespace retention mode unchanged. Adjust relexing to 
preserve token end locations, and make backward lookup skip prefixes that would 
return the following token.

---

Patch is 20.99 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/236597.diff


16 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/LexerUtils.cpp (+1-17) 
- (modified) clang-tools-extra/clang-tidy/utils/LexerUtils.h (+6-13) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/readability/isolate-declaration.cpp 
(+7) 
- (modified) clang/include/clang/Lex/Lexer.h (+2-1) 
- (modified) clang/lib/Lex/Lexer.cpp (+18-7) 
- (modified) clang/lib/Lex/Preprocessor.cpp (-6) 
- (modified) clang/lib/Tooling/Transformer/RangeSelector.cpp (+8-25) 
- (modified) clang/test/Frontend/highlight-text.c (+4-5) 
- (modified) clang/test/Lexer/eof-include.c (+1-1) 
- (modified) clang/test/Lexer/escape_newline_unicode.c (+3-2) 
- (modified) clang/test/SemaTemplate/concepts.cpp (+1-2) 
- (modified) clang/test/SemaTemplate/instantiation-depth.cpp (+2-4) 
- (modified) clang/unittests/Lex/DependencyDirectivesScannerTest.cpp (+2-7) 
- (modified) clang/unittests/Lex/LexerTest.cpp (+56-1) 
- (modified) clang/unittests/Tooling/RangeSelectorTest.cpp (+6) 
- (modified) clang/unittests/Tooling/Syntax/TokensTest.cpp (+6) 


``````````diff
diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
index d83713f06b8003..9a3e04540a9e40 100644
--- a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
@@ -52,23 +52,7 @@ SourceLocation findPreviousTokenKind(SourceLocation Start,
                                      const SourceManager &SM,
                                      const LangOptions &LangOpts,
                                      tok::TokenKind TK) {
-  if (Start.isInvalid() || Start.isMacroID())
-    return {};
-
-  while (true) {
-    const SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
-    if (L.isInvalid() || L.isMacroID())
-      return {};
-
-    Token T;
-    if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
-      return {};
-
-    if (T.is(TK))
-      return T.getLocation();
-
-    Start = L;
-  }
+  return findPreviousAnyTokenKind(Start, SM, LangOpts, TK);
 }
 
 SourceLocation findNextTerminator(SourceLocation Start, const SourceManager 
&SM,
diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.h 
b/clang-tools-extra/clang-tidy/utils/LexerUtils.h
index 9b2daf74965e41..c15a26d0372361 100644
--- a/clang-tools-extra/clang-tidy/utils/LexerUtils.h
+++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.h
@@ -52,21 +52,14 @@ SourceLocation findPreviousAnyTokenKind(SourceLocation 
Start,
                                         TokenKind TK, TokenKinds... TKs) {
   if (Start.isInvalid() || Start.isMacroID())
     return {};
-  while (true) {
-    const SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
-    if (L.isInvalid() || L.isMacroID())
-      return {};
-
-    Token T;
-    // Returning 'true' is used to signal failure to retrieve the token.
-    if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
-      return {};
-
-    if (T.isOneOf(TK, TKs...))
-      return T.getLocation();
+  while (auto T = Lexer::findPreviousToken(Start, SM, LangOpts,
+                                           /*IncludeComments=*/true)) {
+    if (T->isOneOf(TK, TKs...))
+      return T->getLocation();
 
-    Start = L;
+    Start = T->getLocation();
   }
+  return {};
 }
 
 template <typename TokenKind, typename... TokenKinds>
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/isolate-declaration.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/isolate-declaration.cpp
index 94b6f7f1a5d91b..6b2c7969aaaef1 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/isolate-declaration.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/isolate-declaration.cpp
@@ -57,6 +57,13 @@ void f3() {
   // CHECK-FIXES: int *pointer2 = nullptr;
   // CHECK-FIXES: int *pointer3 = &i;
 
+  int *\
+*spliced_pointer = nullptr, spliced_value = 42;
+  // CHECK-MESSAGES: [[@LINE-2]]:3: warning: multiple declarations in a single 
statement reduces readability
+  // CHECK-FIXES: int *{{\\}}
+  // CHECK-FIXES-NEXT: *spliced_pointer = nullptr;
+  // CHECK-FIXES-NEXT: int spliced_value = 42;
+
   int *(i_ptr) = nullptr, *((i_ptr2));
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single 
statement reduces readability
   // CHECK-FIXES: int *(i_ptr) = nullptr;
diff --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h
index b3d8ccdd2d0e30..e0b8aae98784a0 100644
--- a/clang/include/clang/Lex/Lexer.h
+++ b/clang/include/clang/Lex/Lexer.h
@@ -740,7 +740,8 @@ class Lexer : public PreprocessorLexer {
   /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
   /// them), skip over them and return the first non-escaped-newline found,
   /// otherwise return P.
-  static const char *SkipEscapedNewLines(const char *P);
+  static const char *SkipEscapedNewLines(const char *P,
+                                         const LangOptions &LangOpts);
 
   /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
   /// diagnostic.
diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index b659780bac593a..f1636d7cd71528 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -410,6 +410,7 @@ StringRef Lexer::getSpelling(SourceLocation loc,
   Token token;
   lexer.LexFromRawLexer(token);
 
+  tokenBegin = lexer.getBufferLocation() - token.getLength();
   unsigned length = token.getLength();
 
   // Common case:  no need for cleaning.
@@ -512,7 +513,9 @@ unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
   Token TheTok;
   if (getRawToken(Loc, TheTok, SM, LangOpts))
     return 0;
-  return TheTok.getLength();
+  // Include any leading escaped newlines skipped when relexing.
+  return TheTok.getLength() + (TheTok.getLocation().getRawEncoding() -
+                               SM.getExpansionLoc(Loc).getRawEncoding());
 }
 
 SourceLocation Lexer::findEndOfIdentifierContinuation(
@@ -561,7 +564,8 @@ bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
 
   const char *StrData = Buffer.data()+LocInfo.second;
 
-  if (!IgnoreWhiteSpace && isWhitespace(SkipEscapedNewLines(StrData)[0]))
+  if (!IgnoreWhiteSpace &&
+      isWhitespace(SkipEscapedNewLines(StrData, LangOpts)[0]))
     return true;
 
   // Create a lexer starting at the beginning of this token.
@@ -859,7 +863,7 @@ unsigned Lexer::getTokenPrefixLength(SourceLocation 
TokStart, unsigned CharNo,
   // advanced by 3 should return the location of b, not of \\.  One compounding
   // detail of this is that the escape may be made by a trigraph.
   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
-    PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
+    PhysOffset += Lexer::SkipEscapedNewLines(TokPtr, LangOpts) - TokPtr;
 
   return PhysOffset;
 }
@@ -1356,17 +1360,16 @@ unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
 /// them), skip over them and return the first non-escaped-newline found,
 /// otherwise return P.
-const char *Lexer::SkipEscapedNewLines(const char *P) {
+const char *Lexer::SkipEscapedNewLines(const char *P,
+                                       const LangOptions &LangOpts) {
   while (true) {
     const char *AfterEscape;
     if (*P == '\\') {
       AfterEscape = P+1;
-    } else if (*P == '?') {
+    } else if (*P == '?' && LangOpts.Trigraphs) {
       // If not a trigraph for escape, bail out.
       if (P[1] != '?' || P[2] != '/')
         return P;
-      // FIXME: Take LangOpts into account; the language might not
-      // support trigraphs.
       AfterEscape = P+3;
     } else {
       return P;
@@ -1423,6 +1426,9 @@ std::optional<Token> 
Lexer::findPreviousToken(SourceLocation Loc,
     Token Tok;
     if (getRawToken(Loc, Tok, SM, LangOpts))
       continue; // Not a token, go to prev location.
+    // Relexing a leading escaped newline can advance to the following token.
+    if (Loc.isFileID() && Tok.getLocation() != Loc)
+      continue;
     if (!Tok.is(tok::comment) || IncludeComments) {
       return Tok;
     }
@@ -3887,6 +3893,11 @@ bool Lexer::LexTokenInternal(Token &Result) {
 
   // Read a character, advancing over it.
   char Char = getAndAdvanceChar(CurPtr, Result);
+  if (Result.needsCleaning() && !isKeepWhitespaceMode()) {
+    BufferPtr = SkipEscapedNewLines(BufferPtr, LangOpts);
+    // The first character still needs cleaning if it was a trigraph.
+    Result.setFlagValue(Token::NeedsCleaning, CurPtr - BufferPtr > 1);
+  }
   tok::TokenKind Kind;
 
   if (!isVerticalWhitespace(Char))
diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp
index a8717424f1d155..4cbe97ba599d17 100644
--- a/clang/lib/Lex/Preprocessor.cpp
+++ b/clang/lib/Lex/Preprocessor.cpp
@@ -831,12 +831,6 @@ IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token 
&Identifier) const {
   }
 
   // Update the token info (identifier info and appropriate token kind).
-  // FIXME: the raw_identifier may contain leading whitespace which is removed
-  // from the cleaned identifier token. The SourceLocation should be updated to
-  // refer to the non-whitespace character. For instance, the text "\\\nB" (a
-  // line continuation before 'B') is parsed as a single tok::raw_identifier 
and
-  // is cleaned to tok::identifier "B". After cleaning the token's length is
-  // still 3 and the SourceLocation refers to the location of the backslash.
   Identifier.setIdentifierInfo(II);
   Identifier.setKind(II->getTokenID());
 
diff --git a/clang/lib/Tooling/Transformer/RangeSelector.cpp 
b/clang/lib/Tooling/Transformer/RangeSelector.cpp
index 68b16f91652fb4..cef8f6fb96c290 100644
--- a/clang/lib/Tooling/Transformer/RangeSelector.cpp
+++ b/clang/lib/Tooling/Transformer/RangeSelector.cpp
@@ -59,40 +59,23 @@ static Expected<DynTypedNode> getNode(const 
ast_matchers::BoundNodes &Nodes,
   return It->second;
 }
 
-// FIXME: handling of macros should be configurable.
-static SourceLocation findPreviousTokenStart(SourceLocation Start,
-                                             const SourceManager &SM,
-                                             const LangOptions &LangOpts) {
-  if (Start.isInvalid() || Start.isMacroID())
-    return SourceLocation();
-
-  SourceLocation BeforeStart = Start.getLocWithOffset(-1);
-  if (BeforeStart.isInvalid() || BeforeStart.isMacroID())
-    return SourceLocation();
-
-  return Lexer::GetBeginningOfToken(BeforeStart, SM, LangOpts);
-}
-
 // Finds the start location of the previous token of kind \p TK.
 // FIXME: handling of macros should be configurable.
 static SourceLocation findPreviousTokenKind(SourceLocation Start,
                                             const SourceManager &SM,
                                             const LangOptions &LangOpts,
                                             tok::TokenKind TK) {
-  while (true) {
-    SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
-    if (L.isInvalid() || L.isMacroID())
-      return SourceLocation();
-
-    Token T;
-    if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
-      return SourceLocation();
+  if (Start.isInvalid() || Start.isMacroID())
+    return SourceLocation();
 
-    if (T.is(TK))
-      return T.getLocation();
+  while (auto T = Lexer::findPreviousToken(Start, SM, LangOpts,
+                                           /*IncludeComments=*/false)) {
+    if (T->is(TK))
+      return T->getLocation();
 
-    Start = L;
+    Start = T->getLocation();
   }
+  return SourceLocation();
 }
 
 RangeSelector transformer::before(RangeSelector Selector) {
diff --git a/clang/test/Frontend/highlight-text.c 
b/clang/test/Frontend/highlight-text.c
index a81d26caa4c24c..9ac3f8a7086b39 100644
--- a/clang/test/Frontend/highlight-text.c
+++ b/clang/test/Frontend/highlight-text.c
@@ -9,11 +9,10 @@ int a = M;
 // CHECK: :8:9: warning: shift count >= width of type [-Wshift-count-overflow]
 // CHECK-NEXT:     8 | int a = M;
 // CHECK-NEXT:       |         ^
-// CHECK-NEXT: :5:11: note: expanded from macro 'M'
-// CHECK-NEXT:     5 | #define M \
-// CHECK-NEXT:       |           ^
-// CHECK-NEXT: :3:14: note: expanded from macro '\
-// CHECK-NEXT: F'
+// CHECK-NEXT: :6:1: note: expanded from macro 'M'
+// CHECK-NEXT:     6 | F | F
+// CHECK-NEXT:       | ^
+// CHECK-NEXT: :3:14: note: expanded from macro 'F'
 // CHECK-NEXT:     3 | #define F (1 << 99)
 // CHECK-NEXT:       |              ^  ~~
 // CHECK-NEXT: :8:9: warning: shift count >= width of type 
[-Wshift-count-overflow]
diff --git a/clang/test/Lexer/eof-include.c b/clang/test/Lexer/eof-include.c
index ba791d574b558f..1046747bcba06a 100644
--- a/clang/test/Lexer/eof-include.c
+++ b/clang/test/Lexer/eof-include.c
@@ -4,5 +4,5 @@
 // This file intentionally ends without a \n on the last line.  Make sure your
 // editor doesn't add one.
 
-// expected-error@+1{{expected '>'}} expected-note@+1{{to match this '<'}}
+// expected-error@+2{{expected '>'}} expected-note@+1{{to match this '<'}}
 #include <\
diff --git a/clang/test/Lexer/escape_newline_unicode.c 
b/clang/test/Lexer/escape_newline_unicode.c
index 9276d7e0e57de6..4c20776732ef4a 100644
--- a/clang/test/Lexer/escape_newline_unicode.c
+++ b/clang/test/Lexer/escape_newline_unicode.c
@@ -20,7 +20,7 @@ int ス\
 
 int \
 ス = 42;
-// expected-warning@-2 {{unused variable 'ス'}}
+// expected-warning@-1 {{unused variable 'ス'}}
 
 }
 
@@ -28,8 +28,9 @@ void gh65156_err(void) {
 
 int \
 ❌ = 0;
+// expected-error@-1 {{unexpected character '❌' U+274C}}
 // cpp-error@-2 {{expected unqualified-id}}
-// c-error@-3 {{expected identifier}}
+// c-error@-3 {{expected identifier or '('}}
 
 
 int a\
diff --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 4e7001b5c519df..f27a939f185fd7 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -1343,8 +1343,7 @@ template <class _Iter>
 concept __cpp17_iterator = __cpp17_copy_constructible<_Iter>; // 
#__cpp17_copy_constructible
 
 struct not_move_constructible {};
-static_assert(__cpp17_iterator<not_move_constructible>); \
-// expected-error {{static assertion failed}} \
+static_assert(__cpp17_iterator<not_move_constructible>); // expected-error 
{{static assertion failed}} \
 // expected-note {{because 'not_move_constructible' does not satisfy 
'__cpp17_iterator'}} \
 // expected-note@#__cpp17_copy_constructible {{because 
'not_move_constructible' does not satisfy '__cpp17_copy_constructible'}} \
 // expected-note@#__cpp17_move_constructible {{because 
'parameter_mapping_regressions::case3::not_move_constructible' does not satisfy 
'__cpp17_move_constructible'}} \
diff --git a/clang/test/SemaTemplate/instantiation-depth.cpp 
b/clang/test/SemaTemplate/instantiation-depth.cpp
index 15e2c2ba7c8bdb..d8d1f28a65bd4c 100644
--- a/clang/test/SemaTemplate/instantiation-depth.cpp
+++ b/clang/test/SemaTemplate/instantiation-depth.cpp
@@ -4,8 +4,7 @@
 
 #ifndef NOEXCEPT
 
-template<typename T> struct X : X<T*> { }; \
-// expected-error{{recursive template instantiation exceeded maximum depth of 
5}} \
+template<typename T> struct X : X<T*> { }; // expected-error{{recursive 
template instantiation exceeded maximum depth of 5}} \
 // expected-note 3 {{instantiation of template class}} \
 // expected-note {{skipping 2 contexts in backtrace}} \
 // expected-note {{use -ftemplate-depth=N to increase recursive template 
instantiation depth}}
@@ -19,8 +18,7 @@ void test() {
 // RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-depth=5 
-ftemplate-backtrace-limit=4 -std=c++11 -DNOEXCEPT %s
 
 template<typename T> struct S {
-  S() noexcept(noexcept(S<S>())); \
-// expected-error{{recursive template instantiation exceeded maximum depth of 
5}} \
+  S() noexcept(noexcept(S<S>())); // expected-error{{recursive template 
instantiation exceeded maximum depth of 5}} \
 // expected-note 3 {{in instantiation of exception spec}} \
 // expected-note {{skipping 2 contexts in backtrace}} \
 // expected-note {{use -ftemplate-depth=N to increase recursive template 
instantiation depth}}
diff --git a/clang/unittests/Lex/DependencyDirectivesScannerTest.cpp 
b/clang/unittests/Lex/DependencyDirectivesScannerTest.cpp
index 6e0a05a3ef7b9c..6b27853e54efdf 100644
--- a/clang/unittests/Lex/DependencyDirectivesScannerTest.cpp
+++ b/clang/unittests/Lex/DependencyDirectivesScannerTest.cpp
@@ -320,9 +320,7 @@ TEST(MinimizeSourceToDependencyDirectivesTest, 
DefineNoWhitespace) {
   ASSERT_FALSE(minimizeSourceToDependencyDirectives("#define AND\\\n"
                                                     "&\n",
                                                     Out));
-  EXPECT_STREQ("#define AND\\\n"
-               "&\n",
-               Out.data());
+  EXPECT_STREQ("#define AND&\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest, MultilineComment) {
@@ -785,10 +783,7 @@ TEST(MinimizeSourceToDependencyDirectivesTest,
                                                     "2 + \\\t\n"
                                                     "3\n",
                                                     Out));
-  EXPECT_STREQ("#define A 1+\\  \n"
-               "2+\\\t\n"
-               "3\n",
-               Out.data());
+  EXPECT_STREQ("#define A 1+2+3\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest,
diff --git a/clang/unittests/Lex/LexerTest.cpp 
b/clang/unittests/Lex/LexerTest.cpp
index 8f632ccc5b9315..618be5be18af16 100644
--- a/clang/unittests/Lex/LexerTest.cpp
+++ b/clang/unittests/Lex/LexerTest.cpp
@@ -540,6 +540,51 @@ TEST_F(LexerTest, IsNewLineEscapedValid) {
   EXPECT_FALSE(hasNewLineEscaped("\n\n"));
 }
 
+TEST_F(LexerTest, TokenWithLeadingEscapedNewLine) {
+  LangOpts.C99 = true;
+  LangOpts.Trigraphs = true;
+  StringRef Source = "\\\nB \\\r\n\\\n\\u00\\\nE9 \\\n123 "
+                     "\\\n\"te\\\nxt\" \\\n+ \?\?/\n\?\?/u00E9";
+  std::vector<Token> Toks = Lex(Source);
+  FileID FID = SourceMgr.getMainFileID();
+  struct {
+    StringRef RawSpelling;
+    StringRef Spelling;
+    bool NeedsCleaning;
+  } Expected[] = {{"B", "B", false},     {"\\u00\\\nE9", "\\u00E9", true},
+                  {"123", "123", false}, {"\"te\\\nxt\"", "\"text\"", true},
+                  {"+", "+", false},     {"\?\?/u00E9", "\\u00E9", true}};
+  ASSERT_EQ(std::size(Expected), Toks.size());
+  for (size_t I = 0; I != Toks.size(); ++I) {
+    SCOPED_TRACE(I);
+    const Token &Tok = Toks[I];
+    const auto &E = Expected[I];
+    EXPECT_EQ(Source.find(E.RawSpelling),
+              SourceMgr.getFileOffset(Tok.getLocation()));
+    EXPECT_EQ(E.RawSpelling.size(), Tok.getLength());
+    EXPECT_EQ(E.NeedsCleaning, Tok.needsCleaning());
+    SmallString<16> Spelling;
+    EXPECT_EQ(E.Spelling, PP->getSpelling(Tok, Spelling));
+  }
+  ASSERT_TRUE(Toks.back().is(tok::identifier));
+  EXPECT_EQ("é", Toks.back().getIdentifierInfo()->getName());
+
+  SourceLocation Start = SourceMgr.getLocForStartOfFile(FID);
+  SmallString<16> Spelling;
+  EXPECT_EQ("B", Lexer::getSpelling(Start, Spelling, SourceMgr, LangOpts));
+  EXPECT_EQ(Start.getLocWithOffset(3),
+            Lexer::getLocForEndOfToken(Start, 0, SourceMgr, LangOpts));
+}
+
+TEST_F(LexerTest, LeadingEscapedNewLineWithTrigraphsDisabled) {
+  LangOpts.Trigraphs = false;
+  auto Toks = Lex("\\\n\?\?/\nB");
+  ASSERT_EQ(4u, Toks.size());
+  EXPECT_TRUE(Toks[0].is(tok::question));
+  EXPECT_EQ(2u, SourceMgr.getFileOffset(Toks[0].getLocation()));
+  EXPECT_EQ(1u, Toks[0].getLength());
+}
+
 TEST_F(LexerTest, GetBeginningOfTokenWithEscapedNewLine) {
   // Each line should have the same length for
   // further offset calculation to be more straightforward.
@@ -680,13 +725,14 @@ TEST_F(LexerTest, FindNextTokenIncludingComments) {
 TEST_F(LexerTest, FindPreviousToken) {
   Lex("int abcd = 0;\n"
       "// A comment.\n"
-      "int xyz = abcd;\n");
+      "int \\\nxyz = abcd;\n");
   std::vector<std::string> GeneratedByPrevToken;
   SourceLocation Loc = SourceMgr.getLocForEndOfFile(SourceMgr.getMainFileID());
   while (true) {
     auto T = Lexer::findPreviousToken(Loc, SourceMgr, LangOpts, false);
     if (!T.has_value())
       break;
+    ASSERT_LT(T->getLocation(), Loc);
     GeneratedByPrevToken.push_back(getSourceText(*T, *T));
     Loc = Lexer::GetBeginningOfToken(T->getLocation(), SourceMgr, LangOpts);
   }
@@ -694,6 +740,15 @@ TEST_F(LexerTest, FindPreviousToken) {
                                                 ";", "0", "=", "abcd", "int"));
 }
 
+TEST_F(LexerTest, FindPreviousTokenInMacro) {
+  auto Toks = Lex("#define M a b\nM");
+  ASSERT_EQ(2u, Toks.size());
+  auto Tok = Lexer::findPreviousToken(Toks[1].getLocation(), SourceMgr,
+                                      LangOpts, false);
+  ASSERT_TRUE(Tok);
+  EXPECT_EQ("M", getSourceText(*Tok, *Tok));
+}
+
 TEST_F(LexerTest, FindPreviousTokenIncludingComments) {
   Lex("int abcd = 0;\n"
       "// A comment.\n"
diff --git a/clang/unittests/Tooling/RangeSelectorTest.cpp 
b/clang/unittests/Tooling/RangeSelectorTest.cpp
index 9e83fa1dc92ff9..b8b6d9a21885a0 100644
--- a/clang/unittests/Tooling/RangeSelectorTest.cpp
+++ b/clang/unittests/Tooling/RangeSelectorTest.cpp
@@ -661,6 +661,12 @@ TEST(RangeSelectorTest, CallArgsOpWithParens) {
   EXPECT_THAT_EXPECTED(select(callArgs(ID), Match), HasValue("3, 4"));
 }
 
+TEST(RangeSelectorTest, CallArgsOpLeadingEscapedNewLine) {
+  StringRef Code = "int g(int); int f(int x) { return g(\\\n(x)); }";
+  auto Match = matchCode(Cod...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/236597
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to