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