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