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