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