blob: a4c17dbefdedcbaa80131b35ab3dd19de16c679c [file] [log] [blame]
Sam McCall489cc582019-09-03 11:35:50 +00001//===--- FindTarget.cpp - What does an AST node refer to? -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "FindTarget.h"
10#include "AST.h"
11#include "Logger.h"
12#include "clang/AST/ASTTypeTraits.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000013#include "clang/AST/Decl.h"
Sam McCall489cc582019-09-03 11:35:50 +000014#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/DeclarationName.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000018#include "clang/AST/Expr.h"
Ilya Biryukov27744572019-09-27 09:39:10 +000019#include "clang/AST/ExprCXX.h"
Sam McCall489cc582019-09-03 11:35:50 +000020#include "clang/AST/ExprObjC.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000021#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/PrettyPrinter.h"
23#include "clang/AST/RecursiveASTVisitor.h"
Sam McCall489cc582019-09-03 11:35:50 +000024#include "clang/AST/StmtVisitor.h"
Ilya Biryukov1d32da82019-10-01 10:02:23 +000025#include "clang/AST/TemplateBase.h"
Sam McCall489cc582019-09-03 11:35:50 +000026#include "clang/AST/Type.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000027#include "clang/AST/TypeLoc.h"
Sam McCall489cc582019-09-03 11:35:50 +000028#include "clang/AST/TypeLocVisitor.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000029#include "clang/Basic/LangOptions.h"
Sam McCall489cc582019-09-03 11:35:50 +000030#include "clang/Basic/SourceLocation.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallVector.h"
Sam McCall489cc582019-09-03 11:35:50 +000033#include "llvm/Support/Casting.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/raw_ostream.h"
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000036#include <utility>
Sam McCall489cc582019-09-03 11:35:50 +000037
38namespace clang {
39namespace clangd {
40namespace {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +000041using ast_type_traits::DynTypedNode;
Sam McCall489cc582019-09-03 11:35:50 +000042
Sam McCall80195e72019-09-03 13:54:27 +000043LLVM_ATTRIBUTE_UNUSED std::string
Sam McCall489cc582019-09-03 11:35:50 +000044nodeToString(const ast_type_traits::DynTypedNode &N) {
45 std::string S = N.getNodeKind().asStringRef();
46 {
47 llvm::raw_string_ostream OS(S);
48 OS << ": ";
49 N.print(OS, PrintingPolicy(LangOptions()));
50 }
51 std::replace(S.begin(), S.end(), '\n', ' ');
52 return S;
53}
54
Nathan Ridgeecaa9362019-12-05 18:29:32 -050055// Given a dependent type and a member name, heuristically resolve the
56// name to one or more declarations.
57// The current heuristic is simply to look up the name in the primary
58// template. This is a heuristic because the template could potentially
59// have specializations that declare different members.
60// Multiple declarations could be returned if the name is overloaded
61// (e.g. an overloaded method in the primary template).
62// This heuristic will give the desired answer in many cases, e.g.
63// for a call to vector<T>::size().
64std::vector<const NamedDecl *>
65getMembersReferencedViaDependentName(const Type *T, const DeclarationName &Name,
66 bool IsNonstaticMember) {
67 if (!T)
68 return {};
69 if (auto *ICNT = T->getAs<InjectedClassNameType>()) {
70 T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
71 }
72 auto *TST = T->getAs<TemplateSpecializationType>();
73 if (!TST)
74 return {};
75 const ClassTemplateDecl *TD = dyn_cast_or_null<ClassTemplateDecl>(
76 TST->getTemplateName().getAsTemplateDecl());
77 if (!TD)
78 return {};
79 CXXRecordDecl *RD = TD->getTemplatedDecl();
80 if (!RD->hasDefinition())
81 return {};
82 RD = RD->getDefinition();
83 return RD->lookupDependentName(Name, [=](const NamedDecl *D) {
84 return IsNonstaticMember ? D->isCXXInstanceMember()
85 : !D->isCXXInstanceMember();
86 });
87}
88
Sam McCall489cc582019-09-03 11:35:50 +000089// TargetFinder locates the entities that an AST node refers to.
90//
91// Typically this is (possibly) one declaration and (possibly) one type, but
92// may be more:
93// - for ambiguous nodes like OverloadExpr
94// - if we want to include e.g. both typedefs and the underlying type
95//
96// This is organized as a set of mutually recursive helpers for particular node
97// types, but for most nodes this is a short walk rather than a deep traversal.
98//
99// It's tempting to do e.g. typedef resolution as a second normalization step,
100// after finding the 'primary' decl etc. But we do this monolithically instead
101// because:
102// - normalization may require these traversals again (e.g. unwrapping a
103// typedef reveals a decltype which must be traversed)
104// - it doesn't simplify that much, e.g. the first stage must still be able
105// to yield multiple decls to handle OverloadExpr
106// - there are cases where it's required for correctness. e.g:
107// template<class X> using pvec = vector<x*>; pvec<int> x;
108// There's no Decl `pvec<int>`, we must choose `pvec<X>` or `vector<int*>`
109// and both are lossy. We must know upfront what the caller ultimately wants.
110//
111// FIXME: improve common dependent scope using name lookup in primary templates.
112// e.g. template<typename T> int foo() { return std::vector<T>().size(); }
113// formally size() is unresolved, but the primary template is a good guess.
114// This affects:
115// - DependentTemplateSpecializationType,
Sam McCall489cc582019-09-03 11:35:50 +0000116// - DependentNameType
Nathan Ridgeecaa9362019-12-05 18:29:32 -0500117// - UnresolvedUsingValueDecl
118// - UnresolvedUsingTypenameDecl
Sam McCall489cc582019-09-03 11:35:50 +0000119struct TargetFinder {
120 using RelSet = DeclRelationSet;
121 using Rel = DeclRelation;
122 llvm::SmallDenseMap<const Decl *, RelSet> Decls;
123 RelSet Flags;
124
125 static const Decl *getTemplatePattern(const Decl *D) {
126 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
127 return CRD->getTemplateInstantiationPattern();
128 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
129 return FD->getTemplateInstantiationPattern();
130 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
131 // Hmm: getTIP returns its arg if it's not an instantiation?!
132 VarDecl *T = VD->getTemplateInstantiationPattern();
133 return (T == D) ? nullptr : T;
134 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
135 return ED->getInstantiatedFromMemberEnum();
136 } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
137 const auto *ND = cast<NamedDecl>(D);
138 if (const DeclContext *Parent = dyn_cast_or_null<DeclContext>(
139 getTemplatePattern(llvm::cast<Decl>(ND->getDeclContext()))))
140 for (const NamedDecl *BaseND : Parent->lookup(ND->getDeclName()))
141 if (!BaseND->isImplicit() && BaseND->getKind() == ND->getKind())
142 return BaseND;
143 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
144 if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
145 if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
146 for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
147 return BaseECD;
148 }
149 }
150 }
151 return nullptr;
152 }
153
154 template <typename T> void debug(T &Node, RelSet Flags) {
155 dlog("visit [{0}] {1}", Flags,
156 nodeToString(ast_type_traits::DynTypedNode::create(Node)));
157 }
158
159 void report(const Decl *D, RelSet Flags) {
160 dlog("--> [{0}] {1}", Flags,
161 nodeToString(ast_type_traits::DynTypedNode::create(*D)));
162 Decls[D] |= Flags;
163 }
164
165public:
166 void add(const Decl *D, RelSet Flags) {
167 if (!D)
168 return;
169 debug(*D, Flags);
170 if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
171 D = UDD->getNominatedNamespaceAsWritten();
172
173 if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) {
174 add(TND->getUnderlyingType(), Flags | Rel::Underlying);
175 Flags |= Rel::Alias; // continue with the alias.
176 } else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
177 for (const UsingShadowDecl *S : UD->shadows())
178 add(S->getUnderlyingDecl(), Flags | Rel::Underlying);
179 Flags |= Rel::Alias; // continue with the alias.
180 } else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) {
181 add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying);
182 Flags |= Rel::Alias; // continue with the alias
183 } else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
184 // Include the using decl, but don't traverse it. This may end up
185 // including *all* shadows, which we don't want.
186 report(USD->getUsingDecl(), Flags | Rel::Alias);
187 // Shadow decls are synthetic and not themselves interesting.
188 // Record the underlying decl instead, if allowed.
189 D = USD->getTargetDecl();
190 Flags |= Rel::Underlying; // continue with the underlying decl.
191 }
192
193 if (const Decl *Pat = getTemplatePattern(D)) {
194 assert(Pat != D);
195 add(Pat, Flags | Rel::TemplatePattern);
196 // Now continue with the instantiation.
197 Flags |= Rel::TemplateInstantiation;
198 }
199
200 report(D, Flags);
201 }
202
203 void add(const Stmt *S, RelSet Flags) {
204 if (!S)
205 return;
206 debug(*S, Flags);
207 struct Visitor : public ConstStmtVisitor<Visitor> {
208 TargetFinder &Outer;
209 RelSet Flags;
210 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
211
Haojian Wu939544a2019-11-27 16:22:16 +0100212 void VisitCallExpr(const CallExpr *CE) {
213 Outer.add(CE->getCalleeDecl(), Flags);
214 }
Sam McCall489cc582019-09-03 11:35:50 +0000215 void VisitDeclRefExpr(const DeclRefExpr *DRE) {
216 const Decl *D = DRE->getDecl();
217 // UsingShadowDecl allows us to record the UsingDecl.
218 // getFoundDecl() returns the wrong thing in other cases (templates).
219 if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl()))
220 D = USD;
221 Outer.add(D, Flags);
222 }
223 void VisitMemberExpr(const MemberExpr *ME) {
224 const Decl *D = ME->getMemberDecl();
225 if (auto *USD =
226 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl()))
227 D = USD;
228 Outer.add(D, Flags);
229 }
Ilya Biryukova160a0b2019-10-01 07:27:55 +0000230 void VisitOverloadExpr(const OverloadExpr *OE) {
231 for (auto *D : OE->decls())
232 Outer.add(D, Flags);
233 }
Nathan Ridge1a4ee4c2019-12-05 14:27:23 -0500234 void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) {
235 Outer.add(SE->getPack(), Flags);
236 }
Sam McCall489cc582019-09-03 11:35:50 +0000237 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
238 Outer.add(CCE->getConstructor(), Flags);
239 }
240 void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
241 for (const DesignatedInitExpr::Designator &D :
242 llvm::reverse(DIE->designators()))
243 if (D.isFieldDesignator()) {
244 Outer.add(D.getField(), Flags);
245 // We don't know which designator was intended, we assume the outer.
246 break;
247 }
248 }
Nathan Ridgeecaa9362019-12-05 18:29:32 -0500249 void
250 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
251 const Type *BaseType = E->getBaseType().getTypePtrOrNull();
252 if (E->isArrow()) {
253 // FIXME: Handle smart pointer types by looking up operator->
254 // in the primary template.
255 if (!BaseType || !BaseType->isPointerType()) {
256 return;
257 }
258 BaseType = BaseType->getAs<PointerType>()
259 ->getPointeeType()
260 .getTypePtrOrNull();
261 }
262 for (const NamedDecl *D :
263 getMembersReferencedViaDependentName(BaseType, E->getMember(),
264 /*IsNonstaticMember=*/true)) {
265 Outer.add(D, Flags);
266 }
267 }
268 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
269 for (const NamedDecl *D : getMembersReferencedViaDependentName(
270 E->getQualifier()->getAsType(), E->getDeclName(),
271 /*IsNonstaticMember=*/false)) {
272 Outer.add(D, Flags);
273 }
274 }
Sam McCall489cc582019-09-03 11:35:50 +0000275 void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
276 Outer.add(OIRE->getDecl(), Flags);
277 }
278 void VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
279 Outer.add(OME->getMethodDecl(), Flags);
280 }
281 void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
282 if (OPRE->isExplicitProperty())
283 Outer.add(OPRE->getExplicitProperty(), Flags);
284 else {
285 if (OPRE->isMessagingGetter())
286 Outer.add(OPRE->getImplicitPropertyGetter(), Flags);
287 if (OPRE->isMessagingSetter())
288 Outer.add(OPRE->getImplicitPropertySetter(), Flags);
289 }
290 }
291 void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
292 Outer.add(OPE->getProtocol(), Flags);
293 }
294 };
295 Visitor(*this, Flags).Visit(S);
296 }
297
298 void add(QualType T, RelSet Flags) {
299 if (T.isNull())
300 return;
301 debug(T, Flags);
302 struct Visitor : public TypeVisitor<Visitor> {
303 TargetFinder &Outer;
304 RelSet Flags;
305 Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
306
307 void VisitTagType(const TagType *TT) {
308 Outer.add(TT->getAsTagDecl(), Flags);
309 }
310 void VisitDecltypeType(const DecltypeType *DTT) {
311 Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
312 }
313 void VisitDeducedType(const DeducedType *DT) {
314 // FIXME: In practice this doesn't work: the AutoType you find inside
315 // TypeLoc never has a deduced type. https://llvm.org/PR42914
316 Outer.add(DT->getDeducedType(), Flags | Rel::Underlying);
317 }
318 void VisitTypedefType(const TypedefType *TT) {
319 Outer.add(TT->getDecl(), Flags);
320 }
321 void
322 VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
323 // Have to handle these case-by-case.
324
325 // templated type aliases: there's no specialized/instantiated using
326 // decl to point to. So try to find a decl for the underlying type
327 // (after substitution), and failing that point to the (templated) using
328 // decl.
329 if (TST->isTypeAlias()) {
330 Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
331 // Don't *traverse* the alias, which would result in traversing the
332 // template of the underlying type.
333 Outer.report(
334 TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
335 Flags | Rel::Alias | Rel::TemplatePattern);
336 }
337 // specializations of template template parameters aren't instantiated
338 // into decls, so they must refer to the parameter itself.
339 else if (const auto *Parm =
340 llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
341 TST->getTemplateName().getAsTemplateDecl()))
342 Outer.add(Parm, Flags);
343 // class template specializations have a (specialized) CXXRecordDecl.
344 else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
345 Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
346 else {
347 // fallback: the (un-specialized) declaration from primary template.
348 if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
349 Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
350 }
351 }
352 void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
353 Outer.add(TTPT->getDecl(), Flags);
354 }
355 void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
356 Outer.add(OIT->getDecl(), Flags);
357 }
358 void VisitObjCObjectType(const ObjCObjectType *OOT) {
359 // FIXME: ObjCObjectTypeLoc has no children for the protocol list, so
360 // there is no node in id<Foo> that refers to ObjCProtocolDecl Foo.
361 if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1)
362 Outer.add(OOT->getProtocol(0), Flags);
363 }
364 };
365 Visitor(*this, Flags).Visit(T.getTypePtr());
366 }
367
368 void add(const NestedNameSpecifier *NNS, RelSet Flags) {
369 if (!NNS)
370 return;
371 debug(*NNS, Flags);
372 switch (NNS->getKind()) {
373 case NestedNameSpecifier::Identifier:
374 return;
375 case NestedNameSpecifier::Namespace:
376 add(NNS->getAsNamespace(), Flags);
377 return;
378 case NestedNameSpecifier::NamespaceAlias:
379 add(NNS->getAsNamespaceAlias(), Flags);
380 return;
381 case NestedNameSpecifier::TypeSpec:
382 case NestedNameSpecifier::TypeSpecWithTemplate:
383 add(QualType(NNS->getAsType(), 0), Flags);
384 return;
385 case NestedNameSpecifier::Global:
386 // This should be TUDecl, but we can't get a pointer to it!
387 return;
388 case NestedNameSpecifier::Super:
389 add(NNS->getAsRecordDecl(), Flags);
390 return;
391 }
392 llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
393 }
394
395 void add(const CXXCtorInitializer *CCI, RelSet Flags) {
396 if (!CCI)
397 return;
398 debug(*CCI, Flags);
399
400 if (CCI->isAnyMemberInitializer())
401 add(CCI->getAnyMember(), Flags);
402 // Constructor calls contain a TypeLoc node, so we don't handle them here.
403 }
404};
405
406} // namespace
407
408llvm::SmallVector<std::pair<const Decl *, DeclRelationSet>, 1>
409allTargetDecls(const ast_type_traits::DynTypedNode &N) {
410 dlog("allTargetDecls({0})", nodeToString(N));
411 TargetFinder Finder;
412 DeclRelationSet Flags;
413 if (const Decl *D = N.get<Decl>())
414 Finder.add(D, Flags);
415 else if (const Stmt *S = N.get<Stmt>())
416 Finder.add(S, Flags);
417 else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
418 Finder.add(NNSL->getNestedNameSpecifier(), Flags);
419 else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
420 Finder.add(NNS, Flags);
421 else if (const TypeLoc *TL = N.get<TypeLoc>())
422 Finder.add(TL->getType(), Flags);
423 else if (const QualType *QT = N.get<QualType>())
424 Finder.add(*QT, Flags);
425 else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
426 Finder.add(CCI, Flags);
427
428 return {Finder.Decls.begin(), Finder.Decls.end()};
429}
430
431llvm::SmallVector<const Decl *, 1>
432targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
433 llvm::SmallVector<const Decl *, 1> Result;
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000434 for (const auto &Entry : allTargetDecls(N)) {
Sam McCall489cc582019-09-03 11:35:50 +0000435 if (!(Entry.second & ~Mask))
436 Result.push_back(Entry.first);
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000437 }
Sam McCall489cc582019-09-03 11:35:50 +0000438 return Result;
439}
440
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000441namespace {
442/// Find declarations explicitly referenced in the source code defined by \p N.
443/// For templates, will prefer to return a template instantiation whenever
444/// possible. However, can also return a template pattern if the specialization
445/// cannot be picked, e.g. in dependent code or when there is no corresponding
446/// Decl for a template instantitation, e.g. for templated using decls:
447/// template <class T> using Ptr = T*;
448/// Ptr<int> x;
449/// ^~~ there is no Decl for 'Ptr<int>', so we return the template pattern.
450llvm::SmallVector<const NamedDecl *, 1>
451explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask = {}) {
452 assert(!(Mask & (DeclRelation::TemplatePattern |
453 DeclRelation::TemplateInstantiation)) &&
454 "explicitRefenceTargets handles templates on its own");
455 auto Decls = allTargetDecls(N);
456
457 // We prefer to return template instantiation, but fallback to template
458 // pattern if instantiation is not available.
459 Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
460
461 llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
462 llvm::SmallVector<const NamedDecl *, 1> Targets;
463 bool SeenTemplateInstantiations = false;
464 for (auto &D : Decls) {
465 if (D.second & ~Mask)
466 continue;
467 if (D.second & DeclRelation::TemplatePattern) {
468 TemplatePatterns.push_back(llvm::cast<NamedDecl>(D.first));
469 continue;
470 }
471 if (D.second & DeclRelation::TemplateInstantiation)
472 SeenTemplateInstantiations = true;
473 Targets.push_back(llvm::cast<NamedDecl>(D.first));
474 }
475 if (!SeenTemplateInstantiations)
476 Targets.insert(Targets.end(), TemplatePatterns.begin(),
477 TemplatePatterns.end());
478 return Targets;
479}
480
Haojian Wu65f61c02019-10-18 12:07:19 +0000481llvm::SmallVector<ReferenceLoc, 2> refInDecl(const Decl *D) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000482 struct Visitor : ConstDeclVisitor<Visitor> {
Haojian Wu65f61c02019-10-18 12:07:19 +0000483 llvm::SmallVector<ReferenceLoc, 2> Refs;
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000484
485 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000486 // We want to keep it as non-declaration references, as the
487 // "using namespace" declaration doesn't have a name.
488 Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
489 D->getIdentLocation(),
490 /*IsDecl=*/false,
491 {D->getNominatedNamespaceAsWritten()}});
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000492 }
493
494 void VisitUsingDecl(const UsingDecl *D) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000495 // "using ns::identifer;" is a non-declaration reference.
496 Refs.push_back(
497 ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
498 explicitReferenceTargets(DynTypedNode::create(*D),
499 DeclRelation::Underlying)});
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000500 }
501
502 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000503 // For namespace alias, "namespace Foo = Target;", we add two references.
504 // Add a declaration reference for Foo.
505 VisitNamedDecl(D);
506 // Add a non-declaration reference for Target.
507 Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
508 D->getTargetNameLoc(),
509 /*IsDecl=*/false,
510 {D->getAliasedNamespace()}});
511 }
512
513 void VisitNamedDecl(const NamedDecl *ND) {
514 // FIXME: decide on how to surface destructors when we need them.
515 if (llvm::isa<CXXDestructorDecl>(ND))
516 return;
Ilya Biryukov4c430a72019-10-28 14:41:06 +0100517 // Filter anonymous decls, name location will point outside the name token
518 // and the clients are not prepared to handle that.
519 if (ND->getDeclName().isIdentifier() &&
520 !ND->getDeclName().getAsIdentifierInfo())
521 return;
522 Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
523 ND->getLocation(),
524 /*IsDecl=*/true,
525 {ND}});
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000526 }
527 };
528
529 Visitor V;
530 V.Visit(D);
Haojian Wu65f61c02019-10-18 12:07:19 +0000531 return V.Refs;
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000532}
533
Haojian Wu65f61c02019-10-18 12:07:19 +0000534llvm::SmallVector<ReferenceLoc, 2> refInExpr(const Expr *E) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000535 struct Visitor : ConstStmtVisitor<Visitor> {
536 // FIXME: handle more complicated cases, e.g. ObjC, designated initializers.
Haojian Wu65f61c02019-10-18 12:07:19 +0000537 llvm::SmallVector<ReferenceLoc, 2> Refs;
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000538
539 void VisitDeclRefExpr(const DeclRefExpr *E) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000540 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
541 E->getNameInfo().getLoc(),
542 /*IsDecl=*/false,
543 {E->getFoundDecl()}});
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000544 }
545
546 void VisitMemberExpr(const MemberExpr *E) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000547 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
548 E->getMemberNameInfo().getLoc(),
549 /*IsDecl=*/false,
550 {E->getFoundDecl()}});
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000551 }
Ilya Biryukov27744572019-09-27 09:39:10 +0000552
553 void VisitOverloadExpr(const OverloadExpr *E) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000554 Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
555 E->getNameInfo().getLoc(),
556 /*IsDecl=*/false,
557 llvm::SmallVector<const NamedDecl *, 1>(
558 E->decls().begin(), E->decls().end())});
Ilya Biryukov27744572019-09-27 09:39:10 +0000559 }
Nathan Ridge1a4ee4c2019-12-05 14:27:23 -0500560
561 void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
562 Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
563 E->getPackLoc(),
564 /*IsDecl=*/false,
565 {E->getPack()}});
566 }
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000567 };
568
569 Visitor V;
570 V.Visit(E);
Haojian Wu65f61c02019-10-18 12:07:19 +0000571 return V.Refs;
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000572}
573
Haojian Wu65f61c02019-10-18 12:07:19 +0000574llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000575 struct Visitor : TypeLocVisitor<Visitor> {
576 llvm::Optional<ReferenceLoc> Ref;
577
578 void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
579 // We only know about qualifier, rest if filled by inner locations.
580 Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
581 // Fill in the qualifier.
582 if (!Ref)
583 return;
584 assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
585 Ref->Qualifier = L.getQualifierLoc();
586 }
587
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000588 void VisitTagTypeLoc(TagTypeLoc L) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000589 Ref = ReferenceLoc{NestedNameSpecifierLoc(),
590 L.getNameLoc(),
591 /*IsDecl=*/false,
592 {L.getDecl()}};
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000593 }
594
Ilya Biryukovc3835092019-09-27 10:55:53 +0000595 void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000596 Ref = ReferenceLoc{NestedNameSpecifierLoc(),
597 L.getNameLoc(),
598 /*IsDecl=*/false,
599 {L.getDecl()}};
Ilya Biryukovc3835092019-09-27 10:55:53 +0000600 }
601
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000602 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
Ilya Biryukov4ae23812019-09-27 17:55:46 +0000603 // We must ensure template type aliases are included in results if they
604 // were written in the source code, e.g. in
605 // template <class T> using valias = vector<T>;
606 // ^valias<int> x;
607 // 'explicitReferenceTargets' will return:
608 // 1. valias with mask 'Alias'.
609 // 2. 'vector<int>' with mask 'Underlying'.
610 // we want to return only #1 in this case.
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000611 Ref = ReferenceLoc{
Haojian Wu65f61c02019-10-18 12:07:19 +0000612 NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
Ilya Biryukov4ae23812019-09-27 17:55:46 +0000613 explicitReferenceTargets(DynTypedNode::create(L.getType()),
614 DeclRelation::Alias)};
615 }
616 void VisitDeducedTemplateSpecializationTypeLoc(
617 DeducedTemplateSpecializationTypeLoc L) {
618 Ref = ReferenceLoc{
Haojian Wu65f61c02019-10-18 12:07:19 +0000619 NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
Ilya Biryukov4ae23812019-09-27 17:55:46 +0000620 explicitReferenceTargets(DynTypedNode::create(L.getType()),
621 DeclRelation::Alias)};
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000622 }
623
624 void VisitDependentTemplateSpecializationTypeLoc(
625 DependentTemplateSpecializationTypeLoc L) {
626 Ref = ReferenceLoc{
Haojian Wu65f61c02019-10-18 12:07:19 +0000627 L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000628 explicitReferenceTargets(DynTypedNode::create(L.getType()))};
629 }
630
631 void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
632 Ref = ReferenceLoc{
Haojian Wu65f61c02019-10-18 12:07:19 +0000633 L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000634 explicitReferenceTargets(DynTypedNode::create(L.getType()))};
635 }
636
637 void VisitTypedefTypeLoc(TypedefTypeLoc L) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000638 Ref = ReferenceLoc{NestedNameSpecifierLoc(),
639 L.getNameLoc(),
640 /*IsDecl=*/false,
641 {L.getTypedefNameDecl()}};
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000642 }
643 };
644
645 Visitor V;
646 V.Visit(L.getUnqualifiedLoc());
Haojian Wu65f61c02019-10-18 12:07:19 +0000647 if (!V.Ref)
648 return {};
649 return {*V.Ref};
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000650}
651
652class ExplicitReferenceColletor
653 : public RecursiveASTVisitor<ExplicitReferenceColletor> {
654public:
655 ExplicitReferenceColletor(llvm::function_ref<void(ReferenceLoc)> Out)
656 : Out(Out) {
657 assert(Out);
658 }
659
660 bool VisitTypeLoc(TypeLoc TTL) {
661 if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
662 return true;
663 visitNode(DynTypedNode::create(TTL));
664 return true;
665 }
666
667 bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
668 // ElaboratedTypeLoc will reports information for its inner type loc.
669 // Otherwise we loose information about inner types loc's qualifier.
670 TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
671 TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
672 return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
673 }
674
675 bool VisitExpr(Expr *E) {
676 visitNode(DynTypedNode::create(*E));
677 return true;
678 }
679
Ilya Biryukov1d32da82019-10-01 10:02:23 +0000680 // We re-define Traverse*, since there's no corresponding Visit*.
681 // TemplateArgumentLoc is the only way to get locations for references to
682 // template template parameters.
683 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
684 switch (A.getArgument().getKind()) {
685 case TemplateArgument::Template:
686 case TemplateArgument::TemplateExpansion:
687 reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
688 A.getTemplateNameLoc(),
Haojian Wu65f61c02019-10-18 12:07:19 +0000689 /*IsDecl=*/false,
Ilya Biryukov1d32da82019-10-01 10:02:23 +0000690 {A.getArgument()
691 .getAsTemplateOrTemplatePattern()
692 .getAsTemplateDecl()}},
693 DynTypedNode::create(A.getArgument()));
694 break;
695 case TemplateArgument::Declaration:
696 break; // FIXME: can this actually happen in TemplateArgumentLoc?
697 case TemplateArgument::Integral:
698 case TemplateArgument::Null:
699 case TemplateArgument::NullPtr:
700 break; // no references.
701 case TemplateArgument::Pack:
702 case TemplateArgument::Type:
703 case TemplateArgument::Expression:
704 break; // Handled by VisitType and VisitExpression.
705 };
706 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
707 }
708
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000709 bool VisitDecl(Decl *D) {
710 visitNode(DynTypedNode::create(*D));
711 return true;
712 }
713
714 // We have to use Traverse* because there is no corresponding Visit*.
715 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
716 if (!L.getNestedNameSpecifier())
717 return true;
718 visitNode(DynTypedNode::create(L));
719 // Inner type is missing information about its qualifier, skip it.
720 if (auto TL = L.getTypeLoc())
721 TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
722 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
723 }
724
Haojian Wu13fc8992019-10-21 10:11:30 +0200725 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
726 visitNode(DynTypedNode::create(*Init));
727 return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
728 }
729
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000730private:
731 /// Obtain information about a reference directly defined in \p N. Does not
732 /// recurse into child nodes, e.g. do not expect references for constructor
733 /// initializers
734 ///
735 /// Any of the fields in the returned structure can be empty, but not all of
736 /// them, e.g.
737 /// - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
738 /// source location information may be missing,
739 /// - for dependent code, targets may be empty.
740 ///
741 /// (!) For the purposes of this function declarations are not considered to
742 /// be references. However, declarations can have references inside them,
743 /// e.g. 'namespace foo = std' references namespace 'std' and this
744 /// function will return the corresponding reference.
Haojian Wu65f61c02019-10-18 12:07:19 +0000745 llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000746 if (auto *D = N.get<Decl>())
747 return refInDecl(D);
748 if (auto *E = N.get<Expr>())
749 return refInExpr(E);
Ilya Biryukov733777a2019-10-31 11:58:57 +0100750 if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
751 // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
752 return {ReferenceLoc{
753 NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
754 explicitReferenceTargets(
755 DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
756 DeclRelation::Alias)}};
757 }
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000758 if (const TypeLoc *TL = N.get<TypeLoc>())
759 return refInTypeLoc(*TL);
760 if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
Haojian Wu13fc8992019-10-21 10:11:30 +0200761 // Other type initializers (e.g. base initializer) are handled by visiting
762 // the typeLoc.
763 if (CCI->isAnyMemberInitializer()) {
764 return {ReferenceLoc{NestedNameSpecifierLoc(),
765 CCI->getMemberLocation(),
766 /*IsDecl=*/false,
767 {CCI->getAnyMember()}}};
768 }
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000769 }
770 // We do not have location information for other nodes (QualType, etc)
Haojian Wu65f61c02019-10-18 12:07:19 +0000771 return {};
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000772 }
773
774 void visitNode(DynTypedNode N) {
Haojian Wu65f61c02019-10-18 12:07:19 +0000775 for (const auto &R : explicitReference(N))
776 reportReference(R, N);
Ilya Biryukov1d32da82019-10-01 10:02:23 +0000777 }
778
779 void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000780 // Our promise is to return only references from the source code. If we lack
781 // location information, skip these nodes.
782 // Normally this should not happen in practice, unless there are bugs in the
783 // traversals or users started the traversal at an implicit node.
Ilya Biryukov1d32da82019-10-01 10:02:23 +0000784 if (Ref.NameLoc.isInvalid()) {
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000785 dlog("invalid location at node {0}", nodeToString(N));
786 return;
787 }
Ilya Biryukov1d32da82019-10-01 10:02:23 +0000788 Out(Ref);
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000789 }
790
791 llvm::function_ref<void(ReferenceLoc)> Out;
792 /// TypeLocs starting at these locations must be skipped, see
793 /// TraverseElaboratedTypeSpecifierLoc for details.
794 llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
795};
796} // namespace
797
Kadir Cetinkaya007e4fe2019-09-25 15:44:26 +0000798void findExplicitReferences(const Stmt *S,
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000799 llvm::function_ref<void(ReferenceLoc)> Out) {
800 assert(S);
Kadir Cetinkaya007e4fe2019-09-25 15:44:26 +0000801 ExplicitReferenceColletor(Out).TraverseStmt(const_cast<Stmt *>(S));
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000802}
Kadir Cetinkaya007e4fe2019-09-25 15:44:26 +0000803void findExplicitReferences(const Decl *D,
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000804 llvm::function_ref<void(ReferenceLoc)> Out) {
805 assert(D);
Kadir Cetinkaya007e4fe2019-09-25 15:44:26 +0000806 ExplicitReferenceColletor(Out).TraverseDecl(const_cast<Decl *>(D));
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000807}
Ilya Biryukov87e0cb42019-11-05 19:06:12 +0100808void findExplicitReferences(const ASTContext &AST,
809 llvm::function_ref<void(ReferenceLoc)> Out) {
810 ExplicitReferenceColletor(Out).TraverseAST(const_cast<ASTContext &>(AST));
811}
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000812
Sam McCall489cc582019-09-03 11:35:50 +0000813llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
814 switch (R) {
815#define REL_CASE(X) \
816 case DeclRelation::X: \
817 return OS << #X;
818 REL_CASE(Alias);
819 REL_CASE(Underlying);
820 REL_CASE(TemplateInstantiation);
821 REL_CASE(TemplatePattern);
822#undef REL_CASE
Michael Liaode524032019-09-03 15:02:46 +0000823 }
Simon Pilgrim54b989c2019-09-03 13:05:13 +0000824 llvm_unreachable("Unhandled DeclRelation enum");
Sam McCall489cc582019-09-03 11:35:50 +0000825}
826llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
827 const char *Sep = "";
828 for (unsigned I = 0; I < RS.S.size(); ++I) {
829 if (RS.S.test(I)) {
830 OS << Sep << static_cast<DeclRelation>(I);
831 Sep = "|";
832 }
833 }
834 return OS;
835}
836
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000837llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
838 // note we cannot print R.NameLoc without a source manager.
839 OS << "targets = {";
840 bool First = true;
841 for (const NamedDecl *T : R.Targets) {
842 if (!First)
843 OS << ", ";
844 else
845 First = false;
846 OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
847 }
848 OS << "}";
849 if (R.Qualifier) {
850 OS << ", qualifier = '";
851 R.Qualifier.getNestedNameSpecifier()->print(OS,
852 PrintingPolicy(LangOptions()));
853 OS << "'";
854 }
Haojian Wu65f61c02019-10-18 12:07:19 +0000855 if (R.IsDecl)
856 OS << ", decl";
Ilya Biryukovf96d2e12019-09-25 12:40:22 +0000857 return OS;
858}
859
Sam McCall489cc582019-09-03 11:35:50 +0000860} // namespace clangd
861} // namespace clang