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 "URI.h"
20#include "clang-include-cleaner/Analysis.h"
21#include "clang-include-cleaner/Types.h"
22#include "index/Index.h"
23#include "index/Merge.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/LangOptions.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TokenKinds.h"
49#include "clang/Index/IndexDataConsumer.h"
50#include "clang/Index/IndexSymbol.h"
51#include "clang/Index/IndexingAction.h"
52#include "clang/Index/IndexingOptions.h"
53#include "clang/Index/USRGeneration.h"
54#include "clang/Lex/Lexer.h"
55#include "clang/Sema/HeuristicResolver.h"
56#include "clang/Tooling/Syntax/Tokens.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/ScopeExit.h"
61#include "llvm/ADT/SmallSet.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/StringRef.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/Error.h"
66#include "llvm/Support/ErrorHandling.h"
67#include "llvm/Support/Path.h"
68#include "llvm/Support/raw_ostream.h"
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(const 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 }
936
937 std::vector<Reference> take() && {
938 llvm::sort(References, [](const Reference &L, const Reference &R) {
939 auto LTok = L.SpelledTok.location();
940 auto RTok = R.SpelledTok.location();
941 return std::tie(LTok, L.Role) < std::tie(RTok, R.Role);
942 });
943 // We sometimes see duplicates when parts of the AST get traversed twice.
944 References.erase(llvm::unique(References,
945 [](const Reference &L, const Reference &R) {
946 auto LTok = L.SpelledTok.location();
947 auto RTok = R.SpelledTok.location();
948 return std::tie(LTok, L.Role) ==
949 std::tie(RTok, R.Role);
950 }),
951 References.end());
952 return std::move(References);
953 }
954
955 bool
956 handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles,
957 llvm::ArrayRef<index::SymbolRelation> Relations,
958 SourceLocation Loc,
959 index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
960 if (!TargetDecls.contains(D->getCanonicalDecl()))
961 return true;
962 const SourceManager &SM = AST.getSourceManager();
963 if (!isInsideMainFile(Loc, SM))
964 return true;
965 const auto &TB = AST.getTokens();
966
967 llvm::SmallVector<SourceLocation, 1> Locs;
968 if (PerToken) {
969 // Check whether this is one of the few constructs where the reference
970 // can be split over several tokens.
971 if (auto *OME = llvm::dyn_cast_or_null<ObjCMessageExpr>(ASTNode.OrigE)) {
972 OME->getSelectorLocs(Locs);
973 } else if (auto *OMD =
974 llvm::dyn_cast_or_null<ObjCMethodDecl>(ASTNode.OrigD)) {
975 OMD->getSelectorLocs(Locs);
976 }
977 // Sanity check: we expect the *first* token to match the reported loc.
978 // Otherwise, maybe it was e.g. some other kind of reference to a Decl.
979 if (!Locs.empty() && Locs.front() != Loc)
980 Locs.clear(); // First token doesn't match, assume our guess was wrong.
981 }
982 if (Locs.empty())
983 Locs.push_back(Loc);
984
985 SymbolCollector::Options CollectorOpts;
986 CollectorOpts.CollectMainFileSymbols = true;
987 for (SourceLocation L : Locs) {
988 L = SM.getFileLoc(L);
989 if (const auto *Tok = TB.spelledTokenContaining(L))
990 References.push_back(
991 {*Tok, Roles,
992 SymbolCollector::getRefContainer(ASTNode.Parent, CollectorOpts)});
993 }
994 return true;
995 }
996
997private:
998 bool PerToken; // If true, report 3 references for split ObjC selector names.
999 std::vector<Reference> References;
1000 const ParsedAST &AST;
1001 llvm::DenseSet<const Decl *> TargetDecls;
1002};
1003
1004std::vector<ReferenceFinder::Reference>
1005findRefs(const llvm::ArrayRef<const NamedDecl *> TargetDecls, ParsedAST &AST,
1006 bool PerToken) {
1007 ReferenceFinder RefFinder(AST, TargetDecls, PerToken);
1008 index::IndexingOptions IndexOpts;
1009 IndexOpts.SystemSymbolFilter =
1010 index::IndexingOptions::SystemSymbolFilterKind::All;
1011 IndexOpts.IndexFunctionLocals = true;
1012 IndexOpts.IndexParametersInDeclarations = true;
1013 IndexOpts.IndexTemplateParameters = true;
1014 indexTopLevelDecls(AST.getASTContext(), AST.getPreprocessor(),
1015 AST.getLocalTopLevelDecls(), RefFinder, IndexOpts);
1016 return std::move(RefFinder).take();
1017}
1018
1019const Stmt *getFunctionBody(DynTypedNode N) {
1020 if (const auto *FD = N.get<FunctionDecl>())
1021 return FD->getBody();
1022 if (const auto *FD = N.get<BlockDecl>())
1023 return FD->getBody();
1024 if (const auto *FD = N.get<LambdaExpr>())
1025 return FD->getBody();
1026 if (const auto *FD = N.get<ObjCMethodDecl>())
1027 return FD->getBody();
1028 return nullptr;
1029}
1030
1031const Stmt *getLoopBody(DynTypedNode N) {
1032 if (const auto *LS = N.get<ForStmt>())
1033 return LS->getBody();
1034 if (const auto *LS = N.get<CXXForRangeStmt>())
1035 return LS->getBody();
1036 if (const auto *LS = N.get<WhileStmt>())
1037 return LS->getBody();
1038 if (const auto *LS = N.get<DoStmt>())
1039 return LS->getBody();
1040 return nullptr;
1041}
1042
1043// AST traversal to highlight control flow statements under some root.
1044// Once we hit further control flow we prune the tree (or at least restrict
1045// what we highlight) so we capture e.g. breaks from the outer loop only.
1046class FindControlFlow : public RecursiveASTVisitor<FindControlFlow> {
1047 // Types of control-flow statements we might highlight.
1048 enum Target {
1049 Break = 1,
1050 Continue = 2,
1051 Return = 4,
1052 Case = 8,
1053 Throw = 16,
1054 Goto = 32,
1055 All = Break | Continue | Return | Case | Throw | Goto,
1056 };
1057 int Ignore = 0; // bitmask of Target - what are we *not* highlighting?
1058 SourceRange Bounds; // Half-open, restricts reported targets.
1059 std::vector<SourceLocation> &Result;
1060 const SourceManager &SM;
1061
1062 // Masks out targets for a traversal into D.
1063 // Traverses the subtree using Delegate() if any targets remain.
1064 template <typename Func>
1065 bool filterAndTraverse(DynTypedNode D, const Func &Delegate) {
1066 auto RestoreIgnore = llvm::make_scope_exit(
1067 [OldIgnore(Ignore), this] { Ignore = OldIgnore; });
1068 if (getFunctionBody(D))
1069 Ignore = All;
1070 else if (getLoopBody(D))
1071 Ignore |= Continue | Break;
1072 else if (D.get<SwitchStmt>())
1073 Ignore |= Break | Case;
1074 // Prune tree if we're not looking for anything.
1075 return (Ignore == All) ? true : Delegate();
1076 }
1077
1078 void found(Target T, SourceLocation Loc) {
1079 if (T & Ignore)
1080 return;
1081 if (SM.isBeforeInTranslationUnit(Loc, Bounds.getBegin()) ||
1082 SM.isBeforeInTranslationUnit(Bounds.getEnd(), Loc))
1083 return;
1084 Result.push_back(Loc);
1085 }
1086
1087public:
1088 FindControlFlow(SourceRange Bounds, std::vector<SourceLocation> &Result,
1089 const SourceManager &SM)
1090 : Bounds(Bounds), Result(Result), SM(SM) {}
1091
1092 // When traversing function or loops, limit targets to those that still
1093 // refer to the original root.
1094 bool TraverseDecl(Decl *D) {
1095 return !D || filterAndTraverse(DynTypedNode::create(*D), [&] {
1096 return RecursiveASTVisitor::TraverseDecl(D);
1097 });
1098 }
1099 bool TraverseStmt(Stmt *S) {
1100 return !S || filterAndTraverse(DynTypedNode::create(*S), [&] {
1101 return RecursiveASTVisitor::TraverseStmt(S);
1102 });
1103 }
1104
1105 // Add leaves that we found and want.
1106 bool VisitReturnStmt(ReturnStmt *R) {
1107 found(Return, R->getReturnLoc());
1108 return true;
1109 }
1110 bool VisitBreakStmt(BreakStmt *B) {
1111 found(Break, B->getKwLoc());
1112 return true;
1113 }
1114 bool VisitContinueStmt(ContinueStmt *C) {
1115 found(Continue, C->getKwLoc());
1116 return true;
1117 }
1118 bool VisitSwitchCase(SwitchCase *C) {
1119 found(Case, C->getKeywordLoc());
1120 return true;
1121 }
1122 bool VisitCXXThrowExpr(CXXThrowExpr *T) {
1123 found(Throw, T->getThrowLoc());
1124 return true;
1125 }
1126 bool VisitGotoStmt(GotoStmt *G) {
1127 // Goto is interesting if its target is outside the root.
1128 if (const auto *LD = G->getLabel()) {
1129 if (SM.isBeforeInTranslationUnit(LD->getLocation(), Bounds.getBegin()) ||
1130 SM.isBeforeInTranslationUnit(Bounds.getEnd(), LD->getLocation()))
1131 found(Goto, G->getGotoLoc());
1132 }
1133 return true;
1134 }
1135};
1136
1137// Given a location within a switch statement, return the half-open range that
1138// covers the case it's contained in.
1139// We treat `case X: case Y: ...` as one case, and assume no other fallthrough.
1140SourceRange findCaseBounds(const SwitchStmt &Switch, SourceLocation Loc,
1141 const SourceManager &SM) {
1142 // Cases are not stored in order, sort them first.
1143 // (In fact they seem to be stored in reverse order, don't rely on this)
1144 std::vector<const SwitchCase *> Cases;
1145 for (const SwitchCase *Case = Switch.getSwitchCaseList(); Case;
1146 Case = Case->getNextSwitchCase())
1147 Cases.push_back(Case);
1148 llvm::sort(Cases, [&](const SwitchCase *L, const SwitchCase *R) {
1149 return SM.isBeforeInTranslationUnit(L->getKeywordLoc(), R->getKeywordLoc());
1150 });
1151
1152 // Find the first case after the target location, the end of our range.
1153 auto CaseAfter = llvm::partition_point(Cases, [&](const SwitchCase *C) {
1154 return !SM.isBeforeInTranslationUnit(Loc, C->getKeywordLoc());
1155 });
1156 SourceLocation End = CaseAfter == Cases.end() ? Switch.getEndLoc()
1157 : (*CaseAfter)->getKeywordLoc();
1158
1159 // Our target can be before the first case - cases are optional!
1160 if (CaseAfter == Cases.begin())
1161 return SourceRange(Switch.getBeginLoc(), End);
1162 // The start of our range is usually the previous case, but...
1163 auto CaseBefore = std::prev(CaseAfter);
1164 // ... rewind CaseBefore to the first in a `case A: case B: ...` sequence.
1165 while (CaseBefore != Cases.begin() &&
1166 (*std::prev(CaseBefore))->getSubStmt() == *CaseBefore)
1167 --CaseBefore;
1168 return SourceRange((*CaseBefore)->getKeywordLoc(), End);
1169}
1170
1171// Returns the locations of control flow statements related to N. e.g.:
1172// for => branches: break/continue/return/throw
1173// break => controlling loop (forwhile/do), and its related control flow
1174// return => all returns/throws from the same function
1175// When an inner block is selected, we include branches bound to outer blocks
1176// as these are exits from the inner block. e.g. return in a for loop.
1177// FIXME: We don't analyze catch blocks, throw is treated the same as return.
1178std::vector<SourceLocation> relatedControlFlow(const SelectionTree::Node &N) {
1179 const SourceManager &SM =
1180 N.getDeclContext().getParentASTContext().getSourceManager();
1181 std::vector<SourceLocation> Result;
1182
1183 // First, check if we're at a node that can resolve to a root.
1184 enum class Cur { None, Break, Continue, Return, Case, Throw } Cursor;
1185 if (N.ASTNode.get<BreakStmt>()) {
1186 Cursor = Cur::Break;
1187 } else if (N.ASTNode.get<ContinueStmt>()) {
1188 Cursor = Cur::Continue;
1189 } else if (N.ASTNode.get<ReturnStmt>()) {
1190 Cursor = Cur::Return;
1191 } else if (N.ASTNode.get<CXXThrowExpr>()) {
1192 Cursor = Cur::Throw;
1193 } else if (N.ASTNode.get<SwitchCase>()) {
1194 Cursor = Cur::Case;
1195 } else if (const GotoStmt *GS = N.ASTNode.get<GotoStmt>()) {
1196 // We don't know what root to associate with, but highlight the goto/label.
1197 Result.push_back(GS->getGotoLoc());
1198 if (const auto *LD = GS->getLabel())
1199 Result.push_back(LD->getLocation());
1200 Cursor = Cur::None;
1201 } else {
1202 Cursor = Cur::None;
1203 }
1204
1205 const Stmt *Root = nullptr; // Loop or function body to traverse.
1206 SourceRange Bounds;
1207 // Look up the tree for a root (or just at this node if we didn't find a leaf)
1208 for (const auto *P = &N; P; P = P->Parent) {
1209 // return associates with enclosing function
1210 if (const Stmt *FunctionBody = getFunctionBody(P->ASTNode)) {
1211 if (Cursor == Cur::Return || Cursor == Cur::Throw) {
1212 Root = FunctionBody;
1213 }
1214 break; // other leaves don't cross functions.
1215 }
1216 // break/continue associate with enclosing loop.
1217 if (const Stmt *LoopBody = getLoopBody(P->ASTNode)) {
1218 if (Cursor == Cur::None || Cursor == Cur::Break ||
1219 Cursor == Cur::Continue) {
1220 Root = LoopBody;
1221 // Highlight the loop keyword itself.
1222 // FIXME: for do-while, this only covers the `do`..
1223 Result.push_back(P->ASTNode.getSourceRange().getBegin());
1224 break;
1225 }
1226 }
1227 // For switches, users think of case statements as control flow blocks.
1228 // We highlight only occurrences surrounded by the same case.
1229 // We don't detect fallthrough (other than 'case X, case Y').
1230 if (const auto *SS = P->ASTNode.get<SwitchStmt>()) {
1231 if (Cursor == Cur::Break || Cursor == Cur::Case) {
1232 Result.push_back(SS->getSwitchLoc()); // Highlight the switch.
1233 Root = SS->getBody();
1234 // Limit to enclosing case, if there is one.
1235 Bounds = findCaseBounds(*SS, N.ASTNode.getSourceRange().getBegin(), SM);
1236 break;
1237 }
1238 }
1239 // If we didn't start at some interesting node, we're done.
1240 if (Cursor == Cur::None)
1241 break;
1242 }
1243 if (Root) {
1244 if (!Bounds.isValid())
1245 Bounds = Root->getSourceRange();
1246 FindControlFlow(Bounds, Result, SM).TraverseStmt(const_cast<Stmt *>(Root));
1247 }
1248 return Result;
1249}
1250
1251DocumentHighlight toHighlight(const ReferenceFinder::Reference &Ref,
1252 const SourceManager &SM) {
1254 DH.range = Ref.range(SM);
1255 if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Write))
1257 else if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Read))
1259 else
1261 return DH;
1262}
1263
1264std::optional<DocumentHighlight> toHighlight(SourceLocation Loc,
1265 const syntax::TokenBuffer &TB) {
1266 Loc = TB.sourceManager().getFileLoc(Loc);
1267 if (const auto *Tok = TB.spelledTokenContaining(Loc)) {
1268 DocumentHighlight Result;
1269 Result.range = halfOpenToRange(
1270 TB.sourceManager(),
1271 CharSourceRange::getCharRange(Tok->location(), Tok->endLocation()));
1272 return Result;
1273 }
1274 return std::nullopt;
1275}
1276
1277} // namespace
1278
1279std::vector<DocumentHighlight> findDocumentHighlights(ParsedAST &AST,
1280 Position Pos) {
1281 const SourceManager &SM = AST.getSourceManager();
1282 // FIXME: show references to macro within file?
1283 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1284 if (!CurLoc) {
1285 llvm::consumeError(CurLoc.takeError());
1286 return {};
1287 }
1288 std::vector<DocumentHighlight> Result;
1289 auto TryTree = [&](SelectionTree ST) {
1290 if (const SelectionTree::Node *N = ST.commonAncestor()) {
1291 DeclRelationSet Relations =
1293 auto TargetDecls =
1294 targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
1295 if (!TargetDecls.empty()) {
1296 // FIXME: we may get multiple DocumentHighlights with the same location
1297 // and different kinds, deduplicate them.
1298 for (const auto &Ref : findRefs(TargetDecls, AST, /*PerToken=*/true))
1299 Result.push_back(toHighlight(Ref, SM));
1300 return true;
1301 }
1302 auto ControlFlow = relatedControlFlow(*N);
1303 if (!ControlFlow.empty()) {
1304 for (SourceLocation Loc : ControlFlow)
1305 if (auto Highlight = toHighlight(Loc, AST.getTokens()))
1306 Result.push_back(std::move(*Highlight));
1307 return true;
1308 }
1309 }
1310 return false;
1311 };
1312
1313 unsigned Offset =
1314 AST.getSourceManager().getDecomposedSpellingLoc(*CurLoc).second;
1315 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset,
1316 Offset, TryTree);
1317 return Result;
1318}
1319
1320std::vector<LocatedSymbol> findImplementations(ParsedAST &AST, Position Pos,
1321 const SymbolIndex *Index) {
1322 // We rely on index to find the implementations in subclasses.
1323 // FIXME: Index can be stale, so we may loose some latest results from the
1324 // main file.
1325 if (!Index)
1326 return {};
1327 const SourceManager &SM = AST.getSourceManager();
1328 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1329 if (!CurLoc) {
1330 elog("Failed to convert position to source location: {0}",
1331 CurLoc.takeError());
1332 return {};
1333 }
1334 DeclRelationSet Relations =
1336 llvm::DenseSet<SymbolID> IDs;
1338 for (const NamedDecl *ND : getDeclAtPosition(AST, *CurLoc, Relations)) {
1339 if (const auto *CXXMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
1340 if (CXXMD->isVirtual()) {
1341 IDs.insert(getSymbolID(ND));
1342 QueryKind = RelationKind::OverriddenBy;
1343 }
1344 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1345 IDs.insert(getSymbolID(RD));
1346 QueryKind = RelationKind::BaseOf;
1347 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(ND)) {
1348 IDs.insert(getSymbolID(OMD));
1349 QueryKind = RelationKind::OverriddenBy;
1350 } else if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1351 IDs.insert(getSymbolID(ID));
1352 QueryKind = RelationKind::BaseOf;
1353 }
1354 }
1355 return findImplementors(std::move(IDs), QueryKind, Index, AST.tuPath());
1356}
1357
1358namespace {
1359// Recursively finds all the overridden methods of `CMD` in complete type
1360// hierarchy.
1361void getOverriddenMethods(const CXXMethodDecl *CMD,
1362 llvm::DenseSet<SymbolID> &OverriddenMethods) {
1363 if (!CMD)
1364 return;
1365 for (const CXXMethodDecl *Base : CMD->overridden_methods()) {
1366 if (auto ID = getSymbolID(Base))
1367 OverriddenMethods.insert(ID);
1368 getOverriddenMethods(Base, OverriddenMethods);
1369 }
1370}
1371
1372// Recursively finds all the overridden methods of `OMD` in complete type
1373// hierarchy.
1374void getOverriddenMethods(const ObjCMethodDecl *OMD,
1375 llvm::DenseSet<SymbolID> &OverriddenMethods) {
1376 if (!OMD)
1377 return;
1378 llvm::SmallVector<const ObjCMethodDecl *, 4> Overrides;
1379 OMD->getOverriddenMethods(Overrides);
1380 for (const ObjCMethodDecl *Base : Overrides) {
1381 if (auto ID = getSymbolID(Base))
1382 OverriddenMethods.insert(ID);
1383 getOverriddenMethods(Base, OverriddenMethods);
1384 }
1385}
1386
1387std::optional<std::string>
1388stringifyContainerForMainFileRef(const Decl *Container) {
1389 // FIXME We might also want to display the signature here
1390 // When doing so, remember to also add the Signature to index results!
1391 if (auto *ND = llvm::dyn_cast_if_present<NamedDecl>(Container))
1392 return printQualifiedName(*ND);
1393 return {};
1394}
1395
1396std::optional<ReferencesResult>
1397maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
1398 URIForFile URIMainFile) {
1399 const auto &Includes = AST.getIncludeStructure().MainFileIncludes;
1400 auto IncludeOnLine = llvm::find_if(Includes, [&Pos](const Inclusion &Inc) {
1401 return Inc.HashLine == Pos.line;
1402 });
1403 if (IncludeOnLine == Includes.end())
1404 return std::nullopt;
1405
1406 const SourceManager &SM = AST.getSourceManager();
1407 ReferencesResult Results;
1408 auto Converted = convertIncludes(AST);
1409 include_cleaner::walkUsed(
1410 AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
1411 &AST.getPragmaIncludes(), AST.getPreprocessor(),
1412 [&](const include_cleaner::SymbolReference &Ref,
1413 llvm::ArrayRef<include_cleaner::Header> Providers) {
1414 if (Ref.RT != include_cleaner::RefType::Explicit ||
1415 !isPreferredProvider(*IncludeOnLine, Converted, Providers))
1416 return;
1417
1418 auto Loc = SM.getFileLoc(Ref.RefLocation);
1419 // File locations can be outside of the main file if macro is
1420 // expanded through an #include.
1421 while (SM.getFileID(Loc) != SM.getMainFileID())
1422 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
1423
1424 ReferencesResult::Reference Result;
1425 const auto *Token = AST.getTokens().spelledTokenContaining(Loc);
1426 assert(Token && "references expected token here");
1427 Result.Loc.range = Range{sourceLocToPosition(SM, Token->location()),
1428 sourceLocToPosition(SM, Token->endLocation())};
1429 Result.Loc.uri = URIMainFile;
1430 Results.References.push_back(std::move(Result));
1431 });
1432 if (Results.References.empty())
1433 return std::nullopt;
1434
1435 // Add the #include line to the references list.
1437 Result.Loc.range = rangeTillEOL(SM.getBufferData(SM.getMainFileID()),
1438 IncludeOnLine->HashOffset);
1439 Result.Loc.uri = URIMainFile;
1440 Results.References.push_back(std::move(Result));
1441 return Results;
1442}
1443} // namespace
1444
1446 const SymbolIndex *Index, bool AddContext) {
1447 ReferencesResult Results;
1448 const SourceManager &SM = AST.getSourceManager();
1449 auto MainFilePath = AST.tuPath();
1450 auto URIMainFile = URIForFile::canonicalize(MainFilePath, MainFilePath);
1451 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1452 if (!CurLoc) {
1453 llvm::consumeError(CurLoc.takeError());
1454 return {};
1455 }
1456
1457 const auto IncludeReferences =
1458 maybeFindIncludeReferences(AST, Pos, URIMainFile);
1459 if (IncludeReferences)
1460 return *IncludeReferences;
1461
1462 llvm::DenseSet<SymbolID> IDsToQuery, OverriddenMethods;
1463
1464 const auto *IdentifierAtCursor =
1465 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
1466 std::optional<DefinedMacro> Macro;
1467 if (IdentifierAtCursor)
1468 Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
1469 if (Macro) {
1470 // Handle references to macro.
1471 if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {
1472 // Collect macro references from main file.
1473 const auto &IDToRefs = AST.getMacros().MacroRefs;
1474 auto Refs = IDToRefs.find(MacroSID);
1475 if (Refs != IDToRefs.end()) {
1476 for (const auto &Ref : Refs->second) {
1478 Result.Loc.range = Ref.toRange(SM);
1479 Result.Loc.uri = URIMainFile;
1480 if (Ref.IsDefinition) {
1483 }
1484 Results.References.push_back(std::move(Result));
1485 }
1486 }
1487 IDsToQuery.insert(MacroSID);
1488 }
1489 } else {
1490 // Handle references to Decls.
1491
1492 DeclRelationSet Relations =
1494 std::vector<const NamedDecl *> Decls =
1495 getDeclAtPosition(AST, *CurLoc, Relations);
1496 llvm::SmallVector<const NamedDecl *> TargetsInMainFile;
1497 for (const NamedDecl *D : Decls) {
1498 auto ID = getSymbolID(D);
1499 if (!ID)
1500 continue;
1501 TargetsInMainFile.push_back(D);
1502 // Not all symbols can be referenced from outside (e.g. function-locals).
1503 // TODO: we could skip TU-scoped symbols here (e.g. static functions) if
1504 // we know this file isn't a header. The details might be tricky.
1505 if (D->getParentFunctionOrMethod())
1506 continue;
1507 IDsToQuery.insert(ID);
1508 }
1509
1511 if (Index) {
1513 for (const NamedDecl *ND : Decls) {
1514 // Special case: For virtual methods, report decl/def of overrides and
1515 // references to all overridden methods in complete type hierarchy.
1516 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
1517 if (CMD->isVirtual()) {
1518 if (auto ID = getSymbolID(CMD))
1519 OverriddenBy.Subjects.insert(ID);
1520 getOverriddenMethods(CMD, OverriddenMethods);
1521 }
1522 }
1523 // Special case: Objective-C methods can override a parent class or
1524 // protocol, we should be sure to report references to those.
1525 if (const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(ND)) {
1526 OverriddenBy.Subjects.insert(getSymbolID(OMD));
1527 getOverriddenMethods(OMD, OverriddenMethods);
1528 }
1529 }
1530 }
1531
1532 // We traverse the AST to find references in the main file.
1533 auto MainFileRefs = findRefs(TargetsInMainFile, AST, /*PerToken=*/false);
1534 // We may get multiple refs with the same location and different Roles, as
1535 // cross-reference is only interested in locations, we deduplicate them
1536 // by the location to avoid emitting duplicated locations.
1537 MainFileRefs.erase(llvm::unique(MainFileRefs,
1538 [](const ReferenceFinder::Reference &L,
1539 const ReferenceFinder::Reference &R) {
1540 return L.SpelledTok.location() ==
1541 R.SpelledTok.location();
1542 }),
1543 MainFileRefs.end());
1544 for (const auto &Ref : MainFileRefs) {
1546 Result.Loc.range = Ref.range(SM);
1547 Result.Loc.uri = URIMainFile;
1548 if (AddContext)
1549 Result.Loc.containerName =
1550 stringifyContainerForMainFileRef(Ref.Container);
1551 if (Ref.Role & static_cast<unsigned>(index::SymbolRole::Declaration))
1553 // clang-index doesn't report definitions as declarations, but they are.
1554 if (Ref.Role & static_cast<unsigned>(index::SymbolRole::Definition))
1555 Result.Attributes |=
1557 Results.References.push_back(std::move(Result));
1558 }
1559 // Add decl/def of overridding methods.
1560 if (Index && !OverriddenBy.Subjects.empty()) {
1561 LookupRequest ContainerLookup;
1562 // Different overrides will always be contained in different classes, so
1563 // we have a one-to-one mapping between SymbolID and index here, thus we
1564 // don't need to use std::vector as the map's value type.
1565 llvm::DenseMap<SymbolID, size_t> RefIndexForContainer;
1566 Index->relations(OverriddenBy, [&](const SymbolID &Subject,
1567 const Symbol &Object) {
1568 if (Limit && Results.References.size() >= Limit) {
1569 Results.HasMore = true;
1570 return;
1571 }
1572 const auto LSPLocDecl =
1573 toLSPLocation(Object.CanonicalDeclaration, MainFilePath);
1574 const auto LSPLocDef = toLSPLocation(Object.Definition, MainFilePath);
1575 if (LSPLocDecl && LSPLocDecl != LSPLocDef) {
1577 Result.Loc = {std::move(*LSPLocDecl), std::nullopt};
1578 Result.Attributes =
1580 RefIndexForContainer.insert({Object.ID, Results.References.size()});
1581 ContainerLookup.IDs.insert(Object.ID);
1582 Results.References.push_back(std::move(Result));
1583 }
1584 if (LSPLocDef) {
1586 Result.Loc = {std::move(*LSPLocDef), std::nullopt};
1590 RefIndexForContainer.insert({Object.ID, Results.References.size()});
1591 ContainerLookup.IDs.insert(Object.ID);
1592 Results.References.push_back(std::move(Result));
1593 }
1594 });
1595
1596 if (!ContainerLookup.IDs.empty() && AddContext)
1597 Index->lookup(ContainerLookup, [&](const Symbol &Container) {
1598 auto Ref = RefIndexForContainer.find(Container.ID);
1599 assert(Ref != RefIndexForContainer.end());
1600 Results.References[Ref->getSecond()].Loc.containerName =
1601 Container.Scope.str() + Container.Name.str();
1602 });
1603 }
1604 }
1605 // Now query the index for references from other files.
1606 auto QueryIndex = [&](llvm::DenseSet<SymbolID> IDs, bool AllowAttributes,
1607 bool AllowMainFileSymbols) {
1608 if (IDs.empty() || !Index || Results.HasMore)
1609 return;
1610 RefsRequest Req;
1611 Req.IDs = std::move(IDs);
1612 if (Limit) {
1613 if (Limit < Results.References.size()) {
1614 // We've already filled our quota, still check the index to correctly
1615 // return the `HasMore` info.
1616 Req.Limit = 0;
1617 } else {
1618 // Query index only for the remaining size.
1619 Req.Limit = Limit - Results.References.size();
1620 }
1621 }
1622 LookupRequest ContainerLookup;
1623 llvm::DenseMap<SymbolID, std::vector<size_t>> RefIndicesForContainer;
1624 Results.HasMore |= Index->refs(Req, [&](const Ref &R) {
1625 auto LSPLoc = toLSPLocation(R.Location, MainFilePath);
1626 // Avoid indexed results for the main file - the AST is authoritative.
1627 if (!LSPLoc ||
1628 (!AllowMainFileSymbols && LSPLoc->uri.file() == MainFilePath))
1629 return;
1631 Result.Loc = {std::move(*LSPLoc), std::nullopt};
1632 if (AllowAttributes) {
1635 // FIXME: our index should definitely store def | decl separately!
1637 Result.Attributes |=
1639 }
1640 if (AddContext) {
1641 SymbolID Container = R.Container;
1642 ContainerLookup.IDs.insert(Container);
1643 RefIndicesForContainer[Container].push_back(Results.References.size());
1644 }
1645 Results.References.push_back(std::move(Result));
1646 });
1647
1648 if (!ContainerLookup.IDs.empty() && AddContext)
1649 Index->lookup(ContainerLookup, [&](const Symbol &Container) {
1650 auto Ref = RefIndicesForContainer.find(Container.ID);
1651 assert(Ref != RefIndicesForContainer.end());
1652 auto ContainerName = Container.Scope.str() + Container.Name.str();
1653 for (auto I : Ref->getSecond()) {
1654 Results.References[I].Loc.containerName = ContainerName;
1655 }
1656 });
1657 };
1658 QueryIndex(std::move(IDsToQuery), /*AllowAttributes=*/true,
1659 /*AllowMainFileSymbols=*/false);
1660 // For a virtual method: Occurrences of BaseMethod should be treated as refs
1661 // and not as decl/def. Allow symbols from main file since AST does not report
1662 // these.
1663 QueryIndex(std::move(OverriddenMethods), /*AllowAttributes=*/false,
1664 /*AllowMainFileSymbols=*/true);
1665 return Results;
1666}
1667
1668std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) {
1669 const SourceManager &SM = AST.getSourceManager();
1670 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1671 if (!CurLoc) {
1672 llvm::consumeError(CurLoc.takeError());
1673 return {};
1674 }
1675 auto MainFilePath = AST.tuPath();
1676 std::vector<SymbolDetails> Results;
1677
1678 // We also want the targets of using-decls, so we include
1679 // DeclRelation::Underlying.
1682 for (const NamedDecl *D : getDeclAtPosition(AST, *CurLoc, Relations)) {
1683 D = getPreferredDecl(D);
1684
1685 SymbolDetails NewSymbol;
1686 std::string QName = printQualifiedName(*D);
1687 auto SplitQName = splitQualifiedName(QName);
1688 NewSymbol.containerName = std::string(SplitQName.first);
1689 NewSymbol.name = std::string(SplitQName.second);
1690
1691 if (NewSymbol.containerName.empty()) {
1692 if (const auto *ParentND =
1693 dyn_cast_or_null<NamedDecl>(D->getDeclContext()))
1694 NewSymbol.containerName = printQualifiedName(*ParentND);
1695 }
1696 llvm::SmallString<32> USR;
1697 if (!index::generateUSRForDecl(D, USR)) {
1698 NewSymbol.USR = std::string(USR);
1699 NewSymbol.ID = SymbolID(NewSymbol.USR);
1700 }
1701 if (const NamedDecl *Def = getDefinition(D))
1702 NewSymbol.definitionRange = makeLocation(
1703 AST.getASTContext(), nameLocation(*Def, SM), MainFilePath);
1704 NewSymbol.declarationRange =
1705 makeLocation(AST.getASTContext(), nameLocation(*D, SM), MainFilePath);
1706
1707 Results.push_back(std::move(NewSymbol));
1708 }
1709
1710 const auto *IdentifierAtCursor =
1711 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
1712 if (!IdentifierAtCursor)
1713 return Results;
1714
1715 if (auto M = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor())) {
1716 SymbolDetails NewMacro;
1717 NewMacro.name = std::string(M->Name);
1718 llvm::SmallString<32> USR;
1719 if (!index::generateUSRForMacro(NewMacro.name, M->Info->getDefinitionLoc(),
1720 SM, USR)) {
1721 NewMacro.USR = std::string(USR);
1722 NewMacro.ID = SymbolID(NewMacro.USR);
1723 }
1724 Results.push_back(std::move(NewMacro));
1725 }
1726
1727 return Results;
1728}
1729
1730llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const LocatedSymbol &S) {
1731 OS << S.Name << ": " << S.PreferredDeclaration;
1732 if (S.Definition)
1733 OS << " def=" << *S.Definition;
1734 return OS;
1735}
1736
1737llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1738 const ReferencesResult::Reference &R) {
1739 OS << R.Loc;
1741 OS << " [decl]";
1743 OS << " [def]";
1745 OS << " [override]";
1746 return OS;
1747}
1748
1749template <typename HierarchyItem>
1750static std::optional<HierarchyItem>
1751declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1752 ASTContext &Ctx = ND.getASTContext();
1753 auto &SM = Ctx.getSourceManager();
1754 SourceLocation NameLoc = nameLocation(ND, Ctx.getSourceManager());
1755 SourceLocation BeginLoc = SM.getFileLoc(ND.getBeginLoc());
1756 SourceLocation EndLoc = SM.getFileLoc(ND.getEndLoc());
1757 const auto DeclRange =
1758 toHalfOpenFileRange(SM, Ctx.getLangOpts(), {BeginLoc, EndLoc});
1759 if (!DeclRange)
1760 return std::nullopt;
1761 const auto FE = SM.getFileEntryRefForID(SM.getFileID(NameLoc));
1762 if (!FE)
1763 return std::nullopt;
1764 auto FilePath = getCanonicalPath(*FE, SM.getFileManager());
1765 if (!FilePath)
1766 return std::nullopt; // Not useful without a uri.
1767
1768 Position NameBegin = sourceLocToPosition(SM, NameLoc);
1769 Position NameEnd = sourceLocToPosition(
1770 SM, Lexer::getLocForEndOfToken(NameLoc, 0, SM, Ctx.getLangOpts()));
1771
1772 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
1773 // FIXME: This is not classifying constructors, destructors and operators
1774 // correctly.
1775 SymbolKind SK = indexSymbolKindToSymbolKind(SymInfo.Kind);
1776
1777 HierarchyItem HI;
1778 HI.name = printName(Ctx, ND);
1779 // FIXME: Populate HI.detail the way we do in symbolToHierarchyItem?
1780 HI.kind = SK;
1781 HI.range = Range{sourceLocToPosition(SM, DeclRange->getBegin()),
1782 sourceLocToPosition(SM, DeclRange->getEnd())};
1783 HI.selectionRange = Range{NameBegin, NameEnd};
1784 if (!HI.range.contains(HI.selectionRange)) {
1785 // 'selectionRange' must be contained in 'range', so in cases where clang
1786 // reports unrelated ranges we need to reconcile somehow.
1787 HI.range = HI.selectionRange;
1788 }
1789
1790 HI.uri = URIForFile::canonicalize(*FilePath, TUPath);
1791
1792 return HI;
1793}
1794
1795static std::optional<TypeHierarchyItem>
1796declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1797 auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
1798 if (Result) {
1799 Result->deprecated = ND.isDeprecated();
1800 // Compute the SymbolID and store it in the 'data' field.
1801 // This allows typeHierarchy/resolve to be used to
1802 // resolve children of items returned in a previous request
1803 // for parents.
1804 Result->data.symbolID = getSymbolID(&ND);
1805 }
1806 return Result;
1807}
1808
1809static std::optional<CallHierarchyItem>
1810declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
1811 auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
1812 if (!Result)
1813 return Result;
1814 if (ND.isDeprecated())
1815 Result->tags.push_back(SymbolTag::Deprecated);
1816 if (auto ID = getSymbolID(&ND))
1817 Result->data = ID.str();
1818 return Result;
1819}
1820
1821template <typename HierarchyItem>
1822static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
1823 PathRef TUPath) {
1824 auto Loc = symbolToLocation(S, TUPath);
1825 if (!Loc) {
1826 elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError());
1827 return std::nullopt;
1828 }
1829 HierarchyItem HI;
1830 HI.name = std::string(S.Name);
1831 HI.detail = (S.Scope + S.Name).str();
1832 HI.kind = indexSymbolKindToSymbolKind(S.SymInfo.Kind);
1833 HI.selectionRange = Loc->range;
1834 // FIXME: Populate 'range' correctly
1835 // (https://github.com/clangd/clangd/issues/59).
1836 HI.range = HI.selectionRange;
1837 HI.uri = Loc->uri;
1838
1839 return HI;
1840}
1841
1842static std::optional<TypeHierarchyItem>
1844 auto Result = symbolToHierarchyItem<TypeHierarchyItem>(S, TUPath);
1845 if (Result) {
1846 Result->deprecated = (S.Flags & Symbol::Deprecated);
1847 Result->data.symbolID = S.ID;
1848 }
1849 return Result;
1850}
1851
1852static std::optional<CallHierarchyItem>
1854 auto Result = symbolToHierarchyItem<CallHierarchyItem>(S, TUPath);
1855 if (!Result)
1856 return Result;
1857 Result->data = S.ID.str();
1858 if (S.Flags & Symbol::Deprecated)
1859 Result->tags.push_back(SymbolTag::Deprecated);
1860 return Result;
1861}
1862
1863static void fillSubTypes(const SymbolID &ID,
1864 std::vector<TypeHierarchyItem> &SubTypes,
1865 const SymbolIndex *Index, int Levels, PathRef TUPath) {
1866 RelationsRequest Req;
1867 Req.Subjects.insert(ID);
1869 Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
1870 if (std::optional<TypeHierarchyItem> ChildSym =
1872 if (Levels > 1) {
1873 ChildSym->children.emplace();
1874 fillSubTypes(Object.ID, *ChildSym->children, Index, Levels - 1, TUPath);
1875 }
1876 SubTypes.emplace_back(std::move(*ChildSym));
1877 }
1878 });
1879}
1880
1881using RecursionProtectionSet = llvm::SmallPtrSet<const CXXRecordDecl *, 4>;
1882
1883// Extracts parents from AST and populates the type hierarchy item.
1884static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath,
1885 TypeHierarchyItem &Item,
1886 RecursionProtectionSet &RPSet) {
1887 Item.parents.emplace();
1888 Item.data.parents.emplace();
1889 // typeParents() will replace dependent template specializations
1890 // with their class template, so to avoid infinite recursion for
1891 // certain types of hierarchies, keep the templates encountered
1892 // along the parent chain in a set, and stop the recursion if one
1893 // starts to repeat.
1894 auto *Pattern = CXXRD.getDescribedTemplate() ? &CXXRD : nullptr;
1895 if (Pattern) {
1896 if (!RPSet.insert(Pattern).second) {
1897 return;
1898 }
1899 }
1900
1901 for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
1902 if (std::optional<TypeHierarchyItem> ParentSym =
1903 declToTypeHierarchyItem(*ParentDecl, TUPath)) {
1904 fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
1905 Item.data.parents->emplace_back(ParentSym->data);
1906 Item.parents->emplace_back(std::move(*ParentSym));
1907 }
1908 }
1909
1910 if (Pattern) {
1911 RPSet.erase(Pattern);
1912 }
1913}
1914
1915std::vector<const CXXRecordDecl *> findRecordTypeAt(ParsedAST &AST,
1916 Position Pos) {
1917 auto RecordFromNode = [&AST](const SelectionTree::Node *N) {
1918 std::vector<const CXXRecordDecl *> Records;
1919 if (!N)
1920 return Records;
1921
1922 // Note: explicitReferenceTargets() will search for both template
1923 // instantiations and template patterns, and prefer the former if available
1924 // (generally, one will be available for non-dependent specializations of a
1925 // class template).
1926 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Underlying,
1927 AST.getHeuristicResolver());
1928 for (const NamedDecl *D : Decls) {
1929
1930 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1931 // If this is a variable, use the type of the variable.
1932 if (const auto *RD = VD->getType().getTypePtr()->getAsCXXRecordDecl())
1933 Records.push_back(RD);
1934 continue;
1935 }
1936
1937 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1938 // If this is a method, use the type of the class.
1939 Records.push_back(Method->getParent());
1940 continue;
1941 }
1942
1943 // We don't handle FieldDecl because it's not clear what behaviour
1944 // the user would expect: the enclosing class type (as with a
1945 // method), or the field's type (as with a variable).
1946
1947 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1948 Records.push_back(RD);
1949 }
1950 return Records;
1951 };
1952
1953 const SourceManager &SM = AST.getSourceManager();
1954 std::vector<const CXXRecordDecl *> Result;
1955 auto Offset = positionToOffset(SM.getBufferData(SM.getMainFileID()), Pos);
1956 if (!Offset) {
1957 llvm::consumeError(Offset.takeError());
1958 return Result;
1959 }
1960 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), *Offset,
1961 *Offset, [&](SelectionTree ST) {
1962 Result = RecordFromNode(ST.commonAncestor());
1963 return !Result.empty();
1964 });
1965 return Result;
1966}
1967
1968// Return the type most associated with an AST node.
1969// This isn't precisely defined: we want "go to type" to do something useful.
1970static QualType typeForNode(const ASTContext &Ctx, const HeuristicResolver *H,
1971 const SelectionTree::Node *N) {
1972 // If we're looking at a namespace qualifier, walk up to what it's qualifying.
1973 // (If we're pointing at a *class* inside a NNS, N will be a TypeLoc).
1974 while (N && N->ASTNode.get<NestedNameSpecifierLoc>())
1975 N = N->Parent;
1976 if (!N)
1977 return QualType();
1978
1979 // If we're pointing at a type => return it.
1980 if (const TypeLoc *TL = N->ASTNode.get<TypeLoc>()) {
1981 if (llvm::isa<DeducedType>(TL->getTypePtr()))
1982 if (auto Deduced = getDeducedType(
1983 N->getDeclContext().getParentASTContext(), H, TL->getBeginLoc()))
1984 return *Deduced;
1985 // Exception: an alias => underlying type.
1986 if (llvm::isa<TypedefType>(TL->getTypePtr()))
1987 return TL->getTypePtr()->getLocallyUnqualifiedSingleStepDesugaredType();
1988 return TL->getType();
1989 }
1990
1991 // Constructor initializers => the type of thing being initialized.
1992 if (const auto *CCI = N->ASTNode.get<CXXCtorInitializer>()) {
1993 if (const FieldDecl *FD = CCI->getAnyMember())
1994 return FD->getType();
1995 if (const Type *Base = CCI->getBaseClass())
1996 return QualType(Base, 0);
1997 }
1998
1999 // Base specifier => the base type.
2000 if (const auto *CBS = N->ASTNode.get<CXXBaseSpecifier>())
2001 return CBS->getType();
2002
2003 if (const Decl *D = N->ASTNode.get<Decl>()) {
2004 struct Visitor : ConstDeclVisitor<Visitor, QualType> {
2005 const ASTContext &Ctx;
2006 Visitor(const ASTContext &Ctx) : Ctx(Ctx) {}
2007
2008 QualType VisitValueDecl(const ValueDecl *D) { return D->getType(); }
2009 // Declaration of a type => that type.
2010 QualType VisitTypeDecl(const TypeDecl *D) {
2011 return Ctx.getTypeDeclType(D);
2012 }
2013 // Exception: alias declaration => the underlying type, not the alias.
2014 QualType VisitTypedefNameDecl(const TypedefNameDecl *D) {
2015 return D->getUnderlyingType();
2016 }
2017 // Look inside templates.
2018 QualType VisitTemplateDecl(const TemplateDecl *D) {
2019 return Visit(D->getTemplatedDecl());
2020 }
2021 } V(Ctx);
2022 return V.Visit(D);
2023 }
2024
2025 if (const Stmt *S = N->ASTNode.get<Stmt>()) {
2026 struct Visitor : ConstStmtVisitor<Visitor, QualType> {
2027 // Null-safe version of visit simplifies recursive calls below.
2028 QualType type(const Stmt *S) { return S ? Visit(S) : QualType(); }
2029
2030 // In general, expressions => type of expression.
2031 QualType VisitExpr(const Expr *S) {
2032 return S->IgnoreImplicitAsWritten()->getType();
2033 }
2034 QualType VisitMemberExpr(const MemberExpr *S) {
2035 // The `foo` in `s.foo()` pretends not to have a real type!
2036 if (S->getType()->isSpecificBuiltinType(BuiltinType::BoundMember))
2037 return Expr::findBoundMemberType(S);
2038 return VisitExpr(S);
2039 }
2040 // Exceptions for void expressions that operate on a type in some way.
2041 QualType VisitCXXDeleteExpr(const CXXDeleteExpr *S) {
2042 return S->getDestroyedType();
2043 }
2044 QualType VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *S) {
2045 return S->getDestroyedType();
2046 }
2047 QualType VisitCXXThrowExpr(const CXXThrowExpr *S) {
2048 return S->getSubExpr()->getType();
2049 }
2050 QualType VisitCoyieldExpr(const CoyieldExpr *S) {
2051 return type(S->getOperand());
2052 }
2053 // Treat a designated initializer like a reference to the field.
2054 QualType VisitDesignatedInitExpr(const DesignatedInitExpr *S) {
2055 // In .foo.bar we want to jump to bar's type, so find *last* field.
2056 for (auto &D : llvm::reverse(S->designators()))
2057 if (D.isFieldDesignator())
2058 if (const auto *FD = D.getFieldDecl())
2059 return FD->getType();
2060 return QualType();
2061 }
2062
2063 // Control flow statements that operate on data: use the data type.
2064 QualType VisitSwitchStmt(const SwitchStmt *S) {
2065 return type(S->getCond());
2066 }
2067 QualType VisitWhileStmt(const WhileStmt *S) { return type(S->getCond()); }
2068 QualType VisitDoStmt(const DoStmt *S) { return type(S->getCond()); }
2069 QualType VisitIfStmt(const IfStmt *S) { return type(S->getCond()); }
2070 QualType VisitCaseStmt(const CaseStmt *S) { return type(S->getLHS()); }
2071 QualType VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2072 return S->getLoopVariable()->getType();
2073 }
2074 QualType VisitReturnStmt(const ReturnStmt *S) {
2075 return type(S->getRetValue());
2076 }
2077 QualType VisitCoreturnStmt(const CoreturnStmt *S) {
2078 return type(S->getOperand());
2079 }
2080 QualType VisitCXXCatchStmt(const CXXCatchStmt *S) {
2081 return S->getCaughtType();
2082 }
2083 QualType VisitObjCAtThrowStmt(const ObjCAtThrowStmt *S) {
2084 return type(S->getThrowExpr());
2085 }
2086 QualType VisitObjCAtCatchStmt(const ObjCAtCatchStmt *S) {
2087 return S->getCatchParamDecl() ? S->getCatchParamDecl()->getType()
2088 : QualType();
2089 }
2090 } V;
2091 return V.Visit(S);
2092 }
2093
2094 return QualType();
2095}
2096
2097// Given a type targeted by the cursor, return one or more types that are more interesting
2098// to target.
2099static void unwrapFindType(
2100 QualType T, const HeuristicResolver* H, llvm::SmallVector<QualType>& Out) {
2101 if (T.isNull())
2102 return;
2103
2104 // If there's a specific type alias, point at that rather than unwrapping.
2105 if (const auto* TDT = T->getAs<TypedefType>())
2106 return Out.push_back(QualType(TDT, 0));
2107
2108 // Pointers etc => pointee type.
2109 if (const auto *PT = T->getAs<PointerType>())
2110 return unwrapFindType(PT->getPointeeType(), H, Out);
2111 if (const auto *RT = T->getAs<ReferenceType>())
2112 return unwrapFindType(RT->getPointeeType(), H, Out);
2113 if (const auto *AT = T->getAsArrayTypeUnsafe())
2114 return unwrapFindType(AT->getElementType(), H, Out);
2115
2116 // Function type => return type.
2117 if (auto *FT = T->getAs<FunctionType>())
2118 return unwrapFindType(FT->getReturnType(), H, Out);
2119 if (auto *CRD = T->getAsCXXRecordDecl()) {
2120 if (CRD->isLambda())
2121 return unwrapFindType(CRD->getLambdaCallOperator()->getReturnType(), H,
2122 Out);
2123 // FIXME: more cases we'd prefer the return type of the call operator?
2124 // std::function etc?
2125 }
2126
2127 // For smart pointer types, add the underlying type
2128 if (H)
2129 if (auto PointeeType = H->getPointeeType(T.getNonReferenceType());
2130 !PointeeType.isNull()) {
2131 unwrapFindType(PointeeType, H, Out);
2132 return Out.push_back(T);
2133 }
2134
2135 return Out.push_back(T);
2136}
2137
2138// Convenience overload, to allow calling this without the out-parameter
2139static llvm::SmallVector<QualType> unwrapFindType(
2140 QualType T, const HeuristicResolver* H) {
2141 llvm::SmallVector<QualType> Result;
2142 unwrapFindType(T, H, Result);
2143 return Result;
2144}
2145
2146std::vector<LocatedSymbol> findType(ParsedAST &AST, Position Pos,
2147 const SymbolIndex *Index) {
2148 const SourceManager &SM = AST.getSourceManager();
2149 auto Offset = positionToOffset(SM.getBufferData(SM.getMainFileID()), Pos);
2150 std::vector<LocatedSymbol> Result;
2151 if (!Offset) {
2152 elog("failed to convert position {0} for findTypes: {1}", Pos,
2153 Offset.takeError());
2154 return Result;
2155 }
2156 // The general scheme is: position -> AST node -> type -> declaration.
2157 auto SymbolsFromNode =
2158 [&](const SelectionTree::Node *N) -> std::vector<LocatedSymbol> {
2159 std::vector<LocatedSymbol> LocatedSymbols;
2160
2161 // NOTE: unwrapFindType might return duplicates for something like
2162 // unique_ptr<unique_ptr<T>>. Let's *not* remove them, because it gives you some
2163 // information about the type you may have not known before
2164 // (since unique_ptr<unique_ptr<T>> != unique_ptr<T>).
2165 for (const QualType &Type : unwrapFindType(
2166 typeForNode(AST.getASTContext(), AST.getHeuristicResolver(), N),
2167 AST.getHeuristicResolver()))
2168 llvm::copy(locateSymbolForType(AST, Type, Index),
2169 std::back_inserter(LocatedSymbols));
2170
2171 return LocatedSymbols;
2172 };
2173 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), *Offset,
2174 *Offset, [&](SelectionTree ST) {
2175 Result = SymbolsFromNode(ST.commonAncestor());
2176 return !Result.empty();
2177 });
2178 return Result;
2179}
2180
2181std::vector<const CXXRecordDecl *> typeParents(const CXXRecordDecl *CXXRD) {
2182 std::vector<const CXXRecordDecl *> Result;
2183
2184 // If this is an invalid instantiation, instantiation of the bases
2185 // may not have succeeded, so fall back to the template pattern.
2186 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
2187 if (CTSD->isInvalidDecl())
2188 CXXRD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
2189 }
2190
2191 // Can't query bases without a definition.
2192 if (!CXXRD->hasDefinition())
2193 return Result;
2194
2195 for (auto Base : CXXRD->bases()) {
2196 const CXXRecordDecl *ParentDecl = nullptr;
2197
2198 const Type *Type = Base.getType().getTypePtr();
2199 if (const RecordType *RT = Type->getAs<RecordType>()) {
2200 ParentDecl = RT->getAsCXXRecordDecl();
2201 }
2202
2203 if (!ParentDecl) {
2204 // Handle a dependent base such as "Base<T>" by using the primary
2205 // template.
2206 if (const TemplateSpecializationType *TS =
2207 Type->getAs<TemplateSpecializationType>()) {
2208 TemplateName TN = TS->getTemplateName();
2209 if (TemplateDecl *TD = TN.getAsTemplateDecl()) {
2210 ParentDecl = dyn_cast<CXXRecordDecl>(TD->getTemplatedDecl());
2211 }
2212 }
2213 }
2214
2215 if (ParentDecl)
2216 Result.push_back(ParentDecl);
2217 }
2218
2219 return Result;
2220}
2221
2222std::vector<TypeHierarchyItem>
2223getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels,
2224 TypeHierarchyDirection Direction, const SymbolIndex *Index,
2225 PathRef TUPath) {
2226 std::vector<TypeHierarchyItem> Results;
2227 for (const auto *CXXRD : findRecordTypeAt(AST, Pos)) {
2228
2229 bool WantChildren = Direction == TypeHierarchyDirection::Children ||
2230 Direction == TypeHierarchyDirection::Both;
2231
2232 // If we're looking for children, we're doing the lookup in the index.
2233 // The index does not store relationships between implicit
2234 // specializations, so if we have one, use the template pattern instead.
2235 // Note that this needs to be done before the declToTypeHierarchyItem(),
2236 // otherwise the type hierarchy item would misleadingly contain the
2237 // specialization parameters, while the children would involve classes
2238 // that derive from other specializations of the template.
2239 if (WantChildren) {
2240 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD))
2241 CXXRD = CTSD->getTemplateInstantiationPattern();
2242 }
2243
2244 std::optional<TypeHierarchyItem> Result =
2245 declToTypeHierarchyItem(*CXXRD, AST.tuPath());
2246 if (!Result)
2247 continue;
2248
2250 fillSuperTypes(*CXXRD, AST.tuPath(), *Result, RPSet);
2251
2252 if (WantChildren && ResolveLevels > 0) {
2253 Result->children.emplace();
2254
2255 if (Index) {
2256 if (auto ID = getSymbolID(CXXRD))
2257 fillSubTypes(ID, *Result->children, Index, ResolveLevels, TUPath);
2258 }
2259 }
2260 Results.emplace_back(std::move(*Result));
2261 }
2262
2263 return Results;
2264}
2265
2266std::optional<std::vector<TypeHierarchyItem>>
2267superTypes(const TypeHierarchyItem &Item, const SymbolIndex *Index) {
2268 std::vector<TypeHierarchyItem> Results;
2269 if (!Item.data.parents)
2270 return std::nullopt;
2271 if (Item.data.parents->empty())
2272 return Results;
2273 LookupRequest Req;
2274 llvm::DenseMap<SymbolID, const TypeHierarchyItem::ResolveParams *> IDToData;
2275 for (const auto &Parent : *Item.data.parents) {
2276 Req.IDs.insert(Parent.symbolID);
2277 IDToData[Parent.symbolID] = &Parent;
2278 }
2279 Index->lookup(Req, [&Item, &Results, &IDToData](const Symbol &S) {
2280 if (auto THI = symbolToTypeHierarchyItem(S, Item.uri.file())) {
2281 THI->data = *IDToData.lookup(S.ID);
2282 Results.emplace_back(std::move(*THI));
2283 }
2284 });
2285 return Results;
2286}
2287
2288std::vector<TypeHierarchyItem> subTypes(const TypeHierarchyItem &Item,
2289 const SymbolIndex *Index) {
2290 std::vector<TypeHierarchyItem> Results;
2291 fillSubTypes(Item.data.symbolID, Results, Index, 1, Item.uri.file());
2292 for (auto &ChildSym : Results)
2293 ChildSym.data.parents = {Item.data};
2294 return Results;
2295}
2296
2297void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels,
2298 TypeHierarchyDirection Direction,
2299 const SymbolIndex *Index) {
2300 // We only support typeHierarchy/resolve for children, because for parents
2301 // we ignore ResolveLevels and return all levels of parents eagerly.
2302 if (!Index || Direction == TypeHierarchyDirection::Parents ||
2303 ResolveLevels == 0)
2304 return;
2305
2306 Item.children.emplace();
2307 fillSubTypes(Item.data.symbolID, *Item.children, Index, ResolveLevels,
2308 Item.uri.file());
2309}
2310
2311std::vector<CallHierarchyItem>
2313 std::vector<CallHierarchyItem> Result;
2314 const auto &SM = AST.getSourceManager();
2315 auto Loc = sourceLocationInMainFile(SM, Pos);
2316 if (!Loc) {
2317 elog("prepareCallHierarchy failed to convert position to source location: "
2318 "{0}",
2319 Loc.takeError());
2320 return Result;
2321 }
2322 for (const NamedDecl *Decl : getDeclAtPosition(AST, *Loc, {})) {
2323 if (!(isa<DeclContext>(Decl) &&
2324 cast<DeclContext>(Decl)->isFunctionOrMethod()) &&
2325 Decl->getKind() != Decl::Kind::FunctionTemplate &&
2326 !(Decl->getKind() == Decl::Kind::Var &&
2327 !cast<VarDecl>(Decl)->isLocalVarDecl()) &&
2328 Decl->getKind() != Decl::Kind::Field &&
2329 Decl->getKind() != Decl::Kind::EnumConstant)
2330 continue;
2331 if (auto CHI = declToCallHierarchyItem(*Decl, AST.tuPath()))
2332 Result.emplace_back(std::move(*CHI));
2333 }
2334 return Result;
2335}
2336
2337std::vector<CallHierarchyIncomingCall>
2338incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
2339 std::vector<CallHierarchyIncomingCall> Results;
2340 if (!Index || Item.data.empty())
2341 return Results;
2342 auto ID = SymbolID::fromStr(Item.data);
2343 if (!ID) {
2344 elog("incomingCalls failed to find symbol: {0}", ID.takeError());
2345 return Results;
2346 }
2347 // In this function, we find incoming calls based on the index only.
2348 // In principle, the AST could have more up-to-date information about
2349 // occurrences within the current file. However, going from a SymbolID
2350 // to an AST node isn't cheap, particularly when the declaration isn't
2351 // in the main file.
2352 // FIXME: Consider also using AST information when feasible.
2353 RefsRequest Request;
2354 Request.IDs.insert(*ID);
2355 Request.WantContainer = true;
2356 // We could restrict more specifically to calls by introducing a new RefKind,
2357 // but non-call references (such as address-of-function) can still be
2358 // interesting as they can indicate indirect calls.
2359 Request.Filter = RefKind::Reference;
2360 // Initially store the ranges in a map keyed by SymbolID of the caller.
2361 // This allows us to group different calls with the same caller
2362 // into the same CallHierarchyIncomingCall.
2363 llvm::DenseMap<SymbolID, std::vector<Location>> CallsIn;
2364 // We can populate the ranges based on a refs request only. As we do so, we
2365 // also accumulate the container IDs into a lookup request.
2366 LookupRequest ContainerLookup;
2367 Index->refs(Request, [&](const Ref &R) {
2368 auto Loc = indexToLSPLocation(R.Location, Item.uri.file());
2369 if (!Loc) {
2370 elog("incomingCalls failed to convert location: {0}", Loc.takeError());
2371 return;
2372 }
2373 CallsIn[R.Container].push_back(*Loc);
2374
2375 ContainerLookup.IDs.insert(R.Container);
2376 });
2377 // Perform the lookup request and combine its results with CallsIn to
2378 // get complete CallHierarchyIncomingCall objects.
2379 Index->lookup(ContainerLookup, [&](const Symbol &Caller) {
2380 auto It = CallsIn.find(Caller.ID);
2381 assert(It != CallsIn.end());
2382 if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) {
2383 std::vector<Range> FromRanges;
2384 for (const Location &L : It->second) {
2385 if (L.uri != CHI->uri) {
2386 // Call location not in same file as caller.
2387 // This can happen in some edge cases. There's not much we can do,
2388 // since the protocol only allows returning ranges interpreted as
2389 // being in the caller's file.
2390 continue;
2391 }
2392 FromRanges.push_back(L.range);
2393 }
2394 Results.push_back(
2395 CallHierarchyIncomingCall{std::move(*CHI), std::move(FromRanges)});
2396 }
2397 });
2398 // Sort results by name of container.
2399 llvm::sort(Results, [](const CallHierarchyIncomingCall &A,
2400 const CallHierarchyIncomingCall &B) {
2401 return A.from.name < B.from.name;
2402 });
2403 return Results;
2404}
2405
2406std::vector<CallHierarchyOutgoingCall>
2407outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) {
2408 std::vector<CallHierarchyOutgoingCall> Results;
2409 if (!Index || Item.data.empty())
2410 return Results;
2411 auto ID = SymbolID::fromStr(Item.data);
2412 if (!ID) {
2413 elog("outgoingCalls failed to find symbol: {0}", ID.takeError());
2414 return Results;
2415 }
2416 // In this function, we find outgoing calls based on the index only.
2417 ContainedRefsRequest Request;
2418 Request.ID = *ID;
2419 // Initially store the ranges in a map keyed by SymbolID of the callee.
2420 // This allows us to group different calls to the same function
2421 // into the same CallHierarchyOutgoingCall.
2422 llvm::DenseMap<SymbolID, std::vector<Location>> CallsOut;
2423 // We can populate the ranges based on a refs request only. As we do so, we
2424 // also accumulate the callee IDs into a lookup request.
2425 LookupRequest CallsOutLookup;
2426 Index->containedRefs(Request, [&](const auto &R) {
2427 auto Loc = indexToLSPLocation(R.Location, Item.uri.file());
2428 if (!Loc) {
2429 elog("outgoingCalls failed to convert location: {0}", Loc.takeError());
2430 return;
2431 }
2432 auto It = CallsOut.try_emplace(R.Symbol, std::vector<Location>{}).first;
2433 It->second.push_back(*Loc);
2434
2435 CallsOutLookup.IDs.insert(R.Symbol);
2436 });
2437 // Perform the lookup request and combine its results with CallsOut to
2438 // get complete CallHierarchyOutgoingCall objects.
2439 Index->lookup(CallsOutLookup, [&](const Symbol &Callee) {
2440 // The containedRefs request should only return symbols which are
2441 // function-like, i.e. symbols for which references to them can be "calls".
2442 using SK = index::SymbolKind;
2443 auto Kind = Callee.SymInfo.Kind;
2444 assert(Kind == SK::Function || Kind == SK::InstanceMethod ||
2445 Kind == SK::ClassMethod || Kind == SK::StaticMethod ||
2446 Kind == SK::Constructor || Kind == SK::Destructor ||
2447 Kind == SK::ConversionFunction);
2448 (void)Kind;
2449 (void)SK::Function;
2450
2451 auto It = CallsOut.find(Callee.ID);
2452 assert(It != CallsOut.end());
2453 if (auto CHI = symbolToCallHierarchyItem(Callee, Item.uri.file())) {
2454 std::vector<Range> FromRanges;
2455 for (const Location &L : It->second) {
2456 if (L.uri != Item.uri) {
2457 // Call location not in same file as the item that outgoingCalls was
2458 // requested for. This can happen when Item is a declaration separate
2459 // from the implementation. There's not much we can do, since the
2460 // protocol only allows returning ranges interpreted as being in
2461 // Item's file.
2462 continue;
2463 }
2464 FromRanges.push_back(L.range);
2465 }
2466 Results.push_back(
2467 CallHierarchyOutgoingCall{std::move(*CHI), std::move(FromRanges)});
2468 }
2469 });
2470 // Sort results by name of the callee.
2471 llvm::sort(Results, [](const CallHierarchyOutgoingCall &A,
2472 const CallHierarchyOutgoingCall &B) {
2473 return A.to.name < B.to.name;
2474 });
2475 return Results;
2476}
2477
2478llvm::DenseSet<const Decl *> getNonLocalDeclRefs(ParsedAST &AST,
2479 const FunctionDecl *FD) {
2480 if (!FD->hasBody())
2481 return {};
2482 llvm::DenseSet<const Decl *> DeclRefs;
2484 FD,
2485 [&](ReferenceLoc Ref) {
2486 for (const Decl *D : Ref.Targets) {
2487 if (!index::isFunctionLocalSymbol(D) && !D->isTemplateParameter() &&
2488 !Ref.IsDecl)
2489 DeclRefs.insert(D);
2490 }
2491 },
2492 AST.getHeuristicResolver());
2493 return DeclRefs;
2494}
2495
2496} // namespace clangd
2497} // 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.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:45
std::vector< TypeHierarchyItem > subTypes(const TypeHierarchyItem &Item, const SymbolIndex *Index)
Returns direct children of a TypeHierarchyItem.
Definition XRefs.cpp:2288
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:2267
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:2338
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
static std::optional< TypeHierarchyItem > symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath)
Definition XRefs.cpp:1843
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:1853
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:248
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:1279
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:240
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition XRefs.cpp:1668
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:197
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:2146
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:1970
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:2223
static std::optional< TypeHierarchyItem > declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath)
Definition XRefs.cpp:1796
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition AST.cpp:623
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:1445
static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath, TypeHierarchyItem &Item, RecursionProtectionSet &RPSet)
Definition XRefs.cpp:1884
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:1751
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:2099
static std::optional< HierarchyItem > symbolToHierarchyItem(const Symbol &S, PathRef TUPath)
Definition XRefs.cpp:1822
const syntax::Token * findNearbyIdentifier(const SpelledWord &Word, const syntax::TokenBuffer &TB)
Definition XRefs.cpp:685
llvm::SmallPtrSet< const CXXRecordDecl *, 4 > RecursionProtectionSet
Definition XRefs.cpp:1881
static void fillSubTypes(const SymbolID &ID, std::vector< TypeHierarchyItem > &SubTypes, const SymbolIndex *Index, int Levels, PathRef TUPath)
Definition XRefs.cpp:1863
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:1672
std::vector< LocatedSymbol > findImplementations(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns implementations at a specified Pos:
Definition XRefs.cpp:1320
const ObjCImplDecl * getCorrespondingObjCImpl(const ObjCContainerDecl *D)
Return the corresponding implementation/definition for the given ObjC container if it has one,...
Definition AST.cpp:371
void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index)
Definition XRefs.cpp:2297
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:2478
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:207
std::vector< CallHierarchyOutgoingCall > outgoingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index)
Definition XRefs.cpp:2407
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:1810
std::vector< const CXXRecordDecl * > findRecordTypeAt(ParsedAST &AST, Position Pos)
Find the record types referenced at Pos.
Definition XRefs.cpp:1915
std::vector< CallHierarchyItem > prepareCallHierarchy(ParsedAST &AST, Position Pos, PathRef TUPath)
Get call hierarchy information at Pos.
Definition XRefs.cpp:2312
std::vector< const CXXRecordDecl * > typeParents(const CXXRecordDecl *CXXRD)
Given a record type declaration, find its base (parent) types.
Definition XRefs.cpp:2181
SymbolKind
A symbol kind.
Definition Protocol.h:380
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccess 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
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:1642
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