clang-tools 22.0.0git
XRefs.cpp
Go to the documentation of this file.
1//===--- XRefs.cpp -----------------------------------------------*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8#include "XRefs.h"
9#include "AST.h"
10#include "FindSymbols.h"
11#include "FindTarget.h"
12#include "Headers.h"
13#include "IncludeCleaner.h"
14#include "ParsedAST.h"
15#include "Protocol.h"
16#include "Quality.h"
17#include "Selection.h"
18#include "SourceCode.h"
19#include "clang-include-cleaner/Analysis.h"
20#include "clang-include-cleaner/Types.h"
21#include "index/Index.h"
22#include "index/Merge.h"
23#include "index/Ref.h"
24#include "index/Relation.h"
26#include "index/SymbolID.h"
28#include "support/Logger.h"
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/ASTTypeTraits.h"
31#include "clang/AST/Attr.h"
32#include "clang/AST/Attrs.inc"
33#include "clang/AST/Decl.h"
34#include "clang/AST/DeclCXX.h"
35#include "clang/AST/DeclObjC.h"
36#include "clang/AST/DeclTemplate.h"
37#include "clang/AST/DeclVisitor.h"
38#include "clang/AST/ExprCXX.h"
39#include "clang/AST/RecursiveASTVisitor.h"
40#include "clang/AST/Stmt.h"
41#include "clang/AST/StmtCXX.h"
42#include "clang/AST/StmtVisitor.h"
43#include "clang/AST/Type.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/SourceLocation.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TokenKinds.h"
48#include "clang/Index/IndexDataConsumer.h"
49#include "clang/Index/IndexSymbol.h"
50#include "clang/Index/IndexingAction.h"
51#include "clang/Index/IndexingOptions.h"
52#include "clang/Index/USRGeneration.h"
53#include "clang/Lex/Lexer.h"
54#include "clang/Sema/HeuristicResolver.h"
55#include "clang/Tooling/Syntax/Tokens.h"
56#include "llvm/ADT/ArrayRef.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/DenseSet.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/ScopeExit.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/Error.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/Path.h"
67#include "llvm/Support/raw_ostream.h"
68#include <algorithm>
69#include <optional>
70#include <string>
71#include <vector>
72
73namespace clang {
74namespace clangd {
75namespace {
76
77// Returns the single definition of the entity declared by D, if visible.
78// In particular:
79// - for non-redeclarable kinds (e.g. local vars), return D
80// - for kinds that allow multiple definitions (e.g. namespaces), return nullptr
81// Kinds of nodes that always return nullptr here will not have definitions
82// reported by locateSymbolAt().
83const NamedDecl *getDefinition(const NamedDecl *D) {
84 assert(D);
85 // Decl has one definition that we can find.
86 if (const auto *TD = dyn_cast<TagDecl>(D))
87 return TD->getDefinition();
88 if (const auto *VD = dyn_cast<VarDecl>(D))
89 return VD->getDefinition();
90 if (const auto *FD = dyn_cast<FunctionDecl>(D))
91 return FD->getDefinition();
92 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(D))
93 if (const auto *RD = CTD->getTemplatedDecl())
94 return RD->getDefinition();
95 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
96 if (MD->isThisDeclarationADefinition())
97 return MD;
98 // Look for the method definition inside the implementation decl.
99 auto *DeclCtx = cast<Decl>(MD->getDeclContext());
100 if (DeclCtx->isInvalidDecl())
101 return nullptr;
102
103 if (const auto *CD = dyn_cast<ObjCContainerDecl>(DeclCtx))
104 if (const auto *Impl = getCorrespondingObjCImpl(CD))
105 return Impl->getMethod(MD->getSelector(), MD->isInstanceMethod());
106 }
107 if (const auto *CD = dyn_cast<ObjCContainerDecl>(D))
108 return getCorrespondingObjCImpl(CD);
109 // Only a single declaration is allowed.
110 if (isa<ValueDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
111 isa<TemplateTemplateParmDecl>(D)) // except cases above
112 return D;
113 // Multiple definitions are allowed.
114 return nullptr; // except cases above
115}
116
117void logIfOverflow(const SymbolLocation &Loc) {
118 if (Loc.Start.hasOverflow() || Loc.End.hasOverflow())
119 log("Possible overflow in symbol location: {0}", Loc);
120}
121
122// Convert a SymbolLocation to LSP's Location.
123// TUPath is used to resolve the path of URI.
124std::optional<Location> toLSPLocation(const SymbolLocation &Loc,
125 llvm::StringRef TUPath) {
126 if (!Loc)
127 return std::nullopt;
128 auto LSPLoc = indexToLSPLocation(Loc, TUPath);
129 if (!LSPLoc) {
130 elog("{0}", LSPLoc.takeError());
131 return std::nullopt;
132 }
133 logIfOverflow(Loc);
134 return *LSPLoc;
135}
136
137SymbolLocation toIndexLocation(const Location &Loc, std::string &URIStorage) {
138 SymbolLocation SymLoc;
139 URIStorage = Loc.uri.uri();
140 SymLoc.FileURI = URIStorage.c_str();
141 SymLoc.Start.setLine(Loc.range.start.line);
142 SymLoc.Start.setColumn(Loc.range.start.character);
143 SymLoc.End.setLine(Loc.range.end.line);
144 SymLoc.End.setColumn(Loc.range.end.character);
145 return SymLoc;
146}
147
148// Returns the preferred location between an AST location and an index location.
149SymbolLocation getPreferredLocation(const Location &ASTLoc,
150 const SymbolLocation &IdxLoc,
151 std::string &Scratch) {
152 // Also use a mock symbol for the index location so that other fields (e.g.
153 // definition) are not factored into the preference.
154 Symbol ASTSym, IdxSym;
155 ASTSym.ID = IdxSym.ID = SymbolID("mock_symbol_id");
156 ASTSym.CanonicalDeclaration = toIndexLocation(ASTLoc, Scratch);
157 IdxSym.CanonicalDeclaration = IdxLoc;
158 auto Merged = mergeSymbol(ASTSym, IdxSym);
159 return Merged.CanonicalDeclaration;
160}
161
162std::vector<std::pair<const NamedDecl *, DeclRelationSet>>
163getDeclAtPositionWithRelations(ParsedAST &AST, SourceLocation Pos,
164 DeclRelationSet Relations,
165 ASTNodeKind *NodeKind = nullptr) {
166 unsigned Offset = AST.getSourceManager().getDecomposedSpellingLoc(Pos).second;
167 std::vector<std::pair<const NamedDecl *, DeclRelationSet>> Result;
168 auto ResultFromTree = [&](SelectionTree ST) {
169 if (const SelectionTree::Node *N = ST.commonAncestor()) {
170 if (NodeKind)
171 *NodeKind = N->ASTNode.getNodeKind();
172 // Attributes don't target decls, look at the
173 // thing it's attached to.
174 // We still report the original NodeKind!
175 // This makes the `override` hack work.
176 if (N->ASTNode.get<Attr>() && N->Parent)
177 N = N->Parent;
178 llvm::copy_if(allTargetDecls(N->ASTNode, AST.getHeuristicResolver()),
179 std::back_inserter(Result),
180 [&](auto &Entry) { return !(Entry.second & ~Relations); });
181 }
182 return !Result.empty();
183 };
184 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset,
185 Offset, ResultFromTree);
186 return Result;
187}
188
189std::vector<const NamedDecl *>
190getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations,
191 ASTNodeKind *NodeKind = nullptr) {
192 std::vector<const NamedDecl *> Result;
193 for (auto &Entry :
194 getDeclAtPositionWithRelations(AST, Pos, Relations, NodeKind))
195 Result.push_back(Entry.first);
196 return Result;
197}
198
199// Expects Loc to be a SpellingLocation, will bail out otherwise as it can't
200// figure out a filename.
201std::optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
202 llvm::StringRef TUPath) {
203 const auto &SM = AST.getSourceManager();
204 const auto F = SM.getFileEntryRefForID(SM.getFileID(Loc));
205 if (!F)
206 return std::nullopt;
207 auto FilePath = getCanonicalPath(*F, SM.getFileManager());
208 if (!FilePath) {
209 log("failed to get path!");
210 return std::nullopt;
211 }
212 Location L;
213 L.uri = URIForFile::canonicalize(*FilePath, TUPath);
214 // We call MeasureTokenLength here as TokenBuffer doesn't store spelled tokens
215 // outside the main file.
216 auto TokLen = Lexer::MeasureTokenLength(Loc, SM, AST.getLangOpts());
217 L.range = halfOpenToRange(
218 SM, CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(TokLen)));
219 return L;
220}
221
222// Treat #included files as symbols, to enable go-to-definition on them.
223std::optional<LocatedSymbol> locateFileReferent(const Position &Pos,
224 ParsedAST &AST,
225 llvm::StringRef MainFilePath) {
226 for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
227 if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) {
229 File.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
230 File.PreferredDeclaration = {
231 URIForFile::canonicalize(Inc.Resolved, MainFilePath), Range{}};
232 File.Definition = File.PreferredDeclaration;
233 // We're not going to find any further symbols on #include lines.
234 return File;
235 }
236 }
237 return std::nullopt;
238}
239
240// Macros are simple: there's no declaration/definition distinction.
241// As a consequence, there's no need to look them up in the index either.
242std::optional<LocatedSymbol>
243locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST,
244 llvm::StringRef MainFilePath) {
245 if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) {
246 if (auto Loc =
247 makeLocation(AST.getASTContext(), M->NameLoc, MainFilePath)) {
249 Macro.Name = std::string(M->Name);
250 Macro.PreferredDeclaration = *Loc;
251 Macro.Definition = Loc;
252 Macro.ID = getSymbolID(M->Name, M->Info, AST.getSourceManager());
253 return Macro;
254 }
255 }
256 return std::nullopt;
257}
258
259// A wrapper around `Decl::getCanonicalDecl` to support cases where Clang's
260// definition of a canonical declaration doesn't match up to what a programmer
261// would expect. For example, Objective-C classes can have three types of
262// declarations:
263//
264// - forward declaration(s): @class MyClass;
265// - true declaration (interface definition): @interface MyClass ... @end
266// - true definition (implementation): @implementation MyClass ... @end
267//
268// Clang will consider the forward declaration to be the canonical declaration
269// because it is first. We actually want the class definition if it is
270// available since that is what a programmer would consider the primary
271// declaration to be.
272const NamedDecl *getPreferredDecl(const NamedDecl *D) {
273 // FIXME: Canonical declarations of some symbols might refer to built-in
274 // decls with possibly-invalid source locations (e.g. global new operator).
275 // In such cases we should pick up a redecl with valid source location
276 // instead of failing.
277 D = llvm::cast<NamedDecl>(D->getCanonicalDecl());
278
279 // Prefer Objective-C class/protocol definitions over the forward declaration.
280 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
281 if (const auto *DefinitionID = ID->getDefinition())
282 return DefinitionID;
283 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
284 if (const auto *DefinitionID = PD->getDefinition())
285 return DefinitionID;
286
287 return D;
288}
289
290std::vector<LocatedSymbol> findImplementors(llvm::DenseSet<SymbolID> IDs,
291 RelationKind Predicate,
292 const SymbolIndex *Index,
293 llvm::StringRef MainFilePath) {
294 if (IDs.empty() || !Index)
295 return {};
296 static constexpr trace::Metric FindImplementorsMetric(
297 "find_implementors", trace::Metric::Counter, "case");
298 switch (Predicate) {
300 FindImplementorsMetric.record(1, "find-base");
301 break;
303 FindImplementorsMetric.record(1, "find-override");
304 break;
305 }
306
308 Req.Predicate = Predicate;
309 Req.Subjects = std::move(IDs);
310 std::vector<LocatedSymbol> Results;
311 Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
312 auto DeclLoc =
313 indexToLSPLocation(Object.CanonicalDeclaration, MainFilePath);
314 if (!DeclLoc) {
315 elog("Find overrides: {0}", DeclLoc.takeError());
316 return;
317 }
318 Results.emplace_back();
319 Results.back().Name = Object.Name.str();
320 Results.back().PreferredDeclaration = *DeclLoc;
321 auto DefLoc = indexToLSPLocation(Object.Definition, MainFilePath);
322 if (!DefLoc) {
323 elog("Failed to convert location: {0}", DefLoc.takeError());
324 return;
325 }
326 Results.back().Definition = *DefLoc;
327 });
328 return Results;
329}
330
331// Given LocatedSymbol results derived from the AST, query the index to obtain
332// definitions and preferred declarations.
333void enhanceLocatedSymbolsFromIndex(llvm::MutableArrayRef<LocatedSymbol> Result,
334 const SymbolIndex *Index,
335 llvm::StringRef MainFilePath) {
336 LookupRequest QueryRequest;
337 llvm::DenseMap<SymbolID, unsigned> ResultIndex;
338 for (unsigned I = 0; I < Result.size(); ++I) {
339 if (auto ID = Result[I].ID) {
340 ResultIndex.try_emplace(ID, I);
341 QueryRequest.IDs.insert(ID);
342 }
343 }
344 if (!Index || QueryRequest.IDs.empty())
345 return;
346 std::string Scratch;
347 Index->lookup(QueryRequest, [&](const Symbol &Sym) {
348 auto &R = Result[ResultIndex.lookup(Sym.ID)];
349
350 if (R.Definition) { // from AST
351 // Special case: if the AST yielded a definition, then it may not be
352 // the right *declaration*. Prefer the one from the index.
353 if (auto Loc = toLSPLocation(Sym.CanonicalDeclaration, MainFilePath))
354 R.PreferredDeclaration = *Loc;
355
356 // We might still prefer the definition from the index, e.g. for
357 // generated symbols.
358 if (auto Loc = toLSPLocation(
359 getPreferredLocation(*R.Definition, Sym.Definition, Scratch),
360 MainFilePath))
361 R.Definition = *Loc;
362 } else {
363 R.Definition = toLSPLocation(Sym.Definition, MainFilePath);
364
365 // Use merge logic to choose AST or index declaration.
366 if (auto Loc = toLSPLocation(
367 getPreferredLocation(R.PreferredDeclaration,
368 Sym.CanonicalDeclaration, Scratch),
369 MainFilePath))
370 R.PreferredDeclaration = *Loc;
371 }
372 });
373}
374
375bool objcMethodIsTouched(const SourceManager &SM, const ObjCMethodDecl *OMD,
376 SourceLocation Loc) {
377 unsigned NumSels = OMD->getNumSelectorLocs();
378 for (unsigned I = 0; I < NumSels; ++I)
379 if (SM.getSpellingLoc(OMD->getSelectorLoc(I)) == Loc)
380 return true;
381 return false;
382}
383
384// Decls are more complicated.
385// The AST contains at least a declaration, maybe a definition.
386// These are up-to-date, and so generally preferred over index results.
387// We perform a single batch index lookup to find additional definitions.
388std::vector<LocatedSymbol>
389locateASTReferent(SourceLocation CurLoc, const syntax::Token *TouchedIdentifier,
390 ParsedAST &AST, llvm::StringRef MainFilePath,
391 const SymbolIndex *Index, ASTNodeKind &NodeKind) {
392 const SourceManager &SM = AST.getSourceManager();
393 // Results follow the order of Symbols.Decls.
394 std::vector<LocatedSymbol> Result;
395
396 static constexpr trace::Metric LocateASTReferentMetric(
397 "locate_ast_referent", trace::Metric::Counter, "case");
398 auto AddResultDecl = [&](const NamedDecl *D) {
399 D = getPreferredDecl(D);
400 auto Loc =
401 makeLocation(AST.getASTContext(), nameLocation(*D, SM), MainFilePath);
402 if (!Loc)
403 return;
404
405 Result.emplace_back();
406 Result.back().Name = printName(AST.getASTContext(), *D);
407 Result.back().PreferredDeclaration = *Loc;
408 Result.back().ID = getSymbolID(D);
409 if (const NamedDecl *Def = getDefinition(D))
410 Result.back().Definition = makeLocation(
411 AST.getASTContext(), nameLocation(*Def, SM), MainFilePath);
412 };
413
414 // Emit all symbol locations (declaration or definition) from AST.
415 DeclRelationSet Relations =
417 auto Candidates =
418 getDeclAtPositionWithRelations(AST, CurLoc, Relations, &NodeKind);
419 llvm::DenseSet<SymbolID> VirtualMethods;
420 for (const auto &E : Candidates) {
421 const NamedDecl *D = E.first;
422 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
423 // Special case: virtual void ^method() = 0: jump to all overrides.
424 // FIXME: extend it to ^virtual, unfortunately, virtual location is not
425 // saved in the AST.
426 if (CMD->isPureVirtual()) {
427 if (TouchedIdentifier && SM.getSpellingLoc(CMD->getLocation()) ==
428 TouchedIdentifier->location()) {
429 VirtualMethods.insert(getSymbolID(CMD));
430 LocateASTReferentMetric.record(1, "method-to-override");
431 }
432 }
433 // Special case: void foo() ^override: jump to the overridden method.
434 if (NodeKind.isSame(ASTNodeKind::getFromNodeKind<OverrideAttr>()) ||
435 NodeKind.isSame(ASTNodeKind::getFromNodeKind<FinalAttr>())) {
436 // We may be overridding multiple methods - offer them all.
437 for (const NamedDecl *ND : CMD->overridden_methods())
438 AddResultDecl(ND);
439 continue;
440 }
441 }
442 // Special case: - (void)^method {} should jump to overrides, but the decl
443 // shouldn't, only the definition. Note that an Objective-C method can
444 // override a parent class or protocol.
445 //
446 // FIXME: Support jumping from a protocol decl to overrides on go-to
447 // definition.
448 if (const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(D)) {
449 if (OMD->isThisDeclarationADefinition() && TouchedIdentifier &&
450 objcMethodIsTouched(SM, OMD, TouchedIdentifier->location())) {
451 llvm::SmallVector<const ObjCMethodDecl *, 4> Overrides;
452 OMD->getOverriddenMethods(Overrides);
453 if (!Overrides.empty()) {
454 for (const auto *Override : Overrides)
455 AddResultDecl(Override);
456 LocateASTReferentMetric.record(1, "objc-overriden-method");
457 }
458 AddResultDecl(OMD);
459 continue;
460 }
461 }
462
463 // Special case: the cursor is on an alias, prefer other results.
464 // This targets "using ns::^Foo", where the target is more interesting.
465 // This does not trigger on renaming aliases:
466 // `using Foo = ^Bar` already targets Bar via a TypeLoc
467 // `using ^Foo = Bar` has no other results, as Underlying is filtered.
468 if (E.second & DeclRelation::Alias && Candidates.size() > 1 &&
469 // beginLoc/endLoc are a token range, so rewind the identifier we're in.
470 SM.isPointWithin(TouchedIdentifier ? TouchedIdentifier->location()
471 : CurLoc,
472 D->getBeginLoc(), D->getEndLoc()))
473 continue;
474
475 // Special case: the point of declaration of a template specialization,
476 // it's more useful to navigate to the template declaration.
477 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
478 if (TouchedIdentifier &&
479 D->getLocation() == TouchedIdentifier->location()) {
480 LocateASTReferentMetric.record(1, "template-specialization-to-primary");
481 AddResultDecl(CTSD->getSpecializedTemplate());
482 continue;
483 }
484 }
485
486 // Special case: if the class name is selected, also map Objective-C
487 // categories and category implementations back to their class interface.
488 //
489 // Since `TouchedIdentifier` might refer to the `ObjCCategoryImplDecl`
490 // instead of the `ObjCCategoryDecl` we intentionally check the contents
491 // of the locs when checking for class name equivalence.
492 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D))
493 if (const auto *ID = CD->getClassInterface())
494 if (TouchedIdentifier &&
495 (CD->getLocation() == TouchedIdentifier->location() ||
496 ID->getName() == TouchedIdentifier->text(SM))) {
497 LocateASTReferentMetric.record(1, "objc-category-to-class");
498 AddResultDecl(ID);
499 }
500
501 LocateASTReferentMetric.record(1, "regular");
502 // Otherwise the target declaration is the right one.
503 AddResultDecl(D);
504 }
505 enhanceLocatedSymbolsFromIndex(Result, Index, MainFilePath);
506
507 auto Overrides = findImplementors(VirtualMethods, RelationKind::OverriddenBy,
508 Index, MainFilePath);
509 Result.insert(Result.end(), Overrides.begin(), Overrides.end());
510 return Result;
511}
512
513std::vector<LocatedSymbol> locateSymbolForType(const ParsedAST &AST,
514 const QualType &Type,
515 const SymbolIndex *Index) {
516 const auto &SM = AST.getSourceManager();
517 auto MainFilePath = AST.tuPath();
518
519 // FIXME: this sends unique_ptr<Foo> to unique_ptr<T>.
520 // Likely it would be better to send it to Foo (heuristically) or to both.
521 auto Decls = targetDecl(DynTypedNode::create(Type.getNonReferenceType()),
523 AST.getHeuristicResolver());
524 if (Decls.empty())
525 return {};
526
527 std::vector<LocatedSymbol> Results;
528 const auto &ASTContext = AST.getASTContext();
529
530 for (const NamedDecl *D : Decls) {
531 D = getPreferredDecl(D);
532
533 auto Loc = makeLocation(ASTContext, nameLocation(*D, SM), MainFilePath);
534 if (!Loc)
535 continue;
536
537 Results.emplace_back();
538 Results.back().Name = printName(ASTContext, *D);
539 Results.back().PreferredDeclaration = *Loc;
540 Results.back().ID = getSymbolID(D);
541 if (const NamedDecl *Def = getDefinition(D))
542 Results.back().Definition =
543 makeLocation(ASTContext, nameLocation(*Def, SM), MainFilePath);
544 }
545 enhanceLocatedSymbolsFromIndex(Results, Index, MainFilePath);
546
547 return Results;
548}
549
550bool tokenSpelledAt(SourceLocation SpellingLoc, const syntax::TokenBuffer &TB) {
551 auto ExpandedTokens = TB.expandedTokens(
552 TB.sourceManager().getMacroArgExpandedLocation(SpellingLoc));
553 return !ExpandedTokens.empty();
554}
555
556llvm::StringRef sourcePrefix(SourceLocation Loc, const SourceManager &SM) {
557 auto D = SM.getDecomposedLoc(Loc);
558 bool Invalid = false;
559 llvm::StringRef Buf = SM.getBufferData(D.first, &Invalid);
560 if (Invalid || D.second > Buf.size())
561 return "";
562 return Buf.substr(0, D.second);
563}
564
565bool isDependentName(ASTNodeKind NodeKind) {
566 return NodeKind.isSame(ASTNodeKind::getFromNodeKind<OverloadExpr>()) ||
567 NodeKind.isSame(
568 ASTNodeKind::getFromNodeKind<CXXDependentScopeMemberExpr>()) ||
569 NodeKind.isSame(
570 ASTNodeKind::getFromNodeKind<DependentScopeDeclRefExpr>());
571}
572
573} // namespace
574
575std::vector<LocatedSymbol> locateSymbolTextually(const SpelledWord &Word,
576 ParsedAST &AST,
577 const SymbolIndex *Index,
578 llvm::StringRef MainFilePath,
579 ASTNodeKind NodeKind) {
580 // Don't use heuristics if this is a real identifier, or not an
581 // identifier.
582 // Exception: dependent names, because those may have useful textual
583 // matches that AST-based heuristics cannot find.
584 if ((Word.ExpandedToken && !isDependentName(NodeKind)) ||
585 !Word.LikelyIdentifier || !Index)
586 return {};
587 // We don't want to handle words in string literals. (It'd be nice to list
588 // *allowed* token kinds explicitly, but comment Tokens aren't retained).
589 if (Word.PartOfSpelledToken &&
590 isStringLiteral(Word.PartOfSpelledToken->kind()))
591 return {};
592
593 const auto &SM = AST.getSourceManager();
594 // Look up the selected word in the index.
596 Req.Query = Word.Text.str();
597 Req.ProximityPaths = {MainFilePath.str()};
598 // Find the namespaces to query by lexing the file.
599 Req.Scopes =
600 visibleNamespaces(sourcePrefix(Word.Location, SM), AST.getLangOpts());
601 // FIXME: For extra strictness, consider AnyScope=false.
602 Req.AnyScope = true;
603 // We limit the results to 3 further below. This limit is to avoid fetching
604 // too much data, while still likely having enough for 3 results to remain
605 // after additional filtering.
606 Req.Limit = 10;
607 bool TooMany = false;
608 using ScoredLocatedSymbol = std::pair<float, LocatedSymbol>;
609 std::vector<ScoredLocatedSymbol> ScoredResults;
610 Index->fuzzyFind(Req, [&](const Symbol &Sym) {
611 // Only consider exact name matches, including case.
612 // This is to avoid too many false positives.
613 // We could relax this in the future (e.g. to allow for typos) if we make
614 // the query more accurate by other means.
615 if (Sym.Name != Word.Text)
616 return;
617
618 // Exclude constructor results. They have the same name as the class,
619 // but we don't have enough context to prefer them over the class.
620 if (Sym.SymInfo.Kind == index::SymbolKind::Constructor)
621 return;
622
623 auto MaybeDeclLoc =
624 indexToLSPLocation(Sym.CanonicalDeclaration, MainFilePath);
625 if (!MaybeDeclLoc) {
626 log("locateSymbolNamedTextuallyAt: {0}", MaybeDeclLoc.takeError());
627 return;
628 }
629 LocatedSymbol Located;
630 Located.PreferredDeclaration = *MaybeDeclLoc;
631 Located.Name = (Sym.Name + Sym.TemplateSpecializationArgs).str();
632 Located.ID = Sym.ID;
633 if (Sym.Definition) {
634 auto MaybeDefLoc = indexToLSPLocation(Sym.Definition, MainFilePath);
635 if (!MaybeDefLoc) {
636 log("locateSymbolNamedTextuallyAt: {0}", MaybeDefLoc.takeError());
637 return;
638 }
639 Located.PreferredDeclaration = *MaybeDefLoc;
640 Located.Definition = *MaybeDefLoc;
641 }
642
643 if (ScoredResults.size() >= 5) {
644 // If we have more than 5 results, don't return anything,
645 // as confidence is too low.
646 // FIXME: Alternatively, try a stricter query?
647 TooMany = true;
648 return;
649 }
650
651 SymbolQualitySignals Quality;
652 Quality.merge(Sym);
653 SymbolRelevanceSignals Relevance;
654 Relevance.Name = Sym.Name;
656 Relevance.merge(Sym);
657 auto Score = evaluateSymbolAndRelevance(Quality.evaluateHeuristics(),
658 Relevance.evaluateHeuristics());
659 dlog("locateSymbolNamedTextuallyAt: {0}{1} = {2}\n{3}{4}\n", Sym.Scope,
660 Sym.Name, Score, Quality, Relevance);
661
662 ScoredResults.push_back({Score, std::move(Located)});
663 });
664
665 if (TooMany) {
666 vlog("Heuristic index lookup for {0} returned too many candidates, ignored",
667 Word.Text);
668 return {};
669 }
670
671 llvm::sort(ScoredResults,
672 [](const ScoredLocatedSymbol &A, const ScoredLocatedSymbol &B) {
673 return A.first > B.first;
674 });
675 std::vector<LocatedSymbol> Results;
676 for (auto &Res : std::move(ScoredResults))
677 Results.push_back(std::move(Res.second));
678 if (Results.empty())
679 vlog("No heuristic index definition for {0}", Word.Text);
680 else
681 log("Found definition heuristically in index for {0}", Word.Text);
682 return Results;
683}
684
685const syntax::Token *findNearbyIdentifier(const SpelledWord &Word,
686 const syntax::TokenBuffer &TB) {
687 // Don't use heuristics if this is a real identifier.
688 // Unlikely identifiers are OK if they were used as identifiers nearby.
689 if (Word.ExpandedToken)
690 return nullptr;
691 // We don't want to handle words in string literals. (It'd be nice to list
692 // *allowed* token kinds explicitly, but comment Tokens aren't retained).
693 if (Word.PartOfSpelledToken &&
694 isStringLiteral(Word.PartOfSpelledToken->kind()))
695 return {};
696
697 const SourceManager &SM = TB.sourceManager();
698 // We prefer the closest possible token, line-wise. Backwards is penalized.
699 // Ties are implicitly broken by traversal order (first-one-wins).
700 auto File = SM.getFileID(Word.Location);
701 unsigned WordLine = SM.getSpellingLineNumber(Word.Location);
702 auto Cost = [&](SourceLocation Loc) -> unsigned {
703 assert(SM.getFileID(Loc) == File && "spelled token in wrong file?");
704 unsigned Line = SM.getSpellingLineNumber(Loc);
705 return Line >= WordLine ? Line - WordLine : 2 * (WordLine - Line);
706 };
707 const syntax::Token *BestTok = nullptr;
708 unsigned BestCost = -1;
709 // Search bounds are based on word length:
710 // - forward: 2^N lines
711 // - backward: 2^(N-1) lines.
712 unsigned MaxDistance =
713 1U << std::min<unsigned>(Word.Text.size(),
714 std::numeric_limits<unsigned>::digits - 1);
715 // Line number for SM.translateLineCol() should be one-based, also
716 // SM.translateLineCol() can handle line number greater than
717 // number of lines in the file.
718 // - LineMin = max(1, WordLine + 1 - 2^(N-1))
719 // - LineMax = WordLine + 1 + 2^N
720 unsigned LineMin =
721 WordLine + 1 <= MaxDistance / 2 ? 1 : WordLine + 1 - MaxDistance / 2;
722 unsigned LineMax = WordLine + 1 + MaxDistance;
723 SourceLocation LocMin = SM.translateLineCol(File, LineMin, 1);
724 assert(LocMin.isValid());
725 SourceLocation LocMax = SM.translateLineCol(File, LineMax, 1);
726 assert(LocMax.isValid());
727
728 // Updates BestTok and BestCost if Tok is a good candidate.
729 // May return true if the cost is too high for this token.
730 auto Consider = [&](const syntax::Token &Tok) {
731 if (Tok.location() < LocMin || Tok.location() > LocMax)
732 return true; // we are too far from the word, break the outer loop.
733 if (!(Tok.kind() == tok::identifier && Tok.text(SM) == Word.Text))
734 return false;
735 // No point guessing the same location we started with.
736 if (Tok.location() == Word.Location)
737 return false;
738 // We've done cheap checks, compute cost so we can break the caller's loop.
739 unsigned TokCost = Cost(Tok.location());
740 if (TokCost >= BestCost)
741 return true; // causes the outer loop to break.
742 // Allow locations that might be part of the AST, and macros (even if empty)
743 // but not things like disabled preprocessor sections.
744 if (!(tokenSpelledAt(Tok.location(), TB) || TB.expansionStartingAt(&Tok)))
745 return false;
746 // We already verified this token is an improvement.
747 BestCost = TokCost;
748 BestTok = &Tok;
749 return false;
750 };
751 auto SpelledTokens = TB.spelledTokens(File);
752 // Find where the word occurred in the token stream, to search forward & back.
753 auto *I = llvm::partition_point(SpelledTokens, [&](const syntax::Token &T) {
754 assert(SM.getFileID(T.location()) == SM.getFileID(Word.Location));
755 return T.location() < Word.Location; // Comparison OK: same file.
756 });
757 // Search for matches after the cursor.
758 for (const syntax::Token &Tok : llvm::ArrayRef(I, SpelledTokens.end()))
759 if (Consider(Tok))
760 break; // costs of later tokens are greater...
761 // Search for matches before the cursor.
762 for (const syntax::Token &Tok :
763 llvm::reverse(llvm::ArrayRef(SpelledTokens.begin(), I)))
764 if (Consider(Tok))
765 break;
766
767 if (BestTok)
768 vlog(
769 "Word {0} under cursor {1} isn't a token (after PP), trying nearby {2}",
770 Word.Text, Word.Location.printToString(SM),
771 BestTok->location().printToString(SM));
772
773 return BestTok;
774}
775
776std::vector<LocatedSymbol> locateSymbolAt(ParsedAST &AST, Position Pos,
777 const SymbolIndex *Index) {
778 const auto &SM = AST.getSourceManager();
779 auto MainFilePath = AST.tuPath();
780
781 if (auto File = locateFileReferent(Pos, AST, MainFilePath))
782 return {std::move(*File)};
783
784 auto CurLoc = sourceLocationInMainFile(SM, Pos);
785 if (!CurLoc) {
786 elog("locateSymbolAt failed to convert position to source location: {0}",
787 CurLoc.takeError());
788 return {};
789 }
790
791 const syntax::Token *TouchedIdentifier = nullptr;
792 auto TokensTouchingCursor =
793 syntax::spelledTokensTouching(*CurLoc, AST.getTokens());
794 for (const syntax::Token &Tok : TokensTouchingCursor) {
795 if (Tok.kind() == tok::identifier) {
796 if (auto Macro = locateMacroReferent(Tok, AST, MainFilePath))
797 // Don't look at the AST or index if we have a macro result.
798 // (We'd just return declarations referenced from the macro's
799 // expansion.)
800 return {*std::move(Macro)};
801
802 TouchedIdentifier = &Tok;
803 break;
804 }
805
806 if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
807 // go-to-definition on auto should find the definition of the deduced
808 // type, if possible
809 if (auto Deduced =
810 getDeducedType(AST.getASTContext(), AST.getHeuristicResolver(),
811 Tok.location())) {
812 auto LocSym = locateSymbolForType(AST, *Deduced, Index);
813 if (!LocSym.empty())
814 return LocSym;
815 }
816 }
817 }
818
819 ASTNodeKind NodeKind;
820 auto ASTResults = locateASTReferent(*CurLoc, TouchedIdentifier, AST,
821 MainFilePath, Index, NodeKind);
822 if (!ASTResults.empty())
823 return ASTResults;
824
825 // If the cursor can't be resolved directly, try fallback strategies.
826 auto Word =
827 SpelledWord::touching(*CurLoc, AST.getTokens(), AST.getLangOpts());
828 if (Word) {
829 // Is the same word nearby a real identifier that might refer to something?
830 if (const syntax::Token *NearbyIdent =
831 findNearbyIdentifier(*Word, AST.getTokens())) {
832 if (auto Macro = locateMacroReferent(*NearbyIdent, AST, MainFilePath)) {
833 log("Found macro definition heuristically using nearby identifier {0}",
834 Word->Text);
835 return {*std::move(Macro)};
836 }
837 ASTResults = locateASTReferent(NearbyIdent->location(), NearbyIdent, AST,
838 MainFilePath, Index, NodeKind);
839 if (!ASTResults.empty()) {
840 log("Found definition heuristically using nearby identifier {0}",
841 NearbyIdent->text(SM));
842 return ASTResults;
843 }
844 vlog("No definition found using nearby identifier {0} at {1}", Word->Text,
845 Word->Location.printToString(SM));
846 }
847 // No nearby word, or it didn't refer to anything either. Try the index.
848 auto TextualResults =
849 locateSymbolTextually(*Word, AST, Index, MainFilePath, NodeKind);
850 if (!TextualResults.empty())
851 return TextualResults;
852 }
853
854 return {};
855}
856
857std::vector<DocumentLink> getDocumentLinks(ParsedAST &AST) {
858 const auto &SM = AST.getSourceManager();
859
860 std::vector<DocumentLink> Result;
861 for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
862 if (Inc.Resolved.empty())
863 continue;
864
865 // Get the location of the # symbole of the "#include ..." statement
866 auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
867
868 // get the # Token itself, std::next to get the "include" token and the
869 // first token after (aka "File Token")
870 const auto *HashTok = AST.getTokens().spelledTokenContaining(HashLoc);
871 assert(HashTok && "got inclusion at wrong offset");
872 const auto *IncludeTok = std::next(HashTok);
873 const auto *FileTok = std::next(IncludeTok);
874
875 // The File Token can either be of kind :
876 // "less" if using the "#include <h-char-sequence> new-line" syntax
877 // "string_literal" if using the "#include "q-char-sequence" new-line"
878 // syntax something else (most likely "identifier") if using the "#include
879 // pp-tokens new-line" syntax (#include with macro argument)
880
881 CharSourceRange FileRange;
882
883 if (FileTok->kind() == tok::TokenKind::less) {
884 // FileTok->range would only include the '<' char. Hence we explicitly use
885 // Inc.Written's length.
886 FileRange =
887 syntax::FileRange(SM, FileTok->location(), Inc.Written.length())
888 .toCharRange(SM);
889 } else if (FileTok->kind() == tok::TokenKind::string_literal) {
890 // FileTok->range includes the quotes for string literals so just return
891 // it.
892 FileRange = FileTok->range(SM).toCharRange(SM);
893 } else {
894 // FileTok is the first Token of a macro spelling
895
896 // Report the range of the first token (as it should be the macro
897 // identifier)
898 // We could use the AST to find the last spelled token of the macro and
899 // report a range spanning the full macro expression, but it would require
900 // using token-buffers that are deemed too unstable and crash-prone
901 // due to optimizations in cland
902
903 FileRange = FileTok->range(SM).toCharRange(SM);
904 }
905
906 Result.push_back(
907 DocumentLink({halfOpenToRange(SM, FileRange),
908 URIForFile::canonicalize(Inc.Resolved, AST.tuPath())}));
909 }
910
911 return Result;
912}
913
914namespace {
915
916/// Collects references to symbols within the main file.
917class ReferenceFinder : public index::IndexDataConsumer {
918public:
919 struct Reference {
920 syntax::Token SpelledTok;
921 index::SymbolRoleSet Role;
922 const Decl *Container;
923
924 Range range(const SourceManager &SM) const {
925 return halfOpenToRange(SM, SpelledTok.range(SM).toCharRange(SM));
926 }
927 };
928
929 ReferenceFinder(ParsedAST &AST,
930 const llvm::ArrayRef<const NamedDecl *> Targets,
931 bool PerToken)
932 : PerToken(PerToken), AST(AST) {
933 for (const NamedDecl *ND : Targets) {
934 TargetDecls.insert(ND->getCanonicalDecl());
935 if (auto *Constructor = llvm::dyn_cast<clang::CXXConstructorDecl>(ND))
936 TargetConstructors.insert(Constructor);
937 }
938 }
939
940 std::vector<Reference> take() && {
941 llvm::sort(References, [](const Reference &L, const Reference &R) {
942 auto LTok = L.SpelledTok.location();
943 auto RTok = R.SpelledTok.location();
944 return std::tie(LTok, L.Role) < std::tie(RTok, R.Role);
945 });
946 // We sometimes see duplicates when parts of the AST get traversed twice.
947 References.erase(llvm::unique(References,
948 [](const Reference &L, const Reference &R) {
949 auto LTok = L.SpelledTok.location();
950 auto RTok = R.SpelledTok.location();
951 return std::tie(LTok, L.Role) ==
952 std::tie(RTok, R.Role);
953 }),
954 References.end());
955 return std::move(References);
956 }
957
958 bool forwardsToConstructor(const Decl *D) {
959 if (TargetConstructors.empty())
960 return false;
961 auto *FD = llvm::dyn_cast<clang::FunctionDecl>(D);
962 if (FD == nullptr || !FD->isTemplateInstantiation())
963 return false;
964
965 SmallVector<const CXXConstructorDecl *, 1> *Constructors = nullptr;
966 if (auto Entry = AST.ForwardingToConstructorCache.find(FD);
967 Entry != AST.ForwardingToConstructorCache.end())
968 Constructors = &Entry->getSecond();
969 if (Constructors == nullptr) {
970 if (auto *PT = FD->getPrimaryTemplate();
971 PT == nullptr || !isLikelyForwardingFunction(PT))
972 return false;
973
974 SmallVector<const CXXConstructorDecl *, 1> FoundConstructors =
976 auto Iter = AST.ForwardingToConstructorCache.try_emplace(
977 FD, std::move(FoundConstructors));
978 Constructors = &Iter.first->getSecond();
979 }
980 for (auto *Constructor : *Constructors)
981 if (TargetConstructors.contains(Constructor))
982 return true;
983 return false;
984 }
985
986 bool
987 handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles,
988 llvm::ArrayRef<index::SymbolRelation> Relations,
989 SourceLocation Loc,
990 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
991 if (!TargetDecls.contains(D->getCanonicalDecl()) &&
992 !forwardsToConstructor(ASTNode.OrigD))
993 return true;
994 const SourceManager &SM = AST.getSourceManager();
995 if (!isInsideMainFile(Loc, SM))
996 return true;
997 const auto &TB = AST.getTokens();
998
999 llvm::SmallVector<SourceLocation, 1> Locs;
1000 if (PerToken) {
1001 // Check whether this is one of the few constructs where the reference
1002 // can be split over several tokens.
1003 if (auto *OME = llvm::dyn_cast_or_null<ObjCMessageExpr>(ASTNode.OrigE)) {
1004 OME->getSelectorLocs(Locs);
1005 } else if (auto *OMD =
1006 llvm::dyn_cast_or_null<ObjCMethodDecl>(ASTNode.OrigD)) {
1007 OMD->getSelectorLocs(Locs);
1008 }
1009 // Sanity check: we expect the *first* token to match the reported loc.
1010 // Otherwise, maybe it was e.g. some other kind of reference to a Decl.
1011 if (!Locs.empty() && Locs.front() != Loc)
1012 Locs.clear(); // First token doesn't match, assume our guess was wrong.
1013 }
1014 if (Locs.empty())
1015 Locs.push_back(Loc);
1016
1017 SymbolCollector::Options CollectorOpts;
1018 CollectorOpts.CollectMainFileSymbols = true;
1019 for (SourceLocation L : Locs) {
1020 L = SM.getFileLoc(L);
1021 if (const auto *Tok = TB.spelledTokenContaining(L))
1022 References.push_back(
1023 {*Tok, Roles,
1024 SymbolCollector::getRefContainer(ASTNode.Parent, CollectorOpts)});
1025 }
1026 return true;
1027 }
1028
1029private:
1030 bool PerToken; // If true, report 3 references for split ObjC selector names.
1031 std::vector<Reference> References;
1032 ParsedAST &AST;
1033 llvm::DenseSet<const Decl *> TargetDecls;
1034 // Constructors need special handling since they can be hidden behind forwards
1035 llvm::DenseSet<const CXXConstructorDecl *> TargetConstructors;
1036};
1037
1038std::vector<ReferenceFinder::Reference>
1039findRefs(const llvm::ArrayRef<const NamedDecl *> TargetDecls, ParsedAST &AST,
1040 bool PerToken) {
1041 ReferenceFinder RefFinder(AST, TargetDecls, PerToken);
1042 index::IndexingOptions IndexOpts;
1043 IndexOpts.SystemSymbolFilter =
1044 index::IndexingOptions::SystemSymbolFilterKind::All;
1045 IndexOpts.IndexFunctionLocals = true;
1046 IndexOpts.IndexParametersInDeclarations = true;
1047 IndexOpts.IndexTemplateParameters = true;
1048 indexTopLevelDecls(AST.getASTContext(), AST.getPreprocessor(),
1049 AST.getLocalTopLevelDecls(), RefFinder, IndexOpts);
1050 return std::move(RefFinder).take();
1051}
1052
1053const Stmt *getFunctionBody(DynTypedNode N) {
1054 if (const auto *FD = N.get<FunctionDecl>())
1055 return FD->getBody();
1056 if (const auto *FD = N.get<BlockDecl>())
1057 return FD->getBody();
1058 if (const auto *FD = N.get<LambdaExpr>())
1059 return FD->getBody();
1060 if (const auto *FD = N.get<ObjCMethodDecl>())
1061 return FD->getBody();
1062 return nullptr;
1063}
1064
1065const Stmt *getLoopBody(DynTypedNode N) {
1066 if (const auto *LS = N.get<ForStmt>())
1067 return LS->getBody();
1068 if (const auto *LS = N.get<CXXForRangeStmt>())
1069 return LS->getBody();
1070 if (const auto *LS = N.get<WhileStmt>())
1071 return LS->getBody();
1072 if (const auto *LS = N.get<DoStmt>())
1073 return LS->getBody();
1074 return nullptr;
1075}
1076
1077// AST traversal to highlight control flow statements under some root.
1078// Once we hit further control flow we prune the tree (or at least restrict
1079// what we highlight) so we capture e.g. breaks from the outer loop only.
1080class FindControlFlow : public RecursiveASTVisitor<FindControlFlow> {
1081 // Types of control-flow statements we might highlight.
1082 enum Target {
1083 Break = 1,
1084 Continue = 2,
1085 Return = 4,
1086 Case = 8,
1087 Throw = 16,
1088 Goto = 32,
1089 All = Break | Continue | Return | Case | Throw | Goto,
1090 };
1091 int Ignore = 0; // bitmask of Target - what are we *not* highlighting?
1092 SourceRange Bounds; // Half-open, restricts reported targets.
1093 std::vector<SourceLocation> &Result;
1094 const SourceManager &SM;
1095
1096 // Masks out targets for a traversal into D.
1097 // Traverses the subtree using Delegate() if any targets remain.
1098 template <typename Func>
1099 bool filterAndTraverse(DynTypedNode D, const Func &Delegate) {
1100 llvm::scope_exit RestoreIgnore(
1101 [OldIgnore(Ignore), this] { Ignore = OldIgnore; });
1102 if (getFunctionBody(D))
1103 Ignore = All;
1104 else if (getLoopBody(D))
1105 Ignore |= Continue | Break;
1106 else if (D.get<SwitchStmt>())
1107 Ignore |= Break | Case;
1108 // Prune tree if we're not looking for anything.
1109 return (Ignore == All) ? true : Delegate();
1110 }
1111
1112 void found(Target T, SourceLocation Loc) {
1113 if (T & Ignore)
1114 return;
1115 if (SM.isBeforeInTranslationUnit(Loc, Bounds.getBegin()) ||
1116 SM.isBeforeInTranslationUnit(Bounds.getEnd(), Loc))
1117 return;
1118 Result.push_back(Loc);
1119 }
1120
1121public:
1122 FindControlFlow(SourceRange Bounds, std::vector<SourceLocation> &Result,
1123 const SourceManager &SM)
1124 : Bounds(Bounds), Result(Result), SM(SM) {}
1125
1126 // When traversing function or loops, limit targets to those that still
1127 // refer to the original root.
1128 bool TraverseDecl(Decl *D) {
1129 return !D || filterAndTraverse(DynTypedNode::create(*D), [&] {
1130 return RecursiveASTVisitor::TraverseDecl(D);
1131 });
1132 }
1133 bool TraverseStmt(Stmt *S) {
1134 return !S || filterAndTraverse(DynTypedNode::create(*S), [&] {
1135 return RecursiveASTVisitor::TraverseStmt(S);
1136 });
1137 }
1138
1139 // Add leaves that we found and want.
1140 bool VisitReturnStmt(ReturnStmt *R) {
1141 found(Return, R->getReturnLoc());
1142 return true;
1143 }
1144 bool VisitBreakStmt(BreakStmt *B) {
1145 found(Break, B->getKwLoc());
1146 return true;
1147 }
1148 bool VisitContinueStmt(ContinueStmt *C) {
1149 found(Continue, C->getKwLoc());
1150 return true;
1151 }
1152 bool VisitSwitchCase(SwitchCase *C) {
1153 found(Case, C->getKeywordLoc());
1154 return true;
1155 }
1156 bool VisitCXXThrowExpr(CXXThrowExpr *T) {
1157 found(Throw, T->getThrowLoc());
1158 return true;
1159 }
1160 bool VisitGotoStmt(GotoStmt *G) {
1161 // Goto is interesting if its target is outside the root.
1162 if (const auto *LD = G->getLabel()) {
1163 if (SM.isBeforeInTranslationUnit(LD->getLocation(), Bounds.getBegin()) ||
1164 SM.isBeforeInTranslationUnit(Bounds.getEnd(), LD->getLocation()))
1165 found(Goto, G->getGotoLoc());
1166 }
1167 return true;
1168 }
1169};
1170
1171// Given a location within a switch statement, return the half-open range that
1172// covers the case it's contained in.
1173// We treat `case X: case Y: ...` as one case, and assume no other fallthrough.
1174SourceRange findCaseBounds(const SwitchStmt &Switch, SourceLocation Loc,
1175 const SourceManager &SM) {
1176 // Cases are not stored in order, sort them first.
1177 // (In fact they seem to be stored in reverse order, don't rely on this)
1178 std::vector<const SwitchCase *> Cases;
1179 for (const SwitchCase *Case = Switch.getSwitchCaseList(); Case;
1180 Case = Case->getNextSwitchCase())
1181 Cases.push_back(Case);
1182 llvm::sort(Cases, [&](const SwitchCase *L, const SwitchCase *R) {
1183 return SM.isBeforeInTranslationUnit(L->getKeywordLoc(), R->getKeywordLoc());
1184 });
1185
1186 // Find the first case after the target location, the end of our range.
1187 auto CaseAfter = llvm::partition_point(Cases, [&](const SwitchCase *C) {
1188 return !SM.isBeforeInTranslationUnit(Loc, C->getKeywordLoc());
1189 });
1190 SourceLocation End = CaseAfter == Cases.end() ? Switch.getEndLoc()
1191 : (*CaseAfter)->getKeywordLoc();
1192
1193 // Our target can be before the first case - cases are optional!
1194 if (CaseAfter == Cases.begin())
1195 return SourceRange(Switch.getBeginLoc(), End);
1196 // The start of our range is usually the previous case, but...
1197 auto CaseBefore = std::prev(CaseAfter);
1198 // ... rewind CaseBefore to the first in a `case A: case B: ...` sequence.
1199 while (CaseBefore != Cases.begin() &&
1200 (*std::prev(CaseBefore))->getSubStmt() == *CaseBefore)
1201 --CaseBefore;
1202 return SourceRange((*CaseBefore)->getKeywordLoc(), End);
1203}
1204
1205// Returns the locations of control flow statements related to N. e.g.:
1206// for => branches: break/continue/return/throw
1207// break => controlling loop (forwhile/do), and its related control flow
1208// return => all returns/throws from the same function
1209// When an inner block is selected, we include branches bound to outer blocks
1210// as these are exits from the inner block. e.g. return in a for loop.
1211// FIXME: We don't analyze catch blocks, throw is treated the same as return.
1212std::vector<SourceLocation> relatedControlFlow(const SelectionTree::Node &N) {
1213 const SourceManager &SM =
1214 N.getDeclContext().getParentASTContext().getSourceManager();
1215 std::vector<SourceLocation> Result;
1216
1217 // First, check if we're at a node that can resolve to a root.
1218 enum class Cur { None, Break, Continue, Return, Case, Throw } Cursor;
1219 if (N.ASTNode.get<BreakStmt>()) {
1220 Cursor = Cur::Break;
1221 } else if (N.ASTNode.get<ContinueStmt>()) {
1222 Cursor = Cur::Continue;
1223 } else if (N.ASTNode.get<ReturnStmt>()) {
1224 Cursor = Cur::Return;
1225 } else if (N.ASTNode.get<CXXThrowExpr>()) {
1226 Cursor = Cur::Throw;
1227 } else if (N.ASTNode.get<SwitchCase>()) {
1228 Cursor = Cur::Case;
1229 } else if (const GotoStmt *GS = N.ASTNode.get<GotoStmt>()) {
1230 // We don't know what root to associate with, but highlight the goto/label.
1231 Result.push_back(GS->getGotoLoc());
1232 if (const auto *LD = GS->getLabel())
1233 Result.push_back(LD->getLocation());
1234 Cursor = Cur::None;
1235 } else {
1236 Cursor = Cur::None;
1237 }
1238
1239 const Stmt *Root = nullptr; // Loop or function body to traverse.
1240 SourceRange Bounds;
1241 // Look up the tree for a root (or just at this node if we didn't find a leaf)
1242 for (const auto *P = &N; P; P = P->Parent) {
1243 // return associates with enclosing function
1244 if (const Stmt *FunctionBody = getFunctionBody(P->ASTNode)) {
1245 if (Cursor == Cur::Return || Cursor == Cur::Throw) {
1246 Root = FunctionBody;
1247 }
1248 break; // other leaves don't cross functions.
1249 }
1250 // break/continue associate with enclosing loop.
1251 if (const Stmt *LoopBody = getLoopBody(P->ASTNode)) {
1252 if (Cursor == Cur::None || Cursor == Cur::Break ||
1253 Cursor == Cur::Continue) {
1254 Root = LoopBody;
1255 // Highlight the loop keyword itself.
1256 // FIXME: for do-while, this only covers the `do`..
1257 Result.push_back(P->ASTNode.getSourceRange().getBegin());
1258 break;
1259 }
1260 }
1261 // For switches, users think of case statements as control flow blocks.
1262 // We highlight only occurrences surrounded by the same case.
1263 // We don't detect fallthrough (other than 'case X, case Y').
1264 if (const auto *SS = P->ASTNode.get<SwitchStmt>()) {
1265 if (Cursor == Cur::Break || Cursor == Cur::Case) {
1266 Result.push_back(SS->getSwitchLoc()); // Highlight the switch.
1267 Root = SS->getBody();
1268 // Limit to enclosing case, if there is one.
1269 Bounds = findCaseBounds(*SS, N.ASTNode.getSourceRange().getBegin(), SM);
1270 break;
1271 }
1272 }
1273 // If we didn't start at some interesting node, we're done.
1274 if (Cursor == Cur::None)
1275 break;
1276 }
1277 if (Root) {
1278 if (!Bounds.isValid())
1279 Bounds = Root->getSourceRange();
1280 FindControlFlow(Bounds, Result, SM).TraverseStmt(const_cast<Stmt *>(Root));
1281 }
1282 return Result;
1283}
1284
1285DocumentHighlight toHighlight(const ReferenceFinder::Reference &Ref,
1286 const SourceManager &SM) {
1288 DH.range = Ref.range(SM);
1289 if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Write))
1291 else if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Read))
1293 else
1295 return DH;
1296}
1297
1298std::optional<DocumentHighlight> toHighlight(SourceLocation Loc,
1299 const syntax::TokenBuffer &TB) {
1300 Loc = TB.sourceManager().getFileLoc(Loc);
1301 if (const auto *Tok = TB.spelledTokenContaining(Loc)) {
1302 DocumentHighlight Result;
1303 Result.range = halfOpenToRange(
1304 TB.sourceManager(),
1305 CharSourceRange::getCharRange(Tok->location(), Tok->endLocation()));
1306 return Result;
1307 }
1308 return std::nullopt;
1309}
1310
1311} // namespace
1312
1313std::vector<DocumentHighlight> findDocumentHighlights(ParsedAST &AST,
1314 Position Pos) {
1315 const SourceManager &SM = AST.getSourceManager();
1316 // FIXME: show references to macro within file?
1317 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1318 if (!CurLoc) {
1319 llvm::consumeError(CurLoc.takeError());
1320 return {};
1321 }
1322 std::vector<DocumentHighlight> Result;
1323 auto TryTree = [&](SelectionTree ST) {
1324 if (const SelectionTree::Node *N = ST.commonAncestor()) {
1325 DeclRelationSet Relations =
1327 auto TargetDecls =
1328 targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
1329 if (!TargetDecls.empty()) {
1330 // FIXME: we may get multiple DocumentHighlights with the same location
1331 // and different kinds, deduplicate them.
1332 for (const auto &Ref : findRefs(TargetDecls, AST, /*PerToken=*/true))
1333 Result.push_back(toHighlight(Ref, SM));
1334 return true;
1335 }
1336 auto ControlFlow = relatedControlFlow(*N);
1337 if (!ControlFlow.empty()) {
1338 for (SourceLocation Loc : ControlFlow)
1339 if (auto Highlight = toHighlight(Loc, AST.getTokens()))
1340 Result.push_back(std::move(*Highlight));
1341 return true;
1342 }
1343 }
1344 return false;
1345 };
1346
1347 unsigned Offset =
1348 AST.getSourceManager().getDecomposedSpellingLoc(*CurLoc).second;
1349 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset,
1350 Offset, TryTree);
1351 return Result;
1352}
1353
1354std::vector<LocatedSymbol> findImplementations(ParsedAST &AST, Position Pos,
1355 const SymbolIndex *Index) {
1356 // We rely on index to find the implementations in subclasses.
1357 // FIXME: Index can be stale, so we may loose some latest results from the
1358 // main file.
1359 if (!Index)
1360 return {};
1361 const SourceManager &SM = AST.getSourceManager();
1362 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1363 if (!CurLoc) {
1364 elog("Failed to convert position to source location: {0}",
1365 CurLoc.takeError());
1366 return {};
1367 }
1368 DeclRelationSet Relations =
1370 llvm::DenseSet<SymbolID> IDs;
1372 for (const NamedDecl *ND : getDeclAtPosition(AST, *CurLoc, Relations)) {
1373 if (const auto *CXXMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
1374 if (CXXMD->isVirtual()) {
1375 IDs.insert(getSymbolID(ND));
1376 QueryKind = RelationKind::OverriddenBy;
1377 }
1378 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1379 IDs.insert(getSymbolID(RD));
1380 QueryKind = RelationKind::BaseOf;
1381 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(ND)) {
1382 IDs.insert(getSymbolID(OMD));
1383 QueryKind = RelationKind::OverriddenBy;
1384 } else if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1385 IDs.insert(getSymbolID(ID));
1386 QueryKind = RelationKind::BaseOf;
1387 }
1388 }
1389 return findImplementors(std::move(IDs), QueryKind, Index, AST.tuPath());
1390}
1391
1392namespace {
1393// Recursively finds all the overridden methods of `CMD` in complete type
1394// hierarchy.
1395void getOverriddenMethods(const CXXMethodDecl *CMD,
1396 llvm::DenseSet<SymbolID> &OverriddenMethods) {
1397 if (!CMD)
1398 return;
1399 for (const CXXMethodDecl *Base : CMD->overridden_methods()) {
1400 if (auto ID = getSymbolID(Base))
1401 OverriddenMethods.insert(ID);
1402 getOverriddenMethods(Base, OverriddenMethods);
1403 }
1404}
1405
1406// Recursively finds all the overridden methods of `OMD` in complete type
1407// hierarchy.
1408void getOverriddenMethods(const ObjCMethodDecl *OMD,
1409 llvm::DenseSet<SymbolID> &OverriddenMethods) {
1410 if (!OMD)
1411 return;
1412 llvm::SmallVector<const ObjCMethodDecl *, 4> Overrides;
1413 OMD->getOverriddenMethods(Overrides);
1414 for (const ObjCMethodDecl *Base : Overrides) {
1415 if (auto ID = getSymbolID(Base))
1416 OverriddenMethods.insert(ID);
1417 getOverriddenMethods(Base, OverriddenMethods);
1418 }
1419}
1420
1421std::optional<std::string>
1422stringifyContainerForMainFileRef(const Decl *Container) {
1423 // FIXME We might also want to display the signature here
1424 // When doing so, remember to also add the Signature to index results!
1425 if (auto *ND = llvm::dyn_cast_if_present<NamedDecl>(Container))
1426 return printQualifiedName(*ND);
1427 return {};
1428}
1429
1430std::optional<ReferencesResult>
1431maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
1432 URIForFile URIMainFile) {
1433 const auto &Includes = AST.getIncludeStructure().MainFileIncludes;
1434 auto IncludeOnLine = llvm::find_if(Includes, [&Pos](const Inclusion &Inc) {
1435 return Inc.HashLine == Pos.line;
1436 });
1437 if (IncludeOnLine == Includes.end())
1438 return std::nullopt;
1439
1440 const SourceManager &SM = AST.getSourceManager();
1441 ReferencesResult Results;
1442 auto Converted = convertIncludes(AST);
1443 include_cleaner::walkUsed(
1444 AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
1445 &AST.getPragmaIncludes(), AST.getPreprocessor(),
1446 [&](const include_cleaner::SymbolReference &Ref,
1447 llvm::ArrayRef<include_cleaner::Header> Providers) {
1448 if (Ref.RT != include_cleaner::RefType::Explicit ||
1449 !isPreferredProvider(*IncludeOnLine, Converted, Providers))
1450 return;
1451
1452 auto Loc = SM.getFileLoc(Ref.RefLocation);
1453 // File locations can be outside of the main file if macro is
1454 // expanded through an #include.
1455 while (SM.getFileID(Loc) != SM.getMainFileID())
1456 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
1457
1458 ReferencesResult::Reference Result;
1459 const auto *Token = AST.getTokens().spelledTokenContaining(Loc);
1460 assert(Token && "references expected token here");
1461 Result.Loc.range = Range{sourceLocToPosition(SM, Token->location()),
1462 sourceLocToPosition(SM, Token->endLocation())};
1463 Result.Loc.uri = URIMainFile;
1464 Results.References.push_back(std::move(Result));
1465 });
1466 if (Results.References.empty())
1467 return std::nullopt;
1468
1469 // Add the #include line to the references list.
1471 Result.Loc.range = rangeTillEOL(SM.getBufferData(SM.getMainFileID()),
1472 IncludeOnLine->HashOffset);
1473 Result.Loc.uri = URIMainFile;
1474 Results.References.push_back(std::move(Result));
1475 return Results;
1476}
1477} // namespace
1478
1480 const SymbolIndex *Index, bool AddContext) {
1481 ReferencesResult Results;
1482 const SourceManager &SM = AST.getSourceManager();
1483 auto MainFilePath = AST.tuPath();
1484 auto URIMainFile = URIForFile::canonicalize(MainFilePath, MainFilePath);
1485 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1486 if (!CurLoc) {
1487 llvm::consumeError(CurLoc.takeError());
1488 return {};
1489 }
1490
1491 const auto IncludeReferences =
1492 maybeFindIncludeReferences(AST, Pos, URIMainFile);
1493 if (IncludeReferences)
1494 return *IncludeReferences;
1495
1496 llvm::DenseSet<SymbolID> IDsToQuery, OverriddenMethods;
1497
1498 const auto *IdentifierAtCursor =
1499 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
1500 std::optional<DefinedMacro> Macro;
1501 if (IdentifierAtCursor)
1502 Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
1503 if (Macro) {
1504 // Handle references to macro.
1505 if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {
1506 // Collect macro references from main file.
1507 const auto &IDToRefs = AST.getMacros().MacroRefs;
1508 auto Refs = IDToRefs.find(MacroSID);
1509 if (Refs != IDToRefs.end()) {
1510 for (const auto &Ref : Refs->second) {
1512 Result.Loc.range = Ref.toRange(SM);
1513 Result.Loc.uri = URIMainFile;
1514 if (Ref.IsDefinition) {
1517 }
1518 Results.References.push_back(std::move(Result));
1519 }
1520 }
1521 IDsToQuery.insert(MacroSID);
1522 }
1523 } else {
1524 // Handle references to Decls.
1525
1526 DeclRelationSet Relations =
1528 std::vector<const NamedDecl *> Decls =
1529 getDeclAtPosition(AST, *CurLoc, Relations);
1530 llvm::SmallVector<const NamedDecl *> TargetsInMainFile;
1531 for (const NamedDecl *D : Decls) {
1532 auto ID = getSymbolID(D);
1533 if (!ID)
1534 continue;
1535 TargetsInMainFile.push_back(D);
1536 // Not all symbols can be referenced from outside (e.g. function-locals).
1537 // TODO: we could skip TU-scoped symbols here (e.g. static functions) if
1538 // we know this file isn't a header. The details might be tricky.
1539 if (D->getParentFunctionOrMethod())
1540 continue;
1541 IDsToQuery.insert(ID);
1542 }
1543
1545 if (Index) {
1547 for (const NamedDecl *ND : Decls) {
1548 // Special case: For virtual methods, report decl/def of overrides and
1549 // references to all overridden methods in complete type hierarchy.
1550 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
1551 if (CMD->isVirtual()) {
1552 if (auto ID = getSymbolID(CMD))
1553 OverriddenBy.Subjects.insert(ID);
1554 getOverriddenMethods(CMD, OverriddenMethods);
1555 }
1556 }
1557 // Special case: Objective-C methods can override a parent class or
1558 // protocol, we should be sure to report references to those.
1559 if (const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(ND)) {
1560 OverriddenBy.Subjects.insert(getSymbolID(OMD));
1561 getOverriddenMethods(OMD, OverriddenMethods);
1562 }
1563 }
1564 }
1565
1566 // We traverse the AST to find references in the main file.
1567 auto MainFileRefs = findRefs(TargetsInMainFile, AST, /*PerToken=*/false);
1568 // We may get multiple refs with the same location and different Roles, as
1569 // cross-reference is only interested in locations, we deduplicate them
1570 // by the location to avoid emitting duplicated locations.
1571 MainFileRefs.erase(llvm::unique(MainFileRefs,
1572 [](const ReferenceFinder::Reference &L,
1573 const ReferenceFinder::Reference &R) {
1574 return L.SpelledTok.location() ==
1575 R.SpelledTok.location();
1576 }),
1577 MainFileRefs.end());
1578 for (const auto &Ref : MainFileRefs) {
1580 Result.Loc.range = Ref.range(SM);
1581 Result.Loc.uri = URIMainFile;
1582 if (AddContext)
1583 Result.Loc.containerName =
1584 stringifyContainerForMainFileRef(Ref.Container);
1585 if (Ref.Role & static_cast<unsigned>(index::SymbolRole::Declaration))
1587 // clang-index doesn't report definitions as declarations, but they are.
1588 if (Ref.Role & static_cast<unsigned>(index::SymbolRole::Definition))
1589 Result.Attributes |=
1591 Results.References.push_back(std::move(Result));
1592 }
1593 // Add decl/def of overridding methods.
1594 if (Index && !OverriddenBy.Subjects.empty()) {
1595 LookupRequest ContainerLookup;
1596 // Different overrides will always be contained in different classes, so
1597 // we have a one-to-one mapping between SymbolID and index here, thus we
1598 // don't need to use std::vector as the map's value type.
1599 llvm::DenseMap<SymbolID, size_t> RefIndexForContainer;
1600 Index->relations(OverriddenBy, [&](const SymbolID &Subject,
1601 const Symbol &Object) {
1602 if (Limit && Results.References.size() >= Limit) {
1603 Results.HasMore = true;
1604 return;
1605 }
1606 const auto LSPLocDecl =
1607 toLSPLocation(Object.CanonicalDeclaration, MainFilePath);
1608 const auto LSPLocDef = toLSPLocation(Object.Definition, MainFilePath);
1609 if (LSPLocDecl && LSPLocDecl != LSPLocDef) {
1611 Result.Loc = {std::move(*LSPLocDecl), std::nullopt};
1612 Result.Attributes =
1614 RefIndexForContainer.insert({Object.ID, Results.References.size()});
1615 ContainerLookup.IDs.insert(Object.ID);
1616 Results.References.push_back(std::move(Result));
1617 }
1618 if (LSPLocDef) {
1620 Result.Loc = {std::move(*LSPLocDef), std::nullopt};
1624 RefIndexForContainer.insert({Object.ID, Results.References.size()});
1625 ContainerLookup.IDs.insert(Object.ID);
1626 Results.References.push_back(std::move(Result));
1627 }
1628 });
1629
1630 if (!ContainerLookup.IDs.empty() && AddContext)
1631 Index->lookup(ContainerLookup, [&](const Symbol &Container) {
1632 auto Ref = RefIndexForContainer.find(Container.ID);
1633 assert(Ref != RefIndexForContainer.end());
1634 Results.References[Ref->getSecond()].Loc.containerName =
1635 Container.Scope.str() + Container.Name.str();
1636 });
1637 }
1638 }
1639 // Now query the index for references from other files.
1640 auto QueryIndex = [&](llvm::DenseSet<SymbolID> IDs, bool AllowAttributes,
1641 bool AllowMainFileSymbols) {
1642 if (IDs.empty() || !Index || Results.HasMore)
1643 return;
1644 RefsRequest Req;
1645 Req.IDs = std::move(IDs);
1646 if (Limit) {
1647 if (Limit < Results.References.size()) {
1648 // We've already filled our quota, still check the index to correctly
1649 // return the `HasMore` info.
1650 Req.Limit = 0;
1651 } else {
1652 // Query index only for the remaining size.
1653 Req.Limit = Limit - Results.References.size();
1654 }
1655 }
1656 LookupRequest ContainerLookup;
1657 llvm::DenseMap<SymbolID, std::vector<size_t>> RefIndicesForContainer;
1658 Results.HasMore |= Index->refs(Req, [&](const Ref &R) {
1659 auto LSPLoc = toLSPLocation(R.Location, MainFilePath);
1660 // Avoid indexed results for the main file - the AST is authoritative.
1661 if (!LSPLoc ||
1662 (!AllowMainFileSymbols && LSPLoc->uri.file() == MainFilePath))
1663 return;
1665 Result.Loc = {std::move(*LSPLoc), std::nullopt};
1666 if (AllowAttributes) {
1669 // FIXME: our index should definitely store def | decl separately!
1671 Result.Attributes |=
1673 }
1674 if (AddContext) {
1675 SymbolID Container = R.Container;
1676 ContainerLookup.IDs.insert(Container);
1677 RefIndicesForContainer[Container].push_back(Results.References.size());
1678 }
1679 Results.References.push_back(std::move(Result));
1680 });
1681
1682 if (!ContainerLookup.IDs.empty() && AddContext)
1683 Index->lookup(ContainerLookup, [&](const Symbol &Container) {
1684 auto Ref = RefIndicesForContainer.find(Container.ID);
1685 assert(Ref != RefIndicesForContainer.end());
1686 auto ContainerName = Container.Scope.str() + Container.Name.str();
1687 for (auto I : Ref->getSecond()) {
1688 Results.References[I].Loc.containerName = ContainerName;
1689 }
1690 });
1691 };
1692 QueryIndex(std::move(IDsToQuery), /*AllowAttributes=*/true,
1693 /*AllowMainFileSymbols=*/false);
1694 // For a virtual method: Occurrences of BaseMethod should be treated as refs
1695 // and not as decl/def. Allow symbols from main file since AST does not report
1696 // these.
1697 QueryIndex(std::move(OverriddenMethods), /*AllowAttributes=*/false,
1698 /*AllowMainFileSymbols=*/true);
1699 return Results;
1700}
1701
1702std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) {
1703 const SourceManager &SM = AST.getSourceManager();
1704 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1705 if (!CurLoc) {
1706 llvm::consumeError(CurLoc.takeError());
1707 return {};
1708 }
1709 auto MainFilePath = AST.tuPath();
1710 std::vector<SymbolDetails> Results;
1711
1712 // We also want the targets of using-decls, so we include
1713 // DeclRelation::Underlying.
1716 for (const NamedDecl *D : getDeclAtPosition(AST, *CurLoc, Relations)) {
1717 D = getPreferredDecl(D);
1718
1719 SymbolDetails NewSymbol;
1720 std::string QName = printQualifiedName(*D);
1721 auto SplitQName = splitQualifiedName(QName);
1722 NewSymbol.containerName = std::string(SplitQName.first);
1723 NewSymbol.name = std::string(SplitQName.second);
1724
1725 if (NewSymbol.containerName.empty()) {
1726 if (const auto *ParentND =
1727 dyn_cast_or_null<NamedDecl>(D->getDeclContext()))
1728 NewSymbol.containerName = printQualifiedName(*ParentND);
1729 }
1730 llvm::SmallString<32> USR;
1731 if (!index::generateUSRForDecl(D, USR)) {
1732 NewSymbol.USR = std::string(USR);
1733 NewSymbol.ID = SymbolID(NewSymbol.USR);
1734 }
1735 if (const NamedDecl *Def = getDefinition(D))
1736 NewSymbol.definitionRange = makeLocation(
1737 AST.getASTContext(), nameLocation(*Def, SM), MainFilePath);
1738 NewSymbol.declarationRange =
1739 makeLocation(AST.getASTContext(), nameLocation(*D, SM), MainFilePath);
1740
1741 Results.push_back(std::move(NewSymbol));
1742 }
1743
1744 const auto *IdentifierAtCursor =
1745 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
1746 if (!IdentifierAtCursor)
1747 return Results;
1748
1749 if (auto M = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor())) {
1750 SymbolDetails NewMacro;
1751 NewMacro.name = std::string(M->Name);
1752 llvm::SmallString<32> USR;
1753 if (!index::generateUSRForMacro(NewMacro.name, M->Info->getDefinitionLoc(),
1754 SM, USR)) {
1755 NewMacro.USR = std::string(USR);
1756 NewMacro.ID = SymbolID(NewMacro.USR);
1757 }
1758 Results.push_back(std::move(NewMacro));
1759 }
1760
1761 return Results;
1762}
1763
1764llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const LocatedSymbol &S) {
1765 OS << S.Name << ": " << S.PreferredDeclaration;
1766 if (S.Definition)
1767 OS << " def=" << *S.Definition;
1768 return OS;
1769}
1770
1771llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1772 const ReferencesResult::Reference &R) {
1773 OS << R.Loc;
1775 OS << " [decl]";
1777 OS << " [def]";
1779 OS << " [override]";
1780 return OS;
1781}
1782
1783template <typename HierarchyItem>
1784static std::optional<HierarchyItem>
1785declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1786 ASTContext &Ctx = ND.getASTContext();
1787 auto &SM = Ctx.getSourceManager();
1788 SourceLocation NameLoc = nameLocation(ND, Ctx.getSourceManager());
1789 SourceLocation BeginLoc = SM.getFileLoc(ND.getBeginLoc());
1790 SourceLocation EndLoc = SM.getFileLoc(ND.getEndLoc());
1791 const auto DeclRange =
1792 toHalfOpenFileRange(SM, Ctx.getLangOpts(), {BeginLoc, EndLoc});
1793 if (!DeclRange)
1794 return std::nullopt;
1795 const auto FE = SM.getFileEntryRefForID(SM.getFileID(NameLoc));
1796 if (!FE)
1797 return std::nullopt;
1798 auto FilePath = getCanonicalPath(*FE, SM.getFileManager());
1799 if (!FilePath)
1800 return std::nullopt; // Not useful without a uri.
1801
1802 Position NameBegin = sourceLocToPosition(SM, NameLoc);
1803 Position NameEnd = sourceLocToPosition(
1804 SM, Lexer::getLocForEndOfToken(NameLoc, 0, SM, Ctx.getLangOpts()));
1805
1806 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
1807 // FIXME: This is not classifying constructors, destructors and operators
1808 // correctly.
1809 SymbolKind SK = indexSymbolKindToSymbolKind(SymInfo.Kind);
1810
1811 HierarchyItem HI;
1812 HI.name = printName(Ctx, ND);
1813 // FIXME: Populate HI.detail the way we do in symbolToHierarchyItem?
1814 HI.kind = SK;
1815 HI.range = Range{sourceLocToPosition(SM, DeclRange->getBegin()),
1816 sourceLocToPosition(SM, DeclRange->getEnd())};
1817 HI.selectionRange = Range{NameBegin, NameEnd};
1818 if (!HI.range.contains(HI.selectionRange)) {
1819 // 'selectionRange' must be contained in 'range', so in cases where clang
1820 // reports unrelated ranges we need to reconcile somehow.
1821 HI.range = HI.selectionRange;
1822 }
1823
1824 HI.uri = URIForFile::canonicalize(*FilePath, TUPath);
1825
1826 return HI;
1827}
1828
1829static std::optional<TypeHierarchyItem>
1830declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1831 auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
1832 if (Result) {
1833 Result->deprecated = ND.isDeprecated();
1834 // Compute the SymbolID and store it in the 'data' field.
1835 // This allows typeHierarchy/resolve to be used to
1836 // resolve children of items returned in a previous request
1837 // for parents.
1838 Result->data.symbolID = getSymbolID(&ND);
1839 }
1840 return Result;
1841}
1842
1843static std::optional<CallHierarchyItem>
1844declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1845 auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
1846 if (!Result)
1847 return Result;
1848 if (ND.isDeprecated())
1849 Result->tags.push_back(SymbolTag::Deprecated);
1850 if (auto ID = getSymbolID(&ND))
1851 Result->data = ID.str();
1852 return Result;
1853}
1854
1855template <typename HierarchyItem>
1856static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
1857 PathRef TUPath) {
1858 auto Loc = symbolToLocation(S, TUPath);
1859 if (!Loc) {
1860 elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError());
1861 return std::nullopt;
1862 }
1863 HierarchyItem HI;
1864 HI.name = std::string(S.Name);
1865 HI.detail = (S.Scope + S.Name).str();
1866 HI.kind = indexSymbolKindToSymbolKind(S.SymInfo.Kind);
1867 HI.selectionRange = Loc->range;
1868 // FIXME: Populate 'range' correctly
1869 // (https://github.com/clangd/clangd/issues/59).
1870 HI.range = HI.selectionRange;
1871 HI.uri = Loc->uri;
1872
1873 return HI;
1874}
1875
1876static std::optional<TypeHierarchyItem>
1878 auto Result = symbolToHierarchyItem<TypeHierarchyItem>(S, TUPath);
1879 if (Result) {
1880 Result->deprecated = (S.Flags & Symbol::Deprecated);
1881 Result->data.symbolID = S.ID;
1882 }
1883 return Result;
1884}
1885
1886static std::optional<CallHierarchyItem>
1888 auto Result = symbolToHierarchyItem<CallHierarchyItem>(S, TUPath);
1889 if (!Result)
1890 return Result;
1891 Result->data = S.ID.str();
1892 if (S.Flags & Symbol::Deprecated)
1893 Result->tags.push_back(SymbolTag::Deprecated);
1894 return Result;
1895}
1896
1897static void fillSubTypes(const SymbolID &ID,
1898 std::vector<TypeHierarchyItem> &SubTypes,
1899 const SymbolIndex *Index, int Levels, PathRef TUPath) {
1900 RelationsRequest Req;
1901 Req.Subjects.insert(ID);
1903 Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
1904 if (std::optional<TypeHierarchyItem> ChildSym =
1906 if (Levels > 1) {
1907 ChildSym->children.emplace();
1908 fillSubTypes(Object.ID, *ChildSym->children, Index, Levels - 1, TUPath);
1909 }
1910 SubTypes.emplace_back(std::move(*ChildSym));
1911 }
1912 });
1913}
1914
1915using RecursionProtectionSet = llvm::SmallPtrSet<const CXXRecordDecl *, 4>;
1916
1917// Extracts parents from AST and populates the type hierarchy item.
1918static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath,
1919 TypeHierarchyItem &Item,
1920 RecursionProtectionSet &RPSet) {
1921 Item.parents.emplace();
1922 Item.data.parents.emplace();
1923 // typeParents() will replace dependent template specializations
1924 // with their class template, so to avoid infinite recursion for
1925 // certain types of hierarchies, keep the templates encountered
1926 // along the parent chain in a set, and stop the recursion if one
1927 // starts to repeat.
1928 auto *Pattern = CXXRD.getDescribedTemplate() ? &CXXRD : nullptr;
1929 if (Pattern) {
1930 if (!RPSet.insert(Pattern).second) {
1931 return;
1932 }
1933 }
1934
1935 for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
1936 if (std::optional<TypeHierarchyItem> ParentSym =
1937 declToTypeHierarchyItem(*ParentDecl, TUPath)) {
1938 fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
1939 Item.data.parents->emplace_back(ParentSym->data);
1940 Item.parents->emplace_back(std::move(*ParentSym));
1941 }
1942 }
1943
1944 if (Pattern) {
1945 RPSet.erase(Pattern);
1946 }
1947}
1948
1949std::vector<const CXXRecordDecl *> findRecordTypeAt(ParsedAST &AST,
1950 Position Pos) {
1951 auto RecordFromNode = [&AST](const SelectionTree::Node *N) {
1952 std::vector<const CXXRecordDecl *> Records;
1953 if (!N)
1954 return Records;
1955
1956 // Note: explicitReferenceTargets() will search for both template
1957 // instantiations and template patterns, and prefer the former if available
1958 // (generally, one will be available for non-dependent specializations of a
1959 // class template).
1960 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Underlying,
1961 AST.getHeuristicResolver());
1962 for (const NamedDecl *D : Decls) {
1963
1964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1965 // If this is a variable, use the type of the variable.
1966 if (const auto *RD = VD->getType().getTypePtr()->getAsCXXRecordDecl())
1967 Records.push_back(RD);
1968 continue;
1969 }
1970
1971 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1972 // If this is a method, use the type of the class.
1973 Records.push_back(Method->getParent());
1974 continue;
1975 }
1976
1977 // We don't handle FieldDecl because it's not clear what behaviour
1978 // the user would expect: the enclosing class type (as with a
1979 // method), or the field's type (as with a variable).
1980
1981 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1982 Records.push_back(RD);
1983 }
1984 return Records;
1985 };
1986
1987 const SourceManager &SM = AST.getSourceManager();
1988 std::vector<const CXXRecordDecl *> Result;
1989 auto Offset = positionToOffset(SM.getBufferData(SM.getMainFileID()), Pos);
1990 if (!Offset) {
1991 llvm::consumeError(Offset.takeError());
1992 return Result;
1993 }
1994 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), *Offset,
1995 *Offset, [&](SelectionTree ST) {
1996 Result = RecordFromNode(ST.commonAncestor());
1997 return !Result.empty();
1998 });
1999 return Result;
2000}
2001
2002// Return the type most associated with an AST node.
2003// This isn't precisely defined: we want "go to type" to do something useful.
2004static QualType typeForNode(const ASTContext &Ctx, const HeuristicResolver *H,
2005 const SelectionTree::Node *N) {
2006 // If we're looking at a namespace qualifier, walk up to what it's qualifying.
2007 // (If we're pointing at a *class* inside a NNS, N will be a TypeLoc).
2008 while (N && N->ASTNode.get<NestedNameSpecifierLoc>())
2009 N = N->Parent;
2010 if (!N)
2011 return QualType();
2012
2013 // If we're pointing at a type => return it.
2014 if (const TypeLoc *TL = N->ASTNode.get<TypeLoc>()) {
2015 if (llvm::isa<DeducedType>(TL->getTypePtr()))
2016 if (auto Deduced = getDeducedType(
2017 N->getDeclContext().getParentASTContext(), H, TL->getBeginLoc()))
2018 return *Deduced;
2019 // Exception: an alias => underlying type.
2020 if (llvm::isa<TypedefType>(TL->getTypePtr()))
2021 return TL->getTypePtr()->getLocallyUnqualifiedSingleStepDesugaredType();
2022 return TL->getType();
2023 }
2024
2025 // Constructor initializers => the type of thing being initialized.
2026 if (const auto *CCI = N->ASTNode.get<CXXCtorInitializer>()) {
2027 if (const FieldDecl *FD = CCI->getAnyMember())
2028 return FD->getType();
2029 if (const Type *Base = CCI->getBaseClass())
2030 return QualType(Base, 0);
2031 }
2032
2033 // Base specifier => the base type.
2034 if (const auto *CBS = N->ASTNode.get<CXXBaseSpecifier>())
2035 return CBS->getType();
2036
2037 if (const Decl *D = N->ASTNode.get<Decl>()) {
2038 struct Visitor : ConstDeclVisitor<Visitor, QualType> {
2039 const ASTContext &Ctx;
2040 Visitor(const ASTContext &Ctx) : Ctx(Ctx) {}
2041
2042 QualType VisitValueDecl(const ValueDecl *D) { return D->getType(); }
2043 // Declaration of a type => that type.
2044 QualType VisitTypeDecl(const TypeDecl *D) {
2045 return Ctx.getTypeDeclType(D);
2046 }
2047 // Exception: alias declaration => the underlying type, not the alias.
2048 QualType VisitTypedefNameDecl(const TypedefNameDecl *D) {
2049 return D->getUnderlyingType();
2050 }
2051 // Look inside templates.
2052 QualType VisitTemplateDecl(const TemplateDecl *D) {
2053 return Visit(D->getTemplatedDecl());
2054 }
2055 } V(Ctx);
2056 return V.Visit(D);
2057 }
2058
2059 if (const Stmt *S = N->ASTNode.get<Stmt>()) {
2060 struct Visitor : ConstStmtVisitor<Visitor, QualType> {
2061 // Null-safe version of visit simplifies recursive calls below.
2062 QualType type(const Stmt *S) { return S ? Visit(S) : QualType(); }
2063
2064 // In general, expressions => type of expression.
2065 QualType VisitExpr(const Expr *S) {
2066 return S->IgnoreImplicitAsWritten()->getType();
2067 }
2068 QualType VisitMemberExpr(const MemberExpr *S) {
2069 // The `foo` in `s.foo()` pretends not to have a real type!
2070 if (S->getType()->isSpecificBuiltinType(BuiltinType::BoundMember))
2071 return Expr::findBoundMemberType(S);
2072 return VisitExpr(S);
2073 }
2074 // Exceptions for void expressions that operate on a type in some way.
2075 QualType VisitCXXDeleteExpr(const CXXDeleteExpr *S) {
2076 return S->getDestroyedType();
2077 }
2078 QualType VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *S) {
2079 return S->getDestroyedType();
2080 }
2081 QualType VisitCXXThrowExpr(const CXXThrowExpr *S) {
2082 return S->getSubExpr()->getType();
2083 }
2084 QualType VisitCoyieldExpr(const CoyieldExpr *S) {
2085 return type(S->getOperand());
2086 }
2087 // Treat a designated initializer like a reference to the field.
2088 QualType VisitDesignatedInitExpr(const DesignatedInitExpr *S) {
2089 // In .foo.bar we want to jump to bar's type, so find *last* field.
2090 for (auto &D : llvm::reverse(S->designators()))
2091 if (D.isFieldDesignator())
2092 if (const auto *FD = D.getFieldDecl())
2093 return FD->getType();
2094 return QualType();
2095 }
2096
2097 // Control flow statements that operate on data: use the data type.
2098 QualType VisitSwitchStmt(const SwitchStmt *S) {
2099 return type(S->getCond());
2100 }
2101 QualType VisitWhileStmt(const WhileStmt *S) { return type(S->getCond()); }
2102 QualType VisitDoStmt(const DoStmt *S) { return type(S->getCond()); }
2103 QualType VisitIfStmt(const IfStmt *S) { return type(S->getCond()); }
2104 QualType VisitCaseStmt(const CaseStmt *S) { return type(S->getLHS()); }
2105 QualType VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2106 return S->getLoopVariable()->getType();
2107 }
2108 QualType VisitReturnStmt(const ReturnStmt *S) {
2109 return type(S->getRetValue());
2110 }
2111 QualType VisitCoreturnStmt(const CoreturnStmt *S) {
2112 return type(S->getOperand());
2113 }
2114 QualType VisitCXXCatchStmt(const CXXCatchStmt *S) {
2115 return S->getCaughtType();
2116 }
2117 QualType VisitObjCAtThrowStmt(const ObjCAtThrowStmt *S) {
2118 return type(S->getThrowExpr());
2119 }
2120 QualType VisitObjCAtCatchStmt(const ObjCAtCatchStmt *S) {
2121 return S->getCatchParamDecl() ? S->getCatchParamDecl()->getType()
2122 : QualType();
2123 }
2124 } V;
2125 return V.Visit(S);
2126 }
2127
2128 return QualType();
2129}
2130
2131// Given a type targeted by the cursor, return one or more types that are more interesting
2132// to target.
2133static void unwrapFindType(
2134 QualType T, const HeuristicResolver* H, llvm::SmallVector<QualType>& Out) {
2135 if (T.isNull())
2136 return;
2137
2138 // If there's a specific type alias, point at that rather than unwrapping.
2139 if (const auto* TDT = T->getAs<TypedefType>())
2140 return Out.push_back(QualType(TDT, 0));
2141
2142 // Pointers etc => pointee type.
2143 if (const auto *PT = T->getAs<PointerType>())
2144 return unwrapFindType(PT->getPointeeType(), H, Out);
2145 if (const auto *RT = T->getAs<ReferenceType>())
2146 return unwrapFindType(RT->getPointeeType(), H, Out);
2147 if (const auto *AT = T->getAsArrayTypeUnsafe())
2148 return unwrapFindType(AT->getElementType(), H, Out);
2149
2150 // Function type => return type.
2151 if (auto *FT = T->getAs<FunctionType>())
2152 return unwrapFindType(FT->getReturnType(), H, Out);
2153 if (auto *CRD = T->getAsCXXRecordDecl()) {
2154 if (CRD->isLambda())
2155 return unwrapFindType(CRD->getLambdaCallOperator()->getReturnType(), H,
2156 Out);
2157 // FIXME: more cases we'd prefer the return type of the call operator?
2158 // std::function etc?
2159 }
2160
2161 // For smart pointer types, add the underlying type
2162 if (H)
2163 if (auto PointeeType = H->getPointeeType(T.getNonReferenceType());
2164 !PointeeType.isNull()) {
2165 unwrapFindType(PointeeType, H, Out);
2166 return Out.push_back(T);
2167 }
2168
2169 return Out.push_back(T);
2170}
2171
2172// Convenience overload, to allow calling this without the out-parameter
2173static llvm::SmallVector<QualType> unwrapFindType(
2174 QualType T, const HeuristicResolver* H) {
2175 llvm::SmallVector<QualType> Result;
2176 unwrapFindType(T, H, Result);
2177 return Result;
2178}
2179
2180std::vector<LocatedSymbol> findType(ParsedAST &AST, Position Pos,
2181 const SymbolIndex *Index) {
2182 const SourceManager &SM = AST.getSourceManager();
2183 auto Offset = positionToOffset(SM.getBufferData(SM.getMainFileID()), Pos);
2184 std::vector<LocatedSymbol> Result;
2185 if (!Offset) {
2186 elog("failed to convert position {0} for findTypes: {1}", Pos,
2187 Offset.takeError());
2188 return Result;
2189 }
2190 // The general scheme is: position -> AST node -> type -> declaration.
2191 auto SymbolsFromNode =
2192 [&](const SelectionTree::Node *N) -> std::vector<LocatedSymbol> {
2193 std::vector<LocatedSymbol> LocatedSymbols;
2194
2195 // NOTE: unwrapFindType might return duplicates for something like
2196 // unique_ptr<unique_ptr<T>>. Let's *not* remove them, because it gives you some
2197 // information about the type you may have not known before
2198 // (since unique_ptr<unique_ptr<T>> != unique_ptr<T>).
2199 for (const QualType &Type : unwrapFindType(
2200 typeForNode(AST.getASTContext(), AST.getHeuristicResolver(), N),
2201 AST.getHeuristicResolver()))
2202 llvm::copy(locateSymbolForType(AST, Type, Index),
2203 std::back_inserter(LocatedSymbols));
2204
2205 return LocatedSymbols;
2206 };
2207 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), *Offset,
2208 *Offset, [&](SelectionTree ST) {
2209 Result = SymbolsFromNode(ST.commonAncestor());
2210 return !Result.empty();
2211 });
2212 return Result;
2213}
2214
2215std::vector<const CXXRecordDecl *> typeParents(const CXXRecordDecl *CXXRD) {
2216 std::vector<const CXXRecordDecl *> Result;
2217
2218 // If this is an invalid instantiation, instantiation of the bases
2219 // may not have succeeded, so fall back to the template pattern.
2220 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
2221 if (CTSD->isInvalidDecl())
2222 CXXRD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
2223 }
2224
2225 // Can't query bases without a definition.
2226 if (!CXXRD->hasDefinition())
2227 return Result;
2228
2229 for (auto Base : CXXRD->bases()) {
2230 const CXXRecordDecl *ParentDecl = nullptr;
2231
2232 const Type *Type = Base.getType().getTypePtr();
2233 if (const RecordType *RT = Type->getAs<RecordType>()) {
2234 ParentDecl = RT->getAsCXXRecordDecl();
2235 }
2236
2237 if (!ParentDecl) {
2238 // Handle a dependent base such as "Base<T>" by using the primary
2239 // template.
2240 if (const TemplateSpecializationType *TS =
2241 Type->getAs<TemplateSpecializationType>()) {
2242 TemplateName TN = TS->getTemplateName();
2243 if (TemplateDecl *TD = TN.getAsTemplateDecl()) {
2244 ParentDecl = dyn_cast<CXXRecordDecl>(TD->getTemplatedDecl());
2245 }
2246 }
2247 }
2248
2249 if (ParentDecl)
2250 Result.push_back(ParentDecl);
2251 }
2252
2253 return Result;
2254}
2255
2256std::vector<TypeHierarchyItem>
2257getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels,
2258 TypeHierarchyDirection Direction, const SymbolIndex *Index,
2259 PathRef TUPath) {
2260 std::vector<TypeHierarchyItem> Results;
2261 for (const auto *CXXRD : findRecordTypeAt(AST, Pos)) {
2262
2263 bool WantChildren = Direction == TypeHierarchyDirection::Children ||
2264 Direction == TypeHierarchyDirection::Both;
2265
2266 // If we're looking for children, we're doing the lookup in the index.
2267 // The index does not store relationships between implicit
2268 // specializations, so if we have one, use the template pattern instead.
2269 // Note that this needs to be done before the declToTypeHierarchyItem(),
2270 // otherwise the type hierarchy item would misleadingly contain the
2271 // specialization parameters, while the children would involve classes
2272 // that derive from other specializations of the template.
2273 if (WantChildren) {
2274 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD))
2275 CXXRD = CTSD->getTemplateInstantiationPattern();
2276 }
2277
2278 std::optional<TypeHierarchyItem> Result =
2279 declToTypeHierarchyItem(*CXXRD, AST.tuPath());
2280 if (!Result)
2281 continue;
2282
2284 fillSuperTypes(*CXXRD, AST.tuPath(), *Result, RPSet);
2285
2286 if (WantChildren && ResolveLevels > 0) {
2287 Result->children.emplace();
2288
2289 if (Index) {
2290 if (auto ID = getSymbolID(CXXRD))
2291 fillSubTypes(ID, *Result->children, Index, ResolveLevels, TUPath);
2292 }
2293 }
2294 Results.emplace_back(std::move(*Result));
2295 }
2296
2297 return Results;
2298}
2299
2300std::optional<std::vector<TypeHierarchyItem>>
2301superTypes(const TypeHierarchyItem &Item, const SymbolIndex *Index) {
2302 std::vector<TypeHierarchyItem> Results;
2303 if (!Item.data.parents)
2304 return std::nullopt;
2305 if (Item.data.parents->empty())
2306 return Results;
2307 LookupRequest Req;
2308 llvm::DenseMap<SymbolID, const TypeHierarchyItem::ResolveParams *> IDToData;
2309 for (const auto &Parent : *Item.data.parents) {
2310 Req.IDs.insert(Parent.symbolID);
2311 IDToData[Parent.symbolID] = &Parent;
2312 }
2313 Index->lookup(Req, [&Item, &Results, &IDToData](const Symbol &S) {
2314 if (auto THI = symbolToTypeHierarchyItem(S, Item.uri.file())) {
2315 THI->data = *IDToData.lookup(S.ID);
2316 Results.emplace_back(std::move(*THI));
2317 }
2318 });
2319 return Results;
2320}
2321
2322std::vector<TypeHierarchyItem> subTypes(const TypeHierarchyItem &Item,
2323 const SymbolIndex *Index) {
2324 std::vector<TypeHierarchyItem> Results;
2325 fillSubTypes(Item.data.symbolID, Results, Index, 1, Item.uri.file());
2326 for (auto &ChildSym : Results)
2327 ChildSym.data.parents = {Item.data};
2328 return Results;
2329}
2330
2331void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels,
2332 TypeHierarchyDirection Direction,
2333 const SymbolIndex *Index) {
2334 // We only support typeHierarchy/resolve for children, because for parents
2335 // we ignore ResolveLevels and return all levels of parents eagerly.
2336 if (!Index || Direction == TypeHierarchyDirection::Parents ||
2337 ResolveLevels == 0)
2338 return;
2339
2340 Item.children.emplace();
2341 fillSubTypes(Item.data.symbolID, *Item.children, Index, ResolveLevels,
2342 Item.uri.file());
2343}
2344
2345std::vector<CallHierarchyItem>
2347 std::vector<CallHierarchyItem> Result;
2348 const auto &SM = AST.getSourceManager();
2349 auto Loc = sourceLocationInMainFile(SM, Pos);
2350 if (!Loc) {
2351 elog("prepareCallHierarchy failed to convert position to source location: "
2352 "{0}",
2353 Loc.takeError());
2354 return Result;
2355 }
2356 for (const NamedDecl *Decl : getDeclAtPosition(AST, *Loc, {})) {
2357 if (!(isa<DeclContext>(Decl) &&
2358 cast<DeclContext>(Decl)->isFunctionOrMethod()) &&
2359 Decl->getKind() != Decl::Kind::FunctionTemplate &&
2360 !(Decl->getKind() == Decl::Kind::Var &&
2361 !cast<VarDecl>(Decl)->isLocalVarDecl()) &&
2362 Decl->getKind() != Decl::Kind::Field &&
2363 Decl->getKind() != Decl::Kind::EnumConstant)
2364 continue;
2365 if (auto CHI = declToCallHierarchyItem(*Decl, AST.tuPath()))
2366 Result.emplace_back(std::move(*CHI));
2367 }
2368 return Result;
2369}
2370
2371std::vector<CallHierarchyIncomingCall>
2372incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
2373 std::vector<CallHierarchyIncomingCall> Results;
2374 if (!Index || Item.data.empty())
2375 return Results;
2376 auto ID = SymbolID::fromStr(Item.data);
2377 if (!ID) {
2378 elog("incomingCalls failed to find symbol: {0}", ID.takeError());
2379 return Results;
2380 }
2381 // In this function, we find incoming calls based on the index only.
2382 // In principle, the AST could have more up-to-date information about
2383 // occurrences within the current file. However, going from a SymbolID
2384 // to an AST node isn't cheap, particularly when the declaration isn't
2385 // in the main file.
2386 // FIXME: Consider also using AST information when feasible.
2387 auto QueryIndex = [&](llvm::DenseSet<SymbolID> IDs, bool MightNeverCall) {
2388 RefsRequest Request;
2389 Request.IDs = std::move(IDs);
2390 Request.WantContainer = true;
2391 // We could restrict more specifically to calls by introducing a new
2392 // RefKind, but non-call references (such as address-of-function) can still
2393 // be interesting as they can indicate indirect calls.
2394 Request.Filter = RefKind::Reference;
2395 // Initially store the ranges in a map keyed by SymbolID of the caller.
2396 // This allows us to group different calls with the same caller
2397 // into the same CallHierarchyIncomingCall.
2398 llvm::DenseMap<SymbolID, std::vector<Location>> CallsIn;
2399 // We can populate the ranges based on a refs request only. As we do so, we
2400 // also accumulate the container IDs into a lookup request.
2401 LookupRequest ContainerLookup;
2402 Index->refs(Request, [&](const Ref &R) {
2403 auto Loc = indexToLSPLocation(R.Location, Item.uri.file());
2404 if (!Loc) {
2405 elog("incomingCalls failed to convert location: {0}", Loc.takeError());
2406 return;
2407 }
2408 CallsIn[R.Container].push_back(*Loc);
2409
2410 ContainerLookup.IDs.insert(R.Container);
2411 });
2412 // Perform the lookup request and combine its results with CallsIn to
2413 // get complete CallHierarchyIncomingCall objects.
2414 Index->lookup(ContainerLookup, [&](const Symbol &Caller) {
2415 auto It = CallsIn.find(Caller.ID);
2416 assert(It != CallsIn.end());
2417 if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) {
2418 std::vector<Range> FromRanges;
2419 for (const Location &L : It->second) {
2420 if (L.uri != CHI->uri) {
2421 // Call location not in same file as caller.
2422 // This can happen in some edge cases. There's not much we can do,
2423 // since the protocol only allows returning ranges interpreted as
2424 // being in the caller's file.
2425 continue;
2426 }
2427 FromRanges.push_back(L.range);
2428 }
2429 Results.push_back(CallHierarchyIncomingCall{
2430 std::move(*CHI), std::move(FromRanges), MightNeverCall});
2431 }
2432 });
2433 };
2434 QueryIndex({ID.get()}, false);
2435 // In the case of being a virtual function we also want to return
2436 // potential calls through the base function.
2437 if (Item.kind == SymbolKind::Method) {
2438 llvm::DenseSet<SymbolID> IDs;
2439 RelationsRequest Req{{ID.get()}, RelationKind::OverriddenBy, std::nullopt};
2440 Index->reverseRelations(Req, [&](const SymbolID &, const Symbol &Caller) {
2441 IDs.insert(Caller.ID);
2442 });
2443 QueryIndex(std::move(IDs), true);
2444 }
2445 // Sort results by name of container.
2446 llvm::sort(Results, [](const CallHierarchyIncomingCall &A,
2447 const CallHierarchyIncomingCall &B) {
2448 return A.from.name < B.from.name;
2449 });
2450 return Results;
2451}
2452
2453std::vector<CallHierarchyOutgoingCall>
2454outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
2455 std::vector<CallHierarchyOutgoingCall> Results;
2456 if (!Index || Item.data.empty())
2457 return Results;
2458 auto ID = SymbolID::fromStr(Item.data);
2459 if (!ID) {
2460 elog("outgoingCalls failed to find symbol: {0}", ID.takeError());
2461 return Results;
2462 }
2463 // In this function, we find outgoing calls based on the index only.
2464 ContainedRefsRequest Request;
2465 Request.ID = *ID;
2466 // Initially store the ranges in a map keyed by SymbolID of the callee.
2467 // This allows us to group different calls to the same function
2468 // into the same CallHierarchyOutgoingCall.
2469 llvm::DenseMap<SymbolID, std::vector<Location>> CallsOut;
2470 // We can populate the ranges based on a refs request only. As we do so, we
2471 // also accumulate the callee IDs into a lookup request.
2472 LookupRequest CallsOutLookup;
2473 Index->containedRefs(Request, [&](const auto &R) {
2474 auto Loc = indexToLSPLocation(R.Location, Item.uri.file());
2475 if (!Loc) {
2476 elog("outgoingCalls failed to convert location: {0}", Loc.takeError());
2477 return;
2478 }
2479 auto It = CallsOut.try_emplace(R.Symbol, std::vector<Location>{}).first;
2480 It->second.push_back(*Loc);
2481
2482 CallsOutLookup.IDs.insert(R.Symbol);
2483 });
2484 // Perform the lookup request and combine its results with CallsOut to
2485 // get complete CallHierarchyOutgoingCall objects.
2486 Index->lookup(CallsOutLookup, [&](const Symbol &Callee) {
2487 // The containedRefs request should only return symbols which are
2488 // function-like, i.e. symbols for which references to them can be "calls".
2489 using SK = index::SymbolKind;
2490 auto Kind = Callee.SymInfo.Kind;
2491 assert(Kind == SK::Function || Kind == SK::InstanceMethod ||
2492 Kind == SK::ClassMethod || Kind == SK::StaticMethod ||
2493 Kind == SK::Constructor || Kind == SK::Destructor ||
2494 Kind == SK::ConversionFunction);
2495 (void)Kind;
2496 (void)SK::Function;
2497
2498 auto It = CallsOut.find(Callee.ID);
2499 assert(It != CallsOut.end());
2500 if (auto CHI = symbolToCallHierarchyItem(Callee, Item.uri.file())) {
2501 std::vector<Range> FromRanges;
2502 for (const Location &L : It->second) {
2503 if (L.uri != Item.uri) {
2504 // Call location not in same file as the item that outgoingCalls was
2505 // requested for. This can happen when Item is a declaration separate
2506 // from the implementation. There's not much we can do, since the
2507 // protocol only allows returning ranges interpreted as being in
2508 // Item's file.
2509 continue;
2510 }
2511 FromRanges.push_back(L.range);
2512 }
2513 Results.push_back(
2514 CallHierarchyOutgoingCall{std::move(*CHI), std::move(FromRanges)});
2515 }
2516 });
2517 // Sort results by name of the callee.
2518 llvm::sort(Results, [](const CallHierarchyOutgoingCall &A,
2519 const CallHierarchyOutgoingCall &B) {
2520 return A.to.name < B.to.name;
2521 });
2522 return Results;
2523}
2524
2525llvm::DenseSet<const Decl *> getNonLocalDeclRefs(ParsedAST &AST,
2526 const FunctionDecl *FD) {
2527 if (!FD->hasBody())
2528 return {};
2529 llvm::DenseSet<const Decl *> DeclRefs;
2531 FD,
2532 [&](ReferenceLoc Ref) {
2533 for (const Decl *D : Ref.Targets) {
2534 if (!index::isFunctionLocalSymbol(D) && !D->isTemplateParameter() &&
2535 !Ref.IsDecl)
2536 DeclRefs.insert(D);
2537 }
2538 },
2539 AST.getHeuristicResolver());
2540 return DeclRefs;
2541}
2542
2543} // namespace clangd
2544} // namespace clang
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
#define dlog(...)
Definition Logger.h:101
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
Stores and provides access to parsed AST.
Definition ParsedAST.h:46
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End, llvm::function_ref< bool(SelectionTree)> Func)
static const Decl * getRefContainer(const Decl *Enclosing, const SymbolCollector::Options &Opts)
static llvm::Expected< SymbolID > fromStr(llvm::StringRef)
Definition SymbolID.cpp:37
std::string str() const
Definition SymbolID.cpp:35
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition Index.h:134
virtual bool fuzzyFind(const FuzzyFindRequest &Req, llvm::function_ref< void(const Symbol &)> Callback) const =0
Matches symbols in the index fuzzily and applies Callback on each matched symbol before returning.
virtual bool containedRefs(const ContainedRefsRequest &Req, llvm::function_ref< void(const ContainedRefsResult &)> Callback) const =0
Find all symbols that are referenced by a symbol and apply Callback on each result.
virtual void relations(const RelationsRequest &Req, llvm::function_ref< void(const SymbolID &Subject, const Symbol &Object)> Callback) const =0
Finds all relations (S, P, O) stored in the index such that S is among Req.Subjects and P is Req....
virtual bool refs(const RefsRequest &Req, llvm::function_ref< void(const Ref &)> Callback) const =0
Finds all occurrences (e.g.
virtual void lookup(const LookupRequest &Req, llvm::function_ref< void(const Symbol &)> Callback) const =0
Looks up symbols with any of the given symbol IDs and applies Callback on each matched symbol.
virtual void reverseRelations(const RelationsRequest &Req, llvm::function_ref< void(const SymbolID &Subject, const Symbol &Object)> Callback) const =0
Finds all relations (O, P, S) stored in the index such that S is among Req.Subjects and P is Req....
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
std::vector< TypeHierarchyItem > subTypes(const TypeHierarchyItem &Item, const SymbolIndex *Index)
Returns direct children of a TypeHierarchyItem.
Definition XRefs.cpp:2322
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
std::optional< std::vector< TypeHierarchyItem > > superTypes(const TypeHierarchyItem &Item, const SymbolIndex *Index)
Returns direct parents of a TypeHierarchyItem using SymbolIDs stored inside the item.
Definition XRefs.cpp:2301
llvm::Expected< Location > indexToLSPLocation(const SymbolLocation &Loc, llvm::StringRef TUPath)
Helper function for deriving an LSP Location from an index SymbolLocation.
std::vector< CallHierarchyIncomingCall > incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index)
Definition XRefs.cpp:2372
bool isLikelyForwardingFunction(const FunctionTemplateDecl *FT)
Heuristic that checks if FT is likely to be forwarding a parameter pack to another function (e....
Definition AST.cpp:1042
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:353
static std::optional< TypeHierarchyItem > symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath)
Definition XRefs.cpp:1877
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
static std::optional< CallHierarchyItem > symbolToCallHierarchyItem(const Symbol &S, PathRef TUPath)
Definition XRefs.cpp:1887
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition AST.cpp:247
llvm::SmallVector< std::pair< const NamedDecl *, DeclRelationSet >, 1 > allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver)
Similar to targetDecl(), however instead of applying a filter, all possible decls are returned along ...
std::vector< DocumentHighlight > findDocumentHighlights(ParsedAST &AST, Position Pos)
Returns highlights for all usages of a symbol at Pos.
Definition XRefs.cpp:1313
llvm::SmallVector< const NamedDecl *, 1 > explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask, const HeuristicResolver *Resolver)
Find declarations explicitly referenced in the source code defined by N.
std::vector< LocatedSymbol > locateSymbolTextually(const SpelledWord &Word, ParsedAST &AST, const SymbolIndex *Index, llvm::StringRef MainFilePath, ASTNodeKind NodeKind)
Definition XRefs.cpp:575
std::vector< DocumentLink > getDocumentLinks(ParsedAST &AST)
Get all document links.
Definition XRefs.cpp:857
Symbol mergeSymbol(const Symbol &L, const Symbol &R)
Definition Merge.cpp:266
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition XRefs.cpp:1702
std::vector< include_cleaner::SymbolReference > collectMacroReferences(ParsedAST &AST)
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
llvm::Expected< Location > symbolToLocation(const Symbol &Sym, llvm::StringRef TUPath)
Helper function for deriving an LSP Location for a Symbol.
SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM)
Find the source location of the identifier for D.
Definition AST.cpp:196
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
include_cleaner::Includes convertIncludes(const ParsedAST &AST)
Converts the clangd include representation to include-cleaner include representation.
std::vector< LocatedSymbol > findType(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns symbols for types referenced at Pos.
Definition XRefs.cpp:2180
void findExplicitReferences(const Stmt *S, llvm::function_ref< void(ReferenceLoc)> Out, const HeuristicResolver *Resolver)
Recursively traverse S and report all references explicitly written in the code.
static QualType typeForNode(const ASTContext &Ctx, const HeuristicResolver *H, const SelectionTree::Node *N)
Definition XRefs.cpp:2004
std::vector< TypeHierarchyItem > getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index, PathRef TUPath)
Get type hierarchy information at Pos.
Definition XRefs.cpp:2257
static std::optional< TypeHierarchyItem > declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath)
Definition XRefs.cpp:1830
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition AST.cpp:622
llvm::SmallVector< const NamedDecl *, 1 > targetDecl(const DynTypedNode &N, DeclRelationSet Mask, const HeuristicResolver *Resolver)
targetDecl() finds the declaration referred to by an AST node.
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, const SymbolIndex *Index, bool AddContext)
Returns references of the symbol at a specified Pos.
Definition XRefs.cpp:1479
static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath, TypeHierarchyItem &Item, RecursionProtectionSet &RPSet)
Definition XRefs.cpp:1918
std::optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
Definition XRefs.cpp:776
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const LangOptions &LangOpts)
Heuristically determine namespaces visible at a point, without parsing Code.
static std::optional< HierarchyItem > declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath)
Definition XRefs.cpp:1785
std::optional< std::string > getCanonicalPath(const FileEntryRef F, FileManager &FileMgr)
Get the canonical path of F.
static void unwrapFindType(QualType T, const HeuristicResolver *H, llvm::SmallVector< QualType > &Out)
Definition XRefs.cpp:2133
static std::optional< HierarchyItem > symbolToHierarchyItem(const Symbol &S, PathRef TUPath)
Definition XRefs.cpp:1856
SmallVector< const CXXConstructorDecl *, 1 > searchConstructorsInForwardingFunction(const FunctionDecl *FD)
Only call if FD is a likely forwarding function.
Definition AST.cpp:1109
const syntax::Token * findNearbyIdentifier(const SpelledWord &Word, const syntax::TokenBuffer &TB)
Definition XRefs.cpp:685
llvm::SmallPtrSet< const CXXRecordDecl *, 4 > RecursionProtectionSet
Definition XRefs.cpp:1915
static void fillSubTypes(const SymbolID &ID, std::vector< TypeHierarchyItem > &SubTypes, const SymbolIndex *Index, int Levels, PathRef TUPath)
Definition XRefs.cpp:1897
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind)
Definition Protocol.cpp:298
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1678
std::vector< LocatedSymbol > findImplementations(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns implementations at a specified Pos:
Definition XRefs.cpp:1354
const ObjCImplDecl * getCorrespondingObjCImpl(const ObjCContainerDecl *D)
Return the corresponding implementation/definition for the given ObjC container if it has one,...
Definition AST.cpp:370
void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index)
Definition XRefs.cpp:2331
llvm::DenseSet< const Decl * > getNonLocalDeclRefs(ParsedAST &AST, const FunctionDecl *FD)
Returns all decls that are referenced in the FD except local symbols.
Definition XRefs.cpp:2525
clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset)
Returns the range starting at offset and spanning the whole line.
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
Definition Quality.cpp:534
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition AST.cpp:206
std::vector< CallHierarchyOutgoingCall > outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index)
Definition XRefs.cpp:2454
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
@ Underlying
This is the underlying declaration for a renaming-alias, decltype etc.
Definition FindTarget.h:121
@ TemplatePattern
This is the pattern the template specialization was instantiated from.
Definition FindTarget.h:104
@ Alias
This declaration is an alias that was referred to.
Definition FindTarget.h:112
static std::optional< CallHierarchyItem > declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath)
Definition XRefs.cpp:1844
std::vector< const CXXRecordDecl * > findRecordTypeAt(ParsedAST &AST, Position Pos)
Find the record types referenced at Pos.
Definition XRefs.cpp:1949
std::vector< CallHierarchyItem > prepareCallHierarchy(ParsedAST &AST, Position Pos, PathRef TUPath)
Get call hierarchy information at Pos.
Definition XRefs.cpp:2346
std::vector< const CXXRecordDecl * > typeParents(const CXXRecordDecl *CXXRD)
Given a record type declaration, find its base (parent) types.
Definition XRefs.cpp:2215
SymbolKind
A symbol kind.
Definition Protocol.h:380
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Represents an incoming call, e.g. a caller of a method or constructor.
Definition Protocol.h:1623
Represents programming constructs like functions or constructors in the context of call hierarchy.
Definition Protocol.h:1583
URIForFile uri
The resource identifier of this item.
Definition Protocol.h:1597
SymbolKind kind
The kind of this item.
Definition Protocol.h:1588
std::string data
An optional 'data' field, which can be used to identify a call hierarchy item in an incomingCalls or ...
Definition Protocol.h:1610
Represents an outgoing call, e.g.
Definition Protocol.h:1648
A document highlight is a range inside a text document which deserves special attention.
Definition Protocol.h:1468
Range range
The range this highlight applies to.
Definition Protocol.h:1470
std::vector< std::string > Scopes
If this is non-empty, symbols must be in at least one of the scopes (e.g.
Definition Index.h:36
std::string Query
A query string for the fuzzy find.
Definition Index.h:29
std::vector< std::string > ProximityPaths
Contextually relevant files (e.g.
Definition Index.h:47
bool AnyScope
If set to true, allow symbols from any scope.
Definition Index.h:39
std::optional< uint32_t > Limit
The number of top candidates to return.
Definition Index.h:42
Location PreferredDeclaration
Definition XRefs.h:45
std::optional< Location > Definition
Definition XRefs.h:47
URIForFile uri
The text document's URI.
Definition Protocol.h:213
llvm::DenseSet< SymbolID > IDs
Definition Index.h:65
Represents a symbol occurrence in the source file.
Definition Ref.h:88
RefKind Kind
Definition Ref.h:91
SymbolID Container
The ID of the symbol whose definition contains this reference.
Definition Ref.h:95
SymbolLocation Location
The source location where the symbol is named.
Definition Ref.h:90
Information about a reference written in the source code, independent of the actual AST node that thi...
Definition FindTarget.h:128
std::optional< std::string > containerName
clangd extension: contains the name of the function or class in which the reference occurs
Definition Protocol.h:236
std::vector< Reference > References
Definition XRefs.h:94
bool WantContainer
If set, populates the container of the reference.
Definition Index.h:77
llvm::DenseSet< SymbolID > IDs
Definition Index.h:69
std::optional< uint32_t > Limit
If set, limit the number of refers returned from the index.
Definition Index.h:74
llvm::DenseSet< SymbolID > Subjects
Definition Index.h:94
const DeclContext & getDeclContext() const
static std::optional< SpelledWord > touching(SourceLocation SpelledLoc, const syntax::TokenBuffer &TB, const LangOptions &LangOpts)
const syntax::Token * ExpandedToken
Definition SourceCode.h:256
const syntax::Token * PartOfSpelledToken
Definition SourceCode.h:251
Represents information about identifier.
Definition Protocol.h:1168
std::optional< Location > definitionRange
Definition Protocol.h:1184
std::optional< Location > declarationRange
Definition Protocol.h:1182
std::string USR
Unified Symbol Resolution identifier This is an opaque string uniquely identifying a symbol.
Definition Protocol.h:1178
Attributes of a symbol that affect how much we like it.
Definition Quality.h:56
void merge(const CodeCompletionResult &SemaCCResult)
Definition Quality.cpp:178
Attributes of a symbol-query pair that affect how much we like it.
Definition Quality.h:86
llvm::StringRef Name
The name of the symbol (for ContextWords). Must be explicitly assigned.
Definition Quality.h:88
void merge(const CodeCompletionResult &SemaResult)
Definition Quality.cpp:329
enum clang::clangd::SymbolRelevanceSignals::QueryType Query
The class presents a C++ symbol, e.g.
Definition Symbol.h:39
SymbolFlag Flags
Definition Symbol.h:151
@ Deprecated
Indicates if the symbol is deprecated.
Definition Symbol.h:143
SymbolLocation Definition
The location of the symbol's definition, if one was found.
Definition Symbol.h:50
index::SymbolInfo SymInfo
The symbol information, like symbol kind.
Definition Symbol.h:43
llvm::StringRef Name
The unqualified name of the symbol, e.g. "bar" (for ns::bar).
Definition Symbol.h:45
llvm::StringRef Scope
The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
Definition Symbol.h:47
llvm::StringRef TemplateSpecializationArgs
Argument list in human-readable format, will be displayed to help disambiguate between different spec...
Definition Symbol.h:72
SymbolLocation CanonicalDeclaration
The location of the preferred declaration of the symbol.
Definition Symbol.h:59
SymbolID ID
The ID of the symbol.
Definition Symbol.h:41
std::optional< std::vector< ResolveParams > > parents
std::nullopt means parents aren't resolved and empty is no parents.
Definition Protocol.h:1534
URIForFile uri
The resource identifier of this item.
Definition Protocol.h:1520
std::optional< std::vector< TypeHierarchyItem > > children
If this type hierarchy item is resolved, it contains the direct children of the current item.
Definition Protocol.h:1553
std::optional< std::vector< TypeHierarchyItem > > parents
This is a clangd exntesion.
Definition Protocol.h:1547
ResolveParams data
A data entry field that is preserved between a type hierarchy prepare and supertypes or subtypes requ...
Definition Protocol.h:1540
std::string uri() const
Definition Protocol.h:107
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition Protocol.cpp:46
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition Protocol.h:104
Represents measurements of clangd events, e.g.
Definition Trace.h:38
@ Counter
An aggregate number whose rate of change over time is meaningful.
Definition Trace.h:46