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