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