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