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 resolveExprToDecls.
167 const Type *resolveExprToType(const Expr *E);
168 
169 // Try to heuristically resolve a possibly-dependent expression `E` to one
170 // or more declarations that it likely references.
171 std::vector<const NamedDecl *> resolveExprToDecls(const Expr *E) {
172   if (const auto *ME = dyn_cast<CXXDependentScopeMemberExpr>(E)) {
173     const Type *BaseType = ME->getBaseType().getTypePtrOrNull();
174     if (ME->isArrow()) {
175       BaseType = getPointeeType(BaseType);
176     }
177     if (!BaseType)
178       return {};
179     if (const auto *BT = BaseType->getAs<BuiltinType>()) {
180       // If BaseType is the type of a dependent expression, it's just
181       // represented as BultinType::Dependent which gives us no information. We
182       // can get further by analyzing the depedent expression.
183       Expr *Base = ME->isImplicitAccess() ? nullptr : ME->getBase();
184       if (Base && BT->getKind() == BuiltinType::Dependent) {
185         BaseType = resolveExprToType(Base);
186       }
187     }
188     return getMembersReferencedViaDependentName(
189         BaseType, [ME](ASTContext &) { return ME->getMember(); },
190         /*IsNonstaticMember=*/true);
191   }
192   if (const auto *RE = dyn_cast<DependentScopeDeclRefExpr>(E)) {
193     return getMembersReferencedViaDependentName(
194         RE->getQualifier()->getAsType(),
195         [RE](ASTContext &) { return RE->getDeclName(); },
196         /*IsNonstaticMember=*/false);
197   }
198   if (const auto *CE = dyn_cast<CallExpr>(E)) {
199     const auto *CalleeType = resolveExprToType(CE->getCallee());
200     if (!CalleeType)
201       return {};
202     if (const auto *FnTypePtr = CalleeType->getAs<PointerType>())
203       CalleeType = FnTypePtr->getPointeeType().getTypePtr();
204     if (const FunctionType *FnType = CalleeType->getAs<FunctionType>()) {
205       if (const auto *D =
206               resolveTypeToRecordDecl(FnType->getReturnType().getTypePtr())) {
207         return {D};
208       }
209     }
210   }
211   if (const auto *ME = dyn_cast<MemberExpr>(E))
212     return {ME->getMemberDecl()};
213   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
214     return {DRE->getFoundDecl()};
215   return {};
216 }
217 
218 // Try to heuristically resolve the type of a possibly-dependent expression `E`.
219 const Type *resolveExprToType(const Expr *E) {
220   std::vector<const NamedDecl *> Decls = resolveExprToDecls(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     } else if (const ObjCImplementationDecl *IID =
359                    dyn_cast<ObjCImplementationDecl>(D)) {
360       // Treat ObjC{Interface,Implementation}Decl as if they were a decl/def
361       // pair as long as the interface isn't implicit.
362       if (const auto *CID = IID->getClassInterface())
363         if (const auto *DD = CID->getDefinition())
364           if (!DD->isImplicitInterfaceDecl())
365             D = DD;
366     } else if (const ObjCCategoryImplDecl *CID =
367                    dyn_cast<ObjCCategoryImplDecl>(D)) {
368       // Treat ObjC{Category,CategoryImpl}Decl as if they were a decl/def pair.
369       D = CID->getCategoryDecl();
370     }
371     if (!D)
372       return;
373 
374     if (const Decl *Pat = getTemplatePattern(D)) {
375       assert(Pat != D);
376       add(Pat, Flags | Rel::TemplatePattern);
377       // Now continue with the instantiation.
378       Flags |= Rel::TemplateInstantiation;
379     }
380 
381     report(D, Flags);
382   }
383 
384   void add(const Stmt *S, RelSet Flags) {
385     if (!S)
386       return;
387     debug(*S, Flags);
388     struct Visitor : public ConstStmtVisitor<Visitor> {
389       TargetFinder &Outer;
390       RelSet Flags;
391       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
392 
393       void VisitCallExpr(const CallExpr *CE) {
394         Outer.add(CE->getCalleeDecl(), Flags);
395       }
396       void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
397         Outer.add(E->getNamedConcept(), Flags);
398       }
399       void VisitDeclRefExpr(const DeclRefExpr *DRE) {
400         const Decl *D = DRE->getDecl();
401         // UsingShadowDecl allows us to record the UsingDecl.
402         // getFoundDecl() returns the wrong thing in other cases (templates).
403         if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl()))
404           D = USD;
405         Outer.add(D, Flags);
406       }
407       void VisitMemberExpr(const MemberExpr *ME) {
408         const Decl *D = ME->getMemberDecl();
409         if (auto *USD =
410                 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl()))
411           D = USD;
412         Outer.add(D, Flags);
413       }
414       void VisitOverloadExpr(const OverloadExpr *OE) {
415         for (auto *D : OE->decls())
416           Outer.add(D, Flags);
417       }
418       void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) {
419         Outer.add(SE->getPack(), Flags);
420       }
421       void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
422         Outer.add(CCE->getConstructor(), Flags);
423       }
424       void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
425         for (const DesignatedInitExpr::Designator &D :
426              llvm::reverse(DIE->designators()))
427           if (D.isFieldDesignator()) {
428             Outer.add(D.getField(), Flags);
429             // We don't know which designator was intended, we assume the outer.
430             break;
431           }
432       }
433       void VisitGotoStmt(const GotoStmt *Goto) {
434         if (auto *LabelDecl = Goto->getLabel())
435           Outer.add(LabelDecl, Flags);
436       }
437       void VisitLabelStmt(const LabelStmt *Label) {
438         if (auto *LabelDecl = Label->getDecl())
439           Outer.add(LabelDecl, Flags);
440       }
441       void
442       VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
443         for (const NamedDecl *D : resolveExprToDecls(E)) {
444           Outer.add(D, Flags);
445         }
446       }
447       void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
448         for (const NamedDecl *D : resolveExprToDecls(E)) {
449           Outer.add(D, Flags);
450         }
451       }
452       void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
453         Outer.add(OIRE->getDecl(), Flags);
454       }
455       void VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
456         Outer.add(OME->getMethodDecl(), Flags);
457       }
458       void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
459         if (OPRE->isExplicitProperty())
460           Outer.add(OPRE->getExplicitProperty(), Flags);
461         else {
462           if (OPRE->isMessagingGetter())
463             Outer.add(OPRE->getImplicitPropertyGetter(), Flags);
464           if (OPRE->isMessagingSetter())
465             Outer.add(OPRE->getImplicitPropertySetter(), Flags);
466         }
467       }
468       void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
469         Outer.add(OPE->getProtocol(), Flags);
470       }
471       void VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
472         Outer.add(OVE->getSourceExpr(), Flags);
473       }
474       void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
475         Outer.add(POE->getSyntacticForm(), Flags);
476       }
477       void VisitCXXNewExpr(const CXXNewExpr *CNE) {
478         Outer.add(CNE->getOperatorNew(), Flags);
479       }
480       void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE) {
481         Outer.add(CDE->getOperatorDelete(), Flags);
482       }
483     };
484     Visitor(*this, Flags).Visit(S);
485   }
486 
487   void add(QualType T, RelSet Flags) {
488     if (T.isNull())
489       return;
490     debug(T, Flags);
491     struct Visitor : public TypeVisitor<Visitor> {
492       TargetFinder &Outer;
493       RelSet Flags;
494       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
495 
496       void VisitTagType(const TagType *TT) {
497         Outer.add(TT->getAsTagDecl(), Flags);
498       }
499 
500       void VisitElaboratedType(const ElaboratedType *ET) {
501         Outer.add(ET->desugar(), Flags);
502       }
503 
504       void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
505         Outer.add(ICNT->getDecl(), Flags);
506       }
507 
508       void VisitDecltypeType(const DecltypeType *DTT) {
509         Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
510       }
511       void VisitDeducedType(const DeducedType *DT) {
512         // FIXME: In practice this doesn't work: the AutoType you find inside
513         // TypeLoc never has a deduced type. https://llvm.org/PR42914
514         Outer.add(DT->getDeducedType(), Flags | Rel::Underlying);
515       }
516       void VisitDeducedTemplateSpecializationType(
517           const DeducedTemplateSpecializationType *DTST) {
518         // FIXME: This is a workaround for https://llvm.org/PR42914,
519         // which is causing DTST->getDeducedType() to be empty. We
520         // fall back to the template pattern and miss the instantiation
521         // even when it's known in principle. Once that bug is fixed,
522         // this method can be removed (the existing handling in
523         // VisitDeducedType() is sufficient).
524         if (auto *TD = DTST->getTemplateName().getAsTemplateDecl())
525           Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
526       }
527       void VisitTypedefType(const TypedefType *TT) {
528         Outer.add(TT->getDecl(), Flags);
529       }
530       void
531       VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
532         // Have to handle these case-by-case.
533 
534         // templated type aliases: there's no specialized/instantiated using
535         // decl to point to. So try to find a decl for the underlying type
536         // (after substitution), and failing that point to the (templated) using
537         // decl.
538         if (TST->isTypeAlias()) {
539           Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
540           // Don't *traverse* the alias, which would result in traversing the
541           // template of the underlying type.
542           Outer.report(
543               TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
544               Flags | Rel::Alias | Rel::TemplatePattern);
545         }
546         // specializations of template template parameters aren't instantiated
547         // into decls, so they must refer to the parameter itself.
548         else if (const auto *Parm =
549                      llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
550                          TST->getTemplateName().getAsTemplateDecl()))
551           Outer.add(Parm, Flags);
552         // class template specializations have a (specialized) CXXRecordDecl.
553         else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
554           Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
555         else {
556           // fallback: the (un-specialized) declaration from primary template.
557           if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
558             Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
559         }
560       }
561       void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
562         Outer.add(TTPT->getDecl(), Flags);
563       }
564       void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
565         Outer.add(OIT->getDecl(), Flags);
566       }
567       void VisitObjCObjectType(const ObjCObjectType *OOT) {
568         // FIXME: ObjCObjectTypeLoc has no children for the protocol list, so
569         // there is no node in id<Foo> that refers to ObjCProtocolDecl Foo.
570         if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1)
571           Outer.add(OOT->getProtocol(0), Flags);
572       }
573     };
574     Visitor(*this, Flags).Visit(T.getTypePtr());
575   }
576 
577   void add(const NestedNameSpecifier *NNS, RelSet Flags) {
578     if (!NNS)
579       return;
580     debug(*NNS, Flags);
581     switch (NNS->getKind()) {
582     case NestedNameSpecifier::Identifier:
583       return;
584     case NestedNameSpecifier::Namespace:
585       add(NNS->getAsNamespace(), Flags);
586       return;
587     case NestedNameSpecifier::NamespaceAlias:
588       add(NNS->getAsNamespaceAlias(), Flags);
589       return;
590     case NestedNameSpecifier::TypeSpec:
591     case NestedNameSpecifier::TypeSpecWithTemplate:
592       add(QualType(NNS->getAsType(), 0), Flags);
593       return;
594     case NestedNameSpecifier::Global:
595       // This should be TUDecl, but we can't get a pointer to it!
596       return;
597     case NestedNameSpecifier::Super:
598       add(NNS->getAsRecordDecl(), Flags);
599       return;
600     }
601     llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
602   }
603 
604   void add(const CXXCtorInitializer *CCI, RelSet Flags) {
605     if (!CCI)
606       return;
607     debug(*CCI, Flags);
608 
609     if (CCI->isAnyMemberInitializer())
610       add(CCI->getAnyMember(), Flags);
611     // Constructor calls contain a TypeLoc node, so we don't handle them here.
612   }
613 
614   void add(const TemplateArgument &Arg, RelSet Flags) {
615     // Only used for template template arguments.
616     // For type and non-type template arguments, SelectionTree
617     // will hit a more specific node (e.g. a TypeLoc or a
618     // DeclRefExpr).
619     if (Arg.getKind() == TemplateArgument::Template ||
620         Arg.getKind() == TemplateArgument::TemplateExpansion) {
621       if (TemplateDecl *TD = Arg.getAsTemplate().getAsTemplateDecl()) {
622         report(TD, Flags);
623       }
624     }
625   }
626 };
627 
628 } // namespace
629 
630 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
631 allTargetDecls(const ast_type_traits::DynTypedNode &N) {
632   dlog("allTargetDecls({0})", nodeToString(N));
633   TargetFinder Finder;
634   DeclRelationSet Flags;
635   if (const Decl *D = N.get<Decl>())
636     Finder.add(D, Flags);
637   else if (const Stmt *S = N.get<Stmt>())
638     Finder.add(S, Flags);
639   else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
640     Finder.add(NNSL->getNestedNameSpecifier(), Flags);
641   else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
642     Finder.add(NNS, Flags);
643   else if (const TypeLoc *TL = N.get<TypeLoc>())
644     Finder.add(TL->getType(), Flags);
645   else if (const QualType *QT = N.get<QualType>())
646     Finder.add(*QT, Flags);
647   else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
648     Finder.add(CCI, Flags);
649   else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>())
650     Finder.add(TAL->getArgument(), Flags);
651 
652   return Finder.takeDecls();
653 }
654 
655 llvm::SmallVector<const NamedDecl *, 1>
656 targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
657   llvm::SmallVector<const NamedDecl *, 1> Result;
658   for (const auto &Entry : allTargetDecls(N)) {
659     if (!(Entry.second & ~Mask))
660       Result.push_back(Entry.first);
661   }
662   return Result;
663 }
664 
665 llvm::SmallVector<const NamedDecl *, 1>
666 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask) {
667   assert(!(Mask & (DeclRelation::TemplatePattern |
668                    DeclRelation::TemplateInstantiation)) &&
669          "explicitReferenceTargets handles templates on its own");
670   auto Decls = allTargetDecls(N);
671 
672   // We prefer to return template instantiation, but fallback to template
673   // pattern if instantiation is not available.
674   Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
675 
676   llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
677   llvm::SmallVector<const NamedDecl *, 1> Targets;
678   bool SeenTemplateInstantiations = false;
679   for (auto &D : Decls) {
680     if (D.second & ~Mask)
681       continue;
682     if (D.second & DeclRelation::TemplatePattern) {
683       TemplatePatterns.push_back(D.first);
684       continue;
685     }
686     if (D.second & DeclRelation::TemplateInstantiation)
687       SeenTemplateInstantiations = true;
688     Targets.push_back(D.first);
689   }
690   if (!SeenTemplateInstantiations)
691     Targets.insert(Targets.end(), TemplatePatterns.begin(),
692                    TemplatePatterns.end());
693   return Targets;
694 }
695 
696 namespace {
697 llvm::SmallVector<ReferenceLoc, 2> refInDecl(const Decl *D) {
698   struct Visitor : ConstDeclVisitor<Visitor> {
699     llvm::SmallVector<ReferenceLoc, 2> Refs;
700 
701     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
702       // We want to keep it as non-declaration references, as the
703       // "using namespace" declaration doesn't have a name.
704       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
705                                   D->getIdentLocation(),
706                                   /*IsDecl=*/false,
707                                   {D->getNominatedNamespaceAsWritten()}});
708     }
709 
710     void VisitUsingDecl(const UsingDecl *D) {
711       // "using ns::identifier;" is a non-declaration reference.
712       Refs.push_back(
713           ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
714                        explicitReferenceTargets(DynTypedNode::create(*D),
715                                                 DeclRelation::Underlying)});
716     }
717 
718     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
719       // For namespace alias, "namespace Foo = Target;", we add two references.
720       // Add a declaration reference for Foo.
721       VisitNamedDecl(D);
722       // Add a non-declaration reference for Target.
723       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
724                                   D->getTargetNameLoc(),
725                                   /*IsDecl=*/false,
726                                   {D->getAliasedNamespace()}});
727     }
728 
729     void VisitNamedDecl(const NamedDecl *ND) {
730       // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As
731       // as their underlying decls, covering the same range, will be visited.
732       if (llvm::isa<ClassTemplateDecl>(ND) ||
733           llvm::isa<FunctionTemplateDecl>(ND) ||
734           llvm::isa<VarTemplateDecl>(ND) ||
735           llvm::isa<TypeAliasTemplateDecl>(ND))
736         return;
737       // FIXME: decide on how to surface destructors when we need them.
738       if (llvm::isa<CXXDestructorDecl>(ND))
739         return;
740       // Filter anonymous decls, name location will point outside the name token
741       // and the clients are not prepared to handle that.
742       if (ND->getDeclName().isIdentifier() &&
743           !ND->getDeclName().getAsIdentifierInfo())
744         return;
745       Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
746                                   ND->getLocation(),
747                                   /*IsDecl=*/true,
748                                   {ND}});
749     }
750 
751     void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) {
752       // The class template name in a deduction guide targets the class
753       // template.
754       Refs.push_back(ReferenceLoc{DG->getQualifierLoc(),
755                                   DG->getNameInfo().getLoc(),
756                                   /*IsDecl=*/false,
757                                   {DG->getDeducedTemplate()}});
758     }
759   };
760 
761   Visitor V;
762   V.Visit(D);
763   return V.Refs;
764 }
765 
766 llvm::SmallVector<ReferenceLoc, 2> refInStmt(const Stmt *S) {
767   struct Visitor : ConstStmtVisitor<Visitor> {
768     // FIXME: handle more complicated cases: more ObjC, designated initializers.
769     llvm::SmallVector<ReferenceLoc, 2> Refs;
770 
771     void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
772       Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(),
773                                   E->getConceptNameLoc(),
774                                   /*IsDecl=*/false,
775                                   {E->getNamedConcept()}});
776     }
777 
778     void VisitDeclRefExpr(const DeclRefExpr *E) {
779       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
780                                   E->getNameInfo().getLoc(),
781                                   /*IsDecl=*/false,
782                                   {E->getFoundDecl()}});
783     }
784 
785     void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
786       Refs.push_back(ReferenceLoc{
787           E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false,
788           explicitReferenceTargets(DynTypedNode::create(*E), {})});
789     }
790 
791     void VisitMemberExpr(const MemberExpr *E) {
792       // Skip destructor calls to avoid duplication: TypeLoc within will be
793       // visited separately.
794       if (llvm::dyn_cast<CXXDestructorDecl>(E->getFoundDecl().getDecl()))
795         return;
796       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
797                                   E->getMemberNameInfo().getLoc(),
798                                   /*IsDecl=*/false,
799                                   {E->getFoundDecl()}});
800     }
801 
802     void
803     VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
804       Refs.push_back(
805           ReferenceLoc{E->getQualifierLoc(), E->getMemberNameInfo().getLoc(),
806                        /*IsDecl=*/false,
807                        explicitReferenceTargets(DynTypedNode::create(*E), {})});
808     }
809 
810     void VisitOverloadExpr(const OverloadExpr *E) {
811       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
812                                   E->getNameInfo().getLoc(),
813                                   /*IsDecl=*/false,
814                                   llvm::SmallVector<const NamedDecl *, 1>(
815                                       E->decls().begin(), E->decls().end())});
816     }
817 
818     void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
819       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
820                                   E->getPackLoc(),
821                                   /*IsDecl=*/false,
822                                   {E->getPack()}});
823     }
824 
825     void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
826       Refs.push_back(ReferenceLoc{
827           NestedNameSpecifierLoc(), E->getLocation(),
828           /*IsDecl=*/false,
829           // Select the getter, setter, or @property depending on the call.
830           explicitReferenceTargets(DynTypedNode::create(*E), {})});
831     }
832 
833     void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
834       for (const DesignatedInitExpr::Designator &D : DIE->designators()) {
835         if (!D.isFieldDesignator())
836           continue;
837 
838         llvm::SmallVector<const NamedDecl *, 1> Targets;
839         if (D.getField())
840           Targets.push_back(D.getField());
841         Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), D.getFieldLoc(),
842                                     /*IsDecl=*/false, std::move(Targets)});
843       }
844     }
845 
846     void VisitGotoStmt(const GotoStmt *GS) {
847       llvm::SmallVector<const NamedDecl *, 1> Targets;
848       if (const auto *L = GS->getLabel())
849         Targets.push_back(L);
850       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), GS->getLabelLoc(),
851                                   /*IsDecl=*/false, std::move(Targets)});
852     }
853 
854     void VisitLabelStmt(const LabelStmt *LS) {
855       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
856                                   LS->getIdentLoc(),
857                                   /*IsDecl=*/true,
858                                   {LS->getDecl()}});
859     }
860   };
861 
862   Visitor V;
863   V.Visit(S);
864   return V.Refs;
865 }
866 
867 llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
868   struct Visitor : TypeLocVisitor<Visitor> {
869     llvm::Optional<ReferenceLoc> Ref;
870 
871     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
872       // We only know about qualifier, rest if filled by inner locations.
873       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
874       // Fill in the qualifier.
875       if (!Ref)
876         return;
877       assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
878       Ref->Qualifier = L.getQualifierLoc();
879     }
880 
881     void VisitTagTypeLoc(TagTypeLoc L) {
882       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
883                          L.getNameLoc(),
884                          /*IsDecl=*/false,
885                          {L.getDecl()}};
886     }
887 
888     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
889       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
890                          L.getNameLoc(),
891                          /*IsDecl=*/false,
892                          {L.getDecl()}};
893     }
894 
895     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
896       // We must ensure template type aliases are included in results if they
897       // were written in the source code, e.g. in
898       //    template <class T> using valias = vector<T>;
899       //    ^valias<int> x;
900       // 'explicitReferenceTargets' will return:
901       //    1. valias with mask 'Alias'.
902       //    2. 'vector<int>' with mask 'Underlying'.
903       //  we want to return only #1 in this case.
904       Ref = ReferenceLoc{
905           NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
906           explicitReferenceTargets(DynTypedNode::create(L.getType()),
907                                    DeclRelation::Alias)};
908     }
909     void VisitDeducedTemplateSpecializationTypeLoc(
910         DeducedTemplateSpecializationTypeLoc L) {
911       Ref = ReferenceLoc{
912           NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
913           explicitReferenceTargets(DynTypedNode::create(L.getType()),
914                                    DeclRelation::Alias)};
915     }
916 
917     void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
918       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
919                          TL.getNameLoc(),
920                          /*IsDecl=*/false,
921                          {TL.getDecl()}};
922     }
923 
924     void VisitDependentTemplateSpecializationTypeLoc(
925         DependentTemplateSpecializationTypeLoc L) {
926       Ref = ReferenceLoc{
927           L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
928           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
929     }
930 
931     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
932       Ref = ReferenceLoc{
933           L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
934           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
935     }
936 
937     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
938       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
939                          L.getNameLoc(),
940                          /*IsDecl=*/false,
941                          {L.getTypedefNameDecl()}};
942     }
943   };
944 
945   Visitor V;
946   V.Visit(L.getUnqualifiedLoc());
947   if (!V.Ref)
948     return {};
949   return {*V.Ref};
950 }
951 
952 class ExplicitReferenceCollector
953     : public RecursiveASTVisitor<ExplicitReferenceCollector> {
954 public:
955   ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out)
956       : Out(Out) {
957     assert(Out);
958   }
959 
960   bool VisitTypeLoc(TypeLoc TTL) {
961     if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
962       return true;
963     visitNode(DynTypedNode::create(TTL));
964     return true;
965   }
966 
967   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
968     // ElaboratedTypeLoc will reports information for its inner type loc.
969     // Otherwise we loose information about inner types loc's qualifier.
970     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
971     TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
972     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
973   }
974 
975   bool VisitStmt(Stmt *S) {
976     visitNode(DynTypedNode::create(*S));
977     return true;
978   }
979 
980   bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
981     visitNode(DynTypedNode::create(*OVE));
982     // Not clear why the source expression is skipped by default...
983     // FIXME: can we just make RecursiveASTVisitor do this?
984     return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
985   }
986 
987   bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
988     visitNode(DynTypedNode::create(*POE));
989     // Traverse only the syntactic form to find the *written* references.
990     // (The semantic form also contains lots of duplication)
991     return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
992   }
993 
994   // We re-define Traverse*, since there's no corresponding Visit*.
995   // TemplateArgumentLoc is the only way to get locations for references to
996   // template template parameters.
997   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
998     llvm::SmallVector<const NamedDecl *, 1> Targets;
999     switch (A.getArgument().getKind()) {
1000     case TemplateArgument::Template:
1001     case TemplateArgument::TemplateExpansion:
1002       if (const auto *D = A.getArgument()
1003                               .getAsTemplateOrTemplatePattern()
1004                               .getAsTemplateDecl())
1005         Targets.push_back(D);
1006       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
1007                                    A.getTemplateNameLoc(),
1008                                    /*IsDecl=*/false, Targets},
1009                       DynTypedNode::create(A.getArgument()));
1010       break;
1011     case TemplateArgument::Declaration:
1012       break; // FIXME: can this actually happen in TemplateArgumentLoc?
1013     case TemplateArgument::Integral:
1014     case TemplateArgument::Null:
1015     case TemplateArgument::NullPtr:
1016       break; // no references.
1017     case TemplateArgument::Pack:
1018     case TemplateArgument::Type:
1019     case TemplateArgument::Expression:
1020       break; // Handled by VisitType and VisitExpression.
1021     };
1022     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
1023   }
1024 
1025   bool VisitDecl(Decl *D) {
1026     visitNode(DynTypedNode::create(*D));
1027     return true;
1028   }
1029 
1030   // We have to use Traverse* because there is no corresponding Visit*.
1031   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
1032     if (!L.getNestedNameSpecifier())
1033       return true;
1034     visitNode(DynTypedNode::create(L));
1035     // Inner type is missing information about its qualifier, skip it.
1036     if (auto TL = L.getTypeLoc())
1037       TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
1038     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
1039   }
1040 
1041   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
1042     visitNode(DynTypedNode::create(*Init));
1043     return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
1044   }
1045 
1046 private:
1047   /// Obtain information about a reference directly defined in \p N. Does not
1048   /// recurse into child nodes, e.g. do not expect references for constructor
1049   /// initializers
1050   ///
1051   /// Any of the fields in the returned structure can be empty, but not all of
1052   /// them, e.g.
1053   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
1054   ///     source location information may be missing,
1055   ///   - for dependent code, targets may be empty.
1056   ///
1057   /// (!) For the purposes of this function declarations are not considered to
1058   ///     be references. However, declarations can have references inside them,
1059   ///     e.g. 'namespace foo = std' references namespace 'std' and this
1060   ///     function will return the corresponding reference.
1061   llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
1062     if (auto *D = N.get<Decl>())
1063       return refInDecl(D);
1064     if (auto *S = N.get<Stmt>())
1065       return refInStmt(S);
1066     if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
1067       // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
1068       return {ReferenceLoc{
1069           NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
1070           explicitReferenceTargets(
1071               DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
1072               DeclRelation::Alias)}};
1073     }
1074     if (const TypeLoc *TL = N.get<TypeLoc>())
1075       return refInTypeLoc(*TL);
1076     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
1077       // Other type initializers (e.g. base initializer) are handled by visiting
1078       // the typeLoc.
1079       if (CCI->isAnyMemberInitializer()) {
1080         return {ReferenceLoc{NestedNameSpecifierLoc(),
1081                              CCI->getMemberLocation(),
1082                              /*IsDecl=*/false,
1083                              {CCI->getAnyMember()}}};
1084       }
1085     }
1086     // We do not have location information for other nodes (QualType, etc)
1087     return {};
1088   }
1089 
1090   void visitNode(DynTypedNode N) {
1091     for (const auto &R : explicitReference(N))
1092       reportReference(R, N);
1093   }
1094 
1095   void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
1096     // Our promise is to return only references from the source code. If we lack
1097     // location information, skip these nodes.
1098     // Normally this should not happen in practice, unless there are bugs in the
1099     // traversals or users started the traversal at an implicit node.
1100     if (Ref.NameLoc.isInvalid()) {
1101       dlog("invalid location at node {0}", nodeToString(N));
1102       return;
1103     }
1104     Out(Ref);
1105   }
1106 
1107   llvm::function_ref<void(ReferenceLoc)> Out;
1108   /// TypeLocs starting at these locations must be skipped, see
1109   /// TraverseElaboratedTypeSpecifierLoc for details.
1110   llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
1111 };
1112 } // namespace
1113 
1114 void findExplicitReferences(const Stmt *S,
1115                             llvm::function_ref<void(ReferenceLoc)> Out) {
1116   assert(S);
1117   ExplicitReferenceCollector(Out).TraverseStmt(const_cast<Stmt *>(S));
1118 }
1119 void findExplicitReferences(const Decl *D,
1120                             llvm::function_ref<void(ReferenceLoc)> Out) {
1121   assert(D);
1122   ExplicitReferenceCollector(Out).TraverseDecl(const_cast<Decl *>(D));
1123 }
1124 void findExplicitReferences(const ASTContext &AST,
1125                             llvm::function_ref<void(ReferenceLoc)> Out) {
1126   ExplicitReferenceCollector(Out).TraverseAST(const_cast<ASTContext &>(AST));
1127 }
1128 
1129 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
1130   switch (R) {
1131 #define REL_CASE(X)                                                            \
1132   case DeclRelation::X:                                                        \
1133     return OS << #X;
1134     REL_CASE(Alias);
1135     REL_CASE(Underlying);
1136     REL_CASE(TemplateInstantiation);
1137     REL_CASE(TemplatePattern);
1138 #undef REL_CASE
1139   }
1140   llvm_unreachable("Unhandled DeclRelation enum");
1141 }
1142 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
1143   const char *Sep = "";
1144   for (unsigned I = 0; I < RS.S.size(); ++I) {
1145     if (RS.S.test(I)) {
1146       OS << Sep << static_cast<DeclRelation>(I);
1147       Sep = "|";
1148     }
1149   }
1150   return OS;
1151 }
1152 
1153 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
1154   // note we cannot print R.NameLoc without a source manager.
1155   OS << "targets = {";
1156   bool First = true;
1157   for (const NamedDecl *T : R.Targets) {
1158     if (!First)
1159       OS << ", ";
1160     else
1161       First = false;
1162     OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
1163   }
1164   OS << "}";
1165   if (R.Qualifier) {
1166     OS << ", qualifier = '";
1167     R.Qualifier.getNestedNameSpecifier()->print(OS,
1168                                                 PrintingPolicy(LangOptions()));
1169     OS << "'";
1170   }
1171   if (R.IsDecl)
1172     OS << ", decl";
1173   return OS;
1174 }
1175 
1176 } // namespace clangd
1177 } // namespace clang
1178