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