diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp b/clang-tools-extra/clangd/IncludeCleaner.cpp --- a/clang-tools-extra/clangd/IncludeCleaner.cpp +++ b/clang-tools-extra/clangd/IncludeCleaner.cpp @@ -405,9 +405,14 @@ // through an #include. while (SM.getFileID(Loc) != SM.getMainFileID()) Loc = SM.getIncludeLoc(SM.getFileID(Loc)); - const auto *Token = AST.getTokens().spelledTokenAt(Loc); - MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM), - Providers}; + auto TouchingTokens = + syntax::spelledTokensTouching(Loc, AST.getTokens()); + assert(!TouchingTokens.empty()); + // Loc points to the start offset of the ref token, here we use the last + // element of the TouchingTokens, e.g. avoid getting the "::" for + // "ns::^abc". + MissingIncludeDiagInfo DiagInfo{ + Ref.Target, TouchingTokens.back().range(SM), Providers}; MissingIncludes.push_back(std::move(DiagInfo)); }); std::vector UnusedIncludes = diff --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp --- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp +++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp @@ -413,6 +413,28 @@ EXPECT_EQ(RefRange, Findings[1].SymRefRange); } +TEST(IncludeCleaner, NoCrash) { + TestTU TU; + Annotations MainCode(R"cpp( + #include "all.h" + void test() { + [[1s]]; + } + )cpp"); + TU.Code = MainCode.code(); + TU.AdditionalFiles["foo.h"] = + guard("int operator\"\"s(unsigned long long) { return 0; }"); + TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\""); + ParsedAST AST = TU.build(); + const auto &MissingIncludes = + computeIncludeCleanerFindings(AST).MissingIncludes; + EXPECT_THAT(MissingIncludes, testing::SizeIs(1)); + auto &SM = AST.getSourceManager(); + EXPECT_EQ( + halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)), + MainCode.range()); +} + } // namespace } // namespace clangd } // namespace clang