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 llvm::SmallDenseMap<const Decl *, RelSet> Seen; 334 RelSet Flags; 335 336 template <typename T> void debug(T &Node, RelSet Flags) { 337 dlog("visit [{0}] {1}", Flags, nodeToString(DynTypedNode::create(Node))); 338 } 339 340 void report(const NamedDecl *D, RelSet Flags) { 341 dlog("--> [{0}] {1}", Flags, nodeToString(DynTypedNode::create(*D))); 342 auto It = Decls.try_emplace(D, std::make_pair(Flags, Decls.size())); 343 // If already exists, update the flags. 344 if (!It.second) 345 It.first->second.first |= Flags; 346 } 347 348 public: 349 llvm::SmallVector<std::pair<const NamedDecl *, RelSet>, 1> takeDecls() const { 350 using ValTy = std::pair<const NamedDecl *, RelSet>; 351 llvm::SmallVector<ValTy, 1> Result; 352 Result.resize(Decls.size()); 353 for (const auto &Elem : Decls) 354 Result[Elem.second.second] = {Elem.first, Elem.second.first}; 355 return Result; 356 } 357 358 void add(const Decl *Dcl, RelSet Flags) { 359 const NamedDecl *D = llvm::dyn_cast_or_null<NamedDecl>(Dcl); 360 if (!D) 361 return; 362 debug(*D, Flags); 363 364 // Avoid recursion (which can arise in the presence of heuristic 365 // resolution of dependent names) by exiting early if we have 366 // already seen this decl with all flags in Flags. 367 auto Res = Seen.try_emplace(D); 368 if (!Res.second && Res.first->second.contains(Flags)) 369 return; 370 Res.first->second |= Flags; 371 372 if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) 373 D = UDD->getNominatedNamespaceAsWritten(); 374 375 if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) { 376 add(TND->getUnderlyingType(), Flags | Rel::Underlying); 377 Flags |= Rel::Alias; // continue with the alias. 378 } else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 379 // no Underlying as this is a non-renaming alias. 380 for (const UsingShadowDecl *S : UD->shadows()) 381 add(S->getUnderlyingDecl(), Flags); 382 Flags |= Rel::Alias; // continue with the alias. 383 } else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) { 384 add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying); 385 Flags |= Rel::Alias; // continue with the alias 386 } else if (const UnresolvedUsingValueDecl *UUVD = 387 dyn_cast<UnresolvedUsingValueDecl>(D)) { 388 for (const NamedDecl *Target : getMembersReferencedViaDependentName( 389 UUVD->getQualifier()->getAsType(), 390 [UUVD](ASTContext &) { return UUVD->getNameInfo().getName(); }, 391 ValueFilter)) { 392 add(Target, Flags); // no Underlying as this is a non-renaming alias 393 } 394 Flags |= Rel::Alias; // continue with the alias 395 } else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) { 396 // Include the using decl, but don't traverse it. This may end up 397 // including *all* shadows, which we don't want. 398 report(USD->getUsingDecl(), Flags | Rel::Alias); 399 // Shadow decls are synthetic and not themselves interesting. 400 // Record the underlying decl instead, if allowed. 401 D = USD->getTargetDecl(); 402 } else if (const auto *DG = dyn_cast<CXXDeductionGuideDecl>(D)) { 403 D = DG->getDeducedTemplate(); 404 } else if (const ObjCImplementationDecl *IID = 405 dyn_cast<ObjCImplementationDecl>(D)) { 406 // Treat ObjC{Interface,Implementation}Decl as if they were a decl/def 407 // pair as long as the interface isn't implicit. 408 if (const auto *CID = IID->getClassInterface()) 409 if (const auto *DD = CID->getDefinition()) 410 if (!DD->isImplicitInterfaceDecl()) 411 D = DD; 412 } else if (const ObjCCategoryImplDecl *CID = 413 dyn_cast<ObjCCategoryImplDecl>(D)) { 414 // Treat ObjC{Category,CategoryImpl}Decl as if they were a decl/def pair. 415 D = CID->getCategoryDecl(); 416 } 417 if (!D) 418 return; 419 420 if (const Decl *Pat = getTemplatePattern(D)) { 421 assert(Pat != D); 422 add(Pat, Flags | Rel::TemplatePattern); 423 // Now continue with the instantiation. 424 Flags |= Rel::TemplateInstantiation; 425 } 426 427 report(D, Flags); 428 } 429 430 void add(const Stmt *S, RelSet Flags) { 431 if (!S) 432 return; 433 debug(*S, Flags); 434 struct Visitor : public ConstStmtVisitor<Visitor> { 435 TargetFinder &Outer; 436 RelSet Flags; 437 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {} 438 439 void VisitCallExpr(const CallExpr *CE) { 440 Outer.add(CE->getCalleeDecl(), Flags); 441 } 442 void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 443 Outer.add(E->getNamedConcept(), Flags); 444 } 445 void VisitDeclRefExpr(const DeclRefExpr *DRE) { 446 const Decl *D = DRE->getDecl(); 447 // UsingShadowDecl allows us to record the UsingDecl. 448 // getFoundDecl() returns the wrong thing in other cases (templates). 449 if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl())) 450 D = USD; 451 Outer.add(D, Flags); 452 } 453 void VisitMemberExpr(const MemberExpr *ME) { 454 const Decl *D = ME->getMemberDecl(); 455 if (auto *USD = 456 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl())) 457 D = USD; 458 Outer.add(D, Flags); 459 } 460 void VisitOverloadExpr(const OverloadExpr *OE) { 461 for (auto *D : OE->decls()) 462 Outer.add(D, Flags); 463 } 464 void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) { 465 Outer.add(SE->getPack(), Flags); 466 } 467 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 468 Outer.add(CCE->getConstructor(), Flags); 469 } 470 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) { 471 for (const DesignatedInitExpr::Designator &D : 472 llvm::reverse(DIE->designators())) 473 if (D.isFieldDesignator()) { 474 Outer.add(D.getField(), Flags); 475 // We don't know which designator was intended, we assume the outer. 476 break; 477 } 478 } 479 void VisitGotoStmt(const GotoStmt *Goto) { 480 if (auto *LabelDecl = Goto->getLabel()) 481 Outer.add(LabelDecl, Flags); 482 } 483 void VisitLabelStmt(const LabelStmt *Label) { 484 if (auto *LabelDecl = Label->getDecl()) 485 Outer.add(LabelDecl, Flags); 486 } 487 void 488 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 489 for (const NamedDecl *D : resolveExprToDecls(E)) { 490 Outer.add(D, Flags); 491 } 492 } 493 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) { 494 for (const NamedDecl *D : resolveExprToDecls(E)) { 495 Outer.add(D, Flags); 496 } 497 } 498 void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) { 499 Outer.add(OIRE->getDecl(), Flags); 500 } 501 void VisitObjCMessageExpr(const ObjCMessageExpr *OME) { 502 Outer.add(OME->getMethodDecl(), Flags); 503 } 504 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) { 505 if (OPRE->isExplicitProperty()) 506 Outer.add(OPRE->getExplicitProperty(), Flags); 507 else { 508 if (OPRE->isMessagingGetter()) 509 Outer.add(OPRE->getImplicitPropertyGetter(), Flags); 510 if (OPRE->isMessagingSetter()) 511 Outer.add(OPRE->getImplicitPropertySetter(), Flags); 512 } 513 } 514 void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) { 515 Outer.add(OPE->getProtocol(), Flags); 516 } 517 void VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) { 518 Outer.add(OVE->getSourceExpr(), Flags); 519 } 520 void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) { 521 Outer.add(POE->getSyntacticForm(), Flags); 522 } 523 void VisitCXXNewExpr(const CXXNewExpr *CNE) { 524 Outer.add(CNE->getOperatorNew(), Flags); 525 } 526 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE) { 527 Outer.add(CDE->getOperatorDelete(), Flags); 528 } 529 }; 530 Visitor(*this, Flags).Visit(S); 531 } 532 533 void add(QualType T, RelSet Flags) { 534 if (T.isNull()) 535 return; 536 debug(T, Flags); 537 struct Visitor : public TypeVisitor<Visitor> { 538 TargetFinder &Outer; 539 RelSet Flags; 540 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {} 541 542 void VisitTagType(const TagType *TT) { 543 Outer.add(TT->getAsTagDecl(), Flags); 544 } 545 546 void VisitElaboratedType(const ElaboratedType *ET) { 547 Outer.add(ET->desugar(), Flags); 548 } 549 550 void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) { 551 Outer.add(ICNT->getDecl(), Flags); 552 } 553 554 void VisitDecltypeType(const DecltypeType *DTT) { 555 Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying); 556 } 557 void VisitDeducedType(const DeducedType *DT) { 558 // FIXME: In practice this doesn't work: the AutoType you find inside 559 // TypeLoc never has a deduced type. https://llvm.org/PR42914 560 Outer.add(DT->getDeducedType(), Flags | Rel::Underlying); 561 } 562 void VisitDeducedTemplateSpecializationType( 563 const DeducedTemplateSpecializationType *DTST) { 564 // FIXME: This is a workaround for https://llvm.org/PR42914, 565 // which is causing DTST->getDeducedType() to be empty. We 566 // fall back to the template pattern and miss the instantiation 567 // even when it's known in principle. Once that bug is fixed, 568 // this method can be removed (the existing handling in 569 // VisitDeducedType() is sufficient). 570 if (auto *TD = DTST->getTemplateName().getAsTemplateDecl()) 571 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern); 572 } 573 void VisitDependentNameType(const DependentNameType *DNT) { 574 for (const NamedDecl *ND : getMembersReferencedViaDependentName( 575 resolveNestedNameSpecifierToType(DNT->getQualifier()), 576 [DNT](ASTContext &) { return DNT->getIdentifier(); }, 577 TypeFilter)) { 578 Outer.add(ND, Flags); 579 } 580 } 581 void VisitDependentTemplateSpecializationType( 582 const DependentTemplateSpecializationType *DTST) { 583 for (const NamedDecl *ND : getMembersReferencedViaDependentName( 584 resolveNestedNameSpecifierToType(DTST->getQualifier()), 585 [DTST](ASTContext &) { return DTST->getIdentifier(); }, 586 TemplateFilter)) { 587 Outer.add(ND, Flags); 588 } 589 } 590 void VisitTypedefType(const TypedefType *TT) { 591 Outer.add(TT->getDecl(), Flags); 592 } 593 void 594 VisitTemplateSpecializationType(const TemplateSpecializationType *TST) { 595 // Have to handle these case-by-case. 596 597 // templated type aliases: there's no specialized/instantiated using 598 // decl to point to. So try to find a decl for the underlying type 599 // (after substitution), and failing that point to the (templated) using 600 // decl. 601 if (TST->isTypeAlias()) { 602 Outer.add(TST->getAliasedType(), Flags | Rel::Underlying); 603 // Don't *traverse* the alias, which would result in traversing the 604 // template of the underlying type. 605 Outer.report( 606 TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(), 607 Flags | Rel::Alias | Rel::TemplatePattern); 608 } 609 // specializations of template template parameters aren't instantiated 610 // into decls, so they must refer to the parameter itself. 611 else if (const auto *Parm = 612 llvm::dyn_cast_or_null<TemplateTemplateParmDecl>( 613 TST->getTemplateName().getAsTemplateDecl())) 614 Outer.add(Parm, Flags); 615 // class template specializations have a (specialized) CXXRecordDecl. 616 else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl()) 617 Outer.add(RD, Flags); // add(Decl) will despecialize if needed. 618 else { 619 // fallback: the (un-specialized) declaration from primary template. 620 if (auto *TD = TST->getTemplateName().getAsTemplateDecl()) 621 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern); 622 } 623 } 624 void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) { 625 Outer.add(TTPT->getDecl(), Flags); 626 } 627 void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) { 628 Outer.add(OIT->getDecl(), Flags); 629 } 630 void VisitObjCObjectType(const ObjCObjectType *OOT) { 631 // FIXME: ObjCObjectTypeLoc has no children for the protocol list, so 632 // there is no node in id<Foo> that refers to ObjCProtocolDecl Foo. 633 if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1) 634 Outer.add(OOT->getProtocol(0), Flags); 635 } 636 }; 637 Visitor(*this, Flags).Visit(T.getTypePtr()); 638 } 639 640 void add(const NestedNameSpecifier *NNS, RelSet Flags) { 641 if (!NNS) 642 return; 643 debug(*NNS, Flags); 644 switch (NNS->getKind()) { 645 case NestedNameSpecifier::Namespace: 646 add(NNS->getAsNamespace(), Flags); 647 return; 648 case NestedNameSpecifier::NamespaceAlias: 649 add(NNS->getAsNamespaceAlias(), Flags); 650 return; 651 case NestedNameSpecifier::Identifier: 652 case NestedNameSpecifier::TypeSpec: 653 case NestedNameSpecifier::TypeSpecWithTemplate: 654 add(QualType(resolveNestedNameSpecifierToType(NNS), 0), Flags); 655 return; 656 case NestedNameSpecifier::Global: 657 // This should be TUDecl, but we can't get a pointer to it! 658 return; 659 case NestedNameSpecifier::Super: 660 add(NNS->getAsRecordDecl(), Flags); 661 return; 662 } 663 llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind"); 664 } 665 666 void add(const CXXCtorInitializer *CCI, RelSet Flags) { 667 if (!CCI) 668 return; 669 debug(*CCI, Flags); 670 671 if (CCI->isAnyMemberInitializer()) 672 add(CCI->getAnyMember(), Flags); 673 // Constructor calls contain a TypeLoc node, so we don't handle them here. 674 } 675 676 void add(const TemplateArgument &Arg, RelSet Flags) { 677 // Only used for template template arguments. 678 // For type and non-type template arguments, SelectionTree 679 // will hit a more specific node (e.g. a TypeLoc or a 680 // DeclRefExpr). 681 if (Arg.getKind() == TemplateArgument::Template || 682 Arg.getKind() == TemplateArgument::TemplateExpansion) { 683 if (TemplateDecl *TD = Arg.getAsTemplate().getAsTemplateDecl()) { 684 report(TD, Flags); 685 } 686 } 687 } 688 }; 689 690 } // namespace 691 692 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1> 693 allTargetDecls(const DynTypedNode &N) { 694 dlog("allTargetDecls({0})", nodeToString(N)); 695 TargetFinder Finder; 696 DeclRelationSet Flags; 697 if (const Decl *D = N.get<Decl>()) 698 Finder.add(D, Flags); 699 else if (const Stmt *S = N.get<Stmt>()) 700 Finder.add(S, Flags); 701 else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>()) 702 Finder.add(NNSL->getNestedNameSpecifier(), Flags); 703 else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>()) 704 Finder.add(NNS, Flags); 705 else if (const TypeLoc *TL = N.get<TypeLoc>()) 706 Finder.add(TL->getType(), Flags); 707 else if (const QualType *QT = N.get<QualType>()) 708 Finder.add(*QT, Flags); 709 else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) 710 Finder.add(CCI, Flags); 711 else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>()) 712 Finder.add(TAL->getArgument(), Flags); 713 else if (const CXXBaseSpecifier *CBS = N.get<CXXBaseSpecifier>()) 714 Finder.add(CBS->getTypeSourceInfo()->getType(), Flags); 715 return Finder.takeDecls(); 716 } 717 718 llvm::SmallVector<const NamedDecl *, 1> targetDecl(const DynTypedNode &N, 719 DeclRelationSet Mask) { 720 llvm::SmallVector<const NamedDecl *, 1> Result; 721 for (const auto &Entry : allTargetDecls(N)) { 722 if (!(Entry.second & ~Mask)) 723 Result.push_back(Entry.first); 724 } 725 return Result; 726 } 727 728 llvm::SmallVector<const NamedDecl *, 1> 729 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask) { 730 assert(!(Mask & (DeclRelation::TemplatePattern | 731 DeclRelation::TemplateInstantiation)) && 732 "explicitReferenceTargets handles templates on its own"); 733 auto Decls = allTargetDecls(N); 734 735 // We prefer to return template instantiation, but fallback to template 736 // pattern if instantiation is not available. 737 Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation; 738 739 llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns; 740 llvm::SmallVector<const NamedDecl *, 1> Targets; 741 bool SeenTemplateInstantiations = false; 742 for (auto &D : Decls) { 743 if (D.second & ~Mask) 744 continue; 745 if (D.second & DeclRelation::TemplatePattern) { 746 TemplatePatterns.push_back(D.first); 747 continue; 748 } 749 if (D.second & DeclRelation::TemplateInstantiation) 750 SeenTemplateInstantiations = true; 751 Targets.push_back(D.first); 752 } 753 if (!SeenTemplateInstantiations) 754 Targets.insert(Targets.end(), TemplatePatterns.begin(), 755 TemplatePatterns.end()); 756 return Targets; 757 } 758 759 namespace { 760 llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D) { 761 struct Visitor : ConstDeclVisitor<Visitor> { 762 llvm::SmallVector<ReferenceLoc> Refs; 763 764 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) { 765 // We want to keep it as non-declaration references, as the 766 // "using namespace" declaration doesn't have a name. 767 Refs.push_back(ReferenceLoc{D->getQualifierLoc(), 768 D->getIdentLocation(), 769 /*IsDecl=*/false, 770 {D->getNominatedNamespaceAsWritten()}}); 771 } 772 773 void VisitUsingDecl(const UsingDecl *D) { 774 // "using ns::identifier;" is a non-declaration reference. 775 Refs.push_back( 776 ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false, 777 explicitReferenceTargets(DynTypedNode::create(*D), 778 DeclRelation::Underlying)}); 779 } 780 781 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) { 782 // For namespace alias, "namespace Foo = Target;", we add two references. 783 // Add a declaration reference for Foo. 784 VisitNamedDecl(D); 785 // Add a non-declaration reference for Target. 786 Refs.push_back(ReferenceLoc{D->getQualifierLoc(), 787 D->getTargetNameLoc(), 788 /*IsDecl=*/false, 789 {D->getAliasedNamespace()}}); 790 } 791 792 void VisitNamedDecl(const NamedDecl *ND) { 793 // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As 794 // as their underlying decls, covering the same range, will be visited. 795 if (llvm::isa<ClassTemplateDecl>(ND) || 796 llvm::isa<FunctionTemplateDecl>(ND) || 797 llvm::isa<VarTemplateDecl>(ND) || 798 llvm::isa<TypeAliasTemplateDecl>(ND)) 799 return; 800 // FIXME: decide on how to surface destructors when we need them. 801 if (llvm::isa<CXXDestructorDecl>(ND)) 802 return; 803 // Filter anonymous decls, name location will point outside the name token 804 // and the clients are not prepared to handle that. 805 if (ND->getDeclName().isIdentifier() && 806 !ND->getDeclName().getAsIdentifierInfo()) 807 return; 808 Refs.push_back(ReferenceLoc{getQualifierLoc(*ND), 809 ND->getLocation(), 810 /*IsDecl=*/true, 811 {ND}}); 812 } 813 814 void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) { 815 // The class template name in a deduction guide targets the class 816 // template. 817 Refs.push_back(ReferenceLoc{DG->getQualifierLoc(), 818 DG->getNameInfo().getLoc(), 819 /*IsDecl=*/false, 820 {DG->getDeducedTemplate()}}); 821 } 822 }; 823 824 Visitor V; 825 V.Visit(D); 826 return V.Refs; 827 } 828 829 llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S) { 830 struct Visitor : ConstStmtVisitor<Visitor> { 831 // FIXME: handle more complicated cases: more ObjC, designated initializers. 832 llvm::SmallVector<ReferenceLoc> Refs; 833 834 void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 835 Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(), 836 E->getConceptNameLoc(), 837 /*IsDecl=*/false, 838 {E->getNamedConcept()}}); 839 } 840 841 void VisitDeclRefExpr(const DeclRefExpr *E) { 842 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 843 E->getNameInfo().getLoc(), 844 /*IsDecl=*/false, 845 {E->getFoundDecl()}}); 846 } 847 848 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) { 849 Refs.push_back(ReferenceLoc{ 850 E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false, 851 explicitReferenceTargets(DynTypedNode::create(*E), {})}); 852 } 853 854 void VisitMemberExpr(const MemberExpr *E) { 855 // Skip destructor calls to avoid duplication: TypeLoc within will be 856 // visited separately. 857 if (llvm::isa<CXXDestructorDecl>(E->getFoundDecl().getDecl())) 858 return; 859 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 860 E->getMemberNameInfo().getLoc(), 861 /*IsDecl=*/false, 862 {E->getFoundDecl()}}); 863 } 864 865 void 866 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 867 Refs.push_back( 868 ReferenceLoc{E->getQualifierLoc(), E->getMemberNameInfo().getLoc(), 869 /*IsDecl=*/false, 870 explicitReferenceTargets(DynTypedNode::create(*E), {})}); 871 } 872 873 void VisitOverloadExpr(const OverloadExpr *E) { 874 Refs.push_back(ReferenceLoc{E->getQualifierLoc(), 875 E->getNameInfo().getLoc(), 876 /*IsDecl=*/false, 877 llvm::SmallVector<const NamedDecl *, 1>( 878 E->decls().begin(), E->decls().end())}); 879 } 880 881 void VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 882 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 883 E->getPackLoc(), 884 /*IsDecl=*/false, 885 {E->getPack()}}); 886 } 887 888 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) { 889 Refs.push_back(ReferenceLoc{ 890 NestedNameSpecifierLoc(), E->getLocation(), 891 /*IsDecl=*/false, 892 // Select the getter, setter, or @property depending on the call. 893 explicitReferenceTargets(DynTypedNode::create(*E), {})}); 894 } 895 896 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) { 897 for (const DesignatedInitExpr::Designator &D : DIE->designators()) { 898 if (!D.isFieldDesignator()) 899 continue; 900 901 llvm::SmallVector<const NamedDecl *, 1> Targets; 902 if (D.getField()) 903 Targets.push_back(D.getField()); 904 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), D.getFieldLoc(), 905 /*IsDecl=*/false, std::move(Targets)}); 906 } 907 } 908 909 void VisitGotoStmt(const GotoStmt *GS) { 910 llvm::SmallVector<const NamedDecl *, 1> Targets; 911 if (const auto *L = GS->getLabel()) 912 Targets.push_back(L); 913 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), GS->getLabelLoc(), 914 /*IsDecl=*/false, std::move(Targets)}); 915 } 916 917 void VisitLabelStmt(const LabelStmt *LS) { 918 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), 919 LS->getIdentLoc(), 920 /*IsDecl=*/true, 921 {LS->getDecl()}}); 922 } 923 }; 924 925 Visitor V; 926 V.Visit(S); 927 return V.Refs; 928 } 929 930 llvm::SmallVector<ReferenceLoc> refInTypeLoc(TypeLoc L) { 931 struct Visitor : TypeLocVisitor<Visitor> { 932 llvm::Optional<ReferenceLoc> Ref; 933 934 void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) { 935 // We only know about qualifier, rest if filled by inner locations. 936 Visit(L.getNamedTypeLoc().getUnqualifiedLoc()); 937 // Fill in the qualifier. 938 if (!Ref) 939 return; 940 assert(!Ref->Qualifier.hasQualifier() && "qualifier already set"); 941 Ref->Qualifier = L.getQualifierLoc(); 942 } 943 944 void VisitTagTypeLoc(TagTypeLoc L) { 945 Ref = ReferenceLoc{NestedNameSpecifierLoc(), 946 L.getNameLoc(), 947 /*IsDecl=*/false, 948 {L.getDecl()}}; 949 } 950 951 void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) { 952 Ref = ReferenceLoc{NestedNameSpecifierLoc(), 953 L.getNameLoc(), 954 /*IsDecl=*/false, 955 {L.getDecl()}}; 956 } 957 958 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) { 959 // We must ensure template type aliases are included in results if they 960 // were written in the source code, e.g. in 961 // template <class T> using valias = vector<T>; 962 // ^valias<int> x; 963 // 'explicitReferenceTargets' will return: 964 // 1. valias with mask 'Alias'. 965 // 2. 'vector<int>' with mask 'Underlying'. 966 // we want to return only #1 in this case. 967 Ref = ReferenceLoc{ 968 NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false, 969 explicitReferenceTargets(DynTypedNode::create(L.getType()), 970 DeclRelation::Alias)}; 971 } 972 void VisitDeducedTemplateSpecializationTypeLoc( 973 DeducedTemplateSpecializationTypeLoc L) { 974 Ref = ReferenceLoc{ 975 NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false, 976 explicitReferenceTargets(DynTypedNode::create(L.getType()), 977 DeclRelation::Alias)}; 978 } 979 980 void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 981 Ref = ReferenceLoc{NestedNameSpecifierLoc(), 982 TL.getNameLoc(), 983 /*IsDecl=*/false, 984 {TL.getDecl()}}; 985 } 986 987 void VisitDependentTemplateSpecializationTypeLoc( 988 DependentTemplateSpecializationTypeLoc L) { 989 Ref = ReferenceLoc{ 990 L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false, 991 explicitReferenceTargets(DynTypedNode::create(L.getType()), {})}; 992 } 993 994 void VisitDependentNameTypeLoc(DependentNameTypeLoc L) { 995 Ref = ReferenceLoc{ 996 L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false, 997 explicitReferenceTargets(DynTypedNode::create(L.getType()), {})}; 998 } 999 1000 void VisitTypedefTypeLoc(TypedefTypeLoc L) { 1001 Ref = ReferenceLoc{NestedNameSpecifierLoc(), 1002 L.getNameLoc(), 1003 /*IsDecl=*/false, 1004 {L.getTypedefNameDecl()}}; 1005 } 1006 }; 1007 1008 Visitor V; 1009 V.Visit(L.getUnqualifiedLoc()); 1010 if (!V.Ref) 1011 return {}; 1012 return {*V.Ref}; 1013 } 1014 1015 class ExplicitReferenceCollector 1016 : public RecursiveASTVisitor<ExplicitReferenceCollector> { 1017 public: 1018 ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out) 1019 : Out(Out) { 1020 assert(Out); 1021 } 1022 1023 bool VisitTypeLoc(TypeLoc TTL) { 1024 if (TypeLocsToSkip.count(TTL.getBeginLoc())) 1025 return true; 1026 visitNode(DynTypedNode::create(TTL)); 1027 return true; 1028 } 1029 1030 bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) { 1031 // ElaboratedTypeLoc will reports information for its inner type loc. 1032 // Otherwise we loose information about inner types loc's qualifier. 1033 TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc(); 1034 TypeLocsToSkip.insert(Inner.getBeginLoc()); 1035 return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L); 1036 } 1037 1038 bool VisitStmt(Stmt *S) { 1039 visitNode(DynTypedNode::create(*S)); 1040 return true; 1041 } 1042 1043 bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) { 1044 visitNode(DynTypedNode::create(*OVE)); 1045 // Not clear why the source expression is skipped by default... 1046 // FIXME: can we just make RecursiveASTVisitor do this? 1047 return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr()); 1048 } 1049 1050 bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) { 1051 visitNode(DynTypedNode::create(*POE)); 1052 // Traverse only the syntactic form to find the *written* references. 1053 // (The semantic form also contains lots of duplication) 1054 return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm()); 1055 } 1056 1057 // We re-define Traverse*, since there's no corresponding Visit*. 1058 // TemplateArgumentLoc is the only way to get locations for references to 1059 // template template parameters. 1060 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) { 1061 llvm::SmallVector<const NamedDecl *, 1> Targets; 1062 switch (A.getArgument().getKind()) { 1063 case TemplateArgument::Template: 1064 case TemplateArgument::TemplateExpansion: 1065 if (const auto *D = A.getArgument() 1066 .getAsTemplateOrTemplatePattern() 1067 .getAsTemplateDecl()) 1068 Targets.push_back(D); 1069 reportReference(ReferenceLoc{A.getTemplateQualifierLoc(), 1070 A.getTemplateNameLoc(), 1071 /*IsDecl=*/false, Targets}, 1072 DynTypedNode::create(A.getArgument())); 1073 break; 1074 case TemplateArgument::Declaration: 1075 break; // FIXME: can this actually happen in TemplateArgumentLoc? 1076 case TemplateArgument::Integral: 1077 case TemplateArgument::Null: 1078 case TemplateArgument::NullPtr: 1079 break; // no references. 1080 case TemplateArgument::Pack: 1081 case TemplateArgument::Type: 1082 case TemplateArgument::Expression: 1083 break; // Handled by VisitType and VisitExpression. 1084 }; 1085 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A); 1086 } 1087 1088 bool VisitDecl(Decl *D) { 1089 visitNode(DynTypedNode::create(*D)); 1090 return true; 1091 } 1092 1093 // We have to use Traverse* because there is no corresponding Visit*. 1094 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) { 1095 if (!L.getNestedNameSpecifier()) 1096 return true; 1097 visitNode(DynTypedNode::create(L)); 1098 // Inner type is missing information about its qualifier, skip it. 1099 if (auto TL = L.getTypeLoc()) 1100 TypeLocsToSkip.insert(TL.getBeginLoc()); 1101 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L); 1102 } 1103 1104 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { 1105 visitNode(DynTypedNode::create(*Init)); 1106 return RecursiveASTVisitor::TraverseConstructorInitializer(Init); 1107 } 1108 1109 private: 1110 /// Obtain information about a reference directly defined in \p N. Does not 1111 /// recurse into child nodes, e.g. do not expect references for constructor 1112 /// initializers 1113 /// 1114 /// Any of the fields in the returned structure can be empty, but not all of 1115 /// them, e.g. 1116 /// - for implicitly generated nodes (e.g. MemberExpr from range-based-for), 1117 /// source location information may be missing, 1118 /// - for dependent code, targets may be empty. 1119 /// 1120 /// (!) For the purposes of this function declarations are not considered to 1121 /// be references. However, declarations can have references inside them, 1122 /// e.g. 'namespace foo = std' references namespace 'std' and this 1123 /// function will return the corresponding reference. 1124 llvm::SmallVector<ReferenceLoc> explicitReference(DynTypedNode N) { 1125 if (auto *D = N.get<Decl>()) 1126 return refInDecl(D); 1127 if (auto *S = N.get<Stmt>()) 1128 return refInStmt(S); 1129 if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) { 1130 // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases. 1131 return {ReferenceLoc{ 1132 NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false, 1133 explicitReferenceTargets( 1134 DynTypedNode::create(*NNSL->getNestedNameSpecifier()), 1135 DeclRelation::Alias)}}; 1136 } 1137 if (const TypeLoc *TL = N.get<TypeLoc>()) 1138 return refInTypeLoc(*TL); 1139 if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) { 1140 // Other type initializers (e.g. base initializer) are handled by visiting 1141 // the typeLoc. 1142 if (CCI->isAnyMemberInitializer()) { 1143 return {ReferenceLoc{NestedNameSpecifierLoc(), 1144 CCI->getMemberLocation(), 1145 /*IsDecl=*/false, 1146 {CCI->getAnyMember()}}}; 1147 } 1148 } 1149 // We do not have location information for other nodes (QualType, etc) 1150 return {}; 1151 } 1152 1153 void visitNode(DynTypedNode N) { 1154 for (const auto &R : explicitReference(N)) 1155 reportReference(R, N); 1156 } 1157 1158 void reportReference(const ReferenceLoc &Ref, DynTypedNode N) { 1159 // Our promise is to return only references from the source code. If we lack 1160 // location information, skip these nodes. 1161 // Normally this should not happen in practice, unless there are bugs in the 1162 // traversals or users started the traversal at an implicit node. 1163 if (Ref.NameLoc.isInvalid()) { 1164 dlog("invalid location at node {0}", nodeToString(N)); 1165 return; 1166 } 1167 Out(Ref); 1168 } 1169 1170 llvm::function_ref<void(ReferenceLoc)> Out; 1171 /// TypeLocs starting at these locations must be skipped, see 1172 /// TraverseElaboratedTypeSpecifierLoc for details. 1173 llvm::DenseSet<SourceLocation> TypeLocsToSkip; 1174 }; 1175 } // namespace 1176 1177 void findExplicitReferences(const Stmt *S, 1178 llvm::function_ref<void(ReferenceLoc)> Out) { 1179 assert(S); 1180 ExplicitReferenceCollector(Out).TraverseStmt(const_cast<Stmt *>(S)); 1181 } 1182 void findExplicitReferences(const Decl *D, 1183 llvm::function_ref<void(ReferenceLoc)> Out) { 1184 assert(D); 1185 ExplicitReferenceCollector(Out).TraverseDecl(const_cast<Decl *>(D)); 1186 } 1187 void findExplicitReferences(const ASTContext &AST, 1188 llvm::function_ref<void(ReferenceLoc)> Out) { 1189 ExplicitReferenceCollector(Out).TraverseAST(const_cast<ASTContext &>(AST)); 1190 } 1191 1192 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) { 1193 switch (R) { 1194 #define REL_CASE(X) \ 1195 case DeclRelation::X: \ 1196 return OS << #X; 1197 REL_CASE(Alias); 1198 REL_CASE(Underlying); 1199 REL_CASE(TemplateInstantiation); 1200 REL_CASE(TemplatePattern); 1201 #undef REL_CASE 1202 } 1203 llvm_unreachable("Unhandled DeclRelation enum"); 1204 } 1205 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) { 1206 const char *Sep = ""; 1207 for (unsigned I = 0; I < RS.S.size(); ++I) { 1208 if (RS.S.test(I)) { 1209 OS << Sep << static_cast<DeclRelation>(I); 1210 Sep = "|"; 1211 } 1212 } 1213 return OS; 1214 } 1215 1216 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) { 1217 // note we cannot print R.NameLoc without a source manager. 1218 OS << "targets = {"; 1219 bool First = true; 1220 for (const NamedDecl *T : R.Targets) { 1221 if (!First) 1222 OS << ", "; 1223 else 1224 First = false; 1225 OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T); 1226 } 1227 OS << "}"; 1228 if (R.Qualifier) { 1229 OS << ", qualifier = '"; 1230 R.Qualifier.getNestedNameSpecifier()->print(OS, 1231 PrintingPolicy(LangOptions())); 1232 OS << "'"; 1233 } 1234 if (R.IsDecl) 1235 OS << ", decl"; 1236 return OS; 1237 } 1238 1239 } // namespace clangd 1240 } // namespace clang 1241