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