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