1 //===--- FindTarget.cpp - What does an AST node refer to? -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "FindTarget.h"
10 #include "AST.h"
11 #include "support/Logger.h"
12 #include "clang/AST/ASTTypeTraits.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DeclarationName.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprConcepts.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TemplateBase.h"
27 #include "clang/AST/Type.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeLocVisitor.h"
30 #include "clang/AST/TypeVisitor.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/OperatorKinds.h"
33 #include "clang/Basic/SourceLocation.h"
34 #include "clang/Basic/Specifiers.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <iterator>
41 #include <utility>
42 #include <vector>
43 
44 namespace clang {
45 namespace clangd {
46 namespace {
47 using ast_type_traits::DynTypedNode;
48 
49 LLVM_ATTRIBUTE_UNUSED std::string
50 nodeToString(const ast_type_traits::DynTypedNode &N) {
51   std::string S = std::string(N.getNodeKind().asStringRef());
52   {
53     llvm::raw_string_ostream OS(S);
54     OS << ": ";
55     N.print(OS, PrintingPolicy(LangOptions()));
56   }
57   std::replace(S.begin(), S.end(), '\n', ' ');
58   return S;
59 }
60 
61 // 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> refInStmt(const Stmt *S) {
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     void VisitGotoStmt(const GotoStmt *GS) {
727       llvm::SmallVector<const NamedDecl *, 1> Targets;
728       if (const auto *L = GS->getLabel())
729         Targets.push_back(L);
730       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), GS->getLabelLoc(),
731                                   /*IsDecl=*/false, std::move(Targets)});
732     }
733 
734     void VisitLabelStmt(const LabelStmt *LS) {
735       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
736                                   LS->getIdentLoc(),
737                                   /*IsDecl=*/true,
738                                   {LS->getDecl()}});
739     }
740   };
741 
742   Visitor V;
743   V.Visit(S);
744   return V.Refs;
745 }
746 
747 llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
748   struct Visitor : TypeLocVisitor<Visitor> {
749     llvm::Optional<ReferenceLoc> Ref;
750 
751     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
752       // We only know about qualifier, rest if filled by inner locations.
753       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
754       // Fill in the qualifier.
755       if (!Ref)
756         return;
757       assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
758       Ref->Qualifier = L.getQualifierLoc();
759     }
760 
761     void VisitTagTypeLoc(TagTypeLoc L) {
762       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
763                          L.getNameLoc(),
764                          /*IsDecl=*/false,
765                          {L.getDecl()}};
766     }
767 
768     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
769       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
770                          L.getNameLoc(),
771                          /*IsDecl=*/false,
772                          {L.getDecl()}};
773     }
774 
775     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
776       // We must ensure template type aliases are included in results if they
777       // were written in the source code, e.g. in
778       //    template <class T> using valias = vector<T>;
779       //    ^valias<int> x;
780       // 'explicitReferenceTargets' will return:
781       //    1. valias with mask 'Alias'.
782       //    2. 'vector<int>' with mask 'Underlying'.
783       //  we want to return only #1 in this case.
784       Ref = ReferenceLoc{
785           NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
786           explicitReferenceTargets(DynTypedNode::create(L.getType()),
787                                    DeclRelation::Alias)};
788     }
789     void VisitDeducedTemplateSpecializationTypeLoc(
790         DeducedTemplateSpecializationTypeLoc L) {
791       Ref = ReferenceLoc{
792           NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
793           explicitReferenceTargets(DynTypedNode::create(L.getType()),
794                                    DeclRelation::Alias)};
795     }
796 
797     void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
798       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
799                          TL.getNameLoc(),
800                          /*IsDecl=*/false,
801                          {TL.getDecl()}};
802     }
803 
804     void VisitDependentTemplateSpecializationTypeLoc(
805         DependentTemplateSpecializationTypeLoc L) {
806       Ref = ReferenceLoc{
807           L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
808           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
809     }
810 
811     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
812       Ref = ReferenceLoc{
813           L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
814           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
815     }
816 
817     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
818       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
819                          L.getNameLoc(),
820                          /*IsDecl=*/false,
821                          {L.getTypedefNameDecl()}};
822     }
823   };
824 
825   Visitor V;
826   V.Visit(L.getUnqualifiedLoc());
827   if (!V.Ref)
828     return {};
829   return {*V.Ref};
830 }
831 
832 class ExplicitReferenceCollector
833     : public RecursiveASTVisitor<ExplicitReferenceCollector> {
834 public:
835   ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out)
836       : Out(Out) {
837     assert(Out);
838   }
839 
840   bool VisitTypeLoc(TypeLoc TTL) {
841     if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
842       return true;
843     visitNode(DynTypedNode::create(TTL));
844     return true;
845   }
846 
847   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
848     // ElaboratedTypeLoc will reports information for its inner type loc.
849     // Otherwise we loose information about inner types loc's qualifier.
850     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
851     TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
852     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
853   }
854 
855   bool VisitStmt(Stmt *S) {
856     visitNode(DynTypedNode::create(*S));
857     return true;
858   }
859 
860   bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
861     visitNode(DynTypedNode::create(*OVE));
862     // Not clear why the source expression is skipped by default...
863     // FIXME: can we just make RecursiveASTVisitor do this?
864     return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
865   }
866 
867   bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
868     visitNode(DynTypedNode::create(*POE));
869     // Traverse only the syntactic form to find the *written* references.
870     // (The semantic form also contains lots of duplication)
871     return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
872   }
873 
874   // We re-define Traverse*, since there's no corresponding Visit*.
875   // TemplateArgumentLoc is the only way to get locations for references to
876   // template template parameters.
877   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
878     llvm::SmallVector<const NamedDecl *, 1> Targets;
879     switch (A.getArgument().getKind()) {
880     case TemplateArgument::Template:
881     case TemplateArgument::TemplateExpansion:
882       if (const auto *D = A.getArgument()
883                               .getAsTemplateOrTemplatePattern()
884                               .getAsTemplateDecl())
885         Targets.push_back(D);
886       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
887                                    A.getTemplateNameLoc(),
888                                    /*IsDecl=*/false, Targets},
889                       DynTypedNode::create(A.getArgument()));
890       break;
891     case TemplateArgument::Declaration:
892       break; // FIXME: can this actually happen in TemplateArgumentLoc?
893     case TemplateArgument::Integral:
894     case TemplateArgument::Null:
895     case TemplateArgument::NullPtr:
896       break; // no references.
897     case TemplateArgument::Pack:
898     case TemplateArgument::Type:
899     case TemplateArgument::Expression:
900       break; // Handled by VisitType and VisitExpression.
901     };
902     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
903   }
904 
905   bool VisitDecl(Decl *D) {
906     visitNode(DynTypedNode::create(*D));
907     return true;
908   }
909 
910   // We have to use Traverse* because there is no corresponding Visit*.
911   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
912     if (!L.getNestedNameSpecifier())
913       return true;
914     visitNode(DynTypedNode::create(L));
915     // Inner type is missing information about its qualifier, skip it.
916     if (auto TL = L.getTypeLoc())
917       TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
918     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
919   }
920 
921   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
922     visitNode(DynTypedNode::create(*Init));
923     return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
924   }
925 
926 private:
927   /// Obtain information about a reference directly defined in \p N. Does not
928   /// recurse into child nodes, e.g. do not expect references for constructor
929   /// initializers
930   ///
931   /// Any of the fields in the returned structure can be empty, but not all of
932   /// them, e.g.
933   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
934   ///     source location information may be missing,
935   ///   - for dependent code, targets may be empty.
936   ///
937   /// (!) For the purposes of this function declarations are not considered to
938   ///     be references. However, declarations can have references inside them,
939   ///     e.g. 'namespace foo = std' references namespace 'std' and this
940   ///     function will return the corresponding reference.
941   llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
942     if (auto *D = N.get<Decl>())
943       return refInDecl(D);
944     if (auto *S = N.get<Stmt>())
945       return refInStmt(S);
946     if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
947       // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
948       return {ReferenceLoc{
949           NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
950           explicitReferenceTargets(
951               DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
952               DeclRelation::Alias)}};
953     }
954     if (const TypeLoc *TL = N.get<TypeLoc>())
955       return refInTypeLoc(*TL);
956     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
957       // Other type initializers (e.g. base initializer) are handled by visiting
958       // the typeLoc.
959       if (CCI->isAnyMemberInitializer()) {
960         return {ReferenceLoc{NestedNameSpecifierLoc(),
961                              CCI->getMemberLocation(),
962                              /*IsDecl=*/false,
963                              {CCI->getAnyMember()}}};
964       }
965     }
966     // We do not have location information for other nodes (QualType, etc)
967     return {};
968   }
969 
970   void visitNode(DynTypedNode N) {
971     for (const auto &R : explicitReference(N))
972       reportReference(R, N);
973   }
974 
975   void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
976     // Our promise is to return only references from the source code. If we lack
977     // location information, skip these nodes.
978     // Normally this should not happen in practice, unless there are bugs in the
979     // traversals or users started the traversal at an implicit node.
980     if (Ref.NameLoc.isInvalid()) {
981       dlog("invalid location at node {0}", nodeToString(N));
982       return;
983     }
984     Out(Ref);
985   }
986 
987   llvm::function_ref<void(ReferenceLoc)> Out;
988   /// TypeLocs starting at these locations must be skipped, see
989   /// TraverseElaboratedTypeSpecifierLoc for details.
990   llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
991 };
992 } // namespace
993 
994 void findExplicitReferences(const Stmt *S,
995                             llvm::function_ref<void(ReferenceLoc)> Out) {
996   assert(S);
997   ExplicitReferenceCollector(Out).TraverseStmt(const_cast<Stmt *>(S));
998 }
999 void findExplicitReferences(const Decl *D,
1000                             llvm::function_ref<void(ReferenceLoc)> Out) {
1001   assert(D);
1002   ExplicitReferenceCollector(Out).TraverseDecl(const_cast<Decl *>(D));
1003 }
1004 void findExplicitReferences(const ASTContext &AST,
1005                             llvm::function_ref<void(ReferenceLoc)> Out) {
1006   ExplicitReferenceCollector(Out).TraverseAST(const_cast<ASTContext &>(AST));
1007 }
1008 
1009 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
1010   switch (R) {
1011 #define REL_CASE(X)                                                            \
1012   case DeclRelation::X:                                                        \
1013     return OS << #X;
1014     REL_CASE(Alias);
1015     REL_CASE(Underlying);
1016     REL_CASE(TemplateInstantiation);
1017     REL_CASE(TemplatePattern);
1018 #undef REL_CASE
1019   }
1020   llvm_unreachable("Unhandled DeclRelation enum");
1021 }
1022 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
1023   const char *Sep = "";
1024   for (unsigned I = 0; I < RS.S.size(); ++I) {
1025     if (RS.S.test(I)) {
1026       OS << Sep << static_cast<DeclRelation>(I);
1027       Sep = "|";
1028     }
1029   }
1030   return OS;
1031 }
1032 
1033 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
1034   // note we cannot print R.NameLoc without a source manager.
1035   OS << "targets = {";
1036   bool First = true;
1037   for (const NamedDecl *T : R.Targets) {
1038     if (!First)
1039       OS << ", ";
1040     else
1041       First = false;
1042     OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
1043   }
1044   OS << "}";
1045   if (R.Qualifier) {
1046     OS << ", qualifier = '";
1047     R.Qualifier.getNestedNameSpecifier()->print(OS,
1048                                                 PrintingPolicy(LangOptions()));
1049     OS << "'";
1050   }
1051   if (R.IsDecl)
1052     OS << ", decl";
1053   return OS;
1054 }
1055 
1056 } // namespace clangd
1057 } // namespace clang
1058