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