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 // Template template parameters have no templated decl, so they must
401 // refer to the parameter itself.
402 if (const auto *Parm =
403 DTST->getTemplateName().getAsTemplateTemplateParmDecl()) {
404 Outer.add(Parm, Flags);
405 } else if (auto *TD = DTST->getTemplateName().getAsTemplateDecl()) {
406 // FIXME: This is a workaround for https://llvm.org/PR42914,
407 // which is causing DTST->getDeducedType() to be empty. We
408 // fall back to the template pattern and miss the instantiation
409 // even when it's known in principle. Once that bug is fixed,
410 // the following code can be removed (the existing handling in
411 // VisitDeducedType() is sufficient).
412 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
413 }
414 }
415 void VisitDependentNameType(const DependentNameType *DNT) {
416 if (Outer.Resolver) {
417 for (const NamedDecl *ND :
418 Outer.Resolver->resolveDependentNameType(DNT)) {
419 Outer.add(ND, Flags);
420 }
421 }
422 }
423 void VisitTypedefType(const TypedefType *TT) {
424 if (shouldSkipTypedef(TT->getDecl()))
425 return;
426 Outer.add(TT->getDecl(), Flags);
427 }
428 void
429 VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
430 // Have to handle these case-by-case.
431
432 if (const auto *UTN = TST->getTemplateName().getAsUsingShadowDecl())
433 Outer.add(UTN, Flags);
434
435 // templated type aliases: there's no specialized/instantiated using
436 // decl to point to. So try to find a decl for the underlying type
437 // (after substitution), and failing that point to the (templated) using
438 // decl.
439 if (TST->isTypeAlias()) {
440 Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
441 // Don't *traverse* the alias, which would result in traversing the
442 // template of the underlying type.
443
444 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
445 // Builtin templates e.g. __make_integer_seq, __type_pack_element
446 // are such that they don't have alias *decls*. Even then, we still
447 // traverse their desugared *types* so that instantiated decls are
448 // collected.
449 if (llvm::isa<BuiltinTemplateDecl>(TD))
450 return;
451 Outer.report(TD->getTemplatedDecl(),
452 Flags | Rel::Alias | Rel::TemplatePattern);
453 }
454 // specializations of template template parameters aren't instantiated
455 // into decls, so they must refer to the parameter itself.
456 else if (const auto *Parm =
457 TST->getTemplateName().getAsTemplateTemplateParmDecl())
458 Outer.add(Parm, Flags);
459 // class template specializations have a (specialized) CXXRecordDecl.
460 else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
461 Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
462 else if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
463 // fallback: the (un-specialized) declaration from primary template.
464 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
465 else if (Outer.Resolver)
466 for (const NamedDecl *ND :
467 Outer.Resolver->resolveTemplateSpecializationType(TST))
468 Outer.add(ND, Flags);
469 }
470 void
471 VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *STTPT) {
472 Outer.add(STTPT->getReplacementType(), Flags);
473 }
474 void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
475 Outer.add(TTPT->getDecl(), Flags);
476 }
477 void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
478 Outer.add(OIT->getDecl(), Flags);
479 }
480 };
481 Visitor(*this, Flags).Visit(T.getTypePtr());
482 }
483
484 void add(NestedNameSpecifier NNS, RelSet Flags) {
485 if (!NNS)
486 return;
487 debug(NNS, Flags);
488 switch (NNS.getKind()) {
489 case NestedNameSpecifier::Kind::Namespace:
490 add(NNS.getAsNamespaceAndPrefix().Namespace, Flags);
491 return;
492 case NestedNameSpecifier::Kind::Type:
493 add(QualType(NNS.getAsType(), 0), Flags);
494 return;
495 case NestedNameSpecifier::Kind::Global:
496 // This should be TUDecl, but we can't get a pointer to it!
497 return;
498 case NestedNameSpecifier::Kind::MicrosoftSuper:
499 add(NNS.getAsMicrosoftSuper(), Flags);
500 return;
501 case NestedNameSpecifier::Kind::Null:
502 llvm_unreachable("unexpected null nested name specifier");
503 }
504 llvm_unreachable("unhandled NestedNameSpecifier::Kind");
505 }
506
507 void add(const CXXCtorInitializer *CCI, RelSet Flags) {
508 if (!CCI)
509 return;
510 debug(*CCI, Flags);
511
512 if (CCI->isAnyMemberInitializer())
513 add(CCI->getAnyMember(), Flags);
514 // Constructor calls contain a TypeLoc node, so we don't handle them here.
515 }
516
517 void add(const TemplateArgument &Arg, RelSet Flags) {
518 // Only used for template template arguments.
519 // For type and non-type template arguments, SelectionTree
520 // will hit a more specific node (e.g. a TypeLoc or a
521 // DeclRefExpr).
522 if (Arg.getKind() == TemplateArgument::Template ||
523 Arg.getKind() == TemplateArgument::TemplateExpansion) {
524 if (TemplateDecl *TD =
525 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) {
526 report(TD, Flags);
527 }
528 if (const auto *USD =
529 Arg.getAsTemplateOrTemplatePattern().getAsUsingShadowDecl())
530 add(USD, Flags);
531 }
532 }
533
534 void add(const ConceptReference *CR, RelSet Flags) {
535 add(getReferencedConcept(CR), Flags);
536 }
537};
538
539} // namespace
540
541llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
542allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver) {
543 dlog("allTargetDecls({0})", nodeToString(N));
544 TargetFinder Finder(Resolver);
545 DeclRelationSet Flags;
546 if (const Decl *D = N.get<Decl>())
547 Finder.add(D, Flags);
548 else if (const Stmt *S = N.get<Stmt>())
549 Finder.add(S, Flags);
550 else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
551 Finder.add(NNSL->getNestedNameSpecifier(), Flags);
552 else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
553 Finder.add(*NNS, Flags);
554 else if (const TypeLoc *TL = N.get<TypeLoc>())
555 Finder.add(TL->getType(), Flags);
556 else if (const QualType *QT = N.get<QualType>())
557 Finder.add(*QT, Flags);
558 else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
559 Finder.add(CCI, Flags);
560 else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>())
561 Finder.add(TAL->getArgument(), Flags);
562 else if (const CXXBaseSpecifier *CBS = N.get<CXXBaseSpecifier>())
563 Finder.add(CBS->getTypeSourceInfo()->getType(), Flags);
564 else if (const ObjCProtocolLoc *PL = N.get<ObjCProtocolLoc>())
565 Finder.add(PL->getProtocol(), Flags);
566 else if (const ConceptReference *CR = N.get<ConceptReference>())
567 Finder.add(CR, Flags);
568 else if (const OffsetOfNode *OON = N.get<OffsetOfNode>()) {
569 if (OON->getKind() == OffsetOfNode::Field)
570 Finder.add(OON->getField(), Flags);
571 }
572 return Finder.takeDecls();
573}
574
575llvm::SmallVector<const NamedDecl *, 1>
576targetDecl(const DynTypedNode &N, DeclRelationSet Mask,
577 const HeuristicResolver *Resolver) {
578 llvm::SmallVector<const NamedDecl *, 1> Result;
579 for (const auto &Entry : allTargetDecls(N, Resolver)) {
580 if (!(Entry.second & ~Mask))
581 Result.push_back(Entry.first);
582 }
583 return Result;
584}
585
586llvm::SmallVector<const NamedDecl *, 1>
588 const HeuristicResolver *Resolver) {
589 assert(!(Mask & (DeclRelation::TemplatePattern |
591 "explicitReferenceTargets handles templates on its own");
592 auto Decls = allTargetDecls(N, Resolver);
593
594 // We prefer to return template instantiation, but fallback to template
595 // pattern if instantiation is not available.
597
598 llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
599 llvm::SmallVector<const NamedDecl *, 1> Targets;
600 bool SeenTemplateInstantiations = false;
601 for (auto &D : Decls) {
602 if (D.second & ~Mask)
603 continue;
604 if (D.second & DeclRelation::TemplatePattern) {
605 TemplatePatterns.push_back(D.first);
606 continue;
607 }
609 SeenTemplateInstantiations = true;
610 Targets.push_back(D.first);
611 }
612 if (!SeenTemplateInstantiations)
613 Targets.insert(Targets.end(), TemplatePatterns.begin(),
614 TemplatePatterns.end());
615 return Targets;
616}
617
618namespace {
619llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D,
620 const HeuristicResolver *Resolver) {
621 struct Visitor : ConstDeclVisitor<Visitor> {
622 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
623
624 const HeuristicResolver *Resolver;
625 llvm::SmallVector<ReferenceLoc> Refs;
626
627 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
628 // We want to keep it as non-declaration references, as the
629 // "using namespace" declaration doesn't have a name.
630 Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
631 D->getIdentLocation(),
632 /*IsDecl=*/false,
633 {D->getNominatedNamespaceAsWritten()}});
634 }
635
636 void VisitUsingDecl(const UsingDecl *D) {
637 // "using ns::identifier;" is a non-declaration reference.
638 Refs.push_back(ReferenceLoc{
639 D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
640 explicitReferenceTargets(DynTypedNode::create(*D),
641 DeclRelation::Underlying, Resolver)});
642 }
643
644 void VisitUsingEnumDecl(const UsingEnumDecl *D) {
645 // "using enum ns::E" is a non-declaration reference.
646 // The reference is covered by the embedded typeloc.
647 // Don't use the default VisitNamedDecl, which would report a declaration.
648 }
649
650 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
651 // For namespace alias, "namespace Foo = Target;", we add two references.
652 // Add a declaration reference for Foo.
653 VisitNamedDecl(D);
654 // Add a non-declaration reference for Target.
655 Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
656 D->getTargetNameLoc(),
657 /*IsDecl=*/false,
658 {D->getAliasedNamespace()}});
659 }
660
661 void VisitNamedDecl(const NamedDecl *ND) {
662 // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As
663 // as their underlying decls, covering the same range, will be visited.
664 if (llvm::isa<ClassTemplateDecl>(ND) ||
665 llvm::isa<FunctionTemplateDecl>(ND) ||
666 llvm::isa<VarTemplateDecl>(ND) ||
667 llvm::isa<TypeAliasTemplateDecl>(ND))
668 return;
669 // FIXME: decide on how to surface destructors when we need them.
670 if (llvm::isa<CXXDestructorDecl>(ND))
671 return;
672 // Filter anonymous decls, name location will point outside the name token
673 // and the clients are not prepared to handle that.
674 if (ND->getDeclName().isIdentifier() &&
675 !ND->getDeclName().getAsIdentifierInfo())
676 return;
677 Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
678 ND->getLocation(),
679 /*IsDecl=*/true,
680 {ND}});
681 }
682
683 void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) {
684 // The class template name in a deduction guide targets the class
685 // template.
686 Refs.push_back(ReferenceLoc{DG->getQualifierLoc(),
687 DG->getNameInfo().getLoc(),
688 /*IsDecl=*/false,
689 {DG->getDeducedTemplate()}});
690 }
691
692 void VisitObjCMethodDecl(const ObjCMethodDecl *OMD) {
693 // The name may have several tokens, we can only report the first.
694 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
695 OMD->getSelectorStartLoc(),
696 /*IsDecl=*/true,
697 {OMD}});
698 }
699
700 void VisitObjCCategoryDecl(const ObjCCategoryDecl *OCD) {
701 // getLocation is the extended class's location, not the category's.
702 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
703 OCD->getLocation(),
704 /*IsDecl=*/false,
705 {OCD->getClassInterface()}});
706 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
707 OCD->getCategoryNameLoc(),
708 /*IsDecl=*/true,
709 {OCD}});
710 }
711
712 void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *OCID) {
713 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
714 OCID->getLocation(),
715 /*IsDecl=*/false,
716 {OCID->getClassInterface()}});
717 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
718 OCID->getCategoryNameLoc(),
719 /*IsDecl=*/false,
720 {OCID->getCategoryDecl()}});
721 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
722 OCID->getCategoryNameLoc(),
723 /*IsDecl=*/true,
724 {OCID}});
725 }
726
727 void VisitObjCImplementationDecl(const ObjCImplementationDecl *OIMD) {
728 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
729 OIMD->getLocation(),
730 /*IsDecl=*/false,
731 {OIMD->getClassInterface()}});
732 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
733 OIMD->getLocation(),
734 /*IsDecl=*/true,
735 {OIMD}});
736 }
737 };
738
739 Visitor V{Resolver};
740 V.Visit(D);
741 return V.Refs;
742}
743
744llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S,
745 const HeuristicResolver *Resolver) {
746 struct Visitor : ConstStmtVisitor<Visitor> {
747 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
748
749 const HeuristicResolver *Resolver;
750 // FIXME: handle more complicated cases: more ObjC, designated initializers.
751 llvm::SmallVector<ReferenceLoc> Refs;
752
753 void VisitDeclRefExpr(const DeclRefExpr *E) {
754 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
755 E->getNameInfo().getLoc(),
756 /*IsDecl=*/false,
757 {E->getFoundDecl()}});
758 }
759
760 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
761 Refs.push_back(ReferenceLoc{
762 E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false,
763 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
764 }
765
766 void VisitMemberExpr(const MemberExpr *E) {
767 // Skip destructor calls to avoid duplication: TypeLoc within will be
768 // visited separately.
769 if (llvm::isa<CXXDestructorDecl>(E->getFoundDecl().getDecl()))
770 return;
771 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
772 E->getMemberNameInfo().getLoc(),
773 /*IsDecl=*/false,
774 {E->getFoundDecl()}});
775 }
776
777 void
778 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
779 Refs.push_back(ReferenceLoc{
780 E->getQualifierLoc(), E->getMemberNameInfo().getLoc(),
781 /*IsDecl=*/false,
782 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
783 }
784
785 void VisitOverloadExpr(const OverloadExpr *E) {
786 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
787 E->getNameInfo().getLoc(),
788 /*IsDecl=*/false,
789 llvm::SmallVector<const NamedDecl *, 1>(
790 E->decls().begin(), E->decls().end())});
791 }
792
793 void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
794 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
795 E->getPackLoc(),
796 /*IsDecl=*/false,
797 {E->getPack()}});
798 }
799
800 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
801 Refs.push_back(ReferenceLoc{
802 NestedNameSpecifierLoc(), E->getLocation(),
803 /*IsDecl=*/false,
804 // Select the getter, setter, or @property depending on the call.
805 explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
806 }
807
808 void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
809 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
810 OIRE->getLocation(),
811 /*IsDecl=*/false,
812 {OIRE->getDecl()}});
813 }
814
815 void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
816 // The name may have several tokens, we can only report the first.
817 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
818 E->getSelectorStartLoc(),
819 /*IsDecl=*/false,
820 {E->getMethodDecl()}});
821 }
822
823 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
824 for (const DesignatedInitExpr::Designator &D : DIE->designators()) {
825 if (!D.isFieldDesignator())
826 continue;
827
828 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
829 D.getFieldLoc(),
830 /*IsDecl=*/false,
831 {D.getFieldDecl()}});
832 }
833 }
834
835 void VisitGotoStmt(const GotoStmt *GS) {
836 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
837 GS->getLabelLoc(),
838 /*IsDecl=*/false,
839 {GS->getLabel()}});
840 }
841
842 void VisitLabelStmt(const LabelStmt *LS) {
843 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
844 LS->getIdentLoc(),
845 /*IsDecl=*/true,
846 {LS->getDecl()}});
847 }
848 };
849
850 Visitor V{Resolver};
851 V.Visit(S);
852 return V.Refs;
853}
854
855llvm::SmallVector<ReferenceLoc>
856refInTypeLoc(TypeLoc L, const HeuristicResolver *Resolver) {
857 struct Visitor : TypeLocVisitor<Visitor> {
858 Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
859
860 const HeuristicResolver *Resolver;
861 llvm::SmallVector<ReferenceLoc> Refs;
862
863 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc L) {
864 Refs.push_back(ReferenceLoc{L.getQualifierLoc(),
865 L.getNameLoc(),
866 /*IsDecl=*/false,
867 {L.getDecl()}});
868 }
869
870 void VisitUsingTypeLoc(UsingTypeLoc L) {
871 Refs.push_back(ReferenceLoc{L.getQualifierLoc(),
872 L.getNameLoc(),
873 /*IsDecl=*/false,
874 {L.getDecl()}});
875 }
876
877 void VisitTagTypeLoc(TagTypeLoc L) {
878 Refs.push_back(ReferenceLoc{L.getQualifierLoc(),
879 L.getNameLoc(),
880 /*IsDecl=*/false,
881 {L.getDecl()}});
882 }
883
884 void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
885 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
886 L.getNameLoc(),
887 /*IsDecl=*/false,
888 {L.getDecl()}});
889 }
890
891 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
892 // We must ensure template type aliases are included in results if they
893 // were written in the source code, e.g. in
894 // template <class T> using valias = vector<T>;
895 // ^valias<int> x;
896 // 'explicitReferenceTargets' will return:
897 // 1. valias with mask 'Alias'.
898 // 2. 'vector<int>' with mask 'Underlying'.
899 // we want to return only #1 in this case.
900 Refs.push_back(ReferenceLoc{
901 L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
902 explicitReferenceTargets(DynTypedNode::create(L.getType()),
903 DeclRelation::Alias, Resolver)});
904 }
905 void VisitDeducedTemplateSpecializationTypeLoc(
906 DeducedTemplateSpecializationTypeLoc L) {
907 Refs.push_back(ReferenceLoc{
908 L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
909 explicitReferenceTargets(DynTypedNode::create(L.getType()),
910 DeclRelation::Alias, Resolver)});
911 }
912
913 void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
914 Refs.push_back(
915 ReferenceLoc{L.getQualifierLoc(), L.getNameLoc(),
916 /*IsDecl=*/false,
918 DynTypedNode::create(L.getType()), {}, Resolver)});
919 }
920
921 void VisitTypedefTypeLoc(TypedefTypeLoc L) {
922 if (shouldSkipTypedef(L.getDecl()))
923 return;
924 Refs.push_back(ReferenceLoc{L.getQualifierLoc(),
925 L.getNameLoc(),
926 /*IsDecl=*/false,
927 {L.getDecl()}});
928 }
929
930 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc L) {
931 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
932 L.getNameLoc(),
933 /*IsDecl=*/false,
934 {L.getIFaceDecl()}});
935 }
936 };
937
938 Visitor V{Resolver};
939 V.Visit(L.getUnqualifiedLoc());
940 return V.Refs;
941}
942
943class ExplicitReferenceCollector
944 : public RecursiveASTVisitor<ExplicitReferenceCollector> {
945public:
946 ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out,
947 const HeuristicResolver *Resolver)
948 : Out(Out), Resolver(Resolver) {
949 assert(Out);
950 }
951
952 bool VisitTypeLoc(TypeLoc TTL) {
953 if (TypeLocsToSkip.count(TTL.getBeginLoc()))
954 return true;
955 visitNode(DynTypedNode::create(TTL));
956 return true;
957 }
958
959 bool VisitStmt(Stmt *S) {
960 visitNode(DynTypedNode::create(*S));
961 return true;
962 }
963
964 bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
965 visitNode(DynTypedNode::create(*OVE));
966 // Not clear why the source expression is skipped by default...
967 // FIXME: can we just make RecursiveASTVisitor do this?
968 return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
969 }
970
971 bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
972 visitNode(DynTypedNode::create(*POE));
973 // Traverse only the syntactic form to find the *written* references.
974 // (The semantic form also contains lots of duplication)
975 return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
976 }
977
978 // We re-define Traverse*, since there's no corresponding Visit*.
979 // TemplateArgumentLoc is the only way to get locations for references to
980 // template template parameters.
981 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
982 switch (A.getArgument().getKind()) {
983 case TemplateArgument::Template:
984 case TemplateArgument::TemplateExpansion:
985 reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
986 A.getTemplateNameLoc(),
987 /*IsDecl=*/false,
988 {A.getArgument()
989 .getAsTemplateOrTemplatePattern()
990 .getAsTemplateDecl()}},
991 DynTypedNode::create(A.getArgument()));
992 break;
993 case TemplateArgument::Declaration:
994 break; // FIXME: can this actually happen in TemplateArgumentLoc?
995 case TemplateArgument::Integral:
996 case TemplateArgument::Null:
997 case TemplateArgument::NullPtr:
998 break; // no references.
999 case TemplateArgument::Pack:
1000 case TemplateArgument::Type:
1001 case TemplateArgument::Expression:
1002 case TemplateArgument::StructuralValue:
1003 break; // Handled by VisitType and VisitExpression.
1004 };
1005 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
1006 }
1007
1008 bool VisitDecl(Decl *D) {
1009 visitNode(DynTypedNode::create(*D));
1010 return true;
1011 }
1012
1013 // We have to use Traverse* because there is no corresponding Visit*.
1014 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
1015 if (!L.getNestedNameSpecifier())
1016 return true;
1017 visitNode(DynTypedNode::create(L));
1018 // Inner type is missing information about its qualifier, skip it.
1019 if (auto TL = L.getAsTypeLoc())
1020 TypeLocsToSkip.insert(TL.getBeginLoc());
1021 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
1022 }
1023
1024 bool TraverseObjCProtocolLoc(ObjCProtocolLoc ProtocolLoc) {
1025 visitNode(DynTypedNode::create(ProtocolLoc));
1026 return true;
1027 }
1028
1029 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
1030 visitNode(DynTypedNode::create(*Init));
1031 return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
1032 }
1033
1034 bool VisitConceptReference(const ConceptReference *CR) {
1035 visitNode(DynTypedNode::create(*CR));
1036 return true;
1037 }
1038
1039 bool VisitOffsetOfNode(const OffsetOfNode *N) {
1040 visitNode(DynTypedNode::create(*N));
1041 return true;
1042 }
1043
1044private:
1045 /// Obtain information about a reference directly defined in \p N. Does not
1046 /// recurse into child nodes, e.g. do not expect references for constructor
1047 /// initializers
1048 ///
1049 /// Any of the fields in the returned structure can be empty, but not all of
1050 /// them, e.g.
1051 /// - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
1052 /// source location information may be missing,
1053 /// - for dependent code, targets may be empty.
1054 ///
1055 /// (!) For the purposes of this function declarations are not considered to
1056 /// be references. However, declarations can have references inside them,
1057 /// e.g. 'namespace foo = std' references namespace 'std' and this
1058 /// function will return the corresponding reference.
1059 llvm::SmallVector<ReferenceLoc> explicitReference(DynTypedNode N) {
1060 if (auto *D = N.get<Decl>())
1061 return refInDecl(D, Resolver);
1062 if (auto *S = N.get<Stmt>())
1063 return refInStmt(S, Resolver);
1064 if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
1065 if (TypeLoc TL = NNSL->getAsTypeLoc())
1066 return refInTypeLoc(TL, Resolver);
1067 // (!) 'DeclRelation::Alias' ensures we do not lose namespace aliases.
1068 NestedNameSpecifierLoc Qualifier = NNSL->getAsNamespaceAndPrefix().Prefix;
1069 SourceLocation NameLoc = NNSL->getLocalBeginLoc();
1070 return {
1071 ReferenceLoc{Qualifier, NameLoc, false,
1073 DynTypedNode::create(NNSL->getNestedNameSpecifier()),
1074 DeclRelation::Alias, Resolver)}};
1075 }
1076 if (const TypeLoc *TL = N.get<TypeLoc>())
1077 return refInTypeLoc(*TL, Resolver);
1078 if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
1079 // Other type initializers (e.g. base initializer) are handled by visiting
1080 // the typeLoc.
1081 if (CCI->isAnyMemberInitializer()) {
1082 return {ReferenceLoc{NestedNameSpecifierLoc(),
1083 CCI->getMemberLocation(),
1084 /*IsDecl=*/false,
1085 {CCI->getAnyMember()}}};
1086 }
1087 }
1088 if (const ObjCProtocolLoc *PL = N.get<ObjCProtocolLoc>())
1089 return {ReferenceLoc{NestedNameSpecifierLoc(),
1090 PL->getLocation(),
1091 /*IsDecl=*/false,
1092 {PL->getProtocol()}}};
1093 if (const ConceptReference *CR = N.get<ConceptReference>())
1094 return {ReferenceLoc{CR->getNestedNameSpecifierLoc(),
1095 CR->getConceptNameLoc(),
1096 /*IsDecl=*/false,
1097 {getReferencedConcept(CR)}}};
1098 if (const OffsetOfNode *OON = N.get<OffsetOfNode>()) {
1099 if (OON->getKind() == OffsetOfNode::Field)
1100 return {ReferenceLoc{NestedNameSpecifierLoc(),
1101 OON->getEndLoc(),
1102 /*IsDecl=*/false,
1103 {OON->getField()}}};
1104 return {};
1105 }
1106
1107 // We do not have location information for other nodes (QualType, etc)
1108 return {};
1109 }
1110
1111 void visitNode(DynTypedNode N) {
1112 for (auto &R : explicitReference(N))
1113 reportReference(std::move(R), N);
1114 }
1115
1116 void reportReference(ReferenceLoc &&Ref, DynTypedNode N) {
1117 // Strip null targets that can arise from invalid code.
1118 // (This avoids having to check for null everywhere we insert)
1119 llvm::erase(Ref.Targets, nullptr);
1120 // Our promise is to return only references from the source code. If we lack
1121 // location information, skip these nodes.
1122 // Normally this should not happen in practice, unless there are bugs in the
1123 // traversals or users started the traversal at an implicit node.
1124 if (Ref.NameLoc.isInvalid()) {
1125 dlog("invalid location at node {0}", nodeToString(N));
1126 return;
1127 }
1128 Out(Ref);
1129 }
1130
1131 llvm::function_ref<void(ReferenceLoc)> Out;
1132 const HeuristicResolver *Resolver;
1133 /// TypeLocs starting at these locations must be skipped, see
1134 /// TraverseElaboratedTypeSpecifierLoc for details.
1135 llvm::DenseSet<SourceLocation> TypeLocsToSkip;
1136};
1137} // namespace
1138
1139void findExplicitReferences(const Stmt *S,
1140 llvm::function_ref<void(ReferenceLoc)> Out,
1141 const HeuristicResolver *Resolver) {
1142 assert(S);
1143 ExplicitReferenceCollector(Out, Resolver).TraverseStmt(const_cast<Stmt *>(S));
1144}
1145void findExplicitReferences(const Decl *D,
1146 llvm::function_ref<void(ReferenceLoc)> Out,
1147 const HeuristicResolver *Resolver) {
1148 assert(D);
1149 ExplicitReferenceCollector(Out, Resolver).TraverseDecl(const_cast<Decl *>(D));
1150}
1151void findExplicitReferences(const ASTContext &AST,
1152 llvm::function_ref<void(ReferenceLoc)> Out,
1153 const HeuristicResolver *Resolver) {
1154 ExplicitReferenceCollector(Out, Resolver)
1155 .TraverseAST(const_cast<ASTContext &>(AST));
1156}
1157
1158llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
1159 switch (R) {
1160#define REL_CASE(X) \
1161 case DeclRelation::X: \
1162 return OS << #X;
1163 REL_CASE(Alias);
1167#undef REL_CASE
1168 }
1169 llvm_unreachable("Unhandled DeclRelation enum");
1170}
1171llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
1172 const char *Sep = "";
1173 for (unsigned I = 0; I < RS.S.size(); ++I) {
1174 if (RS.S.test(I)) {
1175 OS << Sep << static_cast<DeclRelation>(I);
1176 Sep = "|";
1177 }
1178 }
1179 return OS;
1180}
1181
1182llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
1183 // note we cannot print R.NameLoc without a source manager.
1184 OS << "targets = {";
1185 llvm::SmallVector<std::string> Targets;
1186 for (const NamedDecl *T : R.Targets) {
1187 llvm::raw_string_ostream Target(Targets.emplace_back());
1189 }
1190 llvm::sort(Targets);
1191 OS << llvm::join(Targets, ", ");
1192 OS << "}";
1193 if (R.Qualifier) {
1194 OS << ", qualifier = '";
1195 R.Qualifier.getNestedNameSpecifier().print(OS,
1196 PrintingPolicy(LangOptions()));
1197 OS << "'";
1198 }
1199 if (R.IsDecl)
1200 OS << ", decl";
1201 return OS;
1202}
1203
1204} // namespace clangd
1205} // 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