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