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