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 "CodeCompletionStrings.h" 11 #include "FindSymbols.h" 12 #include "FindTarget.h" 13 #include "ParsedAST.h" 14 #include "Protocol.h" 15 #include "Quality.h" 16 #include "Selection.h" 17 #include "SourceCode.h" 18 #include "URI.h" 19 #include "index/Index.h" 20 #include "index/Merge.h" 21 #include "index/Relation.h" 22 #include "index/SymbolLocation.h" 23 #include "support/Logger.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/ASTTypeTraits.h" 26 #include "clang/AST/Attr.h" 27 #include "clang/AST/Attrs.inc" 28 #include "clang/AST/Decl.h" 29 #include "clang/AST/DeclCXX.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/Type.h" 33 #include "clang/Basic/CharInfo.h" 34 #include "clang/Basic/LLVM.h" 35 #include "clang/Basic/LangOptions.h" 36 #include "clang/Basic/SourceLocation.h" 37 #include "clang/Basic/SourceManager.h" 38 #include "clang/Basic/TokenKinds.h" 39 #include "clang/Index/IndexDataConsumer.h" 40 #include "clang/Index/IndexSymbol.h" 41 #include "clang/Index/IndexingAction.h" 42 #include "clang/Index/IndexingOptions.h" 43 #include "clang/Index/USRGeneration.h" 44 #include "clang/Tooling/Syntax/Tokens.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/None.h" 47 #include "llvm/ADT/STLExtras.h" 48 #include "llvm/ADT/SmallSet.h" 49 #include "llvm/ADT/StringExtras.h" 50 #include "llvm/ADT/StringRef.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/Error.h" 53 #include "llvm/Support/MathExtras.h" 54 #include "llvm/Support/Path.h" 55 #include "llvm/Support/raw_ostream.h" 56 57 namespace clang { 58 namespace clangd { 59 namespace { 60 61 // Returns the single definition of the entity declared by D, if visible. 62 // In particular: 63 // - for non-redeclarable kinds (e.g. local vars), return D 64 // - for kinds that allow multiple definitions (e.g. namespaces), return nullptr 65 // Kinds of nodes that always return nullptr here will not have definitions 66 // reported by locateSymbolAt(). 67 const NamedDecl *getDefinition(const NamedDecl *D) { 68 assert(D); 69 // Decl has one definition that we can find. 70 if (const auto *TD = dyn_cast<TagDecl>(D)) 71 return TD->getDefinition(); 72 if (const auto *VD = dyn_cast<VarDecl>(D)) 73 return VD->getDefinition(); 74 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 75 return FD->getDefinition(); 76 // Only a single declaration is allowed. 77 if (isa<ValueDecl>(D) || isa<TemplateTypeParmDecl>(D) || 78 isa<TemplateTemplateParmDecl>(D)) // except cases above 79 return D; 80 // Multiple definitions are allowed. 81 return nullptr; // except cases above 82 } 83 84 void logIfOverflow(const SymbolLocation &Loc) { 85 if (Loc.Start.hasOverflow() || Loc.End.hasOverflow()) 86 log("Possible overflow in symbol location: {0}", Loc); 87 } 88 89 // Convert a SymbolLocation to LSP's Location. 90 // TUPath is used to resolve the path of URI. 91 // FIXME: figure out a good home for it, and share the implementation with 92 // FindSymbols. 93 llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc, 94 llvm::StringRef TUPath) { 95 if (!Loc) 96 return None; 97 auto Uri = URI::parse(Loc.FileURI); 98 if (!Uri) { 99 elog("Could not parse URI {0}: {1}", Loc.FileURI, Uri.takeError()); 100 return None; 101 } 102 auto U = URIForFile::fromURI(*Uri, TUPath); 103 if (!U) { 104 elog("Could not resolve URI {0}: {1}", Loc.FileURI, U.takeError()); 105 return None; 106 } 107 108 Location LSPLoc; 109 LSPLoc.uri = std::move(*U); 110 LSPLoc.range.start.line = Loc.Start.line(); 111 LSPLoc.range.start.character = Loc.Start.column(); 112 LSPLoc.range.end.line = Loc.End.line(); 113 LSPLoc.range.end.character = Loc.End.column(); 114 logIfOverflow(Loc); 115 return LSPLoc; 116 } 117 118 SymbolLocation toIndexLocation(const Location &Loc, std::string &URIStorage) { 119 SymbolLocation SymLoc; 120 URIStorage = Loc.uri.uri(); 121 SymLoc.FileURI = URIStorage.c_str(); 122 SymLoc.Start.setLine(Loc.range.start.line); 123 SymLoc.Start.setColumn(Loc.range.start.character); 124 SymLoc.End.setLine(Loc.range.end.line); 125 SymLoc.End.setColumn(Loc.range.end.character); 126 return SymLoc; 127 } 128 129 // Returns the preferred location between an AST location and an index location. 130 SymbolLocation getPreferredLocation(const Location &ASTLoc, 131 const SymbolLocation &IdxLoc, 132 std::string &Scratch) { 133 // Also use a dummy symbol for the index location so that other fields (e.g. 134 // definition) are not factored into the preference. 135 Symbol ASTSym, IdxSym; 136 ASTSym.ID = IdxSym.ID = SymbolID("dummy_id"); 137 ASTSym.CanonicalDeclaration = toIndexLocation(ASTLoc, Scratch); 138 IdxSym.CanonicalDeclaration = IdxLoc; 139 auto Merged = mergeSymbol(ASTSym, IdxSym); 140 return Merged.CanonicalDeclaration; 141 } 142 143 std::vector<const NamedDecl *> 144 getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations, 145 ASTNodeKind *NodeKind = nullptr) { 146 unsigned Offset = AST.getSourceManager().getDecomposedSpellingLoc(Pos).second; 147 std::vector<const NamedDecl *> Result; 148 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset, 149 Offset, [&](SelectionTree ST) { 150 if (const SelectionTree::Node *N = 151 ST.commonAncestor()) { 152 if (NodeKind) 153 *NodeKind = N->ASTNode.getNodeKind(); 154 llvm::copy(targetDecl(N->ASTNode, Relations), 155 std::back_inserter(Result)); 156 } 157 return !Result.empty(); 158 }); 159 return Result; 160 } 161 162 // Expects Loc to be a SpellingLocation, will bail out otherwise as it can't 163 // figure out a filename. 164 llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc, 165 llvm::StringRef TUPath) { 166 const auto &SM = AST.getSourceManager(); 167 const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc)); 168 if (!F) 169 return None; 170 auto FilePath = getCanonicalPath(F, SM); 171 if (!FilePath) { 172 log("failed to get path!"); 173 return None; 174 } 175 Location L; 176 L.uri = URIForFile::canonicalize(*FilePath, TUPath); 177 // We call MeasureTokenLength here as TokenBuffer doesn't store spelled tokens 178 // outside the main file. 179 auto TokLen = Lexer::MeasureTokenLength(Loc, SM, AST.getLangOpts()); 180 L.range = halfOpenToRange( 181 SM, CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(TokLen))); 182 return L; 183 } 184 185 // Treat #included files as symbols, to enable go-to-definition on them. 186 llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos, 187 ParsedAST &AST, 188 llvm::StringRef MainFilePath) { 189 for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) { 190 if (!Inc.Resolved.empty() && Inc.R.start.line == Pos.line) { 191 LocatedSymbol File; 192 File.Name = std::string(llvm::sys::path::filename(Inc.Resolved)); 193 File.PreferredDeclaration = { 194 URIForFile::canonicalize(Inc.Resolved, MainFilePath), Range{}}; 195 File.Definition = File.PreferredDeclaration; 196 // We're not going to find any further symbols on #include lines. 197 return File; 198 } 199 } 200 return llvm::None; 201 } 202 203 // Macros are simple: there's no declaration/definition distinction. 204 // As a consequence, there's no need to look them up in the index either. 205 llvm::Optional<LocatedSymbol> 206 locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST, 207 llvm::StringRef MainFilePath) { 208 if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) { 209 if (auto Loc = makeLocation(AST.getASTContext(), 210 M->Info->getDefinitionLoc(), MainFilePath)) { 211 LocatedSymbol Macro; 212 Macro.Name = std::string(M->Name); 213 Macro.PreferredDeclaration = *Loc; 214 Macro.Definition = Loc; 215 return Macro; 216 } 217 } 218 return llvm::None; 219 } 220 221 // Decls are more complicated. 222 // The AST contains at least a declaration, maybe a definition. 223 // These are up-to-date, and so generally preferred over index results. 224 // We perform a single batch index lookup to find additional definitions. 225 std::vector<LocatedSymbol> 226 locateASTReferent(SourceLocation CurLoc, const syntax::Token *TouchedIdentifier, 227 ParsedAST &AST, llvm::StringRef MainFilePath, 228 const SymbolIndex *Index, ASTNodeKind *NodeKind) { 229 const SourceManager &SM = AST.getSourceManager(); 230 // Results follow the order of Symbols.Decls. 231 std::vector<LocatedSymbol> Result; 232 // Keep track of SymbolID -> index mapping, to fill in index data later. 233 llvm::DenseMap<SymbolID, size_t> ResultIndex; 234 235 auto AddResultDecl = [&](const NamedDecl *D) { 236 D = llvm::cast<NamedDecl>(D->getCanonicalDecl()); 237 auto Loc = 238 makeLocation(AST.getASTContext(), nameLocation(*D, SM), MainFilePath); 239 if (!Loc) 240 return; 241 242 Result.emplace_back(); 243 Result.back().Name = printName(AST.getASTContext(), *D); 244 Result.back().PreferredDeclaration = *Loc; 245 if (const NamedDecl *Def = getDefinition(D)) 246 Result.back().Definition = makeLocation( 247 AST.getASTContext(), nameLocation(*Def, SM), MainFilePath); 248 249 // Record SymbolID for index lookup later. 250 if (auto ID = getSymbolID(D)) 251 ResultIndex[*ID] = Result.size() - 1; 252 }; 253 254 // Emit all symbol locations (declaration or definition) from AST. 255 DeclRelationSet Relations = 256 DeclRelation::TemplatePattern | DeclRelation::Alias; 257 for (const NamedDecl *D : 258 getDeclAtPosition(AST, CurLoc, Relations, NodeKind)) { 259 // Special case: void foo() ^override: jump to the overridden method. 260 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) { 261 const InheritableAttr *Attr = D->getAttr<OverrideAttr>(); 262 if (!Attr) 263 Attr = D->getAttr<FinalAttr>(); 264 if (Attr && TouchedIdentifier && 265 SM.getSpellingLoc(Attr->getLocation()) == 266 TouchedIdentifier->location()) { 267 // We may be overridding multiple methods - offer them all. 268 for (const NamedDecl *ND : CMD->overridden_methods()) 269 AddResultDecl(ND); 270 continue; 271 } 272 } 273 274 // Special case: the point of declaration of a template specialization, 275 // it's more useful to navigate to the template declaration. 276 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 277 if (TouchedIdentifier && 278 D->getLocation() == TouchedIdentifier->location()) { 279 AddResultDecl(CTSD->getSpecializedTemplate()); 280 continue; 281 } 282 } 283 284 // Otherwise the target declaration is the right one. 285 AddResultDecl(D); 286 } 287 288 // Now query the index for all Symbol IDs we found in the AST. 289 if (Index && !ResultIndex.empty()) { 290 LookupRequest QueryRequest; 291 for (auto It : ResultIndex) 292 QueryRequest.IDs.insert(It.first); 293 std::string Scratch; 294 Index->lookup(QueryRequest, [&](const Symbol &Sym) { 295 auto &R = Result[ResultIndex.lookup(Sym.ID)]; 296 297 if (R.Definition) { // from AST 298 // Special case: if the AST yielded a definition, then it may not be 299 // the right *declaration*. Prefer the one from the index. 300 if (auto Loc = toLSPLocation(Sym.CanonicalDeclaration, MainFilePath)) 301 R.PreferredDeclaration = *Loc; 302 303 // We might still prefer the definition from the index, e.g. for 304 // generated symbols. 305 if (auto Loc = toLSPLocation( 306 getPreferredLocation(*R.Definition, Sym.Definition, Scratch), 307 MainFilePath)) 308 R.Definition = *Loc; 309 } else { 310 R.Definition = toLSPLocation(Sym.Definition, MainFilePath); 311 312 // Use merge logic to choose AST or index declaration. 313 if (auto Loc = toLSPLocation( 314 getPreferredLocation(R.PreferredDeclaration, 315 Sym.CanonicalDeclaration, Scratch), 316 MainFilePath)) 317 R.PreferredDeclaration = *Loc; 318 } 319 }); 320 } 321 322 return Result; 323 } 324 325 bool tokenSpelledAt(SourceLocation SpellingLoc, const syntax::TokenBuffer &TB) { 326 auto ExpandedTokens = TB.expandedTokens( 327 TB.sourceManager().getMacroArgExpandedLocation(SpellingLoc)); 328 return !ExpandedTokens.empty(); 329 } 330 331 llvm::StringRef sourcePrefix(SourceLocation Loc, const SourceManager &SM) { 332 auto D = SM.getDecomposedLoc(Loc); 333 bool Invalid = false; 334 llvm::StringRef Buf = SM.getBufferData(D.first, &Invalid); 335 if (Invalid || D.second > Buf.size()) 336 return ""; 337 return Buf.substr(0, D.second); 338 } 339 340 bool isDependentName(ASTNodeKind NodeKind) { 341 return NodeKind.isSame(ASTNodeKind::getFromNodeKind<OverloadExpr>()) || 342 NodeKind.isSame( 343 ASTNodeKind::getFromNodeKind<CXXDependentScopeMemberExpr>()) || 344 NodeKind.isSame( 345 ASTNodeKind::getFromNodeKind<DependentScopeDeclRefExpr>()); 346 } 347 348 } // namespace 349 350 std::vector<LocatedSymbol> 351 locateSymbolTextually(const SpelledWord &Word, ParsedAST &AST, 352 const SymbolIndex *Index, const std::string &MainFilePath, 353 ASTNodeKind NodeKind) { 354 // Don't use heuristics if this is a real identifier, or not an 355 // identifier. 356 // Exception: dependent names, because those may have useful textual 357 // matches that AST-based heuristics cannot find. 358 if ((Word.ExpandedToken && !isDependentName(NodeKind)) || 359 !Word.LikelyIdentifier || !Index) 360 return {}; 361 // We don't want to handle words in string literals. It'd be nice to whitelist 362 // comments instead, but they're not retained in TokenBuffer. 363 if (Word.PartOfSpelledToken && 364 isStringLiteral(Word.PartOfSpelledToken->kind())) 365 return {}; 366 367 const auto &SM = AST.getSourceManager(); 368 // Look up the selected word in the index. 369 FuzzyFindRequest Req; 370 Req.Query = Word.Text.str(); 371 Req.ProximityPaths = {MainFilePath}; 372 // Find the namespaces to query by lexing the file. 373 Req.Scopes = 374 visibleNamespaces(sourcePrefix(Word.Location, SM), AST.getLangOpts()); 375 // FIXME: For extra strictness, consider AnyScope=false. 376 Req.AnyScope = true; 377 // We limit the results to 3 further below. This limit is to avoid fetching 378 // too much data, while still likely having enough for 3 results to remain 379 // after additional filtering. 380 Req.Limit = 10; 381 bool TooMany = false; 382 using ScoredLocatedSymbol = std::pair<float, LocatedSymbol>; 383 std::vector<ScoredLocatedSymbol> ScoredResults; 384 Index->fuzzyFind(Req, [&](const Symbol &Sym) { 385 // Only consider exact name matches, including case. 386 // This is to avoid too many false positives. 387 // We could relax this in the future (e.g. to allow for typos) if we make 388 // the query more accurate by other means. 389 if (Sym.Name != Word.Text) 390 return; 391 392 // Exclude constructor results. They have the same name as the class, 393 // but we don't have enough context to prefer them over the class. 394 if (Sym.SymInfo.Kind == index::SymbolKind::Constructor) 395 return; 396 397 auto MaybeDeclLoc = 398 indexToLSPLocation(Sym.CanonicalDeclaration, MainFilePath); 399 if (!MaybeDeclLoc) { 400 log("locateSymbolNamedTextuallyAt: {0}", MaybeDeclLoc.takeError()); 401 return; 402 } 403 Location DeclLoc = *MaybeDeclLoc; 404 Location DefLoc; 405 if (Sym.Definition) { 406 auto MaybeDefLoc = indexToLSPLocation(Sym.Definition, MainFilePath); 407 if (!MaybeDefLoc) { 408 log("locateSymbolNamedTextuallyAt: {0}", MaybeDefLoc.takeError()); 409 return; 410 } 411 DefLoc = *MaybeDefLoc; 412 } 413 414 if (ScoredResults.size() >= 3) { 415 // If we have more than 3 results, don't return anything, 416 // as confidence is too low. 417 // FIXME: Alternatively, try a stricter query? 418 TooMany = true; 419 return; 420 } 421 422 LocatedSymbol Located; 423 Located.Name = (Sym.Name + Sym.TemplateSpecializationArgs).str(); 424 Located.PreferredDeclaration = bool(Sym.Definition) ? DefLoc : DeclLoc; 425 Located.Definition = DefLoc; 426 427 SymbolQualitySignals Quality; 428 Quality.merge(Sym); 429 SymbolRelevanceSignals Relevance; 430 Relevance.Name = Sym.Name; 431 Relevance.Query = SymbolRelevanceSignals::Generic; 432 Relevance.merge(Sym); 433 auto Score = 434 evaluateSymbolAndRelevance(Quality.evaluate(), Relevance.evaluate()); 435 dlog("locateSymbolNamedTextuallyAt: {0}{1} = {2}\n{3}{4}\n", Sym.Scope, 436 Sym.Name, Score, Quality, Relevance); 437 438 ScoredResults.push_back({Score, std::move(Located)}); 439 }); 440 441 if (TooMany) 442 return {}; 443 444 llvm::sort(ScoredResults, 445 [](const ScoredLocatedSymbol &A, const ScoredLocatedSymbol &B) { 446 return A.first > B.first; 447 }); 448 std::vector<LocatedSymbol> Results; 449 for (auto &Res : std::move(ScoredResults)) 450 Results.push_back(std::move(Res.second)); 451 return Results; 452 } 453 454 const syntax::Token *findNearbyIdentifier(const SpelledWord &Word, 455 const syntax::TokenBuffer &TB) { 456 // Don't use heuristics if this is a real identifier. 457 // Unlikely identifiers are OK if they were used as identifiers nearby. 458 if (Word.ExpandedToken) 459 return nullptr; 460 // We don't want to handle words in string literals. It'd be nice to whitelist 461 // comments instead, but they're not retained in TokenBuffer. 462 if (Word.PartOfSpelledToken && 463 isStringLiteral(Word.PartOfSpelledToken->kind())) 464 return {}; 465 466 const SourceManager &SM = TB.sourceManager(); 467 // We prefer the closest possible token, line-wise. Backwards is penalized. 468 // Ties are implicitly broken by traversal order (first-one-wins). 469 auto File = SM.getFileID(Word.Location); 470 unsigned WordLine = SM.getSpellingLineNumber(Word.Location); 471 auto Cost = [&](SourceLocation Loc) -> unsigned { 472 assert(SM.getFileID(Loc) == File && "spelled token in wrong file?"); 473 unsigned Line = SM.getSpellingLineNumber(Loc); 474 if (Line > WordLine) 475 return 1 + llvm::Log2_64(Line - WordLine); 476 if (Line < WordLine) 477 return 2 + llvm::Log2_64(WordLine - Line); 478 return 0; 479 }; 480 const syntax::Token *BestTok = nullptr; 481 // Search bounds are based on word length: 2^N lines forward. 482 unsigned BestCost = Word.Text.size() + 1; 483 484 // Updates BestTok and BestCost if Tok is a good candidate. 485 // May return true if the cost is too high for this token. 486 auto Consider = [&](const syntax::Token &Tok) { 487 if (!(Tok.kind() == tok::identifier && Tok.text(SM) == Word.Text)) 488 return false; 489 // No point guessing the same location we started with. 490 if (Tok.location() == Word.Location) 491 return false; 492 // We've done cheap checks, compute cost so we can break the caller's loop. 493 unsigned TokCost = Cost(Tok.location()); 494 if (TokCost >= BestCost) 495 return true; // causes the outer loop to break. 496 // Allow locations that might be part of the AST, and macros (even if empty) 497 // but not things like disabled preprocessor sections. 498 if (!(tokenSpelledAt(Tok.location(), TB) || TB.expansionStartingAt(&Tok))) 499 return false; 500 // We already verified this token is an improvement. 501 BestCost = TokCost; 502 BestTok = &Tok; 503 return false; 504 }; 505 auto SpelledTokens = TB.spelledTokens(File); 506 // Find where the word occurred in the token stream, to search forward & back. 507 auto *I = llvm::partition_point(SpelledTokens, [&](const syntax::Token &T) { 508 assert(SM.getFileID(T.location()) == SM.getFileID(Word.Location)); 509 return T.location() >= Word.Location; // Comparison OK: same file. 510 }); 511 // Search for matches after the cursor. 512 for (const syntax::Token &Tok : llvm::makeArrayRef(I, SpelledTokens.end())) 513 if (Consider(Tok)) 514 break; // costs of later tokens are greater... 515 // Search for matches before the cursor. 516 for (const syntax::Token &Tok : 517 llvm::reverse(llvm::makeArrayRef(SpelledTokens.begin(), I))) 518 if (Consider(Tok)) 519 break; 520 521 if (BestTok) 522 vlog( 523 "Word {0} under cursor {1} isn't a token (after PP), trying nearby {2}", 524 Word.Text, Word.Location.printToString(SM), 525 BestTok->location().printToString(SM)); 526 527 return BestTok; 528 } 529 530 std::vector<LocatedSymbol> locateSymbolAt(ParsedAST &AST, Position Pos, 531 const SymbolIndex *Index) { 532 const auto &SM = AST.getSourceManager(); 533 auto MainFilePath = 534 getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM); 535 if (!MainFilePath) { 536 elog("Failed to get a path for the main file, so no references"); 537 return {}; 538 } 539 540 if (auto File = locateFileReferent(Pos, AST, *MainFilePath)) 541 return {std::move(*File)}; 542 543 auto CurLoc = sourceLocationInMainFile(SM, Pos); 544 if (!CurLoc) { 545 elog("locateSymbolAt failed to convert position to source location: {0}", 546 CurLoc.takeError()); 547 return {}; 548 } 549 550 const syntax::Token *TouchedIdentifier = 551 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens()); 552 if (TouchedIdentifier) 553 if (auto Macro = 554 locateMacroReferent(*TouchedIdentifier, AST, *MainFilePath)) 555 // Don't look at the AST or index if we have a macro result. 556 // (We'd just return declarations referenced from the macro's 557 // expansion.) 558 return {*std::move(Macro)}; 559 560 ASTNodeKind NodeKind; 561 auto ASTResults = locateASTReferent(*CurLoc, TouchedIdentifier, AST, 562 *MainFilePath, Index, &NodeKind); 563 if (!ASTResults.empty()) 564 return ASTResults; 565 566 // If the cursor can't be resolved directly, try fallback strategies. 567 auto Word = 568 SpelledWord::touching(*CurLoc, AST.getTokens(), AST.getLangOpts()); 569 if (Word) { 570 // Is the same word nearby a real identifier that might refer to something? 571 if (const syntax::Token *NearbyIdent = 572 findNearbyIdentifier(*Word, AST.getTokens())) { 573 if (auto Macro = locateMacroReferent(*NearbyIdent, AST, *MainFilePath)) 574 return {*std::move(Macro)}; 575 ASTResults = 576 locateASTReferent(NearbyIdent->location(), NearbyIdent, AST, 577 *MainFilePath, Index, /*NodeKind=*/nullptr); 578 if (!ASTResults.empty()) 579 return ASTResults; 580 } 581 // No nearby word, or it didn't refer to anything either. Try the index. 582 auto TextualResults = 583 locateSymbolTextually(*Word, AST, Index, *MainFilePath, NodeKind); 584 if (!TextualResults.empty()) 585 return TextualResults; 586 } 587 588 return {}; 589 } 590 591 std::vector<DocumentLink> getDocumentLinks(ParsedAST &AST) { 592 const auto &SM = AST.getSourceManager(); 593 auto MainFilePath = 594 getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM); 595 if (!MainFilePath) { 596 elog("Failed to get a path for the main file, so no links"); 597 return {}; 598 } 599 600 std::vector<DocumentLink> Result; 601 for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) { 602 if (!Inc.Resolved.empty()) { 603 Result.push_back(DocumentLink( 604 {Inc.R, URIForFile::canonicalize(Inc.Resolved, *MainFilePath)})); 605 } 606 } 607 608 return Result; 609 } 610 611 namespace { 612 613 /// Collects references to symbols within the main file. 614 class ReferenceFinder : public index::IndexDataConsumer { 615 public: 616 struct Reference { 617 syntax::Token SpelledTok; 618 index::SymbolRoleSet Role; 619 620 Range range(const SourceManager &SM) const { 621 return halfOpenToRange(SM, SpelledTok.range(SM).toCharRange(SM)); 622 } 623 }; 624 625 ReferenceFinder(const ParsedAST &AST, 626 const std::vector<const NamedDecl *> &TargetDecls) 627 : AST(AST) { 628 for (const NamedDecl *D : TargetDecls) 629 CanonicalTargets.insert(D->getCanonicalDecl()); 630 } 631 632 std::vector<Reference> take() && { 633 llvm::sort(References, [](const Reference &L, const Reference &R) { 634 auto LTok = L.SpelledTok.location(); 635 auto RTok = R.SpelledTok.location(); 636 return std::tie(LTok, L.Role) < std::tie(RTok, R.Role); 637 }); 638 // We sometimes see duplicates when parts of the AST get traversed twice. 639 References.erase(std::unique(References.begin(), References.end(), 640 [](const Reference &L, const Reference &R) { 641 auto LTok = L.SpelledTok.location(); 642 auto RTok = R.SpelledTok.location(); 643 return std::tie(LTok, L.Role) == 644 std::tie(RTok, R.Role); 645 }), 646 References.end()); 647 return std::move(References); 648 } 649 650 bool 651 handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles, 652 llvm::ArrayRef<index::SymbolRelation> Relations, 653 SourceLocation Loc, 654 index::IndexDataConsumer::ASTNodeInfo ASTNode) override { 655 assert(D->isCanonicalDecl() && "expect D to be a canonical declaration"); 656 const SourceManager &SM = AST.getSourceManager(); 657 if (!CanonicalTargets.count(D) || !isInsideMainFile(Loc, SM)) 658 return true; 659 const auto &TB = AST.getTokens(); 660 Loc = SM.getFileLoc(Loc); 661 if (const auto *Tok = TB.spelledTokenAt(Loc)) 662 References.push_back({*Tok, Roles}); 663 return true; 664 } 665 666 private: 667 llvm::SmallSet<const Decl *, 4> CanonicalTargets; 668 std::vector<Reference> References; 669 const ParsedAST &AST; 670 }; 671 672 std::vector<ReferenceFinder::Reference> 673 findRefs(const std::vector<const NamedDecl *> &Decls, ParsedAST &AST) { 674 ReferenceFinder RefFinder(AST, Decls); 675 index::IndexingOptions IndexOpts; 676 IndexOpts.SystemSymbolFilter = 677 index::IndexingOptions::SystemSymbolFilterKind::All; 678 IndexOpts.IndexFunctionLocals = true; 679 IndexOpts.IndexParametersInDeclarations = true; 680 IndexOpts.IndexTemplateParameters = true; 681 indexTopLevelDecls(AST.getASTContext(), AST.getPreprocessor(), 682 AST.getLocalTopLevelDecls(), RefFinder, IndexOpts); 683 return std::move(RefFinder).take(); 684 } 685 686 } // namespace 687 688 std::vector<DocumentHighlight> findDocumentHighlights(ParsedAST &AST, 689 Position Pos) { 690 const SourceManager &SM = AST.getSourceManager(); 691 // FIXME: show references to macro within file? 692 DeclRelationSet Relations = 693 DeclRelation::TemplatePattern | DeclRelation::Alias; 694 auto CurLoc = sourceLocationInMainFile(SM, Pos); 695 if (!CurLoc) { 696 llvm::consumeError(CurLoc.takeError()); 697 return {}; 698 } 699 auto References = findRefs(getDeclAtPosition(AST, *CurLoc, Relations), AST); 700 701 // FIXME: we may get multiple DocumentHighlights with the same location and 702 // different kinds, deduplicate them. 703 std::vector<DocumentHighlight> Result; 704 for (const auto &Ref : References) { 705 DocumentHighlight DH; 706 DH.range = Ref.range(SM); 707 if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Write)) 708 DH.kind = DocumentHighlightKind::Write; 709 else if (Ref.Role & index::SymbolRoleSet(index::SymbolRole::Read)) 710 DH.kind = DocumentHighlightKind::Read; 711 else 712 DH.kind = DocumentHighlightKind::Text; 713 Result.push_back(std::move(DH)); 714 } 715 return Result; 716 } 717 718 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, 719 const SymbolIndex *Index) { 720 if (!Limit) 721 Limit = std::numeric_limits<uint32_t>::max(); 722 ReferencesResult Results; 723 const SourceManager &SM = AST.getSourceManager(); 724 auto MainFilePath = 725 getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM); 726 if (!MainFilePath) { 727 elog("Failed to get a path for the main file, so no references"); 728 return Results; 729 } 730 auto URIMainFile = URIForFile::canonicalize(*MainFilePath, *MainFilePath); 731 auto CurLoc = sourceLocationInMainFile(SM, Pos); 732 if (!CurLoc) { 733 llvm::consumeError(CurLoc.takeError()); 734 return {}; 735 } 736 llvm::Optional<DefinedMacro> Macro; 737 if (const auto *IdentifierAtCursor = 738 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens())) { 739 Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor()); 740 } 741 742 RefsRequest Req; 743 if (Macro) { 744 // Handle references to macro. 745 if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) { 746 // Collect macro references from main file. 747 const auto &IDToRefs = AST.getMacros().MacroRefs; 748 auto Refs = IDToRefs.find(*MacroSID); 749 if (Refs != IDToRefs.end()) { 750 for (const auto Ref : Refs->second) { 751 Location Result; 752 Result.range = Ref; 753 Result.uri = URIMainFile; 754 Results.References.push_back(std::move(Result)); 755 } 756 } 757 Req.IDs.insert(*MacroSID); 758 } 759 } else { 760 // Handle references to Decls. 761 762 // We also show references to the targets of using-decls, so we include 763 // DeclRelation::Underlying. 764 DeclRelationSet Relations = DeclRelation::TemplatePattern | 765 DeclRelation::Alias | DeclRelation::Underlying; 766 auto Decls = getDeclAtPosition(AST, *CurLoc, Relations); 767 768 // We traverse the AST to find references in the main file. 769 auto MainFileRefs = findRefs(Decls, AST); 770 // We may get multiple refs with the same location and different Roles, as 771 // cross-reference is only interested in locations, we deduplicate them 772 // by the location to avoid emitting duplicated locations. 773 MainFileRefs.erase(std::unique(MainFileRefs.begin(), MainFileRefs.end(), 774 [](const ReferenceFinder::Reference &L, 775 const ReferenceFinder::Reference &R) { 776 return L.SpelledTok.location() == 777 R.SpelledTok.location(); 778 }), 779 MainFileRefs.end()); 780 for (const auto &Ref : MainFileRefs) { 781 Location Result; 782 Result.range = Ref.range(SM); 783 Result.uri = URIMainFile; 784 Results.References.push_back(std::move(Result)); 785 } 786 if (Index && Results.References.size() <= Limit) { 787 for (const Decl *D : Decls) { 788 // Not all symbols can be referenced from outside (e.g. 789 // function-locals). 790 // TODO: we could skip TU-scoped symbols here (e.g. static functions) if 791 // we know this file isn't a header. The details might be tricky. 792 if (D->getParentFunctionOrMethod()) 793 continue; 794 if (auto ID = getSymbolID(D)) 795 Req.IDs.insert(*ID); 796 } 797 } 798 } 799 // Now query the index for references from other files. 800 if (!Req.IDs.empty() && Index && Results.References.size() <= Limit) { 801 Req.Limit = Limit; 802 Results.HasMore |= Index->refs(Req, [&](const Ref &R) { 803 // No need to continue process if we reach the limit. 804 if (Results.References.size() > Limit) 805 return; 806 auto LSPLoc = toLSPLocation(R.Location, *MainFilePath); 807 // Avoid indexed results for the main file - the AST is authoritative. 808 if (!LSPLoc || LSPLoc->uri.file() == *MainFilePath) 809 return; 810 811 Results.References.push_back(std::move(*LSPLoc)); 812 }); 813 } 814 if (Results.References.size() > Limit) { 815 Results.HasMore = true; 816 Results.References.resize(Limit); 817 } 818 return Results; 819 } 820 821 std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) { 822 const SourceManager &SM = AST.getSourceManager(); 823 auto CurLoc = sourceLocationInMainFile(SM, Pos); 824 if (!CurLoc) { 825 llvm::consumeError(CurLoc.takeError()); 826 return {}; 827 } 828 829 std::vector<SymbolDetails> Results; 830 831 // We also want the targets of using-decls, so we include 832 // DeclRelation::Underlying. 833 DeclRelationSet Relations = DeclRelation::TemplatePattern | 834 DeclRelation::Alias | DeclRelation::Underlying; 835 for (const NamedDecl *D : getDeclAtPosition(AST, *CurLoc, Relations)) { 836 SymbolDetails NewSymbol; 837 std::string QName = printQualifiedName(*D); 838 auto SplitQName = splitQualifiedName(QName); 839 NewSymbol.containerName = std::string(SplitQName.first); 840 NewSymbol.name = std::string(SplitQName.second); 841 842 if (NewSymbol.containerName.empty()) { 843 if (const auto *ParentND = 844 dyn_cast_or_null<NamedDecl>(D->getDeclContext())) 845 NewSymbol.containerName = printQualifiedName(*ParentND); 846 } 847 llvm::SmallString<32> USR; 848 if (!index::generateUSRForDecl(D, USR)) { 849 NewSymbol.USR = std::string(USR.str()); 850 NewSymbol.ID = SymbolID(NewSymbol.USR); 851 } 852 Results.push_back(std::move(NewSymbol)); 853 } 854 855 const auto *IdentifierAtCursor = 856 syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens()); 857 if (!IdentifierAtCursor) 858 return Results; 859 860 if (auto M = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor())) { 861 SymbolDetails NewMacro; 862 NewMacro.name = std::string(M->Name); 863 llvm::SmallString<32> USR; 864 if (!index::generateUSRForMacro(NewMacro.name, M->Info->getDefinitionLoc(), 865 SM, USR)) { 866 NewMacro.USR = std::string(USR.str()); 867 NewMacro.ID = SymbolID(NewMacro.USR); 868 } 869 Results.push_back(std::move(NewMacro)); 870 } 871 872 return Results; 873 } 874 875 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const LocatedSymbol &S) { 876 OS << S.Name << ": " << S.PreferredDeclaration; 877 if (S.Definition) 878 OS << " def=" << *S.Definition; 879 return OS; 880 } 881 882 // FIXME(nridge): Reduce duplication between this function and declToSym(). 883 static llvm::Optional<TypeHierarchyItem> 884 declToTypeHierarchyItem(ASTContext &Ctx, const NamedDecl &ND, 885 const syntax::TokenBuffer &TB) { 886 auto &SM = Ctx.getSourceManager(); 887 SourceLocation NameLoc = nameLocation(ND, Ctx.getSourceManager()); 888 auto FilePath = 889 getCanonicalPath(SM.getFileEntryForID(SM.getFileID(NameLoc)), SM); 890 auto TUPath = getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM); 891 if (!FilePath || !TUPath) 892 return llvm::None; // Not useful without a uri. 893 894 auto DeclToks = TB.spelledForExpanded(TB.expandedTokens(ND.getSourceRange())); 895 if (!DeclToks || DeclToks->empty()) 896 return llvm::None; 897 898 auto NameToks = TB.spelledForExpanded(TB.expandedTokens(NameLoc)); 899 if (!NameToks || NameToks->empty()) 900 return llvm::None; 901 902 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND); 903 // FIXME: this is not classifying constructors, destructors and operators 904 // correctly (they're all "methods"). 905 SymbolKind SK = indexSymbolKindToSymbolKind(SymInfo.Kind); 906 907 TypeHierarchyItem THI; 908 THI.name = printName(Ctx, ND); 909 THI.kind = SK; 910 THI.deprecated = ND.isDeprecated(); 911 THI.range = halfOpenToRange( 912 SM, syntax::Token::range(SM, DeclToks->front(), DeclToks->back()) 913 .toCharRange(SM)); 914 THI.selectionRange = halfOpenToRange( 915 SM, syntax::Token::range(SM, NameToks->front(), NameToks->back()) 916 .toCharRange(SM)); 917 if (!THI.range.contains(THI.selectionRange)) { 918 // 'selectionRange' must be contained in 'range', so in cases where clang 919 // reports unrelated ranges we need to reconcile somehow. 920 THI.range = THI.selectionRange; 921 } 922 923 THI.uri = URIForFile::canonicalize(*FilePath, *TUPath); 924 925 return THI; 926 } 927 928 static Optional<TypeHierarchyItem> 929 symbolToTypeHierarchyItem(const Symbol &S, const SymbolIndex *Index, 930 PathRef TUPath) { 931 auto Loc = symbolToLocation(S, TUPath); 932 if (!Loc) { 933 log("Type hierarchy: {0}", Loc.takeError()); 934 return llvm::None; 935 } 936 TypeHierarchyItem THI; 937 THI.name = std::string(S.Name); 938 THI.kind = indexSymbolKindToSymbolKind(S.SymInfo.Kind); 939 THI.deprecated = (S.Flags & Symbol::Deprecated); 940 THI.selectionRange = Loc->range; 941 // FIXME: Populate 'range' correctly 942 // (https://github.com/clangd/clangd/issues/59). 943 THI.range = THI.selectionRange; 944 THI.uri = Loc->uri; 945 // Store the SymbolID in the 'data' field. The client will 946 // send this back in typeHierarchy/resolve, allowing us to 947 // continue resolving additional levels of the type hierarchy. 948 THI.data = S.ID.str(); 949 950 return std::move(THI); 951 } 952 953 static void fillSubTypes(const SymbolID &ID, 954 std::vector<TypeHierarchyItem> &SubTypes, 955 const SymbolIndex *Index, int Levels, PathRef TUPath) { 956 RelationsRequest Req; 957 Req.Subjects.insert(ID); 958 Req.Predicate = RelationKind::BaseOf; 959 Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) { 960 if (Optional<TypeHierarchyItem> ChildSym = 961 symbolToTypeHierarchyItem(Object, Index, TUPath)) { 962 if (Levels > 1) { 963 ChildSym->children.emplace(); 964 fillSubTypes(Object.ID, *ChildSym->children, Index, Levels - 1, TUPath); 965 } 966 SubTypes.emplace_back(std::move(*ChildSym)); 967 } 968 }); 969 } 970 971 using RecursionProtectionSet = llvm::SmallSet<const CXXRecordDecl *, 4>; 972 973 static void fillSuperTypes(const CXXRecordDecl &CXXRD, ASTContext &ASTCtx, 974 std::vector<TypeHierarchyItem> &SuperTypes, 975 RecursionProtectionSet &RPSet, 976 const syntax::TokenBuffer &TB) { 977 // typeParents() will replace dependent template specializations 978 // with their class template, so to avoid infinite recursion for 979 // certain types of hierarchies, keep the templates encountered 980 // along the parent chain in a set, and stop the recursion if one 981 // starts to repeat. 982 auto *Pattern = CXXRD.getDescribedTemplate() ? &CXXRD : nullptr; 983 if (Pattern) { 984 if (!RPSet.insert(Pattern).second) { 985 return; 986 } 987 } 988 989 for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) { 990 if (Optional<TypeHierarchyItem> ParentSym = 991 declToTypeHierarchyItem(ASTCtx, *ParentDecl, TB)) { 992 ParentSym->parents.emplace(); 993 fillSuperTypes(*ParentDecl, ASTCtx, *ParentSym->parents, RPSet, TB); 994 SuperTypes.emplace_back(std::move(*ParentSym)); 995 } 996 } 997 998 if (Pattern) { 999 RPSet.erase(Pattern); 1000 } 1001 } 1002 1003 const CXXRecordDecl *findRecordTypeAt(ParsedAST &AST, Position Pos) { 1004 auto RecordFromNode = 1005 [](const SelectionTree::Node *N) -> const CXXRecordDecl * { 1006 if (!N) 1007 return nullptr; 1008 1009 // Note: explicitReferenceTargets() will search for both template 1010 // instantiations and template patterns, and prefer the former if available 1011 // (generally, one will be available for non-dependent specializations of a 1012 // class template). 1013 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Underlying); 1014 if (Decls.empty()) 1015 return nullptr; 1016 1017 const NamedDecl *D = Decls[0]; 1018 1019 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1020 // If this is a variable, use the type of the variable. 1021 return VD->getType().getTypePtr()->getAsCXXRecordDecl(); 1022 } 1023 1024 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1025 // If this is a method, use the type of the class. 1026 return Method->getParent(); 1027 } 1028 1029 // We don't handle FieldDecl because it's not clear what behaviour 1030 // the user would expect: the enclosing class type (as with a 1031 // method), or the field's type (as with a variable). 1032 1033 return dyn_cast<CXXRecordDecl>(D); 1034 }; 1035 1036 const SourceManager &SM = AST.getSourceManager(); 1037 const CXXRecordDecl *Result = nullptr; 1038 auto Offset = positionToOffset(SM.getBufferData(SM.getMainFileID()), Pos); 1039 if (!Offset) { 1040 llvm::consumeError(Offset.takeError()); 1041 return Result; 1042 } 1043 SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), *Offset, 1044 *Offset, [&](SelectionTree ST) { 1045 Result = RecordFromNode(ST.commonAncestor()); 1046 return Result != nullptr; 1047 }); 1048 return Result; 1049 } 1050 1051 std::vector<const CXXRecordDecl *> typeParents(const CXXRecordDecl *CXXRD) { 1052 std::vector<const CXXRecordDecl *> Result; 1053 1054 // If this is an invalid instantiation, instantiation of the bases 1055 // may not have succeeded, so fall back to the template pattern. 1056 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) { 1057 if (CTSD->isInvalidDecl()) 1058 CXXRD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); 1059 } 1060 1061 for (auto Base : CXXRD->bases()) { 1062 const CXXRecordDecl *ParentDecl = nullptr; 1063 1064 const Type *Type = Base.getType().getTypePtr(); 1065 if (const RecordType *RT = Type->getAs<RecordType>()) { 1066 ParentDecl = RT->getAsCXXRecordDecl(); 1067 } 1068 1069 if (!ParentDecl) { 1070 // Handle a dependent base such as "Base<T>" by using the primary 1071 // template. 1072 if (const TemplateSpecializationType *TS = 1073 Type->getAs<TemplateSpecializationType>()) { 1074 TemplateName TN = TS->getTemplateName(); 1075 if (TemplateDecl *TD = TN.getAsTemplateDecl()) { 1076 ParentDecl = dyn_cast<CXXRecordDecl>(TD->getTemplatedDecl()); 1077 } 1078 } 1079 } 1080 1081 if (ParentDecl) 1082 Result.push_back(ParentDecl); 1083 } 1084 1085 return Result; 1086 } 1087 1088 llvm::Optional<TypeHierarchyItem> 1089 getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels, 1090 TypeHierarchyDirection Direction, const SymbolIndex *Index, 1091 PathRef TUPath) { 1092 const CXXRecordDecl *CXXRD = findRecordTypeAt(AST, Pos); 1093 if (!CXXRD) 1094 return llvm::None; 1095 1096 Optional<TypeHierarchyItem> Result = 1097 declToTypeHierarchyItem(AST.getASTContext(), *CXXRD, AST.getTokens()); 1098 if (!Result) 1099 return Result; 1100 1101 if (Direction == TypeHierarchyDirection::Parents || 1102 Direction == TypeHierarchyDirection::Both) { 1103 Result->parents.emplace(); 1104 1105 RecursionProtectionSet RPSet; 1106 fillSuperTypes(*CXXRD, AST.getASTContext(), *Result->parents, RPSet, 1107 AST.getTokens()); 1108 } 1109 1110 if ((Direction == TypeHierarchyDirection::Children || 1111 Direction == TypeHierarchyDirection::Both) && 1112 ResolveLevels > 0) { 1113 Result->children.emplace(); 1114 1115 if (Index) { 1116 // The index does not store relationships between implicit 1117 // specializations, so if we have one, use the template pattern instead. 1118 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) 1119 CXXRD = CTSD->getTemplateInstantiationPattern(); 1120 1121 if (Optional<SymbolID> ID = getSymbolID(CXXRD)) 1122 fillSubTypes(*ID, *Result->children, Index, ResolveLevels, TUPath); 1123 } 1124 } 1125 1126 return Result; 1127 } 1128 1129 void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, 1130 TypeHierarchyDirection Direction, 1131 const SymbolIndex *Index) { 1132 // We only support typeHierarchy/resolve for children, because for parents 1133 // we ignore ResolveLevels and return all levels of parents eagerly. 1134 if (Direction == TypeHierarchyDirection::Parents || ResolveLevels == 0) 1135 return; 1136 1137 Item.children.emplace(); 1138 1139 if (Index && Item.data) { 1140 // We store the item's SymbolID in the 'data' field, and the client 1141 // passes it back to us in typeHierarchy/resolve. 1142 if (Expected<SymbolID> ID = SymbolID::fromStr(*Item.data)) { 1143 fillSubTypes(*ID, *Item.children, Index, ResolveLevels, Item.uri.file()); 1144 } 1145 } 1146 } 1147 1148 llvm::DenseSet<const Decl *> getNonLocalDeclRefs(ParsedAST &AST, 1149 const FunctionDecl *FD) { 1150 if (!FD->hasBody()) 1151 return {}; 1152 llvm::DenseSet<const Decl *> DeclRefs; 1153 findExplicitReferences(FD, [&](ReferenceLoc Ref) { 1154 for (const Decl *D : Ref.Targets) { 1155 if (!index::isFunctionLocalSymbol(D) && !D->isTemplateParameter() && 1156 !Ref.IsDecl) 1157 DeclRefs.insert(D); 1158 } 1159 }); 1160 return DeclRefs; 1161 } 1162 } // namespace clangd 1163 } // namespace clang 1164