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