1 //===--- FindTarget.cpp - What does an AST node refer to? -----------------===// 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 9 #include "FindTarget.h" 10 #include "AST.h" 11 #include "HeuristicResolver.h" 12 #include "support/Logger.h" 13 #include "clang/AST/ASTTypeTraits.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/DeclBase.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclTemplate.h" 18 #include "clang/AST/DeclVisitor.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprConcepts.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/NestedNameSpecifier.h" 25 #include "clang/AST/PrettyPrinter.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/StmtVisitor.h" 28 #include "clang/AST/TemplateBase.h" 29 #include "clang/AST/Type.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/AST/TypeLocVisitor.h" 32 #include "clang/AST/TypeVisitor.h" 33 #include "clang/Basic/LangOptions.h" 34 #include "clang/Basic/OperatorKinds.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/Specifiers.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/Compiler.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <iterator> 43 #include <utility> 44 #include <vector> 45 46 namespace clang { 47 namespace clangd { 48 namespace { 49 50 LLVM_ATTRIBUTE_UNUSED std::string nodeToString(const DynTypedNode &N) { 51 std::string S = std::string(N.getNodeKind().asStringRef()); 52 { 53 llvm::raw_string_ostream OS(S); 54 OS << ": "; 55 N.print(OS, PrintingPolicy(LangOptions())); 56 } 57 std::replace(S.begin(), S.end(), '\n', ' '); 58 return S; 59 } 60 61 const NamedDecl *getTemplatePattern(const NamedDecl *D) { 62 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 63 if (const auto *Result = CRD->getTemplateInstantiationPattern()) 64 return Result; 65 // getTemplateInstantiationPattern returns null if the Specialization is 66 // incomplete (e.g. the type didn't need to be complete), fall back to the 67 // primary template. 68 if (CRD->getTemplateSpecializationKind() == TSK_Undeclared) 69 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) 70 return Spec->getSpecializedTemplate()->getTemplatedDecl(); 71 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 72 return FD->getTemplateInstantiationPattern(); 73 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 74 // Hmm: getTIP returns its arg if it's not an instantiation?! 75 VarDecl *T = VD->getTemplateInstantiationPattern(); 76 return (T == D) ? nullptr : T; 77 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) { 78 return ED->getInstantiatedFromMemberEnum(); 79 } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) { 80 if (const auto *Parent = llvm::dyn_cast<NamedDecl>(D->getDeclContext())) 81 if (const DeclContext *ParentPat = 82 dyn_cast_or_null<DeclContext>(getTemplatePattern(Parent))) 83 for (const NamedDecl *BaseND : ParentPat->lookup(D->getDeclName())) 84 if (!BaseND->isImplicit() && BaseND->getKind() == D->getKind()) 85 return BaseND; 86 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) { 87 if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) { 88 if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) { 89 for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName())) 90 return BaseECD; 91 } 92 } 93 } 94 return nullptr; 95 } 96 97 // Returns true if the `TypedefNameDecl` should not be reported. 98 bool shouldSkipTypedef(const TypedefNameDecl *TD) { 99 // These should be treated as keywords rather than decls - the typedef is an 100 // odd implementation detail. 101 if (TD == TD->getASTContext().getObjCInstanceTypeDecl() || 102 TD == TD->getASTContext().getObjCIdDecl()) 103 return true; 104 return false; 105 } 106 107 // TargetFinder locates the entities that an AST node refers to. 108 // 109 // Typically this is (possibly) one declaration and (possibly) one type, but 110 // may be more: 111 // - for ambiguous nodes like OverloadExpr 112 // - if we want to include e.g. both typedefs and the underlying type 113 // 114 // This is organized as a set of mutually recursive helpers for particular node 115 // types, but for most nodes this is a short walk rather than a deep traversal. 116 // 117 // It's tempting to do e.g. typedef resolution as a second normalization step, 118 // after finding the 'primary' decl etc. But we do this monolithically instead 119 // because: 120 // - normalization may require these traversals again (e.g. unwrapping a 121 // typedef reveals a decltype which must be traversed) 122 // - it doesn't simplify that much, e.g. the first stage must still be able 123 // to yield multiple decls to handle OverloadExpr 124 // - there are cases where it's required for correctness. e.g: 125 // template<class X> using pvec = vector<x*>; pvec<int> x; 126 // There's no Decl `pvec<int>`, we must choose `pvec<X>` or `vector<int*>` 127 // and both are lossy. We must know upfront what the caller ultimately wants. 128 // 129 // FIXME: improve common dependent scope using name lookup in primary templates. 130 // We currently handle several dependent constructs, but some others remain to 131 // be handled: 132 // - UnresolvedUsingTypenameDecl 133 struct TargetFinder { 134 using RelSet = DeclRelationSet; 135 using Rel = DeclRelation; 136 137 private: 138 const HeuristicResolver *Resolver; 139 llvm::SmallDenseMap<const NamedDecl *, 140 std::pair<RelSet, /*InsertionOrder*/ size_t>> 141 Decls; 142 llvm::SmallDenseMap<const Decl *, RelSet> Seen; 143 RelSet Flags; 144 145 template <typename T> void debug(T &Node, RelSet Flags) { 146 dlog("visit [{0}] {1}", Flags, nodeToString(DynTypedNode::create(Node))); 147 } 148 149 void report(const NamedDecl *D, RelSet Flags) { 150 dlog("--> [{0}] {1}", Flags, nodeToString(DynTypedNode::create(*D))); 151 auto It = Decls.try_emplace(D, std::make_pair(Flags, Decls.size())); 152 // If already exists, update the flags. 153 if (!It.second) 154 It.first->second.first |= Flags; 155 } 156 157 public: 158 TargetFinder(const HeuristicResolver *Resolver) : Resolver(Resolver) {} 159 160 llvm::SmallVector<std::pair<const NamedDecl *, RelSet>, 1> takeDecls() const { 161 using ValTy = std::pair<const NamedDecl *, RelSet>; 162 llvm::SmallVector<ValTy, 1> Result; 163 Result.resize(Decls.size()); 164 for (const auto &Elem : Decls) 165 Result[Elem.second.second] = {Elem.first, Elem.second.first}; 166 return Result; 167 } 168 169 void add(const Decl *Dcl, RelSet Flags) { 170 const NamedDecl *D = llvm::dyn_cast_or_null<NamedDecl>(Dcl); 171 if (!D) 172 return; 173 debug(*D, Flags); 174 175 // Avoid recursion (which can arise in the presence of heuristic 176 // resolution of dependent names) by exiting early if we have 177 // already seen this decl with all flags in Flags. 178 auto Res = Seen.try_emplace(D); 179 if (!Res.second && Res.first->second.contains(Flags)) 180 return; 181 Res.first->second |= Flags; 182 183 if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) 184 D = UDD->getNominatedNamespaceAsWritten(); 185 186 if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) { 187 add(TND->getUnderlyingType(), Flags | Rel::Underlying); 188 Flags |= Rel::Alias; // continue with the alias. 189 } else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 190 // no Underlying as this is a non-renaming alias. 191 for (const UsingShadowDecl *S : UD->shadows()) 192 add(S->getUnderlyingDecl(), Flags); 193 Flags |= Rel::Alias; // continue with the alias. 194 } else if (const UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) { 195 add(UED->getEnumDecl(), Flags); 196 Flags |= Rel::Alias; // continue with the alias. 197 } else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) { 198 add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying); 199 Flags |= Rel::Alias; // continue with the alias 200 } else if (const UnresolvedUsingValueDecl *UUVD = 201 dyn_cast<UnresolvedUsingValueDecl>(D)) { 202 if (Resolver) { 203 for (const NamedDecl *Target : Resolver->resolveUsingValueDecl(UUVD)) { 204 add(Target, Flags); // no Underlying as this is a non-renaming alias 205 } 206 } 207 Flags |= Rel::Alias; // continue with the alias 208 } else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) { 209 // Include the Introducing decl, but don't traverse it. This may end up 210 // including *all* shadows, which we don't want. 211 report(USD->getIntroducer(), Flags | Rel::Alias); 212 // Shadow decls are synthetic and not themselves interesting. 213 // Record the underlying decl instead, if allowed. 214 D = USD->getTargetDecl(); 215 } else if (const auto *DG = dyn_cast<CXXDeductionGuideDecl>(D)) { 216 D = DG->getDeducedTemplate(); 217 } else if (const ObjCImplementationDecl *IID = 218 dyn_cast<ObjCImplementationDecl>(D)) { 219 // Treat ObjC{Interface,Implementation}Decl as if they were a decl/def 220 // pair as long as the interface isn't implicit. 221 if (const auto *CID = IID->getClassInterface()) 222 if (const auto *DD = CID->getDefinition()) 223 if (!DD->isImplicitInterfaceDecl()) 224 D = DD; 225 } else if (const ObjCCategoryImplDecl *CID = 226 dyn_cast<ObjCCategoryImplDecl>(D)) { 227 // Treat ObjC{Category,CategoryImpl}Decl as if they were a decl/def pair. 228 D = CID->getCategoryDecl(); 229 } 230 if (!D) 231 return; 232 233 if (const Decl *Pat = getTemplatePattern(D)) { 234 assert(Pat != D); 235 add(Pat, Flags | Rel::TemplatePattern); 236 // Now continue with the instantiation. 237 Flags |= Rel::TemplateInstantiation; 238 } 239 240 report(D, Flags); 241 } 242 243 void add(const Stmt *S, RelSet Flags) { 244 if (!S) 245 return; 246 debug(*S, Flags); 247 struct Visitor : public ConstStmtVisitor<Visitor> { 248 TargetFinder &Outer; 249 RelSet Flags; 250 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {} 251 252 void VisitCallExpr(const CallExpr *CE) { 253 Outer.add(CE->getCalleeDecl(), Flags); 254 } 255 void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 256 Outer.add(E->getNamedConcept(), Flags); 257 } 258 void VisitDeclRefExpr(const DeclRefExpr *DRE) { 259 const Decl *D = DRE->getDecl(); 260 // UsingShadowDecl allows us to record the UsingDecl. 261 // getFoundDecl() returns the wrong thing in other cases (templates). 262 if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl())) 263 D = USD; 264 Outer.add(D, Flags); 265 } 266 void VisitMemberExpr(const MemberExpr *ME) { 267 const Decl *D = ME->getMemberDecl(); 268 if (auto *USD = 269 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl())) 270 D = USD; 271 Outer.add(D, Flags); 272 } 273 void VisitOverloadExpr(const OverloadExpr *OE) { 274 for (auto *D : OE->decls()) 275 Outer.add(D, Flags); 276 } 277 void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) { 278 Outer.add(SE->getPack(), Flags); 279 } 280 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 281 Outer.add(CCE->getConstructor(), Flags); 282 } 283 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) { 284 for (const DesignatedInitExpr::Designator &D : 285 llvm::reverse(DIE->designators())) 286 if (D.isFieldDesignator()) { 287 Outer.add(D.getField(), Flags); 288 // We don't know which designator was intended, we assume the outer. 289 break; 290 } 291 } 292 void VisitGotoStmt(const GotoStmt *Goto) { 293 if (auto *LabelDecl = Goto->getLabel()) 294 Outer.add(LabelDecl, Flags); 295 } 296 void VisitLabelStmt(const LabelStmt *Label) { 297 if (auto *LabelDecl = Label->getDecl()) 298 Outer.add(LabelDecl, Flags); 299 } 300 void 301 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 302 if (Outer.Resolver) { 303 for (const NamedDecl *D : Outer.Resolver->resolveMemberExpr(E)) { 304 Outer.add(D, Flags); 305 } 306 } 307 } 308 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) { 309 if (Outer.Resolver) { 310 for (const NamedDecl *D : Outer.Resolver->resolveDeclRefExpr(E)) { 311 Outer.add(D, Flags); 312 } 313 } 314 } 315 void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) { 316 Outer.add(OIRE->getDecl(), Flags); 317 } 318 void VisitObjCMessageExpr(const ObjCMessageExpr *OME) { 319 Outer.add(OME->getMethodDecl(), Flags); 320 } 321 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) { 322 if (OPRE->isExplicitProperty()) 323 Outer.add(OPRE->getExplicitProperty(), Flags); 324 else { 325 if (OPRE->isMessagingGetter()) 326 Outer.add(OPRE->getImplicitPropertyGetter(), Flags); 327 if (OPRE->isMessagingSetter()) 328 Outer.add(OPRE->getImplicitPropertySetter(), Flags); 329 } 330 } 331 void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) { 332 Outer.add(OPE->getProtocol(), Flags); 333 } 334 void VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) { 335 Outer.add(OVE->getSourceExpr(), Flags); 336 } 337 void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) { 338 Outer.add(POE->getSyntacticForm(), Flags); 339 } 340 void VisitCXXNewExpr(const CXXNewExpr *CNE) { 341 Outer.add(CNE->getOperatorNew(), Flags); 342 } 343 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE) { 344 Outer.add(CDE->getOperatorDelete(), Flags); 345 } 346 }; 347 Visitor(*this, Flags).Visit(S); 348 } 349 350 void add(QualType T, RelSet Flags) { 351 if (T.isNull()) 352 return; 353 debug(T, Flags); 354 struct Visitor : public TypeVisitor<Visitor> { 355 TargetFinder &Outer; 356 RelSet Flags; 357 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {} 358 359 void VisitTagType(const TagType *TT) { 360 Outer.add(TT->getAsTagDecl(), Flags); 361 } 362 363 void VisitElaboratedType(const ElaboratedType *ET) { 364 Outer.add(ET->desugar(), Flags); 365 } 366 367 void VisitUsingType(const UsingType *ET) { 368 Outer.add(ET->getFoundDecl(), Flags); 369 } 370 371 void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) { 372 Outer.add(ICNT->getDecl(), Flags); 373 } 374 375 void VisitDecltypeType(const DecltypeType *DTT) { 376 Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying); 377 } 378 void VisitDeducedType(const DeducedType *DT) { 379 // FIXME: In practice this doesn't work: the AutoType you find inside 380 // TypeLoc never has a deduced type. https://llvm.org/PR42914 381 Outer.add(DT->getDeducedType(), Flags); 382 } 383 void VisitDeducedTemplateSpecializationType( 384 const DeducedTemplateSpecializationType *DTST) { 385 // FIXME: This is a workaround for https://llvm.org/PR42914, 386 // which is causing DTST->getDeducedType() to be empty. We 387 // fall back to the template pattern and miss the instantiation 388 // even when it's known in principle. Once that bug is fixed, 389 // this method can be removed (the existing handling in 390 // VisitDeducedType() is sufficient). 391 if (auto *TD = DTST->getTemplateName().getAsTemplateDecl()) 392 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern); 393 } 394 void VisitDependentNameType(const DependentNameType *DNT) { 395 if (Outer.Resolver) { 396 for (const NamedDecl *ND : 397 Outer.Resolver->resolveDependentNameType(DNT)) { 398 Outer.add(ND, Flags); 399 } 400 } 401 } 402 void VisitDependentTemplateSpecializationType( 403 const DependentTemplateSpecializationType *DTST) { 404 if (Outer.Resolver) { 405 for (const NamedDecl *ND : 406 Outer.Resolver->resolveTemplateSpecializationType(DTST)) { 407 Outer.add(ND, Flags); 408 } 409 } 410 } 411 void VisitTypedefType(const TypedefType *TT) { 412 if (shouldSkipTypedef(TT->getDecl())) 413 return; 414 Outer.add(TT->getDecl(), Flags); 415 } 416 void 417 VisitTemplateSpecializationType(const TemplateSpecializationType *TST) { 418 // Have to handle these case-by-case. 419 420 // templated type aliases: there's no specialized/instantiated using 421 // decl to point to. So try to find a decl for the underlying type 422 // (after substitution), and failing that point to the (templated) using 423 // decl. 424 if (TST->isTypeAlias()) { 425 Outer.add(TST->getAliasedType(), Flags | Rel::Underlying); 426 // Don't *traverse* the alias, which would result in traversing the 427 // template of the underlying type. 428 Outer.report( 429 TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(), 430 Flags | Rel::Alias | Rel::TemplatePattern); 431 } 432 // specializations of template template parameters aren't instantiated 433 // into decls, so they must refer to the parameter itself. 434 else if (const auto *Parm = 435 llvm::dyn_cast_or_null<TemplateTemplateParmDecl>( 436 TST->getTemplateName().getAsTemplateDecl())) 437 Outer.add(Parm, Flags); 438 // class template specializations have a (specialized) CXXRecordDecl. 439 else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl()) 440 Outer.add(RD, Flags); // add(Decl) will despecialize if needed. 441 else { 442 // fallback: the (un-specialized) declaration from primary template. 443 if (auto *TD = TST->getTemplateName().getAsTemplateDecl()) 444 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern); 445 } 446 } 447 void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) { 448 Outer.add(TTPT->getDecl(), Flags); 449 } 450 void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) { 451 Outer.add(OIT->getDecl(), Flags); 452 } 453 void VisitObjCObjectType(const ObjCObjectType *OOT) { 454 // Make all of the protocols targets since there's no child nodes for 455 // protocols. This isn't needed for the base type, which *does* have a 456 // child `ObjCInterfaceTypeLoc`. This structure is a hack, but it works 457 // well for go-to-definition. 458 unsigned NumProtocols = OOT->getNumProtocols(); 459 for (unsigned I = 0; I < NumProtocols; I++) 460 Outer.add(OOT->getProtocol(I), Flags); 461 } 462 }; 463 Visitor(*this, Flags).Visit(T.getTypePtr()); 464 } 465 466 void add(const NestedNameSpecifier *NNS, RelSet Flags) { 467 if (!NNS) 468 return; 469 debug(*NNS, Flags); 470 switch (NNS->getKind()) { 471 case NestedNameSpecifier::Namespace: 472 add(NNS->getAsNamespace(), Flags); 473 return; 474 case NestedNameSpecifier::NamespaceAlias: 475 add(NNS->getAsNamespaceAlias(), Flags); 476 return; 477 case NestedNameSpecifier::Identifier: 478 if (Resolver) { 479 add(QualType(Resolver->resolveNestedNameSpecifierToType(NNS), 0), 480 Flags); 481 } 482 return; 483 case NestedNameSpecifier::TypeSpec: 484 case NestedNameSpecifier::TypeSpecWithTemplate: 485 add(QualType(NNS->getAsType(), 0), Flags); 486 return; 487 case NestedNameSpecifier::Global: 488 // This should be TUDecl, but we can't get a pointer to it! 489 return; 490 case NestedNameSpecifier::Super: 491 add(NNS->getAsRecordDecl(), Flags); 492 return; 493 } 494 llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind"); 495 } 496 497 void add(const CXXCtorInitializer *CCI, RelSet Flags) { 498 if (!CCI) 499 return; 500 debug(*CCI, Flags); 501 502 if (CCI->isAnyMemberInitializer()) 503 add(CCI->getAnyMember(), Flags); 504 // Constructor calls contain a TypeLoc node, so we don't handle them here. 505 } 506 507 void add(const TemplateArgument &Arg, RelSet Flags) { 508 // Only used for template template arguments. 509 // For type and non-type template arguments, SelectionTree 510 // will hit a more specific node (e.g. a TypeLoc or a 511 // DeclRefExpr). 512 if (Arg.getKind() == TemplateArgument::Template || 513 Arg.getKind() == TemplateArgument::TemplateExpansion) { 514 if (TemplateDecl *TD = 515 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) { 516 report(TD, Flags); 517 } 518 } 519 } 520 }; 521 522 } // namespace 523 524 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1> 525 allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver) { 526 dlog("allTargetDecls({0})", nodeToString(N)); 527 TargetFinder Finder(Resolver); 528 DeclRelationSet Flags; 529 if (const Decl *D = N.get<Decl>()) 530 Finder.add(D, Flags); 531 else if (const Stmt *S = N.get<Stmt>()) 532 Finder.add(S, Flags); 533 else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>()) 534 Finder.add(NNSL->getNestedNameSpecifier(), Flags); 535 else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>()) 536 Finder.add(NNS, Flags); 537 else if (const TypeLoc *TL = N.get<TypeLoc>()) 538 Finder.add(TL->getType(), Flags); 539 else if (const QualType *QT = N.get<QualType>()) 540 Finder.add(*QT, Flags); 541 else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) 542 Finder.add(CCI, Flags); 543 else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>()) 544 Finder.add(TAL->getArgument(), Flags); 545 else if (const CXXBaseSpecifier *CBS = N.get<CXXBaseSpecifier>()) 546 Finder.add(CBS->getTypeSourceInfo()->getType(), Flags); 547 return Finder.takeDecls(); 548 } 549 550 llvm::SmallVector<const NamedDecl *, 1> 551 targetDecl(const DynTypedNode &N, DeclRelationSet Mask, 552 const HeuristicResolver *Resolver) { 553 llvm::SmallVector<const NamedDecl *, 1> Result; 554 for (const auto &Entry : allTargetDecls(N, Resolver)) { 555 if (!(Entry.second & ~Mask)) 556 Result.push_back(Entry.first); 557 } 558 return Result; 559 } 560 561 llvm::SmallVector<const NamedDecl *, 1> 562 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask, 563 const HeuristicResolver *Resolver) { 564 assert(!(Mask & (DeclRelation::TemplatePattern | 565 DeclRelation::TemplateInstantiation)) && 566 "explicitReferenceTargets handles templates on its own"); 567 auto Decls = allTargetDecls(N, Resolver); 568 569 // We prefer to return template instantiation, but fallback to template 570 // pattern if instantiation is not available. 571 Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation; 572 573 llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns; 574 llvm::SmallVector<const NamedDecl *, 1> Targets; 575 bool SeenTemplateInstantiations = false; 576 for (auto &D : Decls) { 577 if (D.second & ~Mask) 578 continue; 579 if (D.second & DeclRelation::TemplatePattern) { 580 TemplatePatterns.push_back(D.first); 581 continue; 582 } 583 if (D.second & DeclRelation::TemplateInstantiation) 584 SeenTemplateInstantiations = true; 585 Targets.push_back(D.first); 586 } 587 if (!SeenTemplateInstantiations) 588 Targets.insert(Targets.end(), TemplatePatterns.begin(), 589 TemplatePatterns.end()); 590 return Targets; 591 } 592 593 namespace { 594 llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D, 595 const HeuristicResolver *Resolver) { 596 struct Visitor : ConstDeclVisitor<Visitor> { 597 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {} 598 599 const HeuristicResolver *Resolver; 600 llvm::SmallVector<ReferenceLoc> Refs; 601 602 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) { 603 // We want to keep it as non-declaration references, as the 604 // "using namespace" declaration doesn't have a name. 605 Refs.push_back(ReferenceLoc{D->getQualifierLoc(), 606 D->getIdentLocation(), 607 /*IsDecl=*/false, 608 {D->getNominatedNamespaceAsWritten()}}); 609 } 610 611 void VisitUsingDecl(const UsingDecl *D) { 612 // "using ns::identifier;" is a non-declaration reference. 613 Refs.push_back(ReferenceLoc{ 614 D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false, 615 explicitReferenceTargets(DynTypedNode::create(*D), 616 DeclRelation::Underlying, Resolver)}); 617 } 618 619 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) { 620 // For namespace alias, "namespace Foo = Target;", we add two references. 621 // Add a declaration reference for Foo. 622 VisitNamedDecl(D); 623 // Add a non-declaration reference for Target. 624 Refs.push_back(ReferenceLoc{D->getQualifierLoc(), 625 D->getTargetNameLoc(), 626 /*IsDecl=*/false, 627 {D->getAliasedNamespace()}}); 628 } 629 630 void VisitNamedDecl(const NamedDecl *ND) { 631 // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As 632 // as their underlying decls, covering the same range, will be visited. 633 if (llvm::isa<ClassTemplateDecl>(ND) || 634 llvm::isa<FunctionTemplateDecl>(ND) || 635 llvm::isa<VarTemplateDecl>(ND) || 636 llvm::isa<TypeAliasTemplateDecl>(ND)) 637 return; 638 // FIXME: decide on how to surface destructors when we need them. 639 if (llvm::isa<CXXDestructorDecl>(ND)) 640 return; 641 // Filter anonymous decls, name location will point outside the name token 642 // and the clients are not prepared to handle that. 643 if (ND->getDeclName().isIdentifier() && 644 !ND->getDeclName().getAsIdentifierInfo()) 645 return; 646 Refs.push_back(ReferenceLoc{getQualifierLoc(*ND), 647 ND->getLocation(), 648 /*IsDecl=*/true, 649 {ND}}); 650 } 651 652 void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) { 653 // The class template name in a deduction guide targets the class 654 // template. 655 Refs.push_back(ReferenceLoc{DG->getQualifierLoc(), 656 DG->getNameInfo().getLoc(), 657 /*IsDecl=*/false, 658 {DG->getDeducedTemplate()}}); 659 } 660 661 void VisitObjCMethodDecl(const ObjCMethodDecl *OMD) { 662 // The name may have several tokens, we can only report the first. 663 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 664 OMD->getSelectorStartLoc(), 665 /*IsDecl=*/true, 666 {OMD}}); 667 } 668 669 void visitProtocolList( 670 llvm::iterator_range<ObjCProtocolList::iterator> Protocols, 671 llvm::iterator_range<const SourceLocation *> Locations) { 672 for (const auto &P : llvm::zip(Protocols, Locations)) { 673 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 674 std::get<1>(P), 675 /*IsDecl=*/false, 676 {std::get<0>(P)}}); 677 } 678 } 679 680 void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *OID) { 681 if (OID->isThisDeclarationADefinition()) 682 visitProtocolList(OID->protocols(), OID->protocol_locs()); 683 Base::VisitObjCInterfaceDecl(OID); // Visit the interface's name. 684 } 685 686 void VisitObjCCategoryDecl(const ObjCCategoryDecl *OCD) { 687 visitProtocolList(OCD->protocols(), OCD->protocol_locs()); 688 // getLocation is the extended class's location, not the category's. 689 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 690 OCD->getLocation(), 691 /*IsDecl=*/false, 692 {OCD->getClassInterface()}}); 693 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 694 OCD->getCategoryNameLoc(), 695 /*IsDecl=*/true, 696 {OCD}}); 697 } 698 699 void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *OCID) { 700 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 701 OCID->getLocation(), 702 /*IsDecl=*/false, 703 {OCID->getClassInterface()}}); 704 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 705 OCID->getCategoryNameLoc(), 706 /*IsDecl=*/true, 707 {OCID->getCategoryDecl()}}); 708 } 709 710 void VisitObjCProtocolDecl(const ObjCProtocolDecl *OPD) { 711 if (OPD->isThisDeclarationADefinition()) 712 visitProtocolList(OPD->protocols(), OPD->protocol_locs()); 713 Base::VisitObjCProtocolDecl(OPD); // Visit the protocol's name. 714 } 715 }; 716 717 Visitor V{Resolver}; 718 V.Visit(D); 719 return V.Refs; 720 } 721 722 llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S, 723 const HeuristicResolver *Resolver) { 724 struct Visitor : ConstStmtVisitor<Visitor> { 725 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {} 726 727 const HeuristicResolver *Resolver; 728 // FIXME: handle more complicated cases: more ObjC, designated initializers. 729 llvm::SmallVector<ReferenceLoc> Refs; 730 731 void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 732 Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(), 733 E->getConceptNameLoc(), 734 /*IsDecl=*/false, 735 {E->getNamedConcept()}}); 736 } 737 738 void VisitDeclRefExpr(const DeclRefExpr *E) { 739 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 740 E->getNameInfo().getLoc(), 741 /*IsDecl=*/false, 742 {E->getFoundDecl()}}); 743 } 744 745 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) { 746 Refs.push_back(ReferenceLoc{ 747 E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false, 748 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)}); 749 } 750 751 void VisitMemberExpr(const MemberExpr *E) { 752 // Skip destructor calls to avoid duplication: TypeLoc within will be 753 // visited separately. 754 if (llvm::isa<CXXDestructorDecl>(E->getFoundDecl().getDecl())) 755 return; 756 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 757 E->getMemberNameInfo().getLoc(), 758 /*IsDecl=*/false, 759 {E->getFoundDecl()}}); 760 } 761 762 void 763 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 764 Refs.push_back(ReferenceLoc{ 765 E->getQualifierLoc(), E->getMemberNameInfo().getLoc(), 766 /*IsDecl=*/false, 767 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)}); 768 } 769 770 void VisitOverloadExpr(const OverloadExpr *E) { 771 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 772 E->getNameInfo().getLoc(), 773 /*IsDecl=*/false, 774 llvm::SmallVector<const NamedDecl *, 1>( 775 E->decls().begin(), E->decls().end())}); 776 } 777 778 void VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 779 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 780 E->getPackLoc(), 781 /*IsDecl=*/false, 782 {E->getPack()}}); 783 } 784 785 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) { 786 Refs.push_back(ReferenceLoc{ 787 NestedNameSpecifierLoc(), E->getLocation(), 788 /*IsDecl=*/false, 789 // Select the getter, setter, or @property depending on the call. 790 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)}); 791 } 792 793 void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) { 794 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 795 OIRE->getLocation(), 796 /*IsDecl=*/false, 797 {OIRE->getDecl()}}); 798 } 799 800 void VisitObjCMessageExpr(const ObjCMessageExpr *E) { 801 // The name may have several tokens, we can only report the first. 802 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 803 E->getSelectorStartLoc(), 804 /*IsDecl=*/false, 805 {E->getMethodDecl()}}); 806 } 807 808 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) { 809 for (const DesignatedInitExpr::Designator &D : DIE->designators()) { 810 if (!D.isFieldDesignator()) 811 continue; 812 813 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 814 D.getFieldLoc(), 815 /*IsDecl=*/false, 816 {D.getField()}}); 817 } 818 } 819 820 void VisitGotoStmt(const GotoStmt *GS) { 821 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 822 GS->getLabelLoc(), 823 /*IsDecl=*/false, 824 {GS->getLabel()}}); 825 } 826 827 void VisitLabelStmt(const LabelStmt *LS) { 828 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 829 LS->getIdentLoc(), 830 /*IsDecl=*/true, 831 {LS->getDecl()}}); 832 } 833 }; 834 835 Visitor V{Resolver}; 836 V.Visit(S); 837 return V.Refs; 838 } 839 840 llvm::SmallVector<ReferenceLoc> 841 refInTypeLoc(TypeLoc L, const HeuristicResolver *Resolver) { 842 struct Visitor : TypeLocVisitor<Visitor> { 843 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {} 844 845 const HeuristicResolver *Resolver; 846 llvm::SmallVector<ReferenceLoc> Refs; 847 848 void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) { 849 // We only know about qualifier, rest if filled by inner locations. 850 size_t InitialSize = Refs.size(); 851 Visit(L.getNamedTypeLoc().getUnqualifiedLoc()); 852 size_t NewSize = Refs.size(); 853 // Add qualifier for the newly-added refs. 854 for (unsigned I = InitialSize; I < NewSize; ++I) { 855 ReferenceLoc *Ref = &Refs[I]; 856 // Fill in the qualifier. 857 assert(!Ref->Qualifier.hasQualifier() && "qualifier already set"); 858 Ref->Qualifier = L.getQualifierLoc(); 859 } 860 } 861 862 void VisitUsingTypeLoc(UsingTypeLoc L) { 863 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 864 L.getLocalSourceRange().getBegin(), 865 /*IsDecl=*/false, 866 {L.getFoundDecl()}}); 867 } 868 869 void VisitTagTypeLoc(TagTypeLoc L) { 870 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 871 L.getNameLoc(), 872 /*IsDecl=*/false, 873 {L.getDecl()}}); 874 } 875 876 void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) { 877 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 878 L.getNameLoc(), 879 /*IsDecl=*/false, 880 {L.getDecl()}}); 881 } 882 883 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) { 884 // We must ensure template type aliases are included in results if they 885 // were written in the source code, e.g. in 886 // template <class T> using valias = vector<T>; 887 // ^valias<int> x; 888 // 'explicitReferenceTargets' will return: 889 // 1. valias with mask 'Alias'. 890 // 2. 'vector<int>' with mask 'Underlying'. 891 // we want to return only #1 in this case. 892 Refs.push_back(ReferenceLoc{ 893 NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false, 894 explicitReferenceTargets(DynTypedNode::create(L.getType()), 895 DeclRelation::Alias, Resolver)}); 896 } 897 void VisitDeducedTemplateSpecializationTypeLoc( 898 DeducedTemplateSpecializationTypeLoc L) { 899 Refs.push_back(ReferenceLoc{ 900 NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false, 901 explicitReferenceTargets(DynTypedNode::create(L.getType()), 902 DeclRelation::Alias, Resolver)}); 903 } 904 905 void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 906 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 907 TL.getNameLoc(), 908 /*IsDecl=*/false, 909 {TL.getDecl()}}); 910 } 911 912 void VisitDependentTemplateSpecializationTypeLoc( 913 DependentTemplateSpecializationTypeLoc L) { 914 Refs.push_back( 915 ReferenceLoc{L.getQualifierLoc(), L.getTemplateNameLoc(), 916 /*IsDecl=*/false, 917 explicitReferenceTargets( 918 DynTypedNode::create(L.getType()), {}, Resolver)}); 919 } 920 921 void VisitDependentNameTypeLoc(DependentNameTypeLoc L) { 922 Refs.push_back( 923 ReferenceLoc{L.getQualifierLoc(), L.getNameLoc(), 924 /*IsDecl=*/false, 925 explicitReferenceTargets( 926 DynTypedNode::create(L.getType()), {}, Resolver)}); 927 } 928 929 void VisitTypedefTypeLoc(TypedefTypeLoc L) { 930 if (shouldSkipTypedef(L.getTypedefNameDecl())) 931 return; 932 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 933 L.getNameLoc(), 934 /*IsDecl=*/false, 935 {L.getTypedefNameDecl()}}); 936 } 937 938 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc L) { 939 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 940 L.getNameLoc(), 941 /*IsDecl=*/false, 942 {L.getIFaceDecl()}}); 943 } 944 945 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc L) { 946 unsigned NumProtocols = L.getNumProtocols(); 947 for (unsigned I = 0; I < NumProtocols; I++) { 948 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 949 L.getProtocolLoc(I), 950 /*IsDecl=*/false, 951 {L.getProtocol(I)}}); 952 } 953 } 954 }; 955 956 Visitor V{Resolver}; 957 V.Visit(L.getUnqualifiedLoc()); 958 return V.Refs; 959 } 960 961 class ExplicitReferenceCollector 962 : public RecursiveASTVisitor<ExplicitReferenceCollector> { 963 public: 964 ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out, 965 const HeuristicResolver *Resolver) 966 : Out(Out), Resolver(Resolver) { 967 assert(Out); 968 } 969 970 bool VisitTypeLoc(TypeLoc TTL) { 971 if (TypeLocsToSkip.count(TTL.getBeginLoc())) 972 return true; 973 visitNode(DynTypedNode::create(TTL)); 974 return true; 975 } 976 977 bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) { 978 // ElaboratedTypeLoc will reports information for its inner type loc. 979 // Otherwise we loose information about inner types loc's qualifier. 980 TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc(); 981 TypeLocsToSkip.insert(Inner.getBeginLoc()); 982 return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L); 983 } 984 985 bool VisitStmt(Stmt *S) { 986 visitNode(DynTypedNode::create(*S)); 987 return true; 988 } 989 990 bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) { 991 visitNode(DynTypedNode::create(*OVE)); 992 // Not clear why the source expression is skipped by default... 993 // FIXME: can we just make RecursiveASTVisitor do this? 994 return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr()); 995 } 996 997 bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) { 998 visitNode(DynTypedNode::create(*POE)); 999 // Traverse only the syntactic form to find the *written* references. 1000 // (The semantic form also contains lots of duplication) 1001 return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm()); 1002 } 1003 1004 // We re-define Traverse*, since there's no corresponding Visit*. 1005 // TemplateArgumentLoc is the only way to get locations for references to 1006 // template template parameters. 1007 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) { 1008 switch (A.getArgument().getKind()) { 1009 case TemplateArgument::Template: 1010 case TemplateArgument::TemplateExpansion: 1011 reportReference(ReferenceLoc{A.getTemplateQualifierLoc(), 1012 A.getTemplateNameLoc(), 1013 /*IsDecl=*/false, 1014 {A.getArgument() 1015 .getAsTemplateOrTemplatePattern() 1016 .getAsTemplateDecl()}}, 1017 DynTypedNode::create(A.getArgument())); 1018 break; 1019 case TemplateArgument::Declaration: 1020 break; // FIXME: can this actually happen in TemplateArgumentLoc? 1021 case TemplateArgument::Integral: 1022 case TemplateArgument::Null: 1023 case TemplateArgument::NullPtr: 1024 break; // no references. 1025 case TemplateArgument::Pack: 1026 case TemplateArgument::Type: 1027 case TemplateArgument::Expression: 1028 break; // Handled by VisitType and VisitExpression. 1029 }; 1030 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A); 1031 } 1032 1033 bool VisitDecl(Decl *D) { 1034 visitNode(DynTypedNode::create(*D)); 1035 return true; 1036 } 1037 1038 // We have to use Traverse* because there is no corresponding Visit*. 1039 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) { 1040 if (!L.getNestedNameSpecifier()) 1041 return true; 1042 visitNode(DynTypedNode::create(L)); 1043 // Inner type is missing information about its qualifier, skip it. 1044 if (auto TL = L.getTypeLoc()) 1045 TypeLocsToSkip.insert(TL.getBeginLoc()); 1046 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L); 1047 } 1048 1049 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { 1050 visitNode(DynTypedNode::create(*Init)); 1051 return RecursiveASTVisitor::TraverseConstructorInitializer(Init); 1052 } 1053 1054 private: 1055 /// Obtain information about a reference directly defined in \p N. Does not 1056 /// recurse into child nodes, e.g. do not expect references for constructor 1057 /// initializers 1058 /// 1059 /// Any of the fields in the returned structure can be empty, but not all of 1060 /// them, e.g. 1061 /// - for implicitly generated nodes (e.g. MemberExpr from range-based-for), 1062 /// source location information may be missing, 1063 /// - for dependent code, targets may be empty. 1064 /// 1065 /// (!) For the purposes of this function declarations are not considered to 1066 /// be references. However, declarations can have references inside them, 1067 /// e.g. 'namespace foo = std' references namespace 'std' and this 1068 /// function will return the corresponding reference. 1069 llvm::SmallVector<ReferenceLoc> explicitReference(DynTypedNode N) { 1070 if (auto *D = N.get<Decl>()) 1071 return refInDecl(D, Resolver); 1072 if (auto *S = N.get<Stmt>()) 1073 return refInStmt(S, Resolver); 1074 if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) { 1075 // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases. 1076 return {ReferenceLoc{ 1077 NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false, 1078 explicitReferenceTargets( 1079 DynTypedNode::create(*NNSL->getNestedNameSpecifier()), 1080 DeclRelation::Alias, Resolver)}}; 1081 } 1082 if (const TypeLoc *TL = N.get<TypeLoc>()) 1083 return refInTypeLoc(*TL, Resolver); 1084 if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) { 1085 // Other type initializers (e.g. base initializer) are handled by visiting 1086 // the typeLoc. 1087 if (CCI->isAnyMemberInitializer()) { 1088 return {ReferenceLoc{NestedNameSpecifierLoc(), 1089 CCI->getMemberLocation(), 1090 /*IsDecl=*/false, 1091 {CCI->getAnyMember()}}}; 1092 } 1093 } 1094 // We do not have location information for other nodes (QualType, etc) 1095 return {}; 1096 } 1097 1098 void visitNode(DynTypedNode N) { 1099 for (auto &R : explicitReference(N)) 1100 reportReference(std::move(R), N); 1101 } 1102 1103 void reportReference(ReferenceLoc &&Ref, DynTypedNode N) { 1104 // Strip null targets that can arise from invalid code. 1105 // (This avoids having to check for null everywhere we insert) 1106 llvm::erase_value(Ref.Targets, nullptr); 1107 // Our promise is to return only references from the source code. If we lack 1108 // location information, skip these nodes. 1109 // Normally this should not happen in practice, unless there are bugs in the 1110 // traversals or users started the traversal at an implicit node. 1111 if (Ref.NameLoc.isInvalid()) { 1112 dlog("invalid location at node {0}", nodeToString(N)); 1113 return; 1114 } 1115 Out(Ref); 1116 } 1117 1118 llvm::function_ref<void(ReferenceLoc)> Out; 1119 const HeuristicResolver *Resolver; 1120 /// TypeLocs starting at these locations must be skipped, see 1121 /// TraverseElaboratedTypeSpecifierLoc for details. 1122 llvm::DenseSet<SourceLocation> TypeLocsToSkip; 1123 }; 1124 } // namespace 1125 1126 void findExplicitReferences(const Stmt *S, 1127 llvm::function_ref<void(ReferenceLoc)> Out, 1128 const HeuristicResolver *Resolver) { 1129 assert(S); 1130 ExplicitReferenceCollector(Out, Resolver).TraverseStmt(const_cast<Stmt *>(S)); 1131 } 1132 void findExplicitReferences(const Decl *D, 1133 llvm::function_ref<void(ReferenceLoc)> Out, 1134 const HeuristicResolver *Resolver) { 1135 assert(D); 1136 ExplicitReferenceCollector(Out, Resolver).TraverseDecl(const_cast<Decl *>(D)); 1137 } 1138 void findExplicitReferences(const ASTContext &AST, 1139 llvm::function_ref<void(ReferenceLoc)> Out, 1140 const HeuristicResolver *Resolver) { 1141 ExplicitReferenceCollector(Out, Resolver) 1142 .TraverseAST(const_cast<ASTContext &>(AST)); 1143 } 1144 1145 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) { 1146 switch (R) { 1147 #define REL_CASE(X) \ 1148 case DeclRelation::X: \ 1149 return OS << #X; 1150 REL_CASE(Alias); 1151 REL_CASE(Underlying); 1152 REL_CASE(TemplateInstantiation); 1153 REL_CASE(TemplatePattern); 1154 #undef REL_CASE 1155 } 1156 llvm_unreachable("Unhandled DeclRelation enum"); 1157 } 1158 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) { 1159 const char *Sep = ""; 1160 for (unsigned I = 0; I < RS.S.size(); ++I) { 1161 if (RS.S.test(I)) { 1162 OS << Sep << static_cast<DeclRelation>(I); 1163 Sep = "|"; 1164 } 1165 } 1166 return OS; 1167 } 1168 1169 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) { 1170 // note we cannot print R.NameLoc without a source manager. 1171 OS << "targets = {"; 1172 bool First = true; 1173 for (const NamedDecl *T : R.Targets) { 1174 if (!First) 1175 OS << ", "; 1176 else 1177 First = false; 1178 OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T); 1179 } 1180 OS << "}"; 1181 if (R.Qualifier) { 1182 OS << ", qualifier = '"; 1183 R.Qualifier.getNestedNameSpecifier()->print(OS, 1184 PrintingPolicy(LangOptions())); 1185 OS << "'"; 1186 } 1187 if (R.IsDecl) 1188 OS << ", decl"; 1189 return OS; 1190 } 1191 1192 } // namespace clangd 1193 } // namespace clang 1194