diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -374,6 +374,18 @@ unsigned WordOffset = Word.data() - Code.data(); SourceLocation WordStart = SM.getComposedLoc(File, WordOffset); + // Attempt to determine the kind of token that contains the word, + // and bail if it's a string literal. Note that we cannot always + // determine the token kind (e.g. comments, for which we do want + // to activate, are not retained by TokenBuffer). + for (syntax::Token T : + syntax::spelledTokensTouching(WordStart, AST.getTokens())) { + if (T.range(AST.getSourceManager()).touches(WordOffset + Word.size())) { + if (isStringLiteral(T.kind())) + return {}; + } + } + // Do not consider tokens that survived preprocessing. // We are erring on the safe side here, as a user may expect to get // accurate (as opposed to textual-heuristic) results for such tokens. diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp --- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -644,7 +644,8 @@ // Comment mentioning M^yClass )cpp", R"cpp(// String - struct [[MyClass]] {}; + struct MyClass {}; + // Not triggered for string literal tokens. const char* s = "String literal mentioning M^yClass"; )cpp", R"cpp(// Ifdef'ed out code @@ -696,7 +697,7 @@ EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test; } } -} +} // namespace TEST(LocateSymbol, Ambiguous) { auto T = Annotations(R"cpp(