Skip to content

Commit ca184cf

Browse files
[clangd] Support outgoing calls in call hierarchy (llvm#77556)
Co-authored-by: Quentin Chateau <quentin.chateau@gmail.com>
1 parent eb5cda4 commit ca184cf

23 files changed

+505
-73
lines changed

clang-tools-extra/clangd/ClangdLSPServer.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -1415,6 +1415,12 @@ void ClangdLSPServer::onInlayHint(const InlayHintsParams &Params,
14151415
std::move(Reply));
14161416
}
14171417

1418+
void ClangdLSPServer::onCallHierarchyOutgoingCalls(
1419+
const CallHierarchyOutgoingCallsParams &Params,
1420+
Callback<std::vector<CallHierarchyOutgoingCall>> Reply) {
1421+
Server->outgoingCalls(Params.item, std::move(Reply));
1422+
}
1423+
14181424
void ClangdLSPServer::applyConfiguration(
14191425
const ConfigurationSettings &Settings) {
14201426
// Per-file update to the compilation database.
@@ -1693,6 +1699,7 @@ void ClangdLSPServer::bindMethods(LSPBinder &Bind,
16931699
Bind.method("typeHierarchy/subtypes", this, &ClangdLSPServer::onSubTypes);
16941700
Bind.method("textDocument/prepareCallHierarchy", this, &ClangdLSPServer::onPrepareCallHierarchy);
16951701
Bind.method("callHierarchy/incomingCalls", this, &ClangdLSPServer::onCallHierarchyIncomingCalls);
1702+
Bind.method("callHierarchy/outgoingCalls", this, &ClangdLSPServer::onCallHierarchyOutgoingCalls);
16961703
Bind.method("textDocument/selectionRange", this, &ClangdLSPServer::onSelectionRange);
16971704
Bind.method("textDocument/documentLink", this, &ClangdLSPServer::onDocumentLink);
16981705
Bind.method("textDocument/semanticTokens/full", this, &ClangdLSPServer::onSemanticTokens);

clang-tools-extra/clangd/ClangdLSPServer.h

+3
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
156156
void onCallHierarchyIncomingCalls(
157157
const CallHierarchyIncomingCallsParams &,
158158
Callback<std::vector<CallHierarchyIncomingCall>>);
159+
void onCallHierarchyOutgoingCalls(
160+
const CallHierarchyOutgoingCallsParams &,
161+
Callback<std::vector<CallHierarchyOutgoingCall>>);
159162
void onClangdInlayHints(const InlayHintsParams &,
160163
Callback<llvm::json::Value>);
161164
void onInlayHint(const InlayHintsParams &, Callback<std::vector<InlayHint>>);

clang-tools-extra/clangd/ClangdServer.cpp

+9
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,15 @@ void ClangdServer::inlayHints(PathRef File, std::optional<Range> RestrictRange,
912912
WorkScheduler->runWithAST("InlayHints", File, std::move(Action), Transient);
913913
}
914914

915+
void ClangdServer::outgoingCalls(
916+
const CallHierarchyItem &Item,
917+
Callback<std::vector<CallHierarchyOutgoingCall>> CB) {
918+
WorkScheduler->run("Outgoing Calls", "",
919+
[CB = std::move(CB), Item, this]() mutable {
920+
CB(clangd::outgoingCalls(Item, Index));
921+
});
922+
}
923+
915924
void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
916925
// FIXME: Do nothing for now. This will be used for indexing and potentially
917926
// invalidating other caches.

clang-tools-extra/clangd/ClangdServer.h

+4
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,10 @@ class ClangdServer {
292292
void incomingCalls(const CallHierarchyItem &Item,
293293
Callback<std::vector<CallHierarchyIncomingCall>>);
294294

295+
/// Resolve outgoing calls for a given call hierarchy item.
296+
void outgoingCalls(const CallHierarchyItem &Item,
297+
Callback<std::vector<CallHierarchyOutgoingCall>>);
298+
295299
/// Resolve inlay hints for a given document.
296300
void inlayHints(PathRef File, std::optional<Range> RestrictRange,
297301
Callback<std::vector<InlayHint>>);

clang-tools-extra/clangd/XRefs.cpp

+59
Original file line numberDiff line numberDiff line change
@@ -1702,6 +1702,7 @@ declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
17021702

17031703
HierarchyItem HI;
17041704
HI.name = printName(Ctx, ND);
1705+
// FIXME: Populate HI.detail the way we do in symbolToHierarchyItem?
17051706
HI.kind = SK;
17061707
HI.range = Range{sourceLocToPosition(SM, DeclRange->getBegin()),
17071708
sourceLocToPosition(SM, DeclRange->getEnd())};
@@ -1753,6 +1754,7 @@ static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
17531754
}
17541755
HierarchyItem HI;
17551756
HI.name = std::string(S.Name);
1757+
HI.detail = (S.Scope + S.Name).str();
17561758
HI.kind = indexSymbolKindToSymbolKind(S.SymInfo.Kind);
17571759
HI.selectionRange = Loc->range;
17581760
// FIXME: Populate 'range' correctly
@@ -2319,6 +2321,63 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
23192321
return Results;
23202322
}
23212323

2324+
std::vector<CallHierarchyOutgoingCall>
2325+
outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
2326+
std::vector<CallHierarchyOutgoingCall> Results;
2327+
if (!Index || Item.data.empty())
2328+
return Results;
2329+
auto ID = SymbolID::fromStr(Item.data);
2330+
if (!ID) {
2331+
elog("outgoingCalls failed to find symbol: {0}", ID.takeError());
2332+
return Results;
2333+
}
2334+
// In this function, we find outgoing calls based on the index only.
2335+
ContainedRefsRequest Request;
2336+
Request.ID = *ID;
2337+
// Initially store the ranges in a map keyed by SymbolID of the callee.
2338+
// This allows us to group different calls to the same function
2339+
// into the same CallHierarchyOutgoingCall.
2340+
llvm::DenseMap<SymbolID, std::vector<Range>> CallsOut;
2341+
// We can populate the ranges based on a refs request only. As we do so, we
2342+
// also accumulate the callee IDs into a lookup request.
2343+
LookupRequest CallsOutLookup;
2344+
Index->containedRefs(Request, [&](const auto &R) {
2345+
auto Loc = indexToLSPLocation(R.Location, Item.uri.file());
2346+
if (!Loc) {
2347+
elog("outgoingCalls failed to convert location: {0}", Loc.takeError());
2348+
return;
2349+
}
2350+
auto It = CallsOut.try_emplace(R.Symbol, std::vector<Range>{}).first;
2351+
It->second.push_back(Loc->range);
2352+
2353+
CallsOutLookup.IDs.insert(R.Symbol);
2354+
});
2355+
// Perform the lookup request and combine its results with CallsOut to
2356+
// get complete CallHierarchyOutgoingCall objects.
2357+
Index->lookup(CallsOutLookup, [&](const Symbol &Callee) {
2358+
// The containedRefs request should only return symbols which are
2359+
// function-like, i.e. symbols for which references to them can be "calls".
2360+
using SK = index::SymbolKind;
2361+
auto Kind = Callee.SymInfo.Kind;
2362+
assert(Kind == SK::Function || Kind == SK::InstanceMethod ||
2363+
Kind == SK::ClassMethod || Kind == SK::StaticMethod ||
2364+
Kind == SK::Constructor || Kind == SK::Destructor ||
2365+
Kind == SK::ConversionFunction);
2366+
2367+
auto It = CallsOut.find(Callee.ID);
2368+
assert(It != CallsOut.end());
2369+
if (auto CHI = symbolToCallHierarchyItem(Callee, Item.uri.file()))
2370+
Results.push_back(
2371+
CallHierarchyOutgoingCall{std::move(*CHI), std::move(It->second)});
2372+
});
2373+
// Sort results by name of the callee.
2374+
llvm::sort(Results, [](const CallHierarchyOutgoingCall &A,
2375+
const CallHierarchyOutgoingCall &B) {
2376+
return A.to.name < B.to.name;
2377+
});
2378+
return Results;
2379+
}
2380+
23222381
llvm::DenseSet<const Decl *> getNonLocalDeclRefs(ParsedAST &AST,
23232382
const FunctionDecl *FD) {
23242383
if (!FD->hasBody())

clang-tools-extra/clangd/XRefs.h

+3
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,9 @@ prepareCallHierarchy(ParsedAST &AST, Position Pos, PathRef TUPath);
150150
std::vector<CallHierarchyIncomingCall>
151151
incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index);
152152

153+
std::vector<CallHierarchyOutgoingCall>
154+
outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index);
155+
153156
/// Returns all decls that are referenced in the \p FD except local symbols.
154157
llvm::DenseSet<const Decl *> getNonLocalDeclRefs(ParsedAST &AST,
155158
const FunctionDecl *FD);

clang-tools-extra/clangd/index/Index.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ bool SwapIndex::refs(const RefsRequest &R,
6666
llvm::function_ref<void(const Ref &)> CB) const {
6767
return snapshot()->refs(R, CB);
6868
}
69+
bool SwapIndex::containedRefs(
70+
const ContainedRefsRequest &R,
71+
llvm::function_ref<void(const ContainedRefsResult &)> CB) const {
72+
return snapshot()->containedRefs(R, CB);
73+
}
6974
void SwapIndex::relations(
7075
const RelationsRequest &R,
7176
llvm::function_ref<void(const SymbolID &, const Symbol &)> CB) const {

clang-tools-extra/clangd/index/Index.h

+35
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,34 @@ struct RefsRequest {
7777
bool WantContainer = false;
7878
};
7979

80+
struct ContainedRefsRequest {
81+
/// Note that RefKind::Call just restricts the matched SymbolKind to
82+
/// functions, not the form of the reference (e.g. address-of-function,
83+
/// which can indicate an indirect call, should still be caught).
84+
static const RefKind SupportedRefKinds = RefKind::Call;
85+
86+
SymbolID ID;
87+
/// If set, limit the number of refers returned from the index. The index may
88+
/// choose to return less than this, e.g. it tries to avoid returning stale
89+
/// results.
90+
std::optional<uint32_t> Limit;
91+
};
92+
8093
struct RelationsRequest {
8194
llvm::DenseSet<SymbolID> Subjects;
8295
RelationKind Predicate;
8396
/// If set, limit the number of relations returned from the index.
8497
std::optional<uint32_t> Limit;
8598
};
8699

100+
struct ContainedRefsResult {
101+
/// The source location where the symbol is named.
102+
SymbolLocation Location;
103+
RefKind Kind = RefKind::Unknown;
104+
/// The ID of the symbol which is referred to
105+
SymbolID Symbol;
106+
};
107+
87108
/// Describes what data is covered by an index.
88109
///
89110
/// Indexes may contain symbols but not references from a file, etc.
@@ -141,6 +162,17 @@ class SymbolIndex {
141162
virtual bool refs(const RefsRequest &Req,
142163
llvm::function_ref<void(const Ref &)> Callback) const = 0;
143164

165+
/// Find all symbols that are referenced by a symbol and apply
166+
/// \p Callback on each result.
167+
///
168+
/// Results should be returned in arbitrary order.
169+
/// The returned result must be deep-copied if it's used outside Callback.
170+
///
171+
/// Returns true if there will be more results (limited by Req.Limit);
172+
virtual bool containedRefs(
173+
const ContainedRefsRequest &Req,
174+
llvm::function_ref<void(const ContainedRefsResult &)> Callback) const = 0;
175+
144176
/// Finds all relations (S, P, O) stored in the index such that S is among
145177
/// Req.Subjects and P is Req.Predicate, and invokes \p Callback for (S, O) in
146178
/// each.
@@ -175,6 +207,9 @@ class SwapIndex : public SymbolIndex {
175207
llvm::function_ref<void(const Symbol &)>) const override;
176208
bool refs(const RefsRequest &,
177209
llvm::function_ref<void(const Ref &)>) const override;
210+
bool containedRefs(
211+
const ContainedRefsRequest &,
212+
llvm::function_ref<void(const ContainedRefsResult &)>) const override;
178213
void relations(const RelationsRequest &,
179214
llvm::function_ref<void(const SymbolID &, const Symbol &)>)
180215
const override;

clang-tools-extra/clangd/index/MemIndex.cpp

+20
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include "MemIndex.h"
1010
#include "FuzzyMatch.h"
1111
#include "Quality.h"
12+
#include "index/Index.h"
1213
#include "support/Trace.h"
1314

1415
namespace clang {
@@ -85,6 +86,25 @@ bool MemIndex::refs(const RefsRequest &Req,
8586
return false; // We reported all refs.
8687
}
8788

89+
bool MemIndex::containedRefs(
90+
const ContainedRefsRequest &Req,
91+
llvm::function_ref<void(const ContainedRefsResult &)> Callback) const {
92+
trace::Span Tracer("MemIndex refersTo");
93+
uint32_t Remaining = Req.Limit.value_or(std::numeric_limits<uint32_t>::max());
94+
for (const auto &Pair : Refs) {
95+
for (const auto &R : Pair.second) {
96+
if (!static_cast<int>(ContainedRefsRequest::SupportedRefKinds & R.Kind) ||
97+
Req.ID != R.Container)
98+
continue;
99+
if (Remaining == 0)
100+
return true; // More refs were available.
101+
--Remaining;
102+
Callback({R.Location, R.Kind, Pair.first});
103+
}
104+
}
105+
return false; // We reported all refs.
106+
}
107+
88108
void MemIndex::relations(
89109
const RelationsRequest &Req,
90110
llvm::function_ref<void(const SymbolID &, const Symbol &)> Callback) const {

clang-tools-extra/clangd/index/MemIndex.h

+4
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ class MemIndex : public SymbolIndex {
7272
bool refs(const RefsRequest &Req,
7373
llvm::function_ref<void(const Ref &)> Callback) const override;
7474

75+
bool containedRefs(const ContainedRefsRequest &Req,
76+
llvm::function_ref<void(const ContainedRefsResult &)>
77+
Callback) const override;
78+
7579
void relations(const RelationsRequest &Req,
7680
llvm::function_ref<void(const SymbolID &, const Symbol &)>
7781
Callback) const override;

clang-tools-extra/clangd/index/Merge.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,40 @@ bool MergedIndex::refs(const RefsRequest &Req,
155155
return More || StaticHadMore;
156156
}
157157

158+
bool MergedIndex::containedRefs(
159+
const ContainedRefsRequest &Req,
160+
llvm::function_ref<void(const ContainedRefsResult &)> Callback) const {
161+
trace::Span Tracer("MergedIndex refersTo");
162+
bool More = false;
163+
uint32_t Remaining = Req.Limit.value_or(std::numeric_limits<uint32_t>::max());
164+
// We don't want duplicated refs from the static/dynamic indexes,
165+
// and we can't reliably deduplicate them because offsets may differ slightly.
166+
// We consider the dynamic index authoritative and report all its refs,
167+
// and only report static index refs from other files.
168+
More |= Dynamic->containedRefs(Req, [&](const auto &O) {
169+
Callback(O);
170+
assert(Remaining != 0);
171+
--Remaining;
172+
});
173+
if (Remaining == 0 && More)
174+
return More;
175+
auto DynamicContainsFile = Dynamic->indexedFiles();
176+
// We return less than Req.Limit if static index returns more refs for dirty
177+
// files.
178+
bool StaticHadMore = Static->containedRefs(Req, [&](const auto &O) {
179+
if ((DynamicContainsFile(O.Location.FileURI) & IndexContents::References) !=
180+
IndexContents::None)
181+
return; // ignore refs that have been seen from dynamic index.
182+
if (Remaining == 0) {
183+
More = true;
184+
return;
185+
}
186+
--Remaining;
187+
Callback(O);
188+
});
189+
return More || StaticHadMore;
190+
}
191+
158192
llvm::unique_function<IndexContents(llvm::StringRef) const>
159193
MergedIndex::indexedFiles() const {
160194
return [DynamicContainsFile{Dynamic->indexedFiles()},

clang-tools-extra/clangd/index/Merge.h

+3
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ class MergedIndex : public SymbolIndex {
3838
llvm::function_ref<void(const Symbol &)>) const override;
3939
bool refs(const RefsRequest &,
4040
llvm::function_ref<void(const Ref &)>) const override;
41+
bool containedRefs(
42+
const ContainedRefsRequest &,
43+
llvm::function_ref<void(const ContainedRefsResult &)>) const override;
4144
void relations(const RelationsRequest &,
4245
llvm::function_ref<void(const SymbolID &, const Symbol &)>)
4346
const override;

clang-tools-extra/clangd/index/ProjectAware.cpp

+13
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ class ProjectAwareIndex : public SymbolIndex {
3535
/// Query all indexes while prioritizing the associated one (if any).
3636
bool refs(const RefsRequest &Req,
3737
llvm::function_ref<void(const Ref &)> Callback) const override;
38+
/// Query all indexes while prioritizing the associated one (if any).
39+
bool containedRefs(const ContainedRefsRequest &Req,
40+
llvm::function_ref<void(const ContainedRefsResult &)>
41+
Callback) const override;
3842

3943
/// Queries only the associates index when Req.RestrictForCodeCompletion is
4044
/// set, otherwise queries all.
@@ -94,6 +98,15 @@ bool ProjectAwareIndex::refs(
9498
return false;
9599
}
96100

101+
bool ProjectAwareIndex::containedRefs(
102+
const ContainedRefsRequest &Req,
103+
llvm::function_ref<void(const ContainedRefsResult &)> Callback) const {
104+
trace::Span Tracer("ProjectAwareIndex::refersTo");
105+
if (auto *Idx = getIndex())
106+
return Idx->containedRefs(Req, Callback);
107+
return false;
108+
}
109+
97110
bool ProjectAwareIndex::fuzzyFind(
98111
const FuzzyFindRequest &Req,
99112
llvm::function_ref<void(const Symbol &)> Callback) const {

clang-tools-extra/clangd/index/Ref.h

+3
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ enum class RefKind : uint8_t {
6363
// ^ this references Foo, but does not explicitly spell out its name
6464
// };
6565
Spelled = 1 << 3,
66+
// A reference which is a call. Used as a filter for which references
67+
// to store in data structures used for computing outgoing calls.
68+
Call = 1 << 4,
6669
All = Declaration | Definition | Reference | Spelled,
6770
};
6871

0 commit comments

Comments
 (0)