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