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/ExprObjC.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TemplateBase.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeLocVisitor.h"
29 #include "clang/Basic/LangOptions.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <utility>
37 
38 namespace clang {
39 namespace clangd {
40 namespace {
41 using ast_type_traits::DynTypedNode;
42 
43 LLVM_ATTRIBUTE_UNUSED std::string
44 nodeToString(const ast_type_traits::DynTypedNode &N) {
45   std::string S = N.getNodeKind().asStringRef();
46   {
47     llvm::raw_string_ostream OS(S);
48     OS << ": ";
49     N.print(OS, PrintingPolicy(LangOptions()));
50   }
51   std::replace(S.begin(), S.end(), '\n', ' ');
52   return S;
53 }
54 
55 // TargetFinder locates the entities that an AST node refers to.
56 //
57 // Typically this is (possibly) one declaration and (possibly) one type, but
58 // may be more:
59 //  - for ambiguous nodes like OverloadExpr
60 //  - if we want to include e.g. both typedefs and the underlying type
61 //
62 // This is organized as a set of mutually recursive helpers for particular node
63 // types, but for most nodes this is a short walk rather than a deep traversal.
64 //
65 // It's tempting to do e.g. typedef resolution as a second normalization step,
66 // after finding the 'primary' decl etc. But we do this monolithically instead
67 // because:
68 //  - normalization may require these traversals again (e.g. unwrapping a
69 //    typedef reveals a decltype which must be traversed)
70 //  - it doesn't simplify that much, e.g. the first stage must still be able
71 //    to yield multiple decls to handle OverloadExpr
72 //  - there are cases where it's required for correctness. e.g:
73 //      template<class X> using pvec = vector<x*>; pvec<int> x;
74 //    There's no Decl `pvec<int>`, we must choose `pvec<X>` or `vector<int*>`
75 //    and both are lossy. We must know upfront what the caller ultimately wants.
76 //
77 // FIXME: improve common dependent scope using name lookup in primary templates.
78 // e.g. template<typename T> int foo() { return std::vector<T>().size(); }
79 // formally size() is unresolved, but the primary template is a good guess.
80 // This affects:
81 //  - DependentTemplateSpecializationType,
82 //  - DependentScopeMemberExpr
83 //  - DependentScopeDeclRefExpr
84 //  - DependentNameType
85 struct TargetFinder {
86   using RelSet = DeclRelationSet;
87   using Rel = DeclRelation;
88   llvm::SmallDenseMap<const Decl *, RelSet> Decls;
89   RelSet Flags;
90 
91   static const Decl *getTemplatePattern(const Decl *D) {
92     if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
93       return CRD->getTemplateInstantiationPattern();
94     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
95       return FD->getTemplateInstantiationPattern();
96     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
97       // Hmm: getTIP returns its arg if it's not an instantiation?!
98       VarDecl *T = VD->getTemplateInstantiationPattern();
99       return (T == D) ? nullptr : T;
100     } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
101       return ED->getInstantiatedFromMemberEnum();
102     } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
103       const auto *ND = cast<NamedDecl>(D);
104       if (const DeclContext *Parent = dyn_cast_or_null<DeclContext>(
105               getTemplatePattern(llvm::cast<Decl>(ND->getDeclContext()))))
106         for (const NamedDecl *BaseND : Parent->lookup(ND->getDeclName()))
107           if (!BaseND->isImplicit() && BaseND->getKind() == ND->getKind())
108             return BaseND;
109     } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
110       if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
111         if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
112           for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
113             return BaseECD;
114         }
115       }
116     }
117     return nullptr;
118   }
119 
120   template <typename T> void debug(T &Node, RelSet Flags) {
121     dlog("visit [{0}] {1}", Flags,
122          nodeToString(ast_type_traits::DynTypedNode::create(Node)));
123   }
124 
125   void report(const Decl *D, RelSet Flags) {
126     dlog("--> [{0}] {1}", Flags,
127          nodeToString(ast_type_traits::DynTypedNode::create(*D)));
128     Decls[D] |= Flags;
129   }
130 
131 public:
132   void add(const Decl *D, RelSet Flags) {
133     if (!D)
134       return;
135     debug(*D, Flags);
136     if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
137       D = UDD->getNominatedNamespaceAsWritten();
138 
139     if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) {
140       add(TND->getUnderlyingType(), Flags | Rel::Underlying);
141       Flags |= Rel::Alias; // continue with the alias.
142     } else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
143       for (const UsingShadowDecl *S : UD->shadows())
144         add(S->getUnderlyingDecl(), Flags | Rel::Underlying);
145       Flags |= Rel::Alias; // continue with the alias.
146     } else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) {
147       add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying);
148       Flags |= Rel::Alias; // continue with the alias
149     } else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
150       // Include the using decl, but don't traverse it. This may end up
151       // including *all* shadows, which we don't want.
152       report(USD->getUsingDecl(), Flags | Rel::Alias);
153       // Shadow decls are synthetic and not themselves interesting.
154       // Record the underlying decl instead, if allowed.
155       D = USD->getTargetDecl();
156       Flags |= Rel::Underlying; // continue with the underlying decl.
157     }
158 
159     if (const Decl *Pat = getTemplatePattern(D)) {
160       assert(Pat != D);
161       add(Pat, Flags | Rel::TemplatePattern);
162       // Now continue with the instantiation.
163       Flags |= Rel::TemplateInstantiation;
164     }
165 
166     report(D, Flags);
167   }
168 
169   void add(const Stmt *S, RelSet Flags) {
170     if (!S)
171       return;
172     debug(*S, Flags);
173     struct Visitor : public ConstStmtVisitor<Visitor> {
174       TargetFinder &Outer;
175       RelSet Flags;
176       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
177 
178       void VisitCallExpr(const CallExpr *CE) {
179         Outer.add(CE->getCalleeDecl(), Flags);
180       }
181       void VisitDeclRefExpr(const DeclRefExpr *DRE) {
182         const Decl *D = DRE->getDecl();
183         // UsingShadowDecl allows us to record the UsingDecl.
184         // getFoundDecl() returns the wrong thing in other cases (templates).
185         if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl()))
186           D = USD;
187         Outer.add(D, Flags);
188       }
189       void VisitMemberExpr(const MemberExpr *ME) {
190         const Decl *D = ME->getMemberDecl();
191         if (auto *USD =
192                 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl()))
193           D = USD;
194         Outer.add(D, Flags);
195       }
196       void VisitOverloadExpr(const OverloadExpr *OE) {
197         for (auto *D : OE->decls())
198           Outer.add(D, Flags);
199       }
200       void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
201         Outer.add(CCE->getConstructor(), Flags);
202       }
203       void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
204         for (const DesignatedInitExpr::Designator &D :
205              llvm::reverse(DIE->designators()))
206           if (D.isFieldDesignator()) {
207             Outer.add(D.getField(), Flags);
208             // We don't know which designator was intended, we assume the outer.
209             break;
210           }
211       }
212       void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
213         Outer.add(OIRE->getDecl(), Flags);
214       }
215       void VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
216         Outer.add(OME->getMethodDecl(), Flags);
217       }
218       void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
219         if (OPRE->isExplicitProperty())
220           Outer.add(OPRE->getExplicitProperty(), Flags);
221         else {
222           if (OPRE->isMessagingGetter())
223             Outer.add(OPRE->getImplicitPropertyGetter(), Flags);
224           if (OPRE->isMessagingSetter())
225             Outer.add(OPRE->getImplicitPropertySetter(), Flags);
226         }
227       }
228       void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
229         Outer.add(OPE->getProtocol(), Flags);
230       }
231     };
232     Visitor(*this, Flags).Visit(S);
233   }
234 
235   void add(QualType T, RelSet Flags) {
236     if (T.isNull())
237       return;
238     debug(T, Flags);
239     struct Visitor : public TypeVisitor<Visitor> {
240       TargetFinder &Outer;
241       RelSet Flags;
242       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
243 
244       void VisitTagType(const TagType *TT) {
245         Outer.add(TT->getAsTagDecl(), Flags);
246       }
247       void VisitDecltypeType(const DecltypeType *DTT) {
248         Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
249       }
250       void VisitDeducedType(const DeducedType *DT) {
251         // FIXME: In practice this doesn't work: the AutoType you find inside
252         // TypeLoc never has a deduced type. https://llvm.org/PR42914
253         Outer.add(DT->getDeducedType(), Flags | Rel::Underlying);
254       }
255       void VisitTypedefType(const TypedefType *TT) {
256         Outer.add(TT->getDecl(), Flags);
257       }
258       void
259       VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
260         // Have to handle these case-by-case.
261 
262         // templated type aliases: there's no specialized/instantiated using
263         // decl to point to. So try to find a decl for the underlying type
264         // (after substitution), and failing that point to the (templated) using
265         // decl.
266         if (TST->isTypeAlias()) {
267           Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
268           // Don't *traverse* the alias, which would result in traversing the
269           // template of the underlying type.
270           Outer.report(
271               TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
272               Flags | Rel::Alias | Rel::TemplatePattern);
273         }
274         // specializations of template template parameters aren't instantiated
275         // into decls, so they must refer to the parameter itself.
276         else if (const auto *Parm =
277                      llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
278                          TST->getTemplateName().getAsTemplateDecl()))
279           Outer.add(Parm, Flags);
280         // class template specializations have a (specialized) CXXRecordDecl.
281         else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
282           Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
283         else {
284           // fallback: the (un-specialized) declaration from primary template.
285           if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
286             Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
287         }
288       }
289       void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
290         Outer.add(TTPT->getDecl(), Flags);
291       }
292       void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
293         Outer.add(OIT->getDecl(), Flags);
294       }
295       void VisitObjCObjectType(const ObjCObjectType *OOT) {
296         // FIXME: ObjCObjectTypeLoc has no children for the protocol list, so
297         // there is no node in id<Foo> that refers to ObjCProtocolDecl Foo.
298         if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1)
299           Outer.add(OOT->getProtocol(0), Flags);
300       }
301     };
302     Visitor(*this, Flags).Visit(T.getTypePtr());
303   }
304 
305   void add(const NestedNameSpecifier *NNS, RelSet Flags) {
306     if (!NNS)
307       return;
308     debug(*NNS, Flags);
309     switch (NNS->getKind()) {
310     case NestedNameSpecifier::Identifier:
311       return;
312     case NestedNameSpecifier::Namespace:
313       add(NNS->getAsNamespace(), Flags);
314       return;
315     case NestedNameSpecifier::NamespaceAlias:
316       add(NNS->getAsNamespaceAlias(), Flags);
317       return;
318     case NestedNameSpecifier::TypeSpec:
319     case NestedNameSpecifier::TypeSpecWithTemplate:
320       add(QualType(NNS->getAsType(), 0), Flags);
321       return;
322     case NestedNameSpecifier::Global:
323       // This should be TUDecl, but we can't get a pointer to it!
324       return;
325     case NestedNameSpecifier::Super:
326       add(NNS->getAsRecordDecl(), Flags);
327       return;
328     }
329     llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
330   }
331 
332   void add(const CXXCtorInitializer *CCI, RelSet Flags) {
333     if (!CCI)
334       return;
335     debug(*CCI, Flags);
336 
337     if (CCI->isAnyMemberInitializer())
338       add(CCI->getAnyMember(), Flags);
339     // Constructor calls contain a TypeLoc node, so we don't handle them here.
340   }
341 };
342 
343 } // namespace
344 
345 llvm::SmallVector<std::pair<const Decl *, DeclRelationSet>, 1>
346 allTargetDecls(const ast_type_traits::DynTypedNode &N) {
347   dlog("allTargetDecls({0})", nodeToString(N));
348   TargetFinder Finder;
349   DeclRelationSet Flags;
350   if (const Decl *D = N.get<Decl>())
351     Finder.add(D, Flags);
352   else if (const Stmt *S = N.get<Stmt>())
353     Finder.add(S, Flags);
354   else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
355     Finder.add(NNSL->getNestedNameSpecifier(), Flags);
356   else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
357     Finder.add(NNS, Flags);
358   else if (const TypeLoc *TL = N.get<TypeLoc>())
359     Finder.add(TL->getType(), Flags);
360   else if (const QualType *QT = N.get<QualType>())
361     Finder.add(*QT, Flags);
362   else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
363     Finder.add(CCI, Flags);
364 
365   return {Finder.Decls.begin(), Finder.Decls.end()};
366 }
367 
368 llvm::SmallVector<const Decl *, 1>
369 targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
370   llvm::SmallVector<const Decl *, 1> Result;
371   for (const auto &Entry : allTargetDecls(N)) {
372     if (!(Entry.second & ~Mask))
373       Result.push_back(Entry.first);
374   }
375   return Result;
376 }
377 
378 namespace {
379 /// Find declarations explicitly referenced in the source code defined by \p N.
380 /// For templates, will prefer to return a template instantiation whenever
381 /// possible. However, can also return a template pattern if the specialization
382 /// cannot be picked, e.g. in dependent code or when there is no corresponding
383 /// Decl for a template instantitation, e.g. for templated using decls:
384 ///    template <class T> using Ptr = T*;
385 ///    Ptr<int> x;
386 ///    ^~~ there is no Decl for 'Ptr<int>', so we return the template pattern.
387 llvm::SmallVector<const NamedDecl *, 1>
388 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask = {}) {
389   assert(!(Mask & (DeclRelation::TemplatePattern |
390                    DeclRelation::TemplateInstantiation)) &&
391          "explicitRefenceTargets handles templates on its own");
392   auto Decls = allTargetDecls(N);
393 
394   // We prefer to return template instantiation, but fallback to template
395   // pattern if instantiation is not available.
396   Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
397 
398   llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
399   llvm::SmallVector<const NamedDecl *, 1> Targets;
400   bool SeenTemplateInstantiations = false;
401   for (auto &D : Decls) {
402     if (D.second & ~Mask)
403       continue;
404     if (D.second & DeclRelation::TemplatePattern) {
405       TemplatePatterns.push_back(llvm::cast<NamedDecl>(D.first));
406       continue;
407     }
408     if (D.second & DeclRelation::TemplateInstantiation)
409       SeenTemplateInstantiations = true;
410     Targets.push_back(llvm::cast<NamedDecl>(D.first));
411   }
412   if (!SeenTemplateInstantiations)
413     Targets.insert(Targets.end(), TemplatePatterns.begin(),
414                    TemplatePatterns.end());
415   return Targets;
416 }
417 
418 llvm::SmallVector<ReferenceLoc, 2> refInDecl(const Decl *D) {
419   struct Visitor : ConstDeclVisitor<Visitor> {
420     llvm::SmallVector<ReferenceLoc, 2> Refs;
421 
422     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
423       // We want to keep it as non-declaration references, as the
424       // "using namespace" declaration doesn't have a name.
425       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
426                                   D->getIdentLocation(),
427                                   /*IsDecl=*/false,
428                                   {D->getNominatedNamespaceAsWritten()}});
429     }
430 
431     void VisitUsingDecl(const UsingDecl *D) {
432       // "using ns::identifer;" is a non-declaration reference.
433       Refs.push_back(
434           ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
435                        explicitReferenceTargets(DynTypedNode::create(*D),
436                                                 DeclRelation::Underlying)});
437     }
438 
439     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
440       // For namespace alias, "namespace Foo = Target;", we add two references.
441       // Add a declaration reference for Foo.
442       VisitNamedDecl(D);
443       // Add a non-declaration reference for Target.
444       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
445                                   D->getTargetNameLoc(),
446                                   /*IsDecl=*/false,
447                                   {D->getAliasedNamespace()}});
448     }
449 
450     void VisitNamedDecl(const NamedDecl *ND) {
451       // FIXME: decide on how to surface destructors when we need them.
452       if (llvm::isa<CXXDestructorDecl>(ND))
453         return;
454       // Filter anonymous decls, name location will point outside the name token
455       // and the clients are not prepared to handle that.
456       if (ND->getDeclName().isIdentifier() &&
457           !ND->getDeclName().getAsIdentifierInfo())
458         return;
459       Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
460                                   ND->getLocation(),
461                                   /*IsDecl=*/true,
462                                   {ND}});
463     }
464   };
465 
466   Visitor V;
467   V.Visit(D);
468   return V.Refs;
469 }
470 
471 llvm::SmallVector<ReferenceLoc, 2> refInExpr(const Expr *E) {
472   struct Visitor : ConstStmtVisitor<Visitor> {
473     // FIXME: handle more complicated cases, e.g. ObjC, designated initializers.
474     llvm::SmallVector<ReferenceLoc, 2> Refs;
475 
476     void VisitDeclRefExpr(const DeclRefExpr *E) {
477       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
478                                   E->getNameInfo().getLoc(),
479                                   /*IsDecl=*/false,
480                                   {E->getFoundDecl()}});
481     }
482 
483     void VisitMemberExpr(const MemberExpr *E) {
484       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
485                                   E->getMemberNameInfo().getLoc(),
486                                   /*IsDecl=*/false,
487                                   {E->getFoundDecl()}});
488     }
489 
490     void VisitOverloadExpr(const OverloadExpr *E) {
491       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
492                                   E->getNameInfo().getLoc(),
493                                   /*IsDecl=*/false,
494                                   llvm::SmallVector<const NamedDecl *, 1>(
495                                       E->decls().begin(), E->decls().end())});
496     }
497   };
498 
499   Visitor V;
500   V.Visit(E);
501   return V.Refs;
502 }
503 
504 llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
505   struct Visitor : TypeLocVisitor<Visitor> {
506     llvm::Optional<ReferenceLoc> Ref;
507 
508     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
509       // We only know about qualifier, rest if filled by inner locations.
510       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
511       // Fill in the qualifier.
512       if (!Ref)
513         return;
514       assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
515       Ref->Qualifier = L.getQualifierLoc();
516     }
517 
518     void VisitTagTypeLoc(TagTypeLoc L) {
519       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
520                          L.getNameLoc(),
521                          /*IsDecl=*/false,
522                          {L.getDecl()}};
523     }
524 
525     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
526       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
527                          L.getNameLoc(),
528                          /*IsDecl=*/false,
529                          {L.getDecl()}};
530     }
531 
532     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
533       // We must ensure template type aliases are included in results if they
534       // were written in the source code, e.g. in
535       //    template <class T> using valias = vector<T>;
536       //    ^valias<int> x;
537       // 'explicitReferenceTargets' will return:
538       //    1. valias with mask 'Alias'.
539       //    2. 'vector<int>' with mask 'Underlying'.
540       //  we want to return only #1 in this case.
541       Ref = ReferenceLoc{
542           NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
543           explicitReferenceTargets(DynTypedNode::create(L.getType()),
544                                    DeclRelation::Alias)};
545     }
546     void VisitDeducedTemplateSpecializationTypeLoc(
547         DeducedTemplateSpecializationTypeLoc L) {
548       Ref = ReferenceLoc{
549           NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
550           explicitReferenceTargets(DynTypedNode::create(L.getType()),
551                                    DeclRelation::Alias)};
552     }
553 
554     void VisitDependentTemplateSpecializationTypeLoc(
555         DependentTemplateSpecializationTypeLoc L) {
556       Ref = ReferenceLoc{
557           L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
558           explicitReferenceTargets(DynTypedNode::create(L.getType()))};
559     }
560 
561     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
562       Ref = ReferenceLoc{
563           L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
564           explicitReferenceTargets(DynTypedNode::create(L.getType()))};
565     }
566 
567     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
568       Ref = ReferenceLoc{NestedNameSpecifierLoc(),
569                          L.getNameLoc(),
570                          /*IsDecl=*/false,
571                          {L.getTypedefNameDecl()}};
572     }
573   };
574 
575   Visitor V;
576   V.Visit(L.getUnqualifiedLoc());
577   if (!V.Ref)
578     return {};
579   return {*V.Ref};
580 }
581 
582 class ExplicitReferenceColletor
583     : public RecursiveASTVisitor<ExplicitReferenceColletor> {
584 public:
585   ExplicitReferenceColletor(llvm::function_ref<void(ReferenceLoc)> Out)
586       : Out(Out) {
587     assert(Out);
588   }
589 
590   bool VisitTypeLoc(TypeLoc TTL) {
591     if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
592       return true;
593     visitNode(DynTypedNode::create(TTL));
594     return true;
595   }
596 
597   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
598     // ElaboratedTypeLoc will reports information for its inner type loc.
599     // Otherwise we loose information about inner types loc's qualifier.
600     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
601     TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
602     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
603   }
604 
605   bool VisitExpr(Expr *E) {
606     visitNode(DynTypedNode::create(*E));
607     return true;
608   }
609 
610   // We re-define Traverse*, since there's no corresponding Visit*.
611   // TemplateArgumentLoc is the only way to get locations for references to
612   // template template parameters.
613   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
614     switch (A.getArgument().getKind()) {
615     case TemplateArgument::Template:
616     case TemplateArgument::TemplateExpansion:
617       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
618                                    A.getTemplateNameLoc(),
619                                    /*IsDecl=*/false,
620                                    {A.getArgument()
621                                         .getAsTemplateOrTemplatePattern()
622                                         .getAsTemplateDecl()}},
623                       DynTypedNode::create(A.getArgument()));
624       break;
625     case TemplateArgument::Declaration:
626       break; // FIXME: can this actually happen in TemplateArgumentLoc?
627     case TemplateArgument::Integral:
628     case TemplateArgument::Null:
629     case TemplateArgument::NullPtr:
630       break; // no references.
631     case TemplateArgument::Pack:
632     case TemplateArgument::Type:
633     case TemplateArgument::Expression:
634       break; // Handled by VisitType and VisitExpression.
635     };
636     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
637   }
638 
639   bool VisitDecl(Decl *D) {
640     visitNode(DynTypedNode::create(*D));
641     return true;
642   }
643 
644   // We have to use Traverse* because there is no corresponding Visit*.
645   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
646     if (!L.getNestedNameSpecifier())
647       return true;
648     visitNode(DynTypedNode::create(L));
649     // Inner type is missing information about its qualifier, skip it.
650     if (auto TL = L.getTypeLoc())
651       TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
652     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
653   }
654 
655   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
656     visitNode(DynTypedNode::create(*Init));
657     return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
658   }
659 
660 private:
661   /// Obtain information about a reference directly defined in \p N. Does not
662   /// recurse into child nodes, e.g. do not expect references for constructor
663   /// initializers
664   ///
665   /// Any of the fields in the returned structure can be empty, but not all of
666   /// them, e.g.
667   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
668   ///     source location information may be missing,
669   ///   - for dependent code, targets may be empty.
670   ///
671   /// (!) For the purposes of this function declarations are not considered to
672   ///     be references. However, declarations can have references inside them,
673   ///     e.g. 'namespace foo = std' references namespace 'std' and this
674   ///     function will return the corresponding reference.
675   llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
676     if (auto *D = N.get<Decl>())
677       return refInDecl(D);
678     if (auto *E = N.get<Expr>())
679       return refInExpr(E);
680     if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
681       // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
682       return {ReferenceLoc{
683           NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
684           explicitReferenceTargets(
685               DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
686               DeclRelation::Alias)}};
687     }
688     if (const TypeLoc *TL = N.get<TypeLoc>())
689       return refInTypeLoc(*TL);
690     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
691       // Other type initializers (e.g. base initializer) are handled by visiting
692       // the typeLoc.
693       if (CCI->isAnyMemberInitializer()) {
694         return {ReferenceLoc{NestedNameSpecifierLoc(),
695                              CCI->getMemberLocation(),
696                              /*IsDecl=*/false,
697                              {CCI->getAnyMember()}}};
698       }
699     }
700     // We do not have location information for other nodes (QualType, etc)
701     return {};
702   }
703 
704   void visitNode(DynTypedNode N) {
705     for (const auto &R : explicitReference(N))
706       reportReference(R, N);
707   }
708 
709   void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
710     // Our promise is to return only references from the source code. If we lack
711     // location information, skip these nodes.
712     // Normally this should not happen in practice, unless there are bugs in the
713     // traversals or users started the traversal at an implicit node.
714     if (Ref.NameLoc.isInvalid()) {
715       dlog("invalid location at node {0}", nodeToString(N));
716       return;
717     }
718     Out(Ref);
719   }
720 
721   llvm::function_ref<void(ReferenceLoc)> Out;
722   /// TypeLocs starting at these locations must be skipped, see
723   /// TraverseElaboratedTypeSpecifierLoc for details.
724   llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
725 };
726 } // namespace
727 
728 void findExplicitReferences(const Stmt *S,
729                             llvm::function_ref<void(ReferenceLoc)> Out) {
730   assert(S);
731   ExplicitReferenceColletor(Out).TraverseStmt(const_cast<Stmt *>(S));
732 }
733 void findExplicitReferences(const Decl *D,
734                             llvm::function_ref<void(ReferenceLoc)> Out) {
735   assert(D);
736   ExplicitReferenceColletor(Out).TraverseDecl(const_cast<Decl *>(D));
737 }
738 void findExplicitReferences(const ASTContext &AST,
739                             llvm::function_ref<void(ReferenceLoc)> Out) {
740   ExplicitReferenceColletor(Out).TraverseAST(const_cast<ASTContext &>(AST));
741 }
742 
743 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
744   switch (R) {
745 #define REL_CASE(X)                                                            \
746   case DeclRelation::X:                                                        \
747     return OS << #X;
748     REL_CASE(Alias);
749     REL_CASE(Underlying);
750     REL_CASE(TemplateInstantiation);
751     REL_CASE(TemplatePattern);
752 #undef REL_CASE
753   }
754   llvm_unreachable("Unhandled DeclRelation enum");
755 }
756 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
757   const char *Sep = "";
758   for (unsigned I = 0; I < RS.S.size(); ++I) {
759     if (RS.S.test(I)) {
760       OS << Sep << static_cast<DeclRelation>(I);
761       Sep = "|";
762     }
763   }
764   return OS;
765 }
766 
767 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
768   // note we cannot print R.NameLoc without a source manager.
769   OS << "targets = {";
770   bool First = true;
771   for (const NamedDecl *T : R.Targets) {
772     if (!First)
773       OS << ", ";
774     else
775       First = false;
776     OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
777   }
778   OS << "}";
779   if (R.Qualifier) {
780     OS << ", qualifier = '";
781     R.Qualifier.getNestedNameSpecifier()->print(OS,
782                                                 PrintingPolicy(LangOptions()));
783     OS << "'";
784   }
785   if (R.IsDecl)
786     OS << ", decl";
787   return OS;
788 }
789 
790 } // namespace clangd
791 } // namespace clang
792