Skip to content

Commit

Permalink
[index][clangd] Consider labels when indexing function bodies
Browse files Browse the repository at this point in the history
It's valuable to have document highlights for labels and be able to find
references to them.

Reviewed By: nridge

Differential Revision: https://reviews.llvm.org/D150124
  • Loading branch information
ckandeler committed Aug 1, 2023
1 parent eb9fce0 commit 535f34d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions clang-tools-extra/clangd/unittests/XRefsTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ TEST(HighlightsTest, All) {
[Foo [[x]]:2 [[^y]]:4];
}
)cpp",
R"cpp( // Label
int main() {
goto [[^theLabel]];
[[theLabel]]:
return 1;
}
)cpp",
};
for (const char *Test : Tests) {
Annotations T(Test);
Expand Down
11 changes: 11 additions & 0 deletions clang/lib/Index/IndexBody.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> {
Parent, ParentDC, Roles, Relations, E);
}

bool VisitGotoStmt(GotoStmt *S) {
return IndexCtx.handleReference(S->getLabel(), S->getLabelLoc(), Parent,
ParentDC);
}

bool VisitLabelStmt(LabelStmt *S) {
if (IndexCtx.shouldIndexFunctionLocalSymbols())
return IndexCtx.handleDecl(S->getDecl());
return true;
}

bool VisitMemberExpr(MemberExpr *E) {
SourceLocation Loc = E->getMemberLoc();
if (Loc.isInvalid())
Expand Down
22 changes: 22 additions & 0 deletions clang/unittests/Index/IndexTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,28 @@ TEST(IndexTest, IndexParametersInDecls) {
EXPECT_THAT(Index->Symbols, Not(Contains(QName("bar"))));
}

TEST(IndexTest, IndexLabels) {
std::string Code = R"cpp(
int main() {
goto theLabel;
theLabel:
return 1;
}
)cpp";
auto Index = std::make_shared<Indexer>();
IndexingOptions Opts;
Opts.IndexFunctionLocals = true;
tooling::runToolOnCode(std::make_unique<IndexAction>(Index, Opts), Code);
EXPECT_THAT(Index->Symbols,
Contains(AllOf(QName("theLabel"), WrittenAt(Position(3, 16)),
DeclAt(Position(4, 11)))));

Opts.IndexFunctionLocals = false;
Index->Symbols.clear();
tooling::runToolOnCode(std::make_unique<IndexAction>(Index, Opts), Code);
EXPECT_THAT(Index->Symbols, Not(Contains(QName("theLabel"))));
}

TEST(IndexTest, IndexExplicitTemplateInstantiation) {
std::string Code = R"cpp(
template <typename T>
Expand Down

0 comments on commit 535f34d

Please sign in to comment.