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