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 Optional<ReferenceLoc> refInDecl(const Decl *D) {
416   struct Visitor : ConstDeclVisitor<Visitor> {
417     llvm::Optional<ReferenceLoc> Ref;
418 
419     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
420       Ref = ReferenceLoc{D->getQualifierLoc(),
421                          D->getIdentLocation(),
422                          {D->getNominatedNamespaceAsWritten()}};
423     }
424 
425     void VisitUsingDecl(const UsingDecl *D) {
426       Ref = ReferenceLoc{D->getQualifierLoc(), D->getLocation(),
427                          explicitReferenceTargets(DynTypedNode::create(*D),
428                                                   DeclRelation::Underlying)};
429     }
430 
431     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
432       Ref = ReferenceLoc{D->getQualifierLoc(),
433                          D->getTargetNameLoc(),
434                          {D->getAliasedNamespace()}};
435     }
436   };
437 
438   Visitor V;
439   V.Visit(D);
440   return V.Ref;
441 }
442 
443 Optional<ReferenceLoc> refInExpr(const Expr *E) {
444   struct Visitor : ConstStmtVisitor<Visitor> {
445     // FIXME: handle more complicated cases, e.g. ObjC, designated initializers.
446     llvm::Optional<ReferenceLoc> Ref;
447 
448     void VisitDeclRefExpr(const DeclRefExpr *E) {
449       Ref = ReferenceLoc{
450           E->getQualifierLoc(), E->getNameInfo().getLoc(), {E->getFoundDecl()}};
451     }
452 
453     void VisitMemberExpr(const MemberExpr *E) {
454       Ref = ReferenceLoc{E->getQualifierLoc(),
455                          E->getMemberNameInfo().getLoc(),
456                          {E->getFoundDecl()}};
457     }
458 
459     void VisitOverloadExpr(const OverloadExpr *E) {
460       Ref = ReferenceLoc{E->getQualifierLoc(), E->getNameInfo().getLoc(),
461                          llvm::SmallVector<const NamedDecl *, 1>(
462                              E->decls().begin(), E->decls().end())};
463     }
464   };
465 
466   Visitor V;
467   V.Visit(E);
468   return V.Ref;
469 }
470 
471 Optional<ReferenceLoc> refInTypeLoc(TypeLoc L) {
472   struct Visitor : TypeLocVisitor<Visitor> {
473     llvm::Optional<ReferenceLoc> Ref;
474 
475     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
476       // We only know about qualifier, rest if filled by inner locations.
477       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
478       // Fill in the qualifier.
479       if (!Ref)
480         return;
481       assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
482       Ref->Qualifier = L.getQualifierLoc();
483     }
484 
485     void VisitTagTypeLoc(TagTypeLoc L) {
486       Ref =
487           ReferenceLoc{NestedNameSpecifierLoc(), L.getNameLoc(), {L.getDecl()}};
488     }
489 
490     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
491       Ref =
492           ReferenceLoc{NestedNameSpecifierLoc(), L.getNameLoc(), {L.getDecl()}};
493     }
494 
495     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
496       // We must ensure template type aliases are included in results if they
497       // were written in the source code, e.g. in
498       //    template <class T> using valias = vector<T>;
499       //    ^valias<int> x;
500       // 'explicitReferenceTargets' will return:
501       //    1. valias with mask 'Alias'.
502       //    2. 'vector<int>' with mask 'Underlying'.
503       //  we want to return only #1 in this case.
504       Ref = ReferenceLoc{
505           NestedNameSpecifierLoc(), L.getTemplateNameLoc(),
506           explicitReferenceTargets(DynTypedNode::create(L.getType()),
507                                    DeclRelation::Alias)};
508     }
509     void VisitDeducedTemplateSpecializationTypeLoc(
510         DeducedTemplateSpecializationTypeLoc L) {
511       Ref = ReferenceLoc{
512           NestedNameSpecifierLoc(), L.getNameLoc(),
513           explicitReferenceTargets(DynTypedNode::create(L.getType()),
514                                    DeclRelation::Alias)};
515     }
516 
517     void VisitDependentTemplateSpecializationTypeLoc(
518         DependentTemplateSpecializationTypeLoc L) {
519       Ref = ReferenceLoc{
520           L.getQualifierLoc(), L.getTemplateNameLoc(),
521           explicitReferenceTargets(DynTypedNode::create(L.getType()))};
522     }
523 
524     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
525       Ref = ReferenceLoc{
526           L.getQualifierLoc(), L.getNameLoc(),
527           explicitReferenceTargets(DynTypedNode::create(L.getType()))};
528     }
529 
530     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
531       Ref = ReferenceLoc{
532           NestedNameSpecifierLoc(), L.getNameLoc(), {L.getTypedefNameDecl()}};
533     }
534   };
535 
536   Visitor V;
537   V.Visit(L.getUnqualifiedLoc());
538   return V.Ref;
539 }
540 
541 class ExplicitReferenceColletor
542     : public RecursiveASTVisitor<ExplicitReferenceColletor> {
543 public:
544   ExplicitReferenceColletor(llvm::function_ref<void(ReferenceLoc)> Out)
545       : Out(Out) {
546     assert(Out);
547   }
548 
549   bool VisitTypeLoc(TypeLoc TTL) {
550     if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
551       return true;
552     visitNode(DynTypedNode::create(TTL));
553     return true;
554   }
555 
556   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
557     // ElaboratedTypeLoc will reports information for its inner type loc.
558     // Otherwise we loose information about inner types loc's qualifier.
559     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
560     TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
561     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
562   }
563 
564   bool VisitExpr(Expr *E) {
565     visitNode(DynTypedNode::create(*E));
566     return true;
567   }
568 
569   // We re-define Traverse*, since there's no corresponding Visit*.
570   // TemplateArgumentLoc is the only way to get locations for references to
571   // template template parameters.
572   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
573     switch (A.getArgument().getKind()) {
574     case TemplateArgument::Template:
575     case TemplateArgument::TemplateExpansion:
576       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
577                                    A.getTemplateNameLoc(),
578                                    {A.getArgument()
579                                         .getAsTemplateOrTemplatePattern()
580                                         .getAsTemplateDecl()}},
581                       DynTypedNode::create(A.getArgument()));
582       break;
583     case TemplateArgument::Declaration:
584       break; // FIXME: can this actually happen in TemplateArgumentLoc?
585     case TemplateArgument::Integral:
586     case TemplateArgument::Null:
587     case TemplateArgument::NullPtr:
588       break; // no references.
589     case TemplateArgument::Pack:
590     case TemplateArgument::Type:
591     case TemplateArgument::Expression:
592       break; // Handled by VisitType and VisitExpression.
593     };
594     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
595   }
596 
597   bool VisitDecl(Decl *D) {
598     visitNode(DynTypedNode::create(*D));
599     return true;
600   }
601 
602   // We have to use Traverse* because there is no corresponding Visit*.
603   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
604     if (!L.getNestedNameSpecifier())
605       return true;
606     visitNode(DynTypedNode::create(L));
607     // Inner type is missing information about its qualifier, skip it.
608     if (auto TL = L.getTypeLoc())
609       TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
610     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
611   }
612 
613 private:
614   /// Obtain information about a reference directly defined in \p N. Does not
615   /// recurse into child nodes, e.g. do not expect references for constructor
616   /// initializers
617   ///
618   /// Any of the fields in the returned structure can be empty, but not all of
619   /// them, e.g.
620   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
621   ///     source location information may be missing,
622   ///   - for dependent code, targets may be empty.
623   ///
624   /// (!) For the purposes of this function declarations are not considered to
625   ///     be references. However, declarations can have references inside them,
626   ///     e.g. 'namespace foo = std' references namespace 'std' and this
627   ///     function will return the corresponding reference.
628   llvm::Optional<ReferenceLoc> explicitReference(DynTypedNode N) {
629     if (auto *D = N.get<Decl>())
630       return refInDecl(D);
631     if (auto *E = N.get<Expr>())
632       return refInExpr(E);
633     if (auto *NNSL = N.get<NestedNameSpecifierLoc>())
634       return ReferenceLoc{NNSL->getPrefix(), NNSL->getLocalBeginLoc(),
635                           explicitReferenceTargets(DynTypedNode::create(
636                               *NNSL->getNestedNameSpecifier()))};
637     if (const TypeLoc *TL = N.get<TypeLoc>())
638       return refInTypeLoc(*TL);
639     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
640       if (CCI->isBaseInitializer())
641         return refInTypeLoc(CCI->getBaseClassLoc());
642       assert(CCI->isAnyMemberInitializer());
643       return ReferenceLoc{NestedNameSpecifierLoc(),
644                           CCI->getMemberLocation(),
645                           {CCI->getAnyMember()}};
646     }
647     // We do not have location information for other nodes (QualType, etc)
648     return llvm::None;
649   }
650 
651   void visitNode(DynTypedNode N) {
652     auto Ref = explicitReference(N);
653     if (!Ref)
654       return;
655     reportReference(*Ref, N);
656   }
657 
658   void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
659     // Our promise is to return only references from the source code. If we lack
660     // location information, skip these nodes.
661     // Normally this should not happen in practice, unless there are bugs in the
662     // traversals or users started the traversal at an implicit node.
663     if (Ref.NameLoc.isInvalid()) {
664       dlog("invalid location at node {0}", nodeToString(N));
665       return;
666     }
667     Out(Ref);
668   }
669 
670   llvm::function_ref<void(ReferenceLoc)> Out;
671   /// TypeLocs starting at these locations must be skipped, see
672   /// TraverseElaboratedTypeSpecifierLoc for details.
673   llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
674 };
675 } // namespace
676 
677 void findExplicitReferences(const Stmt *S,
678                             llvm::function_ref<void(ReferenceLoc)> Out) {
679   assert(S);
680   ExplicitReferenceColletor(Out).TraverseStmt(const_cast<Stmt *>(S));
681 }
682 void findExplicitReferences(const Decl *D,
683                             llvm::function_ref<void(ReferenceLoc)> Out) {
684   assert(D);
685   ExplicitReferenceColletor(Out).TraverseDecl(const_cast<Decl *>(D));
686 }
687 
688 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
689   switch (R) {
690 #define REL_CASE(X)                                                            \
691   case DeclRelation::X:                                                        \
692     return OS << #X;
693     REL_CASE(Alias);
694     REL_CASE(Underlying);
695     REL_CASE(TemplateInstantiation);
696     REL_CASE(TemplatePattern);
697 #undef REL_CASE
698   }
699   llvm_unreachable("Unhandled DeclRelation enum");
700 }
701 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
702   const char *Sep = "";
703   for (unsigned I = 0; I < RS.S.size(); ++I) {
704     if (RS.S.test(I)) {
705       OS << Sep << static_cast<DeclRelation>(I);
706       Sep = "|";
707     }
708   }
709   return OS;
710 }
711 
712 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
713   // note we cannot print R.NameLoc without a source manager.
714   OS << "targets = {";
715   bool First = true;
716   for (const NamedDecl *T : R.Targets) {
717     if (!First)
718       OS << ", ";
719     else
720       First = false;
721     OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
722   }
723   OS << "}";
724   if (R.Qualifier) {
725     OS << ", qualifier = '";
726     R.Qualifier.getNestedNameSpecifier()->print(OS,
727                                                 PrintingPolicy(LangOptions()));
728     OS << "'";
729   }
730   return OS;
731 }
732 
733 } // namespace clangd
734 } // namespace clang
735