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