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