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 VisitElaboratedType(const ElaboratedType *ET) {
383         Outer.add(ET->desugar(), Flags);
384       }
385 
386       void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
387         Outer.add(ICNT->getDecl(), Flags);
388       }
389 
390       void VisitDecltypeType(const DecltypeType *DTT) {
391         Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
392       }
393       void VisitDeducedType(const DeducedType *DT) {
394         // FIXME: In practice this doesn't work: the AutoType you find inside
395         // TypeLoc never has a deduced type. https://llvm.org/PR42914
396         Outer.add(DT->getDeducedType(), Flags | Rel::Underlying);
397       }
398       void VisitDeducedTemplateSpecializationType(
399           const DeducedTemplateSpecializationType *DTST) {
400         // FIXME: This is a workaround for https://llvm.org/PR42914,
401         // which is causing DTST->getDeducedType() to be empty. We
402         // fall back to the template pattern and miss the instantiation
403         // even when it's known in principle. Once that bug is fixed,
404         // this method can be removed (the existing handling in
405         // VisitDeducedType() is sufficient).
406         if (auto *TD = DTST->getTemplateName().getAsTemplateDecl())
407           Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
408       }
409       void VisitTypedefType(const TypedefType *TT) {
410         Outer.add(TT->getDecl(), Flags);
411       }
412       void
413       VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
414         // Have to handle these case-by-case.
415 
416         // templated type aliases: there's no specialized/instantiated using
417         // decl to point to. So try to find a decl for the underlying type
418         // (after substitution), and failing that point to the (templated) using
419         // decl.
420         if (TST->isTypeAlias()) {
421           Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
422           // Don't *traverse* the alias, which would result in traversing the
423           // template of the underlying type.
424           Outer.report(
425               TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
426               Flags | Rel::Alias | Rel::TemplatePattern);
427         }
428         // specializations of template template parameters aren't instantiated
429         // into decls, so they must refer to the parameter itself.
430         else if (const auto *Parm =
431                      llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
432                          TST->getTemplateName().getAsTemplateDecl()))
433           Outer.add(Parm, Flags);
434         // class template specializations have a (specialized) CXXRecordDecl.
435         else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
436           Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
437         else {
438           // fallback: the (un-specialized) declaration from primary template.
439           if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
440             Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
441         }
442       }
443       void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
444         Outer.add(TTPT->getDecl(), Flags);
445       }
446       void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
447         Outer.add(OIT->getDecl(), Flags);
448       }
449       void VisitObjCObjectType(const ObjCObjectType *OOT) {
450         // FIXME: ObjCObjectTypeLoc has no children for the protocol list, so
451         // there is no node in id<Foo> that refers to ObjCProtocolDecl Foo.
452         if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1)
453           Outer.add(OOT->getProtocol(0), Flags);
454       }
455     };
456     Visitor(*this, Flags).Visit(T.getTypePtr());
457   }
458 
459   void add(const NestedNameSpecifier *NNS, RelSet Flags) {
460     if (!NNS)
461       return;
462     debug(*NNS, Flags);
463     switch (NNS->getKind()) {
464     case NestedNameSpecifier::Identifier:
465       return;
466     case NestedNameSpecifier::Namespace:
467       add(NNS->getAsNamespace(), Flags);
468       return;
469     case NestedNameSpecifier::NamespaceAlias:
470       add(NNS->getAsNamespaceAlias(), Flags);
471       return;
472     case NestedNameSpecifier::TypeSpec:
473     case NestedNameSpecifier::TypeSpecWithTemplate:
474       add(QualType(NNS->getAsType(), 0), Flags);
475       return;
476     case NestedNameSpecifier::Global:
477       // This should be TUDecl, but we can't get a pointer to it!
478       return;
479     case NestedNameSpecifier::Super:
480       add(NNS->getAsRecordDecl(), Flags);
481       return;
482     }
483     llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
484   }
485 
486   void add(const CXXCtorInitializer *CCI, RelSet Flags) {
487     if (!CCI)
488       return;
489     debug(*CCI, Flags);
490 
491     if (CCI->isAnyMemberInitializer())
492       add(CCI->getAnyMember(), Flags);
493     // Constructor calls contain a TypeLoc node, so we don't handle them here.
494   }
495 };
496 
497 } // namespace
498 
499 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
500 allTargetDecls(const ast_type_traits::DynTypedNode &N) {
501   dlog("allTargetDecls({0})", nodeToString(N));
502   TargetFinder Finder;
503   DeclRelationSet Flags;
504   if (const Decl *D = N.get<Decl>())
505     Finder.add(D, Flags);
506   else if (const Stmt *S = N.get<Stmt>())
507     Finder.add(S, Flags);
508   else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
509     Finder.add(NNSL->getNestedNameSpecifier(), Flags);
510   else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
511     Finder.add(NNS, Flags);
512   else if (const TypeLoc *TL = N.get<TypeLoc>())
513     Finder.add(TL->getType(), Flags);
514   else if (const QualType *QT = N.get<QualType>())
515     Finder.add(*QT, Flags);
516   else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
517     Finder.add(CCI, Flags);
518 
519   return Finder.takeDecls();
520 }
521 
522 llvm::SmallVector<const NamedDecl *, 1>
523 targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
524   llvm::SmallVector<const NamedDecl *, 1> Result;
525   for (const auto &Entry : allTargetDecls(N)) {
526     if (!(Entry.second & ~Mask))
527       Result.push_back(Entry.first);
528   }
529   return Result;
530 }
531 
532 llvm::SmallVector<const NamedDecl *, 1>
533 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask) {
534   assert(!(Mask & (DeclRelation::TemplatePattern |
535                    DeclRelation::TemplateInstantiation)) &&
536          "explicitRefenceTargets handles templates on its own");
537   auto Decls = allTargetDecls(N);
538 
539   // We prefer to return template instantiation, but fallback to template
540   // pattern if instantiation is not available.
541   Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
542 
543   llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
544   llvm::SmallVector<const NamedDecl *, 1> Targets;
545   bool SeenTemplateInstantiations = false;
546   for (auto &D : Decls) {
547     if (D.second & ~Mask)
548       continue;
549     if (D.second & DeclRelation::TemplatePattern) {
550       TemplatePatterns.push_back(D.first);
551       continue;
552     }
553     if (D.second & DeclRelation::TemplateInstantiation)
554       SeenTemplateInstantiations = true;
555     Targets.push_back(D.first);
556   }
557   if (!SeenTemplateInstantiations)
558     Targets.insert(Targets.end(), TemplatePatterns.begin(),
559                    TemplatePatterns.end());
560   return Targets;
561 }
562 
563 namespace {
564 llvm::SmallVector<ReferenceLoc, 2> refInDecl(const Decl *D) {
565   struct Visitor : ConstDeclVisitor<Visitor> {
566     llvm::SmallVector<ReferenceLoc, 2> Refs;
567 
568     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
569       // We want to keep it as non-declaration references, as the
570       // "using namespace" declaration doesn't have a name.
571       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
572                                   D->getIdentLocation(),
573                                   /*IsDecl=*/false,
574                                   {D->getNominatedNamespaceAsWritten()}});
575     }
576 
577     void VisitUsingDecl(const UsingDecl *D) {
578       // "using ns::identifier;" is a non-declaration reference.
579       Refs.push_back(
580           ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
581                        explicitReferenceTargets(DynTypedNode::create(*D),
582                                                 DeclRelation::Underlying)});
583     }
584 
585     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
586       // For namespace alias, "namespace Foo = Target;", we add two references.
587       // Add a declaration reference for Foo.
588       VisitNamedDecl(D);
589       // Add a non-declaration reference for Target.
590       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
591                                   D->getTargetNameLoc(),
592                                   /*IsDecl=*/false,
593                                   {D->getAliasedNamespace()}});
594     }
595 
596     void VisitNamedDecl(const NamedDecl *ND) {
597       // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As
598       // as their underlying decls, covering the same range, will be visited.
599       if (llvm::isa<ClassTemplateDecl>(ND) ||
600           llvm::isa<FunctionTemplateDecl>(ND) ||
601           llvm::isa<VarTemplateDecl>(ND) ||
602           llvm::isa<TypeAliasTemplateDecl>(ND))
603         return;
604       // FIXME: decide on how to surface destructors when we need them.
605       if (llvm::isa<CXXDestructorDecl>(ND))
606         return;
607       // Filter anonymous decls, name location will point outside the name token
608       // and the clients are not prepared to handle that.
609       if (ND->getDeclName().isIdentifier() &&
610           !ND->getDeclName().getAsIdentifierInfo())
611         return;
612       Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
613                                   ND->getLocation(),
614                                   /*IsDecl=*/true,
615                                   {ND}});
616     }
617   };
618 
619   Visitor V;
620   V.Visit(D);
621   return V.Refs;
622 }
623 
624 llvm::SmallVector<ReferenceLoc, 2> refInExpr(const Expr *E) {
625   struct Visitor : ConstStmtVisitor<Visitor> {
626     // FIXME: handle more complicated cases: more ObjC, designated initializers.
627     llvm::SmallVector<ReferenceLoc, 2> Refs;
628 
629     void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
630       Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(),
631                                   E->getConceptNameLoc(),
632                                   /*IsDecl=*/false,
633                                   {E->getNamedConcept()}});
634     }
635     void VisitDeclRefExpr(const DeclRefExpr *E) {
636       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
637                                   E->getNameInfo().getLoc(),
638                                   /*IsDecl=*/false,
639                                   {E->getFoundDecl()}});
640     }
641 
642     void VisitMemberExpr(const MemberExpr *E) {
643       // Skip destructor calls to avoid duplication: TypeLoc within will be
644       // visited separately.
645       if (llvm::dyn_cast<CXXDestructorDecl>(E->getFoundDecl().getDecl()))
646         return;
647       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
648                                   E->getMemberNameInfo().getLoc(),
649                                   /*IsDecl=*/false,
650                                   {E->getFoundDecl()}});
651     }
652 
653     void VisitOverloadExpr(const OverloadExpr *E) {
654       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
655                                   E->getNameInfo().getLoc(),
656                                   /*IsDecl=*/false,
657                                   llvm::SmallVector<const NamedDecl *, 1>(
658                                       E->decls().begin(), E->decls().end())});
659     }
660 
661     void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
662       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
663                                   E->getPackLoc(),
664                                   /*IsDecl=*/false,
665                                   {E->getPack()}});
666     }
667 
668     void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
669       Refs.push_back(ReferenceLoc{
670           NestedNameSpecifierLoc(), E->getLocation(),
671           /*IsDecl=*/false,
672           // Select the getter, setter, or @property depending on the call.
673           explicitReferenceTargets(DynTypedNode::create(*E), {})});
674     }
675   };
676 
677   Visitor V;
678   V.Visit(E);
679   return V.Refs;
680 }
681 
682 llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
683   struct Visitor : TypeLocVisitor<Visitor> {
684     llvm::Optional<ReferenceLoc> Ref;
685 
686     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
687       // We only know about qualifier, rest if filled by inner locations.
688       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
689       // Fill in the qualifier.
690       if (!Ref)
691         return;
692       assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
693       Ref->Qualifier = L.getQualifierLoc();
694     }
695 
696     void VisitTagTypeLoc(TagTypeLoc L) {
697       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
698                          L.getNameLoc(),
699                          /*IsDecl=*/false,
700                          {L.getDecl()}};
701     }
702 
703     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
704       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
705                          L.getNameLoc(),
706                          /*IsDecl=*/false,
707                          {L.getDecl()}};
708     }
709 
710     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
711       // We must ensure template type aliases are included in results if they
712       // were written in the source code, e.g. in
713       //    template <class T> using valias = vector<T>;
714       //    ^valias<int> x;
715       // 'explicitReferenceTargets' will return:
716       //    1. valias with mask 'Alias'.
717       //    2. 'vector<int>' with mask 'Underlying'.
718       //  we want to return only #1 in this case.
719       Ref = ReferenceLoc{
720           NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
721           explicitReferenceTargets(DynTypedNode::create(L.getType()),
722                                    DeclRelation::Alias)};
723     }
724     void VisitDeducedTemplateSpecializationTypeLoc(
725         DeducedTemplateSpecializationTypeLoc L) {
726       Ref = ReferenceLoc{
727           NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
728           explicitReferenceTargets(DynTypedNode::create(L.getType()),
729                                    DeclRelation::Alias)};
730     }
731 
732     void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
733       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
734                          TL.getNameLoc(),
735                          /*IsDecl=*/false,
736                          {TL.getDecl()}};
737     }
738 
739     void VisitDependentTemplateSpecializationTypeLoc(
740         DependentTemplateSpecializationTypeLoc L) {
741       Ref = ReferenceLoc{
742           L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
743           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
744     }
745 
746     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
747       Ref = ReferenceLoc{
748           L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
749           explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
750     }
751 
752     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
753       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
754                          L.getNameLoc(),
755                          /*IsDecl=*/false,
756                          {L.getTypedefNameDecl()}};
757     }
758   };
759 
760   Visitor V;
761   V.Visit(L.getUnqualifiedLoc());
762   if (!V.Ref)
763     return {};
764   return {*V.Ref};
765 }
766 
767 class ExplicitReferenceCollector
768     : public RecursiveASTVisitor<ExplicitReferenceCollector> {
769 public:
770   ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out)
771       : Out(Out) {
772     assert(Out);
773   }
774 
775   bool VisitTypeLoc(TypeLoc TTL) {
776     if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
777       return true;
778     visitNode(DynTypedNode::create(TTL));
779     return true;
780   }
781 
782   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
783     // ElaboratedTypeLoc will reports information for its inner type loc.
784     // Otherwise we loose information about inner types loc's qualifier.
785     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
786     TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
787     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
788   }
789 
790   bool VisitExpr(Expr *E) {
791     visitNode(DynTypedNode::create(*E));
792     return true;
793   }
794 
795   bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
796     visitNode(DynTypedNode::create(*OVE));
797     // Not clear why the source expression is skipped by default...
798     // FIXME: can we just make RecursiveASTVisitor do this?
799     return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
800   }
801 
802   bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
803     visitNode(DynTypedNode::create(*POE));
804     // Traverse only the syntactic form to find the *written* references.
805     // (The semantic form also contains lots of duplication)
806     return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
807   }
808 
809   // We re-define Traverse*, since there's no corresponding Visit*.
810   // TemplateArgumentLoc is the only way to get locations for references to
811   // template template parameters.
812   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
813     switch (A.getArgument().getKind()) {
814     case TemplateArgument::Template:
815     case TemplateArgument::TemplateExpansion:
816       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
817                                    A.getTemplateNameLoc(),
818                                    /*IsDecl=*/false,
819                                    {A.getArgument()
820                                         .getAsTemplateOrTemplatePattern()
821                                         .getAsTemplateDecl()}},
822                       DynTypedNode::create(A.getArgument()));
823       break;
824     case TemplateArgument::Declaration:
825       break; // FIXME: can this actually happen in TemplateArgumentLoc?
826     case TemplateArgument::Integral:
827     case TemplateArgument::Null:
828     case TemplateArgument::NullPtr:
829       break; // no references.
830     case TemplateArgument::Pack:
831     case TemplateArgument::Type:
832     case TemplateArgument::Expression:
833       break; // Handled by VisitType and VisitExpression.
834     };
835     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
836   }
837 
838   bool VisitDecl(Decl *D) {
839     visitNode(DynTypedNode::create(*D));
840     return true;
841   }
842 
843   // We have to use Traverse* because there is no corresponding Visit*.
844   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
845     if (!L.getNestedNameSpecifier())
846       return true;
847     visitNode(DynTypedNode::create(L));
848     // Inner type is missing information about its qualifier, skip it.
849     if (auto TL = L.getTypeLoc())
850       TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
851     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
852   }
853 
854   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
855     visitNode(DynTypedNode::create(*Init));
856     return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
857   }
858 
859 private:
860   /// Obtain information about a reference directly defined in \p N. Does not
861   /// recurse into child nodes, e.g. do not expect references for constructor
862   /// initializers
863   ///
864   /// Any of the fields in the returned structure can be empty, but not all of
865   /// them, e.g.
866   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
867   ///     source location information may be missing,
868   ///   - for dependent code, targets may be empty.
869   ///
870   /// (!) For the purposes of this function declarations are not considered to
871   ///     be references. However, declarations can have references inside them,
872   ///     e.g. 'namespace foo = std' references namespace 'std' and this
873   ///     function will return the corresponding reference.
874   llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
875     if (auto *D = N.get<Decl>())
876       return refInDecl(D);
877     if (auto *E = N.get<Expr>())
878       return refInExpr(E);
879     if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
880       // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
881       return {ReferenceLoc{
882           NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
883           explicitReferenceTargets(
884               DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
885               DeclRelation::Alias)}};
886     }
887     if (const TypeLoc *TL = N.get<TypeLoc>())
888       return refInTypeLoc(*TL);
889     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
890       // Other type initializers (e.g. base initializer) are handled by visiting
891       // the typeLoc.
892       if (CCI->isAnyMemberInitializer()) {
893         return {ReferenceLoc{NestedNameSpecifierLoc(),
894                              CCI->getMemberLocation(),
895                              /*IsDecl=*/false,
896                              {CCI->getAnyMember()}}};
897       }
898     }
899     // We do not have location information for other nodes (QualType, etc)
900     return {};
901   }
902 
903   void visitNode(DynTypedNode N) {
904     for (const auto &R : explicitReference(N))
905       reportReference(R, N);
906   }
907 
908   void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
909     // Our promise is to return only references from the source code. If we lack
910     // location information, skip these nodes.
911     // Normally this should not happen in practice, unless there are bugs in the
912     // traversals or users started the traversal at an implicit node.
913     if (Ref.NameLoc.isInvalid()) {
914       dlog("invalid location at node {0}", nodeToString(N));
915       return;
916     }
917     Out(Ref);
918   }
919 
920   llvm::function_ref<void(ReferenceLoc)> Out;
921   /// TypeLocs starting at these locations must be skipped, see
922   /// TraverseElaboratedTypeSpecifierLoc for details.
923   llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
924 };
925 } // namespace
926 
927 void findExplicitReferences(const Stmt *S,
928                             llvm::function_ref<void(ReferenceLoc)> Out) {
929   assert(S);
930   ExplicitReferenceCollector(Out).TraverseStmt(const_cast<Stmt *>(S));
931 }
932 void findExplicitReferences(const Decl *D,
933                             llvm::function_ref<void(ReferenceLoc)> Out) {
934   assert(D);
935   ExplicitReferenceCollector(Out).TraverseDecl(const_cast<Decl *>(D));
936 }
937 void findExplicitReferences(const ASTContext &AST,
938                             llvm::function_ref<void(ReferenceLoc)> Out) {
939   ExplicitReferenceCollector(Out).TraverseAST(const_cast<ASTContext &>(AST));
940 }
941 
942 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
943   switch (R) {
944 #define REL_CASE(X)                                                            \
945   case DeclRelation::X:                                                        \
946     return OS << #X;
947     REL_CASE(Alias);
948     REL_CASE(Underlying);
949     REL_CASE(TemplateInstantiation);
950     REL_CASE(TemplatePattern);
951 #undef REL_CASE
952   }
953   llvm_unreachable("Unhandled DeclRelation enum");
954 }
955 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
956   const char *Sep = "";
957   for (unsigned I = 0; I < RS.S.size(); ++I) {
958     if (RS.S.test(I)) {
959       OS << Sep << static_cast<DeclRelation>(I);
960       Sep = "|";
961     }
962   }
963   return OS;
964 }
965 
966 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
967   // note we cannot print R.NameLoc without a source manager.
968   OS << "targets = {";
969   bool First = true;
970   for (const NamedDecl *T : R.Targets) {
971     if (!First)
972       OS << ", ";
973     else
974       First = false;
975     OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
976   }
977   OS << "}";
978   if (R.Qualifier) {
979     OS << ", qualifier = '";
980     R.Qualifier.getNestedNameSpecifier()->print(OS,
981                                                 PrintingPolicy(LangOptions()));
982     OS << "'";
983   }
984   if (R.IsDecl)
985     OS << ", decl";
986   return OS;
987 }
988 
989 } // namespace clangd
990 } // namespace clang
991